drizzle-migrations 0.1.16

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
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
//! `PostgreSQL` database introspection
//!
//! This module provides functionality to introspect an existing `PostgreSQL` database
//! and extract its schema as DDL entities, matching drizzle-kit introspect.ts

use super::ddl::{
    CheckConstraint, Column, Enum, ForeignKey, Index, IndexColumn, Policy, PostgresEntity,
    PrimaryKey, Role, Schema, Sequence, Table, UniqueConstraint, View,
};
use super::grammar::{is_system_namespace, is_system_role};
use super::snapshot::PostgresSnapshot;

/// Error type for introspection operations
#[derive(Debug, Clone)]
pub struct IntrospectError {
    pub message: String,
    pub table: Option<String>,
    pub schema: Option<String>,
}

impl std::fmt::Display for IntrospectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match (&self.schema, &self.table) {
            (Some(s), Some(t)) => {
                write!(f, "Introspection error for '{}.{}': {}", s, t, self.message)
            }
            (Some(s), None) => write!(f, "Introspection error in schema '{}': {}", s, self.message),
            (None, Some(t)) => write!(f, "Introspection error for '{}': {}", t, self.message),
            (None, None) => write!(f, "Introspection error: {}", self.message),
        }
    }
}

impl std::error::Error for IntrospectError {}

/// Result type for introspection
pub type IntrospectResult<T> = Result<T, IntrospectError>;

// =============================================================================
// Raw Query Result Types
// =============================================================================

/// Raw table info from `information_schema`
#[derive(Debug, Clone)]
pub struct RawTableInfo {
    pub schema: String,
    pub name: String,
    pub is_rls_enabled: bool,
    pub is_unlogged: bool,
    pub is_temporary: bool,
    pub tablespace: Option<String>,
    pub comment: Option<String>,
}

/// Raw column info from `information_schema`
#[derive(Debug, Clone)]
pub struct RawColumnInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub column_type: String,
    pub type_schema: Option<String>,
    pub not_null: bool,
    pub default_value: Option<String>,
    pub is_identity: bool,
    pub identity_type: Option<String>,
    pub is_generated: bool,
    pub generated_expression: Option<String>,
    pub generated_stored: bool,
    pub dimensions: Option<i32>,
    pub comment: Option<String>,
    pub ordinal_position: i32,
}

/// Raw enum info
#[derive(Debug, Clone)]
pub struct RawEnumInfo {
    pub schema: String,
    pub name: String,
    pub values: Vec<String>,
}

/// Raw sequence info
///
/// Value columns are `Option` because `pg_sequences` returns NULL when the
/// current user lacks privilege on the sequence.
#[derive(Debug, Clone)]
pub struct RawSequenceInfo {
    pub schema: String,
    pub name: String,
    pub data_type: Option<String>,
    pub start_value: Option<String>,
    pub min_value: Option<String>,
    pub max_value: Option<String>,
    pub increment: Option<String>,
    pub cycle: Option<bool>,
    pub cache_value: Option<String>,
    /// `schema.table` of the owning column when `pg_depend` records this
    /// sequence as auto-owned (serial or identity, deptype `a`/`i`);
    /// `None` for standalone, hand-managed sequences.
    pub owned_by: Option<String>,
}

/// Raw index info
#[derive(Debug, Clone)]
pub struct RawIndexInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub is_unique: bool,
    pub is_primary: bool,
    pub method: String,
    pub columns: Vec<RawIndexColumnInfo>,
    pub where_clause: Option<String>,
    pub concurrent: bool,
}

/// Raw index column info
#[derive(Debug, Clone)]
pub struct RawIndexColumnInfo {
    pub name: String,
    pub is_expression: bool,
    pub asc: bool,
    pub nulls_first: bool,
    pub opclass: Option<String>,
}

/// Raw foreign key info
#[derive(Debug, Clone)]
pub struct RawForeignKeyInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub columns: Vec<String>,
    pub schema_to: String,
    pub table_to: String,
    pub columns_to: Vec<String>,
    pub on_update: String,
    pub on_delete: String,
    pub deferrable: bool,
    pub initially_deferred: bool,
}

/// Raw primary key info
#[derive(Debug, Clone)]
pub struct RawPrimaryKeyInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub columns: Vec<String>,
}

/// Raw unique constraint info
#[derive(Debug, Clone)]
pub struct RawUniqueInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub columns: Vec<String>,
    pub nulls_not_distinct: bool,
    pub deferrable: bool,
    pub initially_deferred: bool,
}

/// Raw check constraint info
#[derive(Debug, Clone)]
pub struct RawCheckInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub expression: String,
}

/// Raw view info
#[derive(Debug, Clone)]
pub struct RawViewInfo {
    pub schema: String,
    pub name: String,
    pub definition: String,
    pub is_materialized: bool,
}

/// Raw policy info (RLS)
#[derive(Debug, Clone)]
pub struct RawPolicyInfo {
    pub schema: String,
    pub table: String,
    pub name: String,
    pub as_clause: String,
    pub for_clause: String,
    pub to: Vec<String>,
    pub using: Option<String>,
    pub with_check: Option<String>,
}

/// Raw role info
#[derive(Debug, Clone)]
pub struct RawRoleInfo {
    pub name: String,
    pub create_db: bool,
    pub create_role: bool,
    pub inherit: bool,
}

/// Transport-decoded PostgreSQL catalog rows used by every driver.
#[derive(Debug, Clone, Default)]
pub struct RawIntrospection {
    pub schemas: Vec<Schema>,
    pub tables: Vec<RawTableInfo>,
    pub columns: Vec<RawColumnInfo>,
    pub enums: Vec<RawEnumInfo>,
    pub sequences: Vec<RawSequenceInfo>,
    pub views: Vec<RawViewInfo>,
    pub indexes: Vec<RawIndexInfo>,
    pub foreign_keys: Vec<RawForeignKeyInfo>,
    pub primary_keys: Vec<RawPrimaryKeyInfo>,
    pub unique_constraints: Vec<RawUniqueInfo>,
    pub check_constraints: Vec<RawCheckInfo>,
    pub roles: Vec<RawRoleInfo>,
    pub policies: Vec<RawPolicyInfo>,
}

