ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
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
use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
use std::collections::HashMap;

/// Code generation engine for creating Rust code from introspected database schema
pub struct CodeGenerator;

impl CodeGenerator {
    /// Generate table! macro definitions from introspected tables
    pub fn generate_table_definitions(&self, tables: &[Table]) -> HashMap<String, String> {
        let mut definitions = HashMap::new();

        for table in tables {
            let table_name = &table.name;
            let primary_key = table.primary_key.as_ref();
            let columns = &table.columns;

            let mut macro_body = String::new();
            macro_body.push_str("use ignis_db::table;\n\n");
            macro_body.push_str(&format!("table!({} ", table_name));

            // Handle primary key - always require one, default to "id"
            let default_pk = "id".to_string();
            let pk = primary_key.unwrap_or(&default_pk);
            if pk.contains(',') {
                // Composite primary key
                macro_body.push_str(&format!("({}) {{\n", pk));
            } else {
                // Single primary key
                macro_body.push_str(&format!("({}) {{\n", pk));
            }

            // Add columns
            for column in columns {
                let column_name = &column.name;
                let column_type = self.column_type_to_macro_type(&column.column_type);
                macro_body.push_str(&format!("    {} -> {},\n", column_name, column_type));
            }

            macro_body.push_str("});");

            definitions.insert(table_name.to_string(), macro_body);
        }

        definitions
    }

    /// Generate view! macro definitions  
    pub fn generate_view_definitions(&self, views: &[View]) -> HashMap<String, String> {
        let mut definitions = HashMap::new();

        for view in views {
            let view_name = &view.name;
            let is_materialized = view.materialized;
            let default_sql = String::new();
            let sql = view.ddl.as_ref().unwrap_or(&default_sql);

            let mut macro_body = String::new();
            if is_materialized {
                macro_body.push_str(&format!("view!({} #[materialized] {{\n", view_name));
            } else {
                macro_body.push_str(&format!("view!({} {{\n", view_name));
            }

            macro_body.push_str(&format!("    {}\n", sql));
            macro_body.push_str("});");

            definitions.insert(view_name.to_string(), macro_body);
        }

        definitions
    }

    /// Generate composite type definitions with #[derive(PgComposite)]
    pub fn generate_composite_definitions(
        &self,
        types: &[CompositeType],
    ) -> HashMap<String, String> {
        let mut definitions = HashMap::new();

        // Collect all composite type names for reference detection
        let composite_type_names: std::collections::HashSet<String> =
            types.iter().map(|t| self.to_pascal_case(&t.name)).collect();

        for composite_type in types {
            let type_name = &composite_type.name;
            let fields = &composite_type.fields;

            let mut struct_body = String::new();
            struct_body.push_str("use ignis_derive::PgComposite;\n");

            // Detect references to other composite types and generate imports
            let mut referenced_types = std::collections::HashSet::new();
            for field in fields {
                let field_type = self.field_type_to_rust_type(&field.field_type);
                // Extract the base type from Option<Type> or Type
                let base_type = if field_type.starts_with("Option<") && field_type.ends_with(">") {
                    field_type[7..field_type.len() - 1].to_string() // Remove "Option<" and ">"
                } else {
                    field_type.clone()
                };

                if composite_type_names.contains(&base_type)
                    && base_type != self.to_pascal_case(type_name)
                {
                    referenced_types.insert(base_type);
                }
            }

            // Add imports for referenced composite types
            for referenced_type in &referenced_types {
                let snake_case_name = self.to_snake_case(referenced_type);
                struct_body.push_str(&format!(
                    "use crate::schema::composite_types::{}::{};\n",
                    snake_case_name, referenced_type
                ));
            }

            struct_body.push_str("\n");
            struct_body.push_str(&format!("#[derive(Debug, Clone, PgComposite)]\n"));
            struct_body.push_str(&format!("#[pg_composite(name = \"{}\")]\n", type_name));
            struct_body.push_str(&format!(
                "pub struct {} {{\n",
                self.to_pascal_case(type_name)
            ));

            for field in fields {
                let field_name = &field.name;
                let field_type = self.field_type_to_rust_type(&field.field_type);
                let nullable = field.nullable;

                let rust_type = if nullable {
                    format!("Option<{}>", field_type)
                } else {
                    field_type
                };

                struct_body.push_str(&format!("    pub {}: {},\n", field_name, rust_type));
            }

            struct_body.push_str("}");

            definitions.insert(type_name.to_string(), struct_body);
        }

        definitions
    }

