sz-orm-migration 1.2.1

SZ-ORM Migration, Phinx Migration, and Schema Generation
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
//! Diesel 风格 schema.rs 自动生成
//!
//! 从数据库表元数据生成 `typed_query!` 表声明,配合宏做编译期列名校验。
//!
//! # 设计
//!
//! Diesel 的 `diesel print-schema` 命令从数据库反向生成 `schema.rs` 文件,
//! 包含 `table!` 宏声明,让 SQL 列名错误在编译期被捕获。
//!
//! 本模块提供等价功能,生成 SZ-ORM 的 `typed_query!` 声明:
//!
//! ```ignore
//! // 生成的 schema.rs 内容
//! use sz_orm_migration::typed_query;
//!
//! typed_query! {
//!     table users {
//!         id: i64,
//!         name: String,
//!         email: String,
//!         created_at: String,
//!     }
//! }
//!
//! typed_query! {
//!     table orders {
//!         order_id: i64,
//!         user_id: i64,
//!         total: f64,
//!     }
//! }
//! ```

use std::fmt::Write as _;

/// 单列的元数据(足够生成 typed_query! 声明)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnSchema {
    /// 列名
    pub name: String,
    /// Rust 类型名(如 "i64"、"String"、"f64"、"`Option<String>`")
    pub rust_type: String,
}

/// 单表的元数据
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableSchema {
    /// 表名
    pub name: String,
    /// 所有列
    pub columns: Vec<ColumnSchema>,
}

/// 生成器:把表元数据列表转换成 schema.rs 文件内容
pub struct SchemaGenerator {
    /// 文件头注释(默认包含 SZ-ORM 自动生成提示)
    header: String,
    /// 是否生成 `use` 语句
    emit_use: bool,
    /// #41 修复:是否同时生成 Model struct 定义
    ///
    /// 启用后,会在 typed_query! 声明之前生成对应的 Rust struct 定义,
    /// 便于用户直接作为 ORM 模型使用,避免手写重复代码。
    emit_model_structs: bool,
    /// #41 修复:生成的 Model struct 的派生属性
    ///
    /// 默认派生 `Debug, Clone, serde::Serialize, serde::Deserialize`,
    /// 用户可通过 [`with_model_derives`](SchemaGenerator::with_model_derives) 自定义。
    model_derives: String,
}

impl Default for SchemaGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl SchemaGenerator {
    /// 创建新的生成器
    pub fn new() -> Self {
        Self {
            header: format!(
                "// Auto-generated by sz-orm-cli generate schema at {}\n\
                 // DO NOT EDIT MANUALLY — re-run the command to refresh.\n\
                 //\n\
                 // This file contains typed_query! table declarations\n\
                 // enabling compile-time column-name verification.\n",
                chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
            ),
            emit_use: true,
            emit_model_structs: false,
            model_derives: "Debug, Clone, serde::Serialize, serde::Deserialize".to_string(),
        }
    }

    /// 自定义文件头注释
    pub fn with_header(mut self, header: impl Into<String>) -> Self {
        self.header = header.into();
        self
    }

    /// 是否生成 `use sz_orm_migration::typed_query;` 语句
    pub fn emit_use(mut self, emit: bool) -> Self {
        self.emit_use = emit;
        self
    }

    /// #41 修复:是否同时生成 Model struct 定义
    ///
    /// 启用后,[`generate`](Self::generate) 会在 typed_query! 声明之前
    /// 生成对应的 Rust struct 定义,便于直接作为 ORM 模型使用。
    ///
    /// # 示例
    ///
    /// 对于 `users` 表(包含 `id: i64`, `name: String`),会生成:
    ///
    /// ```ignore
    /// #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
    /// pub struct Users {
    ///     pub id: i64,
    ///     pub name: String,
    /// }
    /// ```
    pub fn emit_model_structs(mut self, emit: bool) -> Self {
        self.emit_model_structs = emit;
        self
    }

    /// #41 修复:自定义 Model struct 的派生属性
    ///
    /// 默认为 `"Debug, Clone, serde::Serialize, serde::Deserialize"`。
    /// 传入空字符串则不生成 `#[derive(...)]` 属性。
    pub fn with_model_derives(mut self, derives: impl Into<String>) -> Self {
        self.model_derives = derives.into();
        self
    }