/// Assemble transport-decoded PostgreSQL metadata into the canonical DDL.
#[must_use]
pub fn assemble_ddl(raw: RawIntrospection) -> super::PostgresDDL {
    let mut ddl = super::PostgresDDL::new();
    for schema in raw.schemas {
        ddl.schemas.push(schema);
    }
    for value in process_enums(&raw.enums) {
        ddl.enums.push(value);
    }
    for sequence in process_sequences(&raw.sequences) {
        ddl.sequences.push(sequence);
    }
    for role in process_roles(&raw.roles) {
        ddl.roles.push(role);
    }
    for policy in process_policies(&raw.policies) {
        ddl.policies.push(policy);
    }
    for table in process_tables(&raw.tables) {
        ddl.tables.push(table);
    }
    for column in process_columns(&raw.columns) {
        ddl.columns.push(column);
    }
    for index in process_indexes(&raw.indexes) {
        ddl.indexes.push(index);
    }
    for foreign_key in process_foreign_keys(&raw.foreign_keys) {
        ddl.fks.push(foreign_key);
    }
    for primary_key in process_primary_keys(&raw.primary_keys) {
        ddl.pks.push(primary_key);
    }
    for unique in process_unique_constraints(&raw.unique_constraints) {
        ddl.uniques.push(unique);
    }
    for check in process_check_constraints(&raw.check_constraints) {
        ddl.checks.push(check);
    }
    for view in process_views(&raw.views) {
        ddl.views.push(view);
    }
    ddl
}

// =============================================================================
// Introspection Result
// =============================================================================

/// Introspection result containing all extracted entities
#[derive(Debug, Clone, Default)]
pub struct IntrospectionResult {
    pub schemas: Vec<Schema>,
    pub enums: Vec<Enum>,
    pub sequences: Vec<Sequence>,
    pub roles: Vec<Role>,
    pub tables: Vec<Table>,
    pub columns: Vec<Column>,
    pub indexes: Vec<Index>,
    pub foreign_keys: Vec<ForeignKey>,
    pub primary_keys: Vec<PrimaryKey>,
    pub unique_constraints: Vec<UniqueConstraint>,
    pub check_constraints: Vec<CheckConstraint>,
    pub views: Vec<View>,
    pub policies: Vec<Policy>,
    pub errors: Vec<IntrospectError>,
}

impl IntrospectionResult {
    /// Convert to a snapshot
    #[must_use]
    pub fn to_snapshot(&self) -> PostgresSnapshot {
        let mut snapshot = PostgresSnapshot::new();

        for schema in &self.schemas {
            snapshot.add_entity(PostgresEntity::Schema(schema.clone()));
        }
        for e in &self.enums {
            snapshot.add_entity(PostgresEntity::Enum(e.clone()));
        }
        for seq in &self.sequences {
            // Serial/identity-owned sequences were already dropped by
            // `process_sequences` (pg_depend ownership); everything left is a
            // real standalone sequence.
            snapshot.add_entity(PostgresEntity::Sequence(seq.clone()));
        }
        for role in &self.roles {
            snapshot.add_entity(PostgresEntity::Role(role.clone()));
        }
        for table in &self.tables {
            snapshot.add_entity(PostgresEntity::Table(table.clone()));
        }
        for column in &self.columns {
            snapshot.add_entity(PostgresEntity::Column(column.clone()));
        }
        for index in &self.indexes {
            snapshot.add_entity(PostgresEntity::Index(index.clone()));
        }
        for fk in &self.foreign_keys {
            snapshot.add_entity(PostgresEntity::ForeignKey(fk.clone()));
        }
        for pk in &self.primary_keys {
            snapshot.add_entity(PostgresEntity::PrimaryKey(pk.clone()));
        }
        for unique in &self.unique_constraints {
            snapshot.add_entity(PostgresEntity::UniqueConstraint(unique.clone()));
        }
        for check in &self.check_constraints {
            snapshot.add_entity(PostgresEntity::CheckConstraint(check.clone()));
        }
        for view in &self.views {
            snapshot.add_entity(PostgresEntity::View(view.clone()));
        }
        for policy in &self.policies {
            snapshot.add_entity(PostgresEntity::Policy(policy.clone()));
        }

        snapshot
    }

    /// Check if introspection had any errors
    #[must_use]
    pub const fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Get all entities as a vector
    #[must_use]
    pub fn to_entities(&self) -> Vec<PostgresEntity> {
        let mut entities = Vec::new();

        for s in &self.schemas {
            entities.push(PostgresEntity::Schema(s.clone()));
        }
        for e in &self.enums {
            entities.push(PostgresEntity::Enum(e.clone()));
        }
        for s in &self.sequences {
            entities.push(PostgresEntity::Sequence(s.clone()));
        }
        for r in &self.roles {
            entities.push(PostgresEntity::Role(r.clone()));
        }
        for t in &self.tables {
            entities.push(PostgresEntity::Table(t.clone()));
        }
        for c in &self.columns {
            entities.push(PostgresEntity::Column(c.clone()));
        }
        for i in &self.indexes {
            entities.push(PostgresEntity::Index(i.clone()));
        }
        for f in &self.foreign_keys {
            entities.push(PostgresEntity::ForeignKey(f.clone()));
        }
        for p in &self.primary_keys {
            entities.push(PostgresEntity::PrimaryKey(p.clone()));
        }
        for u in &self.unique_constraints {
            entities.push(PostgresEntity::UniqueConstraint(u.clone()));
        }
        for c in &self.check_constraints {
            entities.push(PostgresEntity::CheckConstraint(c.clone()));
        }
        for v in &self.views {
            entities.push(PostgresEntity::View(v.clone()));
        }
        for p in &self.policies {
            entities.push(PostgresEntity::Policy(p.clone()));
        }

        entities
    }
}

// =============================================================================
// Processing Functions
// =============================================================================

/// Process raw table info into Table entities
#[must_use]
pub fn process_tables(raw_tables: &[RawTableInfo]) -> Vec<Table> {
    raw_tables
        .iter()
        .filter(|t| !is_system_namespace(&t.schema))
        .map(|t| Table {
            schema: t.schema.clone().into(),
            name: t.name.clone().into(),
            is_unlogged: if t.is_unlogged { Some(true) } else { None },
            is_temporary: if t.is_temporary { Some(true) } else { None },
            inherits: None,
            tablespace: t.tablespace.clone().map(Into::into),
            is_rls_enabled: Some(t.is_rls_enabled),
            comment: t.comment.clone().map(Into::into),
        })
        .collect()
}

/// Identity sequence options decoded from the packed `identity_type` column.
#[derive(Debug, Clone, Default)]
struct IdentityOptions {
    start: Option<String>,
    increment: Option<String>,
    min: Option<String>,
    max: Option<String>,
    cycle: Option<bool>,
}

/// Decode the `identity_type` column: either the JSON object emitted by
/// [`queries::COLUMNS_QUERY`] or a legacy plain `ALWAYS` / `BY DEFAULT`
/// string. Returns the identity type string plus any sequence options.
fn parse_identity_type(raw: &str) -> (String, IdentityOptions) {
    let trimmed = raw.trim();
    if trimmed.starts_with('{')
        && let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed)
    {
        let get = |key: &str| {
            value
                .get(key)
                .and_then(serde_json::Value::as_str)
                .map(ToString::to_string)
        };
        let type_str = get("type").unwrap_or_else(|| "ALWAYS".to_string());
        let options = IdentityOptions {
            start: get("start"),
            increment: get("increment"),
            min: get("min"),
            max: get("max"),
            cycle: value.get("cycle").and_then(serde_json::Value::as_bool),
        };
        return (type_str, options);
    }
    (trimmed.to_string(), IdentityOptions::default())
}

