prax-orm-cli 0.9.0

CLI tool for the Prax ORM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! `prax generate` command - Generate Rust client code from schema.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::cli::GenerateArgs;
use crate::config::{CONFIG_FILE_NAME, Config, SCHEMA_FILE_PATH};
use crate::error::{CliError, CliResult};
use crate::output::{self, success};

/// Run the generate command
pub async fn run(args: GenerateArgs) -> CliResult<()> {
    output::header("Generate Prax Client");

    let cwd = std::env::current_dir()?;

    // Load config
    let config_path = cwd.join(CONFIG_FILE_NAME);
    let config = if config_path.exists() {
        Config::load(&config_path)?
    } else {
        Config::default()
    };

    // Resolve schema path
    let schema_path = args
        .schema
        .clone()
        .unwrap_or_else(|| cwd.join(SCHEMA_FILE_PATH));
    if !schema_path.exists() {
        return Err(CliError::Config(format!(
            "Schema file not found: {}",
            schema_path.display()
        )));
    }

    // Resolve output directory
    let output_dir = args
        .output
        .clone()
        .unwrap_or_else(|| PathBuf::from(&config.generator.output));

    output::kv("Schema", &schema_path.display().to_string());
    output::kv("Output", &output_dir.display().to_string());
    output::newline();

    output::step(1, 4, "Reading schema...");

    // Parse schema
    let schema_content = std::fs::read_to_string(&schema_path)?;
    let schema = parse_schema(&schema_content)?;

    output::step(2, 4, "Validating schema...");

    // Validate schema
    validate_schema(&schema)?;

    output::step(3, 4, "Generating code...");

    // Create output directory
    std::fs::create_dir_all(&output_dir)?;

    // Generate code
    let generated_files = generate_code(&schema, &output_dir, &args, &config)?;

    output::step(4, 4, "Writing files...");

    // Print generated files
    output::newline();
    output::section("Generated files");

    for file in &generated_files {
        let relative_path = file
            .strip_prefix(&cwd)
            .unwrap_or(file)
            .display()
            .to_string();
        output::list_item(&relative_path);
    }

    output::newline();
    success(&format!(
        "Generated {} files in {:.2}s",
        generated_files.len(),
        0.0 // TODO: Add timing
    ));

    Ok(())
}

/// Parse and validate the schema file
fn parse_schema(content: &str) -> CliResult<prax_schema::Schema> {
    // Use validate_schema to ensure field types are properly resolved
    // (e.g., FieldType::Model -> FieldType::Enum for enum references)
    prax_schema::validate_schema(content)
        .map_err(|e| CliError::Schema(format!("Failed to parse/validate schema: {}", e)))
}

/// Validate the schema (now a no-op since parse_schema does validation)
fn validate_schema(_schema: &prax_schema::Schema) -> CliResult<()> {
    // Validation is now done in parse_schema via validate_schema()
    Ok(())
}

/// Generate code from the schema
fn generate_code(
    schema: &prax_schema::ast::Schema,
    output_dir: &Path,
    args: &GenerateArgs,
    config: &Config,
) -> CliResult<Vec<PathBuf>> {
    let mut generated_files = Vec::new();

    // Determine which features to generate
    let features = if !args.features.is_empty() {
        args.features.clone()
    } else {
        config
            .generator
            .features
            .clone()
            .unwrap_or_else(|| vec!["client".to_string()])
    };

    // Build relation graph for cycle detection
    let relation_graph = build_relation_graph(schema);

    // Generate main client module
    let client_path = output_dir.join("mod.rs");
    let client_code = generate_client_module(schema, &features)?;
    std::fs::write(&client_path, client_code)?;
    generated_files.push(client_path);

    // Generate model modules
    for model in schema.models.values() {
        let model_path = output_dir.join(format!("{}.rs", to_snake_case(model.name())));
        let model_code = generate_model_module(model, &features, &relation_graph)?;
        std::fs::write(&model_path, model_code)?;
        generated_files.push(model_path);
    }

    // Generate enum modules
    for enum_def in schema.enums.values() {
        let enum_path = output_dir.join(format!("{}.rs", to_snake_case(enum_def.name())));
        let enum_code = generate_enum_module(enum_def)?;
        std::fs::write(&enum_path, enum_code)?;
        generated_files.push(enum_path);
    }

    // Generate type definitions
    let types_path = output_dir.join("types.rs");
    let types_code = generate_types_module(schema)?;
    std::fs::write(&types_path, types_code)?;
    generated_files.push(types_path);

    // Generate filters
    let filters_path = output_dir.join("filters.rs");
    let filters_code = generate_filters_module(schema)?;
    std::fs::write(&filters_path, filters_code)?;
    generated_files.push(filters_path);

    Ok(generated_files)
}

