sqlmodel-core 0.2.0

Core types and traits for SQLModel Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Model trait for ORM-style struct mapping.
//!
//! The `Model` trait defines the contract for structs that can be
//! mapped to database tables. It is typically derived using the
//! `#[derive(Model)]` macro from `sqlmodel-macros`.

use crate::Result;
use crate::field::{FieldInfo, InheritanceInfo};
use crate::relationship::RelationshipInfo;
use crate::row::Row;
use crate::value::Value;

/// Behavior for handling extra fields during validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExtraFieldsBehavior {
    /// Allow extra fields (ignore them).
    #[default]
    Ignore,
    /// Forbid extra fields (return validation error).
    Forbid,
    /// Allow extra fields and preserve them.
    Allow,
}

/// Model-level configuration matching Pydantic's model_config.
///
/// This struct holds configuration options that affect model behavior
/// during validation, serialization, and database operations.
///
/// # Example
///
/// ```ignore
/// #[derive(Model)]
/// #[sqlmodel(
///     table,
///     from_attributes,
///     validate_assignment,
///     extra = "forbid",
///     strict,
///     populate_by_name,
///     use_enum_values
/// )]
/// struct User {
///     // ...
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct ModelConfig {
    /// Whether this model maps to a database table.
    /// If true, DDL can be generated for this model.
    pub table: bool,

    /// Allow reading data from object attributes (ORM mode).
    /// When true, model_validate can accept objects with attributes
    /// in addition to dicts.
    pub from_attributes: bool,

    /// Validate field values when they are assigned.
    /// When true, assignment to fields triggers validation.
    pub validate_assignment: bool,

    /// How to handle extra fields during validation.
    pub extra: ExtraFieldsBehavior,

    /// Enable strict type checking during validation.
    /// When true, types must match exactly (no coercion).
    pub strict: bool,

    /// Allow populating fields by either name or alias.
    /// When true, both the field name and any aliases are accepted
    /// during deserialization.
    pub populate_by_name: bool,

    /// Use enum values instead of names during serialization.
    /// When true, enum fields serialize to their underlying values
    /// rather than variant names.
    pub use_enum_values: bool,

    /// Allow arbitrary types in fields.
    /// When true, fields can use types that aren't natively supported
    /// by the validation system.
    pub arbitrary_types_allowed: bool,

    /// Defer model validation to allow forward references.
    /// When true, validation of field types is deferred until
    /// the model is first used.
    pub defer_build: bool,

    /// Revalidate instances when converting to this model.
    /// Controls whether existing model instances are revalidated.
    pub revalidate_instances: bool,

    /// Custom JSON schema extra data.
    /// Additional data to include in generated JSON schema.
    pub json_schema_extra: Option<&'static str>,

    /// Title for JSON schema generation.
    pub title: Option<&'static str>,
}

impl ModelConfig {
    /// Create a new ModelConfig with all defaults.
    pub const fn new() -> Self {
        Self {
            table: false,
            from_attributes: false,
            validate_assignment: false,
            extra: ExtraFieldsBehavior::Ignore,
            strict: false,
            populate_by_name: false,
            use_enum_values: false,
            arbitrary_types_allowed: false,
            defer_build: false,
            revalidate_instances: false,
            json_schema_extra: None,
            title: None,
        }
    }

    /// Create a config for a database table model.
    pub const fn table() -> Self {
        Self {
            table: true,
            from_attributes: false,
            validate_assignment: false,
            extra: ExtraFieldsBehavior::Ignore,
            strict: false,
            populate_by_name: false,
            use_enum_values: false,
            arbitrary_types_allowed: false,
            defer_build: false,
            revalidate_instances: false,
            json_schema_extra: None,
            title: None,
        }
    }
}

/// Trait for types that can be mapped to database tables.
///
/// This trait provides metadata about the table structure and
/// methods for converting between Rust structs and database rows.
///
/// # Example
///
/// ```ignore
/// use sqlmodel::Model;
///
/// #[derive(Model)]
/// #[sqlmodel(table = "heroes")]
/// struct Hero {
///     #[sqlmodel(primary_key)]
///     id: Option<i64>,
///     name: String,
///     secret_name: String,
///     age: Option<i32>,
/// }
/// ```
pub trait Model: Sized + Send + Sync {
    /// The name of the database table.
    const TABLE_NAME: &'static str;

