sz-rust-core 0.6.3

SZ-Rust 核心库:HTTP 服务器、路由、控制器、中间件,对标 ThinkPHP 8
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
//! 迁移历史表(Migration History Table)
//!
//! 持久化记录已执行的迁移版本,避免重复执行。对齐 PHP `think migrate` 的
//! `migrations` 表设计:
//!
//! ```sql
//! CREATE TABLE migrations (
//!     id          BIGINT PRIMARY KEY AUTO_INCREMENT,
//!     version     VARCHAR(255) NOT NULL,         -- 迁移版本号(如 "001")
//!     name        VARCHAR(255) NOT NULL,         -- 迁移名称
//!     batch       INT          NOT NULL,         -- 批次号
//!     executed_at TIMESTAMP    NOT NULL          -- 执行时间
//! );
//! ```
//!
//! ## 多方言支持
//!
//! - MySQL / MariaDB / OceanBase / TiDB / PolarDB:`AUTO_INCREMENT` + `TIMESTAMP DEFAULT CURRENT_TIMESTAMP`
//! - PostgreSQL / KingbaseES / GaussDB:`BIGSERIAL` + `TIMESTAMP DEFAULT NOW()`
//! - SQLite:`INTEGER PRIMARY KEY AUTOINCREMENT` + `DATETIME DEFAULT CURRENT_TIMESTAMP`
//! - Oracle / Dameng:`NUMBER GENERATED BY DEFAULT AS IDENTITY` + `TIMESTAMP DEFAULT SYSTIMESTAMP`
//! - SQL Server / Sybase:`BIGINT IDENTITY(1,1)` + `DATETIME DEFAULT GETDATE()`
//!
//! ## 安全约束
//!
//! - 所有标识符(表名)经 `validate_identifier` 校验,防止 SQL 注入
//! - 占位符按方言生成(`?` vs `$1`),由调用方通过参数绑定执行
//! - 本模块只生成 SQL,不执行 SQL(执行由 sz-rust-cli 或上层应用负责)

use std::fmt;

/// 数据库类型枚举(迁移历史表用方言识别)
///
/// 复刻 sz-orm 的 `DbType` 子集,避免 sz-rust-core 强依赖 sz-orm-core。
/// 仅包含迁移历史表 DDL 关心的主流关系型数据库。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum HistoryDbType {
    /// MySQL / MariaDB / OceanBase / TiDB / PolarDB(AUTO_INCREMENT 方言家族)
    MySQL,
    /// PostgreSQL / KingbaseES / GaussDB(BIGSERIAL 方言家族)
    #[default]
    PostgreSQL,
    /// SQLite(AUTOINCREMENT 方言)
    SQLite,
    /// Oracle / Dameng(GENERATED BY DEFAULT AS IDENTITY 方言家族)
    Oracle,
    /// SQL Server / Sybase(IDENTITY(1,1) 方言家族)
    SqlServer,
}

impl HistoryDbType {
    /// 从字符串解析数据库类型
    ///
    /// 支持的别名(大小写不敏感):
    /// - `mysql` / `mariadb` / `oceanbase` / `tidb` / `polardb` → MySQL
    /// - `postgres` / `postgresql` / `kingbase` / `gaussdb` / `clickhouse` → PostgreSQL
    /// - `sqlite` → SQLite
    /// - `oracle` / `dameng` → Oracle
    /// - `mssql` / `sqlserver` / `sybase` → SqlServer
    ///
    /// 注:命名为 `parse_db_type` 而非 `from_str`,避免与 `std::str::FromStr` trait 冲突。
    pub fn parse_db_type(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "mysql" | "mariadb" | "oceanbase" | "tidb" | "polardb" => Some(Self::MySQL),
            "postgres" | "postgresql" | "kingbase" | "gaussdb" | "clickhouse" => {
                Some(Self::PostgreSQL)
            }
            "sqlite" => Some(Self::SQLite),
            "oracle" | "dameng" => Some(Self::Oracle),
            "mssql" | "sqlserver" | "sybase" => Some(Self::SqlServer),
            _ => None,
        }
    }

    /// 返回占位符(`?` 或 `$1`)
    fn placeholder(&self, index: usize) -> String {
        match self {
            Self::PostgreSQL => format!("${}", index),
            _ => "?".to_string(),
        }
    }
}

