yang-base 0.6.0

个人使用构建后端服务器
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
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! PostgreSQL schema 同步纯逻辑单元测试(不连接数据库)。

use super::super::dialect::{collations_equal, SchemaDialect};
use super::super::model::{ExistingCheck, ExistingForeignKey, SchemaPreflightCheck};
use super::super::plan::{
    dedupe_native_enum_steps, expression_references_column, validate_shared_native_enums,
};
use super::super::plan_table_sync_with;
use super::super::{ExistingIndex, ExistingTableSchema, SchemaSyncChangeKind};
use crate::error::BaseError;
use crate::table::{Field, FieldType, SchemaColumn, Table, TableDefinition};
use std::collections::{BTreeMap, BTreeSet};

fn account_table() -> TableDefinition {
    Table::new("pg_accounts")
        .fields([
            Field::id("id"),
            Field::string("username", 32).required().unique(),
        ])
        .build()
        .expect("pg_accounts 表定义应有效")
}

fn account_table_with_default() -> TableDefinition {
    Table::new("pg_accounts")
        .fields([
            Field::id("id"),
            Field::string("username", 32)
                .required()
                .unique()
                .default("guest"),
        ])
        .build()
        .expect("pg_accounts 表定义应有效")
}

fn plain_table() -> TableDefinition {
    Table::new("pg_profile")
        .fields([
            Field::id("id"),
            Field::string("nickname", 32).required().comment("昵称"),
        ])
        .build()
        .expect("pg_profile 表定义应有效")
}

fn identity(id: &str) -> BTreeSet<String> {
    BTreeSet::from([id.to_string()])
}

fn plain_existing() -> ExistingTableSchema {
    ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("nickname", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_comments(BTreeMap::from([(
        "nickname".to_string(),
        "昵称".to_string(),
    )]))
}

#[test]
fn create_table_without_primary_key_omits_pk_clause() {
    let table = Table::new("pg_no_pk")
        .fields([Field::string("name", 32).required()])
        .build()
        .expect("无主键表定义应有效");
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("无主键表应生成建表计划");
    assert!(
        !plan.statements[0].contains("PRIMARY KEY"),
        "无主键表不得渲染 PRIMARY KEY: {}",
        plan.statements[0]
    );
}

#[test]
fn create_table_renders_composite_primary_key() {
    let table = Table::new("pg_composite")
        .fields([
            Field::bigint("tenant_id").required().primary_key(),
            Field::bigint("item_id").required().primary_key(),
        ])
        .build()
        .expect("复合主键表定义应有效");
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("复合主键应生成建表计划");
    let create = &plan.statements[0];
    assert!(
        create.contains("PRIMARY KEY (\"tenant_id\", \"item_id\")"),
        "复合主键必须按声明顺序渲染: {create}"
    );
}

#[test]
fn create_table_uses_postgres_dialect_without_engine_or_inline_key() {
    let table = account_table();
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("新表应生成 PostgreSQL 建表计划");

    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::CreatedTable);
    let create = &plan.statements[0];
    assert!(create.starts_with("CREATE TABLE \"pg_accounts\""));
    assert!(!create.contains("ENGINE"));
    assert!(!create.contains("UNIQUE KEY"));
    assert!(!create.contains(", KEY"));
    assert!(create.contains("\"id\" BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY"));
    assert!(create.contains("PRIMARY KEY (\"id\")"));
    assert!(
        plan.statements
            .iter()
            .any(|statement| statement.contains("CREATE UNIQUE INDEX \"uk_pg_accounts_username\"")),
        "PostgreSQL 索引必须独立创建: {:?}",
        plan.statements
    );
}

#[test]
fn modify_column_renders_type_null_and_default_statements() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("username", "varchar", "varchar(8)", true, Some(8), None),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_pg_accounts_username",
            true,
            vec!["username".to_string()],
        )],
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &account_table_with_default(),
        &existing,
    )
    .expect("受支持的列变更应生成 PostgreSQL 修改计划");

    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::ModifiedColumn);
    let statements = plan.statements.join("; ");
    assert!(statements.contains(
        "ALTER TABLE \"pg_accounts\" ALTER COLUMN \"username\" TYPE VARCHAR(32) \
         USING \"username\"::VARCHAR(32)"
    ));
    assert!(statements.contains("ALTER COLUMN \"username\" SET NOT NULL"));
    assert!(statements.contains("ALTER COLUMN \"username\" SET DEFAULT 'guest'"));
}

#[test]
fn compatible_identity_and_postgres_default_are_noop() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new(
                "username",
                "varchar",
                "varchar(32)",
                false,
                Some(32),
                Some("'guest'::character varying".to_string()),
            ),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_pg_accounts_username",
            true,
            vec!["username".to_string()],
        )],
    )
    .with_column_kinds(identity("id"), BTreeMap::new());

    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &account_table_with_default(),
        &existing,
    )
    .expect("identity 与 PG 默认值写法不应被视为漂移");
    assert!(plan.changes.is_empty());
}

/// 自增判定只认 pg_catalog 的 identity/serial 集合,不解析 column_type 文本。
#[test]
fn identity_is_read_from_catalog_not_column_type() {
    let catalog_identity = ExistingTableSchema::existing(
        vec![
            // column_type 干净,identity 来自 attidentity。
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_pg_accounts_username",
            true,
            vec!["username".to_string()],
        )],
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    assert!(plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &account_table(),
        &catalog_identity
    )
    .expect("catalog identity 应视为一致")
    .changes
    .is_empty());

    let string_marker_only = ExistingTableSchema::existing(
        vec![
            // 只有 column_type 字符串标记,没有 catalog identity -> 必须报漂移。
            SchemaColumn::new("id", "bigint", "bigint auto_increment", false, None, None),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        vec![ExistingIndex::new(
            "uk_pg_accounts_username",
            true,
            vec!["username".to_string()],
        )],
    )
    .with_column_kinds(BTreeSet::new(), BTreeMap::new());
    let error = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &account_table(),
        &string_marker_only,
    )
    .expect_err("column_type 文本不能替代 catalog identity");
    assert!(
        matches!(error, BaseError::DatabaseInitFailed(message) if message.contains("AutoIncrementMismatch"))
    );
}

