Skip to main content

ison_graph/
schema.rs

1//! ISONGraph Schema Validation Module
2//!
3//! Provides graph schema validation with:
4//! - Node type schemas with property validation
5//! - Edge type schemas with reference integrity
6//! - Graph-level constraints (cycles, connectivity, cardinality)
7//! - Builder pattern for schema definition
8//!
9//! # Example
10//!
11//! ```rust
12//! use ison_graph::schema::{
13//!     GraphSchema, NodeType, EdgeType,
14//!     StringField, IntField, Cardinality,
15//! };
16//! use ison_graph::ISONGraph;
17//!
18//! // Define node types
19//! let person = NodeType::new("person")
20//!     .id(IntField::new())
21//!     .field("name", StringField::new().required().max(100))
22//!     .field("age", IntField::new().min(0).max(150));
23//!
24//! let company = NodeType::new("company")
25//!     .id(IntField::new())
26//!     .field("name", StringField::new().required());
27//!
28//! // Define edge types
29//! let knows = EdgeType::new("KNOWS")
30//!     .from_node("person")
31//!     .to_node("person")
32//!     .no_self_loop()
33//!     .unique();
34//!
35//! let works_at = EdgeType::new("WORKS_AT")
36//!     .from_node("person")
37//!     .to_node("company")
38//!     .cardinality(Cardinality::ManyToOne);
39//!
40//! // Define graph schema
41//! let schema = GraphSchema::new("social")
42//!     .node_type(person)
43//!     .node_type(company)
44//!     .edge_type(knows)
45//!     .edge_type(works_at)
46//!     .no_orphans();
47//!
48//! // Validate
49//! let mut graph = ISONGraph::new("test");
50//! // ... add nodes and edges ...
51//! let result = schema.validate(&graph);
52//! if !result.is_valid() {
53//!     for error in result.errors() {
54//!         println!("{}", error);
55//!     }
56//! }
57//! ```
58
59use crate::{Edge, ISONGraph, Node};
60use regex::Regex;
61use std::collections::{HashMap, HashSet};
62use std::fmt;
63use std::sync::OnceLock;
64
65// =============================================================================
66// Enums
67// =============================================================================
68
69/// Edge cardinality constraints
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Cardinality {
72    OneToOne,
73    OneToMany,
74    ManyToOne,
75    ManyToMany,
76}
77
78impl fmt::Display for Cardinality {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            Cardinality::OneToOne => write!(f, "1:1"),
82            Cardinality::OneToMany => write!(f, "1:N"),
83            Cardinality::ManyToOne => write!(f, "N:1"),
84            Cardinality::ManyToMany => write!(f, "N:N"),
85        }
86    }
87}
88
89/// Validation error codes
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum ErrorCode {
92    // Field errors
93    RequiredField,
94    InvalidType,
95    MinValue,
96    MaxValue,
97    MinLength,
98    MaxLength,
99    PatternMismatch,
100    InvalidEmail,
101    InvalidEnum,
102
103    // Reference errors
104    RefNotFound,
105    RefWrongType,
106
107    // Edge errors
108    SelfLoop,
109    DuplicateEdge,
110    CardinalityViolation,
111    InvalidSourceType,
112    InvalidTargetType,
113
114    // Graph errors
115    CycleDetected,
116    NotConnected,
117    OrphanNode,
118    MaxDepthExceeded,
119}
120
121impl fmt::Display for ErrorCode {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        match self {
124            ErrorCode::RequiredField => write!(f, "REQUIRED_FIELD"),
125            ErrorCode::InvalidType => write!(f, "INVALID_TYPE"),
126            ErrorCode::MinValue => write!(f, "MIN_VALUE"),
127            ErrorCode::MaxValue => write!(f, "MAX_VALUE"),
128            ErrorCode::MinLength => write!(f, "MIN_LENGTH"),
129            ErrorCode::MaxLength => write!(f, "MAX_LENGTH"),
130            ErrorCode::PatternMismatch => write!(f, "PATTERN_MISMATCH"),
131            ErrorCode::InvalidEmail => write!(f, "INVALID_EMAIL"),
132            ErrorCode::InvalidEnum => write!(f, "INVALID_ENUM"),
133            ErrorCode::RefNotFound => write!(f, "REF_NOT_FOUND"),
134            ErrorCode::RefWrongType => write!(f, "REF_WRONG_TYPE"),
135            ErrorCode::SelfLoop => write!(f, "SELF_LOOP"),
136            ErrorCode::DuplicateEdge => write!(f, "DUPLICATE_EDGE"),
137            ErrorCode::CardinalityViolation => write!(f, "CARDINALITY_VIOLATION"),
138            ErrorCode::InvalidSourceType => write!(f, "INVALID_SOURCE_TYPE"),
139            ErrorCode::InvalidTargetType => write!(f, "INVALID_TARGET_TYPE"),
140            ErrorCode::CycleDetected => write!(f, "CYCLE_DETECTED"),
141            ErrorCode::NotConnected => write!(f, "NOT_CONNECTED"),
142            ErrorCode::OrphanNode => write!(f, "ORPHAN_NODE"),
143            ErrorCode::MaxDepthExceeded => write!(f, "MAX_DEPTH_EXCEEDED"),
144        }
145    }
146}
147
148// =============================================================================
149// Validation Result
150// =============================================================================
151
152/// Represents a single validation error
153#[derive(Debug, Clone)]
154pub struct ValidationError {
155    pub code: ErrorCode,
156    pub message: String,
157    pub location: String,
158}
159
160impl ValidationError {
161    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
162        Self {
163            code,
164            message: message.into(),
165            location: String::new(),
166        }
167    }
168
169    pub fn with_location(mut self, location: impl Into<String>) -> Self {
170        self.location = location.into();
171        self
172    }
173}
174
175impl fmt::Display for ValidationError {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        if self.location.is_empty() {
178            write!(f, "{}: {}", self.code, self.message)
179        } else {
180            write!(f, "[{}] {}: {}", self.location, self.code, self.message)
181        }
182    }
183}
184
185/// Result of schema validation
186#[derive(Debug, Clone)]
187pub struct ValidationResult {
188    valid: bool,
189    errors: Vec<ValidationError>,
190    warnings: Vec<ValidationError>,
191}
192
193impl ValidationResult {
194    pub fn new() -> Self {
195        Self {
196            valid: true,
197            errors: Vec::new(),
198            warnings: Vec::new(),
199        }
200    }
201
202    pub fn is_valid(&self) -> bool {
203        self.valid
204    }
205
206    pub fn errors(&self) -> &[ValidationError] {
207        &self.errors
208    }
209
210    pub fn warnings(&self) -> &[ValidationError] {
211        &self.warnings
212    }
213
214    pub fn add_error(&mut self, error: ValidationError) {
215        self.errors.push(error);
216        self.valid = false;
217    }
218
219    pub fn add_warning(&mut self, warning: ValidationError) {
220        self.warnings.push(warning);
221    }
222
223    pub fn merge(&mut self, other: ValidationResult) {
224        self.errors.extend(other.errors);
225        self.warnings.extend(other.warnings);
226        if !other.valid {
227            self.valid = false;
228        }
229    }
230}
231
232impl Default for ValidationResult {
233    fn default() -> Self {
234        Self::new()
235    }
236}
237
238// =============================================================================
239// Field Types
240// =============================================================================
241
242/// Trait for field validators
243pub trait FieldValidator: Send + Sync {
244    fn validate(&self, value: Option<&str>, field_name: &str) -> ValidationResult;
245    fn is_required(&self) -> bool;
246}
247
248/// String field validator
249#[derive(Debug, Clone)]
250pub struct StringField {
251    required: bool,
252    min_length: Option<usize>,
253    max_length: Option<usize>,
254    pattern: Option<Regex>,
255    email: bool,
256    allowed_values: Option<Vec<String>>,
257}
258
259impl StringField {
260    pub fn new() -> Self {
261        Self {
262            required: false,
263            min_length: None,
264            max_length: None,
265            pattern: None,
266            email: false,
267            allowed_values: None,
268        }
269    }
270
271    pub fn required(mut self) -> Self {
272        self.required = true;
273        self
274    }
275
276    pub fn min(mut self, length: usize) -> Self {
277        self.min_length = Some(length);
278        self
279    }
280
281    pub fn max(mut self, length: usize) -> Self {
282        self.max_length = Some(length);
283        self
284    }
285
286    pub fn pattern(mut self, regex: &str) -> Self {
287        self.pattern = Regex::new(regex).ok();
288        self
289    }
290
291    pub fn email(mut self) -> Self {
292        self.email = true;
293        self
294    }
295
296    pub fn allowed(mut self, values: Vec<&str>) -> Self {
297        self.allowed_values = Some(values.into_iter().map(String::from).collect());
298        self
299    }
300}
301
302impl Default for StringField {
303    fn default() -> Self {
304        Self::new()
305    }
306}
307
308impl FieldValidator for StringField {
309    fn validate(&self, value: Option<&str>, field_name: &str) -> ValidationResult {
310        let mut result = ValidationResult::new();
311
312        match value {
313            None | Some("") | Some("null") => {
314                if self.required {
315                    result.add_error(
316                        ValidationError::new(
317                            ErrorCode::RequiredField,
318                            format!("Field '{}' is required", field_name),
319                        )
320                        .with_location(field_name),
321                    );
322                }
323                return result;
324            }
325            Some(val) => {
326                if let Some(min) = self.min_length {
327                    if val.len() < min {
328                        result.add_error(
329                            ValidationError::new(
330                                ErrorCode::MinLength,
331                                format!(
332                                    "Field '{}' must be at least {} characters",
333                                    field_name, min
334                                ),
335                            )
336                            .with_location(field_name),
337                        );
338                    }
339                }
340
341                if let Some(max) = self.max_length {
342                    if val.len() > max {
343                        result.add_error(
344                            ValidationError::new(
345                                ErrorCode::MaxLength,
346                                format!(
347                                    "Field '{}' must be at most {} characters",
348                                    field_name, max
349                                ),
350                            )
351                            .with_location(field_name),
352                        );
353                    }
354                }
355
356                if let Some(ref pattern) = self.pattern {
357                    if !pattern.is_match(val) {
358                        result.add_error(
359                            ValidationError::new(
360                                ErrorCode::PatternMismatch,
361                                format!("Field '{}' does not match pattern", field_name),
362                            )
363                            .with_location(field_name),
364                        );
365                    }
366                }
367
368                if self.email {
369                    static EMAIL_REGEX: OnceLock<Regex> = OnceLock::new();
370                    let email_re = EMAIL_REGEX.get_or_init(|| {
371                        Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap()
372                    });
373                    if !email_re.is_match(val) {
374                        result.add_error(
375                            ValidationError::new(
376                                ErrorCode::InvalidEmail,
377                                format!("Field '{}' is not a valid email address", field_name),
378                            )
379                            .with_location(field_name),
380                        );
381                    }
382                }
383
384                if let Some(ref allowed) = self.allowed_values {
385                    if !allowed.contains(&val.to_string()) {
386                        result.add_error(
387                            ValidationError::new(
388                                ErrorCode::InvalidEnum,
389                                format!(
390                                    "Field '{}' must be one of: {}",
391                                    field_name,
392                                    allowed.join(", ")
393                                ),
394                            )
395                            .with_location(field_name),
396                        );
397                    }
398                }
399            }
400        }
401
402        result
403    }
404
405    fn is_required(&self) -> bool {
406        self.required
407    }
408}
409
410/// Integer field validator
411#[derive(Debug, Clone)]
412pub struct IntField {
413    required: bool,
414    min: Option<i64>,
415    max: Option<i64>,
416}
417
418impl IntField {
419    pub fn new() -> Self {
420        Self {
421            required: false,
422            min: None,
423            max: None,
424        }
425    }
426
427    pub fn required(mut self) -> Self {
428        self.required = true;
429        self
430    }
431
432    pub fn min(mut self, value: i64) -> Self {
433        self.min = Some(value);
434        self
435    }
436
437    pub fn max(mut self, value: i64) -> Self {
438        self.max = Some(value);
439        self
440    }
441
442    pub fn range(mut self, min: i64, max: i64) -> Self {
443        self.min = Some(min);
444        self.max = Some(max);
445        self
446    }
447}
448
449impl Default for IntField {
450    fn default() -> Self {
451        Self::new()
452    }
453}
454
455impl FieldValidator for IntField {
456    fn validate(&self, value: Option<&str>, field_name: &str) -> ValidationResult {
457        let mut result = ValidationResult::new();
458
459        match value {
460            None | Some("") | Some("null") => {
461                if self.required {
462                    result.add_error(
463                        ValidationError::new(
464                            ErrorCode::RequiredField,
465                            format!("Field '{}' is required", field_name),
466                        )
467                        .with_location(field_name),
468                    );
469                }
470                return result;
471            }
472            Some(val) => {
473                let parsed: Result<i64, _> = val.parse();
474                match parsed {
475                    Ok(num) => {
476                        if let Some(min) = self.min {
477                            if num < min {
478                                result.add_error(
479                                    ValidationError::new(
480                                        ErrorCode::MinValue,
481                                        format!("Field '{}' must be at least {}", field_name, min),
482                                    )
483                                    .with_location(field_name),
484                                );
485                            }
486                        }
487
488                        if let Some(max) = self.max {
489                            if num > max {
490                                result.add_error(
491                                    ValidationError::new(
492                                        ErrorCode::MaxValue,
493                                        format!("Field '{}' must be at most {}", field_name, max),
494                                    )
495                                    .with_location(field_name),
496                                );
497                            }
498                        }
499                    }
500                    Err(_) => {
501                        result.add_error(
502                            ValidationError::new(
503                                ErrorCode::InvalidType,
504                                format!("Field '{}' must be an integer", field_name),
505                            )
506                            .with_location(field_name),
507                        );
508                    }
509                }
510            }
511        }
512
513        result
514    }
515
516    fn is_required(&self) -> bool {
517        self.required
518    }
519}
520
521/// Float field validator
522#[derive(Debug, Clone)]
523pub struct FloatField {
524    required: bool,
525    min: Option<f64>,
526    max: Option<f64>,
527}
528
529impl FloatField {
530    pub fn new() -> Self {
531        Self {
532            required: false,
533            min: None,
534            max: None,
535        }
536    }
537
538    pub fn required(mut self) -> Self {
539        self.required = true;
540        self
541    }
542
543    pub fn min(mut self, value: f64) -> Self {
544        self.min = Some(value);
545        self
546    }
547
548    pub fn max(mut self, value: f64) -> Self {
549        self.max = Some(value);
550        self
551    }
552
553    pub fn range(mut self, min: f64, max: f64) -> Self {
554        self.min = Some(min);
555        self.max = Some(max);
556        self
557    }
558}
559
560impl Default for FloatField {
561    fn default() -> Self {
562        Self::new()
563    }
564}
565
566impl FieldValidator for FloatField {
567    fn validate(&self, value: Option<&str>, field_name: &str) -> ValidationResult {
568        let mut result = ValidationResult::new();
569
570        match value {
571            None | Some("") | Some("null") => {
572                if self.required {
573                    result.add_error(
574                        ValidationError::new(
575                            ErrorCode::RequiredField,
576                            format!("Field '{}' is required", field_name),
577                        )
578                        .with_location(field_name),
579                    );
580                }
581                return result;
582            }
583            Some(val) => {
584                let parsed: Result<f64, _> = val.parse();
585                match parsed {
586                    Ok(num) => {
587                        if let Some(min) = self.min {
588                            if num < min {
589                                result.add_error(
590                                    ValidationError::new(
591                                        ErrorCode::MinValue,
592                                        format!("Field '{}' must be at least {}", field_name, min),
593                                    )
594                                    .with_location(field_name),
595                                );
596                            }
597                        }
598
599                        if let Some(max) = self.max {
600                            if num > max {
601                                result.add_error(
602                                    ValidationError::new(
603                                        ErrorCode::MaxValue,
604                                        format!("Field '{}' must be at most {}", field_name, max),
605                                    )
606                                    .with_location(field_name),
607                                );
608                            }
609                        }
610                    }
611                    Err(_) => {
612                        result.add_error(
613                            ValidationError::new(
614                                ErrorCode::InvalidType,
615                                format!("Field '{}' must be a number", field_name),
616                            )
617                            .with_location(field_name),
618                        );
619                    }
620                }
621            }
622        }
623
624        result
625    }
626
627    fn is_required(&self) -> bool {
628        self.required
629    }
630}
631
632/// Boolean field validator
633#[derive(Debug, Clone)]
634pub struct BoolField {
635    required: bool,
636}
637
638impl BoolField {
639    pub fn new() -> Self {
640        Self { required: false }
641    }
642
643    pub fn required(mut self) -> Self {
644        self.required = true;
645        self
646    }
647}
648
649impl Default for BoolField {
650    fn default() -> Self {
651        Self::new()
652    }
653}
654
655impl FieldValidator for BoolField {
656    fn validate(&self, value: Option<&str>, field_name: &str) -> ValidationResult {
657        let mut result = ValidationResult::new();
658
659        match value {
660            None | Some("") | Some("null") => {
661                if self.required {
662                    result.add_error(
663                        ValidationError::new(
664                            ErrorCode::RequiredField,
665                            format!("Field '{}' is required", field_name),
666                        )
667                        .with_location(field_name),
668                    );
669                }
670                return result;
671            }
672            Some(val) => {
673                let lower = val.to_lowercase();
674                if lower != "true" && lower != "false" && lower != "1" && lower != "0" {
675                    result.add_error(
676                        ValidationError::new(
677                            ErrorCode::InvalidType,
678                            format!("Field '{}' must be a boolean", field_name),
679                        )
680                        .with_location(field_name),
681                    );
682                }
683            }
684        }
685
686        result
687    }
688
689    fn is_required(&self) -> bool {
690        self.required
691    }
692}
693
694/// Reference field validator
695#[derive(Debug, Clone)]
696pub struct RefField {
697    required: bool,
698    node_type: Option<String>,
699}
700
701impl RefField {
702    pub fn new() -> Self {
703        Self {
704            required: false,
705            node_type: None,
706        }
707    }
708
709    pub fn required(mut self) -> Self {
710        self.required = true;
711        self
712    }
713
714    pub fn to_node(mut self, node_type: impl Into<String>) -> Self {
715        self.node_type = Some(node_type.into());
716        self
717    }
718}
719
720impl Default for RefField {
721    fn default() -> Self {
722        Self::new()
723    }
724}
725
726impl FieldValidator for RefField {
727    fn validate(&self, value: Option<&str>, field_name: &str) -> ValidationResult {
728        let mut result = ValidationResult::new();
729
730        match value {
731            None | Some("") | Some("null") => {
732                if self.required {
733                    result.add_error(
734                        ValidationError::new(
735                            ErrorCode::RequiredField,
736                            format!("Field '{}' is required", field_name),
737                        )
738                        .with_location(field_name),
739                    );
740                }
741                return result;
742            }
743            Some(val) => {
744                // Reference format: :type:id
745                if val.is_empty() || !val.starts_with(':') {
746                    result.add_error(
747                        ValidationError::new(
748                            ErrorCode::InvalidType,
749                            format!("Field '{}' must be a reference (format :type:id)", field_name),
750                        )
751                        .with_location(field_name),
752                    );
753                    return result;
754                }
755
756                // Find second colon
757                let rest = &val[1..];
758                match rest.find(':') {
759                    None => {
760                        result.add_error(
761                            ValidationError::new(
762                                ErrorCode::InvalidType,
763                                format!("Field '{}' must be a reference (format :type:id)", field_name),
764                            )
765                            .with_location(field_name),
766                        );
767                    }
768                    Some(pos) => {
769                        let ref_type = &rest[..pos];
770
771                        if let Some(ref expected_type) = self.node_type {
772                            if ref_type != expected_type {
773                                result.add_error(
774                                    ValidationError::new(
775                                        ErrorCode::RefWrongType,
776                                        format!(
777                                            "Field '{}' must reference '{}', got '{}'",
778                                            field_name, expected_type, ref_type
779                                        ),
780                                    )
781                                    .with_location(field_name),
782                                );
783                            }
784                        }
785                    }
786                }
787            }
788        }
789
790        result
791    }
792
793    fn is_required(&self) -> bool {
794        self.required
795    }
796}
797
798// =============================================================================
799// Node Type Schema
800// =============================================================================
801
802/// Schema definition for a node type
803pub struct NodeType {
804    pub name: String,
805    id_validator: Option<Box<dyn FieldValidator>>,
806    fields: HashMap<String, Box<dyn FieldValidator>>,
807}
808
809impl NodeType {
810    pub fn new(name: impl Into<String>) -> Self {
811        Self {
812            name: name.into(),
813            id_validator: None,
814            fields: HashMap::new(),
815        }
816    }
817
818    pub fn id<V: FieldValidator + 'static>(mut self, validator: V) -> Self {
819        self.id_validator = Some(Box::new(validator));
820        self
821    }
822
823    pub fn field<V: FieldValidator + 'static>(mut self, name: impl Into<String>, validator: V) -> Self {
824        self.fields.insert(name.into(), Box::new(validator));
825        self
826    }
827
828    pub fn validate_node(&self, node: &Node) -> ValidationResult {
829        let mut result = ValidationResult::new();
830        let location = format!("nodes.{}[{}]", self.name, node.id);
831
832        // Validate ID
833        if let Some(ref id_validator) = self.id_validator {
834            let id_result = id_validator.validate(Some(&node.id), "id");
835            if !id_result.is_valid() {
836                for mut err in id_result.errors {
837                    err.location = location.clone();
838                    result.add_error(err);
839                }
840            }
841        }
842
843        // Validate fields
844        for (field_name, validator) in &self.fields {
845            // Rendered to text so validation behaves exactly as it did when
846            // properties were strings. Type-aware validation is a separate
847            // change; typing the storage should not silently alter what a
848            // schema accepts.
849            let rendered = node.properties.get(field_name).map(crate::value_to_text);
850            let value = rendered.as_deref();
851            let field_result = validator.validate(value, field_name);
852            if !field_result.is_valid() {
853                for mut err in field_result.errors {
854                    err.location = format!("{}.{}", location, field_name);
855                    result.add_error(err);
856                }
857            }
858        }
859
860        result
861    }
862}
863
864// =============================================================================
865// Edge Type Schema
866// =============================================================================
867
868/// Schema definition for an edge/relationship type
869pub struct EdgeType {
870    pub name: String,
871    source_type: Option<String>,
872    target_type: Option<String>,
873    fields: HashMap<String, Box<dyn FieldValidator>>,
874    no_self_loop: bool,
875    unique: bool,
876    acyclic: bool,
877    bidirectional: bool,
878    cardinality: Option<Cardinality>,
879}
880
881impl EdgeType {
882    pub fn new(name: impl Into<String>) -> Self {
883        Self {
884            name: name.into(),
885            source_type: None,
886            target_type: None,
887            fields: HashMap::new(),
888            no_self_loop: false,
889            unique: false,
890            acyclic: false,
891            bidirectional: false,
892            cardinality: None,
893        }
894    }
895
896    pub fn from_node(mut self, node_type: impl Into<String>) -> Self {
897        self.source_type = Some(node_type.into());
898        self
899    }
900
901    pub fn to_node(mut self, node_type: impl Into<String>) -> Self {
902        self.target_type = Some(node_type.into());
903        self
904    }
905
906    pub fn field<V: FieldValidator + 'static>(mut self, name: impl Into<String>, validator: V) -> Self {
907        self.fields.insert(name.into(), Box::new(validator));
908        self
909    }
910
911    pub fn no_self_loop(mut self) -> Self {
912        self.no_self_loop = true;
913        self
914    }
915
916    pub fn unique(mut self) -> Self {
917        self.unique = true;
918        self
919    }
920
921    pub fn acyclic(mut self) -> Self {
922        self.acyclic = true;
923        self
924    }
925
926    pub fn bidirectional(mut self) -> Self {
927        self.bidirectional = true;
928        self
929    }
930
931    pub fn cardinality(mut self, card: Cardinality) -> Self {
932        self.cardinality = Some(card);
933        self
934    }
935
936    pub fn is_unique(&self) -> bool {
937        self.unique
938    }
939
940    pub fn is_acyclic(&self) -> bool {
941        self.acyclic
942    }
943
944    pub fn is_bidirectional(&self) -> bool {
945        self.bidirectional
946    }
947
948    pub fn cardinality_constraint(&self) -> Option<Cardinality> {
949        self.cardinality
950    }
951
952    pub fn validate_edge(&self, edge: &Edge, graph: &ISONGraph) -> ValidationResult {
953        let mut result = ValidationResult::new();
954        let location = format!(
955            "edges.{}[{}->{}]",
956            self.name,
957            edge.source.to_key(),
958            edge.target.to_key()
959        );
960
961        // Validate source type
962        if let Some(ref src_type) = self.source_type {
963            if &edge.source.node_type != src_type {
964                result.add_error(
965                    ValidationError::new(
966                        ErrorCode::InvalidSourceType,
967                        format!(
968                            "Edge source must be '{}', got '{}'",
969                            src_type, edge.source.node_type
970                        ),
971                    )
972                    .with_location(&location),
973                );
974            }
975        }
976
977        // Validate target type
978        if let Some(ref tgt_type) = self.target_type {
979            if &edge.target.node_type != tgt_type {
980                result.add_error(
981                    ValidationError::new(
982                        ErrorCode::InvalidTargetType,
983                        format!(
984                            "Edge target must be '{}', got '{}'",
985                            tgt_type, edge.target.node_type
986                        ),
987                    )
988                    .with_location(&location),
989                );
990            }
991        }
992
993        // Validate source exists
994        if !graph.has_node(&edge.source.node_type, &edge.source.id) {
995            result.add_error(
996                ValidationError::new(
997                    ErrorCode::RefNotFound,
998                    format!(
999                        "Source node :{}:{} does not exist",
1000                        edge.source.node_type, edge.source.id
1001                    ),
1002                )
1003                .with_location(&location),
1004            );
1005        }
1006
1007        // Validate target exists
1008        if !graph.has_node(&edge.target.node_type, &edge.target.id) {
1009            result.add_error(
1010                ValidationError::new(
1011                    ErrorCode::RefNotFound,
1012                    format!(
1013                        "Target node :{}:{} does not exist",
1014                        edge.target.node_type, edge.target.id
1015                    ),
1016                )
1017                .with_location(&location),
1018            );
1019        }
1020
1021        // Validate self-loop constraint
1022        if self.no_self_loop && edge.source == edge.target {
1023            result.add_error(
1024                ValidationError::new(
1025                    ErrorCode::SelfLoop,
1026                    format!(
1027                        "Self-loop not allowed: :{}:{}",
1028                        edge.source.node_type, edge.source.id
1029                    ),
1030                )
1031                .with_location(&location),
1032            );
1033        }
1034
1035        // Validate fields
1036        for (field_name, validator) in &self.fields {
1037            let rendered = edge.properties.get(field_name).map(crate::value_to_text);
1038            let value = rendered.as_deref();
1039            let field_result = validator.validate(value, field_name);
1040            if !field_result.is_valid() {
1041                for mut err in field_result.errors {
1042                    err.location = format!("{}.{}", location, field_name);
1043                    result.add_error(err);
1044                }
1045            }
1046        }
1047
1048        result
1049    }
1050}
1051
1052// =============================================================================
1053// Graph Schema
1054// =============================================================================
1055
1056/// Complete graph schema definition
1057pub struct GraphSchema {
1058    pub name: String,
1059    node_types: HashMap<String, NodeType>,
1060    edge_types: HashMap<String, EdgeType>,
1061    require_connected: bool,
1062    require_no_orphans: bool,
1063    max_depth: Option<usize>,
1064}
1065
1066impl GraphSchema {
1067    pub fn new(name: impl Into<String>) -> Self {
1068        Self {
1069            name: name.into(),
1070            node_types: HashMap::new(),
1071            edge_types: HashMap::new(),
1072            require_connected: false,
1073            require_no_orphans: false,
1074            max_depth: None,
1075        }
1076    }
1077
1078    pub fn node_type(mut self, node_type: NodeType) -> Self {
1079        self.node_types.insert(node_type.name.clone(), node_type);
1080        self
1081    }
1082
1083    pub fn edge_type(mut self, edge_type: EdgeType) -> Self {
1084        self.edge_types.insert(edge_type.name.clone(), edge_type);
1085        self
1086    }
1087
1088    pub fn connected(mut self) -> Self {
1089        self.require_connected = true;
1090        self
1091    }
1092
1093    pub fn no_orphans(mut self) -> Self {
1094        self.require_no_orphans = true;
1095        self
1096    }
1097
1098    pub fn max_depth(mut self, depth: usize) -> Self {
1099        self.max_depth = Some(depth);
1100        self
1101    }
1102
1103    /// Validate a graph against this schema
1104    pub fn validate(&self, graph: &ISONGraph) -> ValidationResult {
1105        let mut result = ValidationResult::new();
1106
1107        // Validate nodes
1108        for node in graph.nodes() {
1109            if let Some(node_type) = self.node_types.get(&node.node_type) {
1110                let node_result = node_type.validate_node(node);
1111                result.merge(node_result);
1112            }
1113        }
1114
1115        // Validate edges
1116        for (rel_type, edge_type) in &self.edge_types {
1117            let edges: Vec<_> = graph.edges_of_type(rel_type).collect();
1118
1119            // Check uniqueness
1120            if edge_type.is_unique() {
1121                let mut seen = HashSet::new();
1122                for edge in &edges {
1123                    let key = format!(
1124                        "{}:{}->{}:{}",
1125                        edge.source.node_type,
1126                        edge.source.id,
1127                        edge.target.node_type,
1128                        edge.target.id
1129                    );
1130                    if seen.contains(&key) {
1131                        result.add_error(
1132                            ValidationError::new(
1133                                ErrorCode::DuplicateEdge,
1134                                format!("Duplicate edge: {} -> {}", edge.source.to_key(), edge.target.to_key()),
1135                            )
1136                            .with_location(format!("edges.{}", rel_type)),
1137                        );
1138                    }
1139                    seen.insert(key);
1140                }
1141            }
1142
1143            // Check cardinality
1144            if edge_type.cardinality_constraint().is_some() {
1145                self.check_cardinality(graph, edge_type, &edges, &mut result);
1146            }
1147
1148            // Check acyclic
1149            if edge_type.is_acyclic() && graph.has_cycle(Some(rel_type)) {
1150                result.add_error(
1151                    ValidationError::new(
1152                        ErrorCode::CycleDetected,
1153                        format!("Cycle detected in '{}' edges (must be DAG)", rel_type),
1154                    )
1155                    .with_location(format!("edges.{}", rel_type)),
1156                );
1157            }
1158
1159            // Check bidirectional
1160            if edge_type.is_bidirectional() {
1161                for edge in &edges {
1162                    if !graph.has_edge(
1163                        rel_type,
1164                        (&edge.target.node_type, &edge.target.id),
1165                        (&edge.source.node_type, &edge.source.id),
1166                    ) {
1167                        result.add_error(
1168                            ValidationError::new(
1169                                ErrorCode::DuplicateEdge,
1170                                format!(
1171                                    "Missing reverse edge for bidirectional: {} -> {}",
1172                                    edge.target.to_key(),
1173                                    edge.source.to_key()
1174                                ),
1175                            )
1176                            .with_location(format!("edges.{}", rel_type)),
1177                        );
1178                    }
1179                }
1180            }
1181
1182            // Validate individual edges
1183            for edge in &edges {
1184                let edge_result = edge_type.validate_edge(edge, graph);
1185                result.merge(edge_result);
1186            }
1187        }
1188
1189        // Graph-level constraints
1190        if self.require_connected && !graph.is_connected() {
1191            result.add_error(
1192                ValidationError::new(
1193                    ErrorCode::NotConnected,
1194                    "Graph is not connected (some nodes are unreachable)",
1195                )
1196                .with_location("graph"),
1197            );
1198        }
1199
1200        if self.require_no_orphans {
1201            for node in graph.nodes() {
1202                let node_ref = (&node.node_type as &str, &node.id as &str);
1203                if graph.degree(&node_ref) == 0 {
1204                    result.add_error(
1205                        ValidationError::new(
1206                            ErrorCode::OrphanNode,
1207                            format!(
1208                                "Orphan node (no edges): :{}:{}",
1209                                node.node_type, node.id
1210                            ),
1211                        )
1212                        .with_location(format!("nodes.{}[{}]", node.node_type, node.id)),
1213                    );
1214                }
1215            }
1216        }
1217
1218        result
1219    }
1220
1221    fn check_cardinality(
1222        &self,
1223        _graph: &ISONGraph,
1224        edge_type: &EdgeType,
1225        edges: &[&Edge],
1226        result: &mut ValidationResult,
1227    ) {
1228        let cardinality = match edge_type.cardinality_constraint() {
1229            Some(c) => c,
1230            None => return,
1231        };
1232        let location = format!("edges.{}", edge_type.name);
1233
1234        // Count outgoing edges per source
1235        let mut source_counts: HashMap<String, usize> = HashMap::new();
1236        // Count incoming edges per target
1237        let mut target_counts: HashMap<String, usize> = HashMap::new();
1238
1239        for edge in edges {
1240            let source_key = edge.source.to_key();
1241            let target_key = edge.target.to_key();
1242            *source_counts.entry(source_key).or_insert(0) += 1;
1243            *target_counts.entry(target_key).or_insert(0) += 1;
1244        }
1245
1246        match cardinality {
1247            Cardinality::OneToOne => {
1248                for (source, count) in &source_counts {
1249                    if *count > 1 {
1250                        result.add_error(
1251                            ValidationError::new(
1252                                ErrorCode::CardinalityViolation,
1253                                format!(
1254                                    "ONE_TO_ONE violation: :{} has {} outgoing edges",
1255                                    source, count
1256                                ),
1257                            )
1258                            .with_location(&location),
1259                        );
1260                    }
1261                }
1262                for (target, count) in &target_counts {
1263                    if *count > 1 {
1264                        result.add_error(
1265                            ValidationError::new(
1266                                ErrorCode::CardinalityViolation,
1267                                format!(
1268                                    "ONE_TO_ONE violation: :{} has {} incoming edges",
1269                                    target, count
1270                                ),
1271                            )
1272                            .with_location(&location),
1273                        );
1274                    }
1275                }
1276            }
1277            Cardinality::OneToMany => {
1278                for (target, count) in &target_counts {
1279                    if *count > 1 {
1280                        result.add_error(
1281                            ValidationError::new(
1282                                ErrorCode::CardinalityViolation,
1283                                format!(
1284                                    "ONE_TO_MANY violation: :{} has {} incoming edges",
1285                                    target, count
1286                                ),
1287                            )
1288                            .with_location(&location),
1289                        );
1290                    }
1291                }
1292            }
1293            Cardinality::ManyToOne => {
1294                for (source, count) in &source_counts {
1295                    if *count > 1 {
1296                        result.add_error(
1297                            ValidationError::new(
1298                                ErrorCode::CardinalityViolation,
1299                                format!(
1300                                    "MANY_TO_ONE violation: :{} has {} outgoing edges",
1301                                    source, count
1302                                ),
1303                            )
1304                            .with_location(&location),
1305                        );
1306                    }
1307                }
1308            }
1309            Cardinality::ManyToMany => {
1310                // No restrictions
1311            }
1312        }
1313    }
1314}
1315
1316// =============================================================================
1317// Tests
1318// =============================================================================
1319
1320#[cfg(test)]
1321mod tests {
1322    use super::*;
1323    use crate::Value;
1324
1325    #[test]
1326    fn test_string_field_required() {
1327        let field = StringField::new().required();
1328        let result = field.validate(None, "name");
1329        assert!(!result.is_valid());
1330        assert_eq!(result.errors()[0].code, ErrorCode::RequiredField);
1331    }
1332
1333    #[test]
1334    fn test_string_field_length() {
1335        let field = StringField::new().min(3).max(10);
1336
1337        let result = field.validate(Some("ab"), "name");
1338        assert!(!result.is_valid());
1339
1340        let result = field.validate(Some("hello"), "name");
1341        assert!(result.is_valid());
1342
1343        let result = field.validate(Some("this is too long"), "name");
1344        assert!(!result.is_valid());
1345    }
1346
1347    #[test]
1348    fn test_int_field_range() {
1349        let field = IntField::new().min(0).max(150);
1350
1351        let result = field.validate(Some("-1"), "age");
1352        assert!(!result.is_valid());
1353
1354        let result = field.validate(Some("30"), "age");
1355        assert!(result.is_valid());
1356
1357        let result = field.validate(Some("200"), "age");
1358        assert!(!result.is_valid());
1359    }
1360
1361    #[test]
1362    fn test_node_type_validation() {
1363        let person = NodeType::new("person")
1364            .field("name", StringField::new().required())
1365            .field("age", IntField::new().min(0).max(150));
1366
1367        let mut node = Node::new("person", "1");
1368        node.properties.insert("name".to_string(), Value::String("Alice".to_string()));
1369        node.properties.insert("age".to_string(), Value::String("30".to_string()));
1370
1371        let result = person.validate_node(&node);
1372        assert!(result.is_valid());
1373
1374        let mut invalid_node = Node::new("person", "2");
1375        invalid_node.properties.insert("age".to_string(), Value::String("200".to_string()));
1376
1377        let result = person.validate_node(&invalid_node);
1378        assert!(!result.is_valid());
1379        assert!(result.errors().len() >= 2); // missing required name + age out of range
1380    }
1381
1382    #[test]
1383    fn test_graph_schema_validation() {
1384        let person = NodeType::new("person")
1385            .field("name", StringField::new().required());
1386
1387        let knows = EdgeType::new("KNOWS")
1388            .from_node("person")
1389            .to_node("person")
1390            .no_self_loop();
1391
1392        let schema = GraphSchema::new("social")
1393            .node_type(person)
1394            .edge_type(knows);
1395
1396        let mut graph = ISONGraph::new("test");
1397        graph.add_node("person", "1", props![("name", "Alice")]).unwrap();
1398        graph.add_node("person", "2", props![("name", "Bob")]).unwrap();
1399        graph.add_edge("KNOWS", ("person", "1"), ("person", "2"), props![]).unwrap();
1400
1401        let result = schema.validate(&graph);
1402        assert!(result.is_valid());
1403    }
1404
1405    #[test]
1406    fn test_self_loop_constraint() {
1407        let knows = EdgeType::new("KNOWS")
1408            .from_node("person")
1409            .to_node("person")
1410            .no_self_loop();
1411
1412        let schema = GraphSchema::new("social")
1413            .edge_type(knows);
1414
1415        let mut graph = ISONGraph::new("test");
1416        graph.add_node("person", "1", props![]).unwrap();
1417        graph.add_edge("KNOWS", ("person", "1"), ("person", "1"), props![]).unwrap();
1418
1419        let result = schema.validate(&graph);
1420        assert!(!result.is_valid());
1421        assert!(result.errors().iter().any(|e| e.code == ErrorCode::SelfLoop));
1422    }
1423
1424    #[test]
1425    fn test_orphan_constraint() {
1426        let schema = GraphSchema::new("social")
1427            .no_orphans();
1428
1429        let mut graph = ISONGraph::new("test");
1430        graph.add_node("person", "1", props![]).unwrap();
1431
1432        let result = schema.validate(&graph);
1433        assert!(!result.is_valid());
1434        assert!(result.errors().iter().any(|e| e.code == ErrorCode::OrphanNode));
1435    }
1436
1437    #[test]
1438    fn test_ref_field_required() {
1439        let field = RefField::new().required();
1440
1441        // Missing value should fail
1442        let result = field.validate(None, "manager");
1443        assert!(!result.is_valid());
1444        assert_eq!(result.errors()[0].code, ErrorCode::RequiredField);
1445
1446        // Valid reference should pass
1447        let result = field.validate(Some(":person:1"), "manager");
1448        assert!(result.is_valid());
1449    }
1450
1451    #[test]
1452    fn test_ref_field_format() {
1453        let field = RefField::new();
1454
1455        // Invalid format - missing colon prefix
1456        let result = field.validate(Some("person:1"), "manager");
1457        assert!(!result.is_valid());
1458        assert_eq!(result.errors()[0].code, ErrorCode::InvalidType);
1459
1460        // Invalid format - missing second colon
1461        let result = field.validate(Some(":person"), "manager");
1462        assert!(!result.is_valid());
1463
1464        // Valid format
1465        let result = field.validate(Some(":person:1"), "manager");
1466        assert!(result.is_valid());
1467    }
1468
1469    #[test]
1470    fn test_ref_field_type_constraint() {
1471        let field = RefField::new().to_node("person");
1472
1473        // Wrong node type
1474        let result = field.validate(Some(":company:1"), "manager");
1475        assert!(!result.is_valid());
1476        assert_eq!(result.errors()[0].code, ErrorCode::RefWrongType);
1477
1478        // Correct node type
1479        let result = field.validate(Some(":person:1"), "manager");
1480        assert!(result.is_valid());
1481    }
1482}