impl fmt::Display for HistoryDbType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MySQL => write!(f, "mysql"),
            Self::PostgreSQL => write!(f, "postgres"),
            Self::SQLite => write!(f, "sqlite"),
            Self::Oracle => write!(f, "oracle"),
            Self::SqlServer => write!(f, "mssql"),
        }
    }
}

/// 校验 SQL 标识符(表名/列名),防止 SQL 注入
///
/// 仅允许:字母、数字、下划线,长度 1-64,且不以数字开头。
/// 多表名点号分隔(如 `public.migrations`)按点号拆分后逐段校验。
fn validate_identifier(name: &str, label: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err(format!("{} cannot be empty", label));
    }
    if name.len() > 64 {
        return Err(format!("{} too long (max 64 chars): {}", label, name));
    }
    // 支持模式名.表名(如 public.migrations)
    for segment in name.split('.') {
        if segment.is_empty() {
            return Err(format!("{} has empty segment: {}", label, name));
        }
        let chars: Vec<char> = segment.chars().collect();
        if chars[0].is_ascii_digit() {
            return Err(format!("{} cannot start with digit: {}", label, name));
        }
        for c in chars {
            if !c.is_ascii_alphanumeric() && c != '_' {
                return Err(format!("{} contains invalid char '{}': {}", label, c, name));
            }
        }
    }
    Ok(())
}

/// 迁移历史表仓库
///
/// 封装历史表 DDL 与 CRUD SQL 生成,支持多数据库方言。
/// 仅生成 SQL 字符串,不执行 SQL(执行由调用方负责)。
#[derive(Debug, Clone, Default)]
pub struct MigrationHistory;

