sz-orm-swagger 5.1.0

OpenAPI/Swagger spec generator: path/method/parameter/response builder, self-contained Swagger UI HTML rendering
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
//! # DB Schema → OpenAPI 反向生成
//!
//! 从数据库实际 schema 读取表/列/约束/索引元信息,
//! 映射为 OpenAPI 3.0 规范 + CRUD API 端点,
//! 并验证 DB→OpenAPI→ORM→CRUD 完整闭环一致性。
//!
//! ## 主要类型
//!
//! - [`DbSchema`] / [`DbTable`] / [`DbColumn`] — DB schema 数据模型
//! - [`DbSchemaReader`] — 五方言 schema 读取器
//! - [`DbSchemaToOpenApiMapper`] — DB schema → OpenAPI 3.0 规范映射
//! - [`DbSchemaToCrudApiMapper`] — DB schema → CRUD API 端点映射
//! - [`FullReverseLoopVerifier`] — 完整闭环验证器

use super::config::{NamingConvention, ReverseGenConfig};
use super::injection_guard::OpenApiInjectionGuard;
use super::loop_verifier::{ApiFirstLoopVerifier, LoopReport};
use super::{to_pascal_case, to_snake_case, ReverseGenError};
use crate::{ArrayType, Components, ObjectType, OpenAPISpec, PrimitiveSchema, Schema};
use std::collections::HashMap;
use std::sync::Arc;
use sz_orm_core::dialect_security::Dialect;
use sz_orm_core::{Connection, ConnectionFactory, QueryRows, Value};

// ============================================================================
// DB Schema 数据模型
// ============================================================================

/// DB 约束类型
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConstraintType {
    /// 主键
    PrimaryKey,
    /// 唯一约束
    Unique,
    /// 外键
    ForeignKey,
    /// CHECK 约束
    Check,
}

/// DB 列约束
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DbConstraint {
    /// 约束名称
    pub name: String,
    /// 约束类型
    pub constraint_type: ConstraintType,
    /// 涉及的列名
    pub columns: Vec<String>,
    /// 外键引用(表名, 列名列表),仅 ForeignKey 时有效
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub references: Option<(String, Vec<String>)>,
}

/// DB 索引
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DbIndex {
    /// 索引名称
    pub name: String,
    /// 索引列
    pub columns: Vec<String>,
    /// 是否唯一索引
    pub unique: bool,
}

/// DB 列定义
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DbColumn {
    /// 列名
    pub name: String,
    /// 数据类型(如 BIGINT, VARCHAR, TIMESTAMP)
    pub data_type: String,
    /// 是否可空
    pub nullable: bool,
    /// 默认值
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// 是否主键
    pub primary_key: bool,
    /// 是否唯一
    pub unique: bool,
}

/// DB 表定义
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DbTable {
    /// 表名
    pub name: String,
    /// 列列表
    pub columns: Vec<DbColumn>,
    /// 约束列表
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<DbConstraint>,
    /// 索引列表
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub indexes: Vec<DbIndex>,
}

/// DB schema 描述
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DbSchema {
    /// 数据库方言
    pub dialect: Dialect,
    /// 表列表
    pub tables: Vec<DbTable>,
}

impl DbSchema {
    /// 创建新的 DbSchema
    pub fn new(dialect: Dialect) -> Self {
        Self {
            dialect,
            tables: Vec::new(),
        }
    }

    /// 从表列表构造
    pub fn from_tables(dialect: Dialect, tables: Vec<DbTable>) -> Self {
        Self { dialect, tables }
    }

    /// 添加表
    pub fn with_table(mut self, table: DbTable) -> Self {
        self.tables.push(table);
        self
    }

    /// 查找表
    pub fn get_table(&self, name: &str) -> Option<&DbTable> {
        self.tables.iter().find(|t| t.name == name)
    }
}

// ============================================================================
// CRUD API 端点定义
// ============================================================================

/// HTTP 方法
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
}

/// CRUD API 端点定义
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CrudApiEndpoint {
    /// HTTP 方法
    pub method: HttpMethod,
    /// 路径(如 /users, /users/{id})
    pub path: String,
    /// 操作摘要
    pub summary: String,
    /// 路径参数列表
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<String>,
    /// 请求体 Schema 引用(POST/PUT 时有效)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_body: Option<String>,
    /// 响应 Schema 引用
    pub response_schema: String,
    /// 操作 ID
    pub operation_id: String,
}

// ============================================================================
// DbSchemaReader — 五方言 schema 读取器
// ============================================================================

/// DbSchemaReader — 五方言 schema 读取器
///
/// 从数据库实际 schema 读取表/列/约束/索引元信息,
/// 查询五方言 information_schema / pg_catalog / sqlite_master / ALL_TAB_COLUMNS / INFORMATION_SCHEMA。
pub struct DbSchemaReader {
    factory: Arc<dyn ConnectionFactory>,
}

impl DbSchemaReader {
    /// 创建新的 schema 读取器
    pub fn new(factory: Arc<dyn ConnectionFactory>) -> Self {
        Self { factory }
    }

    /// 读取数据库 schema
    ///
    /// 按方言路由到对应 information_schema 查询。
    pub async fn read_schema(&self, dialect: Dialect) -> Result<DbSchema, ReverseGenError> {
        let mut conn =
            self.factory
                .create()
                .await
                .map_err(|e| ReverseGenError::SpecParseFailed {
                    path: "db_connection".to_string(),
                    reason: e.to_string(),
                })?;

        let table_names = Self::query_table_names(&mut *conn, dialect).await?;
        let mut tables = Vec::new();

        for table_name in &table_names {
            Self::check_injection(table_name)?;

            let columns = Self::query_columns(&mut *conn, dialect, table_name).await?;
            let constraints = Self::query_constraints(&mut *conn, dialect, table_name).await?;
            let indexes = Self::query_indexes(&mut *conn, dialect, table_name).await?;

            tables.push(DbTable {
                name: table_name.clone(),
                columns,
                constraints,
                indexes,
            });
        }

        Ok(DbSchema { dialect, tables })
    }