#[test]
fn postgres_check_normalization_handles_casts_any_array_and_literals() {
    let dialect = SchemaDialect::PostgreSql;
    assert_eq!(
        dialect.normalize_check_expression("CHECK ((schema_version >= 0))"),
        dialect.normalize_check_expression("\"schema_version\" >= 0")
    );
    assert_eq!(
        dialect.normalize_check_expression(
            "CHECK (((status)::text = ANY ((ARRAY['active'::text, 'disabled'::text]))))"
        ),
        dialect.normalize_check_expression("\"status\" IN ('active', 'disabled')")
    );
    // 字符串字面量内容必须保留,空格差异不能被归一。
    assert_ne!(
        dialect.normalize_check_expression("\"a\" <> ' '"),
        dialect.normalize_check_expression("\"a\" <> ''")
    );
}

#[test]
fn postgres_multi_clause_check_normalization_folds_pg_grouping() {
    let dialect = SchemaDialect::PostgreSql;
    // PostgreSQL 读回时会给每个布尔操作数补分组括号,必须与声明文本等价。
    assert_eq!(
        dialect.normalize_check_expression("CHECK (((score >= 0) AND (status <> 'banned'::text)))"),
        dialect.normalize_check_expression("\"score\" >= 0 AND \"status\" <> 'banned'")
    );
    assert_eq!(
        dialect.normalize_check_expression("CHECK (((a >= 10) OR (a < 20)))"),
        dialect.normalize_check_expression("\"a\" >= 10 OR \"a\" < 20")
    );
    assert_eq!(
        dialect.normalize_check_expression("CHECK ((((a >= 0) AND (b < 5)) OR (c = 2)))"),
        dialect.normalize_check_expression("(\"a\" >= 0 AND \"b\" < 5) OR \"c\" = 2")
    );
    assert_eq!(
        dialect.normalize_check_expression("CHECK ((NOT ((a >= 0) AND (b < 5))))"),
        dialect.normalize_check_expression("NOT (\"a\" >= 0 AND \"b\" < 5)")
    );
    // 括号改变布尔结合方式时不得误判相等。
    assert_ne!(
        dialect.normalize_check_expression("(\"a\" = 1 AND \"b\" = 2) OR \"c\" = 3"),
        dialect.normalize_check_expression("\"a\" = 1 AND (\"b\" = 2 OR \"c\" = 3)")
    );
    assert_ne!(
        dialect.normalize_check_expression("(\"a\" = 1 OR \"b\" = 2) AND \"c\" = 3"),
        dialect.normalize_check_expression("\"a\" = 1 OR (\"b\" = 2 AND \"c\" = 3)")
    );
}

#[test]
fn postgres_check_normalization_keeps_parentheses_right_of_comparison_operator() {
    let dialect = SchemaDialect::PostgreSql;
    // `flag = (x AND y)` 与 `(flag = x) AND y` 语义不同,不得归一为同一表达式。
    assert_ne!(
        dialect.normalize_check_expression("flag = (x AND y)"),
        dialect.normalize_check_expression("(flag = x) AND y")
    );
    // 表达式开头 / `(` 后 / AND|OR|NOT 后的布尔分组仍按既有规则折叠。
    assert_eq!(
        dialect.normalize_check_expression("((a AND b) OR c)"),
        dialect.normalize_check_expression("(a AND b) OR c")
    );
    assert_ne!(
        dialect.normalize_check_expression("(a AND b) OR c"),
        dialect.normalize_check_expression("a AND (b OR c)")
    );
    assert_eq!(
        dialect.normalize_check_expression("(flag = x) AND y"),
        dialect.normalize_check_expression("flag = x AND y")
    );
}

#[test]
fn check_column_matching_follows_postgres_identifier_case_folding() {
    // 未加双引号的标识符按 PostgreSQL 规则折叠为小写,大小写不敏感匹配。
    assert!(expression_references_column("SCORE >= 0", "score"));
    assert!(expression_references_column(
        "Score >= 0 AND status <> 'banned'",
        "score"
    ));
    assert!(expression_references_column("scOre >= 0", "score"));
    // 双引号标识符精确匹配,`"SCORE"` 不等同于列 score。
    assert!(!expression_references_column("\"SCORE\" >= 0", "score"));
    assert!(expression_references_column("\"score\" >= 0", "score"));
    // 单引号字符串字面量中的同名文本不算列引用。
    assert!(!expression_references_column("status <> 'score'", "score"));
}

#[test]
fn index_name_longer_than_63_bytes_is_rejected() {
    let long_name = "i".repeat(64);
    let table = Table::new("pg_long_index")
        .fields([Field::id("id"), Field::string("username", 32)])
        .index_named(long_name, ["username"])
        .build()
        .expect("测试表定义应有效");

    let error = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect_err("超过 63 字节的显式索引名必须拒绝");
    assert!(matches!(error, BaseError::ConfigError(message) if message.contains("63")));
}

#[test]
fn index_names_must_be_unique_within_schema() {
    let first = Table::new("pg_first")
        .fields([Field::id("id"), Field::string("name", 16)])
        .index_named("idx_shared_name", ["name"])
        .build()
        .expect("第一张表应有效");
    let second = Table::new("pg_second")
        .fields([Field::id("id"), Field::string("name", 16)])
        .index_named("idx_shared_name", ["name"])
        .build()
        .expect("第二张表应有效");
    let error = SchemaDialect::PostgreSql
        .normalize_definitions(&[&first, &second])
        .expect_err("同一 schema 内跨表重复索引名必须拒绝");
    assert!(matches!(error, BaseError::ConfigError(message) if message.contains("schema")));
}

#[test]
fn explicit_identifiers_longer_than_63_bytes_fail_closed() {
    // PostgreSQL 标识符上限是 63 字节。`TableRef`/`FieldRef` 已在构建期按同一上限
    // 拒绝超长名称,因此同步层不会再看到 64 字节标识符;这里断言 fail-closed。
    let long_table = Table::new("t".repeat(64)).fields([Field::id("id")]).build();
    assert!(long_table.is_err(), "64 字节表名必须在构建期拒绝");

    let long_field = Table::new("pg_long_field")
        .fields([Field::id("i".repeat(64))])
        .build();
    assert!(long_field.is_err(), "64 字节字段名必须在构建期拒绝");
}

