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
//! Input validation for GraphQL mutations and queries.
//!
//! This module provides the validation pipeline that processes GraphQL input
//! variables and validates them against defined validation rules before
//! execution.

use serde_json::Value;

use crate::{
    error::{FraiseQLError, Result, ValidationFieldError},
    schema::CompiledSchema,
    validation::ValidationRule,
};

/// Validation error aggregator - collects multiple validation errors.
#[derive(Debug, Clone, Default)]
pub struct ValidationErrorCollection {
    /// All collected validation errors.
    pub errors: Vec<ValidationFieldError>,
}

impl ValidationErrorCollection {
    /// Create a new empty error collection.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an error to the collection.
    pub fn add_error(&mut self, error: ValidationFieldError) {
        self.errors.push(error);
    }

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

    /// Get the number of errors.
    pub const fn len(&self) -> usize {
        self.errors.len()
    }

    /// Convert to a FraiseQL error.
    pub fn to_error(&self) -> FraiseQLError {
        if self.errors.is_empty() {
            FraiseQLError::validation("No validation errors")
        } else if self.errors.len() == 1 {
            let err = &self.errors[0];
            FraiseQLError::Validation {
                message: err.to_string(),
                path:    Some(err.field.clone()),
            }
        } else {
            let messages: Vec<String> = self.errors.iter().map(|e| e.to_string()).collect();
            FraiseQLError::Validation {
                message: format!("Multiple validation errors: {}", messages.join("; ")),
                path:    None,
            }
        }
    }
}

/// Validate a scalar value against a custom scalar type definition.
///
/// This function validates a JSON value against a custom scalar type registered
/// in the schema, checking both validation rules and ELO expressions.
///
/// # Arguments
///
/// * `value` - The JSON value to validate
/// * `scalar_type_name` - Name of the custom scalar type (e.g., "`LibraryCode`")
/// * `schema` - The compiled schema containing custom scalar definitions
///
/// # Errors
///
/// Returns a validation error if the value doesn't match the custom scalar definition.
pub fn validate_custom_scalar_from_schema(
    value: &Value,
    scalar_type_name: &str,
    schema: &CompiledSchema,
) -> Result<()> {
    // Check if this is a custom scalar type
    if schema.custom_scalars.exists(scalar_type_name) {
        schema.custom_scalars.validate(scalar_type_name, value)
    } else {
        // Not a custom scalar, pass through (built-in type)
        Ok(())
    }
}

/// Validate JSON input against validation rules.
///
/// This function recursively validates a JSON value against a set of
/// validation rules, collecting all errors that occur.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] if any rule is violated (e.g., string
/// too short, value out of range, or a required field is null).
pub fn validate_input(value: &Value, field_path: &str, rules: &[ValidationRule]) -> Result<()> {
    let mut errors = ValidationErrorCollection::new();

    match value {
        Value::String(s) => {
            for rule in rules {
                if let Err(FraiseQLError::Validation { message, .. }) =
                    validate_string_field(s, field_path, rule)
                {
                    if let Some(field_err) = extract_field_error(&message) {
                        errors.add_error(field_err);
                    }
                }
            }
        },
        Value::Null => {
            for rule in rules {
                if rule.is_required() {
                    errors.add_error(ValidationFieldError::new(
                        field_path,
                        "required",
                        "Field is required",
                    ));
                }
            }
        },
        _ => {
            // Other types (number, bool, array, object) have different validation logic
        },
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors.to_error())
    }
}

