fraiseql-cli 2.3.2

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
//! `SchemaValidator` — validates an `IntermediateSchema` with detailed error reporting.

use std::collections::HashSet;

use anyhow::Result;
use tracing::{debug, info};

use super::{
    sql_identifier::validate_sql_identifier,
    types::{ErrorSeverity, ValidationError, ValidationReport},
};
use crate::schema::intermediate::IntermediateSchema;

/// Strip GraphQL type modifiers (`!`, `[]`) to extract the base type name.
///
/// Examples: `"UUID!"` → `"UUID"`, `"[User!]!"` → `"User"`, `"String"` → `"String"`
pub(crate) fn extract_base_type(type_str: &str) -> &str {
    let s = type_str.trim();
    let s = s.trim_start_matches('[').trim_end_matches(']');
    let s = s.trim_end_matches('!').trim_start_matches('!');
    let s = s.trim_start_matches('[').trim_end_matches(']');
    let s = s.trim_end_matches('!');
    s.trim()
}

/// Enhanced schema validator
pub struct SchemaValidator;

impl SchemaValidator {
    /// Validate an intermediate schema with detailed error reporting
    ///
    /// # Errors
    ///
    /// Currently infallible; always returns `Ok` containing the report.
    /// The `Result` return type is reserved for future validation that may
    /// require fallible I/O.
    #[allow(clippy::cognitive_complexity)] // Reason: comprehensive schema validation with many cross-field constraint checks
    pub fn validate(schema: &IntermediateSchema) -> Result<ValidationReport> {
        info!("Validating schema structure");

        let mut report = ValidationReport::default();

        // Build type registry
        let mut type_names = HashSet::new();
        for type_def in &schema.types {
            if type_names.contains(&type_def.name) {
                report.errors.push(ValidationError {
                    message:    format!("Duplicate type name: '{}'", type_def.name),
                    path:       format!("types[{}].name", type_names.len()),
                    severity:   ErrorSeverity::Error,
                    suggestion: Some("Type names must be unique".to_string()),
                });
            }
            type_names.insert(type_def.name.clone());
        }

        // Add input types — valid as mutation argument types (fraiseql/fraiseql#190)
        for input_type in &schema.input_types {
            type_names.insert(input_type.name.clone());
        }

        // Add union type names — valid as mutation/query return types
        for union_def in &schema.unions {
            type_names.insert(union_def.name.clone());
        }

        // Add built-in scalars
        for scalar in crate::schema::BUILTIN_SCALAR_NAMES {
            type_names.insert((*scalar).to_string());
        }

        // Collect custom scalars implicitly: any type name used in object field definitions
        // that isn't already registered (e.g. IPAddress, Hostname, MACAddress, CIDR).
        for type_def in &schema.types {
            for field in &type_def.fields {
                let base = extract_base_type(&field.field_type);
                type_names.insert(base.to_string());
            }
        }

        // Validate queries
        let mut query_names = HashSet::new();
        for (idx, query) in schema.queries.iter().enumerate() {
            debug!("Validating query: {}", query.name);

            // Check for duplicate query names
            if query_names.contains(&query.name) {
                report.errors.push(ValidationError {
                    message:    format!("Duplicate query name: '{}'", query.name),
                    path:       format!("queries[{idx}].name"),
                    severity:   ErrorSeverity::Error,
                    suggestion: Some("Query names must be unique".to_string()),
                });
            }
            query_names.insert(query.name.clone());

            // Validate return type exists (strip ! and [] modifiers)
            let base_return = extract_base_type(&query.return_type);
            if !type_names.contains(base_return) {
                report.errors.push(ValidationError {
                    message:    format!(
                        "Query '{}' references unknown type '{}'",
                        query.name, base_return
                    ),
                    path:       format!("queries[{idx}].return_type"),
                    severity:   ErrorSeverity::Error,
                    suggestion: Some(format!(
                        "Available types: {}",
                        Self::suggest_similar_type(base_return, &type_names)
                    )),
                });
            }

            // Validate argument types
            for (arg_idx, arg) in query.arguments.iter().enumerate() {
                let base_arg = extract_base_type(&arg.arg_type);
                if !type_names.contains(base_arg) {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Query '{}' argument '{}' references unknown type '{}'",
                            query.name, arg.name, base_arg
                        ),
                        path:       format!("queries[{idx}].arguments[{arg_idx}].type"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some(format!(
                            "Available types: {}",
                            Self::suggest_similar_type(base_arg, &type_names)
                        )),
                    });
                }
            }

