cot 0.5.0

The Rust web framework for lazy developers.
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
#![cfg(feature = "fake")]
#![cfg_attr(miri, ignore)]

use cot::db::migrations::{Field, Operation};
use cot::db::query::ExprEq;
use cot::db::{
    Auto, Database, DatabaseError, DatabaseField, ForeignKey, ForeignKeyOnDeletePolicy,
    ForeignKeyOnUpdatePolicy, Identifier, LimitedString, Model, model, query,
};
use cot::test::TestDatabase;
use fake::rand::SeedableRng;
use fake::rand::rngs::StdRng;
use fake::{Dummy, Fake, Faker};

struct WeekdaySetFaker;

impl Dummy<WeekdaySetFaker> for chrono::WeekdaySet {
    fn dummy_with_rng<R: fake::rand::Rng + ?Sized>(_: &WeekdaySetFaker, rng: &mut R) -> Self {
        use chrono::Weekday;

        let mut set = chrono::WeekdaySet::EMPTY;
        let weekdays = [
            Weekday::Mon,
            Weekday::Tue,
            Weekday::Wed,
            Weekday::Thu,
            Weekday::Fri,
            Weekday::Sat,
            Weekday::Sun,
        ];

        for weekday in weekdays {
            if rng.random_bool(0.5) {
                set.insert(weekday);
            }
        }

        set
    }
}

#[derive(Debug, PartialEq)]
#[model]
struct TestModel {
    #[model(primary_key)]
    id: Auto<i32>,
    name: String,
}

#[cot_macros::dbtest]
async fn model_crud(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    assert_eq!(TestModel::objects().all(&**test_db).await.unwrap(), vec![]);

    // Create
    let mut model = TestModel {
        id: Auto::fixed(1),
        name: "test".to_owned(),
    };
    model.save(&**test_db).await.unwrap();

    // Read
    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 1);
    assert_eq!(objects[0].name, "test");

    // Update (& read again)
    model.name = "test2".to_owned();
    model.save(&**test_db).await.unwrap();
    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 1);
    assert_eq!(objects[0].name, "test2");

    // Delete
    TestModel::objects()
        .filter(<TestModel as Model>::Fields::id.eq(1))
        .delete(&**test_db)
        .await
        .unwrap();

    assert_eq!(TestModel::objects().all(&**test_db).await.unwrap(), vec![]);
}

#[cot_macros::dbtest]
async fn model_insert(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    // Insert
    let mut model = TestModel {
        id: Auto::fixed(1),
        name: "test".to_owned(),
    };
    let result = model.insert(&**test_db).await;
    assert!(result.is_ok());

    // Can't insert the same model instance again
    let result = model.insert(&**test_db).await;
    assert!(result.is_err());

    // Read the model from the database
    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 1);
    assert_eq!(objects[0].name, "test");
}

#[cot_macros::dbtest]
async fn model_update(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    // Insert
    let mut model = TestModel {
        id: Auto::fixed(1),
        name: "test".to_owned(),
    };
    let result = model.insert(&**test_db).await;
    assert!(result.is_ok());

    // Update
    model.name = "test2".to_owned();
    let result = model.update(&**test_db).await;
    assert!(result.is_ok());

    // Can't update non-existing object
    let mut model = TestModel {
        id: Auto::fixed(2),
        name: "test3".to_owned(),
    };
    let result = model.update(&**test_db).await;
    assert!(result.is_err());

    // Read the model from the database
    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 1);
    assert_eq!(objects[0].name, "test2");
}

#[cot_macros::dbtest]
async fn model_macro_filtering(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    assert_eq!(TestModel::objects().all(&**test_db).await.unwrap(), vec![]);

    let mut model = TestModel {
        id: Auto::auto(),
        name: "test".to_owned(),
    };
    model.save(&**test_db).await.unwrap();
    let objects = query!(TestModel, $name == "test")
        .all(&**test_db)
        .await
        .unwrap();
    assert_eq!(objects.len(), 1);
    assert_eq!(objects[0].name, "test");

    let objects = query!(TestModel, $name == "t")
        .all(&**test_db)
        .await
        .unwrap();
    assert!(objects.is_empty());
}