/// Validate a string field against a validation rule.
fn validate_string_field(value: &str, field_path: &str, rule: &ValidationRule) -> Result<()> {
    match rule {
        ValidationRule::Required => {
            if value.is_empty() {
                return Err(FraiseQLError::Validation {
                    message: format!(
                        "Field validation failed: {}",
                        ValidationFieldError::new(field_path, "required", "Field is required")
                    ),
                    path:    Some(field_path.to_string()),
                });
            }
            Ok(())
        },
        ValidationRule::Pattern { pattern, message } => {
            let regex = regex::Regex::new(pattern)
                .map_err(|e| FraiseQLError::validation(format!("Invalid regex pattern: {}", e)))?;
            if regex.is_match(value) {
                Ok(())
            } else {
                let msg = message.clone().unwrap_or_else(|| "Pattern mismatch".to_string());
                Err(FraiseQLError::Validation {
                    message: format!(
                        "Field validation failed: {}",
                        ValidationFieldError::new(field_path, "pattern", msg)
                    ),
                    path:    Some(field_path.to_string()),
                })
            }
        },
        ValidationRule::Length { min, max } => {
            let len = value.len();
            let valid = if let Some(m) = min { len >= *m } else { true }
                && if let Some(m) = max { len <= *m } else { true };

            if valid {
                Ok(())
            } else {
                let msg = match (min, max) {
                    (Some(m), Some(x)) => format!("Length must be between {} and {}", m, x),
                    (Some(m), None) => format!("Length must be at least {}", m),
                    (None, Some(x)) => format!("Length must be at most {}", x),
                    (None, None) => "Length validation failed".to_string(),
                };
                Err(FraiseQLError::Validation {
                    message: format!(
                        "Field validation failed: {}",
                        ValidationFieldError::new(field_path, "length", msg)
                    ),
                    path:    Some(field_path.to_string()),
                })
            }
        },
        ValidationRule::Enum { values } => {
            if values.contains(&value.to_string()) {
                Ok(())
            } else {
                Err(FraiseQLError::Validation {
                    message: format!(
                        "Field validation failed: {}",
                        ValidationFieldError::new(
                            field_path,
                            "enum",
                            format!("Must be one of: {}", values.join(", "))
                        )
                    ),
                    path:    Some(field_path.to_string()),
                })
            }
        },
        _ => Ok(()), // Other rule types handled elsewhere
    }
}