/// 自动生成的索引名超长时用稳定 hash 截断,而不是拒绝或让服务端静默截断。
#[test]
fn generated_index_names_are_truncated_stably() {
    let table = Table::new("t".repeat(30))
        .fields([Field::id("id"), Field::string("c".repeat(29), 32)])
        .index([("c".repeat(29)).as_str()])
        .build()
        .expect("长名字表定义应有效");
    let first = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("自动索引名应可截断");
    let second = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("自动索引名应可截断");
    assert_eq!(first.statements, second.statements, "截断结果必须稳定");

    let index_statement = first
        .statements
        .iter()
        .find(|statement| statement.starts_with("CREATE INDEX"))
        .expect("应包含独立索引创建语句");
    let name = index_statement
        .split('"')
        .nth(1)
        .expect("索引语句应包含引号内名称");
    assert!(name.len() <= 63, "截断后索引名长度必须 <= 63: {name}");
    assert!(name.contains('_'), "截断名应保留前缀与 hash 分隔符: {name}");
}

// ---- P0-02 + P1-06:Enum -> varchar + CHECK ----

fn enum_table() -> TableDefinition {
    Table::new("pg_enum")
        .fields([
            Field::id("id"),
            Field::enumeration("status", ["active", "disabled"]).required(),
        ])
        .build()
        .expect("枚举表定义应有效")
}

#[test]
fn enum_columns_render_varchar_and_check() {
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &enum_table(),
        &ExistingTableSchema::missing(),
    )
    .expect("PostgreSQL 枚举应降级为 varchar + CHECK");
    let create = &plan.statements[0];
    assert!(create.contains("\"status\" VARCHAR(8) NOT NULL"));
    assert!(create.contains(
        "CONSTRAINT \"chk_pg_enum_status\" CHECK (\"status\" IN ('active', 'disabled'))"
    ));
    assert!(!create.contains("ENUM"));
}

#[test]
fn enum_check_is_idempotent_on_second_sync() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("status", "varchar", "varchar(8)", false, Some(8), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_constraints(
        vec![ExistingCheck {
            name: "chk_pg_enum_status".to_string(),
            expression: "((status)::text = ANY ((ARRAY['active'::text, 'disabled'::text])))"
                .to_string(),
            validated: true,
        }],
        Vec::new(),
    );
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &enum_table(), &existing)
        .expect("已有等价 CHECK 时枚举必须幂等");
    assert!(plan.changes.is_empty(), "二次同步必须 no-op: {plan:?}");
}

#[test]
fn enum_check_on_existing_table_uses_not_valid_then_validate() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("status", "varchar", "varchar(8)", false, Some(8), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &enum_table(), &existing)
        .expect("缺失枚举 CHECK 应可在线添加");
    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::AddedCheck);
    assert_eq!(
        plan.statements,
        vec![
            "ALTER TABLE \"pg_enum\" ADD CONSTRAINT \"chk_pg_enum_status\" CHECK (\"status\" IN ('active', 'disabled')) NOT VALID",
            "ALTER TABLE \"pg_enum\" VALIDATE CONSTRAINT \"chk_pg_enum_status\"",
        ]
    );
    // VALIDATE 必须在事务提交后执行,避免 ACCESS EXCLUSIVE 锁持有到 COMMIT。
    assert_eq!(plan.steps.len(), 1);
    assert_eq!(
        plan.steps[0].statements,
        vec![
            "ALTER TABLE \"pg_enum\" ADD CONSTRAINT \"chk_pg_enum_status\" CHECK (\"status\" IN ('active', 'disabled')) NOT VALID"
        ]
    );
    assert_eq!(
        plan.steps[0].deferred_statements,
        vec!["ALTER TABLE \"pg_enum\" VALIDATE CONSTRAINT \"chk_pg_enum_status\""]
    );
}

#[test]
fn unvalidated_existing_check_is_self_healed_with_deferred_validate() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("status", "varchar", "varchar(8)", false, Some(8), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_constraints(
        vec![ExistingCheck {
            name: "chk_pg_enum_status".to_string(),
            expression: "((status)::text = ANY ((ARRAY['active'::text, 'disabled'::text])))"
                .to_string(),
            // NOT VALID 添加后尚未验证。
            validated: false,
        }],
        Vec::new(),
    );
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &enum_table(), &existing)
        .expect("未验证的同表达式 CHECK 应可自愈");
    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::ValidatedCheck);
    assert_eq!(plan.steps.len(), 1);
    assert!(plan.steps[0].statements.is_empty());
    assert_eq!(
        plan.steps[0].deferred_statements,
        vec!["ALTER TABLE \"pg_enum\" VALIDATE CONSTRAINT \"chk_pg_enum_status\""]
    );
    // 完整 SQL 文本仍需出现在 plan.statements 中。
    assert_eq!(
        plan.statements,
        vec!["ALTER TABLE \"pg_enum\" VALIDATE CONSTRAINT \"chk_pg_enum_status\""]
    );
}

// ---- P1-06:生成列与注释 ----

fn generated_table() -> TableDefinition {
    Table::new("pg_orders")
        .fields([
            Field::id("id"),
            Field::integer("price").required(),
            Field::bigint("total").required().generated("price * 2"),
        ])
        .build()
        .expect("生成列表定义应有效")
}

#[test]
fn generated_columns_render_stored_and_reflect_into_existing_schema() {
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &generated_table(),
        &ExistingTableSchema::missing(),
    )
    .expect("生成列应可建表");
    let create = &plan.statements[0];
    assert!(create.contains("\"total\" BIGINT NOT NULL GENERATED ALWAYS AS (price * 2) STORED"));
    assert!(!create.contains("\"total\" BIGINT NOT NULL DEFAULT"));

    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("price", "integer", "integer", false, None, None),
            SchemaColumn::new("total", "bigint", "bigint", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(
        identity("id"),
        BTreeMap::from([("total".to_string(), "(price * 2)".to_string())]),
    );
    assert!(
        plan_table_sync_with(SchemaDialect::PostgreSql, &generated_table(), &existing)
            .expect("等价生成表达式必须幂等")
            .changes
            .is_empty()
    );
}