async fn migrate_test_model(db: &Database) {
    CREATE_TEST_MODEL.forwards(db).await.unwrap();
}

const CREATE_TEST_MODEL: Operation = Operation::create_model()
    .table_name(Identifier::new("cot__test_model"))
    .fields(&[
        Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
            .primary_key()
            .auto(),
        Field::new(Identifier::new("name"), <String as DatabaseField>::TYPE),
    ])
    .build();

macro_rules! all_fields_migration_field {
    ($name:ident, $ty:ty) => {
        Field::new(
            Identifier::new(concat!("field_", stringify!($name))),
            <$ty as DatabaseField>::TYPE,
        )
        .set_null(<$ty as DatabaseField>::NULLABLE)
    };
    ($ty:ty) => {
        Field::new(
            Identifier::new(concat!("field_", stringify!($ty))),
            <$ty as DatabaseField>::TYPE,
        )
        .set_null(<$ty as DatabaseField>::NULLABLE)
    };
}

#[derive(Debug, PartialEq, Dummy)]
#[model]
struct AllFieldsModel {
    #[dummy(expr = "Auto::auto()")]
    #[model(primary_key)]
    id: Auto<i32>,
    field_bool: bool,
    field_i8: i8,
    field_i16: i16,
    field_i32: i32,
    field_i64: i64,
    field_u8: u8,
    field_u16: u16,
    field_u32: u32,
    // SQLite only allows us to store signed integers, so we're generating numbers that do not
    // exceed i64::MAX
    #[dummy(faker = "0..i64::MAX as u64")]
    field_u64: u64,
    field_f32: f32,
    field_f64: f64,
    field_date: chrono::NaiveDate,
    field_time: chrono::NaiveTime,
    #[dummy(faker = "fake::chrono::Precision::<6>")]
    field_datetime: chrono::NaiveDateTime,
    #[dummy(faker = "fake::chrono::Precision::<6>")]
    field_datetime_timezone: chrono::DateTime<chrono::FixedOffset>,
    field_string: String,
    field_blob: Vec<u8>,
    field_option: Option<String>,
    field_limited_string: LimitedString<10>,
    #[dummy(faker = "WeekdaySetFaker")]
    field_weekday_set: chrono::WeekdaySet,
}

async fn migrate_all_fields_model(db: &Database) {
    CREATE_ALL_FIELDS_MODEL.forwards(db).await.unwrap();
}

const CREATE_ALL_FIELDS_MODEL: Operation = Operation::create_model()
    .table_name(Identifier::new("cot__all_fields_model"))
    .fields(&[
        Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
            .primary_key()
            .auto(),
        all_fields_migration_field!(bool),
        all_fields_migration_field!(i8),
        all_fields_migration_field!(i16),
        all_fields_migration_field!(i32),
        all_fields_migration_field!(i64),
        all_fields_migration_field!(u8),
        all_fields_migration_field!(u16),
        all_fields_migration_field!(u32),
        all_fields_migration_field!(u64),
        all_fields_migration_field!(f32),
        all_fields_migration_field!(f64),
        all_fields_migration_field!(date, chrono::NaiveDate),
        all_fields_migration_field!(time, chrono::NaiveTime),
        all_fields_migration_field!(datetime, chrono::NaiveDateTime),
        all_fields_migration_field!(datetime_timezone, chrono::DateTime<chrono::FixedOffset>),
        all_fields_migration_field!(string, String),
        all_fields_migration_field!(blob, Vec<u8>),
        all_fields_migration_field!(option, Option<String>),
        all_fields_migration_field!(limited_string, LimitedString<10>),
        all_fields_migration_field!(weekday_set, chrono::WeekdaySet),
    ])
    .build();