/// Extract field error information from an error message.
fn extract_field_error(message: &str) -> Option<ValidationFieldError> {
    // Format: "Field validation failed: field (rule): message"
    if message.contains("Field validation failed:") {
        if let Some(field_start) = message.find("Field validation failed: ") {
            let rest = &message[field_start + "Field validation failed: ".len()..];
            if let Some(paren_start) = rest.find('(') {
                if let Some(paren_end) = rest.find(')') {
                    let field = rest[..paren_start].trim().to_string();
                    let rule_type = rest[paren_start + 1..paren_end].to_string();
                    let msg_start = rest.find(": ").unwrap_or(0) + 2;
                    let message_text = rest[msg_start..].to_string();
                    return Some(ValidationFieldError::new(field, rule_type, message_text));
                }
            }
        }
    }
    None
}

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

    use super::*;

    #[test]
    fn test_validation_error_collection() {
        let mut errors = ValidationErrorCollection::new();
        assert!(errors.is_empty());

        errors.add_error(ValidationFieldError::new("email", "pattern", "Invalid email"));
        assert!(!errors.is_empty());
        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn test_validation_error_collection_to_error() {
        let mut errors = ValidationErrorCollection::new();
        errors.add_error(ValidationFieldError::new("email", "pattern", "Invalid email"));

        let err = errors.to_error();
        assert!(matches!(err, FraiseQLError::Validation { .. }));
    }

    #[test]
    fn test_validate_required_field() {
        let rule = ValidationRule::Required;
        let result = validate_string_field("value", "field", &rule);
        result.unwrap_or_else(|e| panic!("expected Ok for non-empty value: {e}"));

        let result = validate_string_field("", "field", &rule);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for empty required field, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_pattern() {
        let rule = ValidationRule::Pattern {
            pattern: "^[a-z]+$".to_string(),
            message: None,
        };

        let result = validate_string_field("hello", "field", &rule);
        result.unwrap_or_else(|e| panic!("expected Ok for matching pattern: {e}"));

        let result = validate_string_field("Hello", "field", &rule);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for non-matching pattern, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_length() {
        let rule = ValidationRule::Length {
            min: Some(3),
            max: Some(10),
        };

        let result = validate_string_field("hello", "field", &rule);
        result.unwrap_or_else(|e| panic!("expected Ok for in-range length: {e}"));

        let result = validate_string_field("hi", "field", &rule);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for too-short string, got: {result:?}"
        );

        let result = validate_string_field("this is too long", "field", &rule);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for too-long string, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_enum() {
        let rule = ValidationRule::Enum {
            values: vec!["active".to_string(), "inactive".to_string()],
        };

        let result = validate_string_field("active", "field", &rule);
        result.unwrap_or_else(|e| panic!("expected Ok for valid enum value: {e}"));

        let result = validate_string_field("unknown", "field", &rule);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for invalid enum value, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_null_field() {
        let rule = ValidationRule::Required;
        let result = validate_input(&Value::Null, "field", &[rule]);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for null required field, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_custom_scalar_library_code_valid() {
        use crate::{
            schema::CompiledSchema,
            validation::{CustomTypeDef, CustomTypeRegistry, CustomTypeRegistryConfig},
        };

        let schema = {
            let mut s = CompiledSchema::new();
            let registry = CustomTypeRegistry::new(CustomTypeRegistryConfig::default());

            let mut def = CustomTypeDef::new("LibraryCode".to_string());
            def.validation_rules = vec![ValidationRule::Pattern {
                pattern: r"^LIB-[0-9]{4}$".to_string(),
                message: Some("Library code must be LIB-#### format".to_string()),
            }];

            registry.register("LibraryCode".to_string(), def).unwrap();

            s.custom_scalars = registry;
            s
        };

        let value = serde_json::json!("LIB-1234");
        let result = validate_custom_scalar_from_schema(&value, "LibraryCode", &schema);
        result.unwrap_or_else(|e| panic!("expected Ok for valid LibraryCode: {e}"));
    }

    #[test]
    fn test_validate_custom_scalar_library_code_invalid() {
        use crate::{
            schema::CompiledSchema,
            validation::{CustomTypeDef, CustomTypeRegistry, CustomTypeRegistryConfig},
        };

        let schema = {
            let mut s = CompiledSchema::new();
            let registry = CustomTypeRegistry::new(CustomTypeRegistryConfig::default());

            let mut def = CustomTypeDef::new("LibraryCode".to_string());
            def.validation_rules = vec![ValidationRule::Pattern {
                pattern: r"^LIB-[0-9]{4}$".to_string(),
                message: Some("Library code must be LIB-#### format".to_string()),
            }];

            registry.register("LibraryCode".to_string(), def).unwrap();

            s.custom_scalars = registry;
            s
        };

        let value = serde_json::json!("INVALID");
        let result = validate_custom_scalar_from_schema(&value, "LibraryCode", &schema);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for invalid LibraryCode, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_custom_scalar_student_id_with_length() {
        use crate::{
            schema::CompiledSchema,
            validation::{CustomTypeDef, CustomTypeRegistry, CustomTypeRegistryConfig},
        };

        let schema = {
            let mut s = CompiledSchema::new();
            let registry = CustomTypeRegistry::new(CustomTypeRegistryConfig::default());

            let mut def = CustomTypeDef::new("StudentID".to_string());
            def.validation_rules = vec![
                ValidationRule::Pattern {
                    pattern: r"^STU-[0-9]{4}-[0-9]{3}$".to_string(),
                    message: None,
                },
                ValidationRule::Length {
                    min: Some(12),
                    max: Some(12),
                },
            ];

            registry.register("StudentID".to_string(), def).unwrap();

            s.custom_scalars = registry;
            s
        };

        // Valid: matches pattern and length
        let value = serde_json::json!("STU-2024-001");
        let result = validate_custom_scalar_from_schema(&value, "StudentID", &schema);
        result.unwrap_or_else(|e| panic!("expected Ok for valid StudentID: {e}"));

        // Invalid: wrong pattern
        let value = serde_json::json!("STUDENT-2024");
        let result = validate_custom_scalar_from_schema(&value, "StudentID", &schema);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for invalid StudentID, got: {result:?}"
        );
    }

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

        let schema = CompiledSchema::new();

        // Unknown scalar types should pass through (they're built-in types)
        let value = serde_json::json!("any value");
        let result = validate_custom_scalar_from_schema(&value, "UnknownType", &schema);
        result.unwrap_or_else(|e| panic!("expected Ok for unknown scalar passthrough: {e}"));
    }

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

        // Schema without PatientID definition
        let schema = CompiledSchema::new();

        let value = serde_json::json!("PAT-123456");
        let result = validate_custom_scalar_from_schema(&value, "PatientID", &schema);
        // Should pass through (not registered as custom scalar)
        result
            .unwrap_or_else(|e| panic!("expected Ok for unregistered PatientID passthrough: {e}"));
    }

    #[test]
    fn test_validate_custom_scalar_with_elo_expression() {
        use crate::{
            schema::CompiledSchema,
            validation::{CustomTypeDef, CustomTypeRegistry, CustomTypeRegistryConfig},
        };

        let schema = {
            let mut s = CompiledSchema::new();
            let registry = CustomTypeRegistry::new(CustomTypeRegistryConfig::default());

            let mut def = CustomTypeDef::new("StudentID".to_string());
            def.elo_expression = Some("matches(value, \"^STU-[0-9]{4}-[0-9]{3}$\")".to_string());

            registry.register("StudentID".to_string(), def).unwrap();

            s.custom_scalars = registry;
            s
        };

        // Valid: matches ELO expression
        let value = serde_json::json!("STU-2024-001");
        let result = validate_custom_scalar_from_schema(&value, "StudentID", &schema);
        result.unwrap_or_else(|e| panic!("expected Ok for StudentID matching ELO expression: {e}"));

        // Invalid: doesn't match ELO expression
        let value = serde_json::json!("INVALID");
        let result = validate_custom_scalar_from_schema(&value, "StudentID", &schema);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for StudentID not matching ELO expression, got: {result:?}"
        );
    }

    #[test]
    fn test_validate_custom_scalar_combined_rules_and_elo() {
        use crate::{
            schema::CompiledSchema,
            validation::{CustomTypeDef, CustomTypeRegistry, CustomTypeRegistryConfig},
        };

        let schema = {
            let mut s = CompiledSchema::new();
            let registry = CustomTypeRegistry::new(CustomTypeRegistryConfig::default());

            let mut def = CustomTypeDef::new("PatientID".to_string());
            def.validation_rules = vec![ValidationRule::Length {
                min: Some(10),
                max: Some(10),
            }];
            def.elo_expression = Some("matches(value, \"^PAT-[0-9]{6}$\")".to_string());

            registry.register("PatientID".to_string(), def).unwrap();

            s.custom_scalars = registry;
            s
        };

        // Valid: passes both length rule and ELO expression
        let value = serde_json::json!("PAT-123456");
        let result = validate_custom_scalar_from_schema(&value, "PatientID", &schema);
        result.unwrap_or_else(|e| panic!("expected Ok for valid PatientID: {e}"));

        // Invalid: passes length but fails ELO expression
        let value = serde_json::json!("NOTVALID!");
        let result = validate_custom_scalar_from_schema(&value, "PatientID", &schema);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for PatientID failing ELO expression, got: {result:?}"
        );

        // Invalid: fails length rule
        let value = serde_json::json!("PAT-12345");
        let result = validate_custom_scalar_from_schema(&value, "PatientID", &schema);
        assert!(
            matches!(result, Err(FraiseQLError::Validation { .. })),
            "expected Validation error for PatientID failing length rule, got: {result:?}"
        );
    }
}