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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use std::collections::{HashMap, HashSet};

use rustrails_macros::{BelongsToAssociation, HasManyAssociation, HasOneAssociation};
use rustrails_support::{
    database,
    inflector::{foreign_key, singularize},
    runtime,
};
use sea_orm::{ColumnTrait, EntityTrait, Iterable};
use serde::Serialize;
use serde_json::{Value, json};

use crate::{Querying, Record, RecordError, Relation};

/// `belongs_to` association metadata builders.
pub mod belongs_to;
/// `has_and_belongs_to_many` association metadata builders.
pub mod has_and_belongs_to_many;
/// `has_many` association metadata builders.
pub mod has_many;
/// `has_one` association metadata builders.
pub mod has_one;

pub use belongs_to::BelongsToBuilder;
pub use has_and_belongs_to_many::HasAndBelongsToManyBuilder;
pub use has_many::HasManyBuilder;
pub use has_one::HasOneBuilder;

/// The cardinality and ownership semantics of an association.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssociationType {
    /// A one-to-many relationship.
    HasMany,
    /// A one-to-one relationship owned by the current record.
    HasOne,
    /// A many-to-one relationship owned by the current record.
    BelongsTo,
    /// A many-to-many relationship backed by a join table.
    HasAndBelongsToMany,
}

/// Action applied to associated rows when the owner changes lifecycle state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependentAction {
    /// Load each associated record and destroy it through the record lifecycle.
    Destroy,
    /// Delete associated rows directly in storage.
    Delete,
    /// Clear the foreign key on associated rows.
    Nullify,
    /// Prevent the owner action while dependents exist.
    Restrict,
}

/// Metadata describing a declared association.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssociationMeta {
    /// The association name as exposed on the model.
    pub name: String,
    /// The relationship kind.
    pub association_type: AssociationType,
    /// The target table for the associated records.
    pub target_table: String,
    /// The foreign-key column involved in the association.
    pub foreign_key: String,
    /// The primary-key column used on the owning side.
    pub primary_key: String,
    /// Optional dependent action.
    pub dependent: Option<DependentAction>,
    /// Optional join model or join table name.
    pub through: Option<String>,
    /// Whether the association resolves targets polymorphically.
    pub polymorphic: bool,
}

/// Registry of associations declared for a record type.
#[derive(Debug, Default)]
pub struct AssociationRegistry {
    associations: Vec<AssociationMeta>,
}

impl AssociationRegistry {
    /// Creates an empty association registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends association metadata to the registry.
    pub fn add(&mut self, meta: AssociationMeta) {
        self.associations.push(meta);
    }

    /// Returns the association metadata with the given name.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&AssociationMeta> {
        self.associations.iter().find(|meta| meta.name == name)
    }

    /// Returns every association with the requested type.
    #[must_use]
    pub fn of_type(&self, assoc_type: AssociationType) -> Vec<&AssociationMeta> {
        self.associations
            .iter()
            .filter(|meta| meta.association_type == assoc_type)
            .collect()
    }

    /// Returns all registered associations in declaration order.
    #[must_use]
    pub fn all(&self) -> &[AssociationMeta] {
        &self.associations
    }
}

/// Trait implemented by records that expose association metadata.
pub trait HasAssociations: Record {
    /// Returns the registry of associations declared for the record type.
    fn associations() -> &'static AssociationRegistry;
}

/// Query helper generated for `has_many!` associations without a `through:` option.
pub trait HasManyQuery<Target> {
    /// Loads the associated records for the receiver.
    fn has_many(&self) -> Result<Vec<Target>, RecordError>
    where
        Self: Record + Serialize + HasManyAssociation<Target>,
        Target: Querying,
        <Target::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        let Some(owner_id) = self.id() else {
            return Ok(Vec::new());
        };

        let definition = <Self as HasManyAssociation<Target>>::association_definition();
        let foreign_key = definition
            .foreign_key
            .map(str::to_owned)
            .unwrap_or_else(|| default_owner_foreign_key::<Self>());

        load_many_by_field::<Target>(&foreign_key, owner_id)
    }
}

/// Query helper generated for `has_many!` associations that use `through:`.
pub trait HasManyThroughQuery<Target, Join> {
    /// Loads the associated records through the join model.
    fn has_many(&self) -> Result<Vec<Target>, RecordError>
    where
        Self: Record + Serialize + HasManyAssociation<Target>,
        Target: Querying,
        Join: Querying + Serialize,
        <Target::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Join::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        let Some(owner_id) = self.id() else {
            return Ok(Vec::new());
        };