#[cot_macros::dbtest]
async fn all_fields_model(db: &mut TestDatabase) {
    migrate_all_fields_model(db).await;

    assert_eq!(AllFieldsModel::objects().all(&**db).await.unwrap(), vec![]);

    let r = &mut StdRng::seed_from_u64(123_785);
    let mut models = (0..100)
        .map(|_| Faker.fake_with_rng(r))
        .collect::<Vec<AllFieldsModel>>();
    for model in &mut models {
        model.save(&**db).await.unwrap();
    }

    let mut models_from_db: Vec<_> = AllFieldsModel::objects().all(&**db).await.unwrap();
    normalize_datetimes(&mut models);
    normalize_datetimes(&mut models_from_db);

    assert_eq!(models.len(), models_from_db.len());
    for model in &models {
        assert!(
            models_from_db.contains(model),
            "Could not find model {model:?} in models_from_db: {models_from_db:?}",
        );
    }
}

/// Normalize the datetimes to UTC.
fn normalize_datetimes(data: &mut Vec<AllFieldsModel>) {
    for model in data {
        model.field_datetime_timezone = model.field_datetime_timezone.with_timezone(
            &chrono::FixedOffset::east_opt(0).expect("UTC timezone is always valid"),
        );
    }
}

macro_rules! run_migrations {
    ( $db:ident, $( $operations:ident ),* ) => {
        struct TestMigration;

        impl cot::db::migrations::Migration for TestMigration {
            const APP_NAME: &'static str = "cot";
            const DEPENDENCIES: &'static [cot::db::migrations::MigrationDependency] = &[];
            const MIGRATION_NAME: &'static str = "test_migration";
            const OPERATIONS: &'static [Operation] = &[ $($operations),* ];
        }

        cot::db::migrations::MigrationEngine::new(
            cot::db::migrations::wrap_migrations(&[&TestMigration])
        )
            .unwrap()
            .run(&**$db)
            .await
            .unwrap();
    };
}

#[cot_macros::dbtest]
async fn foreign_keys(db: &mut TestDatabase) {
    #[derive(Debug, Clone, PartialEq)]
    #[model]
    struct Artist {
        #[model(primary_key)]
        id: Auto<i32>,
        name: String,
    }

    #[derive(Debug, Clone, PartialEq)]
    #[model]
    struct Track {
        #[model(primary_key)]
        id: Auto<i32>,
        artist: ForeignKey<Artist>,
        name: String,
    }

    const CREATE_ARTIST: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__artist"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
            Field::new(Identifier::new("name"), <String as DatabaseField>::TYPE),
        ])
        .build();
    const CREATE_TRACK: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__track"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
            Field::new(
                Identifier::new("artist"),
                <ForeignKey<Artist> as DatabaseField>::TYPE,
            )
            .foreign_key(
                <Artist as Model>::TABLE_NAME,
                <Artist as Model>::PRIMARY_KEY_NAME,
                ForeignKeyOnDeletePolicy::Restrict,
                ForeignKeyOnUpdatePolicy::Restrict,
            ),
            Field::new(Identifier::new("name"), <String as DatabaseField>::TYPE),
        ])
        .build();

    run_migrations!(db, CREATE_ARTIST, CREATE_TRACK);

    let mut artist = Artist {
        id: Auto::auto(),
        name: "artist".to_owned(),
    };
    artist.save(&**db).await.unwrap();

    let mut track = Track {
        id: Auto::auto(),
        artist: ForeignKey::from(&artist),
        name: "track".to_owned(),
    };
    track.save(&**db).await.unwrap();

    let mut track = Track::objects().all(&**db).await.unwrap()[0].clone();
    let artist_from_db = track.artist.get(&**db).await.unwrap();
    assert_eq!(artist_from_db, &artist);

    let error = query!(Artist, $id == artist.id)
        .delete(&**db)
        .await
        .unwrap_err();
    // expected foreign key violation
    assert!(matches!(error, DatabaseError::DatabaseEngineError(_)));

    query!(Track, $artist == &artist)
        .delete(&**db)
        .await
        .unwrap();
    query!(Artist, $id == artist.id)
        .delete(&**db)
        .await
        .unwrap();
    // no error should be thrown
}

