Skip to main content

ormdantic_schema/
reflection.rs

1use crate::{ColumnDef, NamespaceDef, SchemaDef, TableDef};
2
3#[derive(Debug, Clone, Default, PartialEq, Eq)]
4pub struct ReflectedSchema {
5    namespaces: Vec<NamespaceDef>,
6    tables: Vec<ReflectedTable>,
7}
8
9impl ReflectedSchema {
10    pub fn new() -> Self {
11        Self::default()
12    }
13
14    pub fn with_namespaces(mut self, namespaces: Vec<NamespaceDef>) -> Self {
15        self.namespaces = namespaces;
16        self
17    }
18
19    pub fn with_tables(mut self, tables: Vec<ReflectedTable>) -> Self {
20        self.tables = tables;
21        self
22    }
23
24    pub fn into_schema_def(self) -> SchemaDef {
25        SchemaDef::from_tables(
26            self.tables
27                .into_iter()
28                .map(ReflectedTable::into_table_def)
29                .collect(),
30        )
31        .with_namespaces(self.namespaces)
32    }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct ReflectedTable {
37    name: String,
38    primary_key: String,
39    columns: Vec<ColumnDef>,
40    schema: Option<String>,
41}
42
43impl ReflectedTable {
44    pub fn new(
45        name: impl Into<String>,
46        primary_key: impl Into<String>,
47        columns: Vec<ColumnDef>,
48    ) -> Self {
49        Self {
50            name: name.into(),
51            primary_key: primary_key.into(),
52            columns,
53            schema: None,
54        }
55    }
56
57    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
58        self.schema = Some(schema.into());
59        self
60    }
61
62    fn into_table_def(self) -> TableDef {
63        let table = TableDef::from_parts(
64            self.name.clone(),
65            self.name,
66            self.primary_key,
67            self.columns,
68            Vec::new(),
69            Vec::new(),
70            Vec::new(),
71        );
72        if let Some(schema) = self.schema {
73            table.with_schema(schema)
74        } else {
75            table
76        }
77    }
78}