1use std::collections::{HashMap, HashSet};
4
5use crate::database::DatabaseConfig;
6use crate::errors::ValidationError;
7use crate::model::{Row, Value};
8use crate::parser::ParsedFile;
9use crate::schema::Schema;
10use crate::stamp::TIMESTAMP_FIELDS;
11
12pub fn validate_file(parsed: &ParsedFile, schema: &Schema) -> Vec<ValidationError> {
13 let mut errors = Vec::new();
14 let fp = &parsed.path;
15
16 for msg in &parsed.parse_errors {
18 errors.push(ValidationError {
19 file_path: fp.clone(),
20 error_type: "parse_error".to_string(),
21 field: None,
22 message: msg.clone(),
23 line_number: None,
24 });
25 }
26
27 if errors.iter().any(|e| e.error_type == "parse_error") {
28 return errors;
29 }
30
31 let fm = &parsed.raw_frontmatter;
32 let fm_map = match fm.as_mapping() {
33 Some(m) => m,
34 None => return errors,
35 };
36
37 for (name, field_def) in &schema.frontmatter {
39 let key = serde_yaml::Value::String(name.clone());
40 match fm_map.get(&key) {
41 None => {
42 if field_def.required {
43 errors.push(ValidationError {
44 file_path: fp.clone(),
45 error_type: "missing_field".to_string(),
46 field: Some(name.clone()),
47 message: format!("Missing required frontmatter field '{}'", name),
48 line_number: None,
49 });
50 }
51 }
52 Some(value) => {
53 if let Some(type_err) = check_type(value, &field_def.field_type, name) {
54 errors.push(ValidationError {
55 file_path: fp.clone(),
56 error_type: "type_mismatch".to_string(),
57 field: Some(name.clone()),
58 message: type_err,
59 line_number: None,
60 });
61 }
62
63 if let Some(ref enum_vals) = field_def.enum_values {
64 if !value.is_null() {
65 let str_val = yaml_value_to_string(value);
66 if !enum_vals.contains(&str_val) {
67 errors.push(ValidationError {
68 file_path: fp.clone(),
69 error_type: "enum_violation".to_string(),
70 field: Some(name.clone()),
71 message: format!(
72 "Field '{}' value '{}' not in allowed values: {:?}",
73 name, str_val, enum_vals
74 ),
75 line_number: None,
76 });
77 }
78 }
79 }
80 }
81 }
82 }
83
84 for ts_field in TIMESTAMP_FIELDS {
86 let key = serde_yaml::Value::String(ts_field.to_string());
87 if let Some(value) = fm_map.get(&key) {
88 if let Some(type_err) = check_type(
89 value,
90 &crate::schema::FieldType::Date,
91 ts_field,
92 ) {
93 errors.push(ValidationError {
94 file_path: fp.clone(),
95 error_type: "type_mismatch".to_string(),
96 field: Some(ts_field.to_string()),
97 message: type_err,
98 line_number: None,
99 });
100 }
101 }
102 }
103
104 if schema.rules.reject_unknown_frontmatter {
106 for (key_val, _) in fm_map {
107 if let Some(key) = key_val.as_str() {
108 if !schema.frontmatter.contains_key(key)
109 && !TIMESTAMP_FIELDS.contains(&key)
110 {
111 errors.push(ValidationError {
112 file_path: fp.clone(),
113 error_type: "unknown_field".to_string(),
114 field: Some(key.to_string()),
115 message: format!(
116 "Unknown frontmatter field '{}' (not in schema)",
117 key
118 ),
119 line_number: None,
120 });
121 }
122 }
123 }
124 }
125
126 if schema.h1_required && parsed.h1.is_none() {
128 errors.push(ValidationError {
129 file_path: fp.clone(),
130 error_type: "missing_h1".to_string(),
131 field: None,
132 message: "Missing required H1 heading".to_string(),
133 line_number: None,
134 });
135 }
136
137 if let Some(ref h1_field) = schema.h1_must_equal_frontmatter {
138 if let Some(ref h1) = parsed.h1 {
139 let key = serde_yaml::Value::String(h1_field.clone());
140 if let Some(expected_val) = fm_map.get(&key) {
141 let expected = yaml_value_to_string(expected_val);
142 if h1 != &expected {
143 errors.push(ValidationError {
144 file_path: fp.clone(),
145 error_type: "h1_mismatch".to_string(),
146 field: None,
147 message: format!(
148 "H1 '{}' does not match frontmatter '{}' (expected '{}')",
149 h1, h1_field, expected
150 ),
151 line_number: parsed.h1_line_number,
152 });
153 }
154 }
155 }
156 }
157
158 let section_names: Vec<&str> = parsed
160 .sections
161 .iter()
162 .map(|s| s.normalized_heading.as_str())
163 .collect();
164
165 let mut section_counter: HashMap<&str, usize> = HashMap::new();
167 for name in §ion_names {
168 *section_counter.entry(name).or_insert(0) += 1;
169 }
170
171 if schema.rules.reject_duplicate_sections {
173 for (name, count) in §ion_counter {
174 if *count > 1 {
175 errors.push(ValidationError {
176 file_path: fp.clone(),
177 error_type: "duplicate_section".to_string(),
178 field: Some(name.to_string()),
179 message: format!(
180 "Duplicate section '{}' (appears {} times)",
181 name, count
182 ),
183 line_number: None,
184 });
185 }
186 }
187 }
188
189 for (name, section_def) in &schema.sections {
191 if section_def.required && !section_names.contains(&name.as_str()) {
192 errors.push(ValidationError {
193 file_path: fp.clone(),
194 error_type: "missing_section".to_string(),
195 field: Some(name.clone()),
196 message: format!("Missing required section '{}'", name),
197 line_number: None,
198 });
199 }
200 }
201
202 if schema.rules.reject_unknown_sections {
204 for section in &parsed.sections {
205 if !schema.sections.contains_key(§ion.normalized_heading) {
206 errors.push(ValidationError {
207 file_path: fp.clone(),
208 error_type: "unknown_section".to_string(),
209 field: Some(section.normalized_heading.clone()),
210 message: format!(
211 "Unknown section '{}' (not in schema)",
212 section.normalized_heading
213 ),
214 line_number: Some(section.line_number),
215 });
216 }
217 }
218 }
219
220 errors
221}
222
223fn check_type(
224 value: &serde_yaml::Value,
225 expected: &crate::schema::FieldType,
226 field_name: &str,
227) -> Option<String> {
228 use crate::schema::FieldType;
229
230 if value.is_null() {
231 return None;
232 }
233
234 match expected {
235 FieldType::String => {
236 if !value.is_string() {
237 return Some(format!(
238 "Field '{}' expected string, got {}",
239 field_name,
240 yaml_type_name(value)
241 ));
242 }
243 }
244 FieldType::Int => {
245 if value.is_bool() {
246 return Some(format!(
247 "Field '{}' expected int, got bool",
248 field_name
249 ));
250 }
251 if !value.is_i64() && !value.is_u64() {
253 return Some(format!(
254 "Field '{}' expected int, got {}",
255 field_name,
256 yaml_type_name(value)
257 ));
258 }
259 }
260 FieldType::Float => {
261 if value.is_bool() {
262 return Some(format!(
263 "Field '{}' expected float, got bool",
264 field_name
265 ));
266 }
267 if !value.is_f64() && !value.is_i64() && !value.is_u64() {
268 return Some(format!(
269 "Field '{}' expected float, got {}",
270 field_name,
271 yaml_type_name(value)
272 ));
273 }
274 }
275 FieldType::Bool => {
276 if !value.is_bool() {
277 return Some(format!(
278 "Field '{}' expected bool, got {}",
279 field_name,
280 yaml_type_name(value)
281 ));
282 }
283 }
284 FieldType::Date => {
285 if let Some(s) = value.as_str() {
287 if chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").is_err() {
288 return Some(format!(
289 "Field '{}' expected date, got string '{}' (not ISO format)",
290 field_name, s
291 ));
292 }
293 return None;
294 }
295 if !value.is_string() {
298 return Some(format!(
299 "Field '{}' expected date, got {}",
300 field_name,
301 yaml_type_name(value)
302 ));
303 }
304 }
305 FieldType::StringArray => {
306 match value.as_sequence() {
307 None => {
308 return Some(format!(
309 "Field '{}' expected string[], got {}",
310 field_name,
311 yaml_type_name(value)
312 ));
313 }
314 Some(seq) => {
315 for (i, item) in seq.iter().enumerate() {
316 if !item.is_string() {
317 return Some(format!(
318 "Field '{}[{}]' expected string, got {}",
319 field_name,
320 i,
321 yaml_type_name(item)
322 ));
323 }
324 }
325 }
326 }
327 }
328 }
329
330 None
331}
332
333fn yaml_type_name(value: &serde_yaml::Value) -> &'static str {
334 match value {
335 serde_yaml::Value::Null => "null",
336 serde_yaml::Value::Bool(_) => "bool",
337 serde_yaml::Value::Number(_) => {
338 if value.is_f64() && !value.is_i64() && !value.is_u64() {
339 "float"
340 } else {
341 "int"
342 }
343 }
344 serde_yaml::Value::String(_) => "str",
345 serde_yaml::Value::Sequence(_) => "list",
346 serde_yaml::Value::Mapping(_) => "mapping",
347 _ => "unknown",
348 }
349}
350
351fn yaml_value_to_string(value: &serde_yaml::Value) -> String {
352 match value {
353 serde_yaml::Value::String(s) => s.clone(),
354 serde_yaml::Value::Number(n) => n.to_string(),
355 serde_yaml::Value::Bool(b) => b.to_string(),
356 serde_yaml::Value::Null => "null".to_string(),
357 _ => format!("{:?}", value),
358 }
359}
360
361pub fn validate_foreign_keys(
363 db_config: &DatabaseConfig,
364 tables: &HashMap<String, (Schema, Vec<Row>)>,
365) -> Vec<ValidationError> {
366 let mut errors = Vec::new();
367
368 for fk in &db_config.foreign_keys {
369 let to_table = match tables.get(&fk.to_table) {
370 Some(t) => t,
371 None => {
372 errors.push(ValidationError {
373 file_path: format!("_mdql.md"),
374 error_type: "fk_missing_table".to_string(),
375 field: None,
376 message: format!(
377 "Foreign key references unknown table '{}'",
378 fk.to_table
379 ),
380 line_number: None,
381 });
382 continue;
383 }
384 };
385
386 let from_table = match tables.get(&fk.from_table) {
387 Some(t) => t,
388 None => {
389 errors.push(ValidationError {
390 file_path: format!("_mdql.md"),
391 error_type: "fk_missing_table".to_string(),
392 field: None,
393 message: format!(
394 "Foreign key references unknown table '{}'",
395 fk.from_table
396 ),
397 line_number: None,
398 });
399 continue;
400 }
401 };
402
403 let valid_values: HashSet<String> = to_table
405 .1
406 .iter()
407 .filter_map(|row| {
408 row.get(&fk.to_column).and_then(|v| match v {
409 Value::Null => None,
410 _ => Some(v.to_display_string()),
411 })
412 })
413 .collect();
414
415 for row in &from_table.1 {
417 let value = match row.get(&fk.from_column) {
418 Some(Value::Null) | None => continue,
419 Some(v) => v,
420 };
421
422 let file_path = row
423 .get("path")
424 .map(|v| format!("{}/{}", fk.from_table, v.to_display_string()))
425 .unwrap_or_else(|| fk.from_table.clone());
426
427 let value_str = value.to_display_string();
428 if !valid_values.contains(&value_str) {
429 errors.push(ValidationError {
430 file_path,
431 error_type: "fk_violation".to_string(),
432 field: Some(fk.from_column.clone()),
433 message: format!(
434 "{} = '{}' not found in {}.{}",
435 fk.from_column, value_str, fk.to_table, fk.to_column
436 ),
437 line_number: None,
438 });
439 }
440 }
441 }
442
443 errors
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use crate::parser::parse_text;
450 use crate::schema::*;
451 use indexmap::IndexMap;
452
453 fn make_schema() -> Schema {
454 let mut frontmatter = IndexMap::new();
455 frontmatter.insert("title".to_string(), FieldDef {
456 field_type: FieldType::String,
457 required: true,
458 enum_values: None,
459 });
460 frontmatter.insert("count".to_string(), FieldDef {
461 field_type: FieldType::Int,
462 required: true,
463 enum_values: None,
464 });
465 frontmatter.insert("status".to_string(), FieldDef {
466 field_type: FieldType::String,
467 required: false,
468 enum_values: Some(vec!["ACTIVE".into(), "ARCHIVED".into()]),
469 });
470
471 let mut sections = IndexMap::new();
472 sections.insert("Summary".to_string(), SectionDef {
473 content_type: "markdown".to_string(),
474 required: true,
475 });
476
477 Schema {
478 table: "test".to_string(),
479 primary_key: "path".to_string(),
480 frontmatter,
481 h1_required: false,
482 h1_must_equal_frontmatter: None,
483 sections,
484 rules: Rules {
485 reject_unknown_frontmatter: true,
486 reject_unknown_sections: false,
487 reject_duplicate_sections: true,
488 normalize_numbered_headings: false,
489 },
490 }
491 }
492
493 #[test]
494 fn test_valid_file() {
495 let text = "---\ntitle: \"Hello\"\ncount: 5\n---\n\n## Summary\n\nA summary.\n";
496 let parsed = parse_text(text, "test.md", false);
497 let errors = validate_file(&parsed, &make_schema());
498 assert!(errors.is_empty(), "Expected no errors, got: {:?}", errors);
499 }
500
501 #[test]
502 fn test_missing_required_field() {
503 let text = "---\ntitle: \"Hello\"\n---\n\n## Summary\n\nText.\n";
504 let parsed = parse_text(text, "test.md", false);
505 let errors = validate_file(&parsed, &make_schema());
506 assert!(errors.iter().any(|e| e.error_type == "missing_field" && e.field.as_deref() == Some("count")));
507 }
508
509 #[test]
510 fn test_type_mismatch() {
511 let text = "---\ntitle: \"Hello\"\ncount: \"not a number\"\n---\n\n## Summary\n\nText.\n";
512 let parsed = parse_text(text, "test.md", false);
513 let errors = validate_file(&parsed, &make_schema());
514 assert!(errors.iter().any(|e| e.error_type == "type_mismatch" && e.field.as_deref() == Some("count")));
515 }
516
517 #[test]
518 fn test_enum_violation() {
519 let text = "---\ntitle: \"Hello\"\ncount: 5\nstatus: INVALID\n---\n\n## Summary\n\nText.\n";
520 let parsed = parse_text(text, "test.md", false);
521 let errors = validate_file(&parsed, &make_schema());
522 assert!(errors.iter().any(|e| e.error_type == "enum_violation"));
523 }
524
525 #[test]
526 fn test_unknown_frontmatter() {
527 let text = "---\ntitle: \"Hello\"\ncount: 5\nextra: bad\n---\n\n## Summary\n\nText.\n";
528 let parsed = parse_text(text, "test.md", false);
529 let errors = validate_file(&parsed, &make_schema());
530 assert!(errors.iter().any(|e| e.error_type == "unknown_field" && e.field.as_deref() == Some("extra")));
531 }
532
533 #[test]
534 fn test_missing_required_section() {
535 let text = "---\ntitle: \"Hello\"\ncount: 5\n---\n\n## Other\n\nText.\n";
536 let parsed = parse_text(text, "test.md", false);
537 let errors = validate_file(&parsed, &make_schema());
538 assert!(errors.iter().any(|e| e.error_type == "missing_section"));
539 }
540
541 #[test]
542 fn test_duplicate_section() {
543 let text = "---\ntitle: \"Hello\"\ncount: 5\n---\n\n## Summary\n\nFirst.\n\n## Summary\n\nSecond.\n";
544 let parsed = parse_text(text, "test.md", false);
545 let errors = validate_file(&parsed, &make_schema());
546 assert!(errors.iter().any(|e| e.error_type == "duplicate_section"));
547 }
548
549 use crate::database::{DatabaseConfig, ForeignKey};
552
553 fn make_fk_tables() -> HashMap<String, (Schema, Vec<Row>)> {
554 let strategy_schema = Schema {
555 table: "strategies".to_string(),
556 primary_key: "path".to_string(),
557 frontmatter: IndexMap::new(),
558 h1_required: false,
559 h1_must_equal_frontmatter: None,
560 sections: IndexMap::new(),
561 rules: Rules {
562 reject_unknown_frontmatter: false,
563 reject_unknown_sections: false,
564 reject_duplicate_sections: false,
565 normalize_numbered_headings: false,
566 },
567 };
568
569 let backtest_schema = Schema {
570 table: "backtests".to_string(),
571 primary_key: "path".to_string(),
572 frontmatter: IndexMap::new(),
573 h1_required: false,
574 h1_must_equal_frontmatter: None,
575 sections: IndexMap::new(),
576 rules: Rules {
577 reject_unknown_frontmatter: false,
578 reject_unknown_sections: false,
579 reject_duplicate_sections: false,
580 normalize_numbered_headings: false,
581 },
582 };
583
584 let mut s1 = Row::new();
585 s1.insert("path".into(), Value::String("alpha.md".into()));
586 let mut s2 = Row::new();
587 s2.insert("path".into(), Value::String("beta.md".into()));
588
589 let mut b1 = Row::new();
590 b1.insert("path".into(), Value::String("bt-alpha.md".into()));
591 b1.insert("strategy".into(), Value::String("alpha.md".into()));
592 let mut b2 = Row::new();
593 b2.insert("path".into(), Value::String("bt-beta.md".into()));
594 b2.insert("strategy".into(), Value::String("beta.md".into()));
595
596 let mut tables = HashMap::new();
597 tables.insert("strategies".into(), (strategy_schema, vec![s1, s2]));
598 tables.insert("backtests".into(), (backtest_schema, vec![b1, b2]));
599 tables
600 }
601
602 fn make_fk_config() -> DatabaseConfig {
603 DatabaseConfig {
604 name: "test".into(),
605 foreign_keys: vec![ForeignKey {
606 from_table: "backtests".into(),
607 from_column: "strategy".into(),
608 to_table: "strategies".into(),
609 to_column: "path".into(),
610 }],
611 }
612 }
613
614 #[test]
615 fn test_fk_valid() {
616 let tables = make_fk_tables();
617 let config = make_fk_config();
618 let errors = validate_foreign_keys(&config, &tables);
619 assert!(errors.is_empty(), "Expected no FK errors, got: {:?}", errors);
620 }
621
622 #[test]
623 fn test_fk_violation() {
624 let mut tables = make_fk_tables();
625 let mut broken = Row::new();
627 broken.insert("path".into(), Value::String("bt-broken.md".into()));
628 broken.insert("strategy".into(), Value::String("nonexistent.md".into()));
629 tables.get_mut("backtests").unwrap().1.push(broken);
630
631 let config = make_fk_config();
632 let errors = validate_foreign_keys(&config, &tables);
633 assert_eq!(errors.len(), 1);
634 assert_eq!(errors[0].error_type, "fk_violation");
635 assert!(errors[0].message.contains("nonexistent.md"));
636 }
637
638 #[test]
639 fn test_fk_null_not_violation() {
640 let mut tables = make_fk_tables();
641 let mut nullref = Row::new();
643 nullref.insert("path".into(), Value::String("bt-null.md".into()));
644 nullref.insert("strategy".into(), Value::Null);
645 tables.get_mut("backtests").unwrap().1.push(nullref);
646
647 let config = make_fk_config();
648 let errors = validate_foreign_keys(&config, &tables);
649 assert!(errors.is_empty());
650 }
651
652 #[test]
653 fn test_fk_missing_table() {
654 let tables = make_fk_tables();
655 let config = DatabaseConfig {
656 name: "test".into(),
657 foreign_keys: vec![ForeignKey {
658 from_table: "backtests".into(),
659 from_column: "strategy".into(),
660 to_table: "nonexistent_table".into(),
661 to_column: "path".into(),
662 }],
663 };
664 let errors = validate_foreign_keys(&config, &tables);
665 assert_eq!(errors.len(), 1);
666 assert_eq!(errors[0].error_type, "fk_missing_table");
667 }
668}