#[test]
fn generated_expression_or_presence_drift_fails_closed() {
    let base = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("price", "integer", "integer", false, None, None),
            SchemaColumn::new("total", "bigint", "bigint", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let error = plan_table_sync_with(SchemaDialect::PostgreSql, &generated_table(), &base)
        .expect_err("生成列属性漂移必须拒绝");
    assert!(matches!(error, BaseError::DatabaseInitFailed(message) if message.contains("生成列")));

    let different = base.with_column_kinds(
        identity("id"),
        BTreeMap::from([("total".to_string(), "(price * 3)".to_string())]),
    );
    let error = plan_table_sync_with(SchemaDialect::PostgreSql, &generated_table(), &different)
        .expect_err("生成表达式漂移必须拒绝");
    assert!(matches!(error, BaseError::DatabaseInitFailed(message) if message.contains("生成列")));
}

#[test]
fn column_comments_are_emitted_only_when_different() {
    let existing = plain_existing();
    assert!(
        plan_table_sync_with(SchemaDialect::PostgreSql, &plain_table(), &existing)
            .expect("相同注释应幂等")
            .changes
            .is_empty()
    );

    let without_comment =
        ExistingTableSchema::existing(existing.columns.clone(), vec!["id".to_string()], Vec::new())
            .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &plain_table(), &without_comment)
        .expect("新增注释应生成计划");
    assert_eq!(plan.changes.len(), 1);
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::CommentedColumn);
    assert_eq!(
        plan.statements,
        vec!["COMMENT ON COLUMN \"pg_profile\".\"nickname\" IS '昵称'"]
    );
}

// ---- P1-07:collation ----

#[test]
fn collation_is_rendered_and_diffed() {
    let table = Table::new("pg_collated")
        .fields([
            Field::id("id"),
            Field::string("name", 32).required().collation("C"),
        ])
        .build()
        .expect("collation 表定义应有效");
    let create = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("collation 应可建表");
    assert!(create.statements[0].contains("\"name\" VARCHAR(32) COLLATE \"C\" NOT NULL"));

    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("name", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_collations(BTreeMap::from([("name".to_string(), "C".to_string())]));
    assert!(
        plan_table_sync_with(SchemaDialect::PostgreSql, &table, &existing)
            .expect("相同 collation 应幂等")
            .changes
            .is_empty()
    );

    let different =
        existing.with_collations(BTreeMap::from([("name".to_string(), "en_US".to_string())]));
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &table, &different)
        .expect("collation 漂移应生成修改计划");
    assert_eq!(plan.changes[0].kind, SchemaSyncChangeKind::ModifiedColumn);
    assert!(plan.statements[0].contains("TYPE VARCHAR(32) COLLATE \"C\""));
}

#[test]
fn removing_collation_resets_to_default() {
    let table = Table::new("pg_collated")
        .fields([Field::id("id"), Field::string("name", 32).required()])
        .build()
        .expect("表定义应有效");
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("name", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_collations(BTreeMap::from([("name".to_string(), "C".to_string())]));
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &table, &existing)
        .expect("移除显式 collation 应可重置");
    assert!(plan.statements[0].contains("COLLATE \"default\""));
}

#[test]
fn dotted_collation_names_are_quoted_as_one_identifier() {
    // libc collation 名称本身包含点号(en_US.utf8),不能被拆成 schema.name。
    let table = Table::new("pg_collated")
        .fields([
            Field::id("id"),
            Field::string("name", 32).required().collation("en_US.utf8"),
        ])
        .build()
        .expect("点号 collation 表定义应有效");
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect("点号 collation 应可建表");
    assert!(
        plan.statements[0].contains("COLLATE \"en_US.utf8\""),
        "整个名称必须作为单个标识符: {}",
        plan.statements[0]
    );
    assert!(!plan.statements[0].contains("\"en_US\".\"utf8\""));
}

#[test]
fn collation_name_injection_is_rejected() {
    let table = Table::new("pg_collated")
        .fields([
            Field::id("id"),
            Field::string("name", 32)
                .required()
                .collation("C\"; DROP TABLE x; --"),
        ])
        .build()
        .expect("构建期不解析 collation 字符");
    let error = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &table,
        &ExistingTableSchema::missing(),
    )
    .expect_err("非法 collation 名称必须拒绝");
    assert!(matches!(error, BaseError::ConfigError(message) if message.contains("collation")));
}

// ---- P1-14:在线 DDL ----

fn unique_existing() -> ExistingTableSchema {
    ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
}

#[test]
fn index_creation_on_existing_table_is_concurrent_and_outside_transaction() {
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &account_table(),
        &unique_existing(),
    )
    .expect("已有表加索引应使用并发路径");
    let step = plan
        .steps
        .iter()
        .find(|step| step.change.kind == SchemaSyncChangeKind::AddedIndex)
        .expect("应有索引步骤");
    assert!(step.concurrent, "并发索引步骤必须标记为事务外执行");
    assert!(step.statements[0].contains("CREATE UNIQUE INDEX CONCURRENTLY"));
}

#[test]
fn invalid_index_is_rebuilt_concurrently() {
    let invalid = ExistingIndex::new(
        "uk_pg_accounts_username",
        true,
        vec!["username".to_string()],
    )
    .with_valid(false);
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        vec![invalid],
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &account_table(), &existing)
        .expect("INVALID 索引应自愈");
    let step = plan
        .steps
        .iter()
        .find(|step| step.change.kind == SchemaSyncChangeKind::AddedIndex)
        .expect("应有索引重建步骤");
    assert!(step.concurrent);
    assert_eq!(
        step.statements,
        vec![
            "DROP INDEX CONCURRENTLY IF EXISTS \"uk_pg_accounts_username\"".to_string(),
            "CREATE UNIQUE INDEX CONCURRENTLY \"uk_pg_accounts_username\" ON \"pg_accounts\" (\"username\")".to_string(),
        ]
    );
}

