grounddb 1.0.0

A schema-driven data layer using Markdown files as source of truth
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
use crate::error::{GroundDbError, Result};
use crate::schema::{CollectionDefinition, FieldDefinition, FieldType, SchemaDefinition};

/// Result of validating a document
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

impl ValidationResult {
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }

    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }
}

/// Validate a document's data against its collection definition.
/// Returns ValidationResult with errors and warnings.
/// If strict mode is on, validation errors cause rejection.
/// If strict mode is off, validation issues are warnings only.
pub fn validate_document(
    schema: &SchemaDefinition,
    collection: &CollectionDefinition,
    data: &serde_yaml::Value,
) -> ValidationResult {
    let mut result = ValidationResult {
        errors: Vec::new(),
        warnings: Vec::new(),
    };

    let mapping = match data.as_mapping() {
        Some(m) => m,
        None => {
            result
                .errors
                .push("Document data must be a YAML mapping".into());
            return result;
        }
    };

    // Check required fields and validate each declared field
    for (field_name, field_def) in &collection.fields {
        let value = mapping.get(serde_yaml::Value::String(field_name.clone()));

        if field_def.required && (value.is_none() || value == Some(&serde_yaml::Value::Null)) {
            if field_def.default.is_none() {
                add_issue(
                    &mut result,
                    collection.strict,
                    format!("Required field '{field_name}' is missing"),
                );
            }
            continue;
        }

        if let Some(val) = value {
            if *val != serde_yaml::Value::Null {
                validate_field_value(schema, field_name, field_def, val, collection.strict, &mut result);
            }
        }
    }

    // Check for additional properties
    if !collection.additional_properties {
        for key in mapping.keys() {
            if let serde_yaml::Value::String(key_str) = key {
                if !collection.fields.contains_key(key_str) {
                    add_issue(
                        &mut result,
                        collection.strict,
                        format!("Unexpected field '{key_str}' (additional_properties is false)"),
                    );
                }
            }
        }
    }

    result
}

/// Apply default values to a document's data. Modifies the data in place.
/// Returns the data with defaults applied.
pub fn apply_defaults(
    collection: &CollectionDefinition,
    data: &mut serde_yaml::Value,
) {
    let mapping = match data.as_mapping_mut() {
        Some(m) => m,
        None => return,
    };

    for (field_name, field_def) in &collection.fields {
        let key = serde_yaml::Value::String(field_name.clone());
        let has_value = mapping
            .get(&key)
            .map(|v| *v != serde_yaml::Value::Null)
            .unwrap_or(false);

        if !has_value {
            if let Some(default) = &field_def.default {
                mapping.insert(key, default.clone());
            }
        }
    }
}

