drizzle-migrations 0.1.12

Migration infrastructure for drizzle-rs
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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
//! Schema snapshot builder from parsed schema files.
//!
//! This module converts [`ParseResult`] from the schema parser into
//! [`Snapshot`] values used for migration diffing.
//!
//! It is shared by runtime/build-time migration generation flows that do not
//! rely on the CLI.

use crate::parser::{ParseResult, ParsedField, ParsedIndex, ParsedTable};
use crate::postgres::PostgresSnapshot;
use crate::schema::Snapshot;
use crate::sqlite::SQLiteSnapshot;
use drizzle_types::postgres::{PostgreSQLType, TypeCategory as PgTypeCategory};
use drizzle_types::sqlite::{SQLiteType, TypeCategory as SQLiteTypeCategory};
use drizzle_types::{Casing, Dialect};
use heck::{ToLowerCamelCase, ToSnakeCase};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};

/// Convert a `ParseResult` into a `Snapshot` for migration diffing
///
/// Uses the provided `dialect` from config rather than the parser-detected dialect,
/// allowing users to have multi-dialect schema files and select which to use via config.
#[must_use]
pub fn parse_result_to_snapshot(
    result: &ParseResult,
    dialect: Dialect,
    casing: Option<Casing>,
) -> Snapshot {
    match dialect {
        Dialect::SQLite => Snapshot::Sqlite(build_sqlite_snapshot(result, casing)),
        Dialect::PostgreSQL => Snapshot::Postgres(build_postgres_snapshot(result, casing)),
        Dialect::MySQL => {
            unreachable!("Unsupported dialect for snapshot generation: {dialect:?}")
        }
    }
}

fn apply_casing(name: &str, casing: Casing) -> String {
    match casing {
        Casing::SnakeCase => name.to_snake_case(),
        Casing::CamelCase => name.to_lower_camel_case(),
    }
}

fn trim_wrapping_quotes(s: &str) -> String {
    s.trim().trim_matches('"').trim_matches('\'').to_string()
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct ParsedIndexAttrs {
    name: Option<String>,
}

impl ParsedIndexAttrs {
    fn parse(attr: &str) -> Self {
        let Some(start) = attr.find('(') else {
            return Self::default();
        };
        let Some(end) = attr.rfind(')') else {
            return Self::default();
        };

        let mut parsed = Self::default();
        let content = &attr[start + 1..end];
        for part in content.split(',') {
            let part = part.trim();
            if let Some((k, v)) = part.split_once('=')
                && k.trim() == "name"
            {
                parsed.name = Some(trim_wrapping_quotes(v));
            }
        }

        parsed
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MemberRef<'a> {
    table: &'a str,
    field: &'a str,
}

impl<'a> MemberRef<'a> {
    fn parse(raw: &'a str) -> Option<Self> {
        let (table, field) = raw.split_once("::")?;
        if table.is_empty() || field.is_empty() || field.contains("::") {
            return None;
        }

        Some(Self { table, field })
    }
}

fn sqlite_type_sql(ty: SQLiteType) -> String {
    ty.to_sql_type().to_ascii_lowercase()
}

fn postgres_type_sql(ty: &PostgreSQLType) -> String {
    ty.to_sql_type().to_ascii_lowercase()
}

fn resolve_table_name(table: &ParsedTable, casing: Casing) -> String {
    table.attr_value("name").map_or_else(
        || apply_casing(&table.name, casing),
        |v| trim_wrapping_quotes(&v),
    )
}

fn resolve_field_name(field: &ParsedField, casing: Casing) -> String {
    field.attr_value("name").map_or_else(
        || apply_casing(&field.name, casing),
        |v| trim_wrapping_quotes(&v),
    )
}

fn resolve_sqlite_type(field: &ParsedField) -> SQLiteType {
    explicit_sqlite_type(field).unwrap_or_else(|| infer_sqlite_type(&field.ty))
}

fn explicit_sqlite_type(field: &ParsedField) -> Option<SQLiteType> {
    for attr in &field.attrs {
        let Some(name) = attr_name(attr) else {
            continue;
        };

        if let Some(ty) = sqlite_type_marker(name) {
            return Some(ty);
        }

        if !name.eq_ignore_ascii_case("column") {
            continue;
        }

        let Some(args) = attr_args(attr) else {
            continue;
        };

        for part in split_attr_parts(args) {
            let marker = marker_key(part);
            if let Some(ty) = sqlite_type_marker(marker) {
                return Some(ty);
            }
        }
    }

    None
}

fn sqlite_type_marker(marker: &str) -> Option<SQLiteType> {
    if marker.eq_ignore_ascii_case("json") {
        Some(SQLiteType::Text)
    } else if marker.eq_ignore_ascii_case("jsonb") {
        Some(SQLiteType::Blob)
    } else {
        SQLiteType::from_attribute_name(marker)
    }
}

fn attr_name(attr: &str) -> Option<&str> {
    let rest = attr.trim().strip_prefix("#[")?;
    let end = rest.find(['(', ']'])?;
    Some(rest[..end].trim())
}

fn attr_args(attr: &str) -> Option<&str> {
    let start = attr.find('(')?;
    let end = attr.rfind(')')?;
    (start < end).then_some(&attr[start + 1..end])
}

fn marker_key(part: &str) -> &str {
    let part = part.trim();
    let end = part.find(['=', '(']).unwrap_or(part.len());
    part[..end].trim()
}

fn marker_args(part: &str) -> Option<&str> {
    let start = part.find('(')?;
    let end = part.rfind(')')?;
    (start < end).then_some(&part[start + 1..end])
}

fn marker_value(part: &str) -> Option<&str> {
    part.split_once('=')
        .map(|(_, value)| value.trim())
        .or_else(|| marker_args(part).map(str::trim))
}

fn field_marker_part<'a>(field: &'a ParsedField, marker: &str) -> Option<&'a str> {
    for attr in &field.attrs {
        let Some(name) = attr_name(attr) else {
            continue;
        };

        if name.eq_ignore_ascii_case(marker) {
            return Some(attr);
        }

        if !name.eq_ignore_ascii_case("column") {
            continue;
        }

        let Some(args) = attr_args(attr) else {
            continue;
        };

        for part in split_attr_parts(args) {
            if marker_key(part).eq_ignore_ascii_case(marker) {
                return Some(part);
            }
        }
    }

    None
}

