graphql-codegen-rust 0.1.0

Generate Rust ORM code from GraphQL schemas
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
use graphql_codegen_rust::{
    CodeGenerator, Config,
    parser::{FieldType, ParsedEnum, ParsedField, ParsedSchema, ParsedType},
};
use std::collections::HashMap;
use std::path::PathBuf;
use tempfile::TempDir;

#[test]
fn test_codegen_creation() {
    let config = Config {
        url: "https://api.example.com/graphql".to_string(),
        orm: graphql_codegen_rust::cli::OrmType::Diesel,
        db: graphql_codegen_rust::cli::DatabaseType::Sqlite,
        output_dir: PathBuf::from("./test_output"),
        headers: HashMap::new(),
        type_mappings: HashMap::new(),
        scalar_mappings: HashMap::new(),
        table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
        generate_migrations: true,
        generate_entities: true,
    };

    let _generator = CodeGenerator::new(&config.orm);
    // Just test that we can create a generator without panicking
    // The actual generator type is tested through the config
    assert_eq!(config.orm, graphql_codegen_rust::cli::OrmType::Diesel);
}

#[test]
fn test_config_defaults() {
    let config = Config {
        url: "https://api.example.com/graphql".to_string(),
        orm: graphql_codegen_rust::cli::OrmType::Diesel,
        db: graphql_codegen_rust::cli::DatabaseType::Sqlite,
        output_dir: PathBuf::from("./generated"),
        headers: HashMap::new(),
        type_mappings: HashMap::new(),
        scalar_mappings: HashMap::new(),
        table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
        generate_migrations: true,
        generate_entities: true,
    };

    assert_eq!(config.url, "https://api.example.com/graphql");
    assert_eq!(config.orm, graphql_codegen_rust::cli::OrmType::Diesel);
    assert_eq!(config.db, graphql_codegen_rust::cli::DatabaseType::Sqlite);
    assert_eq!(config.output_dir, PathBuf::from("./generated"));
    assert!(config.headers.is_empty());
    assert!(config.generate_migrations);
    assert!(config.generate_entities);
}

#[test]
fn test_table_naming_conventions() {
    use graphql_codegen_rust::generator::to_snake_case;

    assert_eq!(to_snake_case("User"), "user");
    assert_eq!(to_snake_case("UserProfile"), "user_profile");
    assert_eq!(to_snake_case("APIKey"), "api_key");
    assert_eq!(to_snake_case("userName"), "user_name");
    assert_eq!(to_snake_case("XMLHttpRequest"), "xml_http_request");
}