    /// 生成完整的 schema.rs 文件内容
    pub fn generate(&self, tables: &[TableSchema]) -> String {
        let mut out = String::new();

        // 文件头
        let _ = writeln!(out, "{}", self.header);
        let _ = writeln!(out);

        // use 语句
        if self.emit_use {
            let _ = writeln!(out, "use sz_orm_core::typed_query;");
            // 启用 Model struct 生成时,补充 serde 派生所需的 use 语句
            // 合并嵌套 if 为单层 if(clippy::collapsible_if)
            if self.emit_model_structs
                && !self.model_derives.is_empty()
                && self.model_derives.contains("serde::")
            {
                let _ = writeln!(out, "use serde::{{Serialize, Deserialize}};");
            }
            let _ = writeln!(out);
        }

        // #41 修复:先生成 Model struct 定义(在 typed_query! 之前)
        if self.emit_model_structs {
            for (idx, table) in tables.iter().enumerate() {
                if idx > 0 {
                    let _ = writeln!(out);
                }
                let _ = write!(out, "{}", self.render_model_struct(table));
            }
            // Model struct 与 typed_query! 之间空一行
            if !tables.is_empty() {
                let _ = writeln!(out);
                let _ = writeln!(out);
            }
        }

        // 每张表生成一个 typed_query! 声明
        for (idx, table) in tables.iter().enumerate() {
            if idx > 0 {
                let _ = writeln!(out);
            }
            let _ = write!(out, "{}", self.render_table(table));
        }

        out
    }

    /// 渲染单张表的 typed_query! 声明
    fn render_table(&self, table: &TableSchema) -> String {
        let mut out = String::new();
        let _ = writeln!(out, "typed_query! {{");
        let _ = writeln!(out, "    table {} {{", table.name);
        for col in &table.columns {
            let _ = writeln!(out, "        {}: {},", col.name, col.rust_type);
        }
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out, "}}");
        out
    }

    /// #41 修复:渲染单张表对应的 Model struct 定义
    ///
    /// 将表名转换为 PascalCase 作为 struct 名(如 `users` → `Users`),
    /// 字段名保持 snake_case(符合 Rust 命名约定)。
    fn render_model_struct(&self, table: &TableSchema) -> String {
        let struct_name = to_pascal_case(&table.name);
        let mut out = String::new();
        // 派生属性
        if !self.model_derives.is_empty() {
            let _ = writeln!(out, "#[derive({})]", self.model_derives);
        }
        // 表名注解(便于 ORM 框架映射到具体表)
        let _ = writeln!(out, "#[table_name = \"{}\"]", table.name);
        let _ = writeln!(out, "pub struct {} {{", struct_name);
        for col in &table.columns {
            let _ = writeln!(out, "    pub {}: {},", col.name, col.rust_type);
        }
        let _ = writeln!(out, "}}");
        out
    }
}

/// #41 修复:将 snake_case 或 kebab-case 字符串转换为 PascalCase
///
/// 例如:`users` → `Users`,`order_items` → `OrderItems`,
/// `user-profile` → `UserProfile`。
fn to_pascal_case(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut next_upper = true;
    for ch in input.chars() {
        if ch == '_' || ch == '-' || ch == ' ' {
            next_upper = true;
            continue;
        }
        if next_upper {
            result.push(ch.to_ascii_uppercase());
            next_upper = false;
        } else {
            result.push(ch);
        }
    }
    result
}