fn field_has_marker(field: &ParsedField, marker: &str) -> bool {
    field_marker_part(field, marker).is_some()
}

fn field_marker_args<'a>(field: &'a ParsedField, marker: &str) -> Option<&'a str> {
    let part = field_marker_part(field, marker)?;
    if part.trim_start().starts_with("#[") {
        attr_args(part)
    } else {
        marker_args(part)
    }
}

fn field_marker_value(field: &ParsedField, marker: &str) -> Option<String> {
    let part = field_marker_part(field, marker)?;
    let raw_value = if part.trim_start().starts_with("#[") {
        attr_args(part)?
    } else {
        marker_value(part)?
    };
    Some(trim_wrapping_quotes(raw_value))
}

fn split_attr_parts(content: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;

    for (i, c) in content.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }

        match c {
            '\\' if in_single || in_double => escaped = true,
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '(' | '<' | '[' | '{' if !in_single && !in_double => depth += 1,
            ')' | '>' | ']' | '}' if !in_single && !in_double => {
                depth = depth.saturating_sub(1);
            }
            ',' if depth == 0 && !in_single && !in_double => {
                parts.push(content[start..i].trim());
                start = i + 1;
            }
            _ => {}
        }
    }

    if start < content.len() {
        parts.push(content[start..].trim());
    }

    parts
}

/// Build an `SQLite` snapshot from parsed schema
fn build_sqlite_snapshot(result: &ParseResult, casing: Option<Casing>) -> SQLiteSnapshot {
    use crate::sqlite::{PrimaryKey, SqliteEntity, Table, UniqueConstraint};

    let mut snapshot = SQLiteSnapshot::new();
    let name_casing = casing.unwrap_or(Casing::SnakeCase);

    let sqlite_tables: Vec<_> = result
        .tables
        .values()
        .filter(|t| t.dialect == Dialect::SQLite)
        .collect();

    let mut table_name_map: HashMap<String, String> = HashMap::new();
    let mut field_name_map: HashMap<(String, String), String> = HashMap::new();
    for table in &sqlite_tables {
        let table_name = resolve_table_name(table, name_casing);
        table_name_map.insert(table.name.clone(), table_name);
        for field in &table.fields {
            field_name_map.insert(
                (table.name.clone(), field.name.clone()),
                resolve_field_name(field, name_casing),
            );
        }
    }

    // Process tables (only those matching SQLite dialect)
    for table in sqlite_tables {
        let table_name = table_name_map
            .get(&table.name)
            .cloned()
            .unwrap_or_else(|| resolve_table_name(table, name_casing));

        // Add table entity
        let mut sqlite_table = Table::new(table_name.clone());
        sqlite_table.strict = table.is_strict();
        sqlite_table.without_rowid = table.is_without_rowid();
        snapshot.add_entity(SqliteEntity::Table(sqlite_table));

        // Process columns
        let mut pk_columns = Vec::new();

        for field in &table.fields {
            let col_name = field_name_map
                .get(&(table.name.clone(), field.name.clone()))
                .cloned()
                .unwrap_or_else(|| resolve_field_name(field, name_casing));
            let col = build_sqlite_column(&table_name, field, &col_name);
            snapshot.add_entity(SqliteEntity::Column(col));

            // Track primary key columns
            if field.is_primary_key() {
                pk_columns.push(col_name.clone());
            }

            // Add unique constraint if column is unique (not primary)
            if field.is_unique() && !field.is_primary_key() {
                let constraint_name = format!("{table_name}_{col_name}_unique");
                snapshot.add_entity(SqliteEntity::UniqueConstraint(
                    UniqueConstraint::from_strings(
                        table_name.clone(),
                        constraint_name,
                        vec![col_name.clone()],
                    ),
                ));
            }

            // Add foreign key if references exist
            if let Some(ref_target) = field.references()
                && let Some(fk) = build_sqlite_foreign_key(
                    &table_name,
                    &col_name,
                    field,
                    &ref_target,
                    &table_name_map,
                    &field_name_map,
                    name_casing,
                )
            {
                snapshot.add_entity(SqliteEntity::ForeignKey(fk));
            }
        }

        // Add primary key entity
        if !pk_columns.is_empty() {
            let pk_name = format!("{table_name}_pkey");
            snapshot.add_entity(SqliteEntity::PrimaryKey(PrimaryKey::from_strings(
                table_name, pk_name, pk_columns,
            )));
        }
    }

    // Process indexes (only those matching SQLite dialect)
    for index in result
        .indexes
        .values()
        .filter(|i| i.dialect == Dialect::SQLite)
    {
        let idx = build_sqlite_index(index, &table_name_map, &field_name_map, name_casing);
        snapshot.add_entity(SqliteEntity::Index(idx));
    }

    snapshot
}

/// Name/schema maps for `PostgreSQL` snapshot building, built once up front
/// and reused for column/FK/index resolution.
struct PgNameMaps {
    /// Parsed struct name -> resolved SQL table name.
    table_name_map: HashMap<String, String>,
    /// (parsed struct name, parsed field name) -> resolved SQL column name.
    field_name_map: HashMap<(String, String), String>,
    /// Parsed struct name -> `PostgreSQL` schema ("public" by default).
    table_schemas: HashMap<String, String>,
    /// All distinct schemas discovered in the schema set.
    schema_list: Vec<String>,
}