/// Process raw column info into Column entities
#[must_use]
pub fn process_columns(raw_columns: &[RawColumnInfo]) -> Vec<Column> {
    use super::ddl::{GeneratedType, IdentityType};

    raw_columns
        .iter()
        .filter(|c| !is_system_namespace(&c.schema))
        .map(|c| {
            let generated = if c.is_generated {
                c.generated_expression
                    .as_ref()
                    .map(|expr| super::ddl::Generated {
                        expression: expr.clone().into(),
                        gen_type: if c.generated_stored {
                            GeneratedType::Stored
                        } else {
                            GeneratedType::Virtual
                        },
                    })
            } else {
                None
            };

            let identity = if c.is_identity {
                c.identity_type.as_ref().map(|t| {
                    // `identity_type` is either the packed JSON object built
                    // by COLUMNS_QUERY ({type, start, increment, min, max,
                    // cycle}) or a legacy plain `ALWAYS` / `BY DEFAULT`
                    // string from hand-built rows.
                    let (type_str, options) = parse_identity_type(t);
                    let identity_type = if type_str.eq_ignore_ascii_case("always") {
                        IdentityType::Always
                    } else {
                        IdentityType::ByDefault
                    };
                    super::ddl::Identity {
                        name: format!("{}_{}_seq", c.table, c.name).into(),
                        schema: Some(c.schema.clone().into()),
                        type_: identity_type,
                        increment: options.increment.map(Into::into),
                        min_value: options.min.map(Into::into),
                        max_value: options.max.map(Into::into),
                        start_with: options.start.map(Into::into),
                        cache: None,
                        cycle: options.cycle,
                    }
                })
            } else {
                None
            };

            let dimensions = c.dimensions.filter(|dims| *dims > 0).or_else(|| {
                if c.column_type.starts_with('_') {
                    Some(1)
                } else {
                    None
                }
            });
            let column_type = if dimensions.is_some() {
                c.column_type
                    .strip_prefix('_')
                    .unwrap_or(&c.column_type)
                    .to_string()
            } else {
                c.column_type.clone()
            };

            Column {
                schema: c.schema.clone().into(),
                table: c.table.clone().into(),
                name: c.name.clone().into(),
                sql_type: column_type.into(),
                type_schema: c.type_schema.clone().map(std::convert::Into::into),
                not_null: c.not_null,
                default: c.default_value.clone().map(std::convert::Into::into),
                generated,
                identity,
                dimensions,
                comment: c.comment.clone().map(std::convert::Into::into),
                // pg_attribute exposes attcollation but we don't read it yet
                // (the introspect SQL doesn't pull it). Collation drift
                // detection requires extending the SELECT — defer to a
                // follow-up.
                collate: None,
                ordinal_position: Some(c.ordinal_position),
            }
        })
        .collect()
}

/// Process raw enum info into Enum entities
#[must_use]
pub fn process_enums(raw_enums: &[RawEnumInfo]) -> Vec<Enum> {
    raw_enums
        .iter()
        .filter(|e| !is_system_namespace(&e.schema))
        .map(|e| Enum {
            schema: e.schema.clone().into(),
            name: e.name.clone().into(),
            values: e.values.iter().map(|v| v.clone().into()).collect(),
        })
        .collect()
}

/// Process raw sequence info into Sequence entities.
///
/// Sequences auto-owned by a serial/identity column (per `pg_depend`) are
/// dropped here — PostgreSQL manages them, and surfacing them would make the
/// diff engine DROP them or CREATE duplicates. Hand-managed sequences are kept
/// even when their name matches the `{table}_{column}_seq` pattern.
#[must_use]
pub fn process_sequences(raw_sequences: &[RawSequenceInfo]) -> Vec<Sequence> {
    raw_sequences
        .iter()
        .filter(|s| !is_system_namespace(&s.schema) && s.owned_by.is_none())
        .map(|s| Sequence {
            schema: s.schema.clone().into(),
            name: s.name.clone().into(),
            increment_by: s.increment.clone().map(Into::into),
            min_value: s.min_value.clone().map(Into::into),
            max_value: s.max_value.clone().map(Into::into),
            start_with: s.start_value.clone().map(Into::into),
            cache_size: s.cache_value.as_deref().and_then(|v| v.parse().ok()),
            cycle: s.cycle,
        })
        .collect()
}

/// Process raw index info into Index entities
#[must_use]
pub fn process_indexes(raw_indexes: &[RawIndexInfo]) -> Vec<Index> {
    use super::ddl::Opclass;

    raw_indexes
        .iter()
        .filter(|i| !is_system_namespace(&i.schema) && !i.is_primary)
        .map(|i| {
            let columns: Vec<IndexColumn> = i
                .columns
                .iter()
                .map(|c| IndexColumn {
                    value: c.name.clone().into(),
                    is_expression: c.is_expression,
                    asc: c.asc,
                    nulls_first: c.nulls_first,
                    opclass: c.opclass.clone().map(Opclass::new),
                })
                .collect();

            Index {
                schema: i.schema.clone().into(),
                table: i.table.clone().into(),
                name: i.name.clone().into(),
                name_explicit: true,
                columns,
                is_unique: i.is_unique,
                where_clause: i.where_clause.clone().map(std::convert::Into::into),
                method: Some(i.method.clone().into()),
                concurrently: i.concurrent,
                r#with: None,
            }
        })
        .collect()
}

/// Process raw foreign key info into `ForeignKey` entities
#[must_use]
pub fn process_foreign_keys(raw_fks: &[RawForeignKeyInfo]) -> Vec<ForeignKey> {
    raw_fks
        .iter()
        .filter(|f| !is_system_namespace(&f.schema))
        .map(|f| ForeignKey {
            schema: f.schema.clone().into(),
            table: f.table.clone().into(),
            name: f.name.clone().into(),
            name_explicit: true,
            columns: f.columns.iter().map(|c| c.clone().into()).collect(),
            schema_to: f.schema_to.clone().into(),
            table_to: f.table_to.clone().into(),
            columns_to: f.columns_to.iter().map(|c| c.clone().into()).collect(),
            on_update: Some(f.on_update.clone().into()),
            on_delete: Some(f.on_delete.clone().into()),
            deferrable: f.deferrable,
            initially_deferred: f.initially_deferred,
        })
        .collect()
}

/// Process raw primary key info into `PrimaryKey` entities
#[must_use]
pub fn process_primary_keys(raw_pks: &[RawPrimaryKeyInfo]) -> Vec<PrimaryKey> {
    raw_pks
        .iter()
        .filter(|p| !is_system_namespace(&p.schema))
        .map(|p| PrimaryKey {
            schema: p.schema.clone().into(),
            table: p.table.clone().into(),
            name: p.name.clone().into(),
            name_explicit: true,
            columns: p.columns.iter().map(|c| c.clone().into()).collect(),
        })
        .collect()
}

