umbral-core 0.0.3

umbral internals: ORM, migrations, routing, DB backends, the Plugin trait. Do not depend on this directly; use the `umbral` facade.
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
//! Coverage for Phase 2 of the Postgres rollout: backend-aware DDL
//! rendering. Verifies that `migrate::render_operation_for(op, "postgres")`
//! emits the right Postgres-dialect SQL without needing a live PG
//! server.
//!
//! The dispatch function is the public seam: `render_operation` (the
//! ambient version that reads `crate::backend::active()`) is the
//! production entry point, but `render_operation_for` lets us pin the
//! dialect explicitly. The two share the same per-backend helpers so
//! pinning the explicit form is the contract.
//!
//! No `App::build()` boot, no `OnceLock` writes, no live database —
//! these tests are pure functions over `Operation` values.

use umbral::migrate::{Column, Operation, render_operation_for};
use umbral::orm::SqlType;

/// One column descriptor — a `BigInt` primary key, the
/// `id: i64` shape every umbral model carries.
fn id_pk() -> Column {
    Column {
        name: "id".to_string(),
        ty: SqlType::BigInt,
        primary_key: true,
        nullable: false,
        fk_target: None,
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: None,
        max: None,
        text_format: ::core::option::Option::None,
        slug_from: ::core::option::Option::None,
    }
}

/// A non-nullable text column with the given name.
fn text_not_null(name: &str) -> Column {
    Column {
        name: name.to_string(),
        ty: SqlType::Text,
        primary_key: false,
        nullable: false,
        fk_target: None,
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: None,
        max: None,
        text_format: ::core::option::Option::None,
        slug_from: ::core::option::Option::None,
    }
}

/// A nullable text column with the given name.
fn text_nullable(name: &str) -> Column {
    Column {
        name: name.to_string(),
        ty: SqlType::Text,
        primary_key: false,
        nullable: true,
        fk_target: None,
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: None,
        max: None,
        text_format: ::core::option::Option::None,
        slug_from: ::core::option::Option::None,
    }
}

// --------------------------------------------------------------------- //
// CreateTable                                                            //
// --------------------------------------------------------------------- //

/// Postgres `CreateTable` with a BigInt PK should render `bigserial`
/// (sea-query lowers `BigInteger + auto_increment` to `bigserial` on
/// Postgres). The SQLite quirk (forcing `INTEGER` and attaching
/// `AUTOINCREMENT`) does NOT apply — Postgres has native identity
/// columns and respects the declared width.
#[test]
fn create_table_bigint_pk_renders_bigserial_on_postgres() {
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![id_pk(), text_not_null("title")],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(
        stmts.len(),
        1,
        "CreateTable should render to one statement; got {stmts:?}"
    );
    let sql = &stmts[0];
    let lower = sql.to_ascii_lowercase();

    // The Postgres-shaped identity column for an i64 PK is bigserial.
    // The integer-PRIMARY-KEY-AUTOINCREMENT trick is SQLite-only.
    assert!(
        lower.contains("bigserial"),
        "expected `bigserial` for BigInt PK on postgres; got {sql}",
    );
    assert!(
        !lower.contains("autoincrement"),
        "AUTOINCREMENT is a SQLite-only quirk; got {sql}",
    );

    // Postgres-builder identifiers are double-quoted (vs SQLite's
    // backticks-or-double-quotes choice).
    assert!(
        sql.contains("\"post\""),
        "table identifier should be double-quoted on postgres; got {sql}",
    );
    assert!(
        sql.contains("\"id\""),
        "column identifier should be double-quoted on postgres; got {sql}",
    );
    assert!(
        sql.contains("\"title\""),
        "title column should be double-quoted on postgres; got {sql}",
    );
}