/// Test that generated Diesel code compiles successfully
#[tokio::test]
async fn test_diesel_code_generation_compiles() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let output_dir = temp_dir.path().to_path_buf();

    // Create a simple test schema
    let mut types = HashMap::new();
    let mut enums = HashMap::new();

    // Add User type
    let user_fields = vec![
        ParsedField {
            name: "id".to_string(),
            field_type: FieldType::Scalar("ID".to_string()),
            description: None,
            is_nullable: false,
            is_list: false,
        },
        ParsedField {
            name: "name".to_string(),
            field_type: FieldType::Scalar("String".to_string()),
            description: None,
            is_nullable: false,
            is_list: false,
        },
        ParsedField {
            name: "email".to_string(),
            field_type: FieldType::Scalar("String".to_string()),
            description: None,
            is_nullable: true,
            is_list: false,
        },
    ];

    types.insert(
        "User".to_string(),
        ParsedType {
            kind: graphql_codegen_rust::parser::TypeKind::Object,
            union_members: vec![],
            name: "User".to_string(),
            fields: user_fields,
            description: Some("A user in the system".to_string()),
            interfaces: vec![],
        },
    );

    // Add Role enum
    enums.insert(
        "Role".to_string(),
        ParsedEnum {
            name: "Role".to_string(),
            values: vec!["ADMIN".to_string(), "USER".to_string()],
            description: Some("User roles".to_string()),
        },
    );

    let schema = ParsedSchema {
        types,
        enums,
        scalars: vec![],
    };

    // Create config for Diesel + SQLite
    let config = Config {
        url: "https://example.com/graphql".to_string(),
        orm: graphql_codegen_rust::cli::OrmType::Diesel,
        db: graphql_codegen_rust::cli::DatabaseType::Sqlite,
        output_dir: output_dir.clone(),
        headers: HashMap::new(),
        type_mappings: HashMap::new(),
        scalar_mappings: HashMap::new(),
        table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
        generate_migrations: true,
        generate_entities: true,
    };

    // Generate code using the internal function with pre-parsed schema
    use graphql_codegen_rust::generate_all_code;
    let generator_inner = graphql_codegen_rust::generator::create_generator(&config.orm);
    generate_all_code(&schema, &config, &*generator_inner)
        .await
        .expect("Code generation should succeed");

    // Verify files were created
    assert!(output_dir.join("src/schema.rs").exists());
    assert!(output_dir.join("src/entities/user.rs").exists());
    assert!(output_dir.join("migrations").exists());

    // Verify files were created and contain expected content
    let schema_path = output_dir.join("src/schema.rs");
    let user_entity_path = output_dir.join("src/entities/user.rs");

    assert!(schema_path.exists());
    assert!(user_entity_path.exists());

    let schema_content = std::fs::read_to_string(&schema_path).expect("Failed to read schema");
    assert!(schema_content.contains("table!"));
    assert!(schema_content.contains("user"));

    let user_content =
        std::fs::read_to_string(&user_entity_path).expect("Failed to read user entity");
    assert!(user_content.contains("#[derive"));
    assert!(user_content.contains("pub struct User"));

    // Actually validate the generated code syntax to ensure it's valid Rust
    validate_generated_diesel_code(&schema_path, &user_entity_path);
}

/// Test that generated Sea-ORM code compiles successfully
#[tokio::test]
async fn test_sea_orm_code_generation_compiles() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let output_dir = temp_dir.path().to_path_buf();

    // Create a simple test schema
    let mut types = HashMap::new();
    let mut enums = HashMap::new();

    // Add Product type
    let product_fields = vec![
        ParsedField {
            name: "id".to_string(),
            field_type: FieldType::Scalar("ID".to_string()),
            description: None,
            is_nullable: false,
            is_list: false,
        },
        ParsedField {
            name: "title".to_string(),
            field_type: FieldType::Scalar("String".to_string()),
            description: None,
            is_nullable: false,
            is_list: false,
        },
        ParsedField {
            name: "price".to_string(),
            field_type: FieldType::Scalar("Float".to_string()),
            description: None,
            is_nullable: false,
            is_list: false,
        },
    ];

    types.insert(
        "Product".to_string(),
        ParsedType {
            kind: graphql_codegen_rust::parser::TypeKind::Object,
            union_members: vec![],
            name: "Product".to_string(),
            fields: product_fields,
            description: Some("A product in the catalog".to_string()),
            interfaces: vec![],
        },
    );

    // Add Status enum
    enums.insert(
        "Status".to_string(),
        ParsedEnum {
            name: "Status".to_string(),
            values: vec!["ACTIVE".to_string(), "INACTIVE".to_string()],
            description: Some("Product status".to_string()),
        },
    );

    let schema = ParsedSchema {
        types,
        enums,
        scalars: vec![],
    };

    // Create config for Sea-ORM + PostgreSQL
    let config = Config {
        url: "https://example.com/graphql".to_string(),
        orm: graphql_codegen_rust::cli::OrmType::SeaOrm,
        db: graphql_codegen_rust::cli::DatabaseType::Postgres,
        output_dir: output_dir.clone(),
        headers: HashMap::new(),
        type_mappings: HashMap::new(),
        scalar_mappings: HashMap::new(),
        table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
        generate_migrations: true,
        generate_entities: true,
    };

    // Generate code using the internal function with pre-parsed schema
    use graphql_codegen_rust::generate_all_code;
    let generator_inner = graphql_codegen_rust::generator::create_generator(&config.orm);
    generate_all_code(&schema, &config, &*generator_inner)
        .await
        .expect("Code generation should succeed");

    // Verify files were created
    // Sea-ORM generates mod.rs in the output directory root, not in src/
    assert!(output_dir.join("mod.rs").exists());
    assert!(output_dir.join("src/entities/product.rs").exists());
    assert!(output_dir.join("migrations").exists());

    // Verify files were created and contain expected content
    let mod_path = output_dir.join("mod.rs");
    let product_entity_path = output_dir.join("src/entities/product.rs");

    assert!(mod_path.exists());
    assert!(product_entity_path.exists());

    let mod_content = std::fs::read_to_string(&mod_path).expect("Failed to read mod.rs");
    assert!(mod_content.contains("pub mod product;"));
    assert!(mod_content.contains("pub use product::Entity;"));

    let product_content =
        std::fs::read_to_string(&product_entity_path).expect("Failed to read product entity");
    assert!(product_content.contains("#[derive(Clone, Debug, PartialEq, DeriveEntityModel"));
    assert!(product_content.contains("pub struct Entity;"));
    assert!(product_content.contains("uuid::Uuid")); // Should use UUID for Postgres ID

    // Actually validate the generated code syntax to ensure it's valid Rust
    validate_generated_sea_orm_code(&mod_path, &product_entity_path);
}