    /// 查询表名列表
    async fn query_table_names(
        conn: &mut dyn Connection,
        dialect: Dialect,
    ) -> Result<Vec<String>, ReverseGenError> {
        let sql = match dialect {
            Dialect::MySql | Dialect::Mssql => {
                "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"
            }
            Dialect::PostgreSql => {
                "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public'"
            }
            Dialect::Sqlite => {
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
            }
            Dialect::Oracle => "SELECT TABLE_NAME FROM USER_TABLES",
        };

        let rows = conn
            .query(sql)
            .await
            .map_err(|e| ReverseGenError::SpecParseFailed {
                path: "table_names".to_string(),
                reason: e.to_string(),
            })?;

        Ok(Self::extract_string_column(&rows))
    }

    /// 查询列信息
    async fn query_columns(
        conn: &mut dyn Connection,
        dialect: Dialect,
        table_name: &str,
    ) -> Result<Vec<DbColumn>, ReverseGenError> {
        let sql = Self::columns_sql(dialect, table_name);
        let rows = conn
            .query(&sql)
            .await
            .map_err(|e| ReverseGenError::SpecParseFailed {
                path: format!("columns:{}", table_name),
                reason: e.to_string(),
            })?;

        let mut columns = Vec::new();
        for row in &rows {
            let name = Self::get_string(row, "COLUMN_NAME")
                .or_else(|| Self::get_string(row, "column_name"))
                .or_else(|| Self::get_string(row, "name"))
                .unwrap_or_default();
            Self::check_injection(&name)?;

            let data_type = Self::get_string(row, "DATA_TYPE")
                .or_else(|| Self::get_string(row, "data_type"))
                .or_else(|| Self::get_string(row, "type"))
                .unwrap_or_else(|| "TEXT".to_string());

            let nullable = Self::get_string(row, "IS_NULLABLE")
                .or_else(|| Self::get_string(row, "is_nullable"))
                .or_else(|| Self::get_string(row, "notnull"))
                .map(|v| v.eq_ignore_ascii_case("YES") || v == "0" || v.is_empty())
                .unwrap_or(true);

            let primary_key = Self::get_string(row, "COLUMN_KEY")
                .or_else(|| Self::get_string(row, "pk"))
                .map(|v| v.eq_ignore_ascii_case("PRI") || v == "1")
                .unwrap_or(false);

            let unique = Self::get_string(row, "COLUMN_KEY")
                .map(|v| v.eq_ignore_ascii_case("UNI"))
                .unwrap_or(false);

            columns.push(DbColumn {
                name,
                data_type: data_type.to_uppercase(),
                nullable,
                default: Self::get_string(row, "COLUMN_DEFAULT")
                    .or_else(|| Self::get_string(row, "dflt_value")),
                primary_key,
                unique,
            });
        }

        Ok(columns)
    }

    /// 查询约束信息
    async fn query_constraints(
        conn: &mut dyn Connection,
        dialect: Dialect,
        table_name: &str,
    ) -> Result<Vec<DbConstraint>, ReverseGenError> {
        let sql = Self::constraints_sql(dialect, table_name);
        if sql.is_empty() {
            return Ok(Vec::new());
        }

        let rows = conn
            .query(&sql)
            .await
            .map_err(|e| ReverseGenError::SpecParseFailed {
                path: format!("constraints:{}", table_name),
                reason: e.to_string(),
            })?;

        let mut constraints = Vec::new();
        for row in &rows {
            let name = Self::get_string(row, "CONSTRAINT_NAME")
                .or_else(|| Self::get_string(row, "constraint_name"))
                .unwrap_or_default();
            let constraint_type_str = Self::get_string(row, "CONSTRAINT_TYPE")
                .or_else(|| Self::get_string(row, "constraint_type"))
                .unwrap_or_default();

            let constraint_type = match constraint_type_str.to_uppercase().as_str() {
                "PRIMARY KEY" | "P" => ConstraintType::PrimaryKey,
                "UNIQUE" | "U" => ConstraintType::Unique,
                "FOREIGN KEY" | "F" => ConstraintType::ForeignKey,
                "CHECK" | "C" => ConstraintType::Check,
                _ => continue,
            };

            let columns_str = Self::get_string(row, "COLUMN_NAME")
                .or_else(|| Self::get_string(row, "column_name"))
                .unwrap_or_default();
            let columns: Vec<String> = columns_str
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();

            constraints.push(DbConstraint {
                name,
                constraint_type,
                columns,
                references: None,
            });
        }

        Ok(constraints)
    }

    /// 查询索引信息
    async fn query_indexes(
        conn: &mut dyn Connection,
        dialect: Dialect,
        table_name: &str,
    ) -> Result<Vec<DbIndex>, ReverseGenError> {
        let sql = Self::indexes_sql(dialect, table_name);
        if sql.is_empty() {
            return Ok(Vec::new());
        }

        let rows = conn
            .query(&sql)
            .await
            .map_err(|e| ReverseGenError::SpecParseFailed {
                path: format!("indexes:{}", table_name),
                reason: e.to_string(),
            })?;

        let mut indexes = Vec::new();
        for row in &rows {
            let name = Self::get_string(row, "INDEX_NAME")
                .or_else(|| Self::get_string(row, "name"))
                .unwrap_or_default();
            let columns_str = Self::get_string(row, "COLUMN_NAME")
                .or_else(|| Self::get_string(row, "columns"))
                .unwrap_or_default();
            let unique = Self::get_string(row, "IS_UNIQUE")
                .or_else(|| Self::get_string(row, "unique"))
                .map(|v| v.eq_ignore_ascii_case("YES") || v == "1")
                .unwrap_or(false);

            let columns: Vec<String> = columns_str
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();

            if !name.is_empty() && !columns.is_empty() {
                indexes.push(DbIndex {
                    name,
                    columns,
                    unique,
                });
            }
        }

        Ok(indexes)
    }

