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
//! Input object-level validation.
//!
//! This module provides validation capabilities at the input object level,
//! applying cross-field rules and aggregating errors from multiple validators.
//!
//! # Examples
//!
//! ```
//! use fraiseql_core::validation::{InputObjectRule, validate_input_object};
//! use serde_json::json;
//!
//! // Validate entire input object
//! let input = json!({
//!     "name": "John",
//!     "email": "john@example.com",
//!     "phone": null
//! });
//!
//! let validators = vec![
//!     InputObjectRule::AnyOf { fields: vec!["email".to_string(), "phone".to_string()] },
//!     InputObjectRule::ConditionalRequired {
//!         if_field: "name".to_string(),
//!         then_fields: vec!["email".to_string()],
//!     },
//! ];
//!
//! validate_input_object(&input, &validators, None).unwrap();
//! ```

use serde_json::Value;

use crate::error::{FraiseQLError, Result};

/// Rules that apply at the input object level.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum InputObjectRule {
    /// At least one field from the set must be provided
    AnyOf {
        /// Field names of which at least one must be present.
        fields: Vec<String>,
    },
    /// Exactly one field from the set must be provided
    OneOf {
        /// Field names of which exactly one must be present.
        fields: Vec<String>,
    },
    /// If one field is present, others must be present
    ConditionalRequired {
        /// The trigger field whose presence activates the requirement.
        if_field:    String,
        /// Fields that must be present when `if_field` is provided.
        then_fields: Vec<String>,
    },
    /// If one field is absent, others must be present
    RequiredIfAbsent {
        /// The field whose absence activates the requirement.
        absent_field: String,
        /// Fields that must be present when `absent_field` is missing.
        then_fields:  Vec<String>,
    },
    /// Custom validator function name to invoke
    Custom {
        /// Name of the registered custom validator function.
        name: String,
    },
}

/// Result of validating an input object, aggregating multiple errors.
#[derive(Debug, Clone, Default)]
pub struct InputObjectValidationResult {
    /// All validation errors
    pub errors:      Vec<String>,
    /// Count of errors
    pub error_count: usize,
}

impl InputObjectValidationResult {
    /// Create a new empty result.
    pub const fn new() -> Self {
        Self {
            errors:      Vec::new(),
            error_count: 0,
        }
    }

    /// Add an error to the result.
    pub fn add_error(&mut self, error: String) {
        self.errors.push(error);
        self.error_count += 1;
    }

    /// Add multiple errors at once.
    pub fn add_errors(&mut self, errors: Vec<String>) {
        self.error_count += errors.len();
        self.errors.extend(errors);
    }

    /// Check if there are any errors.
    pub const fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Convert to a Result, failing if there are errors.
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] if any validation errors have been
    /// accumulated via [`add_error`][Self::add_error].
    pub fn into_result(self) -> Result<()> {
        self.into_result_with_path("input")
    }

    /// Convert to a Result with a custom path, failing if there are errors.
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] with the given `path` if any
    /// validation errors have been accumulated.
    pub fn into_result_with_path(self, path: &str) -> Result<()> {
        if self.has_errors() {
            Err(FraiseQLError::Validation {
                message: format!("Input object validation failed: {}", self.errors.join("; ")),
                path:    Some(path.to_string()),
            })
        } else {
            Ok(())
        }
    }
}

/// Validate an input object against a set of rules.
///
/// Applies all rules to the input object and aggregates errors.
///
/// # Arguments
/// * `input` - The input object to validate
/// * `rules` - Rules to apply at the object level
/// * `object_path` - Optional path to the object for error reporting
///
/// # Errors
///
/// Returns `FraiseQLError::Validation` if any input object rule fails.
pub fn validate_input_object(
    input: &Value,
    rules: &[InputObjectRule],
    object_path: Option<&str>,
) -> Result<()> {
    let mut result = InputObjectValidationResult::new();
    let path = object_path.unwrap_or("input");

    if !matches!(input, Value::Object(_)) {
        return Err(FraiseQLError::Validation {
            message: "Input must be an object".to_string(),
            path:    Some(path.to_string()),
        });
    }

    for rule in rules {
        if let Err(FraiseQLError::Validation { message, .. }) = validate_rule(input, rule, path) {
            result.add_error(message);
        }
    }

    result.into_result_with_path(path)
}