/// Build a graph of model relations for cycle detection.
/// Returns a map from model name to the set of model names it references
/// (non-list relations only, since Vec<T> doesn't cause infinite size).
fn build_relation_graph(schema: &prax_schema::ast::Schema) -> HashMap<String, HashSet<String>> {
    let mut graph: HashMap<String, HashSet<String>> = HashMap::new();

    for model in schema.models.values() {
        let entry = graph.entry(model.name().to_string()).or_default();
        for field in model.fields.values() {
            if let prax_schema::ast::FieldType::Model(ref target) = field.field_type
                && !field.is_list()
            {
                entry.insert(target.to_string());
            }
        }
    }

    graph
}

/// Check if a non-list relation field from `source_model` to `target_model`
/// participates in a cycle (i.e. target_model can reach source_model through
/// non-list relations). If so, the field must be wrapped in Box<T>.
fn needs_boxing(
    source_model: &str,
    target_model: &str,
    graph: &HashMap<String, HashSet<String>>,
) -> bool {
    let mut visited = HashSet::new();
    let mut stack = vec![target_model.to_string()];

    while let Some(current) = stack.pop() {
        if current == source_model {
            return true;
        }
        if !visited.insert(current.clone()) {
            continue;
        }
        if let Some(neighbors) = graph.get(&current) {
            for neighbor in neighbors {
                stack.push(neighbor.clone());
            }
        }
    }

    false
}

/// Generate the main client module
fn generate_client_module(
    schema: &prax_schema::ast::Schema,
    _features: &[String],
) -> CliResult<String> {
    let mut code = String::new();

    code.push_str("//! Auto-generated by Prax - DO NOT EDIT\n");
    code.push_str("//!\n");
    code.push_str("//! This module contains the generated Prax client.\n\n");

    // Module declarations
    code.push_str("pub mod types;\n");
    code.push_str("pub mod filters;\n\n");

    for model in schema.models.values() {
        code.push_str(&format!("pub mod {};\n", to_snake_case(model.name())));
    }

    for enum_def in schema.enums.values() {
        code.push_str(&format!("pub mod {};\n", to_snake_case(enum_def.name())));
    }

    code.push('\n');

    // Re-exports
    code.push_str("#[allow(unused_imports)]\npub use types::*;\n");
    code.push_str("#[allow(unused_imports)]\npub use filters::*;\n\n");

    for model in schema.models.values() {
        code.push_str(&format!(
            "#[allow(unused_imports)]\npub use {}::{};\n",
            to_snake_case(model.name()),
            model.name()
        ));
    }

    for enum_def in schema.enums.values() {
        code.push_str(&format!(
            "#[allow(unused_imports)]\npub use {}::{};\n",
            to_snake_case(enum_def.name()),
            enum_def.name()
        ));
    }

    code.push('\n');

    // Client struct with Clone bound and derive
    code.push_str("#[allow(dead_code)]\n");
    code.push_str("/// The Prax database client\n");
    code.push_str("#[derive(Clone)]\n");
    code.push_str("pub struct PraxClient<E: prax_query::QueryEngine> {\n");
    code.push_str("    engine: E,\n");
    code.push_str("}\n\n");

    code.push_str("impl<E: prax_query::QueryEngine> PraxClient<E> {\n");
    code.push_str("    /// Create a new Prax client with the given query engine\n");
    code.push_str("    pub fn new(engine: E) -> Self {\n");
    code.push_str("        Self { engine }\n");
    code.push_str("    }\n\n");

    for model in schema.models.values() {
        let snake_name = to_snake_case(model.name());
        code.push_str(&format!("    /// Access {} operations\n", model.name()));
        code.push_str(&format!(
            "    pub fn {}(&self) -> {}::Client<E> {{\n",
            snake_name, snake_name,
        ));
        code.push_str(&format!(
            "        {}::Client::new(self.engine.clone())\n",
            snake_name,
        ));
        code.push_str("    }\n\n");
    }

    code.push_str("}\n");

    Ok(code)
}