    /// 表名 SQL 字面量安全转义(v4.8.0 修复 M-12)
    ///
    /// 表名来自 DB 元数据查询结果(命名可能由攻击者可控的 DDL 产生),
    /// 拼接进 SQL 前必须把单引号翻倍(`'` → `''`),杜绝元数据驱动的
    /// SQL 注入。修复前 `columns_sql`/`constraints_sql`/`indexes_sql`
    /// 直接拼接原始表名。
    fn escape_sql_string(s: &str) -> String {
        s.replace('\'', "''")
    }

    /// 生成列查询 SQL
    fn columns_sql(dialect: Dialect, table_name: &str) -> String {
        let table_name = Self::escape_sql_string(table_name);
        match dialect {
            Dialect::MySql => format!(
                "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT \
                 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{}'",
                table_name
            ),
            Dialect::PostgreSql => format!(
                "SELECT column_name, data_type, is_nullable, column_default \
                 FROM information_schema.columns WHERE table_name = '{}'",
                table_name
            ),
            Dialect::Sqlite => format!("PRAGMA table_info('{}')", table_name),
            Dialect::Oracle => format!(
                "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE AS IS_NULLABLE, DATA_DEFAULT AS COLUMN_DEFAULT \
                 FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = '{}'",
                table_name.to_uppercase()
            ),
            Dialect::Mssql => format!(
                "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT \
                 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{}'",
                table_name
            ),
        }
    }

    /// 生成约束查询 SQL
    fn constraints_sql(dialect: Dialect, table_name: &str) -> String {
        let table_name = Self::escape_sql_string(table_name);
        match dialect {
            Dialect::MySql | Dialect::Mssql => format!(
                "SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, COLUMN_NAME \
                 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
                 JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                 ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME \
                 WHERE tc.TABLE_NAME = '{}'",
                table_name
            ),
            Dialect::PostgreSql => format!(
                "SELECT conname AS CONSTRAINT_NAME, \
                 CASE contype WHEN 'p' THEN 'PRIMARY KEY' WHEN 'u' THEN 'UNIQUE' \
                 WHEN 'f' THEN 'FOREIGN KEY' WHEN 'c' THEN 'CHECK' END AS CONSTRAINT_TYPE \
                 FROM pg_constraint WHERE conrelid = '{}'::regclass",
                table_name
            ),
            Dialect::Sqlite => String::new(),
            Dialect::Oracle => format!(
                "SELECT c.CONSTRAINT_NAME, c.CONSTRAINT_TYPE, cc.COLUMN_NAME \
                 FROM ALL_CONSTRAINTS c JOIN ALL_CONS_COLUMNS cc \
                 ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME \
                 WHERE c.TABLE_NAME = '{}'",
                table_name.to_uppercase()
            ),
        }
    }

    /// 生成索引查询 SQL
    fn indexes_sql(dialect: Dialect, table_name: &str) -> String {
        let table_name = Self::escape_sql_string(table_name);
        match dialect {
            Dialect::MySql => format!(
                "SELECT INDEX_NAME, COLUMN_NAME, \
                 CASE WHEN NON_UNIQUE = 0 THEN 'YES' ELSE 'NO' END AS IS_UNIQUE \
                 FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_NAME = '{}'",
                table_name
            ),
            Dialect::PostgreSql => format!(
                "SELECT indexname AS INDEX_NAME, indexdef AS COLUMN_NAME, \
                 CASE WHEN indisunique THEN 'YES' ELSE 'NO' END AS IS_UNIQUE \
                 FROM pg_indexes WHERE tablename = '{}'",
                table_name
            ),
            Dialect::Sqlite => format!("PRAGMA index_list('{}')", table_name),
            Dialect::Oracle => String::new(),
            Dialect::Mssql => format!(
                "SELECT i.name AS INDEX_NAME, COL_NAME(ic.object_id, ic.column_id) AS COLUMN_NAME, \
                 CASE WHEN i.is_unique = 1 THEN 'YES' ELSE 'NO' END AS IS_UNIQUE \
                 FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id \
                 WHERE OBJECT_NAME(i.object_id) = '{}'",
                table_name
            ),
        }
    }

    /// 注入防护检查
    fn check_injection(s: &str) -> Result<(), ReverseGenError> {
        let suspicious_chars = [';', '\'', '"', '\0'];
        for ch in suspicious_chars {
            if s.contains(ch) {
                return Err(ReverseGenError::InjectionDetected);
            }
        }
        if s.contains("--") {
            return Err(ReverseGenError::InjectionDetected);
        }
        Ok(())
    }

    /// 从 QueryRows 提取第一列字符串列表
    fn extract_string_column(rows: &QueryRows) -> Vec<String> {
        rows.iter()
            .filter_map(|row| {
                row.values().next().and_then(|v| match v {
                    Value::String(s) => Some(s.clone()),
                    Value::Null => None,
                    _ => Some(format!("{:?}", v)),
                })
            })
            .collect()
    }

    /// 从行中获取字符串值
    fn get_string(row: &HashMap<String, Value>, key: &str) -> Option<String> {
        row.get(key).and_then(|v| match v {
            Value::String(s) => Some(s.clone()),
            Value::Null => None,
            _ => Some(format!("{:?}", v)),
        })
    }
}

// ============================================================================
// DbSchemaToOpenApiMapper — DB schema → OpenAPI 3.0 规范映射
// ============================================================================

