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
//! Mutual exclusivity and conditional requirement validators.
//!
//! This module provides validators for complex field-relationship rules:
//! - `OneOf`: Exactly one field from a set must be provided
//! - `AnyOf`: At least one field from a set must be provided
//! - `ConditionalRequired`: If one field is present, others must be too
//! - `RequiredIfAbsent`: If one field is missing, others must be provided

use serde_json::Value;

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

/// Validates that exactly one field from the specified set is provided.
///
/// # Example
/// ```
/// use fraiseql_core::validation::mutual_exclusivity::OneOfValidator;
/// use serde_json::json;
/// // Either entityId OR entityPayload, but not both
/// let input = json!({ "entityId": "123", "entityPayload": null });
/// assert!(
///     OneOfValidator::validate(&input, &["entityId".to_string(), "entityPayload".to_string()], None).is_ok(),
///     "one-of constraint satisfied when only entityId is present"
/// );
/// ```
pub struct OneOfValidator;

impl OneOfValidator {
    /// Validate that exactly one field from the set is present and non-null.
    ///
    /// # Errors
    ///
    /// Returns `FraiseQLError::Validation` if zero or more than one field is present.
    pub fn validate(
        input: &Value,
        field_names: &[String],
        context_path: Option<&str>,
    ) -> Result<()> {
        let field_path = context_path.unwrap_or("input");

        let present_count = field_names
            .iter()
            .filter(|name| {
                if let Value::Object(obj) = input {
                    obj.get(*name).is_some_and(|v| !matches!(v, Value::Null))
                } else {
                    false
                }
            })
            .count();

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

        Ok(())
    }
}

/// Validates that at least one field from the specified set is provided.
///
/// # Example
/// ```
/// use fraiseql_core::validation::mutual_exclusivity::AnyOfValidator;
/// use serde_json::json;
/// // At least one of: email, phone, address must be present
/// let input = json!({ "email": "user@example.com", "phone": null, "address": null });
/// assert!(
///     AnyOfValidator::validate(&input, &["email".to_string(), "phone".to_string(), "address".to_string()], None).is_ok(),
///     "any-of constraint satisfied when at least one field is present"
/// );
/// ```
pub struct AnyOfValidator;

impl AnyOfValidator {
    /// Validate that at least one field from the set is present and non-null.
    ///
    /// # Errors
    ///
    /// Returns `FraiseQLError::Validation` if none of the specified fields are present.
    pub fn validate(
        input: &Value,
        field_names: &[String],
        context_path: Option<&str>,
    ) -> Result<()> {
        let field_path = context_path.unwrap_or("input");

        let has_any = field_names.iter().any(|name| {
            if let Value::Object(obj) = input {
                obj.get(name).is_some_and(|v| !matches!(v, Value::Null))
            } else {
                false
            }
        });

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

        Ok(())
    }
}

/// Validates conditional requirement: if one field is present, others must be too.
///
/// # Example
/// ```
/// use fraiseql_core::validation::mutual_exclusivity::ConditionalRequiredValidator;
/// use serde_json::json;
/// // If isPremium is true, then paymentMethod is required
/// let input = json!({ "isPremium": true, "paymentMethod": "credit_card" });
/// assert!(
///     ConditionalRequiredValidator::validate(&input, "isPremium", &["paymentMethod".to_string()], None).is_ok(),
///     "conditional requirement satisfied when condition field is true and required field present"
/// );
/// ```
pub struct ConditionalRequiredValidator;

impl ConditionalRequiredValidator {
    /// Validate that if `if_field_present` is present, all `then_required` fields must be too.
    ///
    /// # Errors
    ///
    /// Returns `FraiseQLError::Validation` if the condition field is present but any
    /// required field is missing.
    pub fn validate(
        input: &Value,
        if_field_present: &str,
        then_required: &[String],
        context_path: Option<&str>,
    ) -> Result<()> {
        let field_path = context_path.unwrap_or("input");

        if let Value::Object(obj) = input {
            // Check if the condition field is present and non-null
            let condition_met =
                obj.get(if_field_present).is_some_and(|v| !matches!(v, Value::Null));

            if condition_met {
                // If condition is met, check that all required fields are present
                let missing_fields: Vec<&String> = then_required
                    .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_present,
                            missing_fields
                                .iter()
                                .map(|s| format!("'{}'", s))
                                .collect::<Vec<_>>()
                                .join(", ")
                        ),
                        path:    Some(field_path.to_string()),
                    });
                }
            }
        }

        Ok(())
    }
}

