Skip to main content

che_orm/
schema.rs

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