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