/// Validate a single input object rule.
fn validate_rule(input: &Value, rule: &InputObjectRule, path: &str) -> Result<()> {
    match rule {
        InputObjectRule::AnyOf { fields } => validate_any_of(input, fields, path),
        InputObjectRule::OneOf { fields } => validate_one_of(input, fields, path),
        InputObjectRule::ConditionalRequired {
            if_field,
            then_fields,
        } => validate_conditional_required(input, if_field, then_fields, path),
        InputObjectRule::RequiredIfAbsent {
            absent_field,
            then_fields,
        } => validate_required_if_absent(input, absent_field, then_fields, path),
        InputObjectRule::Custom { name } => Err(FraiseQLError::Validation {
            message: format!(
                "Custom validator '{name}' is not registered. \
                 Register validators via InputValidatorRegistry before executing queries."
            ),
            path:    Some(path.to_string()),
        }),
    }
}

/// Validate that at least one field from the set is present.
fn validate_any_of(input: &Value, fields: &[String], path: &str) -> Result<()> {
    if let Value::Object(obj) = input {
        let has_any = fields
            .iter()
            .any(|name| obj.get(name).is_some_and(|v| !matches!(v, Value::Null)));

        if !has_any {
            return Err(FraiseQLError::Validation {
                message: format!("At least one of [{}] must be provided", fields.join(", ")),
                path:    Some(path.to_string()),
            });
        }
    }

    Ok(())
}

/// Validate that exactly one field from the set is present.
fn validate_one_of(input: &Value, fields: &[String], path: &str) -> Result<()> {
    if let Value::Object(obj) = input {
        let present_count = fields
            .iter()
            .filter(|name| obj.get(*name).is_some_and(|v| !matches!(v, Value::Null)))
            .count();

        if present_count != 1 {
            return Err(FraiseQLError::Validation {
                message: format!(
                    "Exactly one of [{}] must be provided, but {} {} provided",
                    fields.join(", "),
                    present_count,
                    if present_count == 1 { "was" } else { "were" }
                ),
                path:    Some(path.to_string()),
            });
        }
    }

    Ok(())
}

/// Validate conditional requirement: if one field is present, others must be too.
fn validate_conditional_required(
    input: &Value,
    if_field: &str,
    then_fields: &[String],
    path: &str,
) -> Result<()> {
    if let Value::Object(obj) = input {
        let condition_met = obj.get(if_field).is_some_and(|v| !matches!(v, Value::Null));

        if condition_met {
            let missing_fields: Vec<&String> = then_fields
                .iter()
                .filter(|name| obj.get(*name).is_none_or(|v| matches!(v, Value::Null)))
                .collect();

            if !missing_fields.is_empty() {
                return Err(FraiseQLError::Validation {
                    message: format!(
                        "Since '{}' is provided, {} must also be provided",
                        if_field,
                        missing_fields
                            .iter()
                            .map(|s| format!("'{}'", s))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ),
                    path:    Some(path.to_string()),
                });
            }
        }
    }

    Ok(())
}