fn build_pg_name_maps(pg_tables: &[&ParsedTable], casing: Casing) -> PgNameMaps {
    let mut table_name_map: HashMap<String, String> = HashMap::new();
    let mut field_name_map: HashMap<(String, String), String> = HashMap::new();
    for table in pg_tables {
        table_name_map.insert(table.name.clone(), resolve_table_name(table, casing));
        for field in &table.fields {
            field_name_map.insert(
                (table.name.clone(), field.name.clone()),
                resolve_field_name(field, casing),
            );
        }
    }

    let mut table_schemas: HashMap<String, String> = HashMap::new();
    let mut schemas: HashSet<String> = HashSet::new();
    for table in pg_tables {
        let schema_name = table.schema_name().unwrap_or_else(|| "public".to_string());
        table_schemas.insert(table.name.clone(), schema_name.clone());
        schemas.insert(schema_name);
    }
    if schemas.is_empty() {
        schemas.insert("public".to_string());
    }

    let mut schema_list: Vec<String> = schemas.into_iter().collect();
    schema_list.sort();

    PgNameMaps {
        table_name_map,
        field_name_map,
        table_schemas,
        schema_list,
    }
}

/// Add table, column, unique, primary-key and FK entities for a single
/// parsed `PostgreSQL` table.
fn add_postgres_table_entities(
    snapshot: &mut PostgresSnapshot,
    table: &ParsedTable,
    maps: &PgNameMaps,
    casing: Casing,
) {
    use crate::postgres::{PostgresEntity, PrimaryKey, Table, UniqueConstraint};

    let table_name = maps
        .table_name_map
        .get(&table.name)
        .cloned()
        .unwrap_or_else(|| resolve_table_name(table, casing));
    let schema_name = table.schema_name().unwrap_or_else(|| "public".to_string());

    snapshot.add_entity(PostgresEntity::Table(Table {
        schema: schema_name.clone().into(),
        name: table_name.clone().into(),
        is_unlogged: None,
        is_temporary: None,
        inherits: None,
        tablespace: None,
        is_rls_enabled: None,
        comment: None,
    }));

    let mut pk_columns = Vec::new();

    for field in &table.fields {
        let col_name = maps
            .field_name_map
            .get(&(table.name.clone(), field.name.clone()))
            .cloned()
            .unwrap_or_else(|| resolve_field_name(field, casing));
        let col = build_postgres_column(&schema_name, &table_name, field, &col_name);
        snapshot.add_entity(PostgresEntity::Column(col));

        if field.is_primary_key() {
            pk_columns.push(col_name.clone());
        }

        if field.is_unique() && !field.is_primary_key() {
            snapshot.add_entity(PostgresEntity::UniqueConstraint(
                UniqueConstraint::from_strings(
                    schema_name.clone(),
                    table_name.clone(),
                    format!("{table_name}_{col_name}_key"),
                    vec![col_name.clone()],
                ),
            ));
        }

        if let Some(ref_target) = field.references()
            && let Some(fk) = build_postgres_foreign_key(
                &schema_name,
                &table_name,
                &col_name,
                field,
                &ref_target,
                &maps.table_name_map,
                &maps.field_name_map,
                &maps.table_schemas,
                casing,
            )
        {
            snapshot.add_entity(PostgresEntity::ForeignKey(fk));
        }
    }

    if !pk_columns.is_empty() {
        snapshot.add_entity(PostgresEntity::PrimaryKey(PrimaryKey::from_strings(
            schema_name,
            table_name.clone(),
            format!("{table_name}_pkey"),
            pk_columns,
        )));
    }
}

/// Build a `PostgreSQL` snapshot from parsed schema
fn build_postgres_snapshot(result: &ParseResult, casing: Option<Casing>) -> PostgresSnapshot {
    use crate::postgres::{PostgresEntity, Schema as PgSchema};

    let mut snapshot = PostgresSnapshot::new();
    let name_casing = casing.unwrap_or(Casing::SnakeCase);

    let pg_tables: Vec<_> = result
        .tables
        .values()
        .filter(|t| t.dialect == Dialect::PostgreSQL)
        .collect();

    let maps = build_pg_name_maps(&pg_tables, name_casing);

    for schema in &maps.schema_list {
        snapshot.add_entity(PostgresEntity::Schema(PgSchema::new(schema.clone())));
    }

    for table in pg_tables {
        add_postgres_table_entities(&mut snapshot, table, &maps, name_casing);
    }

    // Process indexes (only those matching PostgreSQL dialect)
    for index in result
        .indexes
        .values()
        .filter(|i| i.dialect == Dialect::PostgreSQL)
    {
        let idx = build_postgres_index(
            index,
            &maps.table_name_map,
            &maps.field_name_map,
            &maps.table_schemas,
            name_casing,
        );
        snapshot.add_entity(PostgresEntity::Index(idx));
    }

    snapshot
}

/// Build an `SQLite` column from a parsed field
fn build_sqlite_column(
    table_name: &str,
    field: &ParsedField,
    col_name: &str,
) -> crate::sqlite::Column {
    use crate::sqlite::Column;

    let col_type = resolve_sqlite_type(field);

    let mut col = Column::new(
        table_name.to_string(),
        col_name.to_string(),
        sqlite_type_sql(col_type),
    );

    if !field.is_nullable() {
        col = col.not_null();
    }

    if field.is_autoincrement() {
        col = col.autoincrement();
    }

    if let Some(default) = field.default_value() {
        col = col.default_value(default);
    }

    col
}

fn resolve_postgres_type(field: &ParsedField) -> PostgreSQLType {
    if field_has_marker(field, "smallserial") {
        PostgreSQLType::Smallserial
    } else if field_has_marker(field, "bigserial") {
        PostgreSQLType::Bigserial
    } else if field_has_marker(field, "serial") {
        PostgreSQLType::Serial
    } else if field_has_marker(field, "json") {
        PostgreSQLType::Json
    } else if field_has_marker(field, "jsonb") {
        PostgreSQLType::Jsonb
    } else {
        infer_postgres_type(&field.ty)
    }
}

