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
//! Cross-field comparison validators.
//!
//! This module provides validators for comparing values between two fields in an input object.
//! Supports operators: <, <=, >, >=, ==, !=
//!
//! # Examples
//!
//! ```
//! use fraiseql_core::validation::ValidationRule;
//!
//! // Date range validation: start_date < end_date
//! let _rule = ValidationRule::CrossField {
//!     field: "end_date".to_string(),
//!     operator: "gt".to_string(),
//! };
//!
//! // Numeric range: min < max
//! let _rule = ValidationRule::CrossField {
//!     field: "max_value".to_string(),
//!     operator: "lt".to_string(),
//! };
//! ```

use std::cmp::Ordering;

use serde_json::Value;

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

/// Operators supported for cross-field comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ComparisonOperator {
    /// Less than (<)
    LessThan,
    /// Less than or equal (<=)
    LessEqual,
    /// Greater than (>)
    GreaterThan,
    /// Greater than or equal (>=)
    GreaterEqual,
    /// Equal (==)
    Equal,
    /// Not equal (!=)
    NotEqual,
}

impl ComparisonOperator {
    /// Parse operator from string representation.
    #[allow(clippy::should_implement_trait)] // Reason: returns Option<Self> (unrecognized operators yield None), not a FromStr-compatible Result
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "<" | "lt" => Some(Self::LessThan),
            "<=" | "lte" => Some(Self::LessEqual),
            ">" | "gt" => Some(Self::GreaterThan),
            ">=" | "gte" => Some(Self::GreaterEqual),
            "==" | "eq" => Some(Self::Equal),
            "!=" | "neq" => Some(Self::NotEqual),
            _ => None,
        }
    }

    /// Get the symbol for display.
    pub const fn symbol(&self) -> &'static str {
        match self {
            Self::LessThan => "<",
            Self::LessEqual => "<=",
            Self::GreaterThan => ">",
            Self::GreaterEqual => ">=",
            Self::Equal => "==",
            Self::NotEqual => "!=",
        }
    }

    /// Get the long name for error messages.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::LessThan => "less than",
            Self::LessEqual => "less than or equal to",
            Self::GreaterThan => "greater than",
            Self::GreaterEqual => "greater than or equal to",
            Self::Equal => "equal to",
            Self::NotEqual => "not equal to",
        }
    }
}

/// Validates a cross-field comparison between two fields.
///
/// Compares `left_field` with `right_field` using the given operator.
///
/// # Arguments
///
/// * `input` - The input object containing both fields
/// * `left_field` - The name of the left field to compare
/// * `operator` - The comparison operator
/// * `right_field` - The name of the right field to compare against
/// * `context_path` - Optional field path for error reporting
///
/// # Errors
///
/// Returns an error if:
/// - Either field is missing from the input
/// - The fields have incompatible types
/// - The comparison fails
pub fn validate_cross_field_comparison(
    input: &Value,
    left_field: &str,
    operator: ComparisonOperator,
    right_field: &str,
    context_path: Option<&str>,
) -> Result<()> {
    let field_path = context_path.unwrap_or("input");

    if let Value::Object(obj) = input {
        let left_val = obj.get(left_field).ok_or_else(|| FraiseQLError::Validation {
            message: format!("Field '{}' not found in input", left_field),
            path:    Some(field_path.to_string()),
        })?;

        let right_val = obj.get(right_field).ok_or_else(|| FraiseQLError::Validation {
            message: format!("Field '{}' not found in input", right_field),
            path:    Some(field_path.to_string()),
        })?;

        // Skip validation if either field is null
        if matches!(left_val, Value::Null) || matches!(right_val, Value::Null) {
            return Ok(());
        }

        compare_values(left_val, right_val, left_field, operator, right_field, field_path)
    } else {
        Err(FraiseQLError::Validation {
            message: "Input is not an object".to_string(),
            path:    Some(field_path.to_string()),
        })
    }
}

/// Compare two JSON values and return result based on operator.
fn compare_values(
    left: &Value,
    right: &Value,
    left_field: &str,
    operator: ComparisonOperator,
    right_field: &str,
    context_path: &str,
) -> Result<()> {
    let ordering = match (left, right) {
        // Both are numbers
        (Value::Number(l), Value::Number(r)) => {
            let l_val = l.as_f64().unwrap_or(0.0);
            let r_val = r.as_f64().unwrap_or(0.0);
            if l_val < r_val {
                Ordering::Less
            } else if l_val > r_val {
                Ordering::Greater
            } else {
                Ordering::Equal
            }
        },
        // Both are strings (lexicographic comparison)
        (Value::String(l), Value::String(r)) => l.cmp(r),
        // Type mismatch
        _ => {
            return Err(FraiseQLError::Validation {
                message: format!(
                    "Cannot compare '{}' ({}) with '{}' ({})",
                    left_field,
                    value_type_name(left),
                    right_field,
                    value_type_name(right)
                ),
                path:    Some(context_path.to_string()),
            });
        },
    };

    let result = match operator {
        ComparisonOperator::LessThan => matches!(ordering, Ordering::Less),
        ComparisonOperator::LessEqual => !matches!(ordering, Ordering::Greater),
        ComparisonOperator::GreaterThan => matches!(ordering, Ordering::Greater),
        ComparisonOperator::GreaterEqual => !matches!(ordering, Ordering::Less),
        ComparisonOperator::Equal => matches!(ordering, Ordering::Equal),
        ComparisonOperator::NotEqual => !matches!(ordering, Ordering::Equal),
    };

    if !result {
        return Err(FraiseQLError::Validation {
            message: format!(
                "'{}' ({}) must be {} '{}' ({})",
                left_field,
                value_to_string(left),
                operator.name(),
                right_field,
                value_to_string(right)
            ),
            path:    Some(context_path.to_string()),
        });
    }

    Ok(())
}

