prax-orm-cli 0.11.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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
//! `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::CliResult;
use crate::output::{self, success};
use crate::schema_loader::load_schema;

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

    if args.watch {
        output::warn("watch mode is not yet implemented; generation will run once");
    }

    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 output directory
    let output_dir = args
        .output
        .clone()
        .unwrap_or_else(|| PathBuf::from(&config.generator.output));

    let display_path = args
        .schema
        .as_deref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| SCHEMA_FILE_PATH.to_string());
    output::kv("Schema", &display_path);
    output::kv("Output", &output_dir.display().to_string());
    output::newline();

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

    let loaded = load_schema(args.schema.as_deref())?;
    let schema = &loaded.schema;
    if loaded.sources.len() > 1 {
        output::kv("Source files", &loaded.sources.len().to_string());
    }

    output::step(2, 4, "Validating schema...");
    // Validation already happened inside load_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", generated_files.len()));

    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)?;
    write_formatted(&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)?;
        write_formatted(&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)?;
        write_formatted(&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)?;
    write_formatted(&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)?;
    write_formatted(&filters_path, &filters_code)?;
    generated_files.push(filters_path);

    Ok(generated_files)
}

/// Pretty-print Rust source via `prettyplease` before writing, so
/// `cargo fmt --check` in consumer repos can run without a
/// `rustfmt.toml` exclusion for generated code. `prettyplease`
/// produces byte-identical output across rustfmt versions —
/// deliberately unlike `cargo fmt` — which is what we want for
/// codegen: the emitter's output must not drift based on whichever
/// rustfmt happens to be on the developer's PATH.
///
/// If the emitted string does not parse as a Rust file
/// (shouldn't happen in practice — `generate_*_module` functions
/// are exercised by the workspace's own tests), fall back to the
/// raw string with a warning rather than blowing up. The fallback
/// keeps `prax generate` unblocked while surfacing the formatter
/// contract violation for whoever added the offending generator.
fn write_formatted(path: &Path, code: &str) -> CliResult<()> {
    let formatted = match syn::parse_file(code) {
        Ok(file) => prettyplease::unparse(&file),
        Err(e) => {
            output::warn(&format!(
                "generated code at {} did not parse; writing unformatted. \
                 This is a codegen bug: {}",
                path.display(),
                e
            ));
            code.to_string()
        }
    };
    std::fs::write(path, formatted)?;
    Ok(())
}