/// Test SDL schema parsing
#[test]
fn test_sdl_parsing() {
    let parser = graphql_codegen_rust::parser::GraphQLParser::new();

    let sdl_schema = r#"
        type User {
            id: ID!
            username: String!
            email: String
            posts: [Post!]!
        }

        type Post {
            id: ID!
            title: String!
            content: String!
            authorId: ID!
            published: Boolean!
            categoryId: ID
        }

        type Category {
            id: ID!
            name: String!
            description: String
        }

        enum Role {
            ADMIN
            USER
            MODERATOR
        }

        interface Node {
            id: ID!
        }

        union SearchResult = User | Post
    "#;

    let result = parser.parse_from_sdl(sdl_schema);
    assert!(result.is_ok(), "SDL parsing should succeed");

    let schema = result.unwrap();

    // Check that we parsed the types
    assert!(
        schema.types.contains_key("User"),
        "Should contain User type"
    );
    assert!(
        schema.types.contains_key("Post"),
        "Should contain Post type"
    );
    assert!(
        schema.types.contains_key("Category"),
        "Should contain Category type"
    );
    assert!(
        schema.types.contains_key("Node"),
        "Should contain Node interface"
    );
    assert!(
        schema.types.contains_key("SearchResult"),
        "Should contain SearchResult union"
    );

    // Check that we parsed the enum
    assert!(
        schema.enums.contains_key("Role"),
        "Should contain Role enum"
    );

    // Check User type fields
    let user_type = &schema.types["User"];
    assert_eq!(user_type.name, "User");
    assert_eq!(user_type.fields.len(), 4);

    // Check that ID field is not nullable
    let id_field = user_type.fields.iter().find(|f| f.name == "id").unwrap();
    assert!(!id_field.is_nullable);
    assert!(
        matches!(id_field.field_type, graphql_codegen_rust::parser::FieldType::Scalar(ref s) if s == "ID")
    );

    // Check that email field is nullable
    let email_field = user_type.fields.iter().find(|f| f.name == "email").unwrap();
    assert!(email_field.is_nullable);

    // Check posts field is a list and not nullable
    let posts_field = user_type.fields.iter().find(|f| f.name == "posts").unwrap();
    assert!(posts_field.is_list);
    assert!(!posts_field.is_nullable);

    println!("✓ SDL parsing test passed");
}