#[test]
fn collations_equal_compares_full_names_and_normalizes_only_catalog_prefix() {
    // libc collation 的点号是名称的一部分:不同语言不能被截成相同的 `utf8`。
    assert!(!collations_equal(Some("en_US.utf8"), Some("de_DE.utf8")));
    assert!(collations_equal(Some("en_US.utf8"), Some("en_US.utf8")));
    // 只规范化真正的前缀与引号。
    assert!(collations_equal(Some("pg_catalog.C"), Some("C")));
    assert!(collations_equal(Some("C"), Some("\"C\"")));
    // PostgreSQL 引号标识符大小写敏感:`c` 与 `C` 是不同 collation。
    assert!(!collations_equal(Some("en_us.utf8"), Some("EN_US.UTF8")));
    assert!(!collations_equal(Some("c"), Some("C")));
    // `default` 等价于未显式指定(inspect 在 attcollation == typcollation 时返回 NULL)。
    assert!(collations_equal(Some("default"), None));
    assert!(collations_equal(Some("DEFAULT"), None));
    assert!(collations_equal(Some("\"default\""), None));
    assert!(collations_equal(Some("default"), Some("default")));
    // 未显式指定与显式指定其他 collation 不能视为相等。
    assert!(!collations_equal(None, Some("C")));
    assert!(collations_equal(None, None));
}

#[test]
fn default_collation_case_variants_render_as_lowercase_keyword() {
    // PostgreSQL 只识别 COLLATE "default";"DEFAULT"/"Default" 会报 42704。
    for name in ["default", "DEFAULT", "Default"] {
        let table = Table::new("pg_collated")
            .fields([
                Field::id("id"),
                Field::string("name", 32).required().collation(name),
            ])
            .build()
            .expect("default collation 表定义应有效");
        let plan = plan_table_sync_with(
            SchemaDialect::PostgreSql,
            &table,
            &ExistingTableSchema::missing(),
        )
        .expect("default collation 应可建表");
        assert!(
            plan.statements[0].contains("COLLATE \"default\""),
            "{name:?} 必须渲染为小写 default: {}",
            plan.statements[0]
        );
    }
}

#[test]
fn check_and_foreign_key_use_not_valid_then_validate() {
    let table = Table::new("pg_child")
        .fields([
            Field::id("id"),
            Field::integer("parent_id").required(),
            Field::integer("score").required(),
        ])
        .foreign_key_named("fk_child_parent", ["parent_id"], "pg_parent", ["id"])
        .check_named("chk_score_positive", "score >= 0")
        .build()
        .expect("含 CHECK/FK 的表定义应有效");
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("parent_id", "integer", "integer", false, None, None),
            SchemaColumn::new("score", "integer", "integer", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());

    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &table, &existing)
        .expect("CHECK/FK 应可在线添加");
    assert!(plan.statements.contains(
        &"ALTER TABLE \"pg_child\" ADD CONSTRAINT \"chk_score_positive\" CHECK (score >= 0) NOT VALID"
            .to_string()
    ));
    assert!(plan.statements.contains(
        &"ALTER TABLE \"pg_child\" VALIDATE CONSTRAINT \"chk_score_positive\"".to_string()
    ));
    assert!(plan.statements.iter().any(|statement| {
        statement.contains("ADD CONSTRAINT \"fk_child_parent\" FOREIGN KEY (\"parent_id\")")
            && statement.ends_with("NOT VALID")
    }));
    assert!(plan
        .statements
        .contains(&"ALTER TABLE \"pg_child\" VALIDATE CONSTRAINT \"fk_child_parent\"".to_string()));

    // 外键步骤:事务内只含 ADD ... NOT VALID,VALIDATE 放到外键事务提交后的 deferred。
    let foreign_key_step = plan
        .steps
        .iter()
        .find(|step| step.change.kind == SchemaSyncChangeKind::AddedForeignKey)
        .expect("应有外键步骤");
    assert!(!foreign_key_step.concurrent);
    assert_eq!(foreign_key_step.statements.len(), 1);
    assert!(
        foreign_key_step.statements[0].ends_with("NOT VALID"),
        "事务内只应含 NOT VALID: {:?}",
        foreign_key_step.statements
    );
    assert_eq!(
        foreign_key_step.deferred_statements,
        vec!["ALTER TABLE \"pg_child\" VALIDATE CONSTRAINT \"fk_child_parent\"".to_string()]
    );
}

#[test]
fn unvalidated_existing_foreign_key_is_self_healed_with_deferred_validate() {
    let table = Table::new("pg_child")
        .fields([Field::id("id"), Field::integer("parent_id").required()])
        .foreign_key_named("fk_child_parent", ["parent_id"], "pg_parent", ["id"])
        .build()
        .expect("含外键的表定义应有效");
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("parent_id", "integer", "integer", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_constraints(
        Vec::new(),
        vec![ExistingForeignKey {
            name: "fk_child_parent".to_string(),
            columns: vec!["parent_id".to_string()],
            referenced_table: "pg_parent".to_string(),
            referenced_columns: vec!["id".to_string()],
            update_rule: "NO ACTION".to_string(),
            delete_rule: "NO ACTION".to_string(),
            // NOT VALID 添加后尚未验证。
            validated: false,
        }],
    );

    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &table, &existing)
        .expect("未验证的同定义外键应可自愈");
    assert_eq!(plan.changes.len(), 1);
    assert_eq!(
        plan.changes[0].kind,
        SchemaSyncChangeKind::ValidatedForeignKey
    );
    assert_eq!(plan.steps.len(), 1);
    assert!(plan.steps[0].statements.is_empty());
    assert_eq!(
        plan.steps[0].deferred_statements,
        vec!["ALTER TABLE \"pg_child\" VALIDATE CONSTRAINT \"fk_child_parent\""]
    );
    assert!(plan
        .statements
        .contains(&"ALTER TABLE \"pg_child\" VALIDATE CONSTRAINT \"fk_child_parent\"".to_string()));
}

// ---- 部分索引/表达式索引反射 ----

fn indexed_account_existing(indexes: Vec<ExistingIndex>) -> ExistingTableSchema {
    ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("username", "varchar", "varchar(32)", false, Some(32), None),
        ],
        vec!["id".to_string()],
        indexes,
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
}

