Skip to main content

che_orm/
schema.rs

1use std::marker::PhantomData;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4/// SQL column types supported by the schema compiler.
5pub enum ColumnType {
6    Integer,
7    Text,
8    Boolean,
9    DateTime,
10}
11
12/// Maps a Rust field type to a SQL column type.
13pub trait ColumnTypeOf {
14    fn column_type() -> ColumnType;
15    fn nullable() -> bool {
16        false
17    }
18    fn choices() -> Option<Vec<&'static str>> {
19        None
20    }
21}
22
23impl ColumnTypeOf for i64 {
24    fn column_type() -> ColumnType {
25        ColumnType::Integer
26    }
27}
28
29impl ColumnTypeOf for String {
30    fn column_type() -> ColumnType {
31        ColumnType::Text
32    }
33}
34
35impl ColumnTypeOf for bool {
36    fn column_type() -> ColumnType {
37        ColumnType::Boolean
38    }
39}
40
41impl ColumnTypeOf for time::OffsetDateTime {
42    fn column_type() -> ColumnType {
43        ColumnType::DateTime
44    }
45}
46
47impl<T: ColumnTypeOf> ColumnTypeOf for Option<T> {
48    fn column_type() -> ColumnType {
49        T::column_type()
50    }
51    fn nullable() -> bool {
52        true
53    }
54    fn choices() -> Option<Vec<&'static str>> {
55        T::choices()
56    }
57}
58
59/// A string-backed enum that can be stored in a database column.
60pub trait DbEnum: Sized {
61    const VALUES: &'static [&'static str];
62
63    fn as_str(&self) -> &'static str;
64    fn from_str(value: &str) -> Option<Self>;
65}
66
67impl<T: DbEnum> ColumnTypeOf for T {
68    fn column_type() -> ColumnType {
69        ColumnType::Text
70    }
71
72    fn choices() -> Option<Vec<&'static str>> {
73        Some(T::VALUES.to_vec())
74    }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78/// Foreign key metadata attached to a column.
79pub struct ForeignKey {
80    target: String,
81    on_delete: Option<&'static str>,
82}
83
84impl ForeignKey {
85    pub fn new(target: impl Into<String>, on_delete: Option<&'static str>) -> Self {
86        Self {
87            target: target.into(),
88            on_delete,
89        }
90    }
91
92    pub fn target(&self) -> &str {
93        &self.target
94    }
95
96    pub fn on_delete(&self) -> Option<&'static str> {
97        self.on_delete
98    }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
102/// Metadata for one table column.
103pub struct ColumnSchema {
104    pub name: &'static str,
105    pub column_type: ColumnType,
106    pub nullable: bool,
107    pub primary_key: bool,
108    pub unique: bool,
109    pub default: Option<&'static str>,
110    pub check: Option<&'static str>,
111    pub choices: Option<Vec<&'static str>>,
112    pub references: Option<ForeignKey>,
113    pub auto_now_add: bool,
114    pub auto_now: bool,
115}
116
117impl ColumnSchema {
118    pub fn new(name: &'static str, column_type: ColumnType, nullable: bool) -> Self {
119        Self {
120            name,
121            column_type,
122            nullable,
123            primary_key: false,
124            unique: false,
125            default: None,
126            check: None,
127            choices: None,
128            references: None,
129            auto_now_add: false,
130            auto_now: false,
131        }
132    }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136/// Complete model table metadata used for DDL generation.
137pub struct TableSchema {
138    pub name: &'static str,
139    pub columns: Vec<ColumnSchema>,
140    pub unique_constraints: Vec<Vec<&'static str>>,
141    pub indexes: Vec<Vec<&'static str>>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145/// Errors found in model-generated schema metadata.
146pub enum SchemaError {
147    InvalidIdentifier(String),
148    DuplicateTable(String),
149    DuplicateColumn { table: String, column: String },
150    UnknownColumn { table: String, column: String },
151    InvalidForeignKey(String),
152    InvalidOnDelete(String),
153}
154
155impl TableSchema {
156    /// Validates identifiers, indexes, unique constraints and foreign keys.
157    pub fn validate(&self) -> Result<(), SchemaError> {
158        validate_identifier(self.name)?;
159        let mut columns = std::collections::HashSet::new();
160        for column in &self.columns {
161            validate_identifier(column.name)?;
162            if !columns.insert(column.name) {
163                return Err(SchemaError::DuplicateColumn {
164                    table: self.name.into(),
165                    column: column.name.into(),
166                });
167            }
168            if let Some(reference) = &column.references {
169                validate_reference(reference.target())?;
170                if let Some(action) = reference.on_delete() {
171                    if !matches!(
172                        action.to_ascii_lowercase().as_str(),
173                        "cascade" | "restrict" | "no action" | "set null" | "set default"
174                    ) {
175                        return Err(SchemaError::InvalidOnDelete(action.into()));
176                    }
177                }
178            }
179        }
180        for group in self.unique_constraints.iter().chain(self.indexes.iter()) {
181            for column in group {
182                validate_identifier(column)?;
183                if !columns.contains(column) {
184                    return Err(SchemaError::UnknownColumn {
185                        table: self.name.into(),
186                        column: (*column).into(),
187                    });
188                }
189            }
190        }
191        Ok(())
192    }
193}
194
195impl SchemaSet {
196    /// Validates every registered table and rejects duplicate table names.
197    pub fn validate(&self) -> Result<(), SchemaError> {
198        let mut tables = std::collections::HashSet::new();
199        for table in &self.tables {
200            table.validate()?;
201            if !tables.insert(table.name) {
202                return Err(SchemaError::DuplicateTable(table.name.into()));
203            }
204        }
205        for table in &self.tables {
206            for column in &table.columns {
207                let Some(reference) = &column.references else {
208                    continue;
209                };
210                let (target_table, target_column) = reference
211                    .target
212                    .split_once('(')
213                    .and_then(|(table, column)| {
214                        column.strip_suffix(')').map(|column| (table, column))
215                    })
216                    .ok_or_else(|| SchemaError::InvalidForeignKey(reference.target().into()))?;
217                let target = self
218                    .tables
219                    .iter()
220                    .find(|candidate| candidate.name == target_table)
221                    .ok_or_else(|| SchemaError::InvalidForeignKey(reference.target().into()))?;
222                if !target
223                    .columns
224                    .iter()
225                    .any(|candidate| candidate.name == target_column)
226                {
227                    return Err(SchemaError::UnknownColumn {
228                        table: target_table.into(),
229                        column: target_column.into(),
230                    });
231                }
232            }
233        }
234        Ok(())
235    }
236
237    /// Exports SQL and returns schema validation errors instead of panicking.
238    pub fn try_to_sql<D: crate::SqlDialect>(&self) -> Result<String, SchemaError> {
239        self.validate()?;
240        Ok(self.to_sql_unchecked::<D>())
241    }
242}
243
244fn validate_identifier(identifier: &str) -> Result<(), SchemaError> {
245    let mut chars = identifier.chars();
246    let valid_start = chars
247        .next()
248        .is_some_and(|ch| ch == '_' || ch.is_ascii_alphabetic());
249    if valid_start && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
250        Ok(())
251    } else {
252        Err(SchemaError::InvalidIdentifier(identifier.into()))
253    }
254}
255
256fn validate_reference(reference: &str) -> Result<(), SchemaError> {
257    let Some((table, column)) = reference.split_once('(') else {
258        return Err(SchemaError::InvalidForeignKey(reference.into()));
259    };
260    let Some(column) = column.strip_suffix(')') else {
261        return Err(SchemaError::InvalidForeignKey(reference.into()));
262    };
263    validate_identifier(table)?;
264    validate_identifier(column)
265}
266
267/// A collection of model schemas exported as one Atlas-compatible SQL schema.
268#[derive(Debug, Default, Clone, PartialEq, Eq)]
269pub struct SchemaSet {
270    tables: Vec<TableSchema>,
271}
272
273impl SchemaSet {
274    /// Creates an empty schema collection.
275    pub fn new() -> Self {
276        Self::default()
277    }
278
279    /// Adds a model schema in dependency order.
280    pub fn model<M: crate::Model>(mut self) -> Self {
281        self.tables.push(M::schema());
282        self
283    }
284
285    /// Merges another application schema after the current tables.
286    pub fn merge(mut self, other: Self) -> Self {
287        self.tables.extend(other.tables);
288        self
289    }
290
291    /// Exports the desired schema as semicolon-delimited SQL.
292    pub fn to_sql<D: crate::SqlDialect>(&self) -> String {
293        self.validate().expect("invalid model schema");
294        self.to_sql_unchecked::<D>()
295    }
296
297    fn to_sql_unchecked<D: crate::SqlDialect>(&self) -> String {
298        let mut statements = Vec::new();
299        for table in &self.tables {
300            let compiled = crate::SqlCompiler::<D>::compile_schema(table);
301            statements.push(compiled.table);
302            statements.extend(compiled.indexes);
303        }
304        statements.join(";\n") + if statements.is_empty() { "" } else { ";\n" }
305    }
306}
307
308/// Application-level model registration, similar to a Django app config.
309pub trait AppConfig {
310    /// Stable application label used in diagnostics and registration.
311    fn name() -> &'static str;
312
313    /// Returns models owned by this application in dependency order.
314    fn schema() -> SchemaSet;
315}
316
317/// Registry that combines schemas from multiple application modules.
318#[derive(Debug, Default, Clone, PartialEq, Eq)]
319pub struct AppRegistry {
320    apps: Vec<&'static str>,
321    schema: SchemaSet,
322}
323
324impl AppRegistry {
325    /// Creates an empty application registry.
326    pub fn new() -> Self {
327        Self::default()
328    }
329
330    /// Registers one application and appends its models to the schema.
331    pub fn register<A: AppConfig>(mut self) -> Self {
332        self.apps.push(A::name());
333        self.schema = self.schema.merge(A::schema());
334        self
335    }
336
337    /// Returns registered application labels in registration order.
338    pub fn apps(&self) -> &[&'static str] {
339        &self.apps
340    }
341
342    /// Returns the combined schema.
343    pub fn schema(&self) -> &SchemaSet {
344        &self.schema
345    }
346
347    /// Exports all registered models as Atlas-compatible SQL.
348    pub fn to_sql<D: crate::SqlDialect>(&self) -> String {
349        self.schema.to_sql::<D>()
350    }
351}
352
353#[derive(Debug, Clone)]
354/// AST node for a `CREATE TABLE` statement.
355pub struct CreateTableAst {
356    pub schema: TableSchema,
357}
358
359/// Builder for a model's `CREATE TABLE` statement.
360pub struct CreateTableQuery<M> {
361    ast: CreateTableAst,
362    _model: PhantomData<M>,
363}
364
365impl<M> CreateTableQuery<M> {
366    pub fn new(schema: TableSchema) -> Self {
367        Self {
368            ast: CreateTableAst { schema },
369            _model: PhantomData,
370        }
371    }
372
373    pub fn into_ast(self) -> crate::QueryAst {
374        crate::QueryAst::CreateTable(self.ast)
375    }
376}