impl MigrationHistory {
    /// 生成迁移历史表 DDL(`CREATE TABLE IF NOT EXISTS`)
    ///
    /// # 参数
    ///
    /// - `table_name`:历史表名(默认 `__migrations`)
    /// - `db_type`:目标数据库类型,决定字段类型与自增策略
    ///
    /// # 错误
    ///
    /// 返回 `Result<String, String>`,校验失败时返回 `Err(error_msg)`。
    pub fn create_table_sql(table_name: &str, db_type: HistoryDbType) -> Result<String, String> {
        validate_identifier(table_name, "migration history table name")?;

        let ddl = match db_type {
            // MySQL 方言家族:AUTO_INCREMENT + TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            HistoryDbType::MySQL => format!(
                "CREATE TABLE IF NOT EXISTS {} (\n\
                 \x20   id BIGINT NOT NULL AUTO_INCREMENT,\n\
                 \x20   version VARCHAR(255) NOT NULL,\n\
                 \x20   name VARCHAR(255) NOT NULL,\n\
                 \x20   batch INT NOT NULL,\n\
                 \x20   executed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\
                 \x20   PRIMARY KEY (id),\n\
                 \x20   UNIQUE KEY uk_version (version)\n\
                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
                table_name
            ),
            // PostgreSQL 方言家族:BIGSERIAL + TIMESTAMP DEFAULT NOW()
            HistoryDbType::PostgreSQL => format!(
                "CREATE TABLE IF NOT EXISTS {} (\n\
                 \x20   id BIGSERIAL PRIMARY KEY,\n\
                 \x20   version VARCHAR(255) NOT NULL UNIQUE,\n\
                 \x20   name VARCHAR(255) NOT NULL,\n\
                 \x20   batch INT NOT NULL,\n\
                 \x20   executed_at TIMESTAMP NOT NULL DEFAULT NOW()\n\
                 )",
                table_name
            ),
            // SQLite:INTEGER PRIMARY KEY AUTOINCREMENT
            HistoryDbType::SQLite => format!(
                "CREATE TABLE IF NOT EXISTS {} (\n\
                 \x20   id INTEGER PRIMARY KEY AUTOINCREMENT,\n\
                 \x20   version VARCHAR(255) NOT NULL UNIQUE,\n\
                 \x20   name VARCHAR(255) NOT NULL,\n\
                 \x20   batch INT NOT NULL,\n\
                 \x20   executed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP\n\
                 )",
                table_name
            ),
            // Oracle 方言家族:GENERATED BY DEFAULT AS IDENTITY
            HistoryDbType::Oracle => format!(
                "CREATE TABLE {} (\n\
                 \x20   id NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,\n\
                 \x20   version VARCHAR2(255) NOT NULL UNIQUE,\n\
                 \x20   name VARCHAR2(255) NOT NULL,\n\
                 \x20   batch NUMBER(10) NOT NULL,\n\
                 \x20   executed_at TIMESTAMP NOT NULL DEFAULT SYSTIMESTAMP\n\
                 )",
                table_name
            ),
            // SQL Server 方言家族:IDENTITY(1,1)
            HistoryDbType::SqlServer => format!(
                "CREATE TABLE {} (\n\
                 \x20   id BIGINT IDENTITY(1,1) PRIMARY KEY,\n\
                 \x20   version NVARCHAR(255) NOT NULL UNIQUE,\n\
                 \x20   name NVARCHAR(255) NOT NULL,\n\
                 \x20   batch INT NOT NULL,\n\
                 \x20   executed_at DATETIME NOT NULL DEFAULT GETDATE()\n\
                 )",
                table_name
            ),
        };
        Ok(ddl)
    }

    /// 生成插入历史记录的 SQL(使用占位符 `?` 或 `$1`)
    ///
    /// 占位符顺序:`version`, `name`, `batch`
    ///
    /// # 参数
    ///
    /// - `table_name`:历史表名
    /// - `db_type`:目标数据库类型,决定占位符风格
    pub fn insert_sql(table_name: &str, db_type: HistoryDbType) -> Result<String, String> {
        validate_identifier(table_name, "migration history table name")?;

        let p1 = db_type.placeholder(1);
        let p2 = db_type.placeholder(2);
        let p3 = db_type.placeholder(3);
        Ok(format!(
            "INSERT INTO {} (version, name, batch) VALUES ({}, {}, {})",
            table_name, p1, p2, p3
        ))
    }

    /// 生成删除历史记录的 SQL(按版本号删除)
    ///
    /// # 参数
    ///
    /// - `table_name`:历史表名
    /// - `db_type`:目标数据库类型,决定占位符风格
    pub fn delete_sql(table_name: &str, db_type: HistoryDbType) -> Result<String, String> {
        validate_identifier(table_name, "migration history table name")?;
        let p1 = db_type.placeholder(1);
        Ok(format!("DELETE FROM {} WHERE version = {}", table_name, p1))
    }

    /// 生成查询所有已应用迁移的 SQL(按版本号升序)
    ///
    /// 返回字段:`version`, `name`, `batch`, `executed_at`
    pub fn list_sql(table_name: &str) -> Result<String, String> {
        validate_identifier(table_name, "migration history table name")?;
        Ok(format!(
            "SELECT version, name, batch, executed_at FROM {} ORDER BY version ASC",
            table_name
        ))
    }

    /// 生成查询最大批次号的 SQL
    ///
    /// 返回字段:`max_batch`(无记录时为 NULL,调用方应处理为 0)
    pub fn max_batch_sql(table_name: &str) -> Result<String, String> {
        validate_identifier(table_name, "migration history table name")?;
        Ok(format!(
            "SELECT COALESCE(MAX(batch), 0) AS max_batch FROM {}",
            table_name
        ))
    }

    /// 生成查询指定版本是否已记录的 SQL
    ///
    /// 返回字段:`cnt`(0 表示未记录,1 表示已记录)
    pub fn exists_sql(table_name: &str, db_type: HistoryDbType) -> Result<String, String> {
        validate_identifier(table_name, "migration history table name")?;
        let p1 = db_type.placeholder(1);
        Ok(format!(
            "SELECT COUNT(*) AS cnt FROM {} WHERE version = {}",
            table_name, p1
        ))
    }
}