/// Test relationship detection
#[test]
fn test_relationship_detection() {
    let parser = graphql_codegen_rust::parser::GraphQLParser::new();

    let sdl_schema = r#"
        type User {
            id: ID!
            username: String!
            email: String
        }

        type Post {
            id: ID!
            title: String!
            content: String!
            authorId: ID!
            categoryId: ID
        }

        type Category {
            id: ID!
            name: String!
        }
    "#;

    let result = parser.parse_from_sdl(sdl_schema);
    assert!(result.is_ok(), "SDL parsing should succeed");

    let schema = result.unwrap();

    // Test relationship detection
    let relationships = graphql_codegen_rust::generator::detect_relationships(&schema);

    assert!(
        relationships.contains_key("Post"),
        "Post should have relationships"
    );

    let post_relationships = &relationships["Post"];
    assert_eq!(
        post_relationships.len(),
        1,
        "Post should have 1 relationship"
    );

    // Check categoryId -> Category relationship
    let category_rel = post_relationships
        .iter()
        .find(|r| r.field_name == "categoryId")
        .unwrap();
    assert_eq!(category_rel.related_type, "Category");
    assert!(matches!(
        category_rel.relationship_type,
        graphql_codegen_rust::generator::RelationshipType::BelongsTo
    ));
    assert!(category_rel.foreign_key);

    println!("✓ Relationship detection test passed");
}

/// Test code generation against real GraphQL APIs
#[tokio::test]
async fn test_real_graphql_apis() {
    let real_apis = vec![
        ("https://countries.trevorblades.com/", "Countries API"),
        ("https://api.spacex.land/graphql/", "SpaceX API"),
        ("https://graphql.anilist.co/", "AniList API"),
    ];

    for (endpoint, api_name) in real_apis {
        println!("Testing against {}: {}", api_name, endpoint);

        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Test both Diesel and Sea-ORM
        for orm_type in &[
            graphql_codegen_rust::cli::OrmType::Diesel,
            graphql_codegen_rust::cli::OrmType::SeaOrm,
        ] {
            let db_type = match orm_type {
                graphql_codegen_rust::cli::OrmType::Diesel => {
                    graphql_codegen_rust::cli::DatabaseType::Sqlite
                }
                graphql_codegen_rust::cli::OrmType::SeaOrm => {
                    graphql_codegen_rust::cli::DatabaseType::Postgres
                }
            };

            let config = Config {
                url: endpoint.to_string(),
                orm: orm_type.clone(),
                db: db_type,
                output_dir: temp_dir.path().to_path_buf(),
                headers: HashMap::new(),
                type_mappings: HashMap::new(),
                scalar_mappings: HashMap::new(),
                table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
                generate_migrations: true,
                generate_entities: true,
            };

            // This should succeed for public APIs
            let generator = CodeGenerator::new(&config.orm);
            match generator.generate_from_config(&config).await {
                Ok(_) => println!(
                    "✓ Successfully generated code for {} with {:?}",
                    api_name, orm_type
                ),
                Err(e) => {
                    // Some APIs might have issues, log but don't fail
                    println!(
                        "⚠️  Failed to generate code for {} with {:?}: {}",
                        api_name, orm_type, e
                    );
                }
            }
        }
    }
}

