drizzle-migrations 0.1.10

Migration infrastructure for drizzle-rs
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
//! `PostgreSQL` schema code generation
//!
//! This module generates Rust source code from introspected DDL entities.
//! The generated code uses the lowercase attribute syntax (e.g., `primary` instead of `PRIMARY`)
//! that is the current recommended style.

use super::collection::PostgresDDL;
use super::ddl::{Column, Enum, ForeignKey, Index, Table, View};
use crate::utils::escape_for_rust_literal;
use heck::{ToLowerCamelCase, ToPascalCase, ToSnakeCase};
use std::collections::{HashMap, HashSet};
use std::fmt::Write;

/// Result of code generation
#[derive(Debug, Clone, Default)]
pub struct GeneratedSchema {
    /// The generated Rust source code
    pub code: String,
    /// Enums that were generated
    pub enums: Vec<String>,
    /// Tables that were generated
    pub tables: Vec<String>,
    /// Indexes that were generated
    pub indexes: Vec<String>,
    /// Views that were generated
    pub views: Vec<String>,
    /// Any warnings during generation
    pub warnings: Vec<String>,
}

/// Options for code generation
#[derive(Debug, Clone, Default)]
pub struct CodegenOptions {
    /// Module documentation
    pub module_doc: Option<String>,
    /// Whether to include a schema struct
    pub include_schema: bool,
    /// Schema struct name
    pub schema_name: String,
    /// Whether to use public visibility
    pub use_pub: bool,
    /// Field naming style for generated Rust members
    pub field_casing: FieldCasing,
}

/// Casing strategy for generated Rust field names.
#[derive(Debug, Clone, Copy, Default)]
pub enum FieldCasing {
    /// `snake_case` (default)
    #[default]
    Snake,
    /// `camelCase`
    Camel,
    /// Preserve source casing as much as possible
    Preserve,
}

fn sanitize_rust_identifier(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for (idx, ch) in name.chars().enumerate() {
        let valid = if idx == 0 {
            ch == '_' || ch.is_ascii_alphabetic()
        } else {
            ch == '_' || ch.is_ascii_alphanumeric()
        };

        if valid {
            out.push(ch);
        } else {
            out.push('_');
        }
    }

    if out.is_empty() { "_".to_string() } else { out }
}

fn apply_field_casing(name: &str, casing: FieldCasing) -> String {
    match casing {
        FieldCasing::Snake => name.to_snake_case(),
        FieldCasing::Camel => name.to_lower_camel_case(),
        FieldCasing::Preserve => sanitize_rust_identifier(name),
    }
}

/// Lookup tables derived from a [`PostgresDDL`] and shared across every
/// per-entity generation pass.
struct SchemaMaps<'a> {
    enum_map: HashMap<(String, String), String>,
    table_columns: HashMap<(String, String), Vec<&'a Column>>,
    table_pks: HashMap<(String, String), HashSet<String>>,
    table_uniques: HashMap<(String, String), HashSet<String>>,
    fk_map: HashMap<(String, String, String), (&'a ForeignKey, usize)>,
}

fn build_schema_maps(ddl: &PostgresDDL) -> SchemaMaps<'_> {
    let mut enum_map: HashMap<(String, String), String> = HashMap::new();
    for e in ddl.enums.list() {
        let type_name = e.name.to_pascal_case();
        enum_map.insert((e.schema.to_string(), e.name.to_string()), type_name);
    }

    let mut table_columns: HashMap<(String, String), Vec<&Column>> = HashMap::new();
    for column in ddl.columns.list() {
        table_columns
            .entry((column.schema.to_string(), column.table.to_string()))
            .or_default()
            .push(column);
    }

    let mut table_pks: HashMap<(String, String), HashSet<String>> = HashMap::new();
    for pk in ddl.pks.list() {
        for col in pk.columns.iter() {
            table_pks
                .entry((pk.schema.to_string(), pk.table.to_string()))
                .or_default()
                .insert(col.to_string());
        }
    }

    let mut table_uniques: HashMap<(String, String), HashSet<String>> = HashMap::new();
    for unique in ddl.uniques.list() {
        if unique.columns.len() == 1 {
            table_uniques
                .entry((unique.schema.to_string(), unique.table.to_string()))
                .or_default()
                .insert(unique.columns[0].to_string());
        }
    }

    let mut fk_map: HashMap<(String, String, String), (&ForeignKey, usize)> = HashMap::new();
    for fk in ddl.fks.list() {
        for (idx, col) in fk.columns.iter().enumerate() {
            fk_map.insert(
                (fk.schema.to_string(), fk.table.to_string(), col.to_string()),
                (fk, idx),
            );
        }
    }

    SchemaMaps {
        enum_map,
        table_columns,
        table_pks,
        table_uniques,
        fk_map,
    }
}

