rustrails-record 0.1.2

ORM layer (ActiveRecord equivalent)
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
use rustrails_macros::{__ModelRecordState, ModelDefinition};
use sea_orm::{ActiveModelTrait, EntityTrait};

use crate::connection::ConnectionError;

fn from_model_state(state: __ModelRecordState) -> RecordState {
    match state {
        __ModelRecordState::New => RecordState::New,
        __ModelRecordState::Persisted => RecordState::Persisted,
        __ModelRecordState::Destroyed => RecordState::Destroyed,
    }
}

fn to_model_state(state: RecordState) -> __ModelRecordState {
    match state {
        RecordState::New => __ModelRecordState::New,
        RecordState::Persisted => __ModelRecordState::Persisted,
        RecordState::Destroyed => __ModelRecordState::Destroyed,
    }
}

/// Errors returned by record operations.
#[derive(Debug, thiserror::Error)]
pub enum RecordError {
    /// Raised when a lookup cannot find a matching row.
    #[error("record not found")]
    NotFound,
    /// Raised when a query expected exactly one row but found more than one.
    #[error("multiple records found when exactly one was expected")]
    SoleRecordExceeded,
    /// Raised when caller-provided attributes are invalid.
    #[error("record invalid: {0}")]
    Invalid(String),
    /// Raised when a record cannot be saved in its current state.
    #[error("record not saved")]
    NotSaved,
    /// Raised when persistence is attempted on a readonly record.
    #[error("record is readonly")]
    ReadOnlyRecord,
    /// Raised when a stale object is detected during persistence.
    #[error("stale object")]
    StaleObject,
    /// Wraps SeaORM database errors.
    #[error("database error: {0}")]
    Database(#[from] sea_orm::DbErr),
    /// Wraps connection-management errors.
    #[error("connection error: {0}")]
    Connection(#[from] ConnectionError),
}

/// Tracks whether a record has been persisted or destroyed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RecordState {
    /// The record has not been inserted yet.
    #[default]
    New,
    /// The record exists in the database.
    Persisted,
    /// The record has been deleted.
    Destroyed,
}

/// Bridges a RustRails record wrapper to its SeaORM entity.
pub trait Record: Sized + Send + Sync + 'static {
    /// The SeaORM entity backing this record type.
    type Entity: EntityTrait;

    /// Returns the database table name.
    fn table_name() -> &'static str;

    /// Returns the primary key column name.
    fn primary_key_name() -> &'static str {
        "id"
    }

    /// Returns the primary key value when present.
    fn id(&self) -> Option<i64>;

    /// Returns the current lifecycle state.
    fn record_state(&self) -> RecordState;

    /// Updates the lifecycle state.
    fn set_record_state(&mut self, state: RecordState);

    /// Returns `true` when the record has not been persisted yet.
    fn new_record(&self) -> bool {
        self.record_state() == RecordState::New
    }

    /// Returns `true` when the record exists in the database.
    fn persisted(&self) -> bool {
        self.record_state() == RecordState::Persisted
    }

    /// Returns `true` when the record has been destroyed.
    fn destroyed(&self) -> bool {
        self.record_state() == RecordState::Destroyed
    }

    /// Builds the record wrapper from a SeaORM model.
    fn from_sea_model(model: <Self::Entity as EntityTrait>::Model) -> Self;

    /// Converts the record wrapper into a SeaORM active model.
    fn to_active_model(&self) -> <Self::Entity as EntityTrait>::ActiveModel
    where
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelTrait;
}

impl<T: ModelDefinition> Record for T
where
    <T::SeaEntity as EntityTrait>::ActiveModel: ActiveModelTrait,
{
    type Entity = T::SeaEntity;

    fn table_name() -> &'static str {
        T::table_name()
    }

    fn id(&self) -> Option<i64> {
        self.get_id()
    }

    fn record_state(&self) -> RecordState {
        from_model_state(self.get_record_state())
    }

    fn set_record_state(&mut self, state: RecordState) {
        self.set_model_record_state(to_model_state(state));
    }

    fn from_sea_model(model: <T::SeaEntity as EntityTrait>::Model) -> Self {
        T::from_sea_model(model)
    }

    fn to_active_model(&self) -> <T::SeaEntity as EntityTrait>::ActiveModel {
        self.to_sea_active_model()
    }
}