    /// Generate IgnisModel structs with proper derives
    pub fn generate_model_structs(&self, tables: &[Table]) -> HashMap<String, String> {
        let mut definitions = HashMap::new();

        for table in tables {
            let table_name = &table.name;
            let columns = &table.columns;
            let primary_key = table.primary_key.as_ref();

            let mut struct_body = String::new();
            struct_body
                .push_str("use ignis_db::{IgnisModel, Insertable, Updatable, Deletable};\n\n");
            struct_body.push_str(&format!(
                "#[derive(Debug, Clone, IgnisModel, Insertable, Updatable, Deletable)]\n"
            ));

            // Always require a primary key, default to "id"
            let default_pk = "id".to_string();
            let pk = primary_key.unwrap_or(&default_pk);
            struct_body.push_str(&format!(
                "#[ignis(table = \"{}\", pk = \"{}\")]\n",
                table_name, pk
            ));
            struct_body.push_str(&format!(
                "pub struct {} {{\n",
                self.to_pascal_case(table_name)
            ));

            for column in columns {
                let column_name = &column.name;
                let column_type = self.column_type_to_rust_type(&column.column_type);
                let nullable = column.nullable;

                let rust_type = if nullable {
                    format!("Option<{}>", column_type)
                } else {
                    column_type
                };

                struct_body.push_str(&format!("    pub {}: {},\n", column_name, rust_type));
            }

            struct_body.push_str("}");

            definitions.insert(table_name.to_string(), struct_body);
        }

        definitions
    }

    /// Generate index!, role!, grant! definitions
    pub fn generate_misc_definitions(
        &self,
        indexes: &[Index],
        roles: &[Role],
        grants: &[Grant],
    ) -> HashMap<String, String> {
        let mut definitions = HashMap::new();

        // Generate index definitions
        for index in indexes {
            let index_name = &index.name;
            let table_name = "table_name"; // We don't have table_name in Index struct
            let columns = &index.columns;
            let index_type = if index.unique { "Unique" } else { "BTree" };

            let mut macro_body = String::new();
            macro_body.push_str(&format!("index!({} ON {} {{\n", index_name, table_name));

            for column in columns {
                macro_body.push_str(&format!("    {},\n", column));
            }

            macro_body.push_str(&format!("}} #[{:?}]);", index_type));

            definitions.insert(format!("index_{}", index_name), macro_body);
        }

        // Generate role definitions
        for role in roles {
            let role_name = &role.name;
            let can_login = role.login;
            let is_superuser = role.superuser;

            let mut macro_body = String::new();
            macro_body.push_str(&format!("role! {{\n"));
            macro_body.push_str(&format!("    {} ", role_name));

            if can_login {
                macro_body.push_str("#[login] ");
            }
            if is_superuser {
                macro_body.push_str("#[superuser] ");
            }

            macro_body.push_str("\n}");

            definitions.insert(format!("role_{}", role_name), macro_body);
        }

        // Generate grant definitions
        for grant in grants {
            let grantee = &grant.grantee;
            let privilege = grant.privilege_name();
            let target = &grant.target;
            let object_name = match target {
                crate::schema::GrantTarget::Table { table, .. } => table,
                crate::schema::GrantTarget::Schema(schema) => schema,
                crate::schema::GrantTarget::Database(db) => db,
                crate::schema::GrantTarget::Function { function, .. } => function,
                crate::schema::GrantTarget::AllTablesInSchema(schema) => schema,
                crate::schema::GrantTarget::AllFunctionsInSchema(schema) => schema,
                crate::schema::GrantTarget::Role(role) => role,
            };

            let mut macro_body = String::new();
            macro_body.push_str(&format!("grant! {{\n"));
            macro_body.push_str(&format!(
                "    {} ON {} TO {}\n",
                privilege, object_name, grantee
            ));
            macro_body.push_str("}");

            definitions.insert(
                format!("grant_{}_{}_{}", grantee, privilege, object_name),
                macro_body,
            );
        }

        definitions
    }