/// Generate a model module
fn generate_model_module(
    model: &prax_schema::ast::Model,
    features: &[String],
    relation_graph: &HashMap<String, HashSet<String>>,
) -> CliResult<String> {
    let mut code = String::new();

    code.push_str(&format!(
        "//! Auto-generated module for {} model\n\n",
        model.name()
    ));

    // Import sibling types for relation fields
    code.push_str("#[allow(unused_imports)]\n");
    code.push_str("use super::*;\n");
    code.push_str("#[allow(unused_imports)]\n");
    code.push_str("use prax_query::traits::Model;\n\n");

    // Derive macros based on features
    let mut derives = vec!["Debug", "Clone"];
    if features.contains(&"serde".to_string()) {
        derives.push("serde::Serialize");
        derives.push("serde::Deserialize");
    }

    // Model struct
    code.push_str("#[allow(dead_code)]\n");
    code.push_str(&format!("#[derive({})]\n", derives.join(", ")));
    code.push_str(&format!("pub struct {} {{\n", model.name()));

    for field in model.fields.values() {
        let field_name = to_snake_case(field.name());

        // Add serde rename if mapped
        if let Some(attr) = field.get_attribute("map")
            && features.contains(&"serde".to_string())
            && let Some(value) = attr.first_arg().and_then(|v| v.as_string())
        {
            code.push_str(&format!("    #[serde(rename = \"{}\")]\n", value));
        }

        let rust_type = field_type_to_rust_with_boxing(
            &field.field_type,
            field.modifier,
            model.name(),
            relation_graph,
        );
        code.push_str(&format!("    pub {}: {},\n", field_name, rust_type));
    }

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

    // Model trait implementation
    let table_name = model.table_name();
    let id_fields: Vec<&str> = model.id_fields().iter().map(|f| f.name()).collect();
    let scalar_columns: Vec<String> = model
        .scalar_fields()
        .iter()
        .map(|f| {
            // Use @map name if present, otherwise snake_case the field name
            f.get_attribute("map")
                .and_then(|a| a.first_arg())
                .and_then(|v| v.as_string())
                .map(|s| s.to_string())
                .unwrap_or_else(|| to_snake_case(f.name()))
        })
        .collect();

    code.push_str(&format!("impl Model for {} {{\n", model.name()));
    code.push_str(&format!(
        "    const MODEL_NAME: &'static str = \"{}\";\n",
        model.name()
    ));
    code.push_str(&format!(
        "    const TABLE_NAME: &'static str = \"{}\";\n",
        table_name
    ));
    code.push_str(&format!(
        "    const PRIMARY_KEY: &'static [&'static str] = &[{}];\n",
        id_fields
            .iter()
            .map(|f| format!("\"{}\"", to_snake_case(f)))
            .collect::<Vec<_>>()
            .join(", ")
    ));
    code.push_str(&format!(
        "    const COLUMNS: &'static [&'static str] = &[{}];\n",
        scalar_columns
            .iter()
            .map(|c| format!("\"{}\"", c))
            .collect::<Vec<_>>()
            .join(", ")
    ));
    code.push_str("}\n\n");

    // FromRow — required to decode rows back into the model when an
    // operation is run. Mirrors the emission in
    // `prax-codegen/src/generators/derive_from_row.rs`: scalar fields
    // decode via `FromColumn`; relation fields default-init and are
    // filled later by the relation executor on the `.include` path.
    code.push_str(&format!(
        "impl prax_query::row::FromRow for {} {{\n",
        model.name()
    ));
    code.push_str(
        "    fn from_row(row: &impl prax_query::row::RowRef)\n        -> Result<Self, prax_query::row::RowError>\n    {\n",
    );
    code.push_str("        Ok(Self {\n");
    for field in model.fields.values() {
        let field_name = to_snake_case(field.name());
        let rust_type = field_type_to_rust_with_boxing(
            &field.field_type,
            field.modifier,
            model.name(),
            relation_graph,
        );
        if field.is_relation() {
            code.push_str(&format!(
                "            {}: ::core::default::Default::default(),\n",
                field_name
            ));
        } else {
            let column = field
                .get_attribute("map")
                .and_then(|a| a.first_arg())
                .and_then(|v| v.as_string())
                .map(|s| s.to_string())
                .unwrap_or_else(|| field_name.clone());
            code.push_str(&format!(
                "            {}: <{} as prax_query::row::FromColumn>::from_column(row, \"{}\")?,\n",
                field_name, rust_type, column
            ));
        }
    }
    code.push_str("        })\n");
    code.push_str("    }\n");
    code.push_str("}\n\n");

    // ModelWithPk — required by composite-key handling and by operations
    // that need to extract the primary key from a model instance (e.g.
    // upsert, nested writes). Mirrors
    // `prax-codegen/src/generators/derive_model_with_pk.rs`.
    code.push_str(&format!(
        "impl prax_query::traits::ModelWithPk for {} {{\n",
        model.name()
    ));
    code.push_str("    fn pk_value(&self) -> prax_query::filter::FilterValue {\n");
    let id_field_objs: Vec<_> = model.id_fields();
    if id_field_objs.len() == 1 {
        let f = id_field_objs[0];
        code.push_str(&format!(
            "        <{} as prax_query::filter::ToFilterValue>::to_filter_value(&self.{})\n",
            field_type_to_rust_with_boxing(&f.field_type, f.modifier, model.name(), relation_graph),
            to_snake_case(f.name())
        ));
    } else if id_field_objs.is_empty() {
        code.push_str("        prax_query::filter::FilterValue::Null\n");
    } else {
        code.push_str("        prax_query::filter::FilterValue::List(vec![\n");
        for f in &id_field_objs {
            code.push_str(&format!(
                "            <{} as prax_query::filter::ToFilterValue>::to_filter_value(&self.{}),\n",
                field_type_to_rust_with_boxing(&f.field_type, f.modifier, model.name(), relation_graph),
                to_snake_case(f.name())
            ));
        }
        code.push_str("        ])\n");
    }
    code.push_str("    }\n\n");

    code.push_str(
        "    fn get_column_value(&self, column: &str)\n        -> ::core::option::Option<prax_query::filter::FilterValue>\n    {\n",
    );
    code.push_str("        match column {\n");
    for field in model.scalar_fields() {
        let field_name = to_snake_case(field.name());
        let column = field
            .get_attribute("map")
            .and_then(|a| a.first_arg())
            .and_then(|v| v.as_string())
            .map(|s| s.to_string())
            .unwrap_or_else(|| field_name.clone());
        let rust_type = field_type_to_rust_with_boxing(
            &field.field_type,
            field.modifier,
            model.name(),
            relation_graph,
        );
        code.push_str(&format!(
            "            \"{}\" => ::core::option::Option::Some(\n                <{} as prax_query::filter::ToFilterValue>::to_filter_value(&self.{})\n            ),\n",
            column, rust_type, field_name
        ));
    }
    code.push_str("            _ => ::core::option::Option::None,\n");
    code.push_str("        }\n");
    code.push_str("    }\n");
    code.push_str("}\n\n");

    // Per-model `Client<E>` (named `Client`, not `{Model}Operations`, so
    // `prax::client!(Foo, Bar, ...)` can find `foo::Client::new(...)`
    // and `bar::Client::new(...)` by snake-cased module path — matching
    // the shape emitted by `#[derive(Model)]`).
    code.push_str("#[allow(dead_code)]\n");
    code.push_str(&format!("/// Operations for the {} model\n", model.name()));
    code.push_str("pub struct Client<E: prax_query::QueryEngine> {\n");
    code.push_str("    engine: E,\n");
    code.push_str("}\n\n");

    code.push_str("impl<E: prax_query::QueryEngine> Client<E> {\n");
    code.push_str("    pub fn new(engine: E) -> Self {\n");
    code.push_str("        Self { engine }\n");
    code.push_str("    }\n\n");

    let model_ty = model.name();
    let crud_methods: &[(&str, &str, &str)] = &[
        ("find_many", "FindManyOperation", "Find many records"),
        ("find_unique", "FindUniqueOperation", "Find a unique record"),
        (
            "find_first",
            "FindFirstOperation",
            "Find the first matching record",
        ),
        ("create", "CreateOperation", "Create a new record"),
        (
            "create_many",
            "CreateManyOperation",
            "Create many records in one operation",
        ),
        ("update", "UpdateOperation", "Update a record"),
        (
            "update_many",
            "UpdateManyOperation",
            "Update many records matching a filter",
        ),
        ("upsert", "UpsertOperation", "Insert or update a record"),
        ("delete", "DeleteOperation", "Delete a record"),
        (
            "delete_many",
            "DeleteManyOperation",
            "Delete many records matching a filter",
        ),
        ("count", "CountOperation", "Count records"),
    ];
    for (method, op_ty, doc) in crud_methods {
        code.push_str(&format!("    /// {}\n", doc));
        code.push_str(&format!(
            "    pub fn {}(&self) -> prax_query::operations::{}<E, {}> {{\n",
            method, op_ty, model_ty,
        ));
        code.push_str(&format!(
            "        prax_query::operations::{}::new(self.engine.clone())\n",
            op_ty,
        ));
        code.push_str("    }\n\n");
    }

    code.push_str("}\n");

    Ok(code)
}