        let join_owner_key = default_owner_foreign_key::<Self>();
        let join_target_key = default_target_foreign_key::<Target>();
        let join_rows = load_many_by_field::<Join>(&join_owner_key, owner_id)?;
        let mut target_ids = HashSet::new();
        let mut targets = Vec::new();

        for join_row in join_rows {
            let Some(target_id) = extract_serialized_id(&join_row, &join_target_key)? else {
                continue;
            };
            if target_ids.insert(target_id) {
                targets.push(Target::find_sync(target_id)?);
            }
        }

        Ok(targets)
    }
}

/// Query helper generated for `belongs_to!` associations.
pub trait BelongsToQuery<Target> {
    /// Loads the owner record referenced by the receiver.
    fn belongs_to(&self) -> Result<Target, RecordError>
    where
        Self: Record + Serialize + BelongsToAssociation<Target>,
        Target: Querying,
        <Target::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        let definition = <Self as BelongsToAssociation<Target>>::association_definition();
        let foreign_key = definition
            .foreign_key
            .map(str::to_owned)
            .unwrap_or_else(|| default_target_foreign_key::<Target>());
        let target_id = extract_serialized_id(self, &foreign_key)?.ok_or(RecordError::NotFound)?;

        Target::find_sync(target_id)
    }
}

/// Query helper generated for `has_one!` associations.
pub trait HasOneQuery<Target> {
    /// Loads the singular associated record for the receiver.
    fn has_one(&self) -> Result<Option<Target>, RecordError>
    where
        Self: Record + Serialize + HasOneAssociation<Target>,
        Target: Querying,
        <Target::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        let Some(owner_id) = self.id() else {
            return Ok(None);
        };

        let definition = <Self as HasOneAssociation<Target>>::association_definition();
        let foreign_key = definition
            .foreign_key
            .map(str::to_owned)
            .unwrap_or_else(|| default_owner_foreign_key::<Self>());

        load_one_by_field::<Target>(&foreign_key, owner_id)
    }
}

fn default_owner_foreign_key<Model: Record>() -> String {
    foreign_key(&singularize(Model::table_name()))
}

fn default_target_foreign_key<Target: Record>() -> String {
    foreign_key(&singularize(Target::table_name()))
}

fn load_many_by_field<Target>(field: &str, value: i64) -> Result<Vec<Target>, RecordError>
where
    Target: Querying,
    <Target::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
{
    database::with_db(|db| {
        runtime::block_on(
            Relation::<Target>::new()
                .r#where(HashMap::from([(field.to_owned(), json!(value))]))
                .load(db),
        )
    })
}

fn load_one_by_field<Target>(field: &str, value: i64) -> Result<Option<Target>, RecordError>
where
    Target: Querying,
    <Target::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
{
    database::with_db(|db| {
        runtime::block_on(
            Relation::<Target>::new()
                .r#where(HashMap::from([(field.to_owned(), json!(value))]))
                .first(db),
        )
    })
}

fn extract_serialized_id<T: Serialize>(
    record: &T,
    field: &str,
) -> Result<Option<i64>, RecordError> {
    let value =
        serde_json::to_value(record).map_err(|error| RecordError::Invalid(error.to_string()))?;
    let object = value.as_object().ok_or_else(|| {
        RecordError::Invalid("associated record must serialize to a JSON object".to_owned())
    })?;

    match object.get(field) {
        Some(Value::Null) => Ok(None),
        Some(value) => Ok(Some(json_value_to_i64(value, field)?)),
        None => Err(RecordError::Invalid(format!(
            "missing association key `{field}` on serialized record"
        ))),
    }
}