#[test]
fn plain_index_with_other_name_satisfies_declared_unique_index() {
    let existing = indexed_account_existing(vec![ExistingIndex::new(
        "uk_other_username",
        true,
        vec!["username".to_string()],
    )]);
    assert!(
        plan_table_sync_with(SchemaDialect::PostgreSql, &account_table(), &existing)
            .expect("普通唯一索引应满足声明")
            .changes
            .is_empty()
    );
}

#[test]
fn partial_unique_index_does_not_satisfy_full_unique_declaration() {
    // 部分唯一索引只约束谓词命中的行,不能代替完整唯一约束。
    let existing = indexed_account_existing(vec![ExistingIndex::new(
        "uk_partial_username",
        true,
        vec!["username".to_string()],
    )
    .with_predicate("(username IS NOT NULL)".to_string())]);
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &account_table(), &existing)
        .expect("部分索引不应覆盖完整唯一声明");
    assert!(
        plan.changes
            .iter()
            .any(|change| change.kind == SchemaSyncChangeKind::AddedIndex),
        "部分唯一索引不能阻止补建完整唯一索引: {plan:?}"
    );
}

#[test]
fn expression_index_does_not_satisfy_plain_column_declaration() {
    let existing = indexed_account_existing(vec![ExistingIndex::new(
        "uk_lower_username",
        true,
        Vec::new(),
    )
    .with_expressions(vec!["lower(username)".to_string()])]);
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &account_table(), &existing)
        .expect("表达式索引不应与普通列索引混淆");
    assert!(
        plan.changes
            .iter()
            .any(|change| change.kind == SchemaSyncChangeKind::AddedIndex),
        "表达式索引不能阻止补建普通列索引: {plan:?}"
    );
}

#[test]
fn same_named_partial_index_fails_closed_instead_of_recreating() {
    let existing = indexed_account_existing(vec![ExistingIndex::new(
        "uk_pg_accounts_username",
        true,
        vec!["username".to_string()],
    )
    .with_predicate("(username IS NOT NULL)".to_string())]);
    let error = plan_table_sync_with(SchemaDialect::PostgreSql, &account_table(), &existing)
        .expect_err("同名部分索引与声明定义不同,必须拒绝");
    assert!(
        matches!(&error, BaseError::DatabaseInitFailed(message) if message.contains("定义不同")),
        "应给出 fail-closed 定义冲突: {error}"
    );
}

// ---- 预检顺序:同一轮新增列上的 CHECK/FK ----

fn check_and_foreign_key_table() -> TableDefinition {
    Table::new("pg_child")
        .fields([
            Field::id("id"),
            Field::integer("parent_id").required(),
            Field::integer("score").required(),
        ])
        .foreign_key_named("fk_child_parent", ["parent_id"], "pg_parent", ["id"])
        .check_named("chk_score_positive", "score >= 0")
        .build()
        .expect("含 CHECK/FK 的表定义应有效")
}

#[test]
fn preflight_is_skipped_when_all_check_and_fk_columns_are_newly_added() {
    let existing = ExistingTableSchema::existing(
        vec![SchemaColumn::new(
            "id", "bigint", "bigint", false, None, None,
        )],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &check_and_foreign_key_table(),
        &existing,
    )
    .expect("新增列 + CHECK/FK 应可规划");
    assert!(
        plan.preflight.is_empty(),
        "新增列上的 CHECK/FK 不应生成引用缺失列的预检: {:?}",
        plan.preflight
    );
}

fn mixed_constraints_table() -> TableDefinition {
    Table::new("pg_mixed")
        .fields([
            Field::id("id"),
            Field::string("status", 32).required(),
            Field::integer("score").required(),
            Field::integer("parent_id").required(),
            Field::integer("code").required(),
        ])
        .unique_named("uk_pg_mixed_status_score", ["status", "score"])
        .check_named("chk_pg_mixed_score", "score >= 0 AND status <> 'banned'")
        .foreign_key_named(
            "fk_pg_mixed_parent",
            ["parent_id", "code"],
            "pg_parent",
            ["id", "code"],
        )
        .build()
        .expect("混合新增/既有列的约束表定义应有效")
}

#[test]
fn preflight_is_skipped_when_constraint_mixes_new_and_existing_columns() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("status", "varchar", "varchar(32)", false, Some(32), None),
            SchemaColumn::new("parent_id", "integer", "integer", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &mixed_constraints_table(),
        &existing,
    )
    .expect("混合新增/既有列的约束应可规划");
    assert!(
        plan.changes.iter().any(|change| {
            change.kind == SchemaSyncChangeKind::AddedColumn
                && matches!(change.object.as_str(), "score" | "code")
        }),
        "预计新增 score/code 列: {:?}",
        plan.changes
    );
    assert!(
        !plan.preflight.iter().any(|check| matches!(
            check,
            SchemaPreflightCheck::Check { .. }
                | SchemaPreflightCheck::ForeignKey { .. }
                | SchemaPreflightCheck::UniqueIndex { .. }
        )),
        "引用任一新增列的 CHECK/外键/唯一索引预检必须跳过: {:?}",
        plan.preflight
    );
}

#[test]
fn preflight_is_kept_for_check_and_fk_on_existing_columns() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("parent_id", "integer", "integer", false, None, None),
            SchemaColumn::new("score", "integer", "integer", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &check_and_foreign_key_table(),
        &existing,
    )
    .expect("既有列上的 CHECK/FK 应可规划");
    assert!(plan
        .preflight
        .iter()
        .any(|check| matches!(check, SchemaPreflightCheck::Check { .. })));
    assert!(plan
        .preflight
        .iter()
        .any(|check| matches!(check, SchemaPreflightCheck::ForeignKey { .. })));
}

// ---- DDL 类型渲染 ----

#[test]
fn postgres_type_rendering_matches_expected_ddl() {
    let dialect = SchemaDialect::PostgreSql;
    let cases = [
        (FieldType::Date, "DATE"),
        (FieldType::DateTime, "TIMESTAMPTZ"),
        (
            FieldType::Decimal {
                precision: 12,
                scale: 3,
            },
            "NUMERIC(12,3)",
        ),
        (FieldType::Boolean, "BOOLEAN"),
        (FieldType::Json, "JSONB"),
        (FieldType::Text, "TEXT"),
    ];
    for (field_type, expected) in cases {
        assert_eq!(
            dialect
                .render_type(&field_type, "sample")
                .expect("PostgreSQL 类型渲染应成功"),
            expected
        );
    }
}