fn postgres_identity(
    schema_name: &str,
    table_name: &str,
    col_name: &str,
    field: &ParsedField,
) -> Option<crate::postgres::Identity> {
    use crate::postgres::Identity;
    use crate::postgres::ddl::IdentityType;

    if !field_has_marker(field, "identity") {
        return None;
    }

    let type_ = match field_marker_args(field, "identity")
        .map(str::trim)
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("by_default") => IdentityType::ByDefault,
        Some("always") | None => IdentityType::Always,
        Some(_) => IdentityType::Always,
    };

    Some(Identity {
        name: format!("{table_name}_{col_name}_seq").into(),
        schema: Some(schema_name.to_string().into()),
        type_,
        increment: None,
        min_value: None,
        max_value: None,
        start_with: None,
        cache: None,
        cycle: None,
    })
}

fn postgres_generated(field: &ParsedField) -> Option<crate::postgres::Generated> {
    use crate::postgres::Generated;
    use crate::postgres::ddl::GeneratedType;

    let args = field_marker_args(field, "generated")?;
    let parts = split_attr_parts(args);
    let [kind, expression] = parts.as_slice() else {
        return None;
    };

    if !kind.trim().eq_ignore_ascii_case("stored") {
        return None;
    }

    Some(Generated {
        expression: trim_wrapping_quotes(expression).into(),
        gen_type: GeneratedType::Stored,
    })
}

/// Build a `PostgreSQL` column from a parsed field
fn build_postgres_column(
    schema_name: &str,
    table_name: &str,
    field: &ParsedField,
    col_name: &str,
) -> crate::postgres::Column {
    use crate::postgres::Column;

    let col_type = resolve_postgres_type(field);
    let generated = postgres_generated(field);
    let identity = postgres_identity(schema_name, table_name, col_name, field);
    let default = if matches!(
        &col_type,
        PostgreSQLType::Smallserial | PostgreSQLType::Serial | PostgreSQLType::Bigserial
    ) || generated.is_some()
        || identity.is_some()
    {
        None
    } else {
        field.default_value().map(Cow::Owned)
    };

    Column {
        schema: schema_name.to_string().into(),
        table: table_name.to_string().into(),
        name: col_name.to_string().into(),
        sql_type: postgres_type_sql(&col_type).into(),
        type_schema: None,
        not_null: !field.is_nullable(),
        default,
        generated,
        identity,
        dimensions: None,
        comment: None,
        collate: field_marker_value(field, "collate").map(Cow::Owned),
        ordinal_position: None,
    }
}

/// Build an `SQLite` foreign key from a parsed field
fn build_sqlite_foreign_key(
    table_name: &str,
    col_name: &str,
    field: &ParsedField,
    ref_target: &str,
    table_name_map: &HashMap<String, String>,
    field_name_map: &HashMap<(String, String), String>,
    casing: Casing,
) -> Option<crate::sqlite::ForeignKey> {
    use crate::sqlite::ForeignKey;

    let target = MemberRef::parse(ref_target)?;

    let ref_table = table_name_map
        .get(target.table)
        .cloned()
        .unwrap_or_else(|| apply_casing(target.table, casing));
    let ref_column = field_name_map
        .get(&(target.table.to_string(), target.field.to_string()))
        .cloned()
        .unwrap_or_else(|| apply_casing(target.field, casing));
    let fk_name = format!("{table_name}_{col_name}_{ref_table}_{ref_column}_fk");

    let mut fk = ForeignKey::from_strings(
        table_name.to_string(),
        fk_name,
        vec![col_name.to_string()],
        ref_table,
        vec![ref_column],
    );

    fk.on_delete = field.on_delete().map(Cow::Owned);
    fk.on_update = field.on_update().map(Cow::Owned);

    Some(fk)
}

/// Build a `PostgreSQL` foreign key from a parsed field
#[allow(clippy::too_many_arguments)]
fn build_postgres_foreign_key(
    schema_name: &str,
    table_name: &str,
    col_name: &str,
    field: &ParsedField,
    ref_target: &str,
    table_name_map: &HashMap<String, String>,
    field_name_map: &HashMap<(String, String), String>,
    table_schemas: &HashMap<String, String>,
    casing: Casing,
) -> Option<crate::postgres::ForeignKey> {
    use crate::postgres::ForeignKey;

    let target = MemberRef::parse(ref_target)?;
    let ref_table_struct = target.table;
    let ref_table = table_name_map
        .get(ref_table_struct)
        .cloned()
        .unwrap_or_else(|| apply_casing(ref_table_struct, casing));
    let ref_column = field_name_map
        .get(&(ref_table_struct.to_string(), target.field.to_string()))
        .cloned()
        .unwrap_or_else(|| apply_casing(target.field, casing));
    let ref_schema = table_schemas
        .get(ref_table_struct)
        .cloned()
        .unwrap_or_else(|| "public".to_string());
    let fk_name = format!("{table_name}_{col_name}_{ref_table}_{ref_column}_fk");

    Some(ForeignKey {
        schema: schema_name.to_string().into(),
        table: table_name.to_string().into(),
        name: fk_name.into(),
        name_explicit: false,
        columns: Cow::Owned(vec![Cow::Owned(col_name.to_string())]),
        schema_to: ref_schema.into(),
        table_to: ref_table.into(),
        columns_to: Cow::Owned(vec![Cow::Owned(ref_column)]),
        on_update: field.on_update().map(Cow::Owned),
        on_delete: field.on_delete().map(Cow::Owned),
        deferrable: false,
        initially_deferred: false,
    })
}