/// Validate requirement based on absence: if one field is missing, others must be provided.
fn validate_required_if_absent(
    input: &Value,
    absent_field: &str,
    then_fields: &[String],
    path: &str,
) -> Result<()> {
    if let Value::Object(obj) = input {
        let field_absent = obj.get(absent_field).is_none_or(|v| matches!(v, Value::Null));

        if field_absent {
            let missing_fields: Vec<&String> = then_fields
                .iter()
                .filter(|name| obj.get(*name).is_none_or(|v| matches!(v, Value::Null)))
                .collect();

            if !missing_fields.is_empty() {
                return Err(FraiseQLError::Validation {
                    message: format!(
                        "Since '{}' is not provided, {} must be provided",
                        absent_field,
                        missing_fields
                            .iter()
                            .map(|s| format!("'{}'", s))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ),
                    path:    Some(path.to_string()),
                });
            }
        }
    }

    Ok(())
}

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

    use serde_json::json;

    use super::*;

    #[test]
    fn test_any_of_passes() {
        let input = json!({
            "email": "user@example.com",
            "phone": null,
            "address": null
        });
        let rules = vec![InputObjectRule::AnyOf {
            fields: vec![
                "email".to_string(),
                "phone".to_string(),
                "address".to_string(),
            ],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| panic!("any_of should pass when email is present: {e}"));
    }

    #[test]
    fn test_any_of_fails() {
        let input = json!({
            "email": null,
            "phone": null,
            "address": null
        });
        let rules = vec![InputObjectRule::AnyOf {
            fields: vec![
                "email".to_string(),
                "phone".to_string(),
                "address".to_string(),
            ],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("At least one of")),
            "expected Validation error about missing fields, got: {result:?}"
        );
    }

    #[test]
    fn test_one_of_passes() {
        let input = json!({
            "entityId": "123",
            "entityPayload": null
        });
        let rules = vec![InputObjectRule::OneOf {
            fields: vec!["entityId".to_string(), "entityPayload".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("one_of should pass when exactly one field is present: {e}")
        });
    }

    #[test]
    fn test_one_of_fails_both_present() {
        let input = json!({
            "entityId": "123",
            "entityPayload": { "name": "test" }
        });
        let rules = vec![InputObjectRule::OneOf {
            fields: vec!["entityId".to_string(), "entityPayload".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Exactly one of")),
            "expected Validation error about exactly one field, got: {result:?}"
        );
    }

    #[test]
    fn test_one_of_fails_neither_present() {
        let input = json!({
            "entityId": null,
            "entityPayload": null
        });
        let rules = vec![InputObjectRule::OneOf {
            fields: vec!["entityId".to_string(), "entityPayload".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Exactly one of")),
            "expected Validation error about exactly one field, got: {result:?}"
        );
    }

    #[test]
    fn test_conditional_required_passes() {
        let input = json!({
            "isPremium": true,
            "paymentMethod": "credit_card"
        });
        let rules = vec![InputObjectRule::ConditionalRequired {
            if_field:    "isPremium".to_string(),
            then_fields: vec!["paymentMethod".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("conditional_required should pass when condition is met: {e}")
        });
    }

    #[test]
    fn test_conditional_required_fails() {
        let input = json!({
            "isPremium": true,
            "paymentMethod": null
        });
        let rules = vec![InputObjectRule::ConditionalRequired {
            if_field:    "isPremium".to_string(),
            then_fields: vec!["paymentMethod".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("must also be provided")),
            "expected Validation error about missing conditional fields, got: {result:?}"
        );
    }

    #[test]
    fn test_conditional_required_skips_when_condition_false() {
        let input = json!({
            "isPremium": null,
            "paymentMethod": null
        });
        let rules = vec![InputObjectRule::ConditionalRequired {
            if_field:    "isPremium".to_string(),
            then_fields: vec!["paymentMethod".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("conditional_required should skip when condition field is null: {e}")
        });
    }

    #[test]
    fn test_required_if_absent_passes() {
        let input = json!({
            "addressId": null,
            "street": "123 Main St",
            "city": "Springfield",
            "zip": "12345"
        });
        let rules = vec![InputObjectRule::RequiredIfAbsent {
            absent_field: "addressId".to_string(),
            then_fields:  vec!["street".to_string(), "city".to_string(), "zip".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("required_if_absent should pass when all then_fields are provided: {e}")
        });
    }

    #[test]
    fn test_required_if_absent_fails() {
        let input = json!({
            "addressId": null,
            "street": "123 Main St",
            "city": null,
            "zip": "12345"
        });
        let rules = vec![InputObjectRule::RequiredIfAbsent {
            absent_field: "addressId".to_string(),
            then_fields:  vec!["street".to_string(), "city".to_string(), "zip".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("must be provided")),
            "expected Validation error about missing required fields, got: {result:?}"
        );
    }

    #[test]
    fn test_required_if_absent_skips_when_field_present() {
        let input = json!({
            "addressId": "addr_123",
            "street": null,
            "city": null,
            "zip": null
        });
        let rules = vec![InputObjectRule::RequiredIfAbsent {
            absent_field: "addressId".to_string(),
            then_fields:  vec!["street".to_string(), "city".to_string(), "zip".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("required_if_absent should skip when absent_field is present: {e}")
        });
    }

    #[test]
    fn test_multiple_rules_all_pass() {
        let input = json!({
            "entityId": "123",
            "entityPayload": null,
            "isPremium": true,
            "paymentMethod": "credit_card"
        });
        let rules = vec![
            InputObjectRule::OneOf {
                fields: vec!["entityId".to_string(), "entityPayload".to_string()],
            },
            InputObjectRule::ConditionalRequired {
                if_field:    "isPremium".to_string(),
                then_fields: vec!["paymentMethod".to_string()],
            },
        ];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| panic!("multiple rules should all pass: {e}"));
    }

    #[test]
    fn test_multiple_rules_one_fails() {
        let input = json!({
            "entityId": "123",
            "entityPayload": null,
            "isPremium": true,
            "paymentMethod": null
        });
        let rules = vec![
            InputObjectRule::OneOf {
                fields: vec!["entityId".to_string(), "entityPayload".to_string()],
            },
            InputObjectRule::ConditionalRequired {
                if_field:    "isPremium".to_string(),
                then_fields: vec!["paymentMethod".to_string()],
            },
        ];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error when one rule fails, got: {result:?}"
        );
    }

    #[test]
    fn test_multiple_rules_both_fail() {
        let input = json!({
            "entityId": "123",
            "entityPayload": { "name": "test" },
            "isPremium": true,
            "paymentMethod": null
        });
        let rules = vec![
            InputObjectRule::OneOf {
                fields: vec!["entityId".to_string(), "entityPayload".to_string()],
            },
            InputObjectRule::ConditionalRequired {
                if_field:    "isPremium".to_string(),
                then_fields: vec!["paymentMethod".to_string()],
            },
        ];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. })
                if message.contains("Exactly one") || message.contains("must also be provided")),
            "expected aggregated Validation error with both failures, got: {result:?}"
        );
    }

    #[test]
    fn test_error_aggregation() {
        let input = json!({
            "entityId": "123",
            "entityPayload": { "name": "test" },
            "isPremium": true,
            "paymentMethod": null
        });
        let rules = vec![
            InputObjectRule::OneOf {
                fields: vec!["entityId".to_string(), "entityPayload".to_string()],
            },
            InputObjectRule::ConditionalRequired {
                if_field:    "isPremium".to_string(),
                then_fields: vec!["paymentMethod".to_string()],
            },
        ];

        let result = validate_input_object(&input, &rules, Some("createInput"));
        match result {
            Err(FraiseQLError::Validation {
                ref message,
                ref path,
            }) => {
                assert_eq!(*path, Some("createInput".to_string()));
                assert!(message.contains("failed"), "expected 'failed' in message, got: {message}");
            },
            other => panic!("expected Validation error with custom path, got: {other:?}"),
        }
    }

    #[test]
    fn test_conditional_required_multiple_fields() {
        let input = json!({
            "isInternational": true,
            "customsCode": "ABC123",
            "importDuties": "50.00"
        });
        let rules = vec![InputObjectRule::ConditionalRequired {
            if_field:    "isInternational".to_string(),
            then_fields: vec!["customsCode".to_string(), "importDuties".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("conditional_required with multiple fields should pass: {e}")
        });
    }

    #[test]
    fn test_conditional_required_multiple_fields_one_missing() {
        let input = json!({
            "isInternational": true,
            "customsCode": "ABC123",
            "importDuties": null
        });
        let rules = vec![InputObjectRule::ConditionalRequired {
            if_field:    "isInternational".to_string(),
            then_fields: vec!["customsCode".to_string(), "importDuties".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("must also be provided")),
            "expected Validation error about missing conditional field, got: {result:?}"
        );
    }

    #[test]
    fn test_validation_result_aggregation() {
        let mut result = InputObjectValidationResult::new();
        assert!(!result.has_errors());
        assert_eq!(result.error_count, 0);

        result.add_error("Error 1".to_string());
        assert!(result.has_errors());
        assert_eq!(result.error_count, 1);

        result.add_errors(vec!["Error 2".to_string(), "Error 3".to_string()]);
        assert_eq!(result.error_count, 3);
    }

    #[test]
    fn test_validation_result_into_result_success() {
        let result = InputObjectValidationResult::new();
        result
            .into_result()
            .unwrap_or_else(|e| panic!("empty result should be Ok: {e}"));
    }

    #[test]
    fn test_validation_result_into_result_failure() {
        let mut result = InputObjectValidationResult::new();
        result.add_error("Test error".to_string());
        let outcome = result.into_result();
        assert!(
            matches!(outcome, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Test error")),
            "expected Validation error containing 'Test error', got: {outcome:?}"
        );
    }

    #[test]
    fn test_non_object_input() {
        let input = json!([1, 2, 3]);
        let rules = vec![InputObjectRule::AnyOf {
            fields: vec!["field".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("must be an object")),
            "expected Validation error about non-object input, got: {result:?}"
        );
    }

    #[test]
    fn test_empty_rules() {
        let input = json!({"field": "value"});
        let rules: Vec<InputObjectRule> = vec![];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| panic!("empty rules should always pass: {e}"));
    }

    #[test]
    fn test_custom_validator_not_implemented() {
        let input = json!({"field": "value"});
        let rules = vec![InputObjectRule::Custom {
            name: "myValidator".to_string(),
        }];
        let result = validate_input_object(&input, &rules, None);
        match result {
            Err(FraiseQLError::Validation { ref message, .. }) => {
                assert!(
                    message.contains("myValidator"),
                    "expected 'myValidator' in message, got: {message}"
                );
                assert!(
                    message.contains("InputValidatorRegistry"),
                    "expected 'InputValidatorRegistry' in message, got: {message}"
                );
            },
            other => {
                panic!("expected Validation error about unregistered validator, got: {other:?}")
            },
        }
    }

    #[test]
    fn test_complex_create_or_reference_pattern() {
        // Either provide entityId OR provide (name + description), but not both
        let input = json!({
            "entityId": "123",
            "name": null,
            "description": null
        });
        let rules = vec![InputObjectRule::OneOf {
            fields: vec!["entityId".to_string(), "name".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("create_or_reference pattern should pass with entityId: {e}")
        });
    }

    #[test]
    fn test_complex_address_pattern() {
        // Either provide addressId OR provide all of (street, city, zip)
        let input = json!({
            "addressId": null,
            "street": "123 Main St",
            "city": "Springfield",
            "zip": "12345"
        });
        let rules = vec![InputObjectRule::RequiredIfAbsent {
            absent_field: "addressId".to_string(),
            then_fields:  vec!["street".to_string(), "city".to_string(), "zip".to_string()],
        }];
        let result = validate_input_object(&input, &rules, None);
        result.unwrap_or_else(|e| {
            panic!("address pattern should pass with all fields provided: {e}")
        });
    }
}