#[cot_macros::dbtest]
async fn foreign_keys_option(db: &mut TestDatabase) {
    #[derive(Debug, Clone, PartialEq)]
    #[model]
    struct Parent {
        #[model(primary_key)]
        id: Auto<i32>,
    }

    #[derive(Debug, Clone, PartialEq)]
    #[model]
    struct Child {
        #[model(primary_key)]
        id: Auto<i32>,
        parent: Option<ForeignKey<Parent>>,
    }

    const CREATE_PARENT: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__parent"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
        ])
        .build();
    const CREATE_CHILD: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__child"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
            Field::new(
                Identifier::new("parent"),
                <Option<ForeignKey<Parent>> as DatabaseField>::TYPE,
            )
            .set_null(<Option<ForeignKey<Parent>> as DatabaseField>::NULLABLE)
            .foreign_key(
                <Parent as Model>::TABLE_NAME,
                <Parent as Model>::PRIMARY_KEY_NAME,
                ForeignKeyOnDeletePolicy::SetNone,
                ForeignKeyOnUpdatePolicy::SetNone,
            ),
        ])
        .build();

    run_migrations!(db, CREATE_PARENT, CREATE_CHILD);

    // Test child with `None` parent
    let mut child = Child {
        id: Auto::auto(),
        parent: None,
    };
    child.save(&**db).await.unwrap();

    let child = Child::objects().all(&**db).await.unwrap()[0].clone();
    assert_eq!(child.parent, None);

    query!(Child, $id == child.id).delete(&**db).await.unwrap();

    // Test child with `Some` parent
    let mut parent = Parent { id: Auto::auto() };
    parent.save(&**db).await.unwrap();

    let mut child = Child {
        id: Auto::auto(),
        parent: Some(ForeignKey::from(&parent)),
    };
    child.save(&**db).await.unwrap();

    let child = Child::objects().all(&**db).await.unwrap()[0].clone();
    let mut parent_fk = child.parent.unwrap();
    let parent_from_db = parent_fk.get(&**db).await.unwrap();
    assert_eq!(parent_from_db, &parent);

    // Check none policy
    query!(Parent, $id == parent.id)
        .delete(&**db)
        .await
        .unwrap();
    let child = Child::objects().all(&**db).await.unwrap()[0].clone();
    assert_eq!(child.parent, None);
}

#[cot_macros::dbtest]
async fn foreign_keys_cascade(db: &mut TestDatabase) {
    #[derive(Debug, Clone, PartialEq)]
    #[model]
    struct Parent {
        #[model(primary_key)]
        id: Auto<i32>,
    }

    #[derive(Debug, Clone, PartialEq)]
    #[model]
    struct Child {
        #[model(primary_key)]
        id: Auto<i32>,
        parent: Option<ForeignKey<Parent>>,
    }

    const CREATE_PARENT: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__parent"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
        ])
        .build();
    const CREATE_CHILD: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__child"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
            Field::new(
                Identifier::new("parent"),
                <Option<ForeignKey<Parent>> as DatabaseField>::TYPE,
            )
            .set_null(<Option<ForeignKey<Parent>> as DatabaseField>::NULLABLE)
            .foreign_key(
                <Parent as Model>::TABLE_NAME,
                <Parent as Model>::PRIMARY_KEY_NAME,
                ForeignKeyOnDeletePolicy::Cascade,
                ForeignKeyOnUpdatePolicy::Cascade,
            ),
        ])
        .build();

    run_migrations!(db, CREATE_PARENT, CREATE_CHILD);

    // with parent
    let mut parent = Parent { id: Auto::auto() };
    parent.save(&**db).await.unwrap();

    let mut child = Child {
        id: Auto::auto(),
        parent: Some(ForeignKey::from(&parent)),
    };
    child.save(&**db).await.unwrap();

    let child = Child::objects().all(&**db).await.unwrap()[0].clone();
    let mut parent_fk = child.parent.unwrap();
    let parent_from_db = parent_fk.get(&**db).await.unwrap();
    assert_eq!(parent_from_db, &parent);

    // Check cascade policy
    query!(Parent, $id == parent.id)
        .delete(&**db)
        .await
        .unwrap();
    assert!(Child::objects().all(&**db).await.unwrap().is_empty());
}