    /// Generate complete module structure
    pub fn generate_module_structure(
        &self,
        tables: &[Table],
        views: &[View],
        composite_types: &[CompositeType],
        indexes: &[Index],
        roles: &[Role],
        grants: &[Grant],
    ) -> HashMap<String, String> {
        let mut modules = HashMap::new();

        // Generate schema module
        let schema_mod =
            self.generate_schema_module(tables, views, composite_types, indexes, roles, grants);
        modules.insert("schema/mod.rs".to_string(), schema_mod);

        // Generate models module
        let models_mod = self.generate_models_module(tables);
        modules.insert("models/mod.rs".to_string(), models_mod);

        // Generate individual table modules
        for table in tables {
            let table_name = &table.name;
            let table_mod = self.generate_table_module(table);
            modules.insert(format!("schema/tables/{}.rs", table_name), table_mod);
        }

        // Generate individual view modules
        for view in views {
            let view_name = &view.name;
            let view_mod = self.generate_view_module(view);
            modules.insert(format!("schema/views/{}.rs", view_name), view_mod);
        }

        // Generate individual composite type modules
        for composite_type in composite_types {
            let type_name = &composite_type.name;
            let type_mod = self.generate_composite_type_module(composite_type);
            modules.insert(format!("schema/composite_types/{}.rs", type_name), type_mod);
        }

        modules
    }

    /// Generate the main schema module
    fn generate_schema_module(
        &self,
        tables: &[Table],
        views: &[View],
        composite_types: &[CompositeType],
        _indexes: &[Index],
        _roles: &[Role],
        _grants: &[Grant],
    ) -> String {
        let mut module = String::new();
        module.push_str("// Auto-generated schema module\n");
        module.push_str("// Generated by ignis-db init\n\n");

        // Add table modules
        module.push_str("pub mod tables;\n");
        for table in tables {
            module.push_str(&format!("pub use tables::{};\n", table.name));
        }
        module.push_str("\n");

        // Add view modules
        if !views.is_empty() {
            module.push_str("pub mod views;\n");
            for view in views {
                module.push_str(&format!("pub use views::{};\n", view.name));
            }
            module.push_str("\n");
        }

        // Add composite type modules
        if !composite_types.is_empty() {
            module.push_str("pub mod composite_types;\n");
            for composite_type in composite_types {
                module.push_str(&format!(
                    "pub use composite_types::{};\n",
                    composite_type.name
                ));
            }
            module.push_str("\n");
        }

        module
    }

    /// Generate the models module
    fn generate_models_module(&self, tables: &[Table]) -> String {
        let mut module = String::new();
        module.push_str("// Auto-generated models module\n");
        module.push_str("// Generated by ignis-db init\n\n");

        for table in tables {
            let table_name = &table.name;
            let struct_name = self.to_pascal_case(table_name);
            module.push_str(&format!("pub mod {};\n", table_name));
            module.push_str(&format!("pub use {}::{};\n", table_name, struct_name));
        }

        module
    }

