starfish_core/schema/
mod.rs

1//! Schema management facilities
2
3mod entity;
4mod relation;
5
6pub use entity::*;
7pub use relation::*;
8use sea_orm::{DbConn, DbErr};
9use sea_schema::migration::MigratorTrait;
10
11use crate::{lang::schema::SchemaJson, migrator::Migrator};
12
13/// Define new entity and relation
14#[derive(Debug)]
15pub struct Schema;
16
17/// Prefix the name of node table
18pub fn format_node_table_name<T>(name: T) -> String
19where
20    T: ToString,
21{
22    format!("node_{}", name.to_string())
23}
24
25/// Prefix the name of node attribute column
26pub fn format_node_attribute_name<T>(name: T) -> String
27where
28    T: ToString,
29{
30    format!("attr_{}", name.to_string())
31}
32
33/// Prefix the name of edge table
34pub fn format_edge_table_name<T>(name: T) -> String
35where
36    T: ToString,
37{
38    format!("edge_{}", name.to_string())
39}
40
41impl Schema {
42    /// Insert entity/relation metadata into database and create a corresponding node/edge table
43    pub async fn define_schema(db: &DbConn, schema_json: SchemaJson) -> Result<(), DbErr> {
44        if schema_json.reset {
45            Migrator::fresh(db).await?;
46        }
47
48        for entity_json in schema_json.define.entities {
49            Self::create_entity(db, entity_json).await?;
50        }
51        for relation_json in schema_json.define.relations {
52            Self::create_relation(db, relation_json).await?;
53        }
54
55        Ok(())
56    }
57}