fn write_module_header(code: &mut String, options: &CodegenOptions) {
    code.push_str("//! Auto-generated PostgreSQL schema from introspection\n");
    code.push_str("//!\n");
    if let Some(doc) = &options.module_doc {
        for line in doc.lines() {
            code.push_str("//! ");
            code.push_str(line);
            code.push('\n');
        }
    }
    code.push('\n');
    code.push_str("use drizzle::postgres::prelude::*;\n\n");
}

/// Generate Rust schema code from DDL
#[must_use]
pub fn generate_rust_schema(ddl: &PostgresDDL, options: &CodegenOptions) -> GeneratedSchema {
    let mut result = GeneratedSchema::default();
    let mut code = String::new();

    write_module_header(&mut code, options);

    let maps = build_schema_maps(ddl);

    // Generate enum definitions
    for e in ddl.enums.list() {
        code.push_str(&generate_enum_struct(e, options.use_pub));
        code.push('\n');
        result.enums.push(e.name.to_string());
    }

    // Generate table structs
    for table in ddl.tables.list() {
        let key = (table.schema.to_string(), table.name.to_string());
        let columns = maps
            .table_columns
            .get(&key)
            .map_or(&[][..], std::vec::Vec::as_slice);
        let pk_columns = maps.table_pks.get(&key);
        let unique_columns = maps.table_uniques.get(&key);
        let is_composite_pk = pk_columns.is_some_and(|pks| pks.len() > 1);

        code.push_str(&generate_table_struct(&TableGenContext {
            table,
            columns,
            pk_columns,
            unique_columns,
            is_composite_pk,
            fk_map: &maps.fk_map,
            enum_map: &maps.enum_map,
            use_pub: options.use_pub,
            field_casing: options.field_casing,
        }));
        code.push('\n');
        result.tables.push(table.name.to_string());
    }

    // Generate index structs
    for index in ddl.indexes.list() {
        code.push_str(&generate_index_struct(
            index,
            options.use_pub,
            options.field_casing,
        ));
        code.push('\n');
        result.indexes.push(index.name.to_string());
    }

    // Generate view structs
    for view in ddl.views.list() {
        if view.is_existing {
            continue;
        }
        let key = (view.schema.to_string(), view.name.to_string());
        let columns = maps
            .table_columns
            .get(&key)
            .map_or(&[][..], std::vec::Vec::as_slice);
        code.push_str(&generate_view_struct(
            view,
            columns,
            &maps.enum_map,
            options.use_pub,
            options.field_casing,
        ));
        code.push('\n');
        result.views.push(view.name.to_string());
    }

    if options.include_schema {
        code.push_str(&generate_schema_struct(
            &options.schema_name,
            &result.tables,
            &result.indexes,
            options.use_pub,
            options.field_casing,
        ));
    }

    result.code = code;
    result
}

/// Context for generating a table struct
struct TableGenContext<'a> {
    table: &'a Table,
    columns: &'a [&'a Column],
    pk_columns: Option<&'a HashSet<String>>,
    unique_columns: Option<&'a HashSet<String>>,
    is_composite_pk: bool,
    fk_map: &'a HashMap<(String, String, String), (&'a ForeignKey, usize)>,
    enum_map: &'a HashMap<(String, String), String>,
    use_pub: bool,
    field_casing: FieldCasing,
}