    /// Generate individual table module
    fn generate_table_module(&self, table: &Table) -> String {
        let table_name = &table.name;
        let primary_key = table.primary_key.as_ref();
        let columns = &table.columns;

        let mut module = String::new();
        module.push_str(&format!(
            "// Auto-generated table module for {}\n",
            table_name
        ));
        module.push_str("// Generated by ignis-db init\n\n");

        module.push_str("use crate::schema::{Table, Column, ColumnType};\n\n");

        // Generate table! macro - always require a primary key, default to "id"
        let default_pk = "id".to_string();
        let pk = primary_key.unwrap_or(&default_pk);
        module.push_str(&format!("table!({} ({}) {{\n", table_name, pk));

        for column in columns {
            let column_name = &column.name;
            let column_type = self.column_type_to_macro_type(&column.column_type);
            module.push_str(&format!("    {} -> {},\n", column_name, column_type));
        }

        module.push_str("});\n\n");

        // Generate table() function
        module.push_str(&format!("pub fn table() -> Table {{\n"));
        module.push_str(&format!(
            "    let mut table = Table::new(\"{}\");\n",
            table_name
        ));

        for column in columns {
            let column_name = &column.name;
            let column_type = self.column_type_to_macro_type(&column.column_type);
            module.push_str(&format!(
                "    table = table.add_column(Column::new(\"{}\", {}));\n",
                column_name, column_type
            ));
        }

        // Always set primary key, default to "id"
        module.push_str(&format!("    table = table.set_primary_key(\"{}\");\n", pk));

        module.push_str("    table\n");
        module.push_str("}\n");

        module
    }

    /// Generate individual view module
    fn generate_view_module(&self, view: &View) -> String {
        let view_name = &view.name;
        let is_materialized = view.materialized;
        let default_sql = String::new();
        let sql = view.ddl.as_ref().unwrap_or(&default_sql);

        let mut module = String::new();
        module.push_str(&format!(
            "// Auto-generated view module for {}\n",
            view_name
        ));
        module.push_str("// Generated by ignis-db init\n\n");

        // Generate view! macro
        if is_materialized {
            module.push_str(&format!("view!({} #[materialized] {{\n", view_name));
        } else {
            module.push_str(&format!("view!({} {{\n", view_name));
        }

        module.push_str(&format!("    {}\n", sql));
        module.push_str("});\n");

        module
    }

    /// Generate individual composite type module
    fn generate_composite_type_module(&self, composite_type: &CompositeType) -> String {
        let type_name = &composite_type.name;
        let fields = &composite_type.fields;

        let mut module = String::new();
        module.push_str(&format!(
            "// Auto-generated composite type module for {}\n",
            type_name
        ));
        module.push_str("// Generated by ignis-db init\n\n");

        module.push_str(&format!(
            "use crate::schema::{{CompositeType, CompositeField}};\n\n"
        ));

        // Generate struct
        module.push_str(&format!("#[derive(Debug, Clone, PgComposite)]\n"));
        module.push_str(&format!("#[pg_composite(name = \"{}\")]\n", type_name));
        module.push_str(&format!(
            "pub struct {} {{\n",
            self.to_pascal_case(type_name)
        ));

        for field in fields {
            let field_name = &field.name;
            let field_type = self.field_type_to_rust_type(&field.field_type);
            let nullable = field.nullable;

            let rust_type = if nullable {
                format!("Option<{}>", field_type)
            } else {
                field_type
            };

            module.push_str(&format!("    pub {}: {},\n", field_name, rust_type));
        }

        module.push_str("}\n\n");

        // Generate composite_type() function
        module.push_str(&format!("pub fn composite_type() -> CompositeType {{\n"));
        module.push_str(&format!(
            "    let mut composite_type = CompositeType::new(\"{}\");\n",
            type_name
        ));

        for field in fields {
            let field_name = &field.name;
            let field_type = &field.field_type;
            let nullable = field.nullable;

            module.push_str(&format!("    composite_type = composite_type.add_field(\n"));
            module.push_str(&format!(
                "        CompositeField::new(\"{}\", \"{}\")\n",
                field_name, field_type
            ));
            if !nullable {
                module.push_str(&format!("            .with_nullable(false)\n"));
            }
            module.push_str(&format!("    );\n"));
        }

        module.push_str("    composite_type\n");
        module.push_str("}\n");

        module
    }