/// Process raw unique constraint info into `UniqueConstraint` entities
#[must_use]
pub fn process_unique_constraints(raw_uniques: &[RawUniqueInfo]) -> Vec<UniqueConstraint> {
    raw_uniques
        .iter()
        .filter(|u| !is_system_namespace(&u.schema))
        .map(|u| UniqueConstraint {
            schema: u.schema.clone().into(),
            table: u.table.clone().into(),
            name: u.name.clone().into(),
            name_explicit: true,
            columns: u.columns.iter().map(|c| c.clone().into()).collect(),
            nulls_not_distinct: u.nulls_not_distinct,
            deferrable: u.deferrable,
            initially_deferred: u.initially_deferred,
        })
        .collect()
}

/// Process raw check constraint info into `CheckConstraint` entities
#[must_use]
pub fn process_check_constraints(raw_checks: &[RawCheckInfo]) -> Vec<CheckConstraint> {
    raw_checks
        .iter()
        .filter(|c| !is_system_namespace(&c.schema))
        .map(|c| CheckConstraint {
            schema: c.schema.clone().into(),
            table: c.table.clone().into(),
            name: c.name.clone().into(),
            value: c.expression.clone().into(),
        })
        .collect()
}

/// Process raw view info into View entities
#[must_use]
pub fn process_views(raw_views: &[RawViewInfo]) -> Vec<View> {
    raw_views
        .iter()
        .filter(|v| !is_system_namespace(&v.schema))
        .map(|v| View {
            schema: v.schema.clone().into(),
            name: v.name.clone().into(),
            definition: Some(v.definition.clone().into()),
            materialized: v.is_materialized,
            r#with: None,
            is_existing: false,
            with_no_data: None,
            using: None,
            tablespace: None,
        })
        .collect()
}

/// Process raw policy info into Policy entities
#[must_use]
pub fn process_policies(raw_policies: &[RawPolicyInfo]) -> Vec<Policy> {
    use std::borrow::Cow;

    raw_policies
        .iter()
        .filter(|p| !is_system_namespace(&p.schema))
        .map(|p| {
            let roles = p.to.iter().cloned().map(Cow::Owned).collect();

            Policy {
                schema: p.schema.clone().into(),
                table: p.table.clone().into(),
                name: p.name.clone().into(),
                as_clause: Some(p.as_clause.clone().into()),
                for_clause: Some(p.for_clause.clone().into()),
                to: Some(roles),
                using: p.using.clone().map(std::convert::Into::into),
                with_check: p.with_check.clone().map(std::convert::Into::into),
            }
        })
        .collect()
}

/// Process raw role info into Role entities
#[must_use]
pub fn process_roles(raw_roles: &[RawRoleInfo]) -> Vec<Role> {
    raw_roles
        .iter()
        .filter(|r| !is_system_role(&r.name))
        .map(|r| Role {
            name: r.name.clone().into(),
            superuser: None,
            create_db: Some(r.create_db),
            create_role: Some(r.create_role),
            inherit: Some(r.inherit),
            can_login: None,
            replication: None,
            bypass_rls: None,
            conn_limit: None,
            password: None,
            valid_until: None,
        })
        .collect()
}

// =============================================================================
// SQL Queries
// =============================================================================

/// SQL queries for `PostgreSQL` introspection
pub mod queries {
    /// Query to get all schemas
    pub const SCHEMAS_QUERY: &str = r"
        SELECT n.nspname AS name
        FROM pg_namespace n
        WHERE n.nspname NOT LIKE 'pg_%'
          AND n.nspname != 'information_schema'
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
        ORDER BY n.nspname
    ";

    /// Query to get all tables
    pub const TABLES_QUERY: &str = r"
        SELECT 
            n.nspname AS schema,
            c.relname AS name,
            c.relrowsecurity AS is_rls_enabled,
            c.relpersistence = 'u' AS is_unlogged,
            c.relpersistence = 't' AS is_temporary,
            tsp.spcname AS tablespace,
            obj_description(c.oid, 'pg_class') AS comment
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        LEFT JOIN pg_tablespace tsp ON tsp.oid = c.reltablespace
        WHERE c.relkind IN ('r', 'p')
          AND n.nspname NOT LIKE 'pg_%'
          AND n.nspname != 'information_schema'
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
          AND has_table_privilege(current_user, c.oid, 'SELECT')
        ORDER BY n.nspname, c.relname
    ";

    /// Query to get all columns.
    ///
    /// Result-column positions are load-bearing: every driver decodes rows
    /// by index. Two derived columns pack extra detail without changing the
    /// shape:
    ///
    /// - `column_type` appends the type modifier reconstructed from
    ///   `character_maximum_length` / `numeric_precision+scale`, so
    ///   `varchar(255)` and `numeric(10,2)` survive introspection instead of
    ///   degrading to bare `varchar` / `numeric`.
    /// - `identity_type` is a JSON object
    ///   `{type, start, increment, min, max, cycle}` built from
    ///   `information_schema.columns` identity metadata (the legacy plain
    ///   `ALWAYS` / `BY DEFAULT` strings are still accepted by
    ///   `process_columns` for hand-built rows).
    pub const COLUMNS_QUERY: &str = r"
        SELECT
            c.table_schema AS schema,
            c.table_name AS table,
            c.column_name AS name,
            c.udt_name || CASE
                WHEN c.data_type != 'ARRAY' AND c.character_maximum_length IS NOT NULL
                    THEN '(' || c.character_maximum_length || ')'
                WHEN c.udt_name IN ('numeric', 'decimal')
                     AND c.numeric_precision IS NOT NULL
                     AND c.numeric_scale IS NOT NULL
                    THEN '(' || c.numeric_precision || ',' || c.numeric_scale || ')'
                ELSE ''
            END AS column_type,
            c.udt_schema AS type_schema,
            c.is_nullable = 'NO' AS not_null,
            c.column_default AS default_value,
            c.is_identity = 'YES' AS is_identity,
            CASE
                WHEN c.is_identity = 'YES' THEN json_build_object(
                    'type', c.identity_generation,
                    'start', c.identity_start,
                    'increment', c.identity_increment,
                    'min', c.identity_minimum,
                    'max', c.identity_maximum,
                    'cycle', c.identity_cycle = 'YES'
                )::text
                ELSE NULL
            END AS identity_type,
            c.is_generated = 'ALWAYS' AS is_generated,
            c.generation_expression AS generated_expression,
            COALESCE(a.attgenerated = 's', false) AS generated_stored,
            NULLIF(a.attndims::int4, 0) AS dimensions,
            col_description(cls.oid, a.attnum) AS comment,
            c.ordinal_position
        FROM information_schema.columns c
        LEFT JOIN pg_namespace n
          ON n.nspname = c.table_schema
        LEFT JOIN pg_class cls
          ON cls.relnamespace = n.oid
         AND cls.relname = c.table_name
        LEFT JOIN pg_attribute a
          ON a.attrelid = cls.oid
         AND a.attname = c.column_name
         AND a.attnum > 0
         AND NOT a.attisdropped
        WHERE c.table_schema NOT LIKE 'pg_%'
          AND c.table_schema != 'information_schema'
          AND n.oid IS NOT NULL
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
        UNION ALL
        -- Materialized-view columns: information_schema.columns excludes
        -- matviews entirely, so read them straight from pg_attribute.
        SELECT
            mn.nspname AS schema,
            mc.relname AS table,
            ma.attname AS name,
            mt.typname || COALESCE(
                substring(format_type(ma.atttypid, ma.atttypmod) from '\(.*\)'),
                ''
            ) AS column_type,
            mtn.nspname AS type_schema,
            ma.attnotnull AS not_null,
            NULL::text AS default_value,
            FALSE AS is_identity,
            NULL::text AS identity_type,
            FALSE AS is_generated,
            NULL::text AS generated_expression,
            FALSE AS generated_stored,
            NULLIF(ma.attndims::int4, 0) AS dimensions,
            col_description(mc.oid, ma.attnum) AS comment,
            ma.attnum::int4 AS ordinal_position
        FROM pg_class mc
        JOIN pg_namespace mn ON mn.oid = mc.relnamespace
        JOIN pg_attribute ma ON ma.attrelid = mc.oid
        JOIN pg_type mt ON mt.oid = ma.atttypid
        JOIN pg_namespace mtn ON mtn.oid = mt.typnamespace
        WHERE mc.relkind = 'm'
          AND ma.attnum > 0
          AND NOT ma.attisdropped
          AND mn.nspname NOT LIKE 'pg_%'
          AND mn.nspname != 'information_schema'
          AND has_schema_privilege(current_user, mn.oid, 'USAGE')
          AND has_table_privilege(current_user, mc.oid, 'SELECT')
        ORDER BY 1, 2, 15
    ";