// Check different types for the primary key
#[derive(Debug, PartialEq)]
#[model]
struct TestModelu32Key {
    #[model(primary_key)]
    id: Auto<u32>,
    name: String,
}

#[derive(Debug, PartialEq)]
#[model]
struct TestModelu64Key {
    #[model(primary_key)]
    id: Auto<u64>,
    name: String,
}

#[derive(Debug, PartialEq)]
#[model]
struct TestModeli64Key {
    #[model(primary_key)]
    id: Auto<i64>,
    name: String,
}

#[derive(Debug, PartialEq)]
#[model]
struct TestModelStringKey {
    #[model(primary_key)]
    id: String,
    name: String,
}

#[cot_macros::dbtest]
#[expect(clippy::too_many_lines)]
async fn weekday_set_field_functionality(db: &mut TestDatabase) {
    use chrono::Weekday;

    #[derive(Debug, PartialEq)]
    #[model]
    struct WeekdaySetModel {
        #[model(primary_key)]
        id: Auto<i32>,
        schedule: chrono::WeekdaySet,
        optional_schedule: Option<chrono::WeekdaySet>,
    }

    const CREATE_WEEKDAY_SET_MODEL: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__weekday_set_model"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
            Field::new(
                Identifier::new("schedule"),
                <chrono::WeekdaySet as DatabaseField>::TYPE,
            ),
            Field::new(
                Identifier::new("optional_schedule"),
                <Option<chrono::WeekdaySet> as DatabaseField>::TYPE,
            )
            .set_null(<Option<chrono::WeekdaySet> as DatabaseField>::NULLABLE),
        ])
        .build();

    run_migrations!(db, CREATE_WEEKDAY_SET_MODEL);

    // Test empty WeekdaySet
    let mut model1 = WeekdaySetModel {
        id: Auto::auto(),
        schedule: chrono::WeekdaySet::EMPTY,
        optional_schedule: None,
    };
    model1.save(&**db).await.unwrap();

    // Test WeekdaySet with all weekdays
    let mut all_days = chrono::WeekdaySet::EMPTY;
    for day in [
        Weekday::Mon,
        Weekday::Tue,
        Weekday::Wed,
        Weekday::Thu,
        Weekday::Fri,
        Weekday::Sat,
        Weekday::Sun,
    ] {
        all_days.insert(day);
    }
    let mut model2 = WeekdaySetModel {
        id: Auto::auto(),
        schedule: all_days,
        optional_schedule: Some(chrono::WeekdaySet::EMPTY),
    };
    model2.save(&**db).await.unwrap();

    // Test WeekdaySet with specific weekdays (weekdays only)
    let mut weekdays_only = chrono::WeekdaySet::EMPTY;
    for day in [
        Weekday::Mon,
        Weekday::Tue,
        Weekday::Wed,
        Weekday::Thu,
        Weekday::Fri,
    ] {
        weekdays_only.insert(day);
    }
    let mut model3 = WeekdaySetModel {
        id: Auto::auto(),
        schedule: weekdays_only,
        optional_schedule: Some(weekdays_only),
    };
    model3.save(&**db).await.unwrap();

    // Test WeekdaySet with weekend only
    let mut weekend_only = chrono::WeekdaySet::EMPTY;
    weekend_only.insert(Weekday::Sat);
    weekend_only.insert(Weekday::Sun);
    let mut model4 = WeekdaySetModel {
        id: Auto::auto(),
        schedule: weekend_only,
        optional_schedule: Some(all_days),
    };
    model4.save(&**db).await.unwrap();

    // Retrieve all models and verify they match
    let models_from_db = WeekdaySetModel::objects().all(&**db).await.unwrap();
    assert_eq!(models_from_db.len(), 4);

    // Find and verify each model
    let db_model1 = models_from_db.iter().find(|m| m.id == model1.id).unwrap();
    assert_eq!(db_model1.schedule, chrono::WeekdaySet::EMPTY);
    assert_eq!(db_model1.optional_schedule, None);

    let db_model2 = models_from_db.iter().find(|m| m.id == model2.id).unwrap();
    assert_eq!(db_model2.schedule, all_days);
    assert_eq!(db_model2.optional_schedule, Some(chrono::WeekdaySet::EMPTY));

    let db_model3 = models_from_db.iter().find(|m| m.id == model3.id).unwrap();
    assert_eq!(db_model3.schedule, weekdays_only);
    assert_eq!(db_model3.optional_schedule, Some(weekdays_only));

    let db_model4 = models_from_db.iter().find(|m| m.id == model4.id).unwrap();
    assert_eq!(db_model4.schedule, weekend_only);
    assert_eq!(db_model4.optional_schedule, Some(all_days));

    // Test querying by WeekdaySet
    let weekend_models = query!(WeekdaySetModel, $schedule == weekend_only)
        .all(&**db)
        .await
        .unwrap();
    assert_eq!(weekend_models.len(), 1);
    assert_eq!(weekend_models[0].id, model4.id);

    // Test updating WeekdaySet
    let mut model_to_update = models_from_db
        .into_iter()
        .find(|m| m.id == model1.id)
        .unwrap();
    model_to_update.schedule = weekdays_only;
    model_to_update.optional_schedule = Some(weekend_only);
    model_to_update.save(&**db).await.unwrap();

    let updated_model = WeekdaySetModel::get_by_primary_key(&**db, model_to_update.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(updated_model.schedule, weekdays_only);
    assert_eq!(updated_model.optional_schedule, Some(weekend_only));
}

