audb 0.1.11

AuDB - Compile-time database application framework with gold files
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
//! AST validator for gold file blocks
//!
//! This validator works directly on the parsed AST (GoldFile and Block types)
//! to catch structural and semantic errors before converting to the Project model.

use crate::error::{Error, Result};
use crate::parser::ast::{Block, ConfigBlock, EndpointBlock, GoldFile, QueryBlock, SchemaBlock};
use std::collections::{HashMap, HashSet};

/// AST validator for gold files
///
/// Validates the parsed AST for structural correctness and basic semantic rules.
pub struct AstValidator {
    /// Whether to treat warnings as errors
    strict: bool,
}

impl AstValidator {
    /// Create a new AST validator
    pub fn new() -> Self {
        Self { strict: false }
    }

    /// Create a strict validator (warnings are errors)
    pub fn strict() -> Self {
        Self { strict: true }
    }

    /// Validate a complete gold file
    pub fn validate(&self, file: &GoldFile) -> Result<AstValidationReport> {
        let mut report = AstValidationReport::new();

        // Collect all schema and query names first
        let schema_names = self.collect_schema_names(file);
        let query_names = self.collect_query_names(file);

        // Validate each block
        for block in &file.blocks {
            self.validate_block(block, &schema_names, &query_names, &mut report);
        }

        // Check for duplicates
        self.check_duplicate_schemas(file, &mut report);
        self.check_duplicate_queries(file, &mut report);
        self.check_duplicate_endpoints(file, &mut report);

        // Convert warnings to errors in strict mode
        if self.strict && !report.warnings.is_empty() {
            for warning in &report.warnings {
                report.errors.push(warning.clone());
            }
            report.warnings.clear();
        }

        if !report.is_valid() {
            return Err(Error::Validation {
                message: format!("{} validation error(s) found", report.errors.len()),
                context: Some("AST validation".to_string()),
            });
        }

        Ok(report)
    }

    /// Validate a single block
    fn validate_block(
        &self,
        block: &Block,
        schema_names: &HashSet<&str>,
        query_names: &HashSet<&str>,
        report: &mut AstValidationReport,
    ) {
        match block {
            Block::Schema(schema) => self.validate_schema(schema, report),
            Block::Query(query) => self.validate_query(query, schema_names, report),
            Block::Config(config) => self.validate_config(config, report),
            Block::Endpoint(endpoint) => self.validate_endpoint(endpoint, query_names, report),
            Block::Data(_) => {}   // Data blocks validated later
            Block::Custom(_) => {} // Custom blocks are extensible
        }
    }

    /// Validate a schema block
    fn validate_schema(&self, schema: &SchemaBlock, report: &mut AstValidationReport) {
        if schema.name.is_empty() {
            report.add_error("Schema name cannot be empty");
        }

        if schema.fields.is_empty() && schema.content.is_none() {
            report.add_warning(&format!(
                "Schema '{}' has no fields or content",
                schema.name
            ));
        }

        // Validate field names are not empty
        for field in &schema.fields {
            if field.name.is_empty() {
                report.add_error(&format!("Field in schema '{}' has empty name", schema.name));
            }

            if field.field_type.is_empty() {
                report.add_error(&format!(
                    "Field '{}' in schema '{}' has empty type",
                    field.name, schema.name
                ));
            }
        }

        // Check for duplicate field names
        let mut field_names = HashSet::new();
        for field in &schema.fields {
            if !field_names.insert(&field.name) {
                report.add_error(&format!(
                    "Duplicate field '{}' in schema '{}'",
                    field.name, schema.name
                ));
            }
        }
    }

    /// Validate a query block
    fn validate_query(
        &self,
        query: &QueryBlock,
        schema_names: &HashSet<&str>,
        report: &mut AstValidationReport,
    ) {
        if query.name.is_empty() {
            report.add_error("Query name cannot be empty");
        }

        if query.source.is_empty() {
            report.add_error(&format!("Query '{}' has empty source", query.name));
        }

        if query.language.is_empty() {
            report.add_warning(&format!(
                "Query '{}' has no language specified (will default to 'hyperql')",
                query.name
            ));
        }

        // Validate parameter names are unique
        let mut param_names = HashSet::new();
        for param in &query.params {
            if param.name.is_empty() {
                report.add_error(&format!(
                    "Parameter in query '{}' has empty name",
                    query.name
                ));
            }

            if !param_names.insert(&param.name) {
                report.add_error(&format!(
                    "Duplicate parameter '{}' in query '{}'",
                    param.name, query.name
                ));
            }

            if param.param_type.is_empty() {
                report.add_error(&format!(
                    "Parameter '{}' in query '{}' has empty type",
                    param.name, query.name
                ));
            }
        }

        // Validate return type references existing schema (if not primitive)
        if !query.return_type.is_empty() {
            let base_type = extract_base_type(&query.return_type);
            if !is_primitive_type(base_type) && !schema_names.contains(base_type) {
                report.add_warning(&format!(
                    "Query '{}' return type '{}' may reference undefined schema",
                    query.name, base_type
                ));
            }
        }
    }