/// Build an `SQLite` index from a parsed index
fn build_sqlite_index(
    index: &ParsedIndex,
    table_name_map: &HashMap<String, String>,
    field_name_map: &HashMap<(String, String), String>,
    casing: Casing,
) -> crate::sqlite::Index {
    use crate::sqlite::{Index, IndexColumn, IndexOrigin};

    let table_struct = index.table_name().unwrap_or_default();
    let table_name = table_name_map
        .get(table_struct)
        .cloned()
        .unwrap_or_else(|| apply_casing(table_struct, casing));
    let index_attrs = ParsedIndexAttrs::parse(&index.attr);
    let index_name = index_attrs
        .name
        .unwrap_or_else(|| apply_casing(&index.name, casing));

    let columns: Vec<IndexColumn> = index
        .columns
        .iter()
        .filter_map(|c| {
            let target = MemberRef::parse(c)?;
            let col_name = field_name_map
                .get(&(target.table.to_string(), target.field.to_string()))
                .cloned()
                .unwrap_or_else(|| apply_casing(target.field, casing));
            Some(IndexColumn::new(col_name))
        })
        .collect();

    Index {
        table: table_name.into(),
        name: index_name.into(),
        columns,
        is_unique: index.is_unique(),
        where_clause: None,
        origin: IndexOrigin::Manual,
    }
}

/// Build a `PostgreSQL` index from a parsed index
fn build_postgres_index(
    index: &ParsedIndex,
    table_name_map: &HashMap<String, String>,
    field_name_map: &HashMap<(String, String), String>,
    table_schemas: &HashMap<String, String>,
    casing: Casing,
) -> crate::postgres::Index {
    use crate::postgres::{Index, IndexColumn};

    let table_struct = index.table_name().unwrap_or_default();
    let table_name = table_name_map
        .get(table_struct)
        .cloned()
        .unwrap_or_else(|| apply_casing(table_struct, casing));
    let schema_name = table_schemas
        .get(table_struct)
        .cloned()
        .unwrap_or_else(|| "public".to_string());
    let index_attrs = ParsedIndexAttrs::parse(&index.attr);
    let index_name = index_attrs
        .name
        .unwrap_or_else(|| apply_casing(&index.name, casing));

    let columns: Vec<IndexColumn> = index
        .columns
        .iter()
        .filter_map(|c| {
            let target = MemberRef::parse(c)?;
            let col_name = field_name_map
                .get(&(target.table.to_string(), target.field.to_string()))
                .cloned()
                .unwrap_or_else(|| apply_casing(target.field, casing));
            Some(IndexColumn::new(col_name))
        })
        .collect();

    Index {
        schema: schema_name.into(),
        table: table_name.into(),
        name: index_name.into(),
        name_explicit: false,
        columns,
        is_unique: index.is_unique(),
        where_clause: index.where_clause().map(Cow::Owned),
        method: index.method().map(Cow::Owned),
        with: None,
        concurrently: index.is_concurrent(),
    }
}

/// Infer `SQLite` type from Rust type string
fn infer_sqlite_type(rust_type: &str) -> SQLiteType {
    match SQLiteTypeCategory::from_type_string(rust_type) {
        SQLiteTypeCategory::Unknown => SQLiteType::Any,
        category => category.to_sqlite_type().unwrap_or(SQLiteType::Any),
    }
}