#[cot_macros::dbtest]
async fn bulk_insert_basic(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    let mut models = vec![
        TestModel {
            id: Auto::auto(),
            name: "test1".to_owned(),
        },
        TestModel {
            id: Auto::auto(),
            name: "test2".to_owned(),
        },
        TestModel {
            id: Auto::auto(),
            name: "test3".to_owned(),
        },
    ];

    TestModel::bulk_insert(&**test_db, &mut models)
        .await
        .unwrap();

    assert!(matches!(models[0].id, Auto::Fixed(_)));
    assert!(matches!(models[1].id, Auto::Fixed(_)));
    assert!(matches!(models[2].id, Auto::Fixed(_)));

    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 3);

    let names: Vec<_> = objects.iter().map(|m| m.name.as_str()).collect();
    assert!(names.contains(&"test1"));
    assert!(names.contains(&"test2"));
    assert!(names.contains(&"test3"));

    // Verify IDs match between models and database
    for model in &models {
        if let Auto::Fixed(_) = model.id {
            let db_model = TestModel::get_by_primary_key(&**test_db, model.id)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(db_model.name, model.name);
        }
    }
}

#[cot_macros::dbtest]
async fn bulk_insert_or_update(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    let mut models = vec![
        TestModel {
            id: Auto::auto(),
            name: "test1".to_owned(),
        },
        TestModel {
            id: Auto::auto(),
            name: "test2".to_owned(),
        },
        TestModel {
            id: Auto::auto(),
            name: "test3".to_owned(),
        },
    ];
    TestModel::bulk_insert(&**test_db, &mut models)
        .await
        .unwrap();

    let mut models = vec![
        TestModel {
            id: models[0].id,
            name: "test1_updated".to_owned(),
        },
        TestModel {
            id: models[2].id,
            name: "test3_updated".to_owned(),
        },
    ];
    TestModel::bulk_insert_or_update(&**test_db, &mut models)
        .await
        .unwrap();

    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 3);

    let names: Vec<_> = objects.iter().map(|m| m.name.as_str()).collect();
    assert!(names.contains(&"test1_updated"));
    assert!(names.contains(&"test2"));
    assert!(names.contains(&"test3_updated"));
}