/// Test edge cases and error conditions
#[tokio::test]
async fn test_edge_cases() {
    let edge_cases = vec![
        ("empty_schema", create_empty_schema()),
        ("single_field_type", create_single_field_schema()),
        ("enum_only_schema", create_enum_only_schema()),
        (
            "complex_relationships",
            create_complex_relationships_schema(),
        ),
    ];

    for (case_name, schema) in edge_cases {
        println!("Testing edge case: {}", case_name);

        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Test both ORMs
        for orm_type in &[
            graphql_codegen_rust::cli::OrmType::Diesel,
            graphql_codegen_rust::cli::OrmType::SeaOrm,
        ] {
            let db_type = match orm_type {
                graphql_codegen_rust::cli::OrmType::Diesel => {
                    graphql_codegen_rust::cli::DatabaseType::Sqlite
                }
                graphql_codegen_rust::cli::OrmType::SeaOrm => {
                    graphql_codegen_rust::cli::DatabaseType::Postgres
                }
            };

            let config = Config {
                url: "https://example.com/graphql".to_string(),
                orm: orm_type.clone(),
                db: db_type,
                output_dir: temp_dir.path().to_path_buf(),
                headers: HashMap::new(),
                type_mappings: HashMap::new(),
                scalar_mappings: HashMap::new(),
                table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
                generate_migrations: true,
                generate_entities: true,
            };

            // Generate code using the internal function
            let generator_inner = graphql_codegen_rust::generator::create_generator(&config.orm);
            match graphql_codegen_rust::generate_all_code(&schema, &config, &*generator_inner).await
            {
                Ok(_) => println!("✓ Edge case '{}' passed for {:?}", case_name, orm_type),
                Err(e) => panic!("Edge case '{}' failed for {:?}: {}", case_name, orm_type, e),
            }
        }
    }
}

/// Test performance of code generation
#[tokio::test]
async fn test_codegen_performance() {
    use std::time::Instant;

    // Create a moderately complex schema for benchmarking
    let mut types = HashMap::new();
    let mut enums = HashMap::new();

    // Create 10 types with 5 fields each
    for i in 0..10 {
        let type_name = format!("Type{}", i);
        let mut fields = vec![ParsedField {
            name: "id".to_string(),
            field_type: FieldType::Scalar("ID".to_string()),
            description: None,
            is_nullable: false,
            is_list: false,
        }];

        // Add 5 additional fields
        for j in 0..5 {
            fields.push(ParsedField {
                name: format!("field{}", j),
                field_type: FieldType::Scalar("String".to_string()),
                description: None,
                is_nullable: true,
                is_list: false,
            });
        }

        types.insert(
            type_name,
            ParsedType {
                kind: graphql_codegen_rust::parser::TypeKind::Object,
                union_members: vec![],
                name: format!("Type{}", i),
                fields,
                description: Some(format!("Type {} description", i)),
                interfaces: vec![],
            },
        );
    }

    // Add some enums
    for i in 0..5 {
        enums.insert(
            format!("Enum{}", i),
            ParsedEnum {
                name: format!("Enum{}", i),
                values: vec![
                    "VALUE1".to_string(),
                    "VALUE2".to_string(),
                    "VALUE3".to_string(),
                ],
                description: Some(format!("Enum {} description", i)),
            },
        );
    }

    let schema = ParsedSchema {
        types,
        enums,
        scalars: vec![],
    };

    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let mut total_time = std::time::Duration::new(0, 0);

    // Benchmark both ORMs
    for orm_type in &[
        graphql_codegen_rust::cli::OrmType::Diesel,
        graphql_codegen_rust::cli::OrmType::SeaOrm,
    ] {
        let db_type = match orm_type {
            graphql_codegen_rust::cli::OrmType::Diesel => {
                graphql_codegen_rust::cli::DatabaseType::Sqlite
            }
            graphql_codegen_rust::cli::OrmType::SeaOrm => {
                graphql_codegen_rust::cli::DatabaseType::Postgres
            }
        };

        let config = Config {
            url: "https://example.com/graphql".to_string(),
            orm: orm_type.clone(),
            db: db_type,
            output_dir: temp_dir.path().to_path_buf(),
            headers: HashMap::new(),
            type_mappings: HashMap::new(),
            scalar_mappings: HashMap::new(),
            table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
            generate_migrations: true,
            generate_entities: true,
        };

        let start = Instant::now();
        let generator_inner = graphql_codegen_rust::generator::create_generator(&config.orm);
        graphql_codegen_rust::generate_all_code(&schema, &config, &*generator_inner)
            .await
            .expect("Code generation should succeed");
        let elapsed = start.elapsed();

        total_time += elapsed;
        println!("{:?} generation took {:?}", orm_type, elapsed);
    }

    // Ensure reasonable performance (should complete in under 1 second for this schema)
    assert!(
        total_time < std::time::Duration::from_secs(1),
        "Code generation took too long: {:?}",
        total_time
    );

    println!("✓ Total generation time: {:?}", total_time);
}