/// Validates conditional requirement based on absence: if one field is missing, others must be
/// provided.
///
/// # Example
/// ```
/// use fraiseql_core::validation::mutual_exclusivity::RequiredIfAbsentValidator;
/// use serde_json::json;
/// // If addressId is not provided, then street, city, zip must all be provided
/// let input = json!({ "addressId": null, "street": "123 Main St", "city": "Springfield", "zip": "12345" });
/// assert!(
///     RequiredIfAbsentValidator::validate(&input, "addressId", &["street".to_string(), "city".to_string(), "zip".to_string()], None).is_ok(),
///     "required-if-absent constraint satisfied when absent field is null and all required fields present"
/// );
/// ```
pub struct RequiredIfAbsentValidator;

impl RequiredIfAbsentValidator {
    /// Validate that if `absent_field` is absent/null, all `then_required` fields must be provided.
    ///
    /// # Errors
    ///
    /// Returns `FraiseQLError::Validation` if the condition field is absent and any
    /// required field is also missing.
    pub fn validate(
        input: &Value,
        absent_field: &str,
        then_required: &[String],
        context_path: Option<&str>,
    ) -> Result<()> {
        let field_path = context_path.unwrap_or("input");

        if let Value::Object(obj) = input {
            // Check if the condition field is absent or null
            let field_absent = obj.get(absent_field).is_none_or(|v| matches!(v, Value::Null));

            if field_absent {
                // If field is absent, check that all required fields are present
                let missing_fields: Vec<&String> = then_required
                    .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(field_path.to_string()),
                    });
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn test_one_of_validator_exactly_one_present() {
        let input = json!({
            "entityId": "123",
            "entityPayload": null
        });
        let result = OneOfValidator::validate(
            &input,
            &["entityId".to_string(), "entityPayload".to_string()],
            None,
        );
        result.unwrap_or_else(|e| panic!("expected exactly-one to pass with one present: {e}"));
    }

    #[test]
    fn test_one_of_validator_both_present() {
        let input = json!({
            "entityId": "123",
            "entityPayload": { "name": "test" }
        });
        let result = OneOfValidator::validate(
            &input,
            &["entityId".to_string(), "entityPayload".to_string()],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Exactly one of")),
            "expected Validation error for both fields present, got: {result:?}"
        );
    }

    #[test]
    fn test_one_of_validator_neither_present() {
        let input = json!({
            "entityId": null,
            "entityPayload": null
        });
        let result = OneOfValidator::validate(
            &input,
            &["entityId".to_string(), "entityPayload".to_string()],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Exactly one of")),
            "expected Validation error for neither field present, got: {result:?}"
        );
    }

    #[test]
    fn test_one_of_validator_missing_field() {
        let input = json!({
            "entityId": "123"
        });
        let result = OneOfValidator::validate(
            &input,
            &["entityId".to_string(), "entityPayload".to_string()],
            None,
        );
        result.unwrap_or_else(|e| {
            panic!("expected exactly-one to pass with one field missing from object: {e}")
        });
    }

    #[test]
    fn test_any_of_validator_one_present() {
        let input = json!({
            "email": "user@example.com",
            "phone": null,
            "address": null
        });
        let result = AnyOfValidator::validate(
            &input,
            &[
                "email".to_string(),
                "phone".to_string(),
                "address".to_string(),
            ],
            None,
        );
        result.unwrap_or_else(|e| panic!("expected any-of to pass with one present: {e}"));
    }

    #[test]
    fn test_any_of_validator_multiple_present() {
        let input = json!({
            "email": "user@example.com",
            "phone": "+1234567890",
            "address": null
        });
        let result = AnyOfValidator::validate(
            &input,
            &[
                "email".to_string(),
                "phone".to_string(),
                "address".to_string(),
            ],
            None,
        );
        result.unwrap_or_else(|e| panic!("expected any-of to pass with multiple present: {e}"));
    }

    #[test]
    fn test_any_of_validator_none_present() {
        let input = json!({
            "email": null,
            "phone": null,
            "address": null
        });
        let result = AnyOfValidator::validate(
            &input,
            &[
                "email".to_string(),
                "phone".to_string(),
                "address".to_string(),
            ],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("At least one of")),
            "expected Validation error for no fields present, got: {result:?}"
        );
    }