    /// Query to get all enums
    pub const ENUMS_QUERY: &str = r"
        SELECT 
            n.nspname AS schema,
            t.typname AS name,
            array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
        FROM pg_type t
        JOIN pg_enum e ON t.oid = e.enumtypid
        JOIN pg_namespace n ON n.oid = t.typnamespace
        WHERE n.nspname NOT LIKE 'pg_%'
          AND n.nspname != 'information_schema'
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
        GROUP BY n.nspname, t.typname
        ORDER BY n.nspname, t.typname
    ";

    /// Query to get all sequences
    ///
    /// Uses the underlying `pg_sequence` + `pg_class` catalog tables instead
    /// of the `pg_sequences` convenience view.  The view internally calls
    /// `pg_sequence_parameters()` which can fail when sequences are being
    /// dropped concurrently (e.g. during parallel test runs).  Direct
    /// catalog access is fully MVCC-protected and avoids this issue.
    ///
    /// Value columns are nullable because the current user may lack
    /// privilege on the sequence.
    pub const SEQUENCES_QUERY: &str = r"
        SELECT
            n.nspname AS schema,
            c.relname AS name,
            format_type(s.seqtypid, NULL)::text AS data_type,
            s.seqstart::text AS start_value,
            s.seqmin::text AS min_value,
            s.seqmax::text AS max_value,
            s.seqincrement::text AS increment,
            s.seqcycle AS cycle,
            s.seqcache::text AS cache_value,
            -- Owning column's schema.table when the sequence is auto-owned by
            -- a serial (deptype 'a') or identity (deptype 'i') column; NULL
            -- for standalone, hand-managed sequences.
            (
                SELECT format('%s.%s', dn.nspname, dc.relname)
                FROM pg_depend d
                JOIN pg_class dc ON dc.oid = d.refobjid
                JOIN pg_namespace dn ON dn.oid = dc.relnamespace
                WHERE d.objid = s.seqrelid
                  AND d.classid = 'pg_class'::regclass
                  AND d.refclassid = 'pg_class'::regclass
                  AND d.refobjsubid > 0
                  AND d.deptype IN ('a', 'i')
                LIMIT 1
            )::text AS owned_by
        FROM pg_sequence s
        JOIN pg_class c ON c.oid = s.seqrelid
        JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE n.nspname NOT LIKE 'pg_%'
          AND n.nspname != 'information_schema'
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
          AND (
              -- Reference s.seqrelid (not c.oid) so this qual only depends on
              -- pg_sequence: PostgreSQL 18's planner can push it down to the
              -- pg_class scan before the join filters to sequences, and
              -- has_sequence_privilege errors on non-sequence relations.
              has_sequence_privilege(current_user, s.seqrelid, 'USAGE')
              OR has_sequence_privilege(current_user, s.seqrelid, 'SELECT')
          )
        ORDER BY n.nspname, c.relname
    ";

    /// Query to get all views.
    ///
    /// Accepts `$1::text[]` — when non-NULL, scopes to those schemas;
    /// when NULL, returns all non-system views.
    pub const VIEWS_QUERY: &str = r"
        SELECT
            n.nspname AS schema,
            c.relname AS name,
            pg_get_viewdef(c.oid) AS definition,
            FALSE AS is_materialized
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE (
            ($1::text[] IS NOT NULL AND n.nspname = ANY($1::text[]))
            OR ($1::text[] IS NULL AND n.nspname NOT LIKE 'pg_%'
                AND n.nspname != 'information_schema')
        )
          AND c.relkind = 'v'
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
          AND has_table_privilege(current_user, c.oid, 'SELECT')
          AND pg_get_viewdef(c.oid) IS NOT NULL
        UNION ALL
        SELECT
            n.nspname AS schema,
            c.relname AS name,
            pg_get_viewdef(c.oid) AS definition,
            TRUE AS is_materialized
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE (
            ($1::text[] IS NOT NULL AND n.nspname = ANY($1::text[]))
            OR ($1::text[] IS NULL AND n.nspname NOT LIKE 'pg_%'
                AND n.nspname != 'information_schema')
        )
          AND c.relkind = 'm'
          AND has_schema_privilege(current_user, n.oid, 'USAGE')
          AND has_table_privilege(current_user, c.oid, 'SELECT')
          AND pg_get_viewdef(c.oid) IS NOT NULL
        ORDER BY schema, name
    ";