/// 把 SQL 类型字符串映射到 Rust 类型字符串
///
/// 用于 `generate schema` 命令从 DB 元数据生成 typed_query! 声明
///
/// # P0 修复:精确匹配
///
/// 旧实现使用 `String::contains` 进行子串匹配,存在以下误判:
/// - `INTERVAL` 含 `int` 子串 → 误判为 `i32`(应为 `String`)
/// - `TIMESTAMP` 含 `time` 子串 → 虽因顺序问题未触发,但逻辑脆弱
/// - `MEDIUMINT` 含 `int` → 正确但依赖匹配顺序,不可靠
///
/// 新实现:
/// 1. 小写化
/// 2. 剥离参数列表(`DECIMAL(10,2)` → `decimal`、`VARCHAR(255)` → `varchar`)
/// 3. 剥离无符号/零填充后缀(`INT UNSIGNED` → `int`、`INT ZEROFILL` → `int`)
/// 4. 精确匹配基础类型名,杜绝子串误判
pub fn sql_type_to_rust(sql_type: &str, nullable: bool) -> String {
    // 1. 小写化
    let lower = sql_type.to_lowercase();
    // 2. 剥离参数列表: "DECIMAL(10,2)" → "decimal", "VARCHAR(255)" → "varchar"
    let after_param_strip = lower.split('(').next().unwrap_or(&lower).trim();
    // 3. 剥离无符号/零填充后缀: "INT UNSIGNED" → "INT", "INT ZEROFILL" → "INT"
    //    仅剥离 " unsigned" 与 " zerofill" 后缀,不影响其他类型
    let base_type = after_param_strip
        .strip_suffix(" unsigned")
        .or_else(|| after_param_strip.strip_suffix(" zerofill"))
        .unwrap_or(after_param_strip)
        .trim();

    let rust = match base_type {
        // 整数 — 精确匹配,避免 "interval" 误匹配 "int"
        "tinyint" => "i8",
        "smallint" | "int2" | "smallserial" => "i16",
        "bigint" | "int8" | "bigserial" => "i64",
        "int" | "integer" | "int4" | "mediumint" | "serial" => "i32",
        // 浮点 — "double precision" 需在 "double" 之前匹配(match 按字面顺序,已显式列出)
        "float8" | "double" | "double precision" => "f64",
        "float4" | "real" | "float" => "f32",
        "decimal" | "numeric" => "f64",
        // 布尔
        "bool" | "boolean" => "bool",
        // 字节
        "blob" | "bytea" | "binary" | "varbinary" | "tinyblob" | "mediumblob" | "longblob" => {
            "Vec<u8>"
        }
        // 时间 — interval 单独匹配,不再被 int 子串误判
        "date" => "String",
        "datetime" | "timestamp" | "timestamptz" => "String",
        "time" | "timetz" => "String",
        "interval" => "String",
        // JSON
        "json" | "jsonb" => "String",
        // UUID
        "uuid" => "String",
        // 字符串
        "char" | "varchar" | "text" | "tinytext" | "mediumtext" | "longtext" => "String",
        "enum" | "set" => "String",
        // 默认
        _ => "String",
    };

    if nullable {
        format!("Option<{}>", rust)
    } else {
        rust.to_string()
    }
}

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

    #[test]
    fn test_sql_type_to_rust_int() {
        assert_eq!(sql_type_to_rust("INT", false), "i32");
        assert_eq!(sql_type_to_rust("BIGINT", false), "i64");
        assert_eq!(sql_type_to_rust("SMALLINT", false), "i16");
        assert_eq!(sql_type_to_rust("TINYINT", false), "i8");
    }

    #[test]
    fn test_sql_type_to_rust_float() {
        assert_eq!(sql_type_to_rust("FLOAT", false), "f32");
        assert_eq!(sql_type_to_rust("DOUBLE", false), "f64");
        assert_eq!(sql_type_to_rust("DECIMAL(10,2)", false), "f64");
    }

    #[test]
    fn test_sql_type_to_rust_bool() {
        assert_eq!(sql_type_to_rust("BOOLEAN", false), "bool");
        assert_eq!(sql_type_to_rust("TINYINT(1)", false), "i8");
    }

    #[test]
    fn test_sql_type_to_rust_string() {
        assert_eq!(sql_type_to_rust("VARCHAR(255)", false), "String");
        assert_eq!(sql_type_to_rust("TEXT", false), "String");
        assert_eq!(sql_type_to_rust("CHAR(36)", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_binary() {
        assert_eq!(sql_type_to_rust("BLOB", false), "Vec<u8>");
        assert_eq!(sql_type_to_rust("BYTEA", false), "Vec<u8>");
    }

    #[test]
    fn test_sql_type_to_rust_nullable() {
        assert_eq!(sql_type_to_rust("INT", true), "Option<i32>");
        assert_eq!(sql_type_to_rust("VARCHAR(255)", true), "Option<String>");
    }

    #[test]
    fn test_sql_type_to_rust_pg_types() {
        assert_eq!(sql_type_to_rust("int8", false), "i64");
        assert_eq!(sql_type_to_rust("int2", false), "i16");
        assert_eq!(sql_type_to_rust("float8", false), "f64");
        assert_eq!(sql_type_to_rust("float4", false), "f32");
        assert_eq!(sql_type_to_rust("bytea", false), "Vec<u8>");
    }

    #[test]
    fn test_sql_type_to_rust_json_uuid() {
        assert_eq!(sql_type_to_rust("JSON", false), "String");
        assert_eq!(sql_type_to_rust("JSONB", false), "String");
        assert_eq!(sql_type_to_rust("UUID", false), "String");
    }

    #[test]
    fn test_schema_generator_single_table() {
        let gen = SchemaGenerator::new().emit_use(false);
        let tables = vec![TableSchema {
            name: "users".to_string(),
            columns: vec![
                ColumnSchema {
                    name: "id".to_string(),
                    rust_type: "i64".to_string(),
                },
                ColumnSchema {
                    name: "name".to_string(),
                    rust_type: "String".to_string(),
                },
            ],
        }];
        let output = gen.generate(&tables);

        assert!(output.contains("table users {"));
        assert!(output.contains("id: i64,"));
        assert!(output.contains("name: String,"));
        assert!(output.contains("typed_query! {"));
    }

    #[test]
    fn test_schema_generator_multiple_tables() {
        let gen = SchemaGenerator::new().emit_use(false);
        let tables = vec![
            TableSchema {
                name: "users".to_string(),
                columns: vec![ColumnSchema {
                    name: "id".to_string(),
                    rust_type: "i64".to_string(),
                }],
            },
            TableSchema {
                name: "orders".to_string(),
                columns: vec![ColumnSchema {
                    name: "order_id".to_string(),
                    rust_type: "i64".to_string(),
                }],
            },
        ];
        let output = gen.generate(&tables);

        assert!(output.contains("table users {"));
        assert!(output.contains("table orders {"));
        // 两个表声明之间应有空行
        let users_end = output.find("}").unwrap();
        let orders_start = output.find("table orders").unwrap();
        let between = &output[users_end..orders_start];
        assert!(between.contains("\n\n"));
    }

    #[test]
    fn test_schema_generator_with_use_statement() {
        let gen = SchemaGenerator::new().emit_use(true);
        let tables = vec![TableSchema {
            name: "t".to_string(),
            columns: vec![],
        }];
        let output = gen.generate(&tables);

        assert!(output.contains("use sz_orm_core::typed_query;"));
    }

    #[test]
    fn test_schema_generator_header() {
        let gen = SchemaGenerator::new();
        let output = gen.generate(&[]);
        assert!(output.contains("Auto-generated"));
        assert!(output.contains("DO NOT EDIT MANUALLY"));
    }

    #[test]
    fn test_schema_generator_custom_header() {
        let gen = SchemaGenerator::new().with_header("// Custom header\n");
        let output = gen.generate(&[]);
        assert!(output.starts_with("// Custom header"));
        assert!(!output.contains("Auto-generated"));
    }

    #[test]
    fn test_schema_generator_empty_tables() {
        let gen = SchemaGenerator::new().emit_use(false);
        let output = gen.generate(&[]);
        // 空表列表也应生成(仅有 header,不应有 typed_query! 块)
        assert!(output.contains("Auto-generated"));
        // 应该没有 typed_query! 块(header 里只是描述性文字,不算块)
        // 通过检查 "typed_query! {" 来判断是否有实际声明
        assert!(!output.contains("typed_query! {"));
    }

    #[test]
    fn test_schema_generator_option_type() {
        let gen = SchemaGenerator::new().emit_use(false);
        let tables = vec![TableSchema {
            name: "products".to_string(),
            columns: vec![ColumnSchema {
                name: "price".to_string(),
                rust_type: "Option<f64>".to_string(),
            }],
        }];
        let output = gen.generate(&tables);

        assert!(output.contains("price: Option<f64>,"));
    }

    #[test]
    fn test_schema_generator_compound_type() {
        let gen = SchemaGenerator::new().emit_use(false);
        let tables = vec![TableSchema {
            name: "files".to_string(),
            columns: vec![ColumnSchema {
                name: "content".to_string(),
                rust_type: "Vec<u8>".to_string(),
            }],
        }];
        let output = gen.generate(&tables);

        assert!(output.contains("content: Vec<u8>,"));
    }

    #[test]
    fn test_generated_code_is_valid_syntax() {
        // 验证生成的代码包含正确的 typed_query! 调用语法
        let gen = SchemaGenerator::new().emit_use(false);
        let tables = vec![TableSchema {
            name: "typed_validate_test".to_string(),
            columns: vec![
                ColumnSchema {
                    name: "id".to_string(),
                    rust_type: "i64".to_string(),
                },
                ColumnSchema {
                    name: "name".to_string(),
                    rust_type: "String".to_string(),
                },
            ],
        }];
        let output = gen.generate(&tables);

        // 验证生成的代码包含 typed_query! 块的完整结构
        assert!(output.contains("typed_query! {"));
        assert!(output.contains("table typed_validate_test {"));
        assert!(output.contains("id: i64,"));
        assert!(output.contains("name: String,"));
        // 块应正确闭合
        let count_open = output.matches("typed_query! {").count();
        let count_close = output.matches("}\n}").count();
        assert_eq!(count_open, 1);
        assert_eq!(count_close, 1);
    }

    // ---- P0 修复:精确匹配测试(杜绝 contains 子串误判) ----

    #[test]
    fn test_sql_type_to_rust_interval_not_int() {
        // 关键修复:INTERVAL 不应被 contains("int") 误判为 i32
        assert_eq!(sql_type_to_rust("INTERVAL", false), "String");
        assert_eq!(sql_type_to_rust("interval", false), "String");
        // PostgreSQL INTERVAL DAY TO SECOND 等变体
        assert_eq!(sql_type_to_rust("INTERVAL DAY TO SECOND", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_mediumint() {
        // MySQL MEDIUMINT 应为 i32
        assert_eq!(sql_type_to_rust("MEDIUMINT", false), "i32");
        assert_eq!(sql_type_to_rust("MEDIUMINT(8)", false), "i32");
    }

    #[test]
    fn test_sql_type_to_rust_integer_alias() {
        // INTEGER 是 INT 的别名
        assert_eq!(sql_type_to_rust("INTEGER", false), "i32");
        assert_eq!(sql_type_to_rust("INTEGER(11)", false), "i32");
    }

    #[test]
    fn test_sql_type_to_rust_serial_types() {
        // PostgreSQL SERIAL/BIGSERIAL/SMALLSERIAL
        assert_eq!(sql_type_to_rust("SERIAL", false), "i32");
        assert_eq!(sql_type_to_rust("BIGSERIAL", false), "i64");
        assert_eq!(sql_type_to_rust("SMALLSERIAL", false), "i16");
    }

    #[test]
    fn test_sql_type_to_rust_unsigned_suffix() {
        // MySQL UNSIGNED 后缀剥离
        assert_eq!(sql_type_to_rust("INT UNSIGNED", false), "i32");
        assert_eq!(sql_type_to_rust("BIGINT UNSIGNED", false), "i64");
        assert_eq!(sql_type_to_rust("TINYINT UNSIGNED", false), "i8");
        assert_eq!(sql_type_to_rust("SMALLINT UNSIGNED", false), "i16");
        assert_eq!(sql_type_to_rust("MEDIUMINT UNSIGNED", false), "i32");
    }

    #[test]
    fn test_sql_type_to_rust_zerofill_suffix() {
        // MySQL ZEROFILL 后缀剥离
        assert_eq!(sql_type_to_rust("INT ZEROFILL", false), "i32");
        assert_eq!(sql_type_to_rust("INT(4) ZEROFILL", false), "i32");
    }

    #[test]
    fn test_sql_type_to_rust_timestamptz() {
        // PostgreSQL TIMESTAMPTZ
        assert_eq!(sql_type_to_rust("TIMESTAMPTZ", false), "String");
        assert_eq!(sql_type_to_rust("timestamptz", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_timetz() {
        // PostgreSQL TIMETZ
        assert_eq!(sql_type_to_rust("TIMETZ", false), "String");
        assert_eq!(sql_type_to_rust("timetz", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_double_precision() {
        // PostgreSQL DOUBLE PRECISION(带空格)
        assert_eq!(sql_type_to_rust("DOUBLE PRECISION", false), "f64");
        assert_eq!(sql_type_to_rust("double precision", false), "f64");
    }

    #[test]
    fn test_sql_type_to_rust_varbinary() {
        // MySQL VARBINARY
        assert_eq!(sql_type_to_rust("VARBINARY(255)", false), "Vec<u8>");
        assert_eq!(sql_type_to_rust("VARBINARY", false), "Vec<u8>");
    }

    #[test]
    fn test_sql_type_to_rust_blob_variants() {
        // MySQL TINYBLOB/MEDIUMBLOB/LONGBLOB
        assert_eq!(sql_type_to_rust("TINYBLOB", false), "Vec<u8>");
        assert_eq!(sql_type_to_rust("MEDIUMBLOB", false), "Vec<u8>");
        assert_eq!(sql_type_to_rust("LONGBLOB", false), "Vec<u8>");
    }

    #[test]
    fn test_sql_type_to_rust_text_variants() {
        // MySQL TINYTEXT/MEDIUMTEXT/LONGTEXT
        assert_eq!(sql_type_to_rust("TINYTEXT", false), "String");
        assert_eq!(sql_type_to_rust("MEDIUMTEXT", false), "String");
        assert_eq!(sql_type_to_rust("LONGTEXT", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_enum_and_set() {
        // MySQL ENUM/SET
        assert_eq!(sql_type_to_rust("ENUM('a','b')", false), "String");
        assert_eq!(sql_type_to_rust("SET('a','b')", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_decimal_with_space() {
        // DECIMAL(10, 2)(参数内含空格)
        assert_eq!(sql_type_to_rust("DECIMAL(10, 2)", false), "f64");
        assert_eq!(sql_type_to_rust("NUMERIC(8, 2)", false), "f64");
    }

    #[test]
    fn test_sql_type_to_rust_unknown_defaults_string() {
        // 未知类型默认为 String
        assert_eq!(sql_type_to_rust("UNKNOWN_TYPE", false), "String");
        assert_eq!(sql_type_to_rust("citext", false), "String");
        assert_eq!(sql_type_to_rust("money", false), "String");
    }

    #[test]
    fn test_sql_type_to_rust_interval_nullable() {
        // INTERVAL 可空 → Option<String>
        assert_eq!(sql_type_to_rust("INTERVAL", true), "Option<String>");
    }

    // ====================================================================
    // #41 修复:Model struct 生成测试
    // ====================================================================

    #[test]
    fn test_to_pascal_case_basic() {
        assert_eq!(to_pascal_case("users"), "Users");
        assert_eq!(to_pascal_case("orders"), "Orders");
    }

    #[test]
    fn test_to_pascal_case_snake_case() {
        assert_eq!(to_pascal_case("order_items"), "OrderItems");
        assert_eq!(to_pascal_case("user_profiles"), "UserProfiles");
    }

    #[test]
    fn test_to_pascal_case_kebab_case() {
        assert_eq!(to_pascal_case("user-profile"), "UserProfile");
        assert_eq!(to_pascal_case("order-item"), "OrderItem");
    }

    #[test]
    fn test_to_pascal_case_with_spaces() {
        assert_eq!(to_pascal_case("user profile"), "UserProfile");
    }

    #[test]
    fn test_to_pascal_case_single_char() {
        assert_eq!(to_pascal_case("a"), "A");
        assert_eq!(to_pascal_case("_a"), "A");
    }

    #[test]
    fn test_to_pascal_case_already_pascal() {
        // 已是 PascalCase 的输入应保持原样(首字母仍大写)
        assert_eq!(to_pascal_case("Users"), "Users");
    }

    #[test]
    fn test_emit_model_structs_generates_struct() {
        let gen = SchemaGenerator::new()
            .emit_use(false)
            .emit_model_structs(true);
        let tables = vec![TableSchema {
            name: "users".to_string(),
            columns: vec![
                ColumnSchema {
                    name: "id".to_string(),
                    rust_type: "i64".to_string(),
                },
                ColumnSchema {
                    name: "name".to_string(),
                    rust_type: "String".to_string(),
                },
            ],
        }];
        let output = gen.generate(&tables);

        // 应生成 struct Users
        assert!(output.contains("pub struct Users {"));
        assert!(output.contains("pub id: i64,"));
        assert!(output.contains("pub name: String,"));
        // 应生成派生属性
        assert!(output.contains("#[derive("));
        assert!(output.contains("Debug"));
        assert!(output.contains("Clone"));
        // 应生成表名注解
        assert!(output.contains("#[table_name = \"users\"]"));
        // 同时应生成 typed_query! 声明
        assert!(output.contains("typed_query! {"));
        assert!(output.contains("table users {"));
    }

    #[test]
    fn test_emit_model_structs_disabled_by_default() {
        let gen = SchemaGenerator::new().emit_use(false);
        let tables = vec![TableSchema {
            name: "users".to_string(),
            columns: vec![ColumnSchema {
                name: "id".to_string(),
                rust_type: "i64".to_string(),
            }],
        }];
        let output = gen.generate(&tables);

        // 默认不生成 Model struct
        assert!(!output.contains("pub struct Users"));
        // 但应生成 typed_query! 声明
        assert!(output.contains("typed_query! {"));
    }

    #[test]
    fn test_emit_model_structs_multiple_tables() {
        let gen = SchemaGenerator::new()
            .emit_use(false)
            .emit_model_structs(true);
        let tables = vec![
            TableSchema {
                name: "users".to_string(),
                columns: vec![ColumnSchema {
                    name: "id".to_string(),
                    rust_type: "i64".to_string(),
                }],
            },
            TableSchema {
                name: "order_items".to_string(),
                columns: vec![ColumnSchema {
                    name: "item_id".to_string(),
                    rust_type: "i64".to_string(),
                }],
            },
        ];
        let output = gen.generate(&tables);

        // 应生成两个 struct,且 snake_case 表名转换为 PascalCase
        assert!(output.contains("pub struct Users {"));
        assert!(output.contains("pub struct OrderItems {"));
    }

    #[test]
    fn test_emit_model_structs_with_custom_derives() {
        let gen = SchemaGenerator::new()
            .emit_use(false)
            .emit_model_structs(true)
            .with_model_derives("Debug, Clone");
        let tables = vec![TableSchema {
            name: "users".to_string(),
            columns: vec![ColumnSchema {
                name: "id".to_string(),
                rust_type: "i64".to_string(),
            }],
        }];
        let output = gen.generate(&tables);

        // 应使用自定义派生属性
        assert!(output.contains("#[derive(Debug, Clone)]"));
        // 不应包含默认的 serde 派生
        assert!(!output.contains("serde::Serialize"));
    }

    #[test]
    fn test_emit_model_structs_with_empty_derives() {
        let gen = SchemaGenerator::new()
            .emit_use(false)
            .emit_model_structs(true)
            .with_model_derives("");
        let tables = vec![TableSchema {
            name: "users".to_string(),
            columns: vec![ColumnSchema {
                name: "id".to_string(),
                rust_type: "i64".to_string(),
            }],
        }];
        let output = gen.generate(&tables);

        // 不应生成 #[derive(...)] 属性
        assert!(!output.contains("#[derive("));
        // 但仍应生成 struct 定义
        assert!(output.contains("pub struct Users {"));
    }

    #[test]
    fn test_emit_model_structs_with_nullable_fields() {
        let gen = SchemaGenerator::new()
            .emit_use(false)
            .emit_model_structs(true);
        let tables = vec![TableSchema {
            name: "products".to_string(),
            columns: vec![
                ColumnSchema {
                    name: "id".to_string(),
                    rust_type: "i64".to_string(),
                },
                ColumnSchema {
                    name: "price".to_string(),
                    rust_type: "Option<f64>".to_string(),
                },
                ColumnSchema {
                    name: "description".to_string(),
                    rust_type: "Option<String>".to_string(),
                },
            ],
        }];
        let output = gen.generate(&tables);

        assert!(output.contains("pub struct Products {"));
        assert!(output.contains("pub id: i64,"));
        assert!(output.contains("pub price: Option<f64>,"));
        assert!(output.contains("pub description: Option<String>,"));
    }

    #[test]
    fn test_emit_model_structs_with_serde_use() {
        let gen = SchemaGenerator::new()
            .emit_use(true)
            .emit_model_structs(true);
        let tables = vec![TableSchema {
            name: "users".to_string(),
            columns: vec![ColumnSchema {
                name: "id".to_string(),
                rust_type: "i64".to_string(),
            }],
        }];
        let output = gen.generate(&tables);

        // 启用 serde 派生时应生成对应的 use 语句
        assert!(output.contains("use serde::{Serialize, Deserialize};"));
    }

    #[test]
    fn test_emit_model_structs_empty_tables() {
        let gen = SchemaGenerator::new()
            .emit_use(false)
            .emit_model_structs(true);
        let output = gen.generate(&[]);

        // 空表列表不应生成任何 struct
        assert!(!output.contains("pub struct"));
        // 但应有 header
        assert!(output.contains("Auto-generated"));
    }
}