    /// Convert column type to macro type string
    fn column_type_to_macro_type(&self, column_type: &crate::schema::ColumnType) -> String {
        match column_type {
            crate::schema::ColumnType::Int4 => "Int4".to_string(),
            crate::schema::ColumnType::Int8 => "Int8".to_string(),
            crate::schema::ColumnType::Int2 => "Int2".to_string(),
            crate::schema::ColumnType::Text => "Text".to_string(),
            crate::schema::ColumnType::Varchar(Some(len)) => format!("Varchar({})", len),
            crate::schema::ColumnType::Varchar(None) => "Varchar".to_string(),
            crate::schema::ColumnType::Char => "Char".to_string(),
            crate::schema::ColumnType::Bool => "Bool".to_string(),
            crate::schema::ColumnType::Timestamptz => "Timestamptz".to_string(),
            // Removed duplicate Timestamptz pattern
            crate::schema::ColumnType::Date => "Date".to_string(),
            crate::schema::ColumnType::Time => "Time".to_string(),
            crate::schema::ColumnType::Uuid => "Uuid".to_string(),
            crate::schema::ColumnType::Numeric(Some(p), Some(s)) => {
                format!("Numeric({}, {})", p, s)
            }
            crate::schema::ColumnType::Numeric(Some(p), None) => format!("Numeric({})", p),
            crate::schema::ColumnType::Numeric(None, Some(s)) => format!("Numeric(, {})", s),
            crate::schema::ColumnType::Numeric(None, None) => "Numeric".to_string(),
            crate::schema::ColumnType::Jsonb => "Jsonb".to_string(),
            crate::schema::ColumnType::Json => "Json".to_string(),
            crate::schema::ColumnType::Bytea => "Bytea".to_string(),
            // Removed duplicate patterns
            crate::schema::ColumnType::Array(inner) => {
                let inner_type = self.column_type_to_macro_type(inner);
                format!("Array({})", inner_type)
            }
            crate::schema::ColumnType::Custom(name) => format!("Custom({})", name),
            // Auto-increment types
            crate::schema::ColumnType::Serial => "Serial".to_string(),
            crate::schema::ColumnType::BigSerial => "BigSerial".to_string(),
            crate::schema::ColumnType::SmallSerial => "SmallSerial".to_string(),
        }
    }

    /// Convert column type to Rust type string
    pub fn column_type_to_rust_type(&self, column_type: &crate::schema::ColumnType) -> String {
        match column_type {
            crate::schema::ColumnType::Int4 => "i32".to_string(),
            crate::schema::ColumnType::Int8 => "i64".to_string(),
            crate::schema::ColumnType::Int2 => "i16".to_string(),
            crate::schema::ColumnType::Text => "String".to_string(),
            crate::schema::ColumnType::Varchar(_) => "String".to_string(),
            crate::schema::ColumnType::Char => "String".to_string(),
            crate::schema::ColumnType::Bool => "bool".to_string(),
            crate::schema::ColumnType::Timestamptz => "chrono::DateTime<chrono::Utc>".to_string(),
            // Removed duplicate Timestamptz pattern
            crate::schema::ColumnType::Date => "chrono::NaiveDate".to_string(),
            crate::schema::ColumnType::Time => "chrono::NaiveTime".to_string(),
            crate::schema::ColumnType::Uuid => "sqlx::types::Uuid".to_string(),
            crate::schema::ColumnType::Numeric(_, _) => "rust_decimal::Decimal".to_string(),
            crate::schema::ColumnType::Jsonb => "serde_json::Value".to_string(),
            crate::schema::ColumnType::Json => "serde_json::Value".to_string(),
            crate::schema::ColumnType::Bytea => "Vec<u8>".to_string(),
            // Removed duplicate patterns
            crate::schema::ColumnType::Array(inner) => {
                let inner_type = self.column_type_to_rust_type(inner);
                format!("Vec<{}>", inner_type)
            }
            crate::schema::ColumnType::Custom(name) => self.to_pascal_case(name),
            // Auto-increment types
            crate::schema::ColumnType::Serial => "i32".to_string(),
            crate::schema::ColumnType::BigSerial => "i64".to_string(),
            crate::schema::ColumnType::SmallSerial => "i16".to_string(),
        }
    }