    /// The primary key column name(s).
    const PRIMARY_KEY: &'static [&'static str];

    /// Relationship metadata for this model.
    ///
    /// The derive macro will populate this for relationship fields; models with
    /// no relationships can rely on the default empty slice.
    const RELATIONSHIPS: &'static [RelationshipInfo] = &[];

    /// Inheritance metadata for this model.
    ///
    /// Returns information about table inheritance if this model participates
    /// in an inheritance hierarchy (single, joined, or concrete table).
    /// The default implementation returns no inheritance.
    fn inheritance() -> InheritanceInfo {
        InheritanceInfo::none()
    }

    /// Get field metadata for all columns.
    fn fields() -> &'static [FieldInfo];

    /// Convert this model instance to a row of values.
    fn to_row(&self) -> Vec<(&'static str, Value)>;

    /// Construct a model instance from a database row.
    #[allow(clippy::result_large_err)]
    fn from_row(row: &Row) -> Result<Self>;

    /// If this is a joined-table inheritance *child* model, return the base (parent) table row.
    ///
    /// This enables query builders to implement joined inheritance DML (base+child insert/update/delete)
    /// without runtime reflection.
    ///
    /// The derive macro implements this automatically when a joined child declares exactly one
    /// `#[sqlmodel(parent)]` embedded parent field. Non-joined models (and joined bases) return `None`.
    #[must_use]
    fn joined_parent_row(&self) -> Option<Vec<(&'static str, Value)>> {
        None
    }

    /// Get the value of the primary key field(s).
    fn primary_key_value(&self) -> Vec<Value>;

    /// Check if this is a new record (primary key is None/default).
    fn is_new(&self) -> bool;

    /// Get the model configuration.
    ///
    /// Returns model-level configuration that affects validation,
    /// serialization, and database operations.
    fn model_config() -> ModelConfig {
        ModelConfig::new()
    }

    /// The shard key field name for horizontal sharding.
    ///
    /// Returns `None` if the model doesn't use sharding. When set,
    /// the sharded pool will use this field's value to determine
    /// which shard to route queries to.
    const SHARD_KEY: Option<&'static str> = None;

    /// Get the shard key value for this model instance.
    ///
    /// Returns `None` if the model doesn't have a shard key defined.
    /// The returned value is used by `ShardedPool` to determine the
    /// appropriate shard for insert/update/delete operations.
    fn shard_key_value(&self) -> Option<Value> {
        None
    }
}

/// Marker trait for models that support automatic ID generation.
pub trait AutoIncrement: Model {
    /// Set the auto-generated ID after insert.
    fn set_id(&mut self, id: i64);
}

/// Trait for models that track creation/update timestamps.
pub trait Timestamps: Model {
    /// Set the created_at timestamp.
    fn set_created_at(&mut self, timestamp: i64);

    /// Set the updated_at timestamp.
    fn set_updated_at(&mut self, timestamp: i64);
}

/// Trait for soft-deletable models.
pub trait SoftDelete: Model {
    /// Mark the model as deleted.
    fn mark_deleted(&mut self);

    /// Check if the model is deleted.
    fn is_deleted(&self) -> bool;
}