/// Generate an enum module
fn generate_enum_module(enum_def: &prax_schema::ast::Enum) -> CliResult<String> {
    let mut code = String::new();

    code.push_str(&format!(
        "//! Auto-generated module for {} enum\n\n",
        enum_def.name()
    ));

    code.push_str("#[allow(dead_code)]\n");
    code.push_str(
        "#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]\n",
    );
    code.push_str(&format!("pub enum {} {{\n", enum_def.name()));

    for variant in &enum_def.variants {
        let raw_name = variant.name();
        let pascal_name = to_pascal_case(raw_name);

        // Check for explicit @map attribute first
        if let Some(attr) = variant.attributes.iter().find(|a| a.is("map"))
            && let Some(value) = attr.first_arg().and_then(|v| v.as_string())
        {
            code.push_str(&format!("    #[serde(rename = \"{}\")]\n", value));
            code.push_str(&format!("    {},\n", pascal_name));
            continue;
        }

        // If variant name differs from PascalCase form, add serde rename
        if raw_name != pascal_name {
            code.push_str(&format!("    #[serde(rename = \"{}\")]\n", raw_name));
        }
        code.push_str(&format!("    {},\n", pascal_name));
    }

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

    // Display implementation for SQL serialization
    code.push_str(&format!(
        "impl std::fmt::Display for {} {{\n",
        enum_def.name()
    ));
    code.push_str("    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n");
    code.push_str("        match self {\n");
    for variant in &enum_def.variants {
        let raw_name = variant.name();
        let pascal_name = to_pascal_case(raw_name);
        let db_value = variant.db_value();
        code.push_str(&format!(
            "            Self::{} => write!(f, \"{}\"),\n",
            pascal_name, db_value
        ));
    }
    code.push_str("        }\n");
    code.push_str("    }\n");
    code.push_str("}\n\n");

    // Default implementation
    if let Some(default_variant) = enum_def.variants.first() {
        let pascal_name = to_pascal_case(default_variant.name());
        code.push_str(&format!("impl Default for {} {{\n", enum_def.name()));
        code.push_str(&format!(
            "    fn default() -> Self {{\n        Self::{}\n    }}\n",
            pascal_name
        ));
        code.push_str("}\n");
    }

    Ok(code)
}