#[cot_macros::dbtest]
async fn bulk_insert_empty(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    let mut models: Vec<TestModel> = vec![];
    let result = TestModel::bulk_insert(&**test_db, &mut models).await;

    assert!(result.is_ok());
    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), 0);
}

#[cot_macros::dbtest]
async fn bulk_insert_large_batch(test_db: &mut TestDatabase) {
    const BATCH_SIZE: usize = 100_000;

    migrate_test_model(&*test_db).await;

    let mut models: Vec<TestModel> = (0..BATCH_SIZE)
        .map(|i| TestModel {
            id: Auto::auto(),
            name: format!("test{i}"),
        })
        .collect();

    TestModel::bulk_insert(&**test_db, &mut models)
        .await
        .unwrap();

    for model in &models {
        assert!(matches!(model.id, Auto::Fixed(_)));
    }

    let objects = TestModel::objects().all(&**test_db).await.unwrap();
    assert_eq!(objects.len(), BATCH_SIZE);
}

#[cot_macros::dbtest]
async fn bulk_insert_no_values(test_db: &mut TestDatabase) {
    #[derive(Debug, PartialEq)]
    #[model]
    struct PkOnlyModel {
        #[model(primary_key)]
        id: Auto<i32>,
    }

    const CREATE_PK_ONLY_MODEL: Operation = Operation::create_model()
        .table_name(Identifier::new("cot__pk_only_model"))
        .fields(&[
            Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
                .primary_key()
                .auto(),
        ])
        .build();

    async fn migrate_pk_only_model(db: &Database) {
        CREATE_PK_ONLY_MODEL.forwards(db).await.unwrap();
    }

    const BATCH_SIZE: usize = 17;

    migrate_pk_only_model(&*test_db).await;

    let mut models: Vec<PkOnlyModel> = (0..BATCH_SIZE)
        .map(|_| PkOnlyModel { id: Auto::auto() })
        .collect();

    let result = PkOnlyModel::bulk_insert(&**test_db, &mut models).await;

    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        DatabaseError::BulkInsertNoValueColumns
    ));
}

#[cot_macros::dbtest]
async fn bulk_insert_with_fixed_pk(test_db: &mut TestDatabase) {
    migrate_test_model(&*test_db).await;

    let mut models = vec![
        TestModel {
            id: Auto::fixed(100),
            name: "test100".to_owned(),
        },
        TestModel {
            id: Auto::fixed(200),
            name: "test200".to_owned(),
        },
        TestModel {
            id: Auto::fixed(300),
            name: "test300".to_owned(),
        },
    ];

    TestModel::bulk_insert(&**test_db, &mut models)
        .await
        .unwrap();

    let model100 = TestModel::get_by_primary_key(&**test_db, Auto::fixed(100))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(model100.name, "test100");

    let model200 = TestModel::get_by_primary_key(&**test_db, Auto::fixed(200))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(model200.name, "test200");

    let model300 = TestModel::get_by_primary_key(&**test_db, Auto::fixed(300))
        .await
        .unwrap()
        .unwrap();
    assert_eq!(model300.name, "test300");
}