/// Lifecycle event hooks for model instances.
///
/// Models can implement this trait to receive callbacks at various points
/// in the persistence lifecycle: before/after insert, update, and delete.
///
/// All methods have default no-op implementations, so you only need to
/// override the ones you care about.
///
/// # Example
///
/// ```ignore
/// use sqlmodel_core::{Model, ModelEvents, Result};
///
/// #[derive(Model)]
/// struct User {
///     id: Option<i64>,
///     name: String,
///     created_at: Option<i64>,
///     updated_at: Option<i64>,
/// }
///
/// impl ModelEvents for User {
///     fn before_insert(&mut self) -> Result<()> {
///         let now = std::time::SystemTime::now()
///             .duration_since(std::time::UNIX_EPOCH)
///             .unwrap()
///             .as_secs() as i64;
///         self.created_at = Some(now);
///         self.updated_at = Some(now);
///         Ok(())
///     }
///
///     fn before_update(&mut self) -> Result<()> {
///         let now = std::time::SystemTime::now()
///             .duration_since(std::time::UNIX_EPOCH)
///             .unwrap()
///             .as_secs() as i64;
///         self.updated_at = Some(now);
///         Ok(())
///     }
/// }
/// ```
pub trait ModelEvents: Model {
    /// Called before a new instance is inserted into the database.
    ///
    /// Use this to set default values, validate data, or perform
    /// any pre-insert logic. Return an error to abort the insert.
    #[allow(unused_variables, clippy::result_large_err)]
    fn before_insert(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called after an instance has been successfully inserted.
    ///
    /// The instance now has its auto-generated ID (if applicable).
    /// Use this for post-insert notifications or logging.
    #[allow(unused_variables, clippy::result_large_err)]
    fn after_insert(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called before an existing instance is updated in the database.
    ///
    /// Use this to update timestamps, validate changes, or perform
    /// any pre-update logic. Return an error to abort the update.
    #[allow(unused_variables, clippy::result_large_err)]
    fn before_update(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called after an instance has been successfully updated.
    ///
    /// Use this for post-update notifications or logging.
    #[allow(unused_variables, clippy::result_large_err)]
    fn after_update(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called before an instance is deleted from the database.
    ///
    /// Use this for cleanup, validation, or any pre-delete logic.
    /// Return an error to abort the delete.
    #[allow(unused_variables, clippy::result_large_err)]
    fn before_delete(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called after an instance has been successfully deleted.
    ///
    /// Use this for post-delete notifications or logging.
    #[allow(unused_variables, clippy::result_large_err)]
    fn after_delete(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called after an instance has been loaded from the database.
    ///
    /// Use this to perform post-load initialization or validation.
    #[allow(unused_variables, clippy::result_large_err)]
    fn on_load(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called after an instance has been refreshed from the database.
    ///
    /// Use this to handle any logic needed after a refresh operation.
    #[allow(unused_variables, clippy::result_large_err)]
    fn on_refresh(&mut self) -> Result<()> {
        Ok(())
    }

    /// Called when individual attributes are detected as changed.
    ///
    /// This is invoked during flush when the change tracker detects that
    /// specific fields have been modified. Each change includes the field
    /// name and the old/new values as JSON.
    ///
    /// Return an error to abort the flush.
    ///
    /// # Example
    ///
    /// ```ignore
    /// impl ModelEvents for User {
    ///     fn on_attribute_change(&mut self, changes: &[AttributeChange]) -> Result<()> {
    ///         for change in changes {
    ///             if change.field_name == "email" {
    ///                 // trigger verification
    ///             }
    ///         }
    ///         Ok(())
    ///     }
    /// }
    /// ```
    #[allow(unused_variables, clippy::result_large_err)]
    fn on_attribute_change(&mut self, changes: &[AttributeChange]) -> Result<()> {
        Ok(())
    }
}

/// Describes a single attribute change detected by the change tracker.
#[derive(Debug, Clone)]
pub struct AttributeChange {
    /// The field name that changed.
    pub field_name: &'static str,
    /// The old value (as JSON).
    pub old_value: serde_json::Value,
    /// The new value (as JSON).
    pub new_value: serde_json::Value,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{FieldInfo, Row, SqlType, Value};

    #[derive(Debug)]
    struct TestModel;

    impl Model for TestModel {
        const TABLE_NAME: &'static str = "test_models";
        const PRIMARY_KEY: &'static [&'static str] = &["id"];

        fn fields() -> &'static [FieldInfo] {
            static FIELDS: &[FieldInfo] =
                &[FieldInfo::new("id", "id", SqlType::Integer).primary_key(true)];
            FIELDS
        }

        fn to_row(&self) -> Vec<(&'static str, Value)> {
            vec![]
        }

        fn from_row(_row: &Row) -> Result<Self> {
            Ok(Self)
        }

        fn primary_key_value(&self) -> Vec<Value> {
            vec![Value::from(1_i64)]
        }

        fn is_new(&self) -> bool {
            false
        }
    }

    #[test]
    fn test_default_relationships_is_empty() {
        assert!(TestModel::RELATIONSHIPS.is_empty());
    }

    // Test default ModelEvents implementation
    impl ModelEvents for TestModel {}

    #[test]
    fn test_model_events_default_before_insert() {
        let mut model = TestModel;
        assert!(model.before_insert().is_ok());
    }

    #[test]
    fn test_model_events_default_after_insert() {
        let mut model = TestModel;
        assert!(model.after_insert().is_ok());
    }

    #[test]
    fn test_model_events_default_before_update() {
        let mut model = TestModel;
        assert!(model.before_update().is_ok());
    }

    #[test]
    fn test_model_events_default_after_update() {
        let mut model = TestModel;
        assert!(model.after_update().is_ok());
    }

    #[test]
    fn test_model_events_default_before_delete() {
        let mut model = TestModel;
        assert!(model.before_delete().is_ok());
    }

    #[test]
    fn test_model_events_default_after_delete() {
        let mut model = TestModel;
        assert!(model.after_delete().is_ok());
    }

    #[test]
    fn test_model_events_default_on_load() {
        let mut model = TestModel;
        assert!(model.on_load().is_ok());
    }

    #[test]
    fn test_model_events_default_on_refresh() {
        let mut model = TestModel;
        assert!(model.on_refresh().is_ok());
    }

    // Test custom ModelEvents implementation that modifies state
    #[derive(Debug)]
    struct TimestampedModel {
        id: Option<i64>,
        created_at: i64,
        updated_at: i64,
    }

    impl Model for TimestampedModel {
        const TABLE_NAME: &'static str = "timestamped_models";
        const PRIMARY_KEY: &'static [&'static str] = &["id"];

        fn fields() -> &'static [FieldInfo] {
            static FIELDS: &[FieldInfo] =
                &[FieldInfo::new("id", "id", SqlType::Integer).primary_key(true)];
            FIELDS
        }

        fn to_row(&self) -> Vec<(&'static str, Value)> {
            vec![("id", self.id.map_or(Value::Null, Value::from))]
        }

        fn from_row(_row: &Row) -> Result<Self> {
            Ok(Self {
                id: Some(1),
                created_at: 0,
                updated_at: 0,
            })
        }

        fn primary_key_value(&self) -> Vec<Value> {
            vec![self.id.map_or(Value::Null, Value::from)]
        }

        fn is_new(&self) -> bool {
            self.id.is_none()
        }
    }

    impl ModelEvents for TimestampedModel {
        fn before_insert(&mut self) -> Result<()> {
            // Simulate setting created_at timestamp
            self.created_at = 1000;
            self.updated_at = 1000;
            Ok(())
        }

        fn before_update(&mut self) -> Result<()> {
            // Simulate updating updated_at timestamp
            self.updated_at = 2000;
            Ok(())
        }
    }

    #[test]
    fn test_model_events_custom_before_insert_sets_timestamps() {
        let mut model = TimestampedModel {
            id: None,
            created_at: 0,
            updated_at: 0,
        };

        assert_eq!(model.created_at, 0);
        assert_eq!(model.updated_at, 0);

        model.before_insert().unwrap();

        assert_eq!(model.created_at, 1000);
        assert_eq!(model.updated_at, 1000);
    }

    #[test]
    fn test_model_events_custom_before_update_sets_timestamp() {
        let mut model = TimestampedModel {
            id: Some(1),
            created_at: 1000,
            updated_at: 1000,
        };

        model.before_update().unwrap();

        // created_at should remain unchanged
        assert_eq!(model.created_at, 1000);
        // updated_at should be updated
        assert_eq!(model.updated_at, 2000);
    }

    #[test]
    fn test_model_events_custom_defaults_still_work() {
        // Ensure overriding some methods doesn't break the defaults
        let mut model = TimestampedModel {
            id: Some(1),
            created_at: 0,
            updated_at: 0,
        };

        // These use default implementations
        assert!(model.after_insert().is_ok());
        assert!(model.after_update().is_ok());
        assert!(model.before_delete().is_ok());
        assert!(model.after_delete().is_ok());
        assert!(model.on_load().is_ok());
        assert!(model.on_refresh().is_ok());
    }

    // ==================== ModelConfig Tests ====================

    #[test]
    fn test_model_config_new_defaults() {
        let config = ModelConfig::new();
        assert!(!config.table);
        assert!(!config.from_attributes);
        assert!(!config.validate_assignment);
        assert_eq!(config.extra, ExtraFieldsBehavior::Ignore);
        assert!(!config.strict);
        assert!(!config.populate_by_name);
        assert!(!config.use_enum_values);
        assert!(!config.arbitrary_types_allowed);
        assert!(!config.defer_build);
        assert!(!config.revalidate_instances);
        assert!(config.json_schema_extra.is_none());
        assert!(config.title.is_none());
    }

    #[test]
    fn test_model_config_table_constructor() {
        let config = ModelConfig::table();
        assert!(config.table);
        assert!(!config.from_attributes);
    }

    #[test]
    fn test_extra_fields_behavior_default() {
        let behavior = ExtraFieldsBehavior::default();
        assert_eq!(behavior, ExtraFieldsBehavior::Ignore);
    }

    #[test]
    fn test_model_default_config() {
        // TestModel uses default implementation of model_config()
        let config = TestModel::model_config();
        assert!(!config.table);
        assert!(!config.from_attributes);
    }
}