    /// Query to get all indexes
    pub const INDEXES_QUERY: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    idx.relname AS name,
    ix.indisunique AS is_unique,
    ix.indisprimary AS is_primary,
    am.amname AS method,
    array_agg(pg_get_indexdef(ix.indexrelid, s.n, true) ORDER BY s.n) AS columns,
    pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
FROM pg_index ix
JOIN pg_class idx ON idx.oid = ix.indexrelid
JOIN pg_class tbl ON tbl.oid = ix.indrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
JOIN pg_am am ON am.oid = idx.relam
JOIN generate_series(1, ix.indnkeyatts) AS s(n) ON TRUE
WHERE ns.nspname NOT LIKE 'pg_%'
  AND ns.nspname <> 'information_schema'
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
GROUP BY ns.nspname, tbl.relname, idx.relname, ix.indisunique, ix.indisprimary, am.amname, ix.indpred, ix.indrelid
ORDER BY ns.nspname, tbl.relname, idx.relname
";

    /// Schema-filtered variant of [`INDEXES_QUERY`].
    ///
    /// `pg_get_indexdef()` calls `relation_open()` which is not
    /// MVCC-protected and can fail if concurrent DDL drops an index.
    /// Scoping to specific schemas (`$1::text[]`) avoids encountering
    /// OIDs from schemas being modified by other sessions.
    pub const INDEXES_QUERY_FILTERED: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    idx.relname AS name,
    ix.indisunique AS is_unique,
    ix.indisprimary AS is_primary,
    am.amname AS method,
    array_agg(pg_get_indexdef(ix.indexrelid, s.n, true) ORDER BY s.n) AS columns,
    pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
FROM pg_index ix
JOIN pg_class idx ON idx.oid = ix.indexrelid
JOIN pg_class tbl ON tbl.oid = ix.indrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
JOIN pg_am am ON am.oid = idx.relam
JOIN generate_series(1, ix.indnkeyatts) AS s(n) ON TRUE
WHERE ns.nspname = ANY($1::text[])
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
GROUP BY ns.nspname, tbl.relname, idx.relname, ix.indisunique, ix.indisprimary, am.amname, ix.indpred, ix.indrelid
ORDER BY ns.nspname, tbl.relname, idx.relname
";

    /// Query to get all foreign keys
    pub const FOREIGN_KEYS_QUERY: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    con.conname AS name,
    array_agg(src.attname ORDER BY s.ord) AS columns,
    ns_to.nspname AS schema_to,
    tbl_to.relname AS table_to,
    array_agg(dst.attname ORDER BY s.ord) AS columns_to,
    con.confupdtype::text AS on_update,
    con.confdeltype::text AS on_delete,
    con.condeferrable AS deferrable,
    con.condeferred AS initially_deferred
FROM pg_constraint con
JOIN pg_class tbl ON tbl.oid = con.conrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
JOIN pg_class tbl_to ON tbl_to.oid = con.confrelid
JOIN pg_namespace ns_to ON ns_to.oid = tbl_to.relnamespace
JOIN unnest(con.conkey) WITH ORDINALITY AS s(attnum, ord) ON TRUE
JOIN pg_attribute src ON src.attrelid = tbl.oid AND src.attnum = s.attnum
JOIN unnest(con.confkey) WITH ORDINALITY AS r(attnum, ord) ON r.ord = s.ord
JOIN pg_attribute dst ON dst.attrelid = tbl_to.oid AND dst.attnum = r.attnum
WHERE con.contype = 'f'
  AND ns.nspname NOT LIKE 'pg_%'
  AND ns.nspname <> 'information_schema'
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
GROUP BY ns.nspname, tbl.relname, con.conname, ns_to.nspname, tbl_to.relname, con.confupdtype, con.confdeltype, con.condeferrable, con.condeferred
ORDER BY ns.nspname, tbl.relname, con.conname
";

    /// Query to get all primary keys
    pub const PRIMARY_KEYS_QUERY: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    con.conname AS name,
    array_agg(att.attname ORDER BY s.ord) AS columns
FROM pg_constraint con
JOIN pg_class tbl ON tbl.oid = con.conrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
JOIN unnest(con.conkey) WITH ORDINALITY AS s(attnum, ord) ON TRUE
JOIN pg_attribute att ON att.attrelid = tbl.oid AND att.attnum = s.attnum
WHERE con.contype = 'p'
  AND ns.nspname NOT LIKE 'pg_%'
  AND ns.nspname <> 'information_schema'
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
GROUP BY ns.nspname, tbl.relname, con.conname
ORDER BY ns.nspname, tbl.relname, con.conname
";

    /// Query to get all unique constraints.
    ///
    /// `nulls_not_distinct` reads `pg_index.indnullsnotdistinct` through the
    /// constraint's `conindid`. The column only exists on PostgreSQL 15+,
    /// so it is accessed through `to_jsonb(...) ->> 'indnullsnotdistinct'` —
    /// on older servers the key is simply absent and the value defaults to
    /// FALSE, keeping the query parseable on every supported version.
    pub const UNIQUES_QUERY: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    con.conname AS name,
    array_agg(att.attname ORDER BY s.ord) AS columns,
    COALESCE((
        SELECT (to_jsonb(ix) ->> 'indnullsnotdistinct')::bool
        FROM pg_index ix
        WHERE ix.indexrelid = con.conindid
    ), FALSE) AS nulls_not_distinct,
    con.condeferrable AS deferrable,
    con.condeferred AS initially_deferred
FROM pg_constraint con
JOIN pg_class tbl ON tbl.oid = con.conrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
JOIN unnest(con.conkey) WITH ORDINALITY AS s(attnum, ord) ON TRUE
JOIN pg_attribute att ON att.attrelid = tbl.oid AND att.attnum = s.attnum
WHERE con.contype = 'u'
  AND ns.nspname NOT LIKE 'pg_%'
  AND ns.nspname <> 'information_schema'
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
GROUP BY ns.nspname, tbl.relname, con.conname, con.conindid, con.condeferrable, con.condeferred
ORDER BY ns.nspname, tbl.relname, con.conname
";

    /// Query to get all check constraints
    pub const CHECKS_QUERY: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    con.conname AS name,
    pg_get_expr(con.conbin, con.conrelid) AS expression
FROM pg_constraint con
JOIN pg_class tbl ON tbl.oid = con.conrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
WHERE con.contype = 'c'
  AND ns.nspname NOT LIKE 'pg_%'
  AND ns.nspname <> 'information_schema'
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
ORDER BY ns.nspname, tbl.relname, con.conname
";

    /// Schema-filtered variant of [`CHECKS_QUERY`].
    ///
    /// `pg_get_expr()` calls `relation_open()` which is not MVCC-protected.
    /// Scoping to specific schemas avoids encountering OIDs from
    /// schemas being modified by other sessions.
    pub const CHECKS_QUERY_FILTERED: &str = r"
SELECT
    ns.nspname AS schema,
    tbl.relname AS table,
    con.conname AS name,
    pg_get_expr(con.conbin, con.conrelid) AS expression
FROM pg_constraint con
JOIN pg_class tbl ON tbl.oid = con.conrelid
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
WHERE con.contype = 'c'
  AND ns.nspname = ANY($1::text[])
  AND has_schema_privilege(current_user, ns.oid, 'USAGE')
  AND has_table_privilege(current_user, tbl.oid, 'SELECT')
ORDER BY ns.nspname, tbl.relname, con.conname
";

