1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//! Schema management facilities

mod entity;
mod relation;

pub use entity::*;
pub use relation::*;
use sea_orm::{DbConn, DbErr};
use sea_schema::migration::MigratorTrait;

use crate::{lang::schema::SchemaJson, migrator::Migrator};

/// Define new entity and relation
#[derive(Debug)]
pub struct Schema;

/// Prefix the name of node table
pub fn format_node_table_name<T>(name: T) -> String
where
    T: ToString,
{
    format!("node_{}", name.to_string())
}

/// Prefix the name of node attribute column
pub fn format_node_attribute_name<T>(name: T) -> String
where
    T: ToString,
{
    format!("attr_{}", name.to_string())
}

/// Prefix the name of edge table
pub fn format_edge_table_name<T>(name: T) -> String
where
    T: ToString,
{
    format!("edge_{}", name.to_string())
}

impl Schema {
    /// Insert entity/relation metadata into database and create a corresponding node/edge table
    pub async fn define_schema(db: &DbConn, schema_json: SchemaJson) -> Result<(), DbErr> {
        if schema_json.reset {
            Migrator::fresh(db).await?;
        }

        for entity_json in schema_json.define.entities {
            Self::create_entity(db, entity_json).await?;
        }
        for relation_json in schema_json.define.relations {
            Self::create_relation(db, relation_json).await?;
        }

        Ok(())
    }
}