seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
use serde::{Deserialize, Serialize};

use crate::schema::types::{Column, DataType, DatabaseSchema};

/// Result of schema drift detection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DriftReport {
    pub has_drift: bool,
    pub new_tables: Vec<String>,
    pub removed_tables: Vec<String>,
    pub new_columns: Vec<ColumnRef>,
    pub removed_columns: Vec<ColumnRef>,
    pub changed_columns: Vec<ColumnChange>,
}

impl DriftReport {
    /// Human-readable summary for terminal output.
    pub fn summary(&self) -> String {
        if !self.has_drift {
            return "No schema drift detected.".to_string();
        }

        let mut lines = vec!["Schema drift detected:".to_string()];

        for t in &self.new_tables {
            lines.push(format!("  + table: {}", t));
        }
        for t in &self.removed_tables {
            lines.push(format!("  - table: {}", t));
        }
        for c in &self.new_columns {
            lines.push(format!("  + column: {}.{}", c.table, c.column));
        }
        for c in &self.removed_columns {
            lines.push(format!("  - column: {}.{}", c.table, c.column));
        }
        for c in &self.changed_columns {
            if c.table.is_empty() {
                // Database-level change (enum type, schema metadata)
                lines.push(format!("  ~ {} ({})", c.change_type, c.details));
            } else if c.column.is_empty() {
                // Table-level constraint change (FK, unique, check)
                lines.push(format!(
                    "  ~ {}: {} ({})",
                    c.table, c.change_type, c.details
                ));
            } else {
                lines.push(format!(
                    "  ~ {}.{}: {} ({})",
                    c.table, c.column, c.change_type, c.details
                ));
            }
        }

        lines.join("\n")
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnRef {
    pub table: String,
    pub column: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnChange {
    pub table: String,
    pub column: String,
    pub change_type: String,
    pub details: String,
}

/// Compute the schema hash for drift detection.
///
/// Deep-sorts all non-deterministic arrays (foreign keys, unique constraints,
/// check constraints) before serializing, so the hash is stable regardless
/// of the order the database returns them. SQL databases do not guarantee
/// row order without an explicit `ORDER BY`, so two introspections of the
/// same schema can return constraints in different orders.
pub fn compute_schema_hash(schema: &DatabaseSchema) -> String {
    use sha2::{Digest, Sha256};
    let normalized = normalize_for_hash(schema);
    let serialized = serde_json::to_string(&normalized).unwrap_or_default();
    let mut hasher = Sha256::new();
    hasher.update(serialized.as_bytes());
    format!("{:x}", hasher.finalize())
}

/// Clone the schema and sort all non-deterministic arrays so that
/// serialization is order-independent.
fn normalize_for_hash(schema: &DatabaseSchema) -> DatabaseSchema {
    let mut normalized = schema.clone();

    for table in normalized.tables.values_mut() {
        // Old PostgreSQL snapshots used None for their implicit public schema.
        if normalized.database_type == crate::schema::types::DatabaseType::PostgreSQL
            && table.schema_name.as_deref() == Some("public")
        {
            table.schema_name = None;
        }
        // Sort foreign keys by source columns (deterministic key)
        table.foreign_keys.sort_by(|a, b| {
            a.source_columns
                .cmp(&b.source_columns)
                .then_with(|| a.referenced_schema.cmp(&b.referenced_schema))
                .then_with(|| a.referenced_table.cmp(&b.referenced_table))
        });

        // Sort unique constraints by column list
        table
            .unique_constraints
            .sort_by(|a, b| a.columns.cmp(&b.columns));

        // Sort check constraints by expression (the stable identifier)
        table
            .check_constraints
            .sort_by(|a, b| a.expression.cmp(&b.expression));
    }

    normalized
}

/// Compare the lock file's stored schema snapshot against the current live schema.
///
/// Uses a fast-path hash comparison first: if the hashes match, returns
/// immediately with no drift. When they differ, delegates to
/// `check_drift_detailed` to produce an actionable column-level diff.
///
/// The lock file stores the full `DatabaseSchema` snapshot (like
/// `package-lock.json` stores the full dependency tree), so this always
/// produces detailed reports — never a bare "hash changed" boolean.
pub fn check_drift(
    schema_snapshot: &DatabaseSchema,
    schema_hash: &str,
    current_schema: &DatabaseSchema,
) -> DriftReport {
    let current_hash = compute_schema_hash(current_schema);

    // Fast path: if hashes match, no drift.
    if current_hash == schema_hash {
        return DriftReport {
            has_drift: false,
            new_tables: Vec::new(),
            removed_tables: Vec::new(),
            new_columns: Vec::new(),
            removed_columns: Vec::new(),
            changed_columns: Vec::new(),
        };
    }

    let mut report = check_drift_detailed(schema_snapshot, current_schema);
    if !report.has_drift {
        // `generate --from-lock` rejects every hash mismatch, so report one
        // even when the difference is outside the itemized properties.
        report.has_drift = true;
        report.changed_columns.push(ColumnChange {
            table: String::new(),
            column: String::new(),
            change_type: "schema_changed".to_string(),
            details: "the schema hash differs from seedkit.lock (for example a constraint \
                      name, foreign key action, or column order)"
                .to_string(),
        });
    }
    report
}

/// Declared column type with its length or numeric precision, e.g. `varchar(10)`.
fn column_type(column: &Column) -> String {
    let base = column.data_type.to_string();
    match (
        column.max_length,
        column.numeric_precision,
        column.numeric_scale,
    ) {
        (Some(length), _, _) => format!("{base}({length})"),
        (None, Some(precision), Some(scale)) if column.data_type == DataType::Numeric => {
            format!("{base}({precision},{scale})")
        }
        _ => base,
    }
}

fn labels(values: Option<&[String]>) -> String {
    values.map_or("(none)".to_owned(), |v| format!("[{}]", v.join(", ")))
}

/// Detailed drift detection comparing two schema snapshots.
///
/// The `old` schema is the one captured when the lock file was created.
/// The `current` schema is the live database. This produces a full
/// column-level diff.
pub fn check_drift_detailed(old: &DatabaseSchema, current: &DatabaseSchema) -> DriftReport {
    let mut new_tables = Vec::new();
    let mut removed_tables = Vec::new();
    let mut new_columns = Vec::new();
    let mut removed_columns = Vec::new();
    let mut changed_columns = Vec::new();

    // Find new tables (in current but not in old)
    for table_name in current.tables.keys() {
        if !old.tables.contains_key(table_name) {
            new_tables.push(table_name.clone());
        }
    }

    // Find removed tables (in old but not in current)
    for table_name in old.tables.keys() {
        if !current.tables.contains_key(table_name) {
            removed_tables.push(table_name.clone());
        }
    }

    // Compare columns in tables that exist in both schemas
    for (table_name, current_table) in &current.tables {
        let old_table = match old.tables.get(table_name) {
            Some(t) => t,
            None => continue, // Already captured as new_tables
        };

        // New columns
        for col_name in current_table.columns.keys() {
            if !old_table.columns.contains_key(col_name) {
                new_columns.push(ColumnRef {
                    table: table_name.clone(),
                    column: col_name.clone(),
                });
            }
        }

        // Removed columns
        for col_name in old_table.columns.keys() {
            if !current_table.columns.contains_key(col_name) {
                removed_columns.push(ColumnRef {
                    table: table_name.clone(),
                    column: col_name.clone(),
                });
            }
        }

        // Changed columns (type, identity, defaults, enum labels, nullability)
        for (col_name, current_col) in &current_table.columns {
            if let Some(old_col) = old_table.columns.get(col_name) {
                let change = |change_type: &str, details: String| ColumnChange {
                    table: table_name.clone(),
                    column: col_name.clone(),
                    change_type: change_type.into(),
                    details,
                };
                let (old_type, current_type) = (column_type(old_col), column_type(current_col));
                if old_type != current_type {
                    changed_columns.push(change(
                        "type_changed",
                        format!("{old_type} → {current_type}"),
                    ));
                } else if old_col.raw_type != current_col.raw_type {
                    changed_columns.push(change(
                        "type_changed",
                        format!("{} → {}", old_col.raw_type, current_col.raw_type),
                    ));
                }
                if current_col.is_auto_increment != old_col.is_auto_increment {
                    changed_columns.push(change(
                        "identity_changed",
                        format!(
                            "auto increment: {} → {}",
                            old_col.is_auto_increment, current_col.is_auto_increment
                        ),
                    ));
                }
                if current_col.has_default != old_col.has_default {
                    changed_columns.push(change(
                        "default_changed",
                        format!(
                            "has default: {} → {}",
                            old_col.has_default, current_col.has_default
                        ),
                    ));
                }
                if current_col.enum_values != old_col.enum_values {
                    changed_columns.push(change(
                        "enum_changed",
                        format!(
                            "labels: {} → {}",
                            labels(old_col.enum_values.as_deref()),
                            labels(current_col.enum_values.as_deref())
                        ),
                    ));
                }
                if current_col.is_generated != old_col.is_generated {
                    changed_columns.push(ColumnChange {
                        table: table_name.clone(),
                        column: col_name.clone(),
                        change_type: "generated_changed".into(),
                        details: format!(
                            "database generated: {} → {}",
                            old_col.is_generated, current_col.is_generated
                        ),
                    });
                }
                if current_col.nullable != old_col.nullable {
                    changed_columns.push(ColumnChange {
                        table: table_name.clone(),
                        column: col_name.clone(),
                        change_type: "nullable_changed".to_string(),
                        details: format!(
                            "nullable: {} → {}",
                            old_col.nullable, current_col.nullable
                        ),
                    });
                }
            }
        }

        let primary_key = |table: &crate::schema::types::Table| {
            table
                .primary_key
                .as_ref()
                .map_or("(none)".to_owned(), |pk| {
                    format!("({})", pk.columns.join(","))
                })
        };
        let (old_pk, current_pk) = (primary_key(old_table), primary_key(current_table));
        if old_pk != current_pk {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "pk_changed".to_string(),
                details: format!("PRIMARY KEY {old_pk} → {current_pk}"),
            });
        }

        // Diff foreign keys
        let old_fks: std::collections::BTreeSet<String> = old_table
            .foreign_keys
            .iter()
            .map(|fk| {
                format!(
                    "({}) -> {}({})",
                    fk.source_columns.join(","),
                    fk.target_name(),
                    fk.referenced_columns.join(",")
                )
            })
            .collect();
        let cur_fks: std::collections::BTreeSet<String> = current_table
            .foreign_keys
            .iter()
            .map(|fk| {
                format!(
                    "({}) -> {}({})",
                    fk.source_columns.join(","),
                    fk.target_name(),
                    fk.referenced_columns.join(",")
                )
            })
            .collect();
        for added in cur_fks.difference(&old_fks) {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "fk_added".to_string(),
                details: format!("FOREIGN KEY {}", added),
            });
        }
        for removed in old_fks.difference(&cur_fks) {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "fk_removed".to_string(),
                details: format!("FOREIGN KEY {}", removed),
            });
        }

        // Diff unique constraints
        let old_uqs: std::collections::BTreeSet<String> = old_table
            .unique_constraints
            .iter()
            .map(|uq| format!("({})", uq.columns.join(",")))
            .collect();
        let cur_uqs: std::collections::BTreeSet<String> = current_table
            .unique_constraints
            .iter()
            .map(|uq| format!("({})", uq.columns.join(",")))
            .collect();
        for added in cur_uqs.difference(&old_uqs) {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "unique_added".to_string(),
                details: format!("UNIQUE {}", added),
            });
        }
        for removed in old_uqs.difference(&cur_uqs) {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "unique_removed".to_string(),
                details: format!("UNIQUE {}", removed),
            });
        }

        // Diff check constraints
        let old_cks: std::collections::BTreeSet<String> = old_table
            .check_constraints
            .iter()
            .map(|ck| ck.expression.clone())
            .collect();
        let cur_cks: std::collections::BTreeSet<String> = current_table
            .check_constraints
            .iter()
            .map(|ck| ck.expression.clone())
            .collect();
        for added in cur_cks.difference(&old_cks) {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "check_added".to_string(),
                details: format!("CHECK ({})", added),
            });
        }
        for removed in old_cks.difference(&cur_cks) {
            changed_columns.push(ColumnChange {
                table: table_name.clone(),
                column: String::new(),
                change_type: "check_removed".to_string(),
                details: format!("CHECK ({})", removed),
            });
        }
    }

    // Database-level enum types (PostgreSQL) can change without touching a table.
    let enum_names: std::collections::BTreeSet<&String> =
        old.enums.keys().chain(current.enums.keys()).collect();
    for name in enum_names {
        let (old_labels, current_labels) = (old.enums.get(name), current.enums.get(name));
        if old_labels != current_labels {
            changed_columns.push(ColumnChange {
                table: String::new(),
                column: String::new(),
                change_type: "enum_changed".to_string(),
                details: format!(
                    "ENUM {name}: {} → {}",
                    labels(old_labels.map(Vec::as_slice)),
                    labels(current_labels.map(Vec::as_slice))
                ),
            });
        }
    }

    let has_drift = !new_tables.is_empty()
        || !removed_tables.is_empty()
        || !new_columns.is_empty()
        || !removed_columns.is_empty()
        || !changed_columns.is_empty();

    DriftReport {
        has_drift,
        new_tables,
        removed_tables,
        new_columns,
        removed_columns,
        changed_columns,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::types::*;

    #[allow(clippy::type_complexity)]
    fn make_schema(tables: Vec<(&str, Vec<(&str, DataType, bool)>)>) -> DatabaseSchema {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        for (table_name, cols) in tables {
            let mut table = Table::new(table_name.to_string());
            for (i, (col_name, dt, nullable)) in cols.iter().enumerate() {
                let mut col = Column::new(col_name.to_string(), dt.clone(), dt.to_string());
                col.nullable = *nullable;
                col.ordinal_position = i as u32;
                table.columns.insert(col_name.to_string(), col);
            }
            schema.tables.insert(table_name.to_string(), table);
        }
        schema
    }

    #[test]
    fn public_schema_retains_legacy_lock_hash() {
        let old = make_schema(vec![("items", vec![("id", DataType::Integer, false)])]);
        let mut current = old.clone();
        current.tables["items"].schema_name = Some("public".into());
        assert_eq!(compute_schema_hash(&old), compute_schema_hash(&current));
        current.tables["items"].schema_name = Some("tenant_a".into());
        assert_ne!(compute_schema_hash(&old), compute_schema_hash(&current));
    }

    #[test]
    fn test_no_drift_identical_schemas() {
        let schema = make_schema(vec![(
            "users",
            vec![
                ("id", DataType::Serial, false),
                ("name", DataType::VarChar, false),
            ],
        )]);
        let report = check_drift_detailed(&schema, &schema);
        assert!(!report.has_drift);
    }

    #[test]
    fn test_new_table_detected() {
        let old = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);
        let current = make_schema(vec![
            ("users", vec![("id", DataType::Serial, false)]),
            ("posts", vec![("id", DataType::Serial, false)]),
        ]);
        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(report.new_tables, vec!["posts"]);
    }

    #[test]
    fn test_removed_table_detected() {
        let old = make_schema(vec![
            ("users", vec![("id", DataType::Serial, false)]),
            ("posts", vec![("id", DataType::Serial, false)]),
        ]);
        let current = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);
        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(report.removed_tables, vec!["posts"]);
    }

    #[test]
    fn test_new_column_detected() {
        let old = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);
        let current = make_schema(vec![(
            "users",
            vec![
                ("id", DataType::Serial, false),
                ("email", DataType::VarChar, false),
            ],
        )]);
        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(report.new_columns.len(), 1);
        assert_eq!(report.new_columns[0].column, "email");
    }

    #[test]
    fn test_type_change_detected() {
        let old = make_schema(vec![("users", vec![("age", DataType::Integer, false)])]);
        let current = make_schema(vec![("users", vec![("age", DataType::BigInt, false)])]);
        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(report.changed_columns.len(), 1);
        assert_eq!(report.changed_columns[0].change_type, "type_changed");
        assert!(report.changed_columns[0].details.contains("integer"));
        assert!(report.changed_columns[0].details.contains("bigint"));
    }

    #[test]
    fn test_nullable_change_detected() {
        let old = make_schema(vec![("users", vec![("name", DataType::VarChar, false)])]);
        let current = make_schema(vec![("users", vec![("name", DataType::VarChar, true)])]);
        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(report.changed_columns.len(), 1);
        assert_eq!(report.changed_columns[0].change_type, "nullable_changed");
    }

    #[test]
    fn test_schema_hash_deterministic() {
        let schema = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);
        let h1 = compute_schema_hash(&schema);
        let h2 = compute_schema_hash(&schema);
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_summary_no_drift() {
        let report = DriftReport {
            has_drift: false,
            new_tables: Vec::new(),
            removed_tables: Vec::new(),
            new_columns: Vec::new(),
            removed_columns: Vec::new(),
            changed_columns: Vec::new(),
        };
        assert_eq!(report.summary(), "No schema drift detected.");
    }

    #[test]
    fn test_summary_with_drift() {
        let report = DriftReport {
            has_drift: true,
            new_tables: vec!["posts".to_string()],
            removed_tables: vec!["legacy".to_string()],
            new_columns: vec![ColumnRef {
                table: "users".into(),
                column: "email".into(),
            }],
            removed_columns: Vec::new(),
            changed_columns: Vec::new(),
        };
        let s = report.summary();
        assert!(s.contains("+ table: posts"));
        assert!(s.contains("- table: legacy"));
        assert!(s.contains("+ column: users.email"));
    }

    // --- Heavy lockfile: check_drift with schema snapshot ---

    #[test]
    fn test_check_drift_hash_match_fast_path() {
        let schema = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);
        let hash = compute_schema_hash(&schema);

        let report = check_drift(&schema, &hash, &schema);
        assert!(!report.has_drift);
    }

    #[test]
    fn test_check_drift_hash_mismatch_produces_detailed_report() {
        let old = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);
        let old_hash = compute_schema_hash(&old);

        let current = make_schema(vec![
            (
                "users",
                vec![
                    ("id", DataType::Serial, false),
                    ("email", DataType::VarChar, false),
                ],
            ),
            ("posts", vec![("id", DataType::Serial, false)]),
        ]);

        let report = check_drift(&old, &old_hash, &current);
        assert!(report.has_drift);
        // Must produce actionable details, not empty vectors
        assert_eq!(report.new_tables, vec!["posts"]);
        assert_eq!(report.new_columns.len(), 1);
        assert_eq!(report.new_columns[0].column, "email");
    }

    #[test]
    fn test_check_drift_removed_column_detailed() {
        let old = make_schema(vec![(
            "users",
            vec![
                ("id", DataType::Serial, false),
                ("legacy_field", DataType::Text, true),
            ],
        )]);
        let old_hash = compute_schema_hash(&old);

        let current = make_schema(vec![("users", vec![("id", DataType::Serial, false)])]);

        let report = check_drift(&old, &old_hash, &current);
        assert!(report.has_drift);
        assert_eq!(report.removed_columns.len(), 1);
        assert_eq!(report.removed_columns[0].column, "legacy_field");
    }

    // --- Fix 1: Non-deterministic hash (array ordering) ---

    #[test]
    fn test_hash_stable_regardless_of_fk_order() {
        // Two schemas identical except foreign keys are in different order.
        // Hash must be the same.
        let mut schema_a = make_schema(vec![(
            "orders",
            vec![
                ("id", DataType::Serial, false),
                ("user_id", DataType::Integer, false),
                ("product_id", DataType::Integer, false),
            ],
        )]);
        schema_a.tables.get_mut("orders").unwrap().foreign_keys = vec![
            ForeignKey {
                name: Some("fk_user".to_string()),
                source_columns: vec!["user_id".to_string()],
                referenced_schema: None,
                referenced_table: "users".to_string(),
                referenced_columns: vec!["id".to_string()],
                on_delete: ForeignKeyAction::Cascade,
                on_update: ForeignKeyAction::NoAction,
                is_deferrable: false,
            },
            ForeignKey {
                name: Some("fk_product".to_string()),
                source_columns: vec!["product_id".to_string()],
                referenced_schema: None,
                referenced_table: "products".to_string(),
                referenced_columns: vec!["id".to_string()],
                on_delete: ForeignKeyAction::NoAction,
                on_update: ForeignKeyAction::NoAction,
                is_deferrable: false,
            },
        ];

        let mut schema_b = schema_a.clone();
        // Reverse the FK order
        schema_b
            .tables
            .get_mut("orders")
            .unwrap()
            .foreign_keys
            .reverse();

        let hash_a = compute_schema_hash(&schema_a);
        let hash_b = compute_schema_hash(&schema_b);
        assert_eq!(hash_a, hash_b, "Hash must be stable regardless of FK order");
    }

    #[test]
    fn test_hash_stable_regardless_of_unique_constraint_order() {
        let mut schema_a = make_schema(vec![(
            "users",
            vec![
                ("id", DataType::Serial, false),
                ("email", DataType::VarChar, false),
                ("username", DataType::VarChar, false),
            ],
        )]);
        schema_a.tables.get_mut("users").unwrap().unique_constraints = vec![
            UniqueConstraint {
                name: Some("uq_email".to_string()),
                columns: vec!["email".to_string()],
            },
            UniqueConstraint {
                name: Some("uq_username".to_string()),
                columns: vec!["username".to_string()],
            },
        ];

        let mut schema_b = schema_a.clone();
        schema_b
            .tables
            .get_mut("users")
            .unwrap()
            .unique_constraints
            .reverse();

        let hash_a = compute_schema_hash(&schema_a);
        let hash_b = compute_schema_hash(&schema_b);
        assert_eq!(
            hash_a, hash_b,
            "Hash must be stable regardless of unique constraint order"
        );
    }

    #[test]
    fn test_hash_stable_regardless_of_check_constraint_order() {
        let mut schema_a = make_schema(vec![(
            "products",
            vec![
                ("price", DataType::Numeric, false),
                ("quantity", DataType::Integer, false),
            ],
        )]);
        schema_a
            .tables
            .get_mut("products")
            .unwrap()
            .check_constraints = vec![
            CheckConstraint {
                name: Some("ck_price".to_string()),
                expression: "price >= 0".to_string(),
                parsed: None,
            },
            CheckConstraint {
                name: Some("ck_qty".to_string()),
                expression: "quantity > 0".to_string(),
                parsed: None,
            },
        ];

        let mut schema_b = schema_a.clone();
        schema_b
            .tables
            .get_mut("products")
            .unwrap()
            .check_constraints
            .reverse();

        let hash_a = compute_schema_hash(&schema_a);
        let hash_b = compute_schema_hash(&schema_b);
        assert_eq!(
            hash_a, hash_b,
            "Hash must be stable regardless of check constraint order"
        );
    }

    // --- Fix 2: Constraint blind spot ---

    #[test]
    fn test_drift_detects_added_foreign_key() {
        let old = make_schema(vec![(
            "orders",
            vec![
                ("id", DataType::Serial, false),
                ("user_id", DataType::Integer, false),
            ],
        )]);

        let mut current = old.clone();
        current
            .tables
            .get_mut("orders")
            .unwrap()
            .foreign_keys
            .push(ForeignKey {
                name: Some("fk_user".to_string()),
                source_columns: vec!["user_id".to_string()],
                referenced_schema: None,
                referenced_table: "users".to_string(),
                referenced_columns: vec!["id".to_string()],
                on_delete: ForeignKeyAction::Cascade,
                on_update: ForeignKeyAction::NoAction,
                is_deferrable: false,
            });

        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert!(
            report
                .changed_columns
                .iter()
                .any(|c| c.change_type == "fk_added"),
            "Should detect added FK: {:?}",
            report.changed_columns
        );
    }

    #[test]
    fn test_drift_detects_removed_unique_constraint() {
        let mut old = make_schema(vec![(
            "users",
            vec![
                ("id", DataType::Serial, false),
                ("email", DataType::VarChar, false),
            ],
        )]);
        old.tables
            .get_mut("users")
            .unwrap()
            .unique_constraints
            .push(UniqueConstraint {
                name: Some("uq_email".to_string()),
                columns: vec!["email".to_string()],
            });

        let current = make_schema(vec![(
            "users",
            vec![
                ("id", DataType::Serial, false),
                ("email", DataType::VarChar, false),
            ],
        )]);

        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert!(
            report
                .changed_columns
                .iter()
                .any(|c| c.change_type == "unique_removed"),
            "Should detect removed unique constraint: {:?}",
            report.changed_columns
        );
    }

    #[test]
    fn test_drift_detects_removed_check_constraint() {
        let mut old = make_schema(vec![(
            "products",
            vec![("price", DataType::Numeric, false)],
        )]);
        old.tables
            .get_mut("products")
            .unwrap()
            .check_constraints
            .push(CheckConstraint {
                name: Some("ck_price".to_string()),
                expression: "price >= 0".to_string(),
                parsed: None,
            });

        let current = make_schema(vec![(
            "products",
            vec![("price", DataType::Numeric, false)],
        )]);

        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert!(
            report
                .changed_columns
                .iter()
                .any(|c| c.change_type == "check_removed"),
            "Should detect removed check constraint: {:?}",
            report.changed_columns
        );
    }

    #[test]
    fn test_drift_no_false_positive_on_identical_constraints() {
        let mut schema = make_schema(vec![(
            "orders",
            vec![
                ("id", DataType::Serial, false),
                ("user_id", DataType::Integer, false),
            ],
        )]);
        schema
            .tables
            .get_mut("orders")
            .unwrap()
            .foreign_keys
            .push(ForeignKey {
                name: Some("fk_user".to_string()),
                source_columns: vec!["user_id".to_string()],
                referenced_schema: None,
                referenced_table: "users".to_string(),
                referenced_columns: vec!["id".to_string()],
                on_delete: ForeignKeyAction::Cascade,
                on_update: ForeignKeyAction::NoAction,
                is_deferrable: false,
            });
        schema
            .tables
            .get_mut("orders")
            .unwrap()
            .unique_constraints
            .push(UniqueConstraint {
                name: Some("uq_user".to_string()),
                columns: vec!["user_id".to_string()],
            });

        let report = check_drift_detailed(&schema, &schema);
        assert!(
            !report.has_drift,
            "Identical schemas with constraints should not report drift"
        );
    }

    fn change_types(report: &DriftReport) -> Vec<&str> {
        report
            .changed_columns
            .iter()
            .map(|c| c.change_type.as_str())
            .collect()
    }

    #[test]
    fn test_drift_detects_length_change() {
        let old = make_schema(vec![("users", vec![("name", DataType::VarChar, false)])]);
        let mut current = old.clone();
        current.tables["users"].columns["name"].max_length = Some(20);
        let mut old = old;
        old.tables["users"].columns["name"].max_length = Some(10);

        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(change_types(&report), ["type_changed"]);
        assert_eq!(
            report.changed_columns[0].details,
            "varchar(10) → varchar(20)"
        );
    }

    #[test]
    fn test_drift_detects_primary_key_change() {
        let old = make_schema(vec![(
            "memberships",
            vec![
                ("user_id", DataType::Integer, false),
                ("team_id", DataType::Integer, false),
            ],
        )]);
        let mut current = old.clone();
        let mut old = old;
        old.tables["memberships"].primary_key = Some(PrimaryKey {
            columns: vec!["user_id".into()],
            name: None,
        });
        current.tables["memberships"].primary_key = Some(PrimaryKey {
            columns: vec!["user_id".into(), "team_id".into()],
            name: None,
        });

        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(change_types(&report), ["pk_changed"]);
        assert_eq!(
            report.changed_columns[0].details,
            "PRIMARY KEY (user_id) → (user_id,team_id)"
        );
    }

    #[test]
    fn test_drift_detects_enum_label_change() {
        let mut old = make_schema(vec![("orders", vec![("status", DataType::Text, false)])]);
        let mut current = old.clone();
        old.tables["orders"].columns["status"].enum_values =
            Some(vec!["open".into(), "closed".into()]);
        current.tables["orders"].columns["status"].enum_values =
            Some(vec!["open".into(), "closed".into(), "archived".into()]);
        old.enums.insert("order_status".into(), vec!["open".into()]);
        current.enums.insert(
            "order_status".into(),
            vec!["open".into(), "archived".into()],
        );

        let report = check_drift_detailed(&old, &current);
        assert!(report.has_drift);
        assert_eq!(change_types(&report), ["enum_changed", "enum_changed"]);
        assert_eq!(report.changed_columns[0].table, "orders");
        assert_eq!(report.changed_columns[1].table, "");
        assert!(report.changed_columns[1].details.contains("order_status"));
    }

    #[test]
    fn test_drift_detects_identity_change() {
        let mut old = make_schema(vec![("users", vec![("id", DataType::Integer, false)])]);
        let mut current = old.clone();
        old.tables["users"].columns["id"].is_auto_increment = false;
        current.tables["users"].columns["id"].is_auto_increment = true;
        current.tables["users"].columns["id"].has_default = true;

        let report = check_drift_detailed(&old, &current);
        assert_eq!(
            change_types(&report),
            ["identity_changed", "default_changed"]
        );
    }

    #[test]
    fn test_hash_mismatch_is_always_reported_as_drift() {
        // `generate --from-lock` refuses any hash mismatch, so `check` must too,
        // even when no listed property differs (here: only a constraint name).
        let mut old = make_schema(vec![("users", vec![("email", DataType::Text, false)])]);
        old.tables["users"]
            .unique_constraints
            .push(UniqueConstraint {
                name: Some("users_email_key".into()),
                columns: vec!["email".into()],
            });
        let mut current = old.clone();
        current.tables["users"].unique_constraints[0].name = Some("users_email_idx".into());
        let old_hash = compute_schema_hash(&old);
        assert_ne!(old_hash, compute_schema_hash(&current));

        let report = check_drift(&old, &old_hash, &current);
        assert!(report.has_drift);
        assert_eq!(change_types(&report), ["schema_changed"]);
        assert!(report.summary().contains("schema_changed"));
    }
}