// ---- 原生枚举 ----

fn native_enum_table(values: &[&str]) -> TableDefinition {
    Table::new("pg_orders")
        .fields([
            Field::id("id"),
            Field::enumeration("status", values.iter().copied())
                .required()
                .native_enum("order_status"),
        ])
        .build()
        .expect("原生枚举表定义应有效")
}

#[test]
fn native_enum_creates_type_before_table_and_omits_implicit_check() {
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &native_enum_table(&["pending", "paid"]),
        &ExistingTableSchema::missing(),
    )
    .expect("原生枚举建表计划应成功");
    assert_eq!(
        plan.statements[0],
        "CREATE TYPE \"order_status\" AS ENUM ('pending', 'paid')"
    );
    assert!(
        plan.statements[1].contains("\"status\" \"order_status\" NOT NULL"),
        "列必须直接使用原生枚举类型: {}",
        plan.statements[1]
    );
    assert!(
        !plan.statements.iter().any(|sql| sql.contains("CHECK")),
        "原生枚举不得再生成隐式 CHECK: {:?}",
        plan.statements
    );
}

#[test]
fn native_enum_missing_values_are_appended_before_other_changes() {
    let existing = ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("status", "enum", "order_status", false, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
    .with_enum_types(BTreeMap::from([(
        "order_status".to_string(),
        vec!["pending".to_string()],
    )]));
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &native_enum_table(&["pending", "paid"]),
        &existing,
    )
    .expect("补齐枚举取值应成功");
    assert_eq!(
        plan.statements[0],
        "ALTER TYPE \"order_status\" ADD VALUE IF NOT EXISTS 'paid'"
    );
    assert!(
        plan.changes
            .iter()
            .any(|change| change.kind == SchemaSyncChangeKind::AddedEnumValue),
        "必须报告新增枚举取值: {:?}",
        plan.changes
    );
    assert!(
        !plan
            .statements
            .iter()
            .any(|sql| sql.starts_with("ALTER TABLE")),
        "列类型已匹配时不得再修改列: {:?}",
        plan.statements
    );
}

#[test]
fn native_enum_created_before_added_column() {
    let existing = ExistingTableSchema::existing(
        vec![SchemaColumn::new(
            "id", "bigint", "bigint", false, None, None,
        )],
        vec!["id".to_string()],
        Vec::new(),
    )
    .with_column_kinds(identity("id"), BTreeMap::new());
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &native_enum_table(&["pending", "paid"]),
        &existing,
    )
    .expect("既有表补列计划应成功");
    assert_eq!(
        plan.statements[0],
        "CREATE TYPE \"order_status\" AS ENUM ('pending', 'paid')"
    );
    assert!(
        plan.statements
            .iter()
            .any(|sql| sql.starts_with("ALTER TABLE") && sql.contains("\"order_status\"")),
        "新增列必须引用原生枚举类型: {:?}",
        plan.statements
    );
}

#[cfg(feature = "mysql")]
#[test]
fn native_enum_is_rejected_on_mysql_render() {
    let error = plan_table_sync_with(
        SchemaDialect::MySql,
        &native_enum_table(&["pending", "paid"]),
        &ExistingTableSchema::missing(),
    )
    .expect_err("MySQL 必须拒绝原生枚举");
    assert!(
        error.to_string().contains("MySQL 方言不支持"),
        "错误必须明确指出 MySQL 不支持: {error}"
    );
}

// ---- 部分索引 / 表达式索引 ----

fn index_table() -> TableDefinition {
    Table::new("pg_users")
        .fields([
            Field::id("id"),
            Field::string("email", 128).required(),
            Field::bigint("deleted_at"),
        ])
        .index_spec(
            Some("idx_pg_users_lower_email".to_string()),
            [] as [&str; 0],
            ["lower(email)"],
            None,
            false,
            false,
        )
        .index_spec(
            Some("idx_pg_users_deleted_at".to_string()),
            ["deleted_at"],
            [] as [&str; 0],
            Some("deleted_at IS NULL".to_string()),
            false,
            false,
        )
        .build()
        .expect("部分/表达式索引表定义应有效")
}

fn index_existing(extra: ExistingIndex) -> ExistingTableSchema {
    ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new(
                "email",
                "varchar",
                "varchar(128)",
                false,
                Some(128),
                Some("'x'".into()),
            ),
            SchemaColumn::new("deleted_at", "bigint", "bigint", true, None, None),
        ],
        vec!["id".to_string()],
        vec![extra],
    )
    .with_column_kinds(identity("id"), BTreeMap::new())
}

#[test]
fn partial_and_expression_indexes_render_where_and_expression_keys() {
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &index_table(),
        &ExistingTableSchema::missing(),
    )
    .expect("部分/表达式索引建表计划应成功");
    let sql = plan.statements.join("\n");
    assert!(
        sql.contains("CREATE INDEX \"idx_pg_users_lower_email\" ON \"pg_users\" (lower(email))"),
        "表达式键必须原样渲染: {sql}"
    );
    assert!(
        sql.contains(
            "CREATE INDEX \"idx_pg_users_deleted_at\" ON \"pg_users\" (\"deleted_at\") WHERE deleted_at IS NULL"
        ),
        "部分索引谓词必须原样渲染: {sql}"
    );
}

#[test]
fn partial_index_normalized_predicate_is_idempotent() {
    let existing = index_existing(
        ExistingIndex::new(
            "idx_pg_users_deleted_at",
            false,
            vec!["deleted_at".to_string()],
        )
        .with_predicate("(deleted_at IS NULL)".to_string()),
    );
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &index_table(), &existing)
        .expect("谓词仅外层括号不同应视为同一索引");
    assert!(
        !plan
            .statements
            .iter()
            .any(|sql| sql.contains("idx_pg_users_deleted_at")),
        "匹配的部分索引不得重建: {:?}",
        plan.statements
    );
}