/// Infer `PostgreSQL` type from Rust type string
fn infer_postgres_type(rust_type: &str) -> PostgreSQLType {
    let base_type = rust_type
        .trim()
        .strip_prefix("Option<")
        .and_then(|s| s.strip_suffix(">"))
        .unwrap_or(rust_type)
        .trim();

    match base_type {
        "u8" | "u16" | "u32" => PostgreSQLType::Integer,
        "u64" => PostgreSQLType::Bigint,
        "&str" | "str" => PostgreSQLType::Text,
        "[u8]" => PostgreSQLType::Bytea,
        _ if base_type.contains("Decimal") => PostgreSQLType::Numeric,
        _ => PgTypeCategory::from_type_string(rust_type)
            .to_postgres_type()
            .unwrap_or(PostgreSQLType::Text),
    }
}

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

    #[test]
    fn test_infer_sqlite_type() {
        assert_eq!(infer_sqlite_type("i32"), SQLiteType::Integer);
        assert_eq!(infer_sqlite_type("i64"), SQLiteType::Integer);
        assert_eq!(infer_sqlite_type("f64"), SQLiteType::Real);
        assert_eq!(infer_sqlite_type("String"), SQLiteType::Text);
        assert_eq!(
            infer_sqlite_type("compact_str::CompactString"),
            SQLiteType::Text
        );
        assert_eq!(infer_sqlite_type("bytes::Bytes"), SQLiteType::Blob);
        assert_eq!(
            infer_sqlite_type("smallvec::SmallVec<[u8; 16]>"),
            SQLiteType::Blob
        );
        assert_eq!(infer_sqlite_type("Option<String>"), SQLiteType::Text);
        assert_eq!(infer_sqlite_type("Vec<u8>"), SQLiteType::Blob);
        assert_eq!(infer_sqlite_type("Uuid"), SQLiteType::Blob);
        assert_eq!(infer_sqlite_type("uuid::Uuid"), SQLiteType::Blob);
        assert_eq!(infer_sqlite_type("Option<uuid::Uuid>"), SQLiteType::Blob);
    }

    #[test]
    fn test_infer_postgres_type() {
        assert_eq!(infer_postgres_type("i32"), PostgreSQLType::Integer);
        assert_eq!(infer_postgres_type("i64"), PostgreSQLType::Bigint);
        assert_eq!(infer_postgres_type("bool"), PostgreSQLType::Boolean);
        assert_eq!(infer_postgres_type("String"), PostgreSQLType::Text);
        assert_eq!(
            infer_postgres_type("compact_str::CompactString"),
            PostgreSQLType::Varchar
        );
        assert_eq!(
            infer_postgres_type("arrayvec::ArrayString<32>"),
            PostgreSQLType::Varchar
        );
        assert_eq!(infer_postgres_type("bytes::Bytes"), PostgreSQLType::Bytea);
        assert_eq!(
            infer_postgres_type("smallvec::SmallVec<[u8; 16]>"),
            PostgreSQLType::Bytea
        );
        assert_eq!(infer_postgres_type("Vec<u8>"), PostgreSQLType::Bytea);
        assert_eq!(infer_postgres_type("Uuid"), PostgreSQLType::Uuid);
        assert_eq!(
            infer_postgres_type("serde_json::Value"),
            PostgreSQLType::Jsonb
        );
    }

    #[test]
    fn test_postgres_snapshot_preserves_column_markers() {
        use crate::parser::SchemaParser;
        use crate::postgres::ddl::{GeneratedType, IdentityType, PostgresEntity};

        let code = r#"
#[PostgresTable(schema = "app")]
pub struct PgMarkers {
    #[column(serial, primary, default = 1)]
    pub id: i32,
    #[column(smallserial)]
    pub small_id: i16,
    #[column(bigserial)]
    pub big_id: i64,
    #[column(json)]
    pub json_doc: AppDoc,
    #[column(jsonb)]
    pub jsonb_doc: AppDoc,
    #[column(identity(by_default), default = 2)]
    pub identity_id: i32,
    #[column(generated(stored, "first_name || ' ' || last_name"), default = "'ignored'")]
    pub full_name: String,
    #[column(collate = "C")]
    pub sortable: String,
}
"#;

        let result = SchemaParser::parse(code);
        let snapshot = parse_result_to_snapshot(&result, Dialect::PostgreSQL, None);
        let snap = match snapshot {
            Snapshot::Postgres(s) => s,
            _ => panic!("Expected Postgres snapshot"),
        };

        let column = |name: &str| {
            snap.ddl
                .iter()
                .find_map(|entity| {
                    if let PostgresEntity::Column(column) = entity
                        && column.name.as_ref() == name
                    {
                        Some(column)
                    } else {
                        None
                    }
                })
                .expect("expected column")
        };

        assert_eq!(column("id").sql_type.as_ref(), "serial");
        assert!(column("id").identity.is_none());
        assert!(column("id").default.is_none());
        assert_eq!(column("small_id").sql_type.as_ref(), "smallserial");
        assert_eq!(column("big_id").sql_type.as_ref(), "bigserial");
        assert_eq!(column("json_doc").sql_type.as_ref(), "json");
        assert_eq!(column("jsonb_doc").sql_type.as_ref(), "jsonb");

        let identity = column("identity_id")
            .identity
            .as_ref()
            .expect("expected identity");
        assert_eq!(identity.type_, IdentityType::ByDefault);
        assert!(column("identity_id").default.is_none());

        let generated = column("full_name")
            .generated
            .as_ref()
            .expect("expected generated column");
        assert_eq!(generated.gen_type, GeneratedType::Stored);
        assert_eq!(
            generated.expression.as_ref(),
            "first_name || ' ' || last_name"
        );
        assert!(column("full_name").identity.is_none());
        assert!(column("full_name").default.is_none());

        assert_eq!(column("sortable").collate.as_deref(), Some("C"));
    }

    #[test]
    fn test_sqlite_uuid_snapshot_storage_respects_column_type() {
        use crate::parser::SchemaParser;
        use crate::sqlite::SqliteEntity;

        let code = r#"
#[SQLiteTable]
pub struct UuidStorage {
    #[column(primary)]
    pub id: i64,
    pub blob_uuid: uuid::Uuid,
    #[column(text)]
    pub text_uuid: uuid::Uuid,
    #[blob]
    pub legacy_blob_uuid: uuid::Uuid,
    #[text]
    pub legacy_text_uuid: uuid::Uuid,
}
"#;

        let result = SchemaParser::parse(code);
        let snapshot = parse_result_to_snapshot(&result, Dialect::SQLite, None);
        let snap = match snapshot {
            Snapshot::Sqlite(s) => s,
            _ => panic!("Expected SQLite snapshot"),
        };

        let column_type = |name: &str| {
            snap.ddl
                .iter()
                .find_map(|entity| {
                    if let SqliteEntity::Column(column) = entity
                        && column.name.as_ref() == name
                    {
                        Some(column.sql_type.as_ref())
                    } else {
                        None
                    }
                })
                .expect("expected column")
        };

        assert_eq!(column_type("blob_uuid"), "blob");
        assert_eq!(column_type("text_uuid"), "text");
        assert_eq!(column_type("legacy_blob_uuid"), "blob");
        assert_eq!(column_type("legacy_text_uuid"), "text");
    }

    /// Test that changing a column from Option<String> to String generates table recreation
    #[test]
    fn test_nullable_to_not_null_generates_migration() {
        use crate::parser::SchemaParser;
        use crate::sqlite::collection::SQLiteDDL;
        use crate::sqlite::diff::compute_migration;

        // Previous schema: email is nullable (Option<String>)
        let prev_code = r#"
#[SQLiteTable]
pub struct User {
    #[column(primary)]
    pub id: i64,
    pub name: String,
    pub email: Option<String>,
}
"#;

        // Current schema: email is NOT nullable (String)
        let cur_code = r#"
#[SQLiteTable]
pub struct User {
    #[column(primary)]
    pub id: i64,
    pub name: String,
    pub email: String,
}
"#;

        let prev_result = SchemaParser::parse(prev_code);
        let cur_result = SchemaParser::parse(cur_code);

        let prev_snapshot = parse_result_to_snapshot(&prev_result, Dialect::SQLite, None);
        let cur_snapshot = parse_result_to_snapshot(&cur_result, Dialect::SQLite, None);

        // Extract DDL from snapshots
        let (prev_ddl, cur_ddl) = match (&prev_snapshot, &cur_snapshot) {
            (Snapshot::Sqlite(p), Snapshot::Sqlite(c)) => (
                SQLiteDDL::from_entities(p.ddl.clone()),
                SQLiteDDL::from_entities(c.ddl.clone()),
            ),
            _ => panic!("Expected SQLite snapshots"),
        };

        // Check that previous email column is nullable and current is not
        let prev_email = prev_ddl
            .columns
            .one("user", "email")
            .expect("email column in prev");
        let cur_email = cur_ddl
            .columns
            .one("user", "email")
            .expect("email column in cur");
        assert!(!prev_email.not_null, "Previous email should be nullable");
        assert!(cur_email.not_null, "Current email should be NOT NULL");

        // Compute migration
        let migration = compute_migration(&prev_ddl, &cur_ddl);

        // Should have SQL statements for table recreation
        assert!(
            !migration.sql_statements.is_empty(),
            "Should generate migration SQL for nullable change"
        );

        // Verify individual SQL statements for table recreation pattern
        assert_eq!(migration.sql_statements[0], "PRAGMA foreign_keys=OFF;");
        assert!(
            migration.sql_statements[1].starts_with("CREATE TABLE `__new_user`"),
            "Expected CREATE TABLE `__new_user`, got: {}",
            migration.sql_statements[1]
        );
        assert!(
            migration.sql_statements[1].contains("`email` TEXT NOT NULL"),
            "New table should have NOT NULL on email: {}",
            migration.sql_statements[1]
        );
        assert_eq!(
            migration.sql_statements[2],
            "INSERT INTO `__new_user`(`id`, `name`, `email`) SELECT `id`, `name`, `email` FROM `user`;"
        );
        assert_eq!(migration.sql_statements[3], "DROP TABLE `user`;");
        assert_eq!(
            migration.sql_statements[4],
            "ALTER TABLE `__new_user` RENAME TO `user`;"
        );
        assert_eq!(migration.sql_statements[5], "PRAGMA foreign_keys=ON;");
    }

    /// Test that changing a column from String to Option<String> generates table recreation
    #[test]
    fn test_not_null_to_nullable_generates_migration() {
        use crate::parser::SchemaParser;
        use crate::sqlite::collection::SQLiteDDL;
        use crate::sqlite::diff::compute_migration;

        // Previous schema: email is NOT nullable (String)
        let prev_code = r#"
#[SQLiteTable]
pub struct User {
    #[column(primary)]
    pub id: i64,
    pub email: String,
}
"#;

        // Current schema: email is nullable (Option<String>)
        let cur_code = r#"
#[SQLiteTable]
pub struct User {
    #[column(primary)]
    pub id: i64,
    pub email: Option<String>,
}
"#;

        let prev_result = SchemaParser::parse(prev_code);
        let cur_result = SchemaParser::parse(cur_code);

        let prev_snapshot = parse_result_to_snapshot(&prev_result, Dialect::SQLite, None);
        let cur_snapshot = parse_result_to_snapshot(&cur_result, Dialect::SQLite, None);

        // Extract DDL from snapshots
        let (prev_ddl, cur_ddl) = match (&prev_snapshot, &cur_snapshot) {
            (Snapshot::Sqlite(p), Snapshot::Sqlite(c)) => (
                SQLiteDDL::from_entities(p.ddl.clone()),
                SQLiteDDL::from_entities(c.ddl.clone()),
            ),
            _ => panic!("Expected SQLite snapshots"),
        };

        // Compute migration
        let migration = compute_migration(&prev_ddl, &cur_ddl);

        // Should have SQL statements for table recreation
        assert!(
            !migration.sql_statements.is_empty(),
            "Should generate migration SQL for nullable change"
        );

        // Verify individual SQL statements for table recreation pattern
        assert_eq!(migration.sql_statements[0], "PRAGMA foreign_keys=OFF;");
        assert!(
            migration.sql_statements[1].starts_with("CREATE TABLE `__new_user`"),
            "Expected CREATE TABLE `__new_user`, got: {}",
            migration.sql_statements[1]
        );
        assert_eq!(migration.sql_statements[3], "DROP TABLE `user`;");
        assert_eq!(
            migration.sql_statements[4],
            "ALTER TABLE `__new_user` RENAME TO `user`;"
        );
        assert_eq!(migration.sql_statements[5], "PRAGMA foreign_keys=ON;");
    }

    #[test]
    fn test_postgres_schema_and_index_options_are_preserved() {
        use crate::parser::SchemaParser;
        use crate::postgres::ddl::PostgresEntity;

        let code = r#"
#[PostgresTable(schema = "auth")]
pub struct Users {
    #[column(primary)]
    pub id: i32,
}

#[PostgresTable(schema = "app")]
pub struct Sessions {
    #[column(primary)]
    pub id: i32,
    #[column(references = Users::id)]
    pub user_id: i32,
}

#[PostgresIndex(concurrent, method = "gin", where = "user_id > 0")]
pub struct SessionsUserIdx(Sessions::user_id);
"#;

        let result = SchemaParser::parse(code);
        let snapshot = parse_result_to_snapshot(&result, Dialect::PostgreSQL, None);

        let snap = match snapshot {
            Snapshot::Postgres(s) => s,
            _ => panic!("Expected Postgres snapshot"),
        };

        let has_auth_schema = snap
            .ddl
            .iter()
            .any(|e| matches!(e, PostgresEntity::Schema(s) if s.name.as_ref() == "auth"));
        let has_app_schema = snap
            .ddl
            .iter()
            .any(|e| matches!(e, PostgresEntity::Schema(s) if s.name.as_ref() == "app"));
        assert!(has_auth_schema, "missing auth schema entity");
        assert!(has_app_schema, "missing app schema entity");

        let fk = snap.ddl.iter().find_map(|e| {
            if let PostgresEntity::ForeignKey(fk) = e {
                Some(fk)
            } else {
                None
            }
        });
        let fk = fk.expect("expected foreign key");
        assert_eq!(fk.schema.as_ref(), "app");
        assert_eq!(fk.schema_to.as_ref(), "auth");

        let idx = snap.ddl.iter().find_map(|e| {
            if let PostgresEntity::Index(i) = e {
                Some(i)
            } else {
                None
            }
        });
        let idx = idx.expect("expected index");
        assert!(idx.concurrently);
        assert_eq!(idx.method.as_deref(), Some("gin"));
        assert_eq!(idx.where_clause.as_deref(), Some("user_id > 0"));
        assert_eq!(idx.schema.as_ref(), "app");
    }

    #[test]
    fn test_sqlite_table_options_and_pk_name_are_preserved() {
        use crate::parser::SchemaParser;
        use crate::sqlite::SqliteEntity;

        let code = r#"
#[SQLiteTable(strict, without_rowid)]
pub struct Accounts {
    #[column(primary)]
    pub id: i64,
}
"#;

        let result = SchemaParser::parse(code);
        let snapshot = parse_result_to_snapshot(&result, Dialect::SQLite, None);
        let snap = match snapshot {
            Snapshot::Sqlite(s) => s,
            _ => panic!("Expected SQLite snapshot"),
        };

        let table = snap.ddl.iter().find_map(|e| {
            if let SqliteEntity::Table(t) = e {
                Some(t)
            } else {
                None
            }
        });
        let table = table.expect("expected sqlite table");
        assert!(table.strict, "strict should be preserved");
        assert!(table.without_rowid, "without_rowid should be preserved");

        let pk = snap.ddl.iter().find_map(|e| {
            if let SqliteEntity::PrimaryKey(pk) = e {
                Some(pk)
            } else {
                None
            }
        });
        let pk = pk.expect("expected sqlite primary key");
        assert_eq!(pk.name.as_ref(), "accounts_pkey");
    }

    #[test]
    fn test_sqlite_casing_preserves_explicit_names() {
        use crate::parser::SchemaParser;
        use crate::sqlite::SqliteEntity;

        let code = r#"
#[SQLiteTable(name = "users_tbl")]
pub struct UsersTable {
    #[column(name = "user_id", primary)]
    pub userId: i64,
    pub emailAddress: String,
}

#[SQLiteIndex(name = "users_tbl_email_idx")]
pub struct UsersEmailIdx(UsersTable::emailAddress);
"#;

        let result = SchemaParser::parse(code);
        let snapshot = parse_result_to_snapshot(&result, Dialect::SQLite, Some(Casing::SnakeCase));
        let snap = match snapshot {
            Snapshot::Sqlite(s) => s,
            _ => panic!("Expected SQLite snapshot"),
        };

        let table = snap.ddl.iter().find_map(|e| {
            if let SqliteEntity::Table(t) = e {
                Some(t)
            } else {
                None
            }
        });
        let table = table.expect("expected sqlite table");
        assert_eq!(table.name.as_ref(), "users_tbl");

        let user_id = snap.ddl.iter().find_map(|e| {
            if let SqliteEntity::Column(c) = e
                && c.name.as_ref() == "user_id"
            {
                Some(c)
            } else {
                None
            }
        });
        assert!(user_id.is_some(), "expected explicit column name user_id");

        let email_col = snap.ddl.iter().find_map(|e| {
            if let SqliteEntity::Column(c) = e
                && c.name.as_ref() == "email_address"
            {
                Some(c)
            } else {
                None
            }
        });
        assert!(
            email_col.is_some(),
            "expected inferred snake_case column name"
        );

        let index = snap.ddl.iter().find_map(|e| {
            if let SqliteEntity::Index(i) = e {
                Some(i)
            } else {
                None
            }
        });
        let index = index.expect("expected sqlite index");
        assert_eq!(index.name.as_ref(), "users_tbl_email_idx");
    }

    #[test]
    fn test_postgres_casing_preserves_explicit_names() {
        use crate::parser::SchemaParser;
        use crate::postgres::ddl::PostgresEntity;

        let code = r#"
#[PostgresTable(schema = "auth", name = "users_tbl")]
pub struct UsersTable {
    #[column(name = "user_id", primary)]
    pub userId: i32,
    pub createdAt: String,
}

#[PostgresIndex(name = "users_tbl_created_idx")]
pub struct UsersCreatedIdx(UsersTable::createdAt);
"#;

        let result = SchemaParser::parse(code);
        let snapshot =
            parse_result_to_snapshot(&result, Dialect::PostgreSQL, Some(Casing::SnakeCase));
        let snap = match snapshot {
            Snapshot::Postgres(s) => s,
            _ => panic!("Expected Postgres snapshot"),
        };

        let table = snap.ddl.iter().find_map(|e| {
            if let PostgresEntity::Table(t) = e {
                Some(t)
            } else {
                None
            }
        });
        let table = table.expect("expected postgres table");
        assert_eq!(table.schema.as_ref(), "auth");
        assert_eq!(table.name.as_ref(), "users_tbl");

        let user_id = snap.ddl.iter().find_map(|e| {
            if let PostgresEntity::Column(c) = e
                && c.name.as_ref() == "user_id"
            {
                Some(c)
            } else {
                None
            }
        });
        assert!(user_id.is_some(), "expected explicit column name user_id");

        let created_at = snap.ddl.iter().find_map(|e| {
            if let PostgresEntity::Column(c) = e
                && c.name.as_ref() == "created_at"
            {
                Some(c)
            } else {
                None
            }
        });
        assert!(
            created_at.is_some(),
            "expected inferred snake_case column name created_at"
        );

        let index = snap.ddl.iter().find_map(|e| {
            if let PostgresEntity::Index(i) = e {
                Some(i)
            } else {
                None
            }
        });
        let index = index.expect("expected postgres index");
        assert_eq!(index.name.as_ref(), "users_tbl_created_idx");
        assert_eq!(index.schema.as_ref(), "auth");
    }
}