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            let value = node.properties.get(field_name).map(|s| s.as_str());
846            let field_result = validator.validate(value, field_name);
847            if !field_result.is_valid() {
848                for mut err in field_result.errors {
849                    err.location = format!("{}.{}", location, field_name);
850                    result.add_error(err);
851                }
852            }
853        }
854
855        result
856    }
857}
858
859// =============================================================================
860// Edge Type Schema
861// =============================================================================
862
863/// Schema definition for an edge/relationship type
864pub struct EdgeType {
865    pub name: String,
866    source_type: Option<String>,
867    target_type: Option<String>,
868    fields: HashMap<String, Box<dyn FieldValidator>>,
869    no_self_loop: bool,
870    unique: bool,
871    acyclic: bool,
872    bidirectional: bool,
873    cardinality: Option<Cardinality>,
874}
875
876impl EdgeType {
877    pub fn new(name: impl Into<String>) -> Self {
878        Self {
879            name: name.into(),
880            source_type: None,
881            target_type: None,
882            fields: HashMap::new(),
883            no_self_loop: false,
884            unique: false,
885            acyclic: false,
886            bidirectional: false,
887            cardinality: None,
888        }
889    }
890
891    pub fn from_node(mut self, node_type: impl Into<String>) -> Self {
892        self.source_type = Some(node_type.into());
893        self
894    }
895
896    pub fn to_node(mut self, node_type: impl Into<String>) -> Self {
897        self.target_type = Some(node_type.into());
898        self
899    }
900
901    pub fn field<V: FieldValidator + 'static>(mut self, name: impl Into<String>, validator: V) -> Self {
902        self.fields.insert(name.into(), Box::new(validator));
903        self
904    }
905
906    pub fn no_self_loop(mut self) -> Self {
907        self.no_self_loop = true;
908        self
909    }
910
911    pub fn unique(mut self) -> Self {
912        self.unique = true;
913        self
914    }
915
916    pub fn acyclic(mut self) -> Self {
917        self.acyclic = true;
918        self
919    }
920
921    pub fn bidirectional(mut self) -> Self {
922        self.bidirectional = true;
923        self
924    }
925
926    pub fn cardinality(mut self, card: Cardinality) -> Self {
927        self.cardinality = Some(card);
928        self
929    }
930
931    pub fn is_unique(&self) -> bool {
932        self.unique
933    }
934
935    pub fn is_acyclic(&self) -> bool {
936        self.acyclic
937    }
938
939    pub fn is_bidirectional(&self) -> bool {
940        self.bidirectional
941    }
942
943    pub fn cardinality_constraint(&self) -> Option<Cardinality> {
944        self.cardinality
945    }
946
947    pub fn validate_edge(&self, edge: &Edge, graph: &ISONGraph) -> ValidationResult {
948        let mut result = ValidationResult::new();
949        let location = format!(
950            "edges.{}[{}->{}]",
951            self.name,
952            edge.source.to_key(),
953            edge.target.to_key()
954        );
955
956        // Validate source type
957        if let Some(ref src_type) = self.source_type {
958            if &edge.source.node_type != src_type {
959                result.add_error(
960                    ValidationError::new(
961                        ErrorCode::InvalidSourceType,
962                        format!(
963                            "Edge source must be '{}', got '{}'",
964                            src_type, edge.source.node_type
965                        ),
966                    )
967                    .with_location(&location),
968                );
969            }
970        }
971
972        // Validate target type
973        if let Some(ref tgt_type) = self.target_type {
974            if &edge.target.node_type != tgt_type {
975                result.add_error(
976                    ValidationError::new(
977                        ErrorCode::InvalidTargetType,
978                        format!(
979                            "Edge target must be '{}', got '{}'",
980                            tgt_type, edge.target.node_type
981                        ),
982                    )
983                    .with_location(&location),
984                );
985            }
986        }
987
988        // Validate source exists
989        if !graph.has_node(&edge.source.node_type, &edge.source.id) {
990            result.add_error(
991                ValidationError::new(
992                    ErrorCode::RefNotFound,
993                    format!(
994                        "Source node :{}:{} does not exist",
995                        edge.source.node_type, edge.source.id
996                    ),
997                )
998                .with_location(&location),
999            );
1000        }
1001
1002        // Validate target exists
1003        if !graph.has_node(&edge.target.node_type, &edge.target.id) {
1004            result.add_error(
1005                ValidationError::new(
1006                    ErrorCode::RefNotFound,
1007                    format!(
1008                        "Target node :{}:{} does not exist",
1009                        edge.target.node_type, edge.target.id
1010                    ),
1011                )
1012                .with_location(&location),
1013            );
1014        }
1015
1016        // Validate self-loop constraint
1017        if self.no_self_loop && edge.source == edge.target {
1018            result.add_error(
1019                ValidationError::new(
1020                    ErrorCode::SelfLoop,
1021                    format!(
1022                        "Self-loop not allowed: :{}:{}",
1023                        edge.source.node_type, edge.source.id
1024                    ),
1025                )
1026                .with_location(&location),
1027            );
1028        }
1029
1030        // Validate fields
1031        for (field_name, validator) in &self.fields {
1032            let value = edge.properties.get(field_name).map(|s| s.as_str());
1033            let field_result = validator.validate(value, field_name);
1034            if !field_result.is_valid() {
1035                for mut err in field_result.errors {
1036                    err.location = format!("{}.{}", location, field_name);
1037                    result.add_error(err);
1038                }
1039            }
1040        }
1041
1042        result
1043    }
1044}
1045
1046// =============================================================================
1047// Graph Schema
1048// =============================================================================
1049
1050/// Complete graph schema definition
1051pub struct GraphSchema {
1052    pub name: String,
1053    node_types: HashMap<String, NodeType>,
1054    edge_types: HashMap<String, EdgeType>,
1055    require_connected: bool,
1056    require_no_orphans: bool,
1057    max_depth: Option<usize>,
1058}
1059
1060impl GraphSchema {
1061    pub fn new(name: impl Into<String>) -> Self {
1062        Self {
1063            name: name.into(),
1064            node_types: HashMap::new(),
1065            edge_types: HashMap::new(),
1066            require_connected: false,
1067            require_no_orphans: false,
1068            max_depth: None,
1069        }
1070    }
1071
1072    pub fn node_type(mut self, node_type: NodeType) -> Self {
1073        self.node_types.insert(node_type.name.clone(), node_type);
1074        self
1075    }
1076
1077    pub fn edge_type(mut self, edge_type: EdgeType) -> Self {
1078        self.edge_types.insert(edge_type.name.clone(), edge_type);
1079        self
1080    }
1081
1082    pub fn connected(mut self) -> Self {
1083        self.require_connected = true;
1084        self
1085    }
1086
1087    pub fn no_orphans(mut self) -> Self {
1088        self.require_no_orphans = true;
1089        self
1090    }
1091
1092    pub fn max_depth(mut self, depth: usize) -> Self {
1093        self.max_depth = Some(depth);
1094        self
1095    }
1096
1097    /// Validate a graph against this schema
1098    pub fn validate(&self, graph: &ISONGraph) -> ValidationResult {
1099        let mut result = ValidationResult::new();
1100
1101        // Validate nodes
1102        for node in graph.nodes() {
1103            if let Some(node_type) = self.node_types.get(&node.node_type) {
1104                let node_result = node_type.validate_node(node);
1105                result.merge(node_result);
1106            }
1107        }
1108
1109        // Validate edges
1110        for (rel_type, edge_type) in &self.edge_types {
1111            let edges: Vec<_> = graph.edges_of_type(rel_type).collect();
1112
1113            // Check uniqueness
1114            if edge_type.is_unique() {
1115                let mut seen = HashSet::new();
1116                for edge in &edges {
1117                    let key = format!(
1118                        "{}:{}->{}:{}",
1119                        edge.source.node_type,
1120                        edge.source.id,
1121                        edge.target.node_type,
1122                        edge.target.id
1123                    );
1124                    if seen.contains(&key) {
1125                        result.add_error(
1126                            ValidationError::new(
1127                                ErrorCode::DuplicateEdge,
1128                                format!("Duplicate edge: {} -> {}", edge.source.to_key(), edge.target.to_key()),
1129                            )
1130                            .with_location(format!("edges.{}", rel_type)),
1131                        );
1132                    }
1133                    seen.insert(key);
1134                }
1135            }
1136
1137            // Check cardinality
1138            if edge_type.cardinality_constraint().is_some() {
1139                self.check_cardinality(graph, edge_type, &edges, &mut result);
1140            }
1141
1142            // Check acyclic
1143            if edge_type.is_acyclic() && graph.has_cycle(Some(rel_type)) {
1144                result.add_error(
1145                    ValidationError::new(
1146                        ErrorCode::CycleDetected,
1147                        format!("Cycle detected in '{}' edges (must be DAG)", rel_type),
1148                    )
1149                    .with_location(format!("edges.{}", rel_type)),
1150                );
1151            }
1152
1153            // Check bidirectional
1154            if edge_type.is_bidirectional() {
1155                for edge in &edges {
1156                    if !graph.has_edge(
1157                        rel_type,
1158                        (&edge.target.node_type, &edge.target.id),
1159                        (&edge.source.node_type, &edge.source.id),
1160                    ) {
1161                        result.add_error(
1162                            ValidationError::new(
1163                                ErrorCode::DuplicateEdge,
1164                                format!(
1165                                    "Missing reverse edge for bidirectional: {} -> {}",
1166                                    edge.target.to_key(),
1167                                    edge.source.to_key()
1168                                ),
1169                            )
1170                            .with_location(format!("edges.{}", rel_type)),
1171                        );
1172                    }
1173                }
1174            }
1175
1176            // Validate individual edges
1177            for edge in &edges {
1178                let edge_result = edge_type.validate_edge(edge, graph);
1179                result.merge(edge_result);
1180            }
1181        }
1182
1183        // Graph-level constraints
1184        if self.require_connected && !graph.is_connected() {
1185            result.add_error(
1186                ValidationError::new(
1187                    ErrorCode::NotConnected,
1188                    "Graph is not connected (some nodes are unreachable)",
1189                )
1190                .with_location("graph"),
1191            );
1192        }
1193
1194        if self.require_no_orphans {
1195            for node in graph.nodes() {
1196                let node_ref = (&node.node_type as &str, &node.id as &str);
1197                if graph.degree(&node_ref) == 0 {
1198                    result.add_error(
1199                        ValidationError::new(
1200                            ErrorCode::OrphanNode,
1201                            format!(
1202                                "Orphan node (no edges): :{}:{}",
1203                                node.node_type, node.id
1204                            ),
1205                        )
1206                        .with_location(format!("nodes.{}[{}]", node.node_type, node.id)),
1207                    );
1208                }
1209            }
1210        }
1211
1212        result
1213    }
1214
1215    fn check_cardinality(
1216        &self,
1217        _graph: &ISONGraph,
1218        edge_type: &EdgeType,
1219        edges: &[&Edge],
1220        result: &mut ValidationResult,
1221    ) {
1222        let cardinality = match edge_type.cardinality_constraint() {
1223            Some(c) => c,
1224            None => return,
1225        };
1226        let location = format!("edges.{}", edge_type.name);
1227
1228        // Count outgoing edges per source
1229        let mut source_counts: HashMap<String, usize> = HashMap::new();
1230        // Count incoming edges per target
1231        let mut target_counts: HashMap<String, usize> = HashMap::new();
1232
1233        for edge in edges {
1234            let source_key = edge.source.to_key();
1235            let target_key = edge.target.to_key();
1236            *source_counts.entry(source_key).or_insert(0) += 1;
1237            *target_counts.entry(target_key).or_insert(0) += 1;
1238        }
1239
1240        match cardinality {
1241            Cardinality::OneToOne => {
1242                for (source, count) in &source_counts {
1243                    if *count > 1 {
1244                        result.add_error(
1245                            ValidationError::new(
1246                                ErrorCode::CardinalityViolation,
1247                                format!(
1248                                    "ONE_TO_ONE violation: :{} has {} outgoing edges",
1249                                    source, count
1250                                ),
1251                            )
1252                            .with_location(&location),
1253                        );
1254                    }
1255                }
1256                for (target, count) in &target_counts {
1257                    if *count > 1 {
1258                        result.add_error(
1259                            ValidationError::new(
1260                                ErrorCode::CardinalityViolation,
1261                                format!(
1262                                    "ONE_TO_ONE violation: :{} has {} incoming edges",
1263                                    target, count
1264                                ),
1265                            )
1266                            .with_location(&location),
1267                        );
1268                    }
1269                }
1270            }
1271            Cardinality::OneToMany => {
1272                for (target, count) in &target_counts {
1273                    if *count > 1 {
1274                        result.add_error(
1275                            ValidationError::new(
1276                                ErrorCode::CardinalityViolation,
1277                                format!(
1278                                    "ONE_TO_MANY violation: :{} has {} incoming edges",
1279                                    target, count
1280                                ),
1281                            )
1282                            .with_location(&location),
1283                        );
1284                    }
1285                }
1286            }
1287            Cardinality::ManyToOne => {
1288                for (source, count) in &source_counts {
1289                    if *count > 1 {
1290                        result.add_error(
1291                            ValidationError::new(
1292                                ErrorCode::CardinalityViolation,
1293                                format!(
1294                                    "MANY_TO_ONE violation: :{} has {} outgoing edges",
1295                                    source, count
1296                                ),
1297                            )
1298                            .with_location(&location),
1299                        );
1300                    }
1301                }
1302            }
1303            Cardinality::ManyToMany => {
1304                // No restrictions
1305            }
1306        }
1307    }
1308}
1309
1310// =============================================================================
1311// Tests
1312// =============================================================================
1313
1314#[cfg(test)]
1315mod tests {
1316    use super::*;
1317
1318    #[test]
1319    fn test_string_field_required() {
1320        let field = StringField::new().required();
1321        let result = field.validate(None, "name");
1322        assert!(!result.is_valid());
1323        assert_eq!(result.errors()[0].code, ErrorCode::RequiredField);
1324    }
1325
1326    #[test]
1327    fn test_string_field_length() {
1328        let field = StringField::new().min(3).max(10);
1329
1330        let result = field.validate(Some("ab"), "name");
1331        assert!(!result.is_valid());
1332
1333        let result = field.validate(Some("hello"), "name");
1334        assert!(result.is_valid());
1335
1336        let result = field.validate(Some("this is too long"), "name");
1337        assert!(!result.is_valid());
1338    }
1339
1340    #[test]
1341    fn test_int_field_range() {
1342        let field = IntField::new().min(0).max(150);
1343
1344        let result = field.validate(Some("-1"), "age");
1345        assert!(!result.is_valid());
1346
1347        let result = field.validate(Some("30"), "age");
1348        assert!(result.is_valid());
1349
1350        let result = field.validate(Some("200"), "age");
1351        assert!(!result.is_valid());
1352    }
1353
1354    #[test]
1355    fn test_node_type_validation() {
1356        let person = NodeType::new("person")
1357            .field("name", StringField::new().required())
1358            .field("age", IntField::new().min(0).max(150));
1359
1360        let mut node = Node::new("person", "1");
1361        node.properties.insert("name".to_string(), "Alice".to_string());
1362        node.properties.insert("age".to_string(), "30".to_string());
1363
1364        let result = person.validate_node(&node);
1365        assert!(result.is_valid());
1366
1367        let mut invalid_node = Node::new("person", "2");
1368        invalid_node.properties.insert("age".to_string(), "200".to_string());
1369
1370        let result = person.validate_node(&invalid_node);
1371        assert!(!result.is_valid());
1372        assert!(result.errors().len() >= 2); // missing required name + age out of range
1373    }
1374
1375    #[test]
1376    fn test_graph_schema_validation() {
1377        let person = NodeType::new("person")
1378            .field("name", StringField::new().required());
1379
1380        let knows = EdgeType::new("KNOWS")
1381            .from_node("person")
1382            .to_node("person")
1383            .no_self_loop();
1384
1385        let schema = GraphSchema::new("social")
1386            .node_type(person)
1387            .edge_type(knows);
1388
1389        let mut graph = ISONGraph::new("test");
1390        graph.add_node("person", "1", vec![("name", "Alice")]).unwrap();
1391        graph.add_node("person", "2", vec![("name", "Bob")]).unwrap();
1392        graph.add_edge("KNOWS", ("person", "1"), ("person", "2"), vec![]).unwrap();
1393
1394        let result = schema.validate(&graph);
1395        assert!(result.is_valid());
1396    }
1397
1398    #[test]
1399    fn test_self_loop_constraint() {
1400        let knows = EdgeType::new("KNOWS")
1401            .from_node("person")
1402            .to_node("person")
1403            .no_self_loop();
1404
1405        let schema = GraphSchema::new("social")
1406            .edge_type(knows);
1407
1408        let mut graph = ISONGraph::new("test");
1409        graph.add_node("person", "1", vec![]).unwrap();
1410        graph.add_edge("KNOWS", ("person", "1"), ("person", "1"), vec![]).unwrap();
1411
1412        let result = schema.validate(&graph);
1413        assert!(!result.is_valid());
1414        assert!(result.errors().iter().any(|e| e.code == ErrorCode::SelfLoop));
1415    }
1416
1417    #[test]
1418    fn test_orphan_constraint() {
1419        let schema = GraphSchema::new("social")
1420            .no_orphans();
1421
1422        let mut graph = ISONGraph::new("test");
1423        graph.add_node("person", "1", vec![]).unwrap();
1424
1425        let result = schema.validate(&graph);
1426        assert!(!result.is_valid());
1427        assert!(result.errors().iter().any(|e| e.code == ErrorCode::OrphanNode));
1428    }
1429
1430    #[test]
1431    fn test_ref_field_required() {
1432        let field = RefField::new().required();
1433
1434        // Missing value should fail
1435        let result = field.validate(None, "manager");
1436        assert!(!result.is_valid());
1437        assert_eq!(result.errors()[0].code, ErrorCode::RequiredField);
1438
1439        // Valid reference should pass
1440        let result = field.validate(Some(":person:1"), "manager");
1441        assert!(result.is_valid());
1442    }
1443
1444    #[test]
1445    fn test_ref_field_format() {
1446        let field = RefField::new();
1447
1448        // Invalid format - missing colon prefix
1449        let result = field.validate(Some("person:1"), "manager");
1450        assert!(!result.is_valid());
1451        assert_eq!(result.errors()[0].code, ErrorCode::InvalidType);
1452
1453        // Invalid format - missing second colon
1454        let result = field.validate(Some(":person"), "manager");
1455        assert!(!result.is_valid());
1456
1457        // Valid format
1458        let result = field.validate(Some(":person:1"), "manager");
1459        assert!(result.is_valid());
1460    }
1461
1462    #[test]
1463    fn test_ref_field_type_constraint() {
1464        let field = RefField::new().to_node("person");
1465
1466        // Wrong node type
1467        let result = field.validate(Some(":company:1"), "manager");
1468        assert!(!result.is_valid());
1469        assert_eq!(result.errors()[0].code, ErrorCode::RefWrongType);
1470
1471        // Correct node type
1472        let result = field.validate(Some(":person:1"), "manager");
1473        assert!(result.is_valid());
1474    }
1475}