#[test]
fn expression_index_matching_reflection_is_idempotent() {
    let existing = index_existing(
        ExistingIndex::new("idx_pg_users_lower_email", false, Vec::new())
            .with_expressions(vec!["lower(email)".to_string()]),
    );
    let plan = plan_table_sync_with(SchemaDialect::PostgreSql, &index_table(), &existing)
        .expect("表达式索引应幂等");
    assert!(
        !plan
            .statements
            .iter()
            .any(|sql| sql.contains("idx_pg_users_lower_email")),
        "表达式索引不得重复创建: {:?}",
        plan.statements
    );
}

#[cfg(feature = "mysql")]
#[test]
fn partial_index_is_rejected_on_mysql_render() {
    let error = plan_table_sync_with(
        SchemaDialect::MySql,
        &index_table(),
        &ExistingTableSchema::missing(),
    )
    .expect_err("MySQL 必须拒绝部分/表达式索引");
    assert!(
        error
            .to_string()
            .contains("PostgreSQL 专属的表达式键/部分索引谓词"),
        "错误必须明确指出 MySQL 不支持: {error}"
    );
}

// ---- 跨表共享原生枚举 ----

fn shared_enum_table(table_name: &str, values: &[&str]) -> TableDefinition {
    Table::new(table_name)
        .fields([
            Field::id("id"),
            Field::enumeration("status", values.iter().copied())
                .required()
                .native_enum("shared_status"),
        ])
        .build()
        .expect("共享枚举表定义应有效")
}

#[test]
fn shared_native_enum_creates_type_only_once_across_plans() {
    let first = shared_enum_table("shared_enum_a", &["pending", "paid"]);
    let second = shared_enum_table("shared_enum_b", &["pending", "paid"]);
    let mut plans = vec![
        plan_table_sync_with(
            SchemaDialect::PostgreSql,
            &first,
            &ExistingTableSchema::missing(),
        )
        .expect("第一张表计划应成功"),
        plan_table_sync_with(
            SchemaDialect::PostgreSql,
            &second,
            &ExistingTableSchema::missing(),
        )
        .expect("第二张表计划应成功"),
    ];
    dedupe_native_enum_steps(&mut plans);
    let create_type_count = plans
        .iter()
        .flat_map(|plan| plan.statements.iter())
        .filter(|sql| sql.starts_with("CREATE TYPE \"shared_status\""))
        .count();
    assert_eq!(create_type_count, 1, "共享枚举类型只能创建一次");
    assert!(
        plans.iter().any(|plan| plan

            .statements
            .iter()
            .any(|sql| sql.starts_with("CREATE TABLE"))),
        "去重不得误删建表语句"
    );
}

#[test]
fn shared_native_enum_with_conflicting_values_fails_closed() {
    let first = shared_enum_table("shared_enum_a", &["pending", "paid"]);
    let second = shared_enum_table("shared_enum_b", &["pending", "refunded"]);
    let error =
        validate_shared_native_enums(&[&first, &second]).expect_err("共享类型取值冲突必须失败");
    assert!(
        error.to_string().contains("声明了不同取值"),
        "错误必须说明取值冲突: {error}"
    );
}

#[test]
fn binding_table_name_is_reserved_for_all_sync_paths() {
    let table = Table::new("_yang_schema_binding")
        .fields([Field::id("id")])
        .build()
        .expect("保留表名定义本身可构建");
    let error = SchemaDialect::PostgreSql
        .normalize_definitions(&[&table])
        .expect_err("保留表名必须被拒绝");
    assert!(
        error.to_string().contains("框架保留的系统表"),
        "错误必须说明保留表名: {error}"
    );
}

#[cfg(feature = "mysql")]
#[test]
fn mysql_reserved_binding_name_is_case_insensitive() {
    let table = Table::new("_Yang_Schema_Binding")
        .fields([Field::id("id")])
        .build()
        .expect("大小写变体定义本身可构建");
    let error = SchemaDialect::MySql
        .normalize_definitions(&[&table])
        .expect_err("MySQL 大小写变体也必须拒绝");
    assert!(
        error.to_string().contains("框架保留的系统表"),
        "错误必须说明保留表名: {error}"
    );
}

// ---- opaque 存量列 ----

fn opaque_table() -> TableDefinition {
    Table::new("pg_contacts")
        .fields([Field::bigint("id").required().primary_key()])
        .opaque_column("addr", "inet")
        .build()
        .expect("opaque 表定义应有效")
}

fn opaque_existing(addr_type: &str) -> ExistingTableSchema {
    ExistingTableSchema::existing(
        vec![
            SchemaColumn::new("id", "bigint", "bigint", false, None, None),
            SchemaColumn::new("addr", "inet", addr_type, true, None, None),
        ],
        vec!["id".to_string()],
        Vec::new(),
    )
}

#[test]
fn opaque_column_matching_existing_type_is_noop() {
    let plan = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &opaque_table(),
        &opaque_existing("inet"),
    )
    .expect("opaque 列匹配时应可规划");
    assert!(
        plan.changes.is_empty(),
        "不得对 opaque 列产生 DDL: {:?}",
        plan.changes
    );
}

#[test]
fn opaque_column_type_mismatch_fails_closed() {
    let error = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &opaque_table(),
        &opaque_existing("cidr"),
    )
    .expect_err("opaque 列类型不匹配必须失败");
    assert!(
        error.to_string().contains("opaque 列 addr 类型不匹配"),
        "错误必须指出列与类型: {error}"
    );
}

#[test]
fn opaque_column_requires_existing_table() {
    let error = plan_table_sync_with(
        SchemaDialect::PostgreSql,
        &opaque_table(),
        &ExistingTableSchema::missing(),
    )
    .expect_err("表不存在时不能自动创建 opaque 列");
    assert!(
        error.to_string().contains("无法自动创建 opaque 列"),
        "错误必须说明无法自动建列: {error}"
    );
}

#[cfg(feature = "mysql")]
#[test]
fn opaque_column_is_rejected_on_mysql() {
    let error = plan_table_sync_with(
        SchemaDialect::MySql,
        &opaque_table(),
        &ExistingTableSchema::missing(),
    )
    .expect_err("MySQL 必须拒绝 opaque 列");
    assert!(
        error.to_string().contains("MySQL 不支持"),
        "错误必须明确 MySQL 不支持: {error}"
    );
}