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    IncompatibleSyncRoles,
209}
210
211impl TableSchema {
212    /// Validates identifiers, indexes, unique constraints and foreign keys.
213    pub fn validate(&self) -> Result<(), SchemaError> {
214        validate_identifier(self.name)?;
215        let mut columns = std::collections::HashSet::new();
216        for column in &self.columns {
217            validate_identifier(column.name)?;
218            if !columns.insert(column.name) {
219                return Err(SchemaError::DuplicateColumn {
220                    table: self.name.into(),
221                    column: column.name.into(),
222                });
223            }
224            if let Some(reference) = &column.references {
225                validate_reference(reference.target())?;
226                if let Some(action) = reference.on_delete()
227                    && !matches!(
228                        action.to_ascii_lowercase().as_str(),
229                        "cascade" | "restrict" | "no action" | "set null" | "set default"
230                    )
231                {
232                    return Err(SchemaError::InvalidOnDelete(action.into()));
233                }
234            }
235        }
236        for group in self.unique_constraints.iter().chain(self.indexes.iter()) {
237            for column in group {
238                validate_identifier(column)?;
239                if !columns.contains(column) {
240                    return Err(SchemaError::UnknownColumn {
241                        table: self.name.into(),
242                        column: (*column).into(),
243                    });
244                }
245            }
246        }
247        Ok(())
248    }
249}
250
251impl SchemaSet {
252    /// Validates every registered table and rejects duplicate table names.
253    pub fn validate(&self) -> Result<(), SchemaError> {
254        if let Some(first) = self.sync_models.first()
255            && self
256                .sync_models
257                .iter()
258                .any(|model| model.role != first.role)
259        {
260            return Err(SchemaError::IncompatibleSyncRoles);
261        }
262        let mut tables = std::collections::HashSet::new();
263        for table in &self.tables {
264            table.validate()?;
265            if !tables.insert(table.name) {
266                return Err(SchemaError::DuplicateTable(table.name.into()));
267            }
268        }
269        for table in &self.tables {
270            for column in &table.columns {
271                let Some(reference) = &column.references else {
272                    continue;
273                };
274                let (target_table, target_column) = reference
275                    .target
276                    .split_once('(')
277                    .and_then(|(table, column)| {
278                        column.strip_suffix(')').map(|column| (table, column))
279                    })
280                    .ok_or_else(|| SchemaError::InvalidForeignKey(reference.target().into()))?;
281                let target = self
282                    .tables
283                    .iter()
284                    .find(|candidate| candidate.name == target_table)
285                    .ok_or_else(|| SchemaError::InvalidForeignKey(reference.target().into()))?;
286                if !target
287                    .columns
288                    .iter()
289                    .any(|candidate| candidate.name == target_column)
290                {
291                    return Err(SchemaError::UnknownColumn {
292                        table: target_table.into(),
293                        column: target_column.into(),
294                    });
295                }
296            }
297        }
298        Ok(())
299    }
300
301    /// Exports SQL and returns schema validation errors instead of panicking.
302    pub fn try_to_sql<D: crate::SqlDialect>(&self) -> Result<String, SchemaError> {
303        self.validate()?;
304        Ok(self.to_sql_unchecked::<D>())
305    }
306}
307
308pub(crate) fn validate_identifier(identifier: &str) -> Result<(), SchemaError> {
309    let mut chars = identifier.chars();
310    let valid_start = chars
311        .next()
312        .is_some_and(|ch| ch == '_' || ch.is_ascii_alphabetic());
313    if valid_start && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
314        Ok(())
315    } else {
316        Err(SchemaError::InvalidIdentifier(identifier.into()))
317    }
318}
319
320fn validate_reference(reference: &str) -> Result<(), SchemaError> {
321    let Some((table, column)) = reference.split_once('(') else {
322        return Err(SchemaError::InvalidForeignKey(reference.into()));
323    };
324    let Some(column) = column.strip_suffix(')') else {
325        return Err(SchemaError::InvalidForeignKey(reference.into()));
326    };
327    validate_identifier(table)?;
328    validate_identifier(column)
329}
330
331/// A collection of model schemas exported as one SQL schema.
332#[derive(Debug, Default, Clone, PartialEq, Eq)]
333pub struct SchemaSet {
334    tables: Vec<TableSchema>,
335    model_names: Vec<&'static str>,
336    sync_models: Vec<crate::SyncRegistration>,
337}
338
339impl SchemaSet {
340    /// Creates an empty schema collection.
341    pub fn new() -> Self {
342        Self::default()
343    }
344
345    /// Returns registered tables in schema order.
346    pub fn tables(&self) -> &[TableSchema] {
347        &self.tables
348    }
349
350    /// Returns model names parallel to [`SchemaSet::tables`].
351    pub fn model_names(&self) -> &[&'static str] {
352        &self.model_names
353    }
354
355    /// Adds a model schema in dependency order.
356    pub fn model<M: crate::Model>(mut self) -> Self {
357        self.tables.push(M::schema());
358        self.model_names.push(M::model_name());
359        self
360    }
361
362    /// Register the local editable projection and its confirmed server shadow.
363    pub fn client_model<M: crate::SyncModel>(self) -> Self {
364        self.sync_model::<M>(crate::ModelRole::Client)
365    }
366
367    /// Register authoritative server data, without a shadow table.
368    pub fn server_model<M: crate::SyncModel>(self) -> Self {
369        self.sync_model::<M>(crate::ModelRole::Server)
370    }
371
372    fn sync_model<M: crate::SyncModel>(mut self, role: crate::ModelRole) -> Self {
373        let registration = crate::SyncRegistration::new::<M>(role);
374        self.tables.push(registration.schema.clone());
375        self.model_names.push(M::model_name());
376        self.sync_models.push(registration);
377        self
378    }
379
380    pub fn sync_models(&self) -> &[crate::SyncRegistration] {
381        &self.sync_models
382    }
383
384    /// Merges another application schema after the current tables.
385    pub fn merge(mut self, other: Self) -> Self {
386        self.tables.extend(other.tables);
387        self.model_names.extend(other.model_names);
388        self.sync_models.extend(other.sync_models);
389        self
390    }
391
392    /// Exports the desired schema as semicolon-delimited SQL.
393    pub fn to_sql<D: crate::SqlDialect>(&self) -> String {
394        self.validate().expect("invalid model schema");
395        self.to_sql_unchecked::<D>()
396    }
397
398    fn to_sql_unchecked<D: crate::SqlDialect>(&self) -> String {
399        let mut statements = Vec::new();
400        for table in &self.tables {
401            let compiled = crate::SqlCompiler::<D>::compile_schema(table);
402            statements.push(compiled.table);
403            statements.extend(compiled.indexes);
404        }
405        for operation in
406            crate::sync_migration_operations(&self.sync_models).expect("validated sync roles")
407        {
408            if let crate::MigrationOperation::CreateModel { model } = operation {
409                let compiled = crate::SqlCompiler::<D>::compile_table_state(&model.table);
410                statements.push(compiled.table);
411                statements.extend(compiled.indexes);
412            }
413        }
414        statements.join(";\n") + if statements.is_empty() { "" } else { ";\n" }
415    }
416}
417
418/// Application-level model registration, similar to a Django app config.
419pub trait AppConfig {
420    /// Stable application label used in diagnostics and registration.
421    fn name() -> &'static str;
422
423    /// Returns models owned by this application in dependency order.
424    fn schema() -> SchemaSet;
425}
426
427/// Registry that combines schemas from multiple application modules.
428#[derive(Debug, Default, Clone, PartialEq, Eq)]
429pub struct AppRegistry {
430    apps: Vec<&'static str>,
431    schema: SchemaSet,
432    app_schemas: Vec<(&'static str, SchemaSet)>,
433}
434
435impl AppRegistry {
436    /// Creates an empty application registry.
437    pub fn new() -> Self {
438        Self::default()
439    }
440
441    /// Registers one application and appends its models to the schema.
442    pub fn register<A: AppConfig>(mut self) -> Self {
443        self.apps.push(A::name());
444        let schema = A::schema();
445        self.schema = self.schema.merge(schema.clone());
446        self.app_schemas.push((A::name(), schema));
447        self
448    }
449
450    /// Returns registered application labels in registration order.
451    pub fn apps(&self) -> &[&'static str] {
452        &self.apps
453    }
454
455    /// Returns the combined schema.
456    pub fn schema(&self) -> &SchemaSet {
457        &self.schema
458    }
459
460    /// Returns schemas by owning app, preserving registration order for
461    /// migration-state construction.
462    pub fn app_schemas(&self) -> impl Iterator<Item = (&'static str, &SchemaSet)> {
463        self.app_schemas
464            .iter()
465            .map(|(name, schema)| (*name, schema))
466    }
467
468    /// Exports all registered models as SQL.
469    pub fn to_sql<D: crate::SqlDialect>(&self) -> String {
470        self.schema.to_sql::<D>()
471    }
472}
473
474#[derive(Debug, Clone)]
475/// AST node for a `CREATE TABLE` statement.
476pub struct CreateTableAst {
477    pub schema: TableSchema,
478}
479
480/// Builder for a model's `CREATE TABLE` statement.
481pub struct CreateTableQuery<M> {
482    ast: CreateTableAst,
483    _model: PhantomData<M>,
484}
485
486impl<M> CreateTableQuery<M> {
487    pub fn new(schema: TableSchema) -> Self {
488        Self {
489            ast: CreateTableAst { schema },
490            _model: PhantomData,
491        }
492    }
493
494    pub fn into_ast(self) -> crate::QueryAst {
495        crate::QueryAst::CreateTable(self.ast)
496    }
497}