/// Test with fuzzed/random schema generation
#[tokio::test]
async fn test_fuzz_schema_generation() {
    use rand::rngs::StdRng;
    use rand::{Rng, SeedableRng};

    let mut rng = StdRng::from_seed([42; 32]); // Deterministic seed for reproducible tests

    for test_case in 0..10 {
        // Generate random schema
        let mut types = HashMap::new();
        let mut enums = HashMap::new();

        // Random number of types (1-5)
        let num_types = rng.random_range(1..=5);
        for i in 0..num_types {
            let type_name = format!("Type{}", i);
            let mut fields = vec![ParsedField {
                name: "id".to_string(),
                field_type: FieldType::Scalar("ID".to_string()),
                description: None,
                is_nullable: false,
                is_list: false,
            }];

            // Random number of fields (1-3)
            let num_fields = rng.random_range(1..=3);
            for j in 0..num_fields {
                let field_types = ["String", "Int", "Boolean", "Float"];
                let random_type = field_types[rng.random_range(0..field_types.len())];

                fields.push(ParsedField {
                    name: format!("field{}", j),
                    field_type: FieldType::Scalar(random_type.to_string()),
                    description: None,
                    is_nullable: rng.random_bool(0.5), // 50% chance of being nullable
                    is_list: false,
                });
            }

            types.insert(
                type_name,
                ParsedType {
                    kind: graphql_codegen_rust::parser::TypeKind::Object,
                    union_members: vec![],
                    name: format!("Type{}", i),
                    fields,
                    description: Some(format!("Random type {}", i)),
                    interfaces: vec![],
                },
            );
        }

        // Random enums (0-2)
        let num_enums = rng.random_range(0..=2);
        for i in 0..num_enums {
            let values: Vec<String> = (0..rng.random_range(2..=5))
                .map(|j| format!("VALUE{}", j))
                .collect();

            enums.insert(
                format!("Enum{}", i),
                ParsedEnum {
                    name: format!("Enum{}", i),
                    values,
                    description: Some(format!("Random enum {}", i)),
                },
            );
        }

        let schema = ParsedSchema {
            types,
            enums,
            scalars: vec![],
        };

        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Test both ORMs with the fuzzed schema
        for orm_type in &[
            graphql_codegen_rust::cli::OrmType::Diesel,
            graphql_codegen_rust::cli::OrmType::SeaOrm,
        ] {
            let db_type = match orm_type {
                graphql_codegen_rust::cli::OrmType::Diesel => {
                    graphql_codegen_rust::cli::DatabaseType::Sqlite
                }
                graphql_codegen_rust::cli::OrmType::SeaOrm => {
                    graphql_codegen_rust::cli::DatabaseType::Postgres
                }
            };

            let config = Config {
                url: "https://example.com/graphql".to_string(),
                orm: orm_type.clone(),
                db: db_type,
                output_dir: temp_dir.path().to_path_buf(),
                headers: HashMap::new(),
                type_mappings: HashMap::new(),
                scalar_mappings: HashMap::new(),
                table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
                generate_migrations: true,
                generate_entities: true,
            };

            // This should not panic even with random schemas
            let generator_inner = graphql_codegen_rust::generator::create_generator(&config.orm);
            match graphql_codegen_rust::generate_all_code(&schema, &config, &*generator_inner).await
            {
                Ok(_) => println!("✓ Fuzz test case {} passed for {:?}", test_case, orm_type),
                Err(e) => panic!(
                    "Fuzz test case {} failed for {:?}: {}",
                    test_case, orm_type, e
                ),
            }
        }
    }
}