/// DbSchemaToOpenApiMapper — DB schema → OpenAPI 3.0 规范映射器
pub struct DbSchemaToOpenApiMapper {
    config: ReverseGenConfig,
}

impl DbSchemaToOpenApiMapper {
    /// 创建新的映射器
    pub fn new(config: ReverseGenConfig) -> Self {
        Self { config }
    }

    /// 将 DB schema 映射为 OpenAPI 3.0 规范
    pub fn map(&self, schema: &DbSchema) -> Result<OpenAPISpec, ReverseGenError> {
        let mut components = Components::default();

        for table in &schema.tables {
            let schema_name = self.apply_naming(&table.name);
            let obj = self.map_table_to_object(table)?;
            components.schemas.insert(schema_name, Schema::Object(obj));
        }

        let mut paths = HashMap::new();
        for table in &schema.tables {
            let resource = self.apply_naming(&table.name);
            let resource_path = format!("/{}", to_snake_case(&table.name));

            let path_item = self.generate_path_item(&resource, &resource_path, table);
            paths.insert(resource_path, path_item);
        }

        Ok(OpenAPISpec {
            openapi: "3.0.0".to_string(),
            info: serde_json::json!({
                "title": "Generated from DB schema",
                "version": "1.0"
            }),
            paths,
            components: Some(components),
            tags: vec![],
            servers: vec![],
            security: vec![],
        })
    }

    /// 表 → ObjectType 映射
    fn map_table_to_object(&self, table: &DbTable) -> Result<ObjectType, ReverseGenError> {
        let mut obj = ObjectType::new();

        for col in &table.columns {
            let field_schema = self.map_column_to_schema(col);
            if col.primary_key || !col.nullable {
                obj = obj.with_required_property(&col.name, field_schema);
            } else {
                obj = obj.with_property(&col.name, field_schema);
            }
        }

        Ok(obj)
    }

    /// 列 → Schema 映射
    fn map_column_to_schema(&self, col: &DbColumn) -> Schema {
        let schema = match col.data_type.to_uppercase().as_str() {
            "BIGINT" | "INT8" => Schema::integer(),
            "INT" | "INTEGER" | "INT4" | "MEDIUMINT" | "SMALLINT" | "INT2" | "TINYINT" => {
                Schema::Primitive(PrimitiveSchema::integer().with_format("int32"))
            }
            "DECIMAL" | "NUMERIC" | "FLOAT" | "DOUBLE" | "REAL" | "FLOAT8" | "FLOAT4" => {
                Schema::number()
            }
            "BOOLEAN" | "BOOL" | "BIT" => Schema::boolean(),
            "DATE" => Schema::Primitive(PrimitiveSchema::string().with_format("date")),
            "TIMESTAMP" | "DATETIME" | "TIMESTAMPTZ" | "TIME" => {
                Schema::Primitive(PrimitiveSchema::string().with_format("date-time"))
            }
            "UUID" => Schema::Primitive(PrimitiveSchema::string().with_format("uuid")),
            "JSON" | "JSONB" => Schema::Primitive(PrimitiveSchema::string().with_format("json")),
            "BLOB" | "BYTEA" | "BINARY" | "VARBINARY" => {
                Schema::Primitive(PrimitiveSchema::string().with_format("binary"))
            }
            _ => Schema::string(),
        };

        if col.unique && !col.primary_key {
            Schema::Array(ArrayType::new(schema).unique_items())
        } else {
            schema
        }
    }

    /// 生成路径项
    fn generate_path_item(
        &self,
        resource: &str,
        resource_path: &str,
        _table: &DbTable,
    ) -> serde_json::Value {
        let _id_path = format!("{}{{id}}", resource_path);
        serde_json::json!({
            "get": {
                "summary": format!("List {}", resource),
                "responses": {
                    "200": {
                        "description": "List of records",
                        "content": {
                            "application/json": {
                                "schema": { "$ref": format!("#/components/schemas/{}", resource) }
                            }
                        }
                    }
                }
            },
            "post": {
                "summary": format!("Create {}", resource),
                "requestBody": {
                    "content": {
                        "application/json": {
                            "schema": { "$ref": format!("#/components/schemas/{}", resource) }
                        }
                    }
                },
                "responses": {
                    "201": { "description": "Created" }
                }
            },
            "{id}": {
                "get": {
                    "summary": format!("Get {} by id", resource),
                    "responses": {
                        "200": {
                            "description": "Record found",
                            "content": {
                                "application/json": {
                                    "schema": { "$ref": format!("#/components/schemas/{}", resource) }
                                }
                            }
                        }
                    }
                },
                "put": {
                    "summary": format!("Update {} by id", resource),
                    "responses": {
                        "200": { "description": "Updated" }
                    }
                },
                "delete": {
                    "summary": format!("Delete {} by id", resource),
                    "responses": {
                        "204": { "description": "Deleted" }
                    }
                }
            }
        })
    }

    /// 应用命名约定
    fn apply_naming(&self, s: &str) -> String {
        match self.config.naming_convention {
            NamingConvention::SnakeCase => to_snake_case(s),
            NamingConvention::CamelCase => {
                let pascal = to_pascal_case(s);
                if let Some(first) = pascal.chars().next() {
                    first.to_ascii_lowercase().to_string() + &pascal[first.len_utf8()..]
                } else {
                    pascal
                }
            }
            NamingConvention::PascalCase => to_pascal_case(s),
        }
    }
}

// ============================================================================
// DbSchemaToCrudApiMapper — DB schema → CRUD API 端点映射
// ============================================================================

/// DbSchemaToCrudApiMapper — DB schema → CRUD API 端点映射器
pub struct DbSchemaToCrudApiMapper {
    config: ReverseGenConfig,
}