    /// Validate a config block
    fn validate_config(&self, config: &ConfigBlock, report: &mut AstValidationReport) {
        if config.name.is_empty() {
            report.add_error("Config block name cannot be empty");
        }

        if config.attributes.is_empty() {
            report.add_warning(&format!("Config '{}' has no attributes", config.name));
        }
    }

    /// Validate an endpoint block
    fn validate_endpoint(
        &self,
        endpoint: &EndpointBlock,
        query_names: &HashSet<&str>,
        report: &mut AstValidationReport,
    ) {
        if endpoint.method.is_empty() {
            report.add_error(&format!("Endpoint '{}' has empty method", endpoint.path));
        }

        if endpoint.path.is_empty() {
            report.add_error("Endpoint has empty path");
        }

        // Validate HTTP method
        let valid_methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
        if !valid_methods.contains(&endpoint.method.as_str()) {
            report.add_warning(&format!(
                "Endpoint '{}' has unusual HTTP method '{}'",
                endpoint.path, endpoint.method
            ));
        }

        // Validate query reference
        if !endpoint.query.is_empty() && !query_names.contains(endpoint.query.as_str()) {
            report.add_error(&format!(
                "Endpoint '{}' references undefined query '{}'",
                endpoint.path, endpoint.query
            ));
        }

        // Validate path starts with /
        if !endpoint.path.starts_with('/') {
            report.add_warning(&format!(
                "Endpoint path '{}' should start with '/'",
                endpoint.path
            ));
        }
    }