    /// Query to get all roles
    pub const ROLES_QUERY: &str = r"
SELECT
    rolname AS name,
    rolcreatedb AS create_db,
    rolcreaterole AS create_role,
    rolinherit AS inherit
FROM pg_roles
ORDER BY rolname
";

    /// Query to get all policies
    pub const POLICIES_QUERY: &str = r#"
SELECT
    n.nspname AS schema,
    c.relname AS table,
    p.polname AS name,
    CASE
        WHEN p.polpermissive THEN 'PERMISSIVE'::text
        ELSE 'RESTRICTIVE'::text
    END AS as_clause,
    CASE p.polcmd
        WHEN 'r'::"char" THEN 'SELECT'::text
        WHEN 'a'::"char" THEN 'INSERT'::text
        WHEN 'w'::"char" THEN 'UPDATE'::text
        WHEN 'd'::"char" THEN 'DELETE'::text
        WHEN '*'::"char" THEN 'ALL'::text
        ELSE NULL::text
    END AS for_clause,
    CASE
        WHEN p.polroles = '{0}'::oid[] THEN (string_to_array('public'::text, ''::text))::name[]
        ELSE ARRAY(
            SELECT pg_authid.rolname
            FROM pg_authid
            WHERE pg_authid.oid = ANY(p.polroles)
            ORDER BY pg_authid.rolname
        )
    END AS to,
    pg_get_expr(p.polqual, p.polrelid) AS using,
    pg_get_expr(p.polwithcheck, p.polrelid) AS with_check
FROM pg_policy p
JOIN pg_class c ON c.oid = p.polrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname NOT LIKE 'pg_%'
  AND n.nspname <> 'information_schema'
  AND has_schema_privilege(current_user, n.oid, 'USAGE')
  AND has_table_privilege(current_user, c.oid, 'SELECT')
ORDER BY n.nspname, c.relname, p.polname
"#;
}

// =============================================================================
// Utility Functions
// =============================================================================

/// Convert `PostgreSQL` foreign key action codes to human-readable strings.
///
/// `PostgreSQL` stores FK actions as single-character codes in `pg_constraint`.
#[must_use]
pub fn action_code_to_string(code: &str) -> String {
    match code {
        "r" => "RESTRICT",
        "c" => "CASCADE",
        "n" => "SET NULL",
        "d" => "SET DEFAULT",
        // "a" (NO ACTION) and any unknown code fall through to NO ACTION.
        _ => "NO ACTION",
    }
    .to_string()
}

/// Strip one trailing directive token (case-insensitive) from `value`,
/// returning the remainder when the directive was present at the end.
fn strip_trailing_directive<'a>(value: &'a str, directive: &str) -> Option<&'a str> {
    let value = value.trim_end();
    if value.len() <= directive.len() {
        return None;
    }
    let split = value.len() - directive.len();
    if !value.is_char_boundary(split) {
        return None;
    }
    let (head, tail) = value.split_at(split);
    if tail.eq_ignore_ascii_case(directive) && head.ends_with(char::is_whitespace) {
        Some(head.trim_end())
    } else {
        None
    }
}

/// Check whether a string is a plain (unquoted) SQL identifier.
fn is_plain_identifier(value: &str) -> bool {
    !value.is_empty()
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
        && value
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
}

/// Check whether every parenthesis in `value` is balanced and none of them
/// sit inside quotes we'd mis-parse. (Quotes are not tracked — good enough
/// for `pg_get_indexdef` output, which quotes identifiers, not parens.)
fn parens_balanced(value: &str) -> bool {
    let mut depth = 0_i32;
    for ch in value.chars() {
        match ch {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth < 0 {
                    return false;
                }
            }
            _ => {}
        }
    }
    depth == 0
}

/// Unquote a double-quoted identifier, unescaping doubled quotes
/// (`"userName"` → `userName`, `"say""hi"""` → `say"hi"`).
fn unquote_identifier(value: &str) -> Option<String> {
    let inner = value.strip_prefix('"')?.strip_suffix('"')?;
    Some(inner.replace("\"\"", "\""))
}