/// Generate a single table struct
fn generate_table_struct(ctx: &TableGenContext<'_>) -> String {
    let struct_name = ctx.table.name.to_pascal_case();
    let vis = if ctx.use_pub { "pub " } else { "" };

    let mut code = String::new();

    // Table attribute
    code.push_str("#[PostgresTable]\n");

    // Struct definition
    let _ = writeln!(code, "{vis}struct {struct_name} {{");

    // Sort columns by ordinal position if available, falling back to name.
    let mut sorted_columns: Vec<&&Column> = ctx.columns.iter().collect();
    sorted_columns.sort_by(|a, b| {
        let ao = a.ordinal_position.unwrap_or(i32::MAX);
        let bo = b.ordinal_position.unwrap_or(i32::MAX);
        ao.cmp(&bo).then_with(|| a.name.cmp(&b.name))
    });

    // Generate fields
    for column in sorted_columns {
        let field_code = generate_column_field(column, ctx);
        code.push_str(&field_code);
    }

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

/// Format a column's IDENTITY metadata as a `#[column(identity(...))]` fragment.
fn format_identity_attr(identity: &super::ddl::Identity) -> String {
    use super::ddl::IdentityType;
    let identity_type = match identity.type_ {
        IdentityType::Always => "always",
        IdentityType::ByDefault => "by_default",
    };

    let mut seq_opts: Vec<String> = Vec::new();
    if let Some(increment) = &identity.increment
        && increment != "1"
    {
        seq_opts.push(format!("increment = {increment}"));
    }
    if let Some(start) = &identity.start_with
        && start != "1"
    {
        seq_opts.push(format!("start = {start}"));
    }
    if let Some(min) = &identity.min_value {
        seq_opts.push(format!("min_value = {min}"));
    }
    if let Some(max) = &identity.max_value {
        seq_opts.push(format!("max_value = {max}"));
    }
    if let Some(cache) = &identity.cache
        && *cache != 1
    {
        seq_opts.push(format!("cache = {cache}"));
    }
    if identity.cycle == Some(true) {
        seq_opts.push("cycle".to_string());
    }

    if seq_opts.is_empty() {
        format!("identity({identity_type})")
    } else {
        format!("identity({identity_type}, {})", seq_opts.join(", "))
    }
}

/// Push FK-related attributes (`references`, `on_delete`, `on_update`) for a
/// column onto the accumulator.
fn push_fk_attrs(attrs: &mut Vec<String>, fk: &ForeignKey, idx: usize) {
    let ref_table = fk.table_to.to_pascal_case();
    let ref_column = fk.columns_to.get(idx).cloned().unwrap_or_default();
    attrs.push(format!("references = {ref_table}::{ref_column}"));

    if let Some(on_delete) = &fk.on_delete
        && on_delete != "NO ACTION"
    {
        let action = on_delete.to_lowercase().replace(' ', "_");
        attrs.push(format!("on_delete = {action}"));
    }

    if let Some(on_update) = &fk.on_update
        && on_update != "NO ACTION"
    {
        let action = on_update.to_lowercase().replace(' ', "_");
        attrs.push(format!("on_update = {action}"));
    }
}

/// Generate a single column as a struct field
fn generate_column_field(column: &Column, ctx: &TableGenContext<'_>) -> String {
    let field_name = apply_field_casing(column.name.as_ref(), ctx.field_casing);
    let vis = if ctx.use_pub { "pub " } else { "" };

    let col_name_str = column.name.to_string();
    let is_pk = ctx
        .pk_columns
        .is_some_and(|pks| pks.contains(&col_name_str));
    let is_unique = ctx
        .unique_columns
        .is_some_and(|uqs| uqs.contains(&col_name_str));

    // For single-column PKs, add primary. For composite, skip (handled at table level)
    let should_add_primary = is_pk && !ctx.is_composite_pk;

    // Check for serial (nextval default without identity)
    let is_serial = column
        .default
        .as_ref()
        .is_some_and(|d| d.contains("nextval"))
        && column.identity.is_none();

    // Get FK info if present
    let fk_info = ctx.fk_map.get(&(
        column.schema.to_string(),
        column.table.to_string(),
        col_name_str,
    ));

    // Check if this column uses an enum type
    let type_schema = column.type_schema.as_deref().unwrap_or(&column.schema);
    let enum_type = ctx
        .enum_map
        .get(&(type_schema.to_string(), column.sql_type.to_string()));

    // Build column attributes
    let mut attrs = Vec::new();

    // For SERIAL columns (auto-increment via nextval), use "serial" attribute
    if is_serial {
        attrs.push("serial".to_string());
    }

    // For GENERATED IDENTITY columns, use identity(always) or identity(by_default)
    // with optional sequence options
    if let Some(identity) = &column.identity {
        attrs.push(format_identity_attr(identity));
    }

    if should_add_primary {
        attrs.push("primary".to_string());
    }

    if is_unique {
        attrs.push("unique".to_string());
    }

    // Add "enum" attribute for enum-typed columns
    if enum_type.is_some() {
        attrs.push("enum".to_string());
    }

    // Add generated column attribute for GENERATED AS columns
    if let Some(generated) = &column.generated {
        use super::ddl::GeneratedType;
        let gen_type = match generated.gen_type {
            GeneratedType::Stored => "stored",
        };
        // Escape quotes in expression
        let expr = generated.expression.replace('"', "\\\"");
        attrs.push(format!("generated({gen_type}, \"{expr}\")"));
    }

    // Add default if present (but skip nextval for serial columns)
    if let Some(default) = &column.default
        && !is_serial
        && column.generated.is_none()
        && let Some(formatted) = format_default_value(default, &column.sql_type)
    {
        attrs.push(format!("default = {formatted}"));
    }

    // Add FK reference if present
    if let Some((fk, idx)) = fk_info {
        push_fk_attrs(&mut attrs, fk, *idx);
    }

    // Generate attribute line if there are any
    let mut result = String::new();
    if !attrs.is_empty() {
        let _ = writeln!(result, "    #[column({})]", attrs.join(", "));
    }

    // Determine Rust type - use enum type if available, otherwise map SQL type
    let rust_type = enum_type.map_or_else(
        || sql_type_to_rust_type(&column.sql_type, column.not_null),
        |enum_name| {
            if column.not_null {
                enum_name.clone()
            } else {
                format!("Option<{enum_name}>")
            }
        },
    );

    let _ = writeln!(result, "    {vis}{field_name}: {rust_type},");
    result
}

/// Generate a Rust enum definition from a `PostgreSQL` enum
fn generate_enum_struct(e: &Enum, use_pub: bool) -> String {
    let enum_name = e.name.to_pascal_case();
    let vis = if use_pub { "pub " } else { "" };

    let mut code = String::new();

    // Enum derive attribute with PostgresEnum - matches the project's actual usage
    // #[derive(PostgresEnum, Default, Clone, PartialEq, Debug)]
    code.push_str("#[derive(PostgresEnum, Default, Clone, PartialEq, Debug)]\n");

    // Enum definition
    let _ = writeln!(code, "{vis}enum {enum_name} {{");

    // Generate variants from enum values
    for (idx, value) in e.values.iter().enumerate() {
        let variant_name = value.to_pascal_case();
        // First variant gets #[default] attribute
        if idx == 0 {
            code.push_str("    #[default]\n");
        }
        let _ = writeln!(code, "    {variant_name},");
    }

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

/// Format a default value for Rust syntax
fn format_default_value(default: &str, sql_type: &str) -> Option<String> {
    let default = default.trim();

    // Skip defaults that are function calls (like now(), nextval(), etc.)
    if default.contains('(') || default.starts_with("nextval") {
        return None;
    }

    // Handle NULL
    if default.eq_ignore_ascii_case("null") {
        return None;
    }

    // Handle boolean
    if default.eq_ignore_ascii_case("true") || default.eq_ignore_ascii_case("false") {
        return Some(default.to_lowercase());
    }

    // Handle numeric types
    if sql_type.contains("int")
        || sql_type.contains("numeric")
        || sql_type.contains("decimal")
        || sql_type == "float4"
        || sql_type == "float8"
    {
        // Remove type casts like ::integer
        let value = default.split("::").next().unwrap_or(default);
        return Some(value.trim_matches('\'').to_string());
    }

    // Handle text/string types
    if sql_type.contains("text")
        || sql_type.contains("varchar")
        || sql_type.contains("char")
        || sql_type == "bpchar"
    {
        // Keep as quoted string, removing Postgres specific casts
        let value = default.split("::").next().unwrap_or(default);
        let trimmed = value.trim_matches('\'');
        return Some(format!("\"{trimmed}\""));
    }

    // For other types, just return as-is
    Some(default.to_string())
}

/// Convert `PostgreSQL` type to Rust type
#[must_use]
pub fn sql_type_to_rust_type(sql_type: &str, not_null: bool) -> String {
    // Handle PostgreSQL array types, which are often represented as "_typename" (udt_name).
    // Keep this intentionally simple: one-dimensional arrays map to Vec<T>.
    if let Some(elem) = sql_type.strip_prefix('_') {
        let elem_ty = sql_type_to_rust_type(elem, true);
        let base = format!("Vec<{elem_ty}>");
        return if not_null {
            base
        } else {
            format!("Option<{base}>")
        };
    }

    let base_type = match sql_type {
        // Integer types
        s if s.eq_ignore_ascii_case("int2") || s.eq_ignore_ascii_case("smallint") => "i16",
        s if s.eq_ignore_ascii_case("int4")
            || s.eq_ignore_ascii_case("integer")
            || s.eq_ignore_ascii_case("int") =>
        {
            "i32"
        }
        s if s.eq_ignore_ascii_case("int8") || s.eq_ignore_ascii_case("bigint") => "i64",
        s if s.eq_ignore_ascii_case("serial") || s.eq_ignore_ascii_case("serial4") => "i32",
        s if s.eq_ignore_ascii_case("bigserial") || s.eq_ignore_ascii_case("serial8") => "i64",
        s if s.eq_ignore_ascii_case("smallserial") || s.eq_ignore_ascii_case("serial2") => "i16",

        // Floating point
        s if s.eq_ignore_ascii_case("float4") || s.eq_ignore_ascii_case("real") => "f32",
        s if s.eq_ignore_ascii_case("float8") || s.eq_ignore_ascii_case("double precision") => {
            "f64"
        }
        s if s.eq_ignore_ascii_case("numeric") || s.eq_ignore_ascii_case("decimal") => "String", // Use String for precise decimals

        // Boolean
        s if s.eq_ignore_ascii_case("bool") || s.eq_ignore_ascii_case("boolean") => "bool",

        // Text types
        s if s.eq_ignore_ascii_case("text")
            || s.eq_ignore_ascii_case("varchar")
            || s.eq_ignore_ascii_case("char")
            || s.eq_ignore_ascii_case("bpchar")
            || s.eq_ignore_ascii_case("name") =>
        {
            "String"
        }

        // Binary
        s if s.eq_ignore_ascii_case("bytea") => "Vec<u8>",

        // UUID
        s if s.eq_ignore_ascii_case("uuid") => "uuid::Uuid",

        // Date/Time types
        s if s.eq_ignore_ascii_case("date") => "chrono::NaiveDate",
        s if s.eq_ignore_ascii_case("time") => "chrono::NaiveTime",
        s if s.eq_ignore_ascii_case("timestamp") => "chrono::NaiveDateTime",
        s if s.eq_ignore_ascii_case("timestamptz") => "chrono::DateTime<chrono::Utc>",

        // JSON
        s if s.eq_ignore_ascii_case("json") || s.eq_ignore_ascii_case("jsonb") => {
            "serde_json::Value"
        }

        // Default to String for unknown types
        _ => "String",
    };

    if not_null {
        base_type.to_string()
    } else {
        format!("Option<{base_type}>")
    }
}

/// Generate an index struct
fn generate_index_struct(index: &Index, use_pub: bool, field_casing: FieldCasing) -> String {
    let struct_name = index.name.to_pascal_case();
    let table_name = index.table.to_pascal_case();
    let vis = if use_pub { "pub " } else { "" };

    let mut code = String::new();

    // Index attribute
    let attrs = if index.is_unique {
        "#[PostgresIndex(unique)]"
    } else {
        "#[PostgresIndex]"
    };
    let _ = writeln!(code, "{attrs}");

    // Tuple struct with column references
    let columns: Vec<String> = index
        .columns
        .iter()
        .map(|c| {
            if c.is_expression {
                format!("\"{}\"", c.value) // Expression indexes use string literals
            } else {
                format!(
                    "{}::{}",
                    table_name,
                    apply_field_casing(c.value.as_ref(), field_casing)
                )
            }
        })
        .collect();

    let _ = writeln!(code, "{vis}struct {struct_name}({});", columns.join(", "));
    code
}

/// Generate a view struct
fn generate_view_struct(
    view: &View,
    columns: &[&Column],
    enum_map: &HashMap<(String, String), String>,
    use_pub: bool,
    field_casing: FieldCasing,
) -> String {
    let struct_name = view.name.to_pascal_case();
    let vis = if use_pub { "pub " } else { "" };

    let mut code = String::new();

    // Build view attributes
    let mut attrs = Vec::new();

    // Check if view name differs from struct name (snake_case version)
    if apply_field_casing(&struct_name, field_casing) != view.name.as_ref() {
        attrs.push(format!("name = \"{}\"", view.name));
    }

    // Add schema if not public
    if view.schema != "public" {
        attrs.push(format!("schema = \"{}\"", view.schema));
    }

    // Add materialized flag if true
    if view.materialized {
        attrs.push("materialized".to_string());
    }

    // Add WITH NO DATA for materialized views
    if view.with_no_data == Some(true) {
        attrs.push("with_no_data".to_string());
    }

    // Add USING clause for materialized views
    if let Some(using) = &view.using {
        attrs.push(format!("using = \"{using}\""));
    }

    // Add TABLESPACE for materialized views
    if let Some(tablespace) = &view.tablespace {
        attrs.push(format!("tablespace = \"{tablespace}\""));
    }

    // Add definition
    if let Some(def) = &view.definition {
        let escaped_def = escape_for_rust_literal(def);
        attrs.push(format!("definition = \"{escaped_def}\""));
    }

    // Build the attribute line
    if attrs.is_empty() {
        code.push_str("#[PostgresView]\n");
    } else {
        let _ = writeln!(code, "#[PostgresView({})]", attrs.join(", "));
    }

    // Struct definition with column fields
    let _ = writeln!(code, "{vis}struct {struct_name} {{");

    // Sort columns by ordinal position
    let mut sorted_columns: Vec<&&Column> = columns.iter().collect();
    sorted_columns.sort_by(|a, b| {
        let ao = a.ordinal_position.unwrap_or(i32::MAX);
        let bo = b.ordinal_position.unwrap_or(i32::MAX);
        ao.cmp(&bo).then_with(|| a.name.cmp(&b.name))
    });

    // Generate fields for each column
    for column in sorted_columns {
        let field_name = apply_field_casing(column.name.as_ref(), field_casing);

        // Check if this column uses an enum type
        let type_schema = column.type_schema.as_deref().unwrap_or(&column.schema);
        let enum_type = enum_map.get(&(type_schema.to_string(), column.sql_type.to_string()));

        // Determine Rust type - use enum type if available, otherwise map SQL type
        let rust_type = enum_type.map_or_else(
            || sql_type_to_rust_type(&column.sql_type, column.not_null),
            |enum_name| {
                if column.not_null {
                    enum_name.clone()
                } else {
                    format!("Option<{enum_name}>")
                }
            },
        );

        let _ = writeln!(code, "    {vis}{field_name}: {rust_type},");
    }

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

/// Generate a schema struct
fn generate_schema_struct(
    schema_name: &str,
    tables: &[String],
    indexes: &[String],
    use_pub: bool,
    field_casing: FieldCasing,
) -> String {
    let vis = if use_pub { "pub " } else { "" };

    let mut code = String::new();

    // Schema derive
    code.push_str("#[derive(PostgresSchema)]\n");
    let _ = writeln!(code, "{vis}struct {schema_name} {{");

    // Table fields
    for table in tables {
        let field_name = apply_field_casing(table, field_casing);
        let type_name = table.to_pascal_case();
        let _ = writeln!(code, "    {vis}{field_name}: {type_name},");
    }

    // Index fields (commented as they're typically not needed in schema)
    if !indexes.is_empty() {
        code.push_str("    // Indexes:\n");
        for index in indexes {
            let field_name = apply_field_casing(index, field_casing);
            let type_name = index.to_pascal_case();
            let _ = writeln!(code, "    // {field_name}: {type_name},");
        }
    }

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

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

    #[test]
    fn test_sql_type_to_rust_type() {
        assert_eq!(sql_type_to_rust_type("int4", true), "i32");
        assert_eq!(sql_type_to_rust_type("int8", true), "i64");
        assert_eq!(sql_type_to_rust_type("text", true), "String");
        assert_eq!(sql_type_to_rust_type("bool", true), "bool");
        assert_eq!(sql_type_to_rust_type("bytea", true), "Vec<u8>");

        // Nullable types
        assert_eq!(sql_type_to_rust_type("int4", false), "Option<i32>");
        assert_eq!(sql_type_to_rust_type("text", false), "Option<String>");
    }

    #[test]
    fn test_format_default_value() {
        // Numeric
        assert_eq!(format_default_value("42", "int4"), Some("42".to_string()));
        assert_eq!(
            format_default_value("3.14::numeric", "numeric"),
            Some("3.14".to_string())
        );

        // Boolean
        assert_eq!(
            format_default_value("true", "bool"),
            Some("true".to_string())
        );

        // String
        assert_eq!(
            format_default_value("'hello'::text", "text"),
            Some("\"hello\"".to_string())
        );

        // Function calls should be None
        assert_eq!(format_default_value("now()", "timestamp"), None);
        assert_eq!(
            format_default_value("nextval('seq'::regclass)", "int4"),
            None
        );
    }
}