    /// Convert field type to Rust type string
    fn field_type_to_rust_type(&self, field_type: &str) -> String {
        match field_type.to_lowercase().as_str() {
            "integer" | "int" | "int4" => "i32".to_string(),
            "bigint" | "int8" => "i64".to_string(),
            "smallint" | "int2" => "i16".to_string(),
            "text" => "String".to_string(),
            "varchar" | "character varying" => "String".to_string(),
            "char" | "character" => "String".to_string(),
            "boolean" | "bool" => "bool".to_string(),
            "timestamp with time zone" | "timestamptz" => {
                "chrono::DateTime<chrono::Utc>".to_string()
            }
            "timestamp without time zone" | "timestamp" => "chrono::NaiveDateTime".to_string(),
            "date" => "chrono::NaiveDate".to_string(),
            "time" => "chrono::NaiveTime".to_string(),
            "uuid" => "sqlx::types::Uuid".to_string(),
            "numeric" | "decimal" => "rust_decimal::Decimal".to_string(),
            "jsonb" => "serde_json::Value".to_string(),
            "json" => "serde_json::Value".to_string(),
            "bytea" => "Vec<u8>".to_string(),
            "real" | "float4" => "f32".to_string(),
            "double precision" | "float8" => "f64".to_string(),
            // Handle arrays
            array_type if array_type.ends_with("[]") => {
                let base_type = &array_type[..array_type.len() - 2];
                let base_rust_type = self.field_type_to_rust_type(base_type);
                format!("Vec<{}>", base_rust_type)
            }
            // Handle composite types and other custom types
            custom => self.to_pascal_case(custom),
        }
    }

    /// Convert snake_case to PascalCase
    pub fn to_pascal_case(&self, s: &str) -> String {
        s.split('_')
            .map(|word| {
                let mut chars = word.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().chain(chars).collect(),
                }
            })
            .collect()
    }

    pub fn to_snake_case(&self, s: &str) -> String {
        let mut result = String::new();
        for (i, ch) in s.chars().enumerate() {
            if ch.is_uppercase() && i > 0 {
                result.push('_');
            }
            result.push(ch.to_lowercase().next().unwrap_or(ch));
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{Column, ColumnType};

    #[test]
    fn test_column_type_to_macro_type() {
        let generator = CodeGenerator;

        assert_eq!(
            generator.column_type_to_macro_type(&ColumnType::Int4),
            "Int4"
        );
        assert_eq!(
            generator.column_type_to_macro_type(&ColumnType::Varchar(Some(255))),
            "Varchar(255)"
        );
        assert_eq!(
            generator.column_type_to_macro_type(&ColumnType::Text),
            "Text"
        );
    }

    #[test]
    fn test_column_type_to_rust_type() {
        let generator = CodeGenerator;

        assert_eq!(generator.column_type_to_rust_type(&ColumnType::Int4), "i32");
        assert_eq!(
            generator.column_type_to_rust_type(&ColumnType::Text),
            "String"
        );
        assert_eq!(
            generator.column_type_to_rust_type(&ColumnType::Timestamptz),
            "chrono::DateTime<chrono::Utc>"
        );
    }

    #[test]
    fn test_to_pascal_case() {
        let generator = CodeGenerator;

        assert_eq!(generator.to_pascal_case("user_profile"), "UserProfile");
        assert_eq!(generator.to_pascal_case("order_items"), "OrderItems");
        assert_eq!(generator.to_pascal_case("id"), "Id");
    }
}