/// Parse raw index column strings from `pg_get_indexdef` into `RawIndexColumnInfo`.
///
/// Each string is a single column element like `"name"`, `"\"userName\" DESC"`,
/// `"lower(email) varchar_pattern_ops"`, `"(price * quantity)"`, or
/// `"col DESC NULLS LAST"`.
#[must_use]
pub fn parse_index_columns(cols: Vec<String>) -> Vec<RawIndexColumnInfo> {
    cols.into_iter()
        .map(|c| {
            let mut core = c.trim().to_string();

            // Strip trailing ordering directives only — never tokens inside
            // the expression itself. `NULLS FIRST`/`NULLS LAST` come after
            // `ASC`/`DESC` in pg_get_indexdef output.
            let mut nulls_first: Option<bool> = None;
            if let Some(rest) = strip_trailing_directive(&core, "NULLS FIRST") {
                nulls_first = Some(true);
                core = rest.to_string();
            } else if let Some(rest) = strip_trailing_directive(&core, "NULLS LAST") {
                nulls_first = Some(false);
                core = rest.to_string();
            }
            let asc = if let Some(rest) = strip_trailing_directive(&core, "DESC") {
                core = rest.to_string();
                false
            } else {
                if let Some(rest) = strip_trailing_directive(&core, "ASC") {
                    core = rest.to_string();
                }
                true
            };
            // In PostgreSQL, DESC implies NULLS FIRST unless NULLS LAST was
            // given explicitly; ASC implies NULLS LAST.
            let nulls_first = nulls_first.unwrap_or(!asc);

            // Split off a trailing operator class token, but only when the
            // remainder is still well-formed: the opclass must be a plain
            // identifier and the rest must have balanced parentheses.
            // Expressions like `(price * quantity)` stay verbatim.
            let mut opclass: Option<String> = None;
            if let Some(idx) = core.rfind(char::is_whitespace) {
                let candidate = core[idx..].trim();
                let rest = core[..idx].trim_end();
                if is_plain_identifier(candidate)
                    && (candidate.ends_with("_ops")
                        || super::grammar::VECTOR_OPS.contains(&candidate))
                    && !rest.is_empty()
                    && parens_balanced(rest)
                {
                    opclass = Some(candidate.to_string());
                    core = rest.to_string();
                }
            }

            // Plain quoted identifiers are unquoted (re-rendering quotes them
            // again); anything with expression syntax is stored verbatim.
            let (name, is_expression) = if let Some(unquoted) = unquote_identifier(&core) {
                (unquoted, false)
            } else if is_plain_identifier(&core) {
                (core, false)
            } else {
                (core, true)
            };

            RawIndexColumnInfo {
                name,
                is_expression,
                asc,
                nulls_first,
                opclass,
            }
        })
        .collect()
}

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

    #[test]
    fn test_process_tables() {
        let raw = vec![
            RawTableInfo {
                schema: "public".to_string(),
                name: "users".to_string(),
                is_unlogged: false,
                is_temporary: false,
                tablespace: None,
                comment: None,
                is_rls_enabled: false,
            },
            RawTableInfo {
                schema: "pg_catalog".to_string(),
                name: "pg_class".to_string(),
                is_unlogged: false,
                is_temporary: false,
                tablespace: None,
                comment: None,
                is_rls_enabled: false,
            },
        ];

        let tables = process_tables(&raw);
        assert_eq!(tables.len(), 1);
        assert_eq!(tables[0].name, "users");
    }

    #[test]
    fn test_introspection_result_to_snapshot() {
        let mut result = IntrospectionResult::default();
        result.schemas.push(Schema::new("public"));
        result.tables.push(Table {
            schema: "public".into(),
            name: "users".into(),
            is_unlogged: None,
            is_temporary: None,
            inherits: None,
            tablespace: None,
            is_rls_enabled: None,
            comment: None,
        });

        let snapshot = result.to_snapshot();
        assert_eq!(snapshot.ddl.len(), 2);
    }

    #[test]
    fn parse_index_columns_handles_realistic_indexdef_output() {
        let cols = parse_index_columns(vec![
            "(price * quantity)".to_string(),
            "\"userName\" DESC".to_string(),
            "lower(email) varchar_pattern_ops".to_string(),
            "col DESC NULLS LAST".to_string(),
            "\"say\"\"hi\"\"\"".to_string(),
            "plain_col".to_string(),
            "name text_pattern_ops".to_string(),
        ]);

        // Expression stays verbatim — no opclass split of `*` / `quantity)`.
        assert_eq!(cols[0].name, "(price * quantity)");
        assert!(cols[0].is_expression);
        assert_eq!(cols[0].opclass, None);
        assert!(cols[0].asc);
        assert!(!cols[0].nulls_first);

        // Quoted identifier is unquoted; DESC implies NULLS FIRST.
        assert_eq!(cols[1].name, "userName");
        assert!(!cols[1].is_expression);
        assert!(!cols[1].asc);
        assert!(cols[1].nulls_first);

        // Expression + trailing opclass token.
        assert_eq!(cols[2].name, "lower(email)");
        assert!(cols[2].is_expression);
        assert_eq!(cols[2].opclass.as_deref(), Some("varchar_pattern_ops"));

        // Explicit NULLS LAST wins over the DESC default.
        assert_eq!(cols[3].name, "col");
        assert!(!cols[3].asc);
        assert!(!cols[3].nulls_first);

        // Doubled quotes are unescaped.
        assert_eq!(cols[4].name, "say\"hi\"");
        assert!(!cols[4].is_expression);

        // Plain identifier, defaults.
        assert_eq!(cols[5].name, "plain_col");
        assert!(!cols[5].is_expression);
        assert!(cols[5].asc);
        assert!(!cols[5].nulls_first);

        // Identifier + opclass.
        assert_eq!(cols[6].name, "name");
        assert!(!cols[6].is_expression);
        assert_eq!(cols[6].opclass.as_deref(), Some("text_pattern_ops"));
    }

    #[test]
    fn process_columns_populates_identity_options_from_packed_json() {
        let raw = RawColumnInfo {
            schema: "public".to_string(),
            table: "users".to_string(),
            name: "id".to_string(),
            column_type: "int4".to_string(),
            type_schema: Some("pg_catalog".to_string()),
            not_null: true,
            default_value: None,
            is_identity: true,
            identity_type: Some(
                r#"{"type":"ALWAYS","start":"100","increment":"5","min":"1","max":"1000","cycle":true}"#
                    .to_string(),
            ),
            is_generated: false,
            generated_expression: None,
            generated_stored: false,
            dimensions: None,
            comment: None,
            ordinal_position: 1,
        };

        let columns = process_columns(&[raw]);
        let identity = columns[0].identity.as_ref().expect("identity");
        assert_eq!(identity.start_with.as_deref(), Some("100"));
        assert_eq!(identity.increment.as_deref(), Some("5"));
        assert_eq!(identity.min_value.as_deref(), Some("1"));
        assert_eq!(identity.max_value.as_deref(), Some("1000"));
        assert_eq!(identity.cycle, Some(true));
    }

    #[test]
    fn process_columns_accepts_legacy_plain_identity_type() {
        let raw = RawColumnInfo {
            schema: "public".to_string(),
            table: "users".to_string(),
            name: "id".to_string(),
            column_type: "int4".to_string(),
            type_schema: Some("pg_catalog".to_string()),
            not_null: true,
            default_value: None,
            is_identity: true,
            identity_type: Some("BY DEFAULT".to_string()),
            is_generated: false,
            generated_expression: None,
            generated_stored: false,
            dimensions: None,
            comment: None,
            ordinal_position: 1,
        };

        let columns = process_columns(&[raw]);
        let identity = columns[0].identity.as_ref().expect("identity");
        assert_eq!(identity.type_, super::super::ddl::IdentityType::ByDefault);
        assert_eq!(identity.increment, None);
    }

    #[test]
    fn postgres_catalog_queries_are_privilege_scoped() {
        use queries::{
            CHECKS_QUERY, COLUMNS_QUERY, ENUMS_QUERY, FOREIGN_KEYS_QUERY, INDEXES_QUERY,
            POLICIES_QUERY, PRIMARY_KEYS_QUERY, SCHEMAS_QUERY, SEQUENCES_QUERY, TABLES_QUERY,
            UNIQUES_QUERY, VIEWS_QUERY,
        };

        for query in [
            SCHEMAS_QUERY,
            TABLES_QUERY,
            COLUMNS_QUERY,
            ENUMS_QUERY,
            SEQUENCES_QUERY,
            VIEWS_QUERY,
            INDEXES_QUERY,
            FOREIGN_KEYS_QUERY,
            PRIMARY_KEYS_QUERY,
            UNIQUES_QUERY,
            CHECKS_QUERY,
            POLICIES_QUERY,
        ] {
            assert!(
                query.contains("has_schema_privilege"),
                "query is not schema-privilege scoped: {query}"
            );
        }

        for query in [
            TABLES_QUERY,
            VIEWS_QUERY,
            INDEXES_QUERY,
            FOREIGN_KEYS_QUERY,
            PRIMARY_KEYS_QUERY,
            UNIQUES_QUERY,
            CHECKS_QUERY,
            POLICIES_QUERY,
        ] {
            assert!(
                query.contains("has_table_privilege"),
                "query is not table-privilege scoped: {query}"
            );
        }
    }
}