fraiseql-core 2.2.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
//! GraphQL introspection types per GraphQL spec §4.1-4.2.
//!
//! This module provides standard GraphQL introspection support, enabling
//! tools like Apollo Sandbox, `GraphiQL`, and Altair to query the schema.
//!
//! # Architecture
//!
//! FraiseQL generates introspection responses at **compile time** for performance.
//! The `IntrospectionSchema` is built from `CompiledSchema` and cached.
//!
//! # Supported Queries
//!
//! - `__schema` - Returns the full schema introspection
//! - `__type(name: String!)` - Returns a specific type's introspection
//! - `__typename` - Handled at projection level, not here
//!
//! # Module Layout
//!
//! | Sub-module | Responsibility |
//! |---|---|
//! | `types` | All `__*` introspection structs and enums |
//! | `field_resolver` | `FieldType` → `IntrospectionType` conversion, validation rules |
//! | `type_resolver` | Per-type builders (object, enum, input, interface, union, scalars) |
//! | `directive_builder` | Built-in and custom directive definitions |
//! | `schema_builder` | Root type builders, `IntrospectionBuilder`, `IntrospectionResponses` |

mod directive_builder;
mod field_resolver;
mod schema_builder;
mod type_resolver;
mod types;

// Re-export the complete public API (unchanged from the old flat module).
pub use schema_builder::{IntrospectionBuilder, IntrospectionResponses};
pub use types::{
    DirectiveLocation, IntrospectionDirective, IntrospectionEnumValue, IntrospectionField,
    IntrospectionInputValue, IntrospectionSchema, IntrospectionType, IntrospectionTypeRef,
    IntrospectionValidationRule, TypeKind,
};

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use std::collections::HashMap;

    use indexmap::IndexMap;

    use super::*;
    use crate::schema::{AutoParams, CursorType, FieldDenyPolicy, FieldType};

    fn test_schema() -> crate::schema::CompiledSchema {
        use crate::schema::{CompiledSchema, FieldDefinition, QueryDefinition, TypeDefinition};

        let mut schema = CompiledSchema::new();

        // Add a User type
        schema.types.push(
            TypeDefinition::new("User", "v_user")
                .with_field(FieldDefinition::new("id", FieldType::Id))
                .with_field(FieldDefinition::new("name", FieldType::String))
                .with_field(FieldDefinition::nullable("email", FieldType::String))
                .with_description("A user in the system"),
        );

        // Add a users query
        schema.queries.push(QueryDefinition {
            name:                "users".to_string(),
            return_type:         "User".to_string(),
            returns_list:        true,
            nullable:            false,
            arguments:           vec![],
            sql_source:          Some("v_user".to_string()),
            description:         Some("Get all users".to_string()),
            auto_params:         AutoParams::default(),
            deprecation:         None,
            jsonb_column:        "data".to_string(),
            relay:               false,
            relay_cursor_column: None,
            relay_cursor_type:   CursorType::default(),
            inject_params:       IndexMap::default(),
            cache_ttl_seconds:   None,
            additional_views:    vec![],
            requires_role:       None,
            rest_path:           None,
            rest_method:         None,
            native_columns:      HashMap::new(),
        });

        // Add a user query with argument
        schema.queries.push(QueryDefinition {
            name:                "user".to_string(),
            return_type:         "User".to_string(),
            returns_list:        false,
            nullable:            true,
            arguments:           vec![crate::schema::ArgumentDefinition {
                name:          "id".to_string(),
                arg_type:      FieldType::Id,
                nullable:      false, // required
                default_value: None,
                description:   Some("User ID".to_string()),
                deprecation:   None,
            }],
            sql_source:          Some("v_user".to_string()),
            description:         Some("Get user by ID".to_string()),
            auto_params:         AutoParams::default(),
            deprecation:         None,
            jsonb_column:        "data".to_string(),
            relay:               false,
            relay_cursor_column: None,
            relay_cursor_type:   CursorType::default(),
            inject_params:       IndexMap::default(),
            cache_ttl_seconds:   None,
            additional_views:    vec![],
            requires_role:       None,
            rest_path:           None,
            rest_method:         None,
            native_columns:      HashMap::new(),
        });

        schema
    }

    #[test]
    fn test_build_introspection_schema() {
        let schema = test_schema();
        let introspection = IntrospectionBuilder::build(&schema);

        // Should have Query type
        assert_eq!(introspection.query_type.name, "Query");

        // Should not have Mutation type (no mutations)
        assert!(introspection.mutation_type.is_none());

        // Should have built-in scalars
        let scalar_names: Vec<_> = introspection
            .types
            .iter()
            .filter(|t| t.kind == TypeKind::Scalar)
            .filter_map(|t| t.name.as_ref())
            .collect();
        assert!(scalar_names.contains(&&"Int".to_string()));
        assert!(scalar_names.contains(&&"String".to_string()));
        assert!(scalar_names.contains(&&"Boolean".to_string()));

        // Should have User type
        let user_type = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"User".to_string()));
        assert!(user_type.is_some());
        let user_type = user_type.unwrap();
        assert_eq!(user_type.kind, TypeKind::Object);
        assert!(user_type.fields.is_some());
        assert_eq!(user_type.fields.as_ref().unwrap().len(), 3);
    }

    #[test]
    fn test_build_introspection_responses() {
        let schema = test_schema();
        let responses = IntrospectionResponses::build(&schema);

        // Should have schema response
        assert!(responses.schema_response.get("data").is_some());
        assert!(responses.schema_response["data"].get("__schema").is_some());

        // Should have type responses
        assert!(responses.type_responses.contains_key("User"));
        assert!(responses.type_responses.contains_key("Query"));
        assert!(responses.type_responses.contains_key("Int"));

        // Unknown type should return null
        let unknown = responses.get_type_response("Unknown");
        assert!(unknown["data"]["__type"].is_null());
    }

    #[test]
    fn test_query_field_introspection() {
        let schema = test_schema();
        let introspection = IntrospectionBuilder::build(&schema);

        let query_type = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"Query".to_string()))
            .unwrap();

        let fields = query_type.fields.as_ref().unwrap();

        // Should have 'users' query
        let users_field = fields.iter().find(|f| f.name == "users").unwrap();
        assert_eq!(users_field.field_type.kind, TypeKind::NonNull);
        assert!(users_field.args.is_empty());

        // Should have 'user' query with argument
        let user_field = fields.iter().find(|f| f.name == "user").unwrap();
        assert!(!user_field.args.is_empty());
        assert_eq!(user_field.args[0].name, "id");
    }

    #[test]
    fn test_field_type_non_null() {
        let schema = test_schema();
        let introspection = IntrospectionBuilder::build(&schema);

        let user_type = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"User".to_string()))
            .unwrap();

        let fields = user_type.fields.as_ref().unwrap();

        // 'id' should be NON_NULL
        let id_field = fields.iter().find(|f| f.name == "id").unwrap();
        assert_eq!(id_field.field_type.kind, TypeKind::NonNull);

        // 'email' should be nullable (not wrapped in NON_NULL)
        let email_field = fields.iter().find(|f| f.name == "email").unwrap();
        assert_ne!(email_field.field_type.kind, TypeKind::NonNull);
    }

    #[test]
    fn test_deprecated_field_introspection() {
        use crate::schema::{CompiledSchema, DeprecationInfo, FieldDefinition, TypeDefinition};

        // Create a schema with a deprecated field
        let mut schema = CompiledSchema::new();
        schema.types.push(TypeDefinition {
            name:                "Product".into(),
            sql_source:          "products".into(),
            jsonb_column:        "data".to_string(),
            description:         None,
            sql_projection_hint: None,
            implements:          vec![],
            requires_role:       None,
            is_error:            false,
            relay:               false,
            relationships:       vec![],
            fields:              vec![
                FieldDefinition::new("id", FieldType::Id),
                FieldDefinition {
                    name:           "oldSku".into(),
                    field_type:     FieldType::String,
                    nullable:       false,
                    description:    Some("Legacy SKU field".to_string()),
                    default_value:  None,
                    vector_config:  None,
                    alias:          None,
                    deprecation:    Some(DeprecationInfo {
                        reason: Some("Use 'sku' instead".to_string()),
                    }),
                    requires_scope: None,
                    on_deny:        FieldDenyPolicy::default(),
                    encryption:     None,
                },
                FieldDefinition::new("sku", FieldType::String),
            ],
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find Product type
        let product_type = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"Product".to_string()))
            .unwrap();

        let fields = product_type.fields.as_ref().unwrap();

        // 'oldSku' should be deprecated
        let old_sku_field = fields.iter().find(|f| f.name == "oldSku").unwrap();
        assert!(old_sku_field.is_deprecated);
        assert_eq!(old_sku_field.deprecation_reason, Some("Use 'sku' instead".to_string()));

        // 'sku' should NOT be deprecated
        let sku_field = fields.iter().find(|f| f.name == "sku").unwrap();
        assert!(!sku_field.is_deprecated);
        assert!(sku_field.deprecation_reason.is_none());

        // 'id' should NOT be deprecated
        let id_field = fields.iter().find(|f| f.name == "id").unwrap();
        assert!(!id_field.is_deprecated);
        assert!(id_field.deprecation_reason.is_none());
    }

    #[test]
    fn test_enum_type_introspection() {
        use crate::schema::{CompiledSchema, DeprecationInfo, EnumDefinition, EnumValueDefinition};

        let mut schema = CompiledSchema::new();

        // Add an enum type with some values, one deprecated
        schema.enums.push(EnumDefinition {
            name:        "OrderStatus".to_string(),
            description: Some("Status of an order".to_string()),
            values:      vec![
                EnumValueDefinition {
                    name:        "PENDING".to_string(),
                    description: Some("Order is pending".to_string()),
                    deprecation: None,
                },
                EnumValueDefinition {
                    name:        "PROCESSING".to_string(),
                    description: None,
                    deprecation: None,
                },
                EnumValueDefinition {
                    name:        "SHIPPED".to_string(),
                    description: None,
                    deprecation: None,
                },
                EnumValueDefinition {
                    name:        "CANCELLED".to_string(),
                    description: Some("Order was cancelled".to_string()),
                    deprecation: Some(DeprecationInfo {
                        reason: Some("Use REFUNDED instead".to_string()),
                    }),
                },
            ],
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find OrderStatus enum
        let order_status = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"OrderStatus".to_string()))
            .unwrap();

        assert_eq!(order_status.kind, TypeKind::Enum);
        assert_eq!(order_status.description, Some("Status of an order".to_string()));

        // Should have enum_values
        let enum_values = order_status.enum_values.as_ref().unwrap();
        assert_eq!(enum_values.len(), 4);

        // Check PENDING value
        let pending = enum_values.iter().find(|v| v.name == "PENDING").unwrap();
        assert_eq!(pending.description, Some("Order is pending".to_string()));
        assert!(!pending.is_deprecated);
        assert!(pending.deprecation_reason.is_none());

        // Check CANCELLED value (deprecated)
        let cancelled = enum_values.iter().find(|v| v.name == "CANCELLED").unwrap();
        assert!(cancelled.is_deprecated);
        assert_eq!(cancelled.deprecation_reason, Some("Use REFUNDED instead".to_string()));

        // Enum should not have fields
        assert!(order_status.fields.is_none());
    }

    #[test]
    fn test_input_object_introspection() {
        use crate::schema::{CompiledSchema, InputFieldDefinition, InputObjectDefinition};

        let mut schema = CompiledSchema::new();

        // Add an input object type
        schema.input_types.push(InputObjectDefinition {
            name:        "UserFilter".to_string(),
            description: Some("Filter for user queries".to_string()),
            fields:      vec![
                InputFieldDefinition {
                    name:             "name".to_string(),
                    field_type:       "String".to_string(),
                    description:      Some("Filter by name".to_string()),
                    default_value:    None,
                    deprecation:      None,
                    validation_rules: Vec::new(),
                },
                InputFieldDefinition {
                    name:             "email".to_string(),
                    field_type:       "String".to_string(),
                    description:      None,
                    default_value:    None,
                    deprecation:      None,
                    validation_rules: Vec::new(),
                },
                InputFieldDefinition {
                    name:             "limit".to_string(),
                    field_type:       "Int".to_string(),
                    description:      Some("Max results".to_string()),
                    default_value:    Some("10".to_string()),
                    deprecation:      None,
                    validation_rules: Vec::new(),
                },
            ],
            metadata:    None,
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find UserFilter input type
        let user_filter = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"UserFilter".to_string()))
            .unwrap();

        assert_eq!(user_filter.kind, TypeKind::InputObject);
        assert_eq!(user_filter.description, Some("Filter for user queries".to_string()));

        // Should have input_fields
        let input_fields = user_filter.input_fields.as_ref().unwrap();
        assert_eq!(input_fields.len(), 3);

        // Check name field
        let name_field = input_fields.iter().find(|f| f.name == "name").unwrap();
        assert_eq!(name_field.description, Some("Filter by name".to_string()));
        assert!(name_field.default_value.is_none());

        // Check limit field with default value
        let limit_field = input_fields.iter().find(|f| f.name == "limit").unwrap();
        assert_eq!(limit_field.description, Some("Max results".to_string()));
        assert_eq!(limit_field.default_value, Some("10".to_string()));

        // Input object should not have fields
        assert!(user_filter.fields.is_none());
    }

    #[test]
    fn test_enum_in_type_map() {
        use crate::schema::{CompiledSchema, EnumDefinition};

        let mut schema = CompiledSchema::new();
        schema.enums.push(EnumDefinition {
            name:        "Status".to_string(),
            description: None,
            values:      vec![],
        });

        let introspection = IntrospectionBuilder::build(&schema);
        let type_map = IntrospectionBuilder::build_type_map(&introspection);

        // Enum should be in the type map
        assert!(type_map.contains_key("Status"));
        let status = type_map.get("Status").unwrap();
        assert_eq!(status.kind, TypeKind::Enum);
    }

    #[test]
    fn test_input_object_in_type_map() {
        use crate::schema::{CompiledSchema, InputObjectDefinition};

        let mut schema = CompiledSchema::new();
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            description: None,
            fields:      vec![],
            metadata:    None,
        });

        let introspection = IntrospectionBuilder::build(&schema);
        let type_map = IntrospectionBuilder::build_type_map(&introspection);

        // Input object should be in the type map
        assert!(type_map.contains_key("CreateUserInput"));
        let input = type_map.get("CreateUserInput").unwrap();
        assert_eq!(input.kind, TypeKind::InputObject);
    }

    #[test]
    fn test_interface_introspection() {
        use crate::schema::{CompiledSchema, FieldDefinition, InterfaceDefinition, TypeDefinition};

        let mut schema = CompiledSchema::new();

        // Add a Node interface
        schema.interfaces.push(InterfaceDefinition {
            name:        "Node".to_string(),
            description: Some("An object with a globally unique ID".to_string()),
            fields:      vec![FieldDefinition::new("id", FieldType::Id)],
        });

        // Add types that implement the interface
        schema.types.push(TypeDefinition {
            name:                "User".into(),
            sql_source:          "users".into(),
            jsonb_column:        "data".to_string(),
            description:         Some("A user".to_string()),
            sql_projection_hint: None,
            implements:          vec!["Node".to_string()],
            requires_role:       None,
            is_error:            false,
            relay:               false,
            relationships:       vec![],
            fields:              vec![
                FieldDefinition::new("id", FieldType::Id),
                FieldDefinition::new("name", FieldType::String),
            ],
        });

        schema.types.push(TypeDefinition {
            name:                "Post".into(),
            sql_source:          "posts".into(),
            jsonb_column:        "data".to_string(),
            description:         Some("A blog post".to_string()),
            sql_projection_hint: None,
            implements:          vec!["Node".to_string()],
            requires_role:       None,
            is_error:            false,
            relay:               false,
            relationships:       vec![],
            fields:              vec![
                FieldDefinition::new("id", FieldType::Id),
                FieldDefinition::new("title", FieldType::String),
            ],
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find Node interface
        let node = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"Node".to_string()))
            .unwrap();

        assert_eq!(node.kind, TypeKind::Interface);
        assert_eq!(node.description, Some("An object with a globally unique ID".to_string()));

        // Interface should have fields
        let fields = node.fields.as_ref().unwrap();
        assert_eq!(fields.len(), 1);
        assert_eq!(fields[0].name, "id");

        // Interface should have possible_types (implementors)
        let possible_types = node.possible_types.as_ref().unwrap();
        assert_eq!(possible_types.len(), 2);
        assert!(possible_types.iter().any(|t| t.name == "User"));
        assert!(possible_types.iter().any(|t| t.name == "Post"));

        // Interface should not have enum_values or input_fields
        assert!(node.enum_values.is_none());
        assert!(node.input_fields.is_none());
    }

    #[test]
    fn test_type_implements_interface() {
        use crate::schema::{CompiledSchema, FieldDefinition, InterfaceDefinition, TypeDefinition};

        let mut schema = CompiledSchema::new();

        // Add interfaces
        schema.interfaces.push(InterfaceDefinition {
            name:        "Node".to_string(),
            description: None,
            fields:      vec![FieldDefinition::new("id", FieldType::Id)],
        });

        schema.interfaces.push(InterfaceDefinition {
            name:        "Timestamped".to_string(),
            description: None,
            fields:      vec![FieldDefinition::new("createdAt", FieldType::DateTime)],
        });

        // Add a type that implements both interfaces
        schema.types.push(TypeDefinition {
            name:                "Comment".into(),
            sql_source:          "comments".into(),
            jsonb_column:        "data".to_string(),
            description:         None,
            sql_projection_hint: None,
            implements:          vec!["Node".to_string(), "Timestamped".to_string()],
            requires_role:       None,
            is_error:            false,
            relay:               false,
            relationships:       vec![],
            fields:              vec![
                FieldDefinition::new("id", FieldType::Id),
                FieldDefinition::new("createdAt", FieldType::DateTime),
                FieldDefinition::new("text", FieldType::String),
            ],
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find Comment type
        let comment = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"Comment".to_string()))
            .unwrap();

        assert_eq!(comment.kind, TypeKind::Object);

        // Type should list interfaces it implements
        let interfaces = comment.interfaces.as_ref().unwrap();
        assert_eq!(interfaces.len(), 2);
        assert!(interfaces.iter().any(|i| i.name == "Node"));
        assert!(interfaces.iter().any(|i| i.name == "Timestamped"));
    }

    #[test]
    fn test_interface_in_type_map() {
        use crate::schema::{CompiledSchema, InterfaceDefinition};

        let mut schema = CompiledSchema::new();
        schema.interfaces.push(InterfaceDefinition {
            name:        "Searchable".to_string(),
            description: None,
            fields:      vec![],
        });

        let introspection = IntrospectionBuilder::build(&schema);
        let type_map = IntrospectionBuilder::build_type_map(&introspection);

        // Interface should be in the type map
        assert!(type_map.contains_key("Searchable"));
        let interface = type_map.get("Searchable").unwrap();
        assert_eq!(interface.kind, TypeKind::Interface);
    }

    #[test]
    fn test_filter_deprecated_fields() {
        // Create a type with some deprecated fields
        let introspection_type = IntrospectionType {
            kind:               TypeKind::Object,
            name:               Some("TestType".to_string()),
            description:        None,
            fields:             Some(vec![
                IntrospectionField {
                    name:               "id".to_string(),
                    description:        None,
                    args:               vec![],
                    field_type:         IntrospectionBuilder::type_ref("ID"),
                    is_deprecated:      false,
                    deprecation_reason: None,
                },
                IntrospectionField {
                    name:               "oldField".to_string(),
                    description:        None,
                    args:               vec![],
                    field_type:         IntrospectionBuilder::type_ref("String"),
                    is_deprecated:      true,
                    deprecation_reason: Some("Use newField instead".to_string()),
                },
                IntrospectionField {
                    name:               "newField".to_string(),
                    description:        None,
                    args:               vec![],
                    field_type:         IntrospectionBuilder::type_ref("String"),
                    is_deprecated:      false,
                    deprecation_reason: None,
                },
            ]),
            interfaces:         None,
            possible_types:     None,
            enum_values:        None,
            input_fields:       None,
            of_type:            None,
            specified_by_u_r_l: None,
        };

        // With includeDeprecated = false, should only have 2 fields
        let filtered = introspection_type.filter_deprecated_fields(false);
        let fields = filtered.fields.as_ref().unwrap();
        assert_eq!(fields.len(), 2);
        assert!(fields.iter().any(|f| f.name == "id"));
        assert!(fields.iter().any(|f| f.name == "newField"));
        assert!(!fields.iter().any(|f| f.name == "oldField"));

        // With includeDeprecated = true, should have all 3 fields
        let unfiltered = introspection_type.filter_deprecated_fields(true);
        let fields = unfiltered.fields.as_ref().unwrap();
        assert_eq!(fields.len(), 3);
    }

    #[test]
    fn test_filter_deprecated_enum_values() {
        // Create an enum type with some deprecated values
        let introspection_type = IntrospectionType {
            kind:               TypeKind::Enum,
            name:               Some("Status".to_string()),
            description:        None,
            fields:             None,
            interfaces:         None,
            possible_types:     None,
            enum_values:        Some(vec![
                IntrospectionEnumValue {
                    name:               "ACTIVE".to_string(),
                    description:        None,
                    is_deprecated:      false,
                    deprecation_reason: None,
                },
                IntrospectionEnumValue {
                    name:               "INACTIVE".to_string(),
                    description:        None,
                    is_deprecated:      true,
                    deprecation_reason: Some("Use DISABLED instead".to_string()),
                },
                IntrospectionEnumValue {
                    name:               "DISABLED".to_string(),
                    description:        None,
                    is_deprecated:      false,
                    deprecation_reason: None,
                },
            ]),
            input_fields:       None,
            of_type:            None,
            specified_by_u_r_l: None,
        };

        // With includeDeprecated = false, should only have 2 values
        let filtered = introspection_type.filter_deprecated_enum_values(false);
        let values = filtered.enum_values.as_ref().unwrap();
        assert_eq!(values.len(), 2);
        assert!(values.iter().any(|v| v.name == "ACTIVE"));
        assert!(values.iter().any(|v| v.name == "DISABLED"));
        assert!(!values.iter().any(|v| v.name == "INACTIVE"));

        // With includeDeprecated = true, should have all 3 values
        let unfiltered = introspection_type.filter_deprecated_enum_values(true);
        let values = unfiltered.enum_values.as_ref().unwrap();
        assert_eq!(values.len(), 3);
    }

    #[test]
    fn test_specified_by_url_for_custom_scalars() {
        use crate::schema::CompiledSchema;

        let schema = CompiledSchema::new();
        let introspection = IntrospectionBuilder::build(&schema);

        // Find DateTime scalar
        let datetime = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"DateTime".to_string()))
            .unwrap();

        assert_eq!(datetime.kind, TypeKind::Scalar);
        assert!(datetime.specified_by_u_r_l.is_some());
        assert!(datetime.specified_by_u_r_l.as_ref().unwrap().contains("date-time"));

        // Find UUID scalar
        let uuid = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"UUID".to_string()))
            .unwrap();

        assert_eq!(uuid.kind, TypeKind::Scalar);
        assert!(uuid.specified_by_u_r_l.is_some());
        assert!(uuid.specified_by_u_r_l.as_ref().unwrap().contains("rfc4122"));

        // Built-in scalars (Int, String, etc.) should NOT have specifiedByURL
        let int = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"Int".to_string()))
            .unwrap();

        assert_eq!(int.kind, TypeKind::Scalar);
        assert!(int.specified_by_u_r_l.is_none());
    }

    #[test]
    fn test_deprecated_query_introspection() {
        use crate::schema::{
            ArgumentDefinition, AutoParams, CompiledSchema, DeprecationInfo, QueryDefinition,
        };

        let mut schema = CompiledSchema::new();

        // Add a deprecated query
        schema.queries.push(QueryDefinition {
            name:                "oldUsers".to_string(),
            return_type:         "User".to_string(),
            returns_list:        true,
            nullable:            false,
            arguments:           vec![],
            sql_source:          Some("v_user".to_string()),
            description:         Some("Old way to get users".to_string()),
            auto_params:         AutoParams::default(),
            deprecation:         Some(DeprecationInfo {
                reason: Some("Use 'users' instead".to_string()),
            }),
            jsonb_column:        "data".to_string(),
            relay:               false,
            relay_cursor_column: None,
            relay_cursor_type:   CursorType::default(),
            inject_params:       IndexMap::default(),
            cache_ttl_seconds:   None,
            additional_views:    vec![],
            requires_role:       None,
            rest_path:           None,
            rest_method:         None,
            native_columns:      HashMap::new(),
        });

        // Add a non-deprecated query with a deprecated argument
        schema.queries.push(QueryDefinition {
            name:                "users".to_string(),
            return_type:         "User".to_string(),
            returns_list:        true,
            nullable:            false,
            arguments:           vec![
                ArgumentDefinition {
                    name:          "first".to_string(),
                    arg_type:      FieldType::Int,
                    nullable:      true,
                    default_value: None,
                    description:   Some("Number of results to return".to_string()),
                    deprecation:   None,
                },
                ArgumentDefinition {
                    name:          "limit".to_string(),
                    arg_type:      FieldType::Int,
                    nullable:      true,
                    default_value: None,
                    description:   Some("Old parameter for limiting results".to_string()),
                    deprecation:   Some(DeprecationInfo {
                        reason: Some("Use 'first' instead".to_string()),
                    }),
                },
            ],
            sql_source:          Some("v_user".to_string()),
            description:         Some("Get users with pagination".to_string()),
            auto_params:         AutoParams::default(),
            deprecation:         None,
            jsonb_column:        "data".to_string(),
            relay:               false,
            relay_cursor_column: None,
            relay_cursor_type:   CursorType::default(),
            inject_params:       IndexMap::default(),
            cache_ttl_seconds:   None,
            additional_views:    vec![],
            requires_role:       None,
            rest_path:           None,
            rest_method:         None,
            native_columns:      HashMap::new(),
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find Query type
        let query_type = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"Query".to_string()))
            .unwrap();

        let fields = query_type.fields.as_ref().unwrap();

        // 'oldUsers' should be deprecated
        let old_users = fields.iter().find(|f| f.name == "oldUsers").unwrap();
        assert!(old_users.is_deprecated);
        assert_eq!(old_users.deprecation_reason, Some("Use 'users' instead".to_string()));

        // 'users' should NOT be deprecated
        let users = fields.iter().find(|f| f.name == "users").unwrap();
        assert!(!users.is_deprecated);
        assert!(users.deprecation_reason.is_none());

        // 'users' should have 2 arguments
        assert_eq!(users.args.len(), 2);

        // 'first' argument should NOT be deprecated
        let first_arg = users.args.iter().find(|a| a.name == "first").unwrap();
        assert!(!first_arg.is_deprecated);
        assert!(first_arg.deprecation_reason.is_none());

        // 'limit' argument should be deprecated
        let limit_arg = users.args.iter().find(|a| a.name == "limit").unwrap();
        assert!(limit_arg.is_deprecated);
        assert_eq!(limit_arg.deprecation_reason, Some("Use 'first' instead".to_string()));
    }

    #[test]
    fn test_deprecated_input_field_introspection() {
        use crate::schema::{
            CompiledSchema, DeprecationInfo, InputFieldDefinition, InputObjectDefinition,
        };

        let mut schema = CompiledSchema::new();

        // Add an input type with a deprecated field
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            description: Some("Input for creating a user".to_string()),
            fields:      vec![
                InputFieldDefinition {
                    name:             "name".to_string(),
                    field_type:       "String!".to_string(),
                    default_value:    None,
                    description:      Some("User name".to_string()),
                    deprecation:      None,
                    validation_rules: Vec::new(),
                },
                InputFieldDefinition {
                    name:             "oldEmail".to_string(),
                    field_type:       "String".to_string(),
                    default_value:    None,
                    description:      Some("Legacy email field".to_string()),
                    deprecation:      Some(DeprecationInfo {
                        reason: Some("Use 'email' instead".to_string()),
                    }),
                    validation_rules: Vec::new(),
                },
            ],
            metadata:    None,
        });

        let introspection = IntrospectionBuilder::build(&schema);

        // Find CreateUserInput type
        let create_user_input = introspection
            .types
            .iter()
            .find(|t| t.name.as_ref() == Some(&"CreateUserInput".to_string()))
            .unwrap();

        let input_fields = create_user_input.input_fields.as_ref().unwrap();

        // 'name' should NOT be deprecated
        let name_field = input_fields.iter().find(|f| f.name == "name").unwrap();
        assert!(!name_field.is_deprecated);
        assert!(name_field.deprecation_reason.is_none());

        // 'oldEmail' should be deprecated
        let old_email = input_fields.iter().find(|f| f.name == "oldEmail").unwrap();
        assert!(old_email.is_deprecated);
        assert_eq!(old_email.deprecation_reason, Some("Use 'email' instead".to_string()));
    }
}