/// Generate types module
fn generate_types_module(schema: &prax_schema::ast::Schema) -> CliResult<String> {
    let mut code = String::new();

    code.push_str("//! Common type definitions\n\n");
    code.push_str("#[allow(unused_imports)]\npub use chrono::{DateTime, Utc};\n");
    code.push_str("#[allow(unused_imports)]\npub use uuid::Uuid;\n");
    code.push_str("#[allow(unused_imports)]\npub use serde_json::Value as Json;\n");
    code.push('\n');

    // Add any custom types from composite types
    for composite in schema.types.values() {
        code.push_str("#[allow(dead_code)]\n");
        code.push_str("#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n");
        code.push_str(&format!("pub struct {} {{\n", composite.name()));
        for field in composite.fields.values() {
            let rust_type = field_type_to_rust(&field.field_type, field.modifier);
            let field_name = to_snake_case(field.name());
            code.push_str(&format!("    pub {}: {},\n", field_name, rust_type));
        }
        code.push_str("}\n\n");
    }

    Ok(code)
}

/// Generate filters module
fn generate_filters_module(schema: &prax_schema::ast::Schema) -> CliResult<String> {
    let mut code = String::new();

    code.push_str("//! Filter types for queries\n\n");
    code.push_str("#[allow(unused_imports)]\n");
    code.push_str("use prax_query::filter::{Filter, ScalarFilter};\n");

    // Collect all enum types referenced by model scalar fields
    let mut referenced_enums = HashSet::new();
    for model in schema.models.values() {
        for field in model.fields.values() {
            if !field.is_relation()
                && let prax_schema::ast::FieldType::Enum(ref name) = field.field_type
            {
                referenced_enums.insert(name.to_string());
            }
        }
    }

    // Import enum types
    for enum_name in &referenced_enums {
        code.push_str(&format!(
            "#[allow(unused_imports)]\nuse super::{}::{};\n",
            to_snake_case(enum_name),
            enum_name
        ));
    }

    code.push('\n');

    for model in schema.models.values() {
        // Where input
        code.push_str("#[allow(dead_code)]\n");
        code.push_str(&format!("/// Filter input for {} queries\n", model.name()));
        code.push_str("#[derive(Debug, Default, Clone)]\n");
        code.push_str(&format!("pub struct {}WhereInput {{\n", model.name()));

        for field in model.fields.values() {
            if !field.is_relation() {
                let filter_type = field_to_filter_type(&field.field_type);
                let field_name = to_snake_case(field.name());
                code.push_str(&format!(
                    "    pub {}: Option<{}>,\n",
                    field_name, filter_type
                ));
            }
        }

        code.push_str("    pub and: Option<Vec<Self>>,\n");
        code.push_str("    pub or: Option<Vec<Self>>,\n");
        code.push_str("    pub not: Option<Box<Self>>,\n");
        code.push_str("}\n\n");

        // OrderBy input
        code.push_str("#[allow(dead_code)]\n");
        code.push_str(&format!(
            "/// Order by input for {} queries\n",
            model.name()
        ));
        code.push_str("#[derive(Debug, Default, Clone)]\n");
        code.push_str(&format!("pub struct {}OrderByInput {{\n", model.name()));

        for field in model.fields.values() {
            if !field.is_relation() {
                let field_name = to_snake_case(field.name());
                code.push_str(&format!(
                    "    pub {}: Option<prax_query::SortOrder>,\n",
                    field_name
                ));
            }
        }

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

    Ok(code)
}

/// Convert a field type to Rust type (basic, without boxing)
fn field_type_to_rust(
    field_type: &prax_schema::ast::FieldType,
    modifier: prax_schema::ast::TypeModifier,
) -> String {
    use prax_schema::ast::{FieldType, ScalarType, TypeModifier};

    let base_type = match field_type {
        FieldType::Scalar(scalar) => match scalar {
            ScalarType::Int => "i32".to_string(),
            ScalarType::BigInt => "i64".to_string(),
            ScalarType::Float => "f64".to_string(),
            ScalarType::String => "String".to_string(),
            ScalarType::Boolean => "bool".to_string(),
            ScalarType::DateTime => "chrono::DateTime<chrono::Utc>".to_string(),
            ScalarType::Date => "chrono::NaiveDate".to_string(),
            ScalarType::Time => "chrono::NaiveTime".to_string(),
            ScalarType::Json => "serde_json::Value".to_string(),
            ScalarType::Bytes => "Vec<u8>".to_string(),
            ScalarType::Decimal => "rust_decimal::Decimal".to_string(),
            ScalarType::Uuid => "uuid::Uuid".to_string(),
            ScalarType::Cuid => "String".to_string(),
            ScalarType::Cuid2 => "String".to_string(),
            ScalarType::NanoId => "String".to_string(),
            ScalarType::Ulid => "String".to_string(),
            ScalarType::Vector(_) | ScalarType::HalfVector(_) => "Vec<f32>".to_string(),
            ScalarType::SparseVector(_) => "Vec<(u32, f32)>".to_string(),
            ScalarType::Bit(_) => "Vec<u8>".to_string(),
        },
        FieldType::Model(name) => name.to_string(),
        FieldType::Enum(name) => name.to_string(),
        FieldType::Composite(name) => name.to_string(),
        FieldType::Unsupported(_) => "serde_json::Value".to_string(),
    };

    match modifier {
        TypeModifier::Optional | TypeModifier::OptionalList => format!("Option<{}>", base_type),
        TypeModifier::List => format!("Vec<{}>", base_type),
        TypeModifier::Required => base_type,
    }
}

/// Convert a field type to Rust type with Box<T> wrapping for cyclic relations.
fn field_type_to_rust_with_boxing(
    field_type: &prax_schema::ast::FieldType,
    modifier: prax_schema::ast::TypeModifier,
    source_model: &str,
    relation_graph: &HashMap<String, HashSet<String>>,
) -> String {
    use prax_schema::ast::{FieldType, TypeModifier};

    // For model references (non-list), check if boxing is needed to break cycles.
    // Non-list relations are always emitted as `Option<T>` regardless of the
    // schema's required/optional modifier: the relation is "not loaded" until
    // `.include` populates it, so the Rust struct must allow representing the
    // un-included state. This also gives the field a `Default::default()`
    // (== `None`), which `FromRow` relies on to construct a row that hasn't
    // been join-decoded yet. The schema-level required-ness is a database
    // constraint enforced by FK + NOT NULL, not a Rust struct invariant.
    if let FieldType::Model(target) = field_type
        && !matches!(modifier, TypeModifier::List)
    {
        let should_box = needs_boxing(source_model, target, relation_graph);
        let base = target.to_string();
        return if should_box {
            format!("Option<Box<{}>>", base)
        } else {
            format!("Option<{}>", base)
        };
    }

    // Fallback to basic conversion for non-cyclic fields
    field_type_to_rust(field_type, modifier)
}

/// Convert a field type to filter type
fn field_to_filter_type(field_type: &prax_schema::ast::FieldType) -> String {
    use prax_schema::ast::{FieldType, ScalarType};

    match field_type {
        FieldType::Scalar(scalar) => match scalar {
            ScalarType::Int | ScalarType::BigInt => "ScalarFilter<i64>".to_string(),
            ScalarType::Float | ScalarType::Decimal => "ScalarFilter<f64>".to_string(),
            ScalarType::String
            | ScalarType::Uuid
            | ScalarType::Cuid
            | ScalarType::Cuid2
            | ScalarType::NanoId
            | ScalarType::Ulid => "ScalarFilter<String>".to_string(),
            ScalarType::Boolean => "ScalarFilter<bool>".to_string(),
            ScalarType::DateTime => "ScalarFilter<chrono::DateTime<chrono::Utc>>".to_string(),
            ScalarType::Date => "ScalarFilter<chrono::NaiveDate>".to_string(),
            ScalarType::Time => "ScalarFilter<chrono::NaiveTime>".to_string(),
            ScalarType::Json => "ScalarFilter<serde_json::Value>".to_string(),
            ScalarType::Bytes => "ScalarFilter<Vec<u8>>".to_string(),
            // Vector types don't have standard scalar filters
            ScalarType::Vector(_) | ScalarType::HalfVector(_) => "VectorFilter".to_string(),
            ScalarType::SparseVector(_) => "SparseVectorFilter".to_string(),
            ScalarType::Bit(_) => "BitFilter".to_string(),
        },
        FieldType::Enum(name) => format!("ScalarFilter<{}>", name),
        _ => "Filter".to_string(),
    }
}

/// Convert PascalCase to snake_case
fn to_snake_case(name: &str) -> String {
    let mut result = String::new();
    for (i, c) in name.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_lowercase().next().unwrap());
        } else {
            result.push(c);
        }
    }
    result
}