/// 历史记录条目(对应一行迁移执行记录)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationHistoryRecord {
    /// 迁移版本号
    pub version: String,
    /// 迁移名称
    pub name: String,
    /// 批次号
    pub batch: i32,
    /// 执行时间(ISO 8601 字符串)
    pub executed_at: String,
}

impl MigrationHistoryRecord {
    /// 创建新的历史记录条目
    pub fn new(version: impl Into<String>, name: impl Into<String>, batch: i32) -> Self {
        Self {
            version: version.into(),
            name: name.into(),
            batch,
            executed_at: String::new(),
        }
    }

    /// 设置执行时间
    pub fn with_executed_at(mut self, executed_at: impl Into<String>) -> Self {
        self.executed_at = executed_at.into();
        self
    }
}

/// 迁移历史表配置
#[derive(Debug, Clone)]
pub struct MigrationHistoryConfig {
    /// 历史表名(默认 `__migrations`)
    pub table_name: String,
    /// 数据库类型
    pub db_type: HistoryDbType,
}

impl Default for MigrationHistoryConfig {
    fn default() -> Self {
        Self {
            table_name: "__migrations".to_string(),
            db_type: HistoryDbType::default(),
        }
    }
}

impl MigrationHistoryConfig {
    /// 创建 MySQL 配置
    pub fn mysql() -> Self {
        Self {
            table_name: "__migrations".to_string(),
            db_type: HistoryDbType::MySQL,
        }
    }

    /// 创建 PostgreSQL 配置
    pub fn postgres() -> Self {
        Self {
            table_name: "__migrations".to_string(),
            db_type: HistoryDbType::PostgreSQL,
        }
    }

    /// 创建 SQLite 配置
    pub fn sqlite() -> Self {
        Self {
            table_name: "__migrations".to_string(),
            db_type: HistoryDbType::SQLite,
        }
    }

    /// 设置自定义表名
    pub fn with_table_name(mut self, name: impl Into<String>) -> Self {
        self.table_name = name.into();
        self
    }
}