/// The SQLite path keeps its INTEGER-PRIMARY-KEY-AUTOINCREMENT quirk
/// even for a BigInt PK. Pinning the contrast so the Postgres change
/// doesn't quietly regress SQLite behaviour.
#[test]
fn create_table_bigint_pk_renders_integer_autoincrement_on_sqlite() {
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![id_pk(), text_not_null("title")],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };

    let stmts = render_operation_for(&op, "sqlite");
    let sql = &stmts[0];
    let lower = sql.to_ascii_lowercase();

    assert!(
        lower.contains("autoincrement"),
        "SQLite path keeps the INTEGER PK + AUTOINCREMENT quirk; got {sql}",
    );
    assert!(
        !lower.contains("bigserial"),
        "BIGSERIAL is Postgres-only; got {sql}",
    );
}

// --------------------------------------------------------------------- //
// AlterColumn                                                            //
// --------------------------------------------------------------------- //

/// Flipping a column to nullable on Postgres should emit one native
/// `ALTER TABLE ... ALTER COLUMN ... DROP NOT NULL`, NOT the SQLite
/// four-step table-recreation dance.
#[test]
fn alter_column_to_nullable_uses_native_alter_on_postgres() {
    let op = Operation::AlterColumn {
        table: "post".to_string(),
        column: "title".to_string(),
        new_columns: vec![id_pk(), text_nullable("title")],
        prev_columns: None,
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(
        stmts.len(),
        1,
        "native ALTER is one statement, not the four-step SQLite dance; got {stmts:?}",
    );
    let sql = &stmts[0];
    let upper = sql.to_ascii_uppercase();
    assert!(
        upper.contains("ALTER TABLE"),
        "expected ALTER TABLE on postgres; got {sql}",
    );
    assert!(
        upper.contains("DROP NOT NULL"),
        "nullable=true should emit DROP NOT NULL; got {sql}",
    );
    assert!(
        sql.contains("\"post\""),
        "table identifier double-quoted; got {sql}",
    );
    assert!(
        sql.contains("\"title\""),
        "column identifier double-quoted; got {sql}",
    );
}

/// Flipping a column to non-nullable on Postgres emits `SET NOT NULL`.
#[test]
fn alter_column_to_not_null_uses_set_not_null_on_postgres() {
    let op = Operation::AlterColumn {
        table: "post".to_string(),
        column: "title".to_string(),
        new_columns: vec![id_pk(), text_not_null("title")],
        prev_columns: None,
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(stmts.len(), 1);
    let sql = &stmts[0];
    let upper = sql.to_ascii_uppercase();
    assert!(
        upper.contains("SET NOT NULL"),
        "nullable=false should emit SET NOT NULL; got {sql}",
    );
    assert!(
        !upper.contains("DROP NOT NULL"),
        "should not emit DROP NOT NULL when flipping to non-null; got {sql}",
    );
}

/// The SQLite path keeps the four-step table-recreation dance for
/// nullable flips. Pinning the contrast so the Postgres change
/// doesn't quietly regress SQLite behaviour.
#[test]
fn alter_column_keeps_recreation_dance_on_sqlite() {
    let op = Operation::AlterColumn {
        table: "post".to_string(),
        column: "title".to_string(),
        new_columns: vec![id_pk(), text_nullable("title")],
        prev_columns: None,
    };

    let stmts = render_operation_for(&op, "sqlite");
    assert_eq!(
        stmts.len(),
        4,
        "SQLite dance is CREATE + INSERT...SELECT + DROP + RENAME; got {stmts:?}",
    );
    let upper_join = stmts.join("\n").to_ascii_uppercase();
    assert!(upper_join.contains("CREATE TABLE"));
    assert!(upper_join.contains("INSERT INTO"));
    assert!(upper_join.contains("DROP TABLE"));
    assert!(upper_join.contains("RENAME"));
}

// --------------------------------------------------------------------- //
// DropTable / AddColumn / DropColumn                                     //
// --------------------------------------------------------------------- //

/// DropTable renders identical-shape SQL on both backends; the only
/// observable difference is identifier quoting. The Postgres builder
/// uses double quotes consistently.
#[test]
fn drop_table_on_postgres_double_quotes_identifier() {
    let op = Operation::DropTable {
        table: "post".to_string(),
    };

    let stmts = render_operation_for(&op, "postgres");
    let sql = &stmts[0];
    let upper = sql.to_ascii_uppercase();
    assert!(upper.contains("DROP TABLE"));
    assert!(sql.contains("\"post\""), "got {sql}");
}

/// AddColumn on Postgres emits ALTER TABLE ADD COLUMN with the
/// Postgres native type mapping (`text` for SqlType::Text).
#[test]
fn add_column_on_postgres_uses_pg_type_mapping() {
    let op = Operation::AddColumn {
        table: "post".to_string(),
        column: text_not_null("body"),
    };

    let stmts = render_operation_for(&op, "postgres");
    let sql = &stmts[0];
    let upper = sql.to_ascii_uppercase();
    assert!(upper.contains("ALTER TABLE"));
    assert!(upper.contains("ADD COLUMN"));
    // The Postgres mapping for SqlType::Text is `text`.
    assert!(
        sql.to_ascii_lowercase().contains("text"),
        "Postgres Text should render as `text`; got {sql}",
    );
    assert!(sql.contains("\"body\""), "got {sql}");
}

/// DropColumn on Postgres emits ALTER TABLE DROP COLUMN with a
/// double-quoted identifier.
#[test]
fn drop_column_on_postgres_double_quotes_identifier() {
    let op = Operation::DropColumn {
        table: "post".to_string(),
        column: "body".to_string(),
    };

    let stmts = render_operation_for(&op, "postgres");
    let sql = &stmts[0];
    let upper = sql.to_ascii_uppercase();
    assert!(upper.contains("ALTER TABLE"));
    assert!(upper.contains("DROP COLUMN"));
    assert!(sql.contains("\"body\""), "got {sql}");
}

// --------------------------------------------------------------------- //
// Safe-cast support (gap #64)                                            //
// --------------------------------------------------------------------- //

/// Helper: build a non-nullable column of a given type.
fn col(name: &str, ty: SqlType) -> Column {
    Column {
        name: name.to_string(),
        ty,
        primary_key: false,
        nullable: false,
        fk_target: None,
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: None,
        max: None,
        text_format: ::core::option::Option::None,
        slug_from: ::core::option::Option::None,
    }
}

/// BigInt → Text on Postgres emits an `ALTER COLUMN ... TYPE TEXT
/// USING <col>::text`. This is the canonical case from gap #64
/// (Session.user_id flipping to polymorphic Text storage).
#[test]
fn safe_cast_bigint_to_text_emits_using_on_postgres() {
    let op = Operation::AlterColumn {
        table: "session".to_string(),
        column: "user_id".to_string(),
        new_columns: vec![id_pk(), col("user_id", SqlType::Text)],
        prev_columns: Some(vec![id_pk(), col("user_id", SqlType::BigInt)]),
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(
        stmts.len(),
        1,
        "type-only change should emit one ALTER (no nullable flip); got {stmts:?}",
    );
    let sql = &stmts[0];
    assert!(sql.contains("TYPE text"), "expected TYPE text; got {sql}");
    assert!(
        sql.contains("USING \"user_id\"::text"),
        "expected USING <col>::text cast; got {sql}",
    );
    assert!(
        sql.contains("\"session\""),
        "table identifier double-quoted; got {sql}",
    );
}

/// Integer widening also flows through the safe-cast path.
#[test]
fn safe_cast_smallint_to_integer_emits_using_on_postgres() {
    let op = Operation::AlterColumn {
        table: "thing".to_string(),
        column: "count".to_string(),
        new_columns: vec![id_pk(), col("count", SqlType::Integer)],
        prev_columns: Some(vec![id_pk(), col("count", SqlType::SmallInt)]),
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(stmts.len(), 1);
    let sql = &stmts[0];
    assert!(
        sql.contains("TYPE integer"),
        "expected TYPE integer; got {sql}",
    );
    assert!(
        sql.contains("USING \"count\"::integer"),
        "expected USING cast; got {sql}",
    );
}

/// A combined type + nullable flip emits BOTH statements in order
/// (TYPE first so the NOT NULL flip evaluates against the new type).
#[test]
fn safe_cast_with_nullable_flip_emits_two_statements_in_order() {
    let mut prev = col("user_id", SqlType::BigInt);
    prev.nullable = false;
    let mut next = col("user_id", SqlType::Text);
    next.nullable = true;

    let op = Operation::AlterColumn {
        table: "session".to_string(),
        column: "user_id".to_string(),
        new_columns: vec![id_pk(), next],
        prev_columns: Some(vec![id_pk(), prev]),
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(stmts.len(), 2, "expected TYPE + nullable; got {stmts:?}");
    assert!(stmts[0].contains("TYPE text"), "TYPE first; got {stmts:?}");
    assert!(
        stmts[1].contains("DROP NOT NULL"),
        "nullable change second; got {stmts:?}",
    );
}

/// Without a previous snapshot the renderer falls back to the legacy
/// nullable-only path (the migration was produced before the safe-cast
/// machinery shipped, so we can't tell what changed and emit just the
/// nullable flip).
#[test]
fn missing_prev_columns_keeps_legacy_nullable_only_behaviour() {
    let op = Operation::AlterColumn {
        table: "post".to_string(),
        column: "title".to_string(),
        new_columns: vec![id_pk(), text_nullable("title")],
        prev_columns: None,
    };

    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(stmts.len(), 1);
    assert!(stmts[0].contains("DROP NOT NULL"));
    assert!(
        !stmts[0].contains("TYPE"),
        "no prev means no TYPE inference; got {stmts:?}",
    );
}

// --------------------------------------------------------------------- //
// Dispatch guards                                                        //
// --------------------------------------------------------------------- //

/// `render_operation_for` panics on an unknown backend name with a
/// clear hint about the two shipped dialects. Phase 2 explicitly only
/// covers sqlite + postgres.
#[test]
#[should_panic(expected = "no DDL renderer for backend `mysql`")]
fn render_operation_for_unknown_backend_panics() {
    let op = Operation::DropTable {
        table: "x".to_string(),
    };
    let _ = render_operation_for(&op, "mysql");
}

// --------------------------------------------------------------------- //
// IMP-3: `#[umbral(min = N)]` / `#[umbral(max = N)]` CHECK constraints      //
// --------------------------------------------------------------------- //

/// An integer column with min/max bounds renders a CHECK clause that
/// quotes the column name and combines both bounds with AND.
#[test]
fn create_table_int_with_min_max_emits_check_on_postgres() {
    let mut age = Column {
        name: "age".to_string(),
        ty: SqlType::Integer,
        primary_key: false,
        nullable: false,
        fk_target: None,
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: Some(0),
        max: Some(150),
        text_format: ::core::option::Option::None,
        slug_from: ::core::option::Option::None,
    };
    let op = Operation::CreateTable {
        table: "person".to_string(),
        columns: vec![id_pk(), age.clone()],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };
    let stmts = render_operation_for(&op, "postgres");
    let sql = &stmts[0];
    assert!(
        sql.contains("CHECK (\"age\" >= 0 AND \"age\" <= 150)"),
        "expected combined min+max CHECK; got {sql}",
    );

    // SQLite emits the same CHECK; both dialects accept the syntax.
    let op2 = Operation::CreateTable {
        table: "person".to_string(),
        columns: vec![id_pk(), age.clone()],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };
    let sqlite_sql = &render_operation_for(&op2, "sqlite")[0];
    assert!(
        sqlite_sql.contains("CHECK (\"age\" >= 0 AND \"age\" <= 150)"),
        "expected the same CHECK on SQLite; got {sqlite_sql}",
    );

    // Min-only is just `>=`.
    age.max = None;
    let op3 = Operation::CreateTable {
        table: "person".to_string(),
        columns: vec![id_pk(), age.clone()],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };
    let pg_min_only = &render_operation_for(&op3, "postgres")[0];
    assert!(
        pg_min_only.contains("CHECK (\"age\" >= 0)") && !pg_min_only.contains("<="),
        "min-only should drop the upper bound; got {pg_min_only}",
    );
}

// --------------------------------------------------------------------- //
// BUG-6/7: `unique_together` + `indexes` struct-level attributes          //
// --------------------------------------------------------------------- //

/// A `CreateTable` carrying a `unique_together` group emits an inline
/// `UNIQUE (col, col)` clause on both backends. Two groups → two
/// clauses.
#[test]
fn create_table_emits_unique_together_clauses() {
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![id_pk(), text_not_null("tenant_id"), text_not_null("slug")],
        unique_together: vec![vec!["tenant_id".to_string(), "slug".to_string()]],
        indexes: Vec::new(),
    };
    let sql_pg = &render_operation_for(&op, "postgres")[0];
    let sql_lite = &render_operation_for(
        &Operation::CreateTable {
            table: "post".to_string(),
            columns: vec![id_pk(), text_not_null("tenant_id"), text_not_null("slug")],
            unique_together: vec![vec!["tenant_id".to_string(), "slug".to_string()]],
            indexes: Vec::new(),
        },
        "sqlite",
    )[0]
    .clone();
    assert!(
        sql_pg.to_ascii_uppercase().contains("UNIQUE")
            && sql_pg.contains("\"tenant_id\"")
            && sql_pg.contains("\"slug\""),
        "expected composite UNIQUE on postgres; got {sql_pg}",
    );
    assert!(
        sql_lite.to_ascii_uppercase().contains("UNIQUE")
            && sql_lite.contains("tenant_id")
            && sql_lite.contains("slug"),
        "expected composite UNIQUE on sqlite; got {sql_lite}",
    );
}

/// A `CreateTable` with an `indexes` group emits a follow-up
/// `CREATE INDEX IF NOT EXISTS` statement after the table, with a
/// deterministic `idx_<table>_<col1>_<col2>` name.
#[test]
fn create_table_emits_multi_column_index_after_table() {
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![
            id_pk(),
            text_not_null("tenant_id"),
            text_not_null("created_at"),
        ],
        unique_together: Vec::new(),
        indexes: vec![vec!["tenant_id".to_string(), "created_at".to_string()]],
    };
    let stmts = render_operation_for(&op, "postgres");
    assert_eq!(
        stmts.len(),
        2,
        "expected CREATE TABLE + CREATE INDEX = 2 stmts; got {stmts:?}",
    );
    let idx = &stmts[1];
    assert!(
        idx.contains("CREATE INDEX IF NOT EXISTS")
            && idx.contains("\"idx_post_tenant_id_created_at\"")
            && idx.contains("\"tenant_id\"")
            && idx.contains("\"created_at\""),
        "expected multi-col index DDL; got {idx}",
    );
}

/// Non-numeric column types skip the CHECK even when bounds are set.
/// Min/max on a TEXT column is nonsensical (lexicographic comparison)
/// so the renderer treats them as a no-op rather than a footgun.
#[test]
fn min_max_skipped_for_non_numeric_columns() {
    let mut title = text_not_null("title");
    title.min = Some(1);
    title.max = Some(100);
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![id_pk(), title],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };
    let sql = &render_operation_for(&op, "postgres")[0];
    assert!(
        !sql.contains("CHECK"),
        "min/max on TEXT must not emit a CHECK clause; got {sql}",
    );
}

// --------------------------------------------------------------------- //
// Auto-index emission for FK columns + soft-delete (deleted_at)         //
// --------------------------------------------------------------------- //

/// Helper: build a ForeignKey column pointing at a named table.
fn fk_col(name: &str, target_table: &str) -> Column {
    Column {
        name: name.to_string(),
        ty: SqlType::ForeignKey,
        primary_key: false,
        nullable: false,
        fk_target: Some(target_table.to_string()),
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: None,
        max: None,
        text_format: None,
        slug_from: None,
    }
}

/// Helper: build a nullable Timestamptz column named `deleted_at` (the
/// soft-delete sentinel column). Every soft-delete model carries this
/// in its FIELDS; the migration engine should auto-index it so
/// `WHERE deleted_at IS NULL` never does a full-table scan.
fn deleted_at_col() -> Column {
    Column {
        name: "deleted_at".to_string(),
        ty: SqlType::Timestamptz,
        primary_key: false,
        nullable: true,
        fk_target: None,
        noform: false,
        db_constraint: true,
        noedit: false,
        is_string_repr: false,
        max_length: 0,
        choices: Vec::new(),
        choice_labels: Vec::new(),
        default: String::new(),
        is_multichoice: false,
        unique: false,
        on_delete: umbral_core::orm::FkAction::NoAction,
        on_update: umbral_core::orm::FkAction::NoAction,
        index: false,
        auto_now_add: false,
        auto_now: false,
        help: String::new(),
        example: String::new(),
        widget: None,
        supported_backends: Vec::new(),
        min: None,
        max: None,
        text_format: None,
        slug_from: None,
    }
}

/// A `CreateTable` with a FK column auto-emits a `CREATE INDEX` on that
/// column on both backends. FK columns are always indexed so reverse
/// lookups and `select_related` joins never do full-table scans.
///
/// The index name follows the `idx_<table>_<col>` convention and the
/// statement uses `IF NOT EXISTS` so re-applying an already-applied
/// migration is idempotent.
#[test]
fn test_fk_column_gets_index() {
    let op = Operation::CreateTable {
        table: "comment".to_string(),
        columns: vec![id_pk(), fk_col("post_id", "post"), text_not_null("body")],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };

    for backend in ["postgres", "sqlite"] {
        let stmts = render_operation_for(&op, backend);
        // Must be CREATE TABLE + CREATE INDEX (at least 2 statements).
        assert!(
            stmts.len() >= 2,
            "{backend}: expected CREATE TABLE + CREATE INDEX; got {stmts:?}",
        );
        let joined = stmts.join("\n");
        assert!(
            joined.contains("CREATE INDEX IF NOT EXISTS"),
            "{backend}: missing CREATE INDEX IF NOT EXISTS; got {joined}",
        );
        assert!(
            joined.contains("idx_comment_post_id"),
            "{backend}: expected index name `idx_comment_post_id`; got {joined}",
        );
        assert!(
            joined.contains("\"post_id\"") || joined.contains("`post_id`"),
            "{backend}: index should reference the post_id column; got {joined}",
        );
    }
}

/// A `CreateTable` for a soft-delete model (carrying a `deleted_at`
/// column) auto-emits a `CREATE INDEX` on `deleted_at` so the default
/// `WHERE deleted_at IS NULL` filter in every QuerySet terminal never
/// scans the full table.
#[test]
fn test_soft_delete_column_gets_index() {
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![id_pk(), text_not_null("title"), deleted_at_col()],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };

    for backend in ["postgres", "sqlite"] {
        let stmts = render_operation_for(&op, backend);
        assert!(
            stmts.len() >= 2,
            "{backend}: expected CREATE TABLE + CREATE INDEX on deleted_at; got {stmts:?}",
        );
        let joined = stmts.join("\n");
        assert!(
            joined.contains("idx_post_deleted_at"),
            "{backend}: expected index name `idx_post_deleted_at`; got {joined}",
        );
    }
}

/// Plain string / integer columns do NOT receive a spurious index.
/// Only FK columns, explicit `#[umbral(index)]` columns, and `deleted_at`
/// should trigger auto-index emission; `title` and `view_count` must not.
#[test]
fn test_plain_column_no_index() {
    let mut view_count = col("view_count", SqlType::Integer);
    view_count.nullable = true;
    let op = Operation::CreateTable {
        table: "post".to_string(),
        columns: vec![id_pk(), text_not_null("title"), view_count],
        unique_together: Vec::new(),
        indexes: Vec::new(),
    };

    for backend in ["postgres", "sqlite"] {
        let stmts = render_operation_for(&op, backend);
        assert_eq!(
            stmts.len(),
            1,
            "{backend}: plain columns must not emit a spurious CREATE INDEX; got {stmts:?}",
        );
        assert!(
            !stmts[0].contains("CREATE INDEX"),
            "{backend}: unexpected CREATE INDEX for plain columns; got {stmts:?}",
        );
    }
}