    #[test]
    fn test_conditional_required_validator_condition_met_requirement_met() {
        let input = json!({
            "isPremium": true,
            "paymentMethod": "credit_card"
        });
        let result = ConditionalRequiredValidator::validate(
            &input,
            "isPremium",
            &["paymentMethod".to_string()],
            None,
        );
        result.unwrap_or_else(|e| {
            panic!("expected conditional-required to pass when requirement met: {e}")
        });
    }

    #[test]
    fn test_conditional_required_validator_condition_met_requirement_missing() {
        let input = json!({
            "isPremium": true,
            "paymentMethod": null
        });
        let result = ConditionalRequiredValidator::validate(
            &input,
            "isPremium",
            &["paymentMethod".to_string()],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Since") && message.contains("must also be provided")),
            "expected Validation error for missing conditional requirement, got: {result:?}"
        );
    }

    #[test]
    fn test_conditional_required_validator_condition_not_met() {
        let input = json!({
            "isPremium": null,
            "paymentMethod": null
        });
        let result = ConditionalRequiredValidator::validate(
            &input,
            "isPremium",
            &["paymentMethod".to_string()],
            None,
        );
        result.unwrap_or_else(|e| {
            panic!("expected conditional-required to pass when condition not met: {e}")
        });
    }

    #[test]
    fn test_conditional_required_validator_multiple_requirements() {
        let input = json!({
            "isInternational": true,
            "customsCode": "ABC123",
            "importDuties": "50.00"
        });
        let result = ConditionalRequiredValidator::validate(
            &input,
            "isInternational",
            &["customsCode".to_string(), "importDuties".to_string()],
            None,
        );
        result.unwrap_or_else(|e| {
            panic!("expected conditional-required to pass with all requirements met: {e}")
        });
    }

    #[test]
    fn test_conditional_required_validator_one_requirement_missing() {
        let input = json!({
            "isInternational": true,
            "customsCode": "ABC123",
            "importDuties": null
        });
        let result = ConditionalRequiredValidator::validate(
            &input,
            "isInternational",
            &["customsCode".to_string(), "importDuties".to_string()],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Since") && message.contains("must also be provided")),
            "expected Validation error for one missing requirement, got: {result:?}"
        );
    }

    #[test]
    fn test_required_if_absent_validator_field_absent_requirements_met() {
        let input = json!({
            "addressId": null,
            "street": "123 Main St",
            "city": "Springfield",
            "zip": "12345"
        });
        let result = RequiredIfAbsentValidator::validate(
            &input,
            "addressId",
            &["street".to_string(), "city".to_string(), "zip".to_string()],
            None,
        );
        result.unwrap_or_else(|e| {
            panic!("expected required-if-absent to pass when requirements met: {e}")
        });
    }

    #[test]
    fn test_required_if_absent_validator_field_absent_requirements_missing() {
        let input = json!({
            "addressId": null,
            "street": "123 Main St",
            "city": null,
            "zip": "12345"
        });
        let result = RequiredIfAbsentValidator::validate(
            &input,
            "addressId",
            &["street".to_string(), "city".to_string(), "zip".to_string()],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Since") && message.contains("must be provided")),
            "expected Validation error for missing requirements when field absent, got: {result:?}"
        );
    }

    #[test]
    fn test_required_if_absent_validator_field_present() {
        let input = json!({
            "addressId": "addr_123",
            "street": null,
            "city": null,
            "zip": null
        });
        let result = RequiredIfAbsentValidator::validate(
            &input,
            "addressId",
            &["street".to_string(), "city".to_string(), "zip".to_string()],
            None,
        );
        result.unwrap_or_else(|e| {
            panic!("expected required-if-absent to pass when field present: {e}")
        });
    }

    #[test]
    fn test_required_if_absent_validator_all_missing_from_object() {
        let input = json!({});
        let result = RequiredIfAbsentValidator::validate(
            &input,
            "addressId",
            &["street".to_string(), "city".to_string()],
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Since") && message.contains("must be provided")),
            "expected Validation error for all fields missing from empty object, got: {result:?}"
        );
    }

    #[test]
    fn test_error_messages_include_context() {
        let input = json!({
            "entityId": "123",
            "entityPayload": { "name": "test" }
        });
        let result = OneOfValidator::validate(
            &input,
            &["entityId".to_string(), "entityPayload".to_string()],
            Some("createInput"),
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref path, .. }) if *path == Some("createInput".to_string())),
            "expected Validation error with path 'createInput', got: {result:?}"
        );
    }
}