            // Validate sql_source is a safe SQL identifier
            if let Some(sql_source) = &query.sql_source {
                if let Err(e) = validate_sql_identifier(
                    sql_source,
                    "sql_source",
                    &format!("Query.{}", query.name),
                ) {
                    report.errors.push(e);
                }
            }

            // Warning for queries without SQL source
            if query.sql_source.is_none() && query.returns_list {
                report.errors.push(ValidationError {
                    message:    format!(
                        "Query '{}' returns a list but has no sql_source",
                        query.name
                    ),
                    path:       format!("queries[{idx}]"),
                    severity:   ErrorSeverity::Warning,
                    suggestion: Some("Add sql_source for SQL-backed queries".to_string()),
                });
            }
        }

        // Validate mutations
        let mut mutation_names = HashSet::new();
        for (idx, mutation) in schema.mutations.iter().enumerate() {
            debug!("Validating mutation: {}", mutation.name);

            // Check for duplicate mutation names
            if mutation_names.contains(&mutation.name) {
                report.errors.push(ValidationError {
                    message:    format!("Duplicate mutation name: '{}'", mutation.name),
                    path:       format!("mutations[{idx}].name"),
                    severity:   ErrorSeverity::Error,
                    suggestion: Some("Mutation names must be unique".to_string()),
                });
            }
            mutation_names.insert(mutation.name.clone());

            // Validate return type exists (strip ! and [] modifiers)
            let base_return = extract_base_type(&mutation.return_type);
            if !type_names.contains(base_return) {
                report.errors.push(ValidationError {
                    message:    format!(
                        "Mutation '{}' references unknown type '{}'",
                        mutation.name, base_return
                    ),
                    path:       format!("mutations[{idx}].return_type"),
                    severity:   ErrorSeverity::Error,
                    suggestion: Some(format!(
                        "Available types: {}",
                        Self::suggest_similar_type(base_return, &type_names)
                    )),
                });
            }

            // Validate argument types
            for (arg_idx, arg) in mutation.arguments.iter().enumerate() {
                let base_arg = extract_base_type(&arg.arg_type);
                if !type_names.contains(base_arg) {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Mutation '{}' argument '{}' references unknown type '{}'",
                            mutation.name, arg.name, base_arg
                        ),
                        path:       format!("mutations[{idx}].arguments[{arg_idx}].type"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some(format!(
                            "Available types: {}",
                            Self::suggest_similar_type(base_arg, &type_names)
                        )),
                    });
                }
            }

            // Validate sql_source is a safe SQL identifier
            if let Some(sql_source) = &mutation.sql_source {
                if let Err(e) = validate_sql_identifier(
                    sql_source,
                    "sql_source",
                    &format!("Mutation.{}", mutation.name),
                ) {
                    report.errors.push(e);
                }
            }

            // Warn about inject_params ordering contract
            if !mutation.inject.is_empty() {
                let inject_names: Vec<&str> = mutation.inject.keys().map(String::as_str).collect();
                let fn_name = mutation.sql_source.as_deref().unwrap_or("<unknown>");
                report.errors.push(ValidationError {
                    message:    format!(
                        "Mutation '{}' has inject params {:?}. \
                         These are appended as the LAST positional arguments to \
                         `{fn_name}`. Your SQL function MUST declare injected \
                         parameters last, after all client-provided arguments.",
                        mutation.name, inject_names,
                    ),
                    path:       format!("Mutation.{}", mutation.name),
                    severity:   ErrorSeverity::Warning,
                    suggestion: None,
                });
            }
        }

        // Validate observers
        if let Some(observers) = &schema.observers {
            let mut observer_names = HashSet::new();
            for (idx, observer) in observers.iter().enumerate() {
                debug!("Validating observer: {}", observer.name);

                // Check for duplicate observer names
                if observer_names.contains(&observer.name) {
                    report.errors.push(ValidationError {
                        message:    format!("Duplicate observer name: '{}'", observer.name),
                        path:       format!("observers[{idx}].name"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some("Observer names must be unique".to_string()),
                    });
                }
                observer_names.insert(observer.name.clone());

                // Validate entity type exists
                if !type_names.contains(&observer.entity) {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' references unknown entity '{}'",
                            observer.name, observer.entity
                        ),
                        path:       format!("observers[{idx}].entity"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some(format!(
                            "Available types: {}",
                            Self::suggest_similar_type(&observer.entity, &type_names)
                        )),
                    });
                }

                // Validate event type
                let valid_events = ["INSERT", "UPDATE", "DELETE"];
                if !valid_events.contains(&observer.event.as_str()) {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' has invalid event '{}'. Must be INSERT, UPDATE, or DELETE",
                            observer.name, observer.event
                        ),
                        path:       format!("observers[{idx}].event"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some("Valid events: INSERT, UPDATE, DELETE".to_string()),
                    });
                }

                // Validate at least one action exists
                if observer.actions.is_empty() {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' must have at least one action",
                            observer.name
                        ),
                        path:       format!("observers[{idx}].actions"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some("Add a webhook, slack, or email action".to_string()),
                    });
                }

                // Validate each action
                for (action_idx, action) in observer.actions.iter().enumerate() {
                    if let Some(obj) = action.as_object() {
                        // Check action has a type field
                        if let Some(action_type) = obj.get("type").and_then(|v| v.as_str()) {
                            let valid_action_types = ["webhook", "slack", "email"];
                            if !valid_action_types.contains(&action_type) {
                                report.errors.push(ValidationError {
                                    message:    format!(
                                        "Observer '{}' action {} has invalid type '{}'",
                                        observer.name, action_idx, action_type
                                    ),
                                    path:       format!(
                                        "observers[{idx}].actions[{action_idx}].type"
                                    ),
                                    severity:   ErrorSeverity::Error,
                                    suggestion: Some(
                                        "Valid action types: webhook, slack, email".to_string(),
                                    ),
                                });
                            }

                            // Validate action-specific required fields
                            match action_type {
                                "webhook" => {
                                    let has_url = obj.contains_key("url");
                                    let has_url_env = obj.contains_key("url_env");
                                    if !has_url && !has_url_env {
                                        report.errors.push(ValidationError {
                                            message:    format!(
                                                "Observer '{}' webhook action must have 'url' or 'url_env'",
                                                observer.name
                                            ),
                                            path:       format!("observers[{idx}].actions[{action_idx}]"),
                                            severity:   ErrorSeverity::Error,
                                            suggestion: Some("Add 'url' or 'url_env' field".to_string()),
                                        });
                                    }
                                },
                                "slack" => {
                                    if !obj.contains_key("channel") {
                                        report.errors.push(ValidationError {
                                            message:    format!(
                                                "Observer '{}' slack action must have 'channel' field",
                                                observer.name
                                            ),
                                            path:       format!("observers[{idx}].actions[{action_idx}]"),
                                            severity:   ErrorSeverity::Error,
                                            suggestion: Some("Add 'channel' field (e.g., '#sales')".to_string()),
                                        });
                                    }
                                    if !obj.contains_key("message") {
                                        report.errors.push(ValidationError {
                                            message:    format!(
                                                "Observer '{}' slack action must have 'message' field",
                                                observer.name
                                            ),
                                            path:       format!("observers[{idx}].actions[{action_idx}]"),
                                            severity:   ErrorSeverity::Error,
                                            suggestion: Some("Add 'message' field".to_string()),
                                        });
                                    }
                                },
                                "email" => {
                                    let required_fields = ["to", "subject", "body"];
                                    for field in &required_fields {
                                        if !obj.contains_key(*field) {
                                            report.errors.push(ValidationError {
                                                message:    format!(
                                                    "Observer '{}' email action must have '{}' field",
                                                    observer.name, field
                                                ),
                                                path:       format!("observers[{idx}].actions[{action_idx}]"),
                                                severity:   ErrorSeverity::Error,
                                                suggestion: Some(format!("Add '{field}' field")),
                                            });
                                        }
                                    }
                                },
                                _ => {},
                            }
                        } else {
                            report.errors.push(ValidationError {
                                message:    format!(
                                    "Observer '{}' action {} missing 'type' field",
                                    observer.name, action_idx
                                ),
                                path:       format!("observers[{idx}].actions[{action_idx}]"),
                                severity:   ErrorSeverity::Error,
                                suggestion: Some(
                                    "Add 'type' field (webhook, slack, or email)".to_string(),
                                ),
                            });
                        }
                    } else {
                        report.errors.push(ValidationError {
                            message:    format!(
                                "Observer '{}' action {} must be an object",
                                observer.name, action_idx
                            ),
                            path:       format!("observers[{idx}].actions[{action_idx}]"),
                            severity:   ErrorSeverity::Error,
                            suggestion: None,
                        });
                    }
                }

                // Validate retry config
                let valid_backoff_strategies = ["exponential", "linear", "fixed"];
                if !valid_backoff_strategies.contains(&observer.retry.backoff_strategy.as_str()) {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' has invalid backoff_strategy '{}'",
                            observer.name, observer.retry.backoff_strategy
                        ),
                        path:       format!("observers[{idx}].retry.backoff_strategy"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some(
                            "Valid strategies: exponential, linear, fixed".to_string(),
                        ),
                    });
                }

                if observer.retry.max_attempts == 0 {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' has max_attempts=0, actions will never execute",
                            observer.name
                        ),
                        path:       format!("observers[{idx}].retry.max_attempts"),
                        severity:   ErrorSeverity::Warning,
                        suggestion: Some("Set max_attempts >= 1".to_string()),
                    });
                }

                if observer.retry.initial_delay_ms == 0 {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' has initial_delay_ms=0, retries will be immediate",
                            observer.name
                        ),
                        path:       format!("observers[{idx}].retry.initial_delay_ms"),
                        severity:   ErrorSeverity::Warning,
                        suggestion: Some("Consider setting initial_delay_ms > 0".to_string()),
                    });
                }

                if observer.retry.max_delay_ms < observer.retry.initial_delay_ms {
                    report.errors.push(ValidationError {
                        message:    format!(
                            "Observer '{}' has max_delay_ms < initial_delay_ms",
                            observer.name
                        ),
                        path:       format!("observers[{idx}].retry.max_delay_ms"),
                        severity:   ErrorSeverity::Error,
                        suggestion: Some("max_delay_ms must be >= initial_delay_ms".to_string()),
                    });
                }
            }
        }

        info!(
            "Validation complete: {} errors, {} warnings",
            report.error_count(),
            report.warning_count()
        );

        Ok(report)
    }

    /// Suggest similar type names for typos.
    ///
    /// # Panics
    ///
    /// Panics if `typo` is empty (cannot slice first character).
    fn suggest_similar_type(typo: &str, available: &HashSet<String>) -> String {
        // Simple Levenshtein-style similarity (first letter match)
        let similar: Vec<&String> = available
            .iter()
            .filter(|name| {
                name.to_lowercase().starts_with(&typo[0..1].to_lowercase())
                    || typo.to_lowercase().starts_with(&name[0..1].to_lowercase())
            })
            .take(3)
            .collect();

        if similar.is_empty() {
            available.iter().take(5).cloned().collect::<Vec<_>>().join(", ")
        } else {
            similar.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
        }
    }
}