// ============================================================================
// 单元测试
// ============================================================================

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

    // ========================================================================
    // HistoryDbType
    // ========================================================================

    #[test]
    fn test_db_type_from_str_mysql_family() {
        assert_eq!(
            HistoryDbType::parse_db_type("mysql"),
            Some(HistoryDbType::MySQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("MySQL"),
            Some(HistoryDbType::MySQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("mariadb"),
            Some(HistoryDbType::MySQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("oceanbase"),
            Some(HistoryDbType::MySQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("tidb"),
            Some(HistoryDbType::MySQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("polardb"),
            Some(HistoryDbType::MySQL)
        );
    }

    #[test]
    fn test_db_type_from_str_pg_family() {
        assert_eq!(
            HistoryDbType::parse_db_type("postgres"),
            Some(HistoryDbType::PostgreSQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("postgresql"),
            Some(HistoryDbType::PostgreSQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("kingbase"),
            Some(HistoryDbType::PostgreSQL)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("gaussdb"),
            Some(HistoryDbType::PostgreSQL)
        );
    }

    #[test]
    fn test_db_type_from_str_others() {
        assert_eq!(
            HistoryDbType::parse_db_type("sqlite"),
            Some(HistoryDbType::SQLite)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("oracle"),
            Some(HistoryDbType::Oracle)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("dameng"),
            Some(HistoryDbType::Oracle)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("mssql"),
            Some(HistoryDbType::SqlServer)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("sqlserver"),
            Some(HistoryDbType::SqlServer)
        );
        assert_eq!(
            HistoryDbType::parse_db_type("sybase"),
            Some(HistoryDbType::SqlServer)
        );
    }

    #[test]
    fn test_db_type_from_str_unknown_returns_none() {
        assert_eq!(HistoryDbType::parse_db_type("redis"), None);
        assert_eq!(HistoryDbType::parse_db_type("mongodb"), None);
        assert_eq!(HistoryDbType::parse_db_type(""), None);
    }

    #[test]
    fn test_db_type_display() {
        assert_eq!(format!("{}", HistoryDbType::MySQL), "mysql");
        assert_eq!(format!("{}", HistoryDbType::PostgreSQL), "postgres");
        assert_eq!(format!("{}", HistoryDbType::SQLite), "sqlite");
        assert_eq!(format!("{}", HistoryDbType::Oracle), "oracle");
        assert_eq!(format!("{}", HistoryDbType::SqlServer), "mssql");
    }

    #[test]
    fn test_db_type_default_is_postgres() {
        assert_eq!(HistoryDbType::default(), HistoryDbType::PostgreSQL);
    }

    // ========================================================================
    // validate_identifier
    // ========================================================================

    #[test]
    fn test_validate_identifier_valid() {
        assert!(validate_identifier("__migrations", "table").is_ok());
        assert!(validate_identifier("migrations", "table").is_ok());
        assert!(validate_identifier("public.migrations", "table").is_ok());
        assert!(validate_identifier("_t123", "table").is_ok());
    }

    #[test]
    fn test_validate_identifier_rejects_empty() {
        assert!(validate_identifier("", "table").is_err());
    }

    #[test]
    fn test_validate_identifier_rejects_too_long() {
        let long = "a".repeat(65);
        assert!(validate_identifier(&long, "table").is_err());
    }

    #[test]
    fn test_validate_identifier_rejects_digit_start() {
        assert!(validate_identifier("1table", "table").is_err());
    }

    #[test]
    fn test_validate_identifier_rejects_special_chars() {
        assert!(validate_identifier("table;", "table").is_err());
        assert!(validate_identifier("table'", "table").is_err());
        assert!(validate_identifier("table--", "table").is_err());
        assert!(validate_identifier("ta ble", "table").is_err());
        assert!(validate_identifier("table; DROP TABLE users", "table").is_err());
    }

    #[test]
    fn test_validate_identifier_rejects_empty_segment() {
        assert!(validate_identifier("public..migrations", "table").is_err());
        assert!(validate_identifier(".migrations", "table").is_err());
        assert!(validate_identifier("migrations.", "table").is_err());
    }

    // ========================================================================
    // MigrationHistory::create_table_sql
    // ========================================================================

    #[test]
    fn test_create_table_sql_mysql() {
        let sql = MigrationHistory::create_table_sql("__migrations", HistoryDbType::MySQL).unwrap();
        assert!(sql.contains("CREATE TABLE IF NOT EXISTS __migrations"));
        assert!(sql.contains("AUTO_INCREMENT"));
        assert!(sql.contains("UNIQUE KEY uk_version"));
        assert!(sql.contains("CURRENT_TIMESTAMP"));
    }

    #[test]
    fn test_create_table_sql_postgres() {
        let sql =
            MigrationHistory::create_table_sql("__migrations", HistoryDbType::PostgreSQL).unwrap();
        assert!(sql.contains("BIGSERIAL"));
        assert!(sql.contains("DEFAULT NOW()"));
        assert!(sql.contains("UNIQUE"));
    }

    #[test]
    fn test_create_table_sql_sqlite() {
        let sql =
            MigrationHistory::create_table_sql("__migrations", HistoryDbType::SQLite).unwrap();
        assert!(sql.contains("AUTOINCREMENT"));
        assert!(sql.contains("CURRENT_TIMESTAMP"));
    }

    #[test]
    fn test_create_table_sql_oracle() {
        let sql =
            MigrationHistory::create_table_sql("__migrations", HistoryDbType::Oracle).unwrap();
        assert!(sql.contains("GENERATED BY DEFAULT AS IDENTITY"));
        assert!(sql.contains("SYSTIMESTAMP"));
        assert!(sql.contains("VARCHAR2"));
        // Oracle 不支持 IF NOT EXISTS
        assert!(!sql.contains("IF NOT EXISTS"));
    }

    #[test]
    fn test_create_table_sql_mssql() {
        let sql =
            MigrationHistory::create_table_sql("__migrations", HistoryDbType::SqlServer).unwrap();
        assert!(sql.contains("IDENTITY(1,1)"));
        assert!(sql.contains("GETDATE()"));
        assert!(sql.contains("NVARCHAR"));
    }

    #[test]
    fn test_create_table_sql_supports_schema_qualified_name() {
        let sql =
            MigrationHistory::create_table_sql("public.migrations", HistoryDbType::PostgreSQL)
                .unwrap();
        assert!(sql.contains("public.migrations"));
    }

    #[test]
    fn test_create_table_sql_rejects_injection() {
        let result =
            MigrationHistory::create_table_sql("m; DROP TABLE users", HistoryDbType::MySQL);
        assert!(result.is_err());
    }

    // ========================================================================
    // MigrationHistory::insert_sql
    // ========================================================================

    #[test]
    fn test_insert_sql_mysql_uses_question_mark() {
        let sql = MigrationHistory::insert_sql("__migrations", HistoryDbType::MySQL).unwrap();
        assert!(sql.contains("INSERT INTO __migrations"));
        assert!(sql.contains("(?, ?, ?)"));
    }

    #[test]
    fn test_insert_sql_postgres_uses_dollar() {
        let sql = MigrationHistory::insert_sql("__migrations", HistoryDbType::PostgreSQL).unwrap();
        assert!(sql.contains("($1, $2, $3)"));
    }

    #[test]
    fn test_insert_sql_sqlite_uses_question_mark() {
        let sql = MigrationHistory::insert_sql("__migrations", HistoryDbType::SQLite).unwrap();
        assert!(sql.contains("(?, ?, ?)"));
    }

    #[test]
    fn test_insert_sql_oracle_uses_question_mark() {
        let sql = MigrationHistory::insert_sql("__migrations", HistoryDbType::Oracle).unwrap();
        assert!(sql.contains("(?, ?, ?)"));
    }

    #[test]
    fn test_insert_sql_rejects_injection() {
        let result = MigrationHistory::insert_sql("m; DROP TABLE users", HistoryDbType::MySQL);
        assert!(result.is_err());
    }

    // ========================================================================
    // MigrationHistory::delete_sql
    // ========================================================================

    #[test]
    fn test_delete_sql_mysql() {
        let sql = MigrationHistory::delete_sql("__migrations", HistoryDbType::MySQL).unwrap();
        assert!(sql.contains("DELETE FROM __migrations WHERE version = ?"));
    }

    #[test]
    fn test_delete_sql_postgres() {
        let sql = MigrationHistory::delete_sql("__migrations", HistoryDbType::PostgreSQL).unwrap();
        assert!(sql.contains("WHERE version = $1"));
    }

    #[test]
    fn test_delete_sql_rejects_injection() {
        let result = MigrationHistory::delete_sql("m; DROP TABLE users", HistoryDbType::MySQL);
        assert!(result.is_err());
    }

    // ========================================================================
    // MigrationHistory::list_sql / max_batch_sql / exists_sql
    // ========================================================================

    #[test]
    fn test_list_sql() {
        let sql = MigrationHistory::list_sql("__migrations").unwrap();
        assert!(sql.contains("SELECT version, name, batch, executed_at"));
        assert!(sql.contains("FROM __migrations"));
        assert!(sql.contains("ORDER BY version ASC"));
    }

    #[test]
    fn test_max_batch_sql() {
        let sql = MigrationHistory::max_batch_sql("__migrations").unwrap();
        assert!(sql.contains("COALESCE(MAX(batch), 0)"));
        assert!(sql.contains("AS max_batch"));
    }

    #[test]
    fn test_exists_sql_mysql() {
        let sql = MigrationHistory::exists_sql("__migrations", HistoryDbType::MySQL).unwrap();
        assert!(sql.contains("SELECT COUNT(*) AS cnt"));
        assert!(sql.contains("WHERE version = ?"));
    }

    #[test]
    fn test_exists_sql_postgres() {
        let sql = MigrationHistory::exists_sql("__migrations", HistoryDbType::PostgreSQL).unwrap();
        assert!(sql.contains("WHERE version = $1"));
    }

    #[test]
    fn test_list_sql_rejects_injection() {
        let result = MigrationHistory::list_sql("m; DROP TABLE users");
        assert!(result.is_err());
    }

    // ========================================================================
    // MigrationHistoryRecord
    // ========================================================================

    #[test]
    fn test_history_record_new() {
        let record = MigrationHistoryRecord::new("001", "create_users", 1);
        assert_eq!(record.version, "001");
        assert_eq!(record.name, "create_users");
        assert_eq!(record.batch, 1);
        assert!(record.executed_at.is_empty());
    }

    #[test]
    fn test_history_record_with_executed_at() {
        let record =
            MigrationHistoryRecord::new("001", "init", 1).with_executed_at("2026-07-25T10:00:00Z");
        assert_eq!(record.executed_at, "2026-07-25T10:00:00Z");
    }

    #[test]
    fn test_history_record_equality() {
        let r1 = MigrationHistoryRecord::new("001", "init", 1);
        let r2 = MigrationHistoryRecord::new("001", "init", 1);
        assert_eq!(r1, r2);
    }

    // ========================================================================
    // MigrationHistoryConfig
    // ========================================================================

    #[test]
    fn test_config_default() {
        let config = MigrationHistoryConfig::default();
        assert_eq!(config.table_name, "__migrations");
        assert_eq!(config.db_type, HistoryDbType::PostgreSQL);
    }

    #[test]
    fn test_config_mysql() {
        let config = MigrationHistoryConfig::mysql();
        assert_eq!(config.db_type, HistoryDbType::MySQL);
    }

    #[test]
    fn test_config_postgres() {
        let config = MigrationHistoryConfig::postgres();
        assert_eq!(config.db_type, HistoryDbType::PostgreSQL);
    }

    #[test]
    fn test_config_sqlite() {
        let config = MigrationHistoryConfig::sqlite();
        assert_eq!(config.db_type, HistoryDbType::SQLite);
    }

    #[test]
    fn test_config_with_table_name() {
        let config = MigrationHistoryConfig::default().with_table_name("app_migrations");
        assert_eq!(config.table_name, "app_migrations");
    }

    // ========================================================================
    // 端到端:配置 → SQL 生成
    // ========================================================================

    #[test]
    fn test_end_to_end_mysql_workflow() {
        let config = MigrationHistoryConfig::mysql();

        let ddl = MigrationHistory::create_table_sql(&config.table_name, config.db_type).unwrap();
        assert!(ddl.contains("CREATE TABLE IF NOT EXISTS __migrations"));

        let insert = MigrationHistory::insert_sql(&config.table_name, config.db_type).unwrap();
        assert!(insert.contains("(?, ?, ?)"));

        let delete = MigrationHistory::delete_sql(&config.table_name, config.db_type).unwrap();
        assert!(delete.contains("WHERE version = ?"));

        let list = MigrationHistory::list_sql(&config.table_name).unwrap();
        assert!(list.contains("ORDER BY version ASC"));

        let max_batch = MigrationHistory::max_batch_sql(&config.table_name).unwrap();
        assert!(max_batch.contains("COALESCE(MAX(batch), 0)"));
    }

    #[test]
    fn test_end_to_end_postgres_workflow() {
        let config = MigrationHistoryConfig::postgres();

        let ddl = MigrationHistory::create_table_sql(&config.table_name, config.db_type).unwrap();
        assert!(ddl.contains("BIGSERIAL"));

        let insert = MigrationHistory::insert_sql(&config.table_name, config.db_type).unwrap();
        assert!(insert.contains("($1, $2, $3)"));

        let delete = MigrationHistory::delete_sql(&config.table_name, config.db_type).unwrap();
        assert!(delete.contains("WHERE version = $1"));
    }

    #[test]
    fn test_end_to_end_custom_table_name() {
        let config = MigrationHistoryConfig::default().with_table_name("app_migrations");

        let ddl = MigrationHistory::create_table_sql(&config.table_name, config.db_type).unwrap();
        assert!(ddl.contains("app_migrations"));
    }
}