    /// Collect all schema names
    fn collect_schema_names<'a>(&self, file: &'a GoldFile) -> HashSet<&'a str> {
        file.blocks
            .iter()
            .filter_map(|block| {
                if let Block::Schema(schema) = block {
                    Some(schema.name.as_str())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Collect all query names
    fn collect_query_names<'a>(&self, file: &'a GoldFile) -> HashSet<&'a str> {
        file.blocks
            .iter()
            .filter_map(|block| {
                if let Block::Query(query) = block {
                    Some(query.name.as_str())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Check for duplicate schema names
    fn check_duplicate_schemas(&self, file: &GoldFile, report: &mut AstValidationReport) {
        let mut seen = HashMap::new();
        for block in &file.blocks {
            if let Block::Schema(schema) = block {
                if let Some(_) = seen.insert(&schema.name, ()) {
                    report.add_error(&format!("Duplicate schema name '{}'", schema.name));
                }
            }
        }
    }

    /// Check for duplicate query names
    fn check_duplicate_queries(&self, file: &GoldFile, report: &mut AstValidationReport) {
        let mut seen = HashMap::new();
        for block in &file.blocks {
            if let Block::Query(query) = block {
                if let Some(_) = seen.insert(&query.name, ()) {
                    report.add_error(&format!("Duplicate query name '{}'", query.name));
                }
            }
        }
    }

    /// Check for duplicate endpoints
    fn check_duplicate_endpoints(&self, file: &GoldFile, report: &mut AstValidationReport) {
        let mut seen = HashSet::new();
        for block in &file.blocks {
            if let Block::Endpoint(endpoint) = block {
                let key = format!("{} {}", endpoint.method, endpoint.path);
                if !seen.insert(key.clone()) {
                    report.add_error(&format!("Duplicate endpoint '{}'", key));
                }
            }
        }
    }
}

impl Default for AstValidator {
    fn default() -> Self {
        Self::new()
    }
}

/// Validation report for AST validation
#[derive(Debug, Clone)]
pub struct AstValidationReport {
    /// Validation errors
    pub errors: Vec<String>,
    /// Validation warnings
    pub warnings: Vec<String>,
}

impl AstValidationReport {
    /// Create a new empty report
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Check if validation passed (no errors)
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// Add an error
    pub fn add_error(&mut self, message: &str) {
        self.errors.push(message.to_string());
    }

    /// Add a warning
    pub fn add_warning(&mut self, message: &str) {
        self.warnings.push(message.to_string());
    }

    /// Get total number of issues
    pub fn total_issues(&self) -> usize {
        self.errors.len() + self.warnings.len()
    }
}

impl Default for AstValidationReport {
    fn default() -> Self {
        Self::new()
    }
}

/// Extract base type from type string (e.g., "Vec<User>" -> "User")
fn extract_base_type(type_str: &str) -> &str {
    if let Some(start) = type_str.find('<') {
        if let Some(end) = type_str.rfind('>') {
            return type_str[start + 1..end].trim();
        }
    }
    type_str
}

/// Check if a type is a primitive type
fn is_primitive_type(type_name: &str) -> bool {
    matches!(
        type_name,
        "String"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "f32"
            | "f64"
            | "bool"
            | "char"
            | "EntityId"
            | "Timestamp"
            | "Integer"
            | "Float"
            | "Boolean"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::ast::{EndpointBlock, Parameter, QueryBlock, SchemaField};
    use std::collections::HashMap;

    #[test]
    fn test_validator_creation() {
        let validator = AstValidator::new();
        assert!(!validator.strict);

        let strict = AstValidator::strict();
        assert!(strict.strict);
    }

    #[test]
    fn test_validation_report() {
        let mut report = AstValidationReport::new();
        assert!(report.is_valid());
        assert_eq!(report.total_issues(), 0);

        report.add_error("test error");
        assert!(!report.is_valid());
        assert_eq!(report.errors.len(), 1);

        report.add_warning("test warning");
        assert_eq!(report.warnings.len(), 1);
        assert_eq!(report.total_issues(), 2);
    }

    #[test]
    fn test_validate_empty_schema_name() {
        let validator = AstValidator::new();
        let mut file = GoldFile::new();
        file.add_block(Block::Schema(SchemaBlock {
            name: String::new(),
            format: None,
            fields: Vec::new(),
            content: None,
        }));

        let result = validator.validate(&file);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_duplicate_schemas() {
        let validator = AstValidator::new();
        let mut file = GoldFile::new();

        file.add_block(Block::Schema(SchemaBlock {
            name: "User".to_string(),
            format: None,
            fields: vec![SchemaField {
                name: "id".to_string(),
                field_type: "EntityId".to_string(),
                nullable: false,
                default: None,
                embedding_annotation: None,
            }],
            content: None,
        }));

        file.add_block(Block::Schema(SchemaBlock {
            name: "User".to_string(),
            format: None,
            fields: vec![SchemaField {
                name: "name".to_string(),
                field_type: "String".to_string(),
                nullable: false,
                default: None,
                embedding_annotation: None,
            }],
            content: None,
        }));

        let result = validator.validate(&file);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_duplicate_field_names() {
        let validator = AstValidator::new();
        let mut file = GoldFile::new();

        file.add_block(Block::Schema(SchemaBlock {
            name: "User".to_string(),
            format: None,
            fields: vec![
                SchemaField {
                    name: "id".to_string(),
                    field_type: "EntityId".to_string(),
                    nullable: false,
                    default: None,
                    embedding_annotation: None,
                },
                SchemaField {
                    name: "id".to_string(),
                    field_type: "String".to_string(),
                    nullable: false,
                    default: None,
                    embedding_annotation: None,
                },
            ],
            content: None,
        }));

        let result = validator.validate(&file);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_query_references_undefined_schema() {
        let validator = AstValidator::new();
        let mut file = GoldFile::new();

        file.add_block(Block::Query(QueryBlock {
            name: "get_user".to_string(),
            params: vec![Parameter {
                name: "id".to_string(),
                param_type: "EntityId".to_string(),
            }],
            return_type: "User".to_string(),
            language: "hyperql".to_string(),
            source: "SELECT * FROM users".to_string(),
        }));

        let result = validator.validate(&file);
        // Should succeed with warning
        assert!(result.is_ok());
        let report = result.unwrap();
        assert!(!report.warnings.is_empty());
    }

    #[test]
    fn test_validate_endpoint_references_undefined_query() {
        let validator = AstValidator::new();
        let mut file = GoldFile::new();

        file.add_block(Block::Endpoint(EndpointBlock {
            method: "GET".to_string(),
            path: "/api/users".to_string(),
            query: "get_users".to_string(),
            auth: false,
            params: HashMap::new(),
        }));

        let result = validator.validate(&file);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_valid_file() {
        let validator = AstValidator::new();
        let mut file = GoldFile::new();

        // Add schema
        file.add_block(Block::Schema(SchemaBlock {
            name: "User".to_string(),
            format: None,
            fields: vec![SchemaField {
                name: "id".to_string(),
                field_type: "EntityId".to_string(),
                nullable: false,
                default: None,
                embedding_annotation: None,
            }],
            content: None,
        }));

        // Add query
        file.add_block(Block::Query(QueryBlock {
            name: "get_user".to_string(),
            params: vec![Parameter {
                name: "id".to_string(),
                param_type: "EntityId".to_string(),
            }],
            return_type: "User".to_string(),
            language: "hyperql".to_string(),
            source: "SELECT * FROM users WHERE id = :id".to_string(),
        }));

        // Add endpoint
        file.add_block(Block::Endpoint(EndpointBlock {
            method: "GET".to_string(),
            path: "/api/users/:id".to_string(),
            query: "get_user".to_string(),
            auth: false,
            params: HashMap::new(),
        }));

        let result = validator.validate(&file);
        assert!(result.is_ok());
        let report = result.unwrap();
        assert!(report.is_valid());
    }

    #[test]
    fn test_extract_base_type() {
        assert_eq!(extract_base_type("User"), "User");
        assert_eq!(extract_base_type("Vec<User>"), "User");
        assert_eq!(extract_base_type("Option<String>"), "String");
    }

    #[test]
    fn test_is_primitive_type() {
        assert!(is_primitive_type("String"));
        assert!(is_primitive_type("i64"));
        assert!(is_primitive_type("EntityId"));
        assert!(!is_primitive_type("User"));
        assert!(!is_primitive_type("CustomType"));
    }
}