/// 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");
    // Generated code is a superset of the schema's shape; any given
    // consumer only touches a fraction of it, and the codegen favors
    // explicit form over what clippy would write. Silence the lints
    // at the module root so downstream crates don't have to sprinkle
    // allows at every unused accessor / derivable impl / shadowed
    // identifier.
    code.push_str("#![allow(dead_code)]\n");
    code.push_str("#![allow(clippy::derivable_impls)]\n");
    code.push_str("#![allow(clippy::needless_update)]\n");
    code.push_str("#![allow(clippy::too_many_arguments)]\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");

    code.push_str("    /// Borrow the underlying engine. Useful when composing\n");
    code.push_str("    /// per-model operations directly or running raw SQL.\n");
    code.push_str("    pub fn engine(&self) -> &E {\n");
    code.push_str("        &self.engine\n");
    code.push_str("    }\n\n");

    code.push_str("    /// Execute a typed raw SQL query, decoding each returned\n");
    code.push_str("    /// row as `T`. Mirrors `prax_orm::PraxClient::query_raw`.\n");
    code.push_str("    ///\n");
    code.push_str("    /// The typed per-model API covers the common CRUD cases;\n");
    code.push_str("    /// use this for window functions, vendor-specific\n");
    code.push_str("    /// extensions, CTEs, JOIN-driven row shapes, and aggregates\n");
    code.push_str("    /// that the fluent builder doesn't model yet. `T` must\n");
    code.push_str("    /// implement both `Model` (for the table association) and\n");
    code.push_str("    /// `FromRow` (for row decoding); the generator emits both\n");
    code.push_str("    /// impls on every model in this client.\n");
    code.push_str("    pub async fn query_raw<T>(&self, sql: prax_query::raw::Sql)\n");
    code.push_str("        -> prax_query::error::QueryResult<Vec<T>>\n");
    code.push_str("    where\n");
    code.push_str(
        "        T: prax_query::traits::Model + prax_query::row::FromRow + Send + 'static,\n",
    );
    code.push_str("    {\n");
    code.push_str("        let (s, p) = sql.build();\n");
    code.push_str("        self.engine.query_many::<T>(&s, p).await\n");
    code.push_str("    }\n\n");

    code.push_str("    /// Execute a raw statement that doesn't return rows\n");
    code.push_str("    /// (INSERT / UPDATE / DELETE / DDL). Returns the\n");
    code.push_str("    /// driver-reported affected-row count. Mirrors\n");
    code.push_str("    /// `prax_orm::PraxClient::execute_raw`.\n");
    code.push_str("    pub async fn execute_raw(&self, sql: prax_query::raw::Sql)\n");
    code.push_str("        -> prax_query::error::QueryResult<u64>\n");
    code.push_str("    {\n");
    code.push_str("        let (s, p) = sql.build();\n");
    code.push_str("        self.engine.execute_raw(&s, p).await\n");
    code.push_str("    }\n\n");

    code.push_str("    /// Run a closure inside a transaction. The closure receives\n");
    code.push_str("    /// a fresh `PraxClient<E>` wrapping the transaction's engine;\n");
    code.push_str("    /// every query issued through it participates in the same\n");
    code.push_str("    /// transactional scope. Commits on `Ok`, rolls back on\n");
    code.push_str("    /// `Err`. Mirrors `prax_orm::PraxClient::transaction`.\n");
    code.push_str("    ///\n");
    code.push_str("    /// Nested `transaction()` calls on the same engine currently\n");
    code.push_str("    /// return `QueryError::internal(...)` until dialect-aware\n");
    code.push_str("    /// SAVEPOINT support lands.\n");
    code.push_str("    pub async fn transaction<R, Fut, F>(&self, f: F)\n");
    code.push_str("        -> prax_query::error::QueryResult<R>\n");
    code.push_str("    where\n");
    code.push_str("        F: FnOnce(PraxClient<E>) -> Fut + Send + 'static,\n");
    code.push_str("        Fut: ::core::future::Future<Output = prax_query::error::QueryResult<R>> + Send + 'static,\n");
    code.push_str("        R: Send + 'static,\n");
    code.push_str("    {\n");
    code.push_str("        self.engine\n");
    code.push_str("            .transaction(move |tx_engine| async move { f(PraxClient::new(tx_engine)).await })\n");
    code.push_str("            .await\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_field_ident(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_field_ident(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_field_ident(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_field_ident(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() {
        // Rust field identifier — escape reserved keywords.
        let field_name = to_field_ident(field.name());
        // SQL column name — use raw snake_case (no r# prefix) because the
        // @map override or fallback feeds a string literal passed to
        // `FromColumn::from_column(row, "...")`, not an identifier.
        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(|| to_snake_case(field.name()));
        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");

    // ModelRelationLoader — uniformity requirement for
    // `FindManyOperation` / `FindUniqueOperation` / `FindFirstOperation`
    // bounds. Schema-generated models don't currently expose the
    // relation-accessor surface that the derive path does (no
    // `super::super::<module>::<field>::Relation` markers), so every
    // `.include(...)` attempt on a schema-generated model errors at
    // runtime rather than at compile time. That's acceptable for now —
    // plain `find_unique()` / `find_many()` without `.include()` work,
    // which is what every current consumer of the schema-gen path uses.
    // Adding real relation loading here is tracked as a follow-up.
    code.push_str(&format!(
        "impl<E: prax_query::traits::QueryEngine>\n    prax_query::traits::ModelRelationLoader<E>\n    for {}\n{{\n",
        model.name()
    ));
    code.push_str("    fn load_relation<'a>(\n");
    code.push_str("        _engine: &'a E,\n");
    code.push_str("        _parents: &'a mut [Self],\n");
    code.push_str("        spec: &'a prax_query::relations::IncludeSpec,\n");
    code.push_str(
        "    ) -> prax_query::traits::BoxFuture<'a, prax_query::error::QueryResult<()>> {\n",
    );
    code.push_str("        let name = spec.relation_name.clone();\n");
    code.push_str(&format!("        let model_name = \"{}\";\n", model.name()));
    code.push_str("        Box::pin(async move {\n");
    code.push_str("            Err(prax_query::error::QueryError::internal(format!(\n");
    code.push_str("                \"relation '{}' on schema-generated model '{}' is not wired for .include() — use query_raw for JOINs\",\n");
    code.push_str("                name,\n");
    code.push_str("                model_name,\n");
    code.push_str("            )))\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\n");
    }

    // Round-trip helper: parse the DB string form back into an enum variant.
    // Used by the `FromColumn` impls below and callable directly by
    // consumers that need to deserialize a raw string payload.
    code.push_str(&format!(
        "impl std::str::FromStr for {} {{\n",
        enum_def.name()
    ));
    code.push_str("    type Err = prax_query::row::RowError;\n");
    code.push_str("    fn from_str(s: &str) -> Result<Self, Self::Err> {\n");
    code.push_str("        match s {\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!(
            "            \"{}\" => Ok(Self::{}),\n",
            db_value, pascal_name
        ));
    }
    code.push_str(&format!(
        "            _ => Err(prax_query::row::RowError::TypeConversion {{\n                column: String::new(),\n                message: format!(\"unknown {} variant: {{}}\", s),\n            }}),\n",
        enum_def.name()
    ));
    code.push_str("        }\n");
    code.push_str("    }\n");
    code.push_str("}\n\n");

    // `FromColumn` — decode a string column back into the enum. Required
    // for `find_many` / `find_unique` / any query that returns rows with
    // this enum as a field type.
    code.push_str(&format!(
        "impl prax_query::row::FromColumn for {} {{\n",
        enum_def.name()
    ));
    code.push_str(
        "    fn from_column(row: &impl prax_query::row::RowRef, column: &str)\n        -> Result<Self, prax_query::row::RowError>\n    {\n",
    );
    code.push_str("        let raw = row.get_string(column)?;\n");
    code.push_str("        <Self as std::str::FromStr>::from_str(&raw).map_err(|e| {\n");
    code.push_str("            let msg = match &e {\n");
    code.push_str(
        "                prax_query::row::RowError::TypeConversion { message, .. } => message.clone(),\n",
    );
    code.push_str("                other => other.to_string(),\n");
    code.push_str("            };\n");
    code.push_str("            prax_query::row::RowError::TypeConversion {\n");
    code.push_str("                column: column.to_string(),\n");
    code.push_str("                message: msg,\n");
    code.push_str("            }\n");
    code.push_str("        })\n");
    code.push_str("    }\n");
    code.push_str("}\n\n");

    // `Option<Enum>` handled by the blanket `impl<T: FromColumn>
    // FromColumn for Option<T>` in prax-query — no per-enum Option impl
    // needed here (the orphan rule would forbid it on the consumer side
    // anyway).

    // `ToFilterValue` — encode the enum as a string FilterValue so that
    // `where` clauses / `ModelWithPk::pk_value` / nested writes can send
    // it as a bind parameter.
    code.push_str(&format!(
        "impl prax_query::filter::ToFilterValue for {} {{\n",
        enum_def.name()
    ));
    code.push_str("    fn to_filter_value(&self) -> prax_query::filter::FilterValue {\n");
    code.push_str("        prax_query::filter::FilterValue::String(self.to_string())\n");
    code.push_str("    }\n");
    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_field_ident(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_field_ident(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_field_ident(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(),
            // pgvector scalars. Only `VectorFilter` exists in prax-pgvector
            // today (for `vector(N)` and `halfvec(N)`); sparse and bit
            // columns fall back to the raw element type under
            // `ScalarFilter` until dedicated filter types ship upstream.
            // Fully qualify the path so the generated filters.rs compiles
            // without requiring the consumer to add a `use` statement.
            ScalarType::Vector(_) | ScalarType::HalfVector(_) => {
                "prax_pgvector::filter::VectorFilter".to_string()
            }
            ScalarType::SparseVector(_) => "ScalarFilter<Vec<(u32, f32)>>".to_string(),
            ScalarType::Bit(_) => "ScalarFilter<Vec<u8>>".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
}

/// Snake-case a name and escape it as a raw identifier if the result
/// collides with a Rust reserved keyword. Use for any emitted Rust field
/// or variable name; plain column-name strings (serde rename values, SQL
/// column lookups) still use `to_snake_case` directly.
///
/// Schemas with columns literally named `type`, `match`, `use`, `loop`,
/// etc. (common in Prisma — documents, notifications, email_verification
/// all have a `type` column) otherwise produce code like `pub type: …`
/// that fails to parse. This function emits `r#type` instead.
///
/// The four keywords Rust forbids as raw identifiers (`crate`, `self`,
/// `Self`, `super`) are intentionally not escaped; a column literally
/// named `self` would still fail to compile, which is the correct
/// behavior (the schema should be fixed).
fn to_field_ident(name: &str) -> String {
    let snake = to_snake_case(name);
    if is_rust_keyword(&snake) {
        format!("r#{}", snake)
    } else {
        snake
    }
}

fn is_rust_keyword(s: &str) -> bool {
    matches!(
        s,
        "abstract"
            | "as"
            | "async"
            | "await"
            | "become"
            | "box"
            | "break"
            | "const"
            | "continue"
            | "do"
            | "dyn"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "final"
            | "fn"
            | "for"
            | "gen"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "macro"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "override"
            | "priv"
            | "pub"
            | "ref"
            | "return"
            | "static"
            | "struct"
            | "trait"
            | "true"
            | "try"
            | "type"
            | "typeof"
            | "unsafe"
            | "unsized"
            | "use"
            | "virtual"
            | "where"
            | "while"
            | "yield"
    )
}

/// 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));
    }
}