impl<T: ModelDefinition> crate::querying::AsyncQuerying for T where
    <T::SeaEntity as EntityTrait>::ActiveModel: ActiveModelTrait
{
}

impl<T: ModelDefinition> crate::persistence::AsyncPersistence for T where
    <T::SeaEntity as EntityTrait>::ActiveModel: ActiveModelTrait
{
}

#[cfg(test)]
pub(crate) mod test_support {
    use sea_orm::entity::prelude::*;
    use sea_orm::{
        ActiveValue::NotSet, ActiveValue::Set, ConnectionTrait, Database, DatabaseConnection,
        Schema,
    };
    use serde::{Deserialize, Serialize};

    use super::{Record, RecordState};
    use crate::{persistence::AsyncPersistence, querying::AsyncQuerying};

    /// SeaORM test entity used across record-module tests.
    pub mod test_user {
        use sea_orm::entity::prelude::*;

        #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
        #[sea_orm(table_name = "test_users")]
        pub struct Model {
            #[sea_orm(primary_key)]
            pub id: i32,
            pub name: String,
            pub email: String,
        }

        #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
        pub enum Relation {}

        impl ActiveModelBehavior for ActiveModel {}
    }

    fn default_record_state() -> RecordState {
        RecordState::New
    }

    /// Concrete test record used to exercise generic record behavior.
    #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct TestUser {
        /// Primary key.
        pub id: Option<i64>,
        /// Display name.
        pub name: String,
        /// Email address.
        pub email: String,
        /// Lifecycle state tracked outside serialized attributes.
        #[serde(skip, default = "default_record_state")]
        pub state: RecordState,
    }

    impl TestUser {
        /// Creates a persisted test user value.
        pub fn persisted(id: i64, name: &str, email: &str) -> Self {
            Self {
                id: Some(id),
                name: name.to_owned(),
                email: email.to_owned(),
                state: RecordState::Persisted,
            }
        }
    }

    impl Record for TestUser {
        type Entity = test_user::Entity;

        fn table_name() -> &'static str {
            "test_users"
        }

        fn id(&self) -> Option<i64> {
            self.id
        }

        fn record_state(&self) -> RecordState {
            self.state
        }

        fn set_record_state(&mut self, state: RecordState) {
            self.state = state;
        }

        fn from_sea_model(model: <Self::Entity as EntityTrait>::Model) -> Self {
            Self {
                id: Some(i64::from(model.id)),
                name: model.name,
                email: model.email,
                state: RecordState::Persisted,
            }
        }

        fn to_active_model(&self) -> <Self::Entity as EntityTrait>::ActiveModel {
            test_user::ActiveModel {
                id: match self.id.and_then(|value| i32::try_from(value).ok()) {
                    Some(value) => Set(value),
                    None => NotSet,
                },
                name: Set(self.name.clone()),
                email: Set(self.email.clone()),
            }
        }
    }

    impl AsyncPersistence for TestUser {}
    impl AsyncQuerying for TestUser {}

    /// Creates an in-memory SQLite database with the test table.
    pub async fn setup_db() -> DatabaseConnection {
        let db = Database::connect("sqlite::memory:")
            .await
            .expect("in-memory sqlite connection should succeed");
        let backend = db.get_database_backend();
        let schema = Schema::new(backend);
        db.execute(&schema.create_table_from_entity(test_user::Entity))
            .await
            .expect("test_users table should be created");
        db
    }

    pub fn with_sync_test_user_db(test: impl FnOnce() + Send + 'static) {
        rustrails_support::testing::run_sync_db_test(|| {
            rustrails_support::runtime::block_on(async {
                let db = rustrails_support::database::db();
                let schema = Schema::new(db.get_database_backend());
                db.execute(&schema.create_table_from_entity(test_user::Entity))
                    .await
                    .expect("test_users table should be created");
            });
            test();
        });
    }

    /// Inserts three ordered fixture rows and returns their record wrappers.
    pub async fn seed_users(db: &DatabaseConnection) -> Vec<TestUser> {
        let mut users = Vec::new();
        for (name, email) in [
            ("Alice", "alice@example.com"),
            ("Bob", "bob@example.com"),
            ("Carol", "carol@example.com"),
        ] {
            let model = test_user::ActiveModel {
                name: Set(name.to_owned()),
                email: Set(email.to_owned()),
                ..Default::default()
            }
            .insert(db)
            .await
            .expect("fixture insert should succeed");
            users.push(TestUser::from_sea_model(model));
        }
        users
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::{Record, RecordState};
    use crate::{
        Persistence, Querying,
        base::test_support::{TestUser, test_user},
    };
    use rustrails_macros::model;
    use rustrails_support::{database, runtime};
    use serde_json::json;

    model! {
        MacroBackedPost {
            title: String,
            published: bool,
        }
        table_name: "macro_backed_posts";
    }

    #[test]
    fn macro_backed_models_implement_record_and_sync_traits() {
        fn assert_record<T: Record>() {}
        fn assert_querying<T: Querying>() {}
        fn assert_persistence<T: Persistence>() {}

        assert_record::<MacroBackedPost>();
        assert_querying::<MacroBackedPost>();
        assert_persistence::<MacroBackedPost>();
    }

    #[test]
    fn state_helpers_match_record_state() {
        let mut user = TestUser::default();
        assert!(user.new_record());
        assert!(!user.persisted());
        assert!(!user.destroyed());

        user.set_record_state(RecordState::Persisted);
        assert!(!user.new_record());
        assert!(user.persisted());
        assert!(!user.destroyed());

        user.set_record_state(RecordState::Destroyed);
        assert!(!user.new_record());
        assert!(!user.persisted());
        assert!(user.destroyed());
    }

    #[test]
    fn primary_key_name_defaults_to_id() {
        assert_eq!(TestUser::primary_key_name(), "id");
    }

    #[test]
    fn table_name_matches_entity_mapping() {
        assert_eq!(TestUser::table_name(), "test_users");
    }

    #[test]
    fn from_sea_model_marks_record_persisted() {
        let record = TestUser::from_sea_model(test_user::Model {
            id: 7,
            name: "Alice".to_owned(),
            email: "alice@example.com".to_owned(),
        });

        assert_eq!(record.id(), Some(7));
        assert_eq!(record.name, "Alice");
        assert_eq!(record.email, "alice@example.com");
        assert_eq!(record.record_state(), RecordState::Persisted);
    }

    #[test]
    fn to_active_model_preserves_attributes() {
        let user = TestUser::persisted(11, "Bob", "bob@example.com");
        let active = user.to_active_model();

        assert_eq!(active.id, sea_orm::ActiveValue::Set(11));
        assert_eq!(active.name, sea_orm::ActiveValue::Set("Bob".to_owned()));
        assert_eq!(
            active.email,
            sea_orm::ActiveValue::Set("bob@example.com".to_owned())
        );
    }

    #[test]
    fn macro_backed_model_supports_sync_crud_cycle() {
        let _runtime = runtime::init_runtime();
        database::establish("sqlite::memory:").expect("sqlite in-memory connection should succeed");

        runtime::block_on(async {
            let db = database::db();
            use sea_orm::ConnectionTrait;
            db.execute_unprepared(
                "CREATE TABLE macro_backed_posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, published BOOLEAN NOT NULL DEFAULT 0)",
            )
            .await
            .expect("macro_backed_posts table should be created");
        });

        let mut created = MacroBackedPost::create_sync(HashMap::from([
            ("title".to_owned(), json!("Hello World")),
            ("published".to_owned(), json!(false)),
        ]))
        .expect("create_sync should persist the record");

        assert!(created.id.is_some());
        assert_eq!(created.title, "Hello World");
        assert!(!created.published);
        assert!(created.persisted());

        let found =
            MacroBackedPost::find_sync(created.id.expect("created record should have an id"))
                .expect("find_sync should load the inserted record");
        assert_eq!(found.title, "Hello World");
        assert!(!found.published);

        created.title = "Updated".to_owned();
        created.published = true;
        created
            .save_sync()
            .expect("save_sync should update persisted records");

        let reloaded =
            MacroBackedPost::find_sync(created.id.expect("updated record should keep its id"))
                .expect("find_sync should load the updated record");
        assert_eq!(reloaded.title, "Updated");
        assert!(reloaded.published);
        assert_eq!(
            MacroBackedPost::count_sync().expect("count_sync should work"),
            1
        );

        created
            .destroy_sync()
            .expect("destroy_sync should delete the row");
        assert!(created.destroyed());
        assert_eq!(
            MacroBackedPost::count_sync().expect("count_sync should work"),
            0
        );
    }
}