fn validate_field_value(
    schema: &SchemaDefinition,
    field_name: &str,
    field_def: &FieldDefinition,
    value: &serde_yaml::Value,
    strict: bool,
    result: &mut ValidationResult,
) {
    match &field_def.field_type {
        FieldType::String => {
            if !value.is_string() {
                add_issue(
                    result,
                    strict,
                    format!("Field '{field_name}' expected string, got {}", type_name(value)),
                );
                return;
            }

            // Check enum values
            if let Some(enum_values) = &field_def.enum_values {
                if let Some(s) = value.as_str() {
                    if !enum_values.contains(&s.to_string()) {
                        add_issue(
                            result,
                            strict,
                            format!(
                                "Field '{field_name}' value '{}' is not in enum: {:?}",
                                s, enum_values
                            ),
                        );
                    }
                }
            }
        }
        FieldType::Number => {
            if !value.is_number() {
                add_issue(
                    result,
                    strict,
                    format!("Field '{field_name}' expected number, got {}", type_name(value)),
                );
            }
        }
        FieldType::Boolean => {
            if !value.is_bool() {
                add_issue(
                    result,
                    strict,
                    format!("Field '{field_name}' expected boolean, got {}", type_name(value)),
                );
            }
        }
        FieldType::Date | FieldType::Datetime => {
            // Dates are stored as strings in YAML
            if !value.is_string() {
                add_issue(
                    result,
                    strict,
                    format!("Field '{field_name}' expected date string, got {}", type_name(value)),
                );
            }
        }
        FieldType::List => {
            if !value.is_sequence() {
                add_issue(
                    result,
                    strict,
                    format!("Field '{field_name}' expected list, got {}", type_name(value)),
                );
            }
            // Could validate items here but keeping it simple for v1
        }
        FieldType::Object => {
            if !value.is_mapping() {
                add_issue(
                    result,
                    strict,
                    format!("Field '{field_name}' expected object, got {}", type_name(value)),
                );
            }
        }
        FieldType::Ref => {
            // Refs can be strings (single target) or mappings (polymorphic)
            match &field_def.target {
                Some(crate::schema::RefTarget::Single(_)) => {
                    if !value.is_string() {
                        add_issue(
                            result,
                            strict,
                            format!(
                                "Field '{field_name}' (ref) expected string ID, got {}",
                                type_name(value)
                            ),
                        );
                    }
                }
                Some(crate::schema::RefTarget::Multiple(_)) => {
                    // Polymorphic ref: either a string or a mapping with type+id
                    if !value.is_string() && !value.is_mapping() {
                        add_issue(
                            result,
                            strict,
                            format!(
                                "Field '{field_name}' (polymorphic ref) expected string or {{type, id}} mapping, got {}",
                                type_name(value)
                            ),
                        );
                    }
                }
                None => {
                    // Already caught by schema validation, but be defensive
                }
            }
        }
        FieldType::Custom(type_name_str) => {
            // Validate against reusable type definition
            if let Some(type_fields) = schema.get_custom_type(type_name_str) {
                if let Some(obj) = value.as_mapping() {
                    for (sub_field_name, sub_field_def) in type_fields {
                        let sub_val =
                            obj.get(serde_yaml::Value::String(sub_field_name.clone()));

                        if sub_field_def.required
                            && (sub_val.is_none()
                                || sub_val == Some(&serde_yaml::Value::Null))
                        {
                            add_issue(
                                result,
                                strict,
                                format!(
                                    "Field '{field_name}.{sub_field_name}' is required in type '{type_name_str}'"
                                ),
                            );
                        }
                    }
                } else {
                    add_issue(
                        result,
                        strict,
                        format!(
                            "Field '{field_name}' expected object (type '{type_name_str}'), got {}",
                            type_name(value)
                        ),
                    );
                }
            }
        }
    }
}

fn add_issue(result: &mut ValidationResult, strict: bool, message: String) {
    if strict {
        result.errors.push(message);
    } else {
        result.warnings.push(message);
    }
}

fn type_name(value: &serde_yaml::Value) -> &'static str {
    match value {
        serde_yaml::Value::Null => "null",
        serde_yaml::Value::Bool(_) => "boolean",
        serde_yaml::Value::Number(_) => "number",
        serde_yaml::Value::String(_) => "string",
        serde_yaml::Value::Sequence(_) => "list",
        serde_yaml::Value::Mapping(_) => "object",
        serde_yaml::Value::Tagged(_) => "tagged",
    }
}