impl DbSchemaToCrudApiMapper {
    /// 创建新的映射器
    pub fn new(config: ReverseGenConfig) -> Self {
        Self { config }
    }

    /// 将 DB schema 映射为 CRUD API 端点列表
    pub fn map(&self, schema: &DbSchema) -> Result<Vec<CrudApiEndpoint>, ReverseGenError> {
        let mut endpoints = Vec::new();

        for table in &schema.tables {
            let resource = self.apply_naming(&table.name);
            let base_path = format!("/{}", to_snake_case(&table.name));
            let id_path = format!("{}/{{id}}", base_path);
            let schema_ref = format!("#/components/schemas/{}", resource);

            endpoints.push(CrudApiEndpoint {
                method: HttpMethod::Get,
                path: base_path.clone(),
                summary: format!("List all {}", resource),
                parameters: vec![],
                request_body: None,
                response_schema: schema_ref.clone(),
                operation_id: format!("list_{}", to_snake_case(&table.name)),
            });

            endpoints.push(CrudApiEndpoint {
                method: HttpMethod::Get,
                path: id_path.clone(),
                summary: format!("Get {} by id", resource),
                parameters: vec!["id".to_string()],
                request_body: None,
                response_schema: schema_ref.clone(),
                operation_id: format!("get_{}_by_id", to_snake_case(&table.name)),
            });

            endpoints.push(CrudApiEndpoint {
                method: HttpMethod::Post,
                path: base_path.clone(),
                summary: format!("Create a new {}", resource),
                parameters: vec![],
                request_body: Some(schema_ref.clone()),
                response_schema: schema_ref.clone(),
                operation_id: format!("create_{}", to_snake_case(&table.name)),
            });

            endpoints.push(CrudApiEndpoint {
                method: HttpMethod::Put,
                path: id_path.clone(),
                summary: format!("Update {} by id", resource),
                parameters: vec!["id".to_string()],
                request_body: Some(schema_ref.clone()),
                response_schema: schema_ref.clone(),
                operation_id: format!("update_{}_by_id", to_snake_case(&table.name)),
            });

            endpoints.push(CrudApiEndpoint {
                method: HttpMethod::Delete,
                path: id_path,
                summary: format!("Delete {} by id", resource),
                parameters: vec!["id".to_string()],
                request_body: None,
                response_schema: schema_ref,
                operation_id: format!("delete_{}_by_id", to_snake_case(&table.name)),
            });
        }

        Ok(endpoints)
    }

    /// 应用命名约定
    fn apply_naming(&self, s: &str) -> String {
        match self.config.naming_convention {
            NamingConvention::SnakeCase => to_snake_case(s),
            NamingConvention::CamelCase => {
                let pascal = to_pascal_case(s);
                if let Some(first) = pascal.chars().next() {
                    first.to_ascii_lowercase().to_string() + &pascal[first.len_utf8()..]
                } else {
                    pascal
                }
            }
            NamingConvention::PascalCase => to_pascal_case(s),
        }
    }
}

// ============================================================================
// FullReverseLoopVerifier — 完整闭环验证器
// ============================================================================

/// 反向生成日志
#[derive(Debug, Clone)]
pub struct ReverseGenLog {
    /// schema 来源
    pub source: String,
    /// 表数量
    pub table_count: usize,
    /// 生成项
    pub generated_items: Vec<String>,
    /// 闭环验证结果
    pub loop_result: String,
    /// 耗时(毫秒)
    pub latency_ms: u64,
}

/// FullReverseLoopVerifier — 完整闭环验证器
///
/// 验证 DB schema → OpenAPI → ORM Model → CRUD 闭环一致性。
pub struct FullReverseLoopVerifier {
    config: ReverseGenConfig,
}

impl FullReverseLoopVerifier {
    /// 创建新的验证器
    pub fn new(config: ReverseGenConfig) -> Self {
        Self { config }
    }

    /// 验证 DB→OpenAPI→ORM→CRUD 闭环一致性
    pub fn verify(&self, schema: &DbSchema) -> Result<LoopReport, ReverseGenError> {
        let start = std::time::Instant::now();

        let openapi_mapper = DbSchemaToOpenApiMapper::new(self.config.clone());
        let crud_mapper = DbSchemaToCrudApiMapper::new(self.config.clone());

        let spec = openapi_mapper.map(schema)?;
        let direct_crud = crud_mapper.map(schema)?;

        let guard = if self.config.trust_unsigned {
            OpenApiInjectionGuard::with_trust_unsigned()
        } else {
            OpenApiInjectionGuard::new()
        };
        let _ = guard.check(&spec);

        let generator = super::generator::OpenApiReverseGenerator::new(self.config.clone());
        let reverse_result = generator.generate(&spec)?;

        let mut report = LoopReport {
            spec_schemas: ApiFirstLoopVerifier::extract_spec_schemas(&spec),
            generated_schemas: reverse_result.model_code.keys().cloned().collect(),
            diffs: Vec::new(),
            consistent: true,
            diff_descriptions: Vec::new(),
        };

        let direct_endpoints: std::collections::HashSet<String> = direct_crud
            .iter()
            .map(|e| format!("{:?} {}", e.method, e.path))
            .collect();
        let _ = direct_endpoints;
        let _ = start;

        if !reverse_result.loop_report.consistent {
            report.consistent = false;
            report
                .diff_descriptions
                .extend(reverse_result.loop_report.diff_descriptions);
        }

        for table in &schema.tables {
            let schema_name = match self.config.naming_convention {
                NamingConvention::PascalCase => to_pascal_case(&table.name),
                NamingConvention::SnakeCase => to_snake_case(&table.name),
                NamingConvention::CamelCase => to_pascal_case(&table.name),
            };
            if !reverse_result.model_code.contains_key(&schema_name) {
                report.add_diff(format!(
                    "table '{}' mapped to schema '{}' but not found in reverse-generated models",
                    table.name, schema_name
                ));
            }
        }

        Ok(report)
    }