/// Test both ORM types with different databases
#[tokio::test]
async fn test_multi_database_support() {
    let databases = vec![
        (graphql_codegen_rust::cli::DatabaseType::Sqlite, "i32"),
        (
            graphql_codegen_rust::cli::DatabaseType::Postgres,
            "uuid::Uuid",
        ),
        (graphql_codegen_rust::cli::DatabaseType::Mysql, "u32"),
    ];

    for (db_type, expected_id_type) in databases {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Simple schema with just ID field
        let mut types = HashMap::new();
        types.insert(
            "Test".to_string(),
            ParsedType {
                kind: graphql_codegen_rust::parser::TypeKind::Object,
                union_members: vec![],
                name: "Test".to_string(),
                fields: vec![ParsedField {
                    name: "id".to_string(),
                    field_type: FieldType::Scalar("ID".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                }],
                description: None,
                interfaces: vec![],
            },
        );

        let schema = ParsedSchema {
            types,
            enums: HashMap::new(),
            scalars: vec![],
        };

        // Test both ORMs
        for orm_type in &[
            graphql_codegen_rust::cli::OrmType::Diesel,
            graphql_codegen_rust::cli::OrmType::SeaOrm,
        ] {
            let config = Config {
                url: "https://example.com/graphql".to_string(),
                orm: orm_type.clone(),
                db: db_type.clone(),
                output_dir: temp_dir.path().to_path_buf(),
                headers: HashMap::new(),
                type_mappings: HashMap::new(),
                scalar_mappings: HashMap::new(),
                table_naming: graphql_codegen_rust::config::TableNamingConvention::SnakeCase,
                generate_migrations: true,
                generate_entities: true,
            };

            // Generate code using the internal function with pre-parsed schema
            use graphql_codegen_rust::generate_all_code;
            let generator_inner = graphql_codegen_rust::generator::create_generator(&config.orm);
            generate_all_code(&schema, &config, &*generator_inner)
                .await
                .expect("Code generation should succeed");

            // For Sea-ORM, check that the generated entity uses the correct ID type
            if matches!(orm_type, graphql_codegen_rust::cli::OrmType::SeaOrm) {
                let entity_path = temp_dir.path().join("src/entities/test.rs");
                let content = std::fs::read_to_string(entity_path).expect("Failed to read entity");
                assert!(
                    content.contains(expected_id_type),
                    "Expected {} in Sea-ORM entity for {:?}",
                    expected_id_type,
                    db_type
                );
            }
        }
    }
}

// Helper functions for creating test schemas

fn create_empty_schema() -> ParsedSchema {
    ParsedSchema {
        types: HashMap::new(),
        enums: HashMap::new(),
        scalars: vec![],
    }
}

fn create_single_field_schema() -> ParsedSchema {
    let mut types = HashMap::new();

    types.insert(
        "Minimal".to_string(),
        ParsedType {
            kind: graphql_codegen_rust::parser::TypeKind::Object,
            union_members: vec![],
            name: "Minimal".to_string(),
            fields: vec![ParsedField {
                name: "id".to_string(),
                field_type: FieldType::Scalar("ID".to_string()),
                description: None,
                is_nullable: false,
                is_list: false,
            }],
            description: None,
            interfaces: vec![],
        },
    );

    ParsedSchema {
        types,
        enums: HashMap::new(),
        scalars: vec![],
    }
}

fn create_enum_only_schema() -> ParsedSchema {
    let mut enums = HashMap::new();

    enums.insert(
        "Status".to_string(),
        ParsedEnum {
            name: "Status".to_string(),
            values: vec![
                "ACTIVE".to_string(),
                "INACTIVE".to_string(),
                "PENDING".to_string(),
            ],
            description: Some("Entity status".to_string()),
        },
    );

    ParsedSchema {
        types: HashMap::new(),
        enums,
        scalars: vec![],
    }
}

fn create_complex_relationships_schema() -> ParsedSchema {
    let mut types = HashMap::new();
    let mut enums = HashMap::new();

    // Author type
    types.insert(
        "Author".to_string(),
        ParsedType {
            kind: graphql_codegen_rust::parser::TypeKind::Object,
            union_members: vec![],
            name: "Author".to_string(),
            fields: vec![
                ParsedField {
                    name: "id".to_string(),
                    field_type: FieldType::Scalar("ID".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
                ParsedField {
                    name: "name".to_string(),
                    field_type: FieldType::Scalar("String".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
            ],
            description: Some("Blog author".to_string()),
            interfaces: vec![],
        },
    );

    // Blog post type with relationships
    types.insert(
        "BlogPost".to_string(),
        ParsedType {
            kind: graphql_codegen_rust::parser::TypeKind::Object,
            union_members: vec![],
            name: "BlogPost".to_string(),
            fields: vec![
                ParsedField {
                    name: "id".to_string(),
                    field_type: FieldType::Scalar("ID".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
                ParsedField {
                    name: "title".to_string(),
                    field_type: FieldType::Scalar("String".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
                ParsedField {
                    name: "content".to_string(),
                    field_type: FieldType::Scalar("String".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
                ParsedField {
                    name: "authorId".to_string(),
                    field_type: FieldType::Scalar("ID".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
                ParsedField {
                    name: "published".to_string(),
                    field_type: FieldType::Scalar("Boolean".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: false,
                },
                ParsedField {
                    name: "tags".to_string(),
                    field_type: FieldType::Scalar("String".to_string()),
                    description: None,
                    is_nullable: false,
                    is_list: true,
                },
            ],
            description: Some("Blog post".to_string()),
            interfaces: vec![],
        },
    );

    // Status enum
    enums.insert(
        "PostStatus".to_string(),
        ParsedEnum {
            name: "PostStatus".to_string(),
            values: vec![
                "DRAFT".to_string(),
                "PUBLISHED".to_string(),
                "ARCHIVED".to_string(),
            ],
            description: Some("Post publication status".to_string()),
        },
    );

    ParsedSchema {
        types,
        enums,
        scalars: vec![],
    }
}

/// Parse the generated Diesel code to ensure it's valid Rust syntax
fn validate_generated_diesel_code(schema_path: &std::path::Path, entity_path: &std::path::Path) {
    // Read and parse the schema file
    let schema_content = std::fs::read_to_string(schema_path).expect("Failed to read schema file");
    match syn::parse_file(&schema_content) {
        Ok(_) => println!("✓ Schema file parses successfully"),
        Err(e) => panic!("Schema file failed to parse: {}", e),
    }

    // Read and parse the entity file
    let entity_content = std::fs::read_to_string(entity_path).expect("Failed to read entity file");
    match syn::parse_file(&entity_content) {
        Ok(_) => println!("✓ Entity file parses successfully"),
        Err(e) => panic!("Entity file failed to parse: {}", e),
    }
}

/// Parse the generated Sea-ORM code to ensure it's valid Rust syntax
fn validate_generated_sea_orm_code(mod_path: &std::path::Path, entity_path: &std::path::Path) {
    // Read and parse the mod.rs file
    let mod_content = std::fs::read_to_string(mod_path).expect("Failed to read mod.rs file");
    match syn::parse_file(&mod_content) {
        Ok(_) => println!("✓ Mod file parses successfully"),
        Err(e) => panic!("Mod file failed to parse: {}", e),
    }

    // Read and parse the entity file
    let entity_content = std::fs::read_to_string(entity_path).expect("Failed to read entity file");
    match syn::parse_file(&entity_content) {
        Ok(_) => println!("✓ Entity file parses successfully"),
        Err(e) => panic!("Entity file failed to parse: {}", e),
    }
}