/// Validate and apply defaults. Returns an error if strict validation fails.
pub fn validate_and_prepare(
    schema: &SchemaDefinition,
    collection: &CollectionDefinition,
    data: &mut serde_yaml::Value,
) -> Result<Vec<String>> {
    apply_defaults(collection, data);
    let result = validate_document(schema, collection, data);

    if !result.is_ok() {
        return Err(GroundDbError::Validation(format!(
            "Document validation failed:\n  - {}",
            result.errors.join("\n  - ")
        )));
    }

    Ok(result.warnings)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::parse_schema_str;

    fn test_schema() -> SchemaDefinition {
        parse_schema_str(
            r#"
types:
  address:
    street: { type: string, required: true }
    city: { type: string, required: true }
    state: { type: string }
    zip: { type: string }

collections:
  users:
    path: "users/{name}.md"
    fields:
      name: { type: string, required: true }
      email: { type: string, required: true }
      role: { type: string, enum: [admin, member, guest], default: member }
      address: { type: address }
    additional_properties: false
    strict: true

  posts:
    path: "posts/{status}/{date:YYYY-MM-DD}-{title}.md"
    fields:
      title: { type: string, required: true }
      author_id: { type: ref, target: users, required: true }
      date: { type: date, required: true }
      tags: { type: list, items: string }
      status: { type: string, enum: [draft, published, archived], default: draft }
    content: true
    additional_properties: false
    strict: true

  events:
    path: "events/{id}.md"
    id: { auto: ulid }
    fields:
      type: { type: string, required: true }
      payload: { type: object }
    additional_properties: true
    strict: false
"#,
        )
        .unwrap()
    }

    #[test]
    fn test_valid_user() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com\nrole: admin",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(result.is_ok(), "Errors: {:?}", result.errors);
    }

    #[test]
    fn test_missing_required_field() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value =
            serde_yaml::from_str("name: Alice").unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(!result.is_ok());
        assert!(result.errors.iter().any(|e| e.contains("email")));
    }

    #[test]
    fn test_invalid_enum_value() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com\nrole: superadmin",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(!result.is_ok());
        assert!(result.errors.iter().any(|e| e.contains("superadmin")));
    }

    #[test]
    fn test_type_mismatch() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "name: 42\nemail: alice@test.com",
        )
        .unwrap();

        // name: 42 -- YAML parses this as number, not string
        let result = validate_document(&schema, collection, &data);
        assert!(!result.is_ok());
        assert!(result.errors.iter().any(|e| e.contains("name")));
    }

    #[test]
    fn test_additional_properties_rejected() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com\nextra_field: oops",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(!result.is_ok());
        assert!(result.errors.iter().any(|e| e.contains("extra_field")));
    }

    #[test]
    fn test_additional_properties_allowed() {
        let schema = test_schema();
        let collection = &schema.collections["events"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "type: click\nextra: data",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        // events has additional_properties: true and strict: false
        assert!(result.is_ok());
    }

    #[test]
    fn test_non_strict_mode_warnings() {
        let schema = test_schema();
        let collection = &schema.collections["events"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "type: 123", // wrong type for string field, but strict: false
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(result.is_ok()); // no errors
        assert!(result.has_warnings()); // but has warnings
    }

    #[test]
    fn test_apply_defaults() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let mut data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com",
        )
        .unwrap();

        apply_defaults(collection, &mut data);
        assert_eq!(
            data["role"],
            serde_yaml::Value::String("member".into())
        );
    }

    #[test]
    fn test_apply_defaults_doesnt_overwrite() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let mut data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com\nrole: admin",
        )
        .unwrap();

        apply_defaults(collection, &mut data);
        assert_eq!(
            data["role"],
            serde_yaml::Value::String("admin".into())
        );
    }

    #[test]
    fn test_validate_and_prepare() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let mut data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com",
        )
        .unwrap();

        let warnings = validate_and_prepare(&schema, collection, &mut data).unwrap();
        assert!(warnings.is_empty());
        // Default should be applied
        assert_eq!(
            data["role"],
            serde_yaml::Value::String("member".into())
        );
    }

    #[test]
    fn test_custom_type_validation() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com\naddress:\n  city: NYC",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        // address.street is required but missing
        assert!(!result.is_ok());
        assert!(result.errors.iter().any(|e| e.contains("street")));
    }

    #[test]
    fn test_valid_custom_type() {
        let schema = test_schema();
        let collection = &schema.collections["users"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "name: Alice\nemail: alice@test.com\naddress:\n  street: '123 Main St'\n  city: NYC",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(result.is_ok(), "Errors: {:?}", result.errors);
    }

    #[test]
    fn test_list_type_validation() {
        let schema = test_schema();
        let collection = &schema.collections["posts"];
        let data: serde_yaml::Value = serde_yaml::from_str(
            "title: Test\nauthor_id: alice\ndate: '2026-01-01'\ntags: not-a-list",
        )
        .unwrap();

        let result = validate_document(&schema, collection, &data);
        assert!(!result.is_ok());
        assert!(result.errors.iter().any(|e| e.contains("tags")));
    }
}