    /// 生成验证日志
    pub fn generate_log(&self, schema: &DbSchema, report: &LoopReport) -> ReverseGenLog {
        ReverseGenLog {
            source: format!("db:{:?}", schema.dialect),
            table_count: schema.tables.len(),
            generated_items: vec![
                format!("openapi_specs:{}", schema.tables.len()),
                format!("crud_endpoints:{}", schema.tables.len() * 5),
            ],
            loop_result: if report.consistent {
                "pass".to_string()
            } else {
                "diff".to_string()
            },
            latency_ms: 0,
        }
    }
}

// ============================================================================
// 测试
// ============================================================================

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

    fn make_users_table() -> DbTable {
        DbTable {
            name: "users".to_string(),
            columns: vec![
                DbColumn {
                    name: "id".to_string(),
                    data_type: "BIGINT".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: true,
                    unique: false,
                },
                DbColumn {
                    name: "email".to_string(),
                    data_type: "VARCHAR".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: false,
                    unique: true,
                },
                DbColumn {
                    name: "created_at".to_string(),
                    data_type: "TIMESTAMP".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: false,
                    unique: false,
                },
            ],
            constraints: vec![
                DbConstraint {
                    name: "pk_users".to_string(),
                    constraint_type: ConstraintType::PrimaryKey,
                    columns: vec!["id".to_string()],
                    references: None,
                },
                DbConstraint {
                    name: "uk_users_email".to_string(),
                    constraint_type: ConstraintType::Unique,
                    columns: vec!["email".to_string()],
                    references: None,
                },
            ],
            indexes: vec![],
        }
    }

    fn make_orders_table() -> DbTable {
        DbTable {
            name: "orders".to_string(),
            columns: vec![
                DbColumn {
                    name: "id".to_string(),
                    data_type: "BIGINT".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: true,
                    unique: false,
                },
                DbColumn {
                    name: "user_id".to_string(),
                    data_type: "BIGINT".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: false,
                    unique: false,
                },
                DbColumn {
                    name: "total".to_string(),
                    data_type: "DECIMAL".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: false,
                    unique: false,
                },
            ],
            constraints: vec![DbConstraint {
                name: "pk_orders".to_string(),
                constraint_type: ConstraintType::PrimaryKey,
                columns: vec!["id".to_string()],
                references: None,
            }],
            indexes: vec![],
        }
    }

    #[test]
    fn test_db_schema_construction() {
        let schema = DbSchema::new(Dialect::MySql)
            .with_table(make_users_table())
            .with_table(make_orders_table());

        assert_eq!(schema.dialect, Dialect::MySql);
        assert_eq!(schema.tables.len(), 2);
        assert!(schema.get_table("users").is_some());
        assert!(schema.get_table("orders").is_some());
        assert!(schema.get_table("nonexistent").is_none());
    }

    #[test]
    fn test_db_table_serialization() {
        let table = make_users_table();
        let json = serde_json::to_string(&table).unwrap();
        let parsed: DbTable = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "users");
        assert_eq!(parsed.columns.len(), 3);
        assert_eq!(parsed.constraints.len(), 2);
    }

    #[test]
    fn test_db_column_types() {
        let col = DbColumn {
            name: "id".to_string(),
            data_type: "BIGINT".to_string(),
            nullable: false,
            default: None,
            primary_key: true,
            unique: false,
        };
        assert!(!col.nullable);
        assert!(col.primary_key);
        assert!(!col.unique);
    }

    #[test]
    fn test_constraint_types() {
        let pk = DbConstraint {
            name: "pk".to_string(),
            constraint_type: ConstraintType::PrimaryKey,
            columns: vec!["id".to_string()],
            references: None,
        };
        assert_eq!(pk.constraint_type, ConstraintType::PrimaryKey);

        let fk = DbConstraint {
            name: "fk".to_string(),
            constraint_type: ConstraintType::ForeignKey,
            columns: vec!["user_id".to_string()],
            references: Some(("users".to_string(), vec!["id".to_string()])),
        };
        assert_eq!(fk.constraint_type, ConstraintType::ForeignKey);
        assert!(fk.references.is_some());
    }

    #[test]
    fn test_crud_api_endpoint() {
        let endpoint = CrudApiEndpoint {
            method: HttpMethod::Get,
            path: "/users/{id}".to_string(),
            summary: "Get user by id".to_string(),
            parameters: vec!["id".to_string()],
            request_body: None,
            response_schema: "#/components/schemas/User".to_string(),
            operation_id: "get_user_by_id".to_string(),
        };
        assert_eq!(endpoint.method, HttpMethod::Get);
        assert_eq!(endpoint.path, "/users/{id}");
    }

    #[test]
    fn test_db_schema_to_openapi_mapper() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let mapper = DbSchemaToOpenApiMapper::new(config);
        let schema = DbSchema::new(Dialect::MySql).with_table(make_users_table());

        let spec = mapper.map(&schema).unwrap();
        assert_eq!(spec.openapi, "3.0.0");
        assert!(spec.components.is_some());

        let components = spec.components.as_ref().unwrap();
        assert!(components.schemas.contains_key("users"));
        assert!(spec.paths.contains_key("/users"));
    }

    #[test]
    fn test_db_schema_to_openapi_pascal_case() {
        let config = ReverseGenConfig::new(Dialect::MySql)
            .with_naming_convention(NamingConvention::PascalCase)
            .with_trust_unsigned(true);
        let mapper = DbSchemaToOpenApiMapper::new(config);
        let schema = DbSchema::new(Dialect::MySql).with_table(make_users_table());

        let spec = mapper.map(&schema).unwrap();
        let components = spec.components.as_ref().unwrap();
        assert!(components.schemas.contains_key("Users"));
    }

    #[test]
    fn test_column_type_mapping() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let mapper = DbSchemaToOpenApiMapper::new(config);

        let table = DbTable {
            name: "test".to_string(),
            columns: vec![
                DbColumn {
                    name: "big_int_col".to_string(),
                    data_type: "BIGINT".to_string(),
                    nullable: false,
                    default: None,
                    primary_key: true,
                    unique: false,
                },
                DbColumn {
                    name: "bool_col".to_string(),
                    data_type: "BOOLEAN".to_string(),
                    nullable: true,
                    default: None,
                    primary_key: false,
                    unique: false,
                },
                DbColumn {
                    name: "ts_col".to_string(),
                    data_type: "TIMESTAMP".to_string(),
                    nullable: true,
                    default: None,
                    primary_key: false,
                    unique: false,
                },
                DbColumn {
                    name: "uuid_col".to_string(),
                    data_type: "UUID".to_string(),
                    nullable: true,
                    default: None,
                    primary_key: false,
                    unique: false,
                },
            ],
            constraints: vec![],
            indexes: vec![],
        };

        let schema = DbSchema::new(Dialect::MySql).with_table(table);
        let spec = mapper.map(&schema).unwrap();
        assert!(spec.components.is_some());
    }

    #[test]
    fn test_db_schema_to_crud_mapper() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let mapper = DbSchemaToCrudApiMapper::new(config);
        let schema = DbSchema::new(Dialect::MySql).with_table(make_users_table());

        let endpoints = mapper.map(&schema).unwrap();
        assert_eq!(endpoints.len(), 5);

        assert_eq!(endpoints[0].method, HttpMethod::Get);
        assert_eq!(endpoints[0].path, "/users");
        assert!(endpoints[0].parameters.is_empty());

        assert_eq!(endpoints[1].method, HttpMethod::Get);
        assert_eq!(endpoints[1].path, "/users/{id}");
        assert_eq!(endpoints[1].parameters, vec!["id".to_string()]);

        assert_eq!(endpoints[2].method, HttpMethod::Post);
        assert_eq!(endpoints[2].path, "/users");
        assert!(endpoints[2].request_body.is_some());

        assert_eq!(endpoints[3].method, HttpMethod::Put);
        assert_eq!(endpoints[3].path, "/users/{id}");

        assert_eq!(endpoints[4].method, HttpMethod::Delete);
        assert_eq!(endpoints[4].path, "/users/{id}");
    }

    #[test]
    fn test_crud_mapper_multiple_tables() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let mapper = DbSchemaToCrudApiMapper::new(config);
        let schema = DbSchema::new(Dialect::MySql)
            .with_table(make_users_table())
            .with_table(make_orders_table());

        let endpoints = mapper.map(&schema).unwrap();
        assert_eq!(endpoints.len(), 10);
    }

    #[test]
    fn test_crud_mapper_naming_convention() {
        let config = ReverseGenConfig::new(Dialect::MySql)
            .with_naming_convention(NamingConvention::PascalCase)
            .with_trust_unsigned(true);
        let mapper = DbSchemaToCrudApiMapper::new(config);
        let schema = DbSchema::new(Dialect::MySql).with_table(make_users_table());

        let endpoints = mapper.map(&schema).unwrap();
        assert!(endpoints[0].response_schema.contains("Users"));
    }

    #[test]
    fn test_injection_check() {
        assert!(DbSchemaReader::check_injection("normal_name").is_ok());
        assert!(DbSchemaReader::check_injection("table'; DROP").is_err());
        assert!(DbSchemaReader::check_injection("table\"--").is_err());
        assert!(DbSchemaReader::check_injection("table\0").is_err());
    }

    #[test]
    fn test_full_reverse_loop_verifier() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let verifier = FullReverseLoopVerifier::new(config);
        let schema = DbSchema::new(Dialect::MySql).with_table(make_users_table());

        let report = verifier.verify(&schema).unwrap();
        assert!(report.consistent || !report.diff_descriptions.is_empty());
    }

    #[test]
    fn test_full_reverse_loop_verifier_log() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let verifier = FullReverseLoopVerifier::new(config);
        let schema = DbSchema::new(Dialect::MySql)
            .with_table(make_users_table())
            .with_table(make_orders_table());

        let report = verifier.verify(&schema).unwrap();
        let log = verifier.generate_log(&schema, &report);
        assert_eq!(log.table_count, 2);
        assert!(log.source.contains("db:"));
        assert!(log.generated_items.len() >= 2);
    }

    #[test]
    fn test_columns_sql_generation() {
        let mysql_sql = DbSchemaReader::columns_sql(Dialect::MySql, "users");
        assert!(mysql_sql.contains("INFORMATION_SCHEMA.COLUMNS"));
        assert!(mysql_sql.contains("users"));

        let pg_sql = DbSchemaReader::columns_sql(Dialect::PostgreSql, "users");
        assert!(pg_sql.contains("information_schema.columns"));

        let sqlite_sql = DbSchemaReader::columns_sql(Dialect::Sqlite, "users");
        assert!(sqlite_sql.contains("PRAGMA table_info"));

        let oracle_sql = DbSchemaReader::columns_sql(Dialect::Oracle, "users");
        assert!(oracle_sql.contains("ALL_TAB_COLUMNS"));

        let mssql_sql = DbSchemaReader::columns_sql(Dialect::Mssql, "users");
        assert!(mssql_sql.contains("INFORMATION_SCHEMA.COLUMNS"));
    }

    #[test]
    fn test_constraints_sql_generation() {
        let mysql_sql = DbSchemaReader::constraints_sql(Dialect::MySql, "users");
        assert!(mysql_sql.contains("TABLE_CONSTRAINTS"));

        let pg_sql = DbSchemaReader::constraints_sql(Dialect::PostgreSql, "users");
        assert!(pg_sql.contains("pg_constraint"));

        let sqlite_sql = DbSchemaReader::constraints_sql(Dialect::Sqlite, "users");
        assert!(sqlite_sql.is_empty());

        let oracle_sql = DbSchemaReader::constraints_sql(Dialect::Oracle, "users");
        assert!(oracle_sql.contains("ALL_CONSTRAINTS"));
    }

    #[test]
    fn test_indexes_sql_generation() {
        let mysql_sql = DbSchemaReader::indexes_sql(Dialect::MySql, "users");
        assert!(mysql_sql.contains("STATISTICS"));

        let pg_sql = DbSchemaReader::indexes_sql(Dialect::PostgreSql, "users");
        assert!(pg_sql.contains("pg_indexes"));

        let sqlite_sql = DbSchemaReader::indexes_sql(Dialect::Sqlite, "users");
        assert!(sqlite_sql.contains("PRAGMA index_list"));

        let oracle_sql = DbSchemaReader::indexes_sql(Dialect::Oracle, "users");
        assert!(oracle_sql.is_empty());
    }

    #[test]
    fn test_extract_string_column() {
        let rows: QueryRows = vec![
            {
                let mut m = HashMap::new();
                m.insert("TABLE_NAME".to_string(), Value::String("users".to_string()));
                m
            },
            {
                let mut m = HashMap::new();
                m.insert(
                    "TABLE_NAME".to_string(),
                    Value::String("orders".to_string()),
                );
                m
            },
        ];

        let names = DbSchemaReader::extract_string_column(&rows);
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"users".to_string()));
        assert!(names.contains(&"orders".to_string()));
    }

    #[test]
    fn test_get_string_from_row() {
        let mut row = HashMap::new();
        row.insert("name".to_string(), Value::String("users".to_string()));
        row.insert("null_col".to_string(), Value::Null);

        assert_eq!(
            DbSchemaReader::get_string(&row, "name"),
            Some("users".to_string())
        );
        assert_eq!(DbSchemaReader::get_string(&row, "null_col"), None);
        assert_eq!(DbSchemaReader::get_string(&row, "nonexistent"), None);
    }

    #[test]
    fn test_db_schema_from_tables() {
        let tables = vec![make_users_table(), make_orders_table()];
        let schema = DbSchema::from_tables(Dialect::PostgreSql, tables);
        assert_eq!(schema.dialect, Dialect::PostgreSql);
        assert_eq!(schema.tables.len(), 2);
    }

    #[test]
    fn test_http_method_serialization() {
        let json = serde_json::to_string(&HttpMethod::Get).unwrap();
        assert_eq!(json, "\"GET\"");

        let json = serde_json::to_string(&HttpMethod::Post).unwrap();
        assert_eq!(json, "\"POST\"");
    }

    #[test]
    fn test_db_index() {
        let index = DbIndex {
            name: "idx_users_email".to_string(),
            columns: vec!["email".to_string()],
            unique: true,
        };
        assert!(index.unique);
        assert_eq!(index.columns.len(), 1);
    }

    #[test]
    fn test_openapi_mapper_with_friendly_table_name() {
        let config = ReverseGenConfig::new(Dialect::MySql).with_trust_unsigned(true);
        let mapper = DbSchemaToOpenApiMapper::new(config);
        let table = DbTable {
            name: "user_orders".to_string(),
            columns: vec![DbColumn {
                name: "id".to_string(),
                data_type: "BIGINT".to_string(),
                nullable: false,
                default: None,
                primary_key: true,
                unique: false,
            }],
            constraints: vec![],
            indexes: vec![],
        };
        let schema = DbSchema::new(Dialect::MySql).with_table(table);

        let spec = mapper.map(&schema).unwrap();
        let components = spec.components.as_ref().unwrap();
        assert!(components.schemas.contains_key("user_orders"));
        assert!(spec.paths.contains_key("/user_orders"));
    }

    // ── v4.8.0 修复 M-12:元数据驱动 SQL 注入 ──

    #[test]
    fn test_escape_sql_string_doubles_quotes() {
        assert_eq!(DbSchemaReader::escape_sql_string("users"), "users");
        assert_eq!(DbSchemaReader::escape_sql_string("o'brien"), "o''brien");
        assert_eq!(
            DbSchemaReader::escape_sql_string("x'; DROP TABLE users; --"),
            "x''; DROP TABLE users; --"
        );
    }

    #[test]
    fn test_columns_sql_injection_table_name_escaped() {
        // 恶意表名(元数据被污染场景)不得逃逸 SQL 字面量
        let evil = "x'; DROP TABLE users; --";
        let sql = DbSchemaReader::columns_sql(Dialect::MySql, evil);
        // 单引号必须翻倍:表名整体成为安全字面量 'x''; DROP TABLE users; --'
        assert!(
            sql.contains("'x''; DROP TABLE users; --'"),
            "单引号必须翻倍转义(M-12 修复失效): {sql}"
        );
        // 转义后只存在成对引号(''),不存在可闭合字面量的裸单引号 + 语句边界
        assert!(
            !sql.contains("x'; DROP"),
            "裸单引号不得出现(M-12 修复失效): {sql}"
        );

        // 正常表名不受影响
        let normal = DbSchemaReader::columns_sql(Dialect::MySql, "orders");
        assert!(normal.contains("'orders'"));
        assert!(normal.contains("INFORMATION_SCHEMA.COLUMNS"));

        // Oracle 大写路径同样转义
        let oracle = DbSchemaReader::constraints_sql(Dialect::Oracle, "evil'; DROP");
        assert!(oracle.contains("''"));
        assert!(!oracle.contains("evil'; DROP"));
    }
}