fn json_value_to_i64(value: &Value, field: &str) -> Result<i64, RecordError> {
    match value {
        Value::Number(number) => {
            if let Some(value) = number.as_i64() {
                Ok(value)
            } else if let Some(value) = number.as_u64() {
                i64::try_from(value).map_err(|_| {
                    RecordError::Invalid(format!("association key `{field}` does not fit in i64"))
                })
            } else {
                Err(RecordError::Invalid(format!(
                    "association key `{field}` must be an integer"
                )))
            }
        }
        _ => Err(RecordError::Invalid(format!(
            "association key `{field}` must be numeric"
        ))),
    }
}

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

    use rustrails_macros::{
        AssociationKind, BelongsToAssociation, HasManyAssociation, HasOneAssociation, belongs_to,
        has_many, has_one, model,
    };
    use rustrails_support::{database, runtime};
    use serde_json::json;

    use crate::{
        Persistence,
        associations::{
            AssociationRegistry, AssociationType, BelongsToBuilder, BelongsToQuery,
            DependentAction, HasAndBelongsToManyBuilder, HasAssociations, HasManyBuilder,
            HasManyQuery, HasOneBuilder, HasOneQuery,
        },
        base::test_support::TestUser,
    };

    model! {
        QueryBlog {
            title: String,
        }
        table_name: "query_blogs";
    }

    model! {
        QueryPost {
            query_blog_id: i64,
            title: String,
        }
        table_name: "query_posts";
    }

    model! {
        QueryProfile {
            query_blog_id: i64,
            bio: String,
        }
        table_name: "query_profiles";
    }

    has_many!(QueryBlog => QueryPost, foreign_key: query_blog_id);
    belongs_to!(QueryPost => QueryBlog, foreign_key: query_blog_id);
    has_one!(QueryBlog => QueryProfile);

    struct DefaultHasManyAuthor;
    struct DefaultHasManyPost;
    struct ForeignKeyHasManyAuthor;
    struct ForeignKeyHasManyPost;
    struct ThroughHasManyAuthor;
    struct ThroughHasManyTag;
    struct PostTagging;
    struct DefaultBelongsToComment;
    struct DefaultBelongsToPost;
    struct ForeignKeyBelongsToComment;
    struct ForeignKeyBelongsToBlog;
    struct DefaultHasOneUser;
    struct DefaultHasOneProfile;

    has_many!(DefaultHasManyAuthor => DefaultHasManyPost);
    has_many!(ForeignKeyHasManyAuthor => ForeignKeyHasManyPost, foreign_key: author_id);
    has_many!(ThroughHasManyAuthor => ThroughHasManyTag, through: PostTagging);
    belongs_to!(DefaultBelongsToComment => DefaultBelongsToPost);
    belongs_to!(ForeignKeyBelongsToComment => ForeignKeyBelongsToBlog, foreign_key: blog_id);
    has_one!(DefaultHasOneUser => DefaultHasOneProfile);

    static TEST_ASSOCIATIONS: LazyLock<AssociationRegistry> = LazyLock::new(|| {
        let mut registry = AssociationRegistry::new();
        registry.add(
            HasManyBuilder::new("comments")
                .dependent(DependentAction::Destroy)
                .build(),
        );
        registry.add(HasOneBuilder::new("profile").build());
        registry.add(BelongsToBuilder::new("account").build());
        registry.add(
            HasAndBelongsToManyBuilder::new("roles")
                .through("accounts_roles")
                .build(),
        );
        registry
    });

    impl HasAssociations for TestUser {
        fn associations() -> &'static AssociationRegistry {
            &TEST_ASSOCIATIONS
        }
    }

    #[test]
    fn registry_returns_named_association() {
        let association = TestUser::associations()
            .get("comments")
            .expect("comments association should exist");

        assert_eq!(association.association_type, AssociationType::HasMany);
        assert_eq!(association.dependent, Some(DependentAction::Destroy));
    }

    #[test]
    fn registry_filters_associations_by_type() {
        let has_many = TestUser::associations().of_type(AssociationType::HasMany);
        let belongs_to = TestUser::associations().of_type(AssociationType::BelongsTo);

        assert_eq!(has_many.len(), 1);
        assert_eq!(has_many[0].name, "comments");
        assert_eq!(belongs_to.len(), 1);
        assert_eq!(belongs_to[0].name, "account");
    }

    #[test]
    fn registry_exposes_all_associations_in_order() {
        let names = TestUser::associations()
            .all()
            .iter()
            .map(|meta| meta.name.as_str())
            .collect::<Vec<_>>();

        assert_eq!(names, vec!["comments", "profile", "account", "roles"]);
    }

    #[test]
    fn registry_returns_none_for_unknown_association() {
        assert!(TestUser::associations().get("missing").is_none());
    }
    #[test]
    fn new_registry_starts_empty() {
        let registry = AssociationRegistry::new();

        assert!(registry.all().is_empty());
    }

    #[test]
    fn add_appends_associations() {
        let mut registry = AssociationRegistry::new();
        registry.add(HasManyBuilder::new("comments").build());
        registry.add(HasOneBuilder::new("profile").build());

        assert_eq!(registry.all().len(), 2);
    }

    #[test]
    fn get_is_case_sensitive() {
        assert!(TestUser::associations().get("Comments").is_none());
    }

    #[test]
    fn get_returns_first_matching_name_when_duplicates_exist() {
        let mut registry = AssociationRegistry::new();
        registry.add(HasManyBuilder::new("comments").build());
        registry.add(
            HasManyBuilder::new("comments")
                .foreign_key("owner_id")
                .build(),
        );

        let association = registry.get("comments").expect("association should exist");

        assert_eq!(association.foreign_key, "comment_id");
    }

    #[test]
    fn of_type_returns_empty_when_no_associations_match() {
        let registry = AssociationRegistry::new();

        assert!(registry.of_type(AssociationType::HasMany).is_empty());
    }

    #[test]
    fn of_type_preserves_declaration_order() {
        let mut registry = AssociationRegistry::new();
        registry.add(HasManyBuilder::new("comments").build());
        registry.add(HasManyBuilder::new("tags").build());

        let names = registry
            .of_type(AssociationType::HasMany)
            .into_iter()
            .map(|meta| meta.name.as_str())
            .collect::<Vec<_>>();

        assert_eq!(names, vec!["comments", "tags"]);
    }

    #[test]
    fn all_returns_empty_slice_for_new_registry() {
        let registry = AssociationRegistry::new();

        assert_eq!(registry.all(), &[]);
    }

    #[test]
    fn associations_registry_is_stable_across_calls() {
        assert!(std::ptr::eq(
            TestUser::associations(),
            TestUser::associations()
        ));
    }

    fn association_kind_name(kind: AssociationKind) -> &'static str {
        match kind {
            AssociationKind::HasMany => "has_many",
            AssociationKind::BelongsTo => "belongs_to",
            AssociationKind::HasOne => "has_one",
        }
    }

    #[test]
    fn default_has_many_definition_sets_has_many_kind() {
        let definition =
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition();

        assert_eq!(definition.kind, AssociationKind::HasMany);
    }

    #[test]
    fn default_has_many_definition_records_model_name() {
        let definition =
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition();

        assert_eq!(definition.model, "DefaultHasManyAuthor");
    }

    #[test]
    fn default_has_many_definition_records_target_name() {
        let definition =
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition();

        assert_eq!(definition.target, "DefaultHasManyPost");
    }

    #[test]
    fn default_has_many_definition_has_no_foreign_key_override() {
        let definition =
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition();

        assert_eq!(definition.foreign_key, None);
    }

    #[test]
    fn default_has_many_definition_has_no_through_target() {
        let definition =
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition();

        assert_eq!(definition.through, None);
    }

    #[test]
    fn foreign_key_has_many_definition_records_foreign_key_override() {
        let definition = <ForeignKeyHasManyAuthor as HasManyAssociation<ForeignKeyHasManyPost>>::association_definition();

        assert_eq!(definition.foreign_key, Some("author_id"));
    }

    #[test]
    fn through_has_many_definition_records_through_target() {
        let definition =
            <ThroughHasManyAuthor as HasManyAssociation<ThroughHasManyTag>>::association_definition(
            );

        assert_eq!(definition.through, Some("PostTagging"));
    }

    #[test]
    fn has_many_association_definition_is_stable_across_calls() {
        assert_eq!(
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition(),
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition(),
        );
    }

    #[test]
    fn default_belongs_to_definition_sets_belongs_to_kind() {
        let definition = <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition();

        assert_eq!(definition.kind, AssociationKind::BelongsTo);
    }

    #[test]
    fn default_belongs_to_definition_records_model_name() {
        let definition = <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition();

        assert_eq!(definition.model, "DefaultBelongsToComment");
    }

    #[test]
    fn default_belongs_to_definition_records_target_name() {
        let definition = <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition();

        assert_eq!(definition.target, "DefaultBelongsToPost");
    }

    #[test]
    fn default_belongs_to_definition_has_no_foreign_key_override() {
        let definition = <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition();

        assert_eq!(definition.foreign_key, None);
    }

    #[test]
    fn default_belongs_to_definition_has_no_through_target() {
        let definition = <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition();

        assert_eq!(definition.through, None);
    }

    #[test]
    fn foreign_key_belongs_to_definition_records_foreign_key_override() {
        let definition = <ForeignKeyBelongsToComment as BelongsToAssociation<
            ForeignKeyBelongsToBlog,
        >>::association_definition();

        assert_eq!(definition.foreign_key, Some("blog_id"));
    }

    #[test]
    fn belongs_to_association_definition_is_stable_across_calls() {
        assert_eq!(
            <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition(),
            <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition(),
        );
    }

    #[test]
    fn default_has_one_definition_sets_has_one_kind() {
        let definition =
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            );

        assert_eq!(definition.kind, AssociationKind::HasOne);
    }

    #[test]
    fn default_has_one_definition_records_model_name() {
        let definition =
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            );

        assert_eq!(definition.model, "DefaultHasOneUser");
    }

    #[test]
    fn default_has_one_definition_records_target_name() {
        let definition =
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            );

        assert_eq!(definition.target, "DefaultHasOneProfile");
    }

    #[test]
    fn default_has_one_definition_has_no_foreign_key_override() {
        let definition =
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            );

        assert_eq!(definition.foreign_key, None);
    }

    #[test]
    fn default_has_one_definition_has_no_through_target() {
        let definition =
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            );

        assert_eq!(definition.through, None);
    }

    #[test]
    fn has_one_association_definition_is_stable_across_calls() {
        assert_eq!(
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            ),
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            ),
        );
    }

    #[test]
    fn has_many_definition_kind_matches_has_many_branch() {
        let definition =
            <DefaultHasManyAuthor as HasManyAssociation<DefaultHasManyPost>>::association_definition();

        assert_eq!(association_kind_name(definition.kind), "has_many");
    }

    #[test]
    fn belongs_to_definition_kind_matches_belongs_to_branch() {
        let definition = <DefaultBelongsToComment as BelongsToAssociation<DefaultBelongsToPost>>::association_definition();

        assert_eq!(association_kind_name(definition.kind), "belongs_to");
    }

    #[test]
    fn has_one_definition_kind_matches_has_one_branch() {
        let definition =
            <DefaultHasOneUser as HasOneAssociation<DefaultHasOneProfile>>::association_definition(
            );

        assert_eq!(association_kind_name(definition.kind), "has_one");
    }

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

        runtime::block_on(async {
            use sea_orm::ConnectionTrait;

            let db = database::db();
            db.execute_unprepared(
                "CREATE TABLE query_blogs (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL)",
            )
            .await
            .expect("query_blogs table should be created");
            db.execute_unprepared(
                "CREATE TABLE query_posts (id INTEGER PRIMARY KEY AUTOINCREMENT, query_blog_id INTEGER NOT NULL, title TEXT NOT NULL)",
            )
            .await
            .expect("query_posts table should be created");
            db.execute_unprepared(
                "CREATE TABLE query_profiles (id INTEGER PRIMARY KEY AUTOINCREMENT, query_blog_id INTEGER NOT NULL, bio TEXT NOT NULL)",
            )
            .await
            .expect("query_profiles table should be created");
        });

        let blog = QueryBlog::create_sync(HashMap::from([("title".to_owned(), json!("Main"))]))
            .expect("blog should be created");
        let blog_id = blog.id.expect("blog should have an id");

        let post = QueryPost::create_sync(HashMap::from([
            ("query_blog_id".to_owned(), json!(blog_id)),
            ("title".to_owned(), json!("First")),
        ]))
        .expect("post should be created");
        QueryProfile::create_sync(HashMap::from([
            ("query_blog_id".to_owned(), json!(blog_id)),
            ("bio".to_owned(), json!("About the blog")),
        ]))
        .expect("profile should be created");

        let posts: Vec<QueryPost> = blog.has_many().expect("has_many should load related posts");
        assert_eq!(posts.len(), 1);
        assert_eq!(posts[0].title, "First");

        let owner: QueryBlog = post.belongs_to().expect("belongs_to should load the owner");
        assert_eq!(owner.title, "Main");

        let profile = blog
            .has_one()
            .expect("has_one should query the related record");
        assert_eq!(profile.expect("profile should exist").bio, "About the blog");
    }
}