/// Convert snake_case, SCREAMING_SNAKE_CASE, or any other casing to PascalCase.
fn to_pascal_case(name: &str) -> String {
    if name.is_empty() {
        return String::new();
    }

    // If already PascalCase (starts with uppercase, contains lowercase), return as-is
    let first = name.chars().next().unwrap();
    if first.is_uppercase() && name.chars().any(|c| c.is_lowercase()) && !name.contains('_') {
        return name.to_string();
    }

    // Split on underscores and capitalize each segment
    name.split('_')
        .filter(|s| !s.is_empty())
        .map(|segment| {
            let mut chars = segment.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => {
                    let rest: String = chars.collect();
                    format!("{}{}", first.to_uppercase(), rest.to_lowercase())
                }
            }
        })
        .collect()
}

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

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("BoardMember"), "board_member");
        assert_eq!(to_snake_case("User"), "user");
        assert_eq!(to_snake_case("JiraImportConfig"), "jira_import_config");
    }

    #[test]
    fn test_to_pascal_case_from_snake() {
        assert_eq!(to_pascal_case("card_created"), "CardCreated");
        assert_eq!(to_pascal_case("branch_deleted"), "BranchDeleted");
        assert_eq!(to_pascal_case("pr_merged"), "PrMerged");
    }

    #[test]
    fn test_to_pascal_case_from_screaming() {
        assert_eq!(to_pascal_case("CARD_CREATED"), "CardCreated");
        assert_eq!(to_pascal_case("PR_MERGED"), "PrMerged");
    }

    #[test]
    fn test_to_pascal_case_already_pascal() {
        assert_eq!(to_pascal_case("Admin"), "Admin");
        assert_eq!(to_pascal_case("SuperAdmin"), "SuperAdmin");
        assert_eq!(to_pascal_case("Low"), "Low");
    }

    #[test]
    fn test_to_pascal_case_single_word() {
        assert_eq!(to_pascal_case("active"), "Active");
        assert_eq!(to_pascal_case("ACTIVE"), "Active");
    }

    #[test]
    fn test_needs_boxing_direct_cycle() {
        let mut graph = HashMap::new();
        graph.insert(
            "Board".to_string(),
            HashSet::from(["JiraConfig".to_string()]),
        );
        graph.insert(
            "JiraConfig".to_string(),
            HashSet::from(["Board".to_string()]),
        );

        assert!(needs_boxing("Board", "JiraConfig", &graph));
        assert!(needs_boxing("JiraConfig", "Board", &graph));
    }

    #[test]
    fn test_needs_boxing_no_cycle() {
        let mut graph = HashMap::new();
        graph.insert("Post".to_string(), HashSet::from(["User".to_string()]));
        graph.insert("User".to_string(), HashSet::new());

        assert!(!needs_boxing("Post", "User", &graph));
    }

    #[test]
    fn test_needs_boxing_indirect_cycle() {
        let mut graph = HashMap::new();
        graph.insert("A".to_string(), HashSet::from(["B".to_string()]));
        graph.insert("B".to_string(), HashSet::from(["C".to_string()]));
        graph.insert("C".to_string(), HashSet::from(["A".to_string()]));

        assert!(needs_boxing("A", "B", &graph));
        assert!(needs_boxing("B", "C", &graph));
        assert!(needs_boxing("C", "A", &graph));
    }
}