/// Get the type name of a JSON value.
const fn value_type_name(val: &Value) -> &'static str {
    match val {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

/// Convert a JSON value to a string for display in error messages.
fn value_to_string(val: &Value) -> String {
    match val {
        Value::String(s) => format!("\"{}\"", s),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Null => "null".to_string(),
        _ => val.to_string(),
    }
}

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

    use super::*;

    #[test]
    fn test_operator_parsing() {
        assert_eq!(ComparisonOperator::from_str("<"), Some(ComparisonOperator::LessThan));
        assert_eq!(ComparisonOperator::from_str("lt"), Some(ComparisonOperator::LessThan));
        assert_eq!(ComparisonOperator::from_str("<="), Some(ComparisonOperator::LessEqual));
        assert_eq!(ComparisonOperator::from_str("lte"), Some(ComparisonOperator::LessEqual));
        assert_eq!(ComparisonOperator::from_str(">"), Some(ComparisonOperator::GreaterThan));
        assert_eq!(ComparisonOperator::from_str("gt"), Some(ComparisonOperator::GreaterThan));
        assert_eq!(ComparisonOperator::from_str(">="), Some(ComparisonOperator::GreaterEqual));
        assert_eq!(ComparisonOperator::from_str("gte"), Some(ComparisonOperator::GreaterEqual));
        assert_eq!(ComparisonOperator::from_str("=="), Some(ComparisonOperator::Equal));
        assert_eq!(ComparisonOperator::from_str("eq"), Some(ComparisonOperator::Equal));
        assert_eq!(ComparisonOperator::from_str("!="), Some(ComparisonOperator::NotEqual));
        assert_eq!(ComparisonOperator::from_str("neq"), Some(ComparisonOperator::NotEqual));
        assert_eq!(ComparisonOperator::from_str("invalid"), None);
    }

    #[test]
    fn test_numeric_less_than() {
        let input = json!({
            "start": 10,
            "end": 20
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected 10 < 20 to pass: {e}"));
    }

    #[test]
    fn test_numeric_less_than_fails() {
        let input = json!({
            "start": 30,
            "end": 20
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("must be") && message.contains("less than")),
            "expected Validation error for 30 < 20, got: {result:?}"
        );
    }

    #[test]
    fn test_numeric_equal() {
        let input = json!({
            "a": 42,
            "b": 42
        });
        let result =
            validate_cross_field_comparison(&input, "a", ComparisonOperator::Equal, "b", None);
        result.unwrap_or_else(|e| panic!("expected 42 == 42 to pass: {e}"));
    }

    #[test]
    fn test_numeric_not_equal() {
        let input = json!({
            "a": 10,
            "b": 20
        });
        let result =
            validate_cross_field_comparison(&input, "a", ComparisonOperator::NotEqual, "b", None);
        result.unwrap_or_else(|e| panic!("expected 10 != 20 to pass: {e}"));
    }

    #[test]
    fn test_numeric_greater_than_or_equal() {
        let input = json!({
            "min": 10,
            "max": 10
        });
        let result = validate_cross_field_comparison(
            &input,
            "max",
            ComparisonOperator::GreaterEqual,
            "min",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected 10 >= 10 to pass: {e}"));
    }

    #[test]
    fn test_string_comparison() {
        let input = json!({
            "start_name": "alice",
            "end_name": "zoe"
        });
        let result = validate_cross_field_comparison(
            &input,
            "start_name",
            ComparisonOperator::LessThan,
            "end_name",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected 'alice' < 'zoe' to pass: {e}"));
    }

    #[test]
    fn test_string_comparison_fails() {
        let input = json!({
            "start_name": "zoe",
            "end_name": "alice"
        });
        let result = validate_cross_field_comparison(
            &input,
            "start_name",
            ComparisonOperator::LessThan,
            "end_name",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("must be") && message.contains("less than")),
            "expected Validation error for 'zoe' < 'alice', got: {result:?}"
        );
    }

    #[test]
    fn test_date_string_comparison() {
        let input = json!({
            "start_date": "2024-01-01",
            "end_date": "2024-12-31"
        });
        let result = validate_cross_field_comparison(
            &input,
            "start_date",
            ComparisonOperator::LessThan,
            "end_date",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected date string comparison to pass: {e}"));
    }

    #[test]
    fn test_float_comparison() {
        let input = json!({
            "price": 19.99,
            "budget": 25.50
        });
        let result = validate_cross_field_comparison(
            &input,
            "price",
            ComparisonOperator::LessThan,
            "budget",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected 19.99 < 25.50 to pass: {e}"));
    }

    #[test]
    fn test_missing_left_field() {
        let input = json!({
            "end": 20
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("not found")),
            "expected Validation error for missing left field, got: {result:?}"
        );
    }

    #[test]
    fn test_missing_right_field() {
        let input = json!({
            "start": 10
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("not found")),
            "expected Validation error for missing right field, got: {result:?}"
        );
    }

    #[test]
    fn test_null_fields_skipped() {
        let input = json!({
            "start": null,
            "end": 20
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected null field to be skipped: {e}"));
    }

    #[test]
    fn test_both_null_fields_skipped() {
        let input = json!({
            "start": null,
            "end": null
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        result.unwrap_or_else(|e| panic!("expected both null fields to be skipped: {e}"));
    }

    #[test]
    fn test_type_mismatch_error() {
        let input = json!({
            "start": 10,
            "end": "twenty"
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("Cannot compare")),
            "expected Validation error for type mismatch, got: {result:?}"
        );
    }

    #[test]
    fn test_error_includes_context_path() {
        let input = json!({
            "start": 30,
            "end": 20
        });
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            Some("dateRange"),
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref path, .. }) if *path == Some("dateRange".to_string())),
            "expected Validation error with path 'dateRange', got: {result:?}"
        );
    }

    #[test]
    fn test_error_message_includes_values() {
        let input = json!({
            "price": 100,
            "max_price": 50
        });
        let result = validate_cross_field_comparison(
            &input,
            "price",
            ComparisonOperator::LessThan,
            "max_price",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("price") && message.contains("max_price") && message.contains("100") && message.contains("50")),
            "expected Validation error with field names and values, got: {result:?}"
        );
    }

    #[test]
    fn test_all_operators() {
        let test_cases = vec![
            (10, 20, ComparisonOperator::LessThan, true),
            (10, 10, ComparisonOperator::LessEqual, true),
            (20, 10, ComparisonOperator::GreaterThan, true),
            (10, 10, ComparisonOperator::GreaterEqual, true),
            (42, 42, ComparisonOperator::Equal, true),
            (10, 20, ComparisonOperator::NotEqual, true),
            (20, 10, ComparisonOperator::LessThan, false),
            (10, 20, ComparisonOperator::GreaterThan, false),
        ];

        for (left, right, op, should_pass) in test_cases {
            let input = json!({ "a": left, "b": right });
            let result = validate_cross_field_comparison(&input, "a", op, "b", None);
            assert_eq!(
                result.is_ok(),
                should_pass,
                "Failed for {} {} {}",
                left,
                op.symbol(),
                right
            );
        }
    }

    #[test]
    fn test_non_object_input() {
        let input = json!([1, 2, 3]);
        let result =
            validate_cross_field_comparison(&input, "a", ComparisonOperator::LessThan, "b", None);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("not an object")),
            "expected Validation error for non-object input, got: {result:?}"
        );
    }

    #[test]
    fn test_empty_object() {
        let input = json!({});
        let result = validate_cross_field_comparison(
            &input,
            "start",
            ComparisonOperator::LessThan,
            "end",
            None,
        );
        assert!(
            matches!(result, Err(FraiseQLError::Validation { ref message, .. }) if message.contains("not found")),
            "expected Validation error for empty object, got: {result:?}"
        );
    }

    #[test]
    fn test_zero_comparison() {
        let input = json!({
            "a": 0,
            "b": 0
        });
        let result =
            validate_cross_field_comparison(&input, "a", ComparisonOperator::Equal, "b", None);
        result.unwrap_or_else(|e| panic!("expected 0 == 0 to pass: {e}"));
    }

    #[test]
    fn test_negative_number_comparison() {
        let input = json!({
            "a": -10,
            "b": 5
        });
        let result =
            validate_cross_field_comparison(&input, "a", ComparisonOperator::LessThan, "b", None);
        result.unwrap_or_else(|e| panic!("expected -10 < 5 to pass: {e}"));
    }

    #[test]
    fn test_empty_string_comparison() {
        let input = json!({
            "a": "",
            "b": "text"
        });
        let result =
            validate_cross_field_comparison(&input, "a", ComparisonOperator::LessThan, "b", None);
        result.unwrap_or_else(|e| panic!("expected '' < 'text' to pass: {e}"));
    }
}