Skip to main content

ison_graph/
query.rs

1//! ISONQL - Pure Property Graph Query Language for ISONGraph (Rust)
2//!
3//! A declarative query language for property graph operations.
4//!
5//! # Supported Query Types
6//! - NODES: Select and filter nodes
7//! - EDGES: Select and filter edges
8//! - TRAVERSE: Graph traversal with patterns
9//! - PATH: Shortest path finding
10//! - COUNT: Count nodes matching criteria
11//! - SUM/AVG/MIN/MAX: Numeric aggregations
12//!
13//! # Example
14//!
15//! ```rust
16//! use ison_graph::{ISONGraph, query::{QueryEngine, QueryResult}};
17//!
18//! let mut graph = ISONGraph::new("social");
19//! graph.add_node("person", "alice", vec![("name", "Alice"), ("age", "30")]).unwrap();
20//! graph.add_node("person", "bob", vec![("name", "Bob"), ("age", "25")]).unwrap();
21//! graph.add_edge("KNOWS", ("person", "alice"), ("person", "bob"), vec![("since", "2020")]).unwrap();
22//!
23//! let engine = QueryEngine::new(&graph);
24//! let result = engine.execute("NODES person WHERE age > 25").unwrap();
25//! ```
26
27use std::collections::{HashMap, HashSet};
28use std::time::Instant;
29use crate::{ISONGraph, Node, Edge, NodeId, Direction, GraphError, Result};
30
31/// Query operators for conditions
32#[derive(Debug, Clone, PartialEq)]
33pub enum Operator {
34    Eq,
35    Ne,
36    Gt,
37    Ge,
38    Lt,
39    Le,
40    In,
41    NotIn,
42    Contains,
43    StartsWith,
44    EndsWith,
45    Matches,
46    Exists,
47    NotExists,
48}
49
50impl Operator {
51    fn from_str(s: &str) -> Option<Self> {
52        match s {
53            "=" | "==" => Some(Operator::Eq),
54            "!=" | "<>" => Some(Operator::Ne),
55            ">" => Some(Operator::Gt),
56            ">=" => Some(Operator::Ge),
57            "<" => Some(Operator::Lt),
58            "<=" => Some(Operator::Le),
59            _ => None,
60        }
61    }
62}
63
64/// Sort order for results
65#[derive(Debug, Clone, PartialEq)]
66pub enum SortOrder {
67    Asc,
68    Desc,
69}
70
71/// A query condition for filtering
72#[derive(Debug, Clone)]
73pub struct Condition {
74    pub field: String,
75    pub operator: Operator,
76    pub value: Value,
77}
78
79/// Value types in queries
80#[derive(Debug, Clone)]
81pub enum Value {
82    String(String),
83    Int(i64),
84    Float(f64),
85    Bool(bool),
86    Null,
87    List(Vec<Value>),
88}
89
90impl Value {
91    fn as_f64(&self) -> Option<f64> {
92        match self {
93            Value::Float(f) => Some(*f),
94            Value::Int(i) => Some(*i as f64),
95            _ => None,
96        }
97    }
98}
99
100impl Condition {
101    pub fn new(field: impl Into<String>, operator: Operator, value: Value) -> Self {
102        Self {
103            field: field.into(),
104            operator,
105            value,
106        }
107    }
108
109    /// Evaluate condition against properties
110    pub fn evaluate(&self, properties: &HashMap<String, String>) -> bool {
111        match self.operator {
112            Operator::Exists => properties.contains_key(&self.field),
113            Operator::NotExists => !properties.contains_key(&self.field),
114            _ => {
115                if let Some(prop_value) = properties.get(&self.field) {
116                    self.compare(prop_value)
117                } else {
118                    false
119                }
120            }
121        }
122    }
123
124    fn compare(&self, prop_value: &str) -> bool {
125        match &self.operator {
126            Operator::Eq => self.eq_compare(prop_value),
127            Operator::Ne => !self.eq_compare(prop_value),
128            Operator::Gt => self.numeric_compare(prop_value, |a, b| a > b),
129            Operator::Ge => self.numeric_compare(prop_value, |a, b| a >= b),
130            Operator::Lt => self.numeric_compare(prop_value, |a, b| a < b),
131            Operator::Le => self.numeric_compare(prop_value, |a, b| a <= b),
132            Operator::In => self.in_compare(prop_value, true),
133            Operator::NotIn => self.in_compare(prop_value, false),
134            Operator::Contains => {
135                if let Value::String(s) = &self.value {
136                    prop_value.contains(s.as_str())
137                } else {
138                    false
139                }
140            }
141            Operator::StartsWith => {
142                if let Value::String(s) = &self.value {
143                    prop_value.starts_with(s.as_str())
144                } else {
145                    false
146                }
147            }
148            Operator::EndsWith => {
149                if let Value::String(s) = &self.value {
150                    prop_value.ends_with(s.as_str())
151                } else {
152                    false
153                }
154            }
155            Operator::Matches => {
156                if let Value::String(pattern) = &self.value {
157                    regex::Regex::new(pattern)
158                        .map(|re| re.is_match(prop_value))
159                        .unwrap_or(false)
160                } else {
161                    false
162                }
163            }
164            _ => false,
165        }
166    }
167
168    fn eq_compare(&self, prop_value: &str) -> bool {
169        match &self.value {
170            Value::String(s) => prop_value == s,
171            Value::Int(i) => prop_value.parse::<i64>().ok() == Some(*i),
172            Value::Float(f) => prop_value.parse::<f64>().ok() == Some(*f),
173            Value::Bool(b) => prop_value.parse::<bool>().ok() == Some(*b),
174            Value::Null => prop_value.is_empty(),
175            _ => false,
176        }
177    }
178
179    fn numeric_compare<F>(&self, prop_value: &str, cmp: F) -> bool
180    where
181        F: Fn(f64, f64) -> bool,
182    {
183        let prop_num = prop_value.parse::<f64>().ok();
184        let val_num = self.value.as_f64();
185        match (prop_num, val_num) {
186            (Some(a), Some(b)) => cmp(a, b),
187            _ => false,
188        }
189    }
190
191    fn in_compare(&self, prop_value: &str, should_contain: bool) -> bool {
192        if let Value::List(list) = &self.value {
193            let found = list.iter().any(|v| {
194                if let Value::String(s) = v {
195                    prop_value == s
196                } else if let Value::Int(i) = v {
197                    prop_value.parse::<i64>().ok() == Some(*i)
198                } else {
199                    false
200                }
201            });
202            if should_contain { found } else { !found }
203        } else {
204            false
205        }
206    }
207}
208
209/// Traversal step in TRAVERSE query
210#[derive(Debug, Clone)]
211pub struct TraversalStep {
212    pub direction: Direction,
213    pub rel_type: String,
214    pub target_type: String,
215}
216
217/// Parsed query structure
218///
219/// WHERE conditions are stored as OR-groups of AND-ed conditions
220/// (`c1 AND c2 OR c3` parses as `[[c1, c2], [c3]]`): a row matches when
221/// every condition of at least one group matches. An empty list matches
222/// everything.
223#[derive(Debug, Clone)]
224pub struct ParsedQuery {
225    pub query_type: String,
226    pub node_type: Option<String>,
227    pub rel_type: Option<String>,
228    pub condition_groups: Vec<Vec<Condition>>,
229    pub order_by: Option<String>,
230    pub order_dir: SortOrder,
231    pub limit: Option<usize>,
232    pub offset: usize,
233    pub return_fields: Option<Vec<String>>,
234    pub start: Option<NodeId>,
235    pub target: Option<NodeId>,
236    pub source: Option<NodeId>,
237    pub pattern: Vec<TraversalStep>,
238    pub max_depth: Option<usize>,
239    pub max_hops: usize,
240    pub via: Option<String>,
241    pub property: Option<String>,
242}
243
244impl Default for ParsedQuery {
245    fn default() -> Self {
246        Self {
247            query_type: String::new(),
248            node_type: None,
249            rel_type: None,
250            condition_groups: Vec::new(),
251            order_by: None,
252            order_dir: SortOrder::Asc,
253            limit: None,
254            offset: 0,
255            return_fields: None,
256            start: None,
257            target: None,
258            source: None,
259            pattern: Vec::new(),
260            max_depth: None,
261            max_hops: 10,
262            via: None,
263            property: None,
264        }
265    }
266}
267
268/// Result of a query execution
269#[derive(Debug)]
270pub struct QueryResult {
271    pub data: Vec<QueryData>,
272    pub count: usize,
273    pub total_count: usize,
274    pub execution_time_ms: f64,
275    pub query: String,
276    pub query_type: String,
277}
278
279/// Query result data variants
280#[derive(Debug, Clone)]
281pub enum QueryData {
282    Node {
283        node_type: String,
284        id: String,
285        properties: HashMap<String, String>,
286    },
287    Edge {
288        rel_type: String,
289        source: NodeId,
290        target: NodeId,
291        properties: HashMap<String, String>,
292    },
293    NodeRef(NodeId),
294    Path {
295        nodes: Vec<NodeId>,
296        edges: Vec<EdgeData>,
297        length: usize,
298    },
299    Count(usize),
300    Aggregate(Option<f64>),
301    Fields(HashMap<String, String>),
302}
303
304#[derive(Debug, Clone)]
305pub struct EdgeData {
306    pub rel_type: String,
307    pub source: NodeId,
308    pub target: NodeId,
309}
310
311impl QueryResult {
312    /// Get first result
313    pub fn first(&self) -> Option<&QueryData> {
314        self.data.first()
315    }
316
317    /// Check if result is empty
318    pub fn is_empty(&self) -> bool {
319        self.data.is_empty()
320    }
321
322    /// Iterate over data
323    pub fn iter(&self) -> impl Iterator<Item = &QueryData> {
324        self.data.iter()
325    }
326}
327
328// =============================================================================
329// ISONQL Parser
330// =============================================================================
331
332/// Parser for ISONQL queries
333pub struct ISONQLParser {
334    tokens: Vec<String>,
335    pos: usize,
336}
337
338impl ISONQLParser {
339    pub fn new() -> Self {
340        Self {
341            tokens: Vec::new(),
342            pos: 0,
343        }
344    }
345
346    /// Parse an ISONQL query string
347    pub fn parse(&mut self, query: &str) -> Result<ParsedQuery> {
348        self.tokens = self.tokenize(query);
349        self.pos = 0;
350
351        if self.tokens.is_empty() {
352            return Err(GraphError::ParseError("Empty query".into()));
353        }
354
355        let keyword = self.tokens[0].to_uppercase();
356        match keyword.as_str() {
357            "NODES" => self.parse_nodes_query(),
358            "EDGES" => self.parse_edges_query(),
359            "TRAVERSE" => self.parse_traverse_query(),
360            "PATH" => self.parse_path_query(),
361            "COUNT" => self.parse_count_query(),
362            "SUM" | "AVG" | "MIN" | "MAX" => self.parse_aggregation_query(&keyword),
363            _ => Err(GraphError::ParseError(format!(
364                "Unknown query type: {}. Supported: NODES, EDGES, TRAVERSE, PATH, COUNT, SUM, AVG, MIN, MAX",
365                keyword
366            ))),
367        }
368    }
369
370    fn tokenize(&self, query: &str) -> Vec<String> {
371        let mut tokens = Vec::new();
372        let chars: Vec<char> = query.chars().collect();
373        let mut i = 0;
374
375        while i < chars.len() {
376            // Skip whitespace
377            if chars[i].is_whitespace() {
378                i += 1;
379                continue;
380            }
381
382            // String literals
383            if chars[i] == '"' || chars[i] == '\'' {
384                let quote = chars[i];
385                i += 1;
386                let start = i;
387                while i < chars.len() && chars[i] != quote {
388                    if chars[i] == '\\' && i + 1 < chars.len() {
389                        i += 2;
390                    } else {
391                        i += 1;
392                    }
393                }
394                tokens.push(chars[start..i].iter().collect());
395                i += 1;
396                continue;
397            }
398
399            // Multi-char operators
400            if i + 1 < chars.len() {
401                let two: String = chars[i..=i + 1].iter().collect();
402                if ["==", "!=", ">=", "<=", "<>", "->", "<-", "--"].contains(&two.as_str()) {
403                    tokens.push(two);
404                    i += 2;
405                    continue;
406                }
407            }
408
409            // Single-char operators
410            if "=<>!(),.".contains(chars[i]) {
411                tokens.push(chars[i].to_string());
412                i += 1;
413                continue;
414            }
415
416            // Node reference :type:id
417            if chars[i] == ':' {
418                let start = i;
419                i += 1;
420                while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == ':' || chars[i] == '_' || chars[i] == '-') {
421                    i += 1;
422                }
423                tokens.push(chars[start..i].iter().collect());
424                continue;
425            }
426
427            // Words (a ':' joins the word when immediately followed by an
428            // alphanumeric/underscore char, so `type:id` lexes as one token)
429            if chars[i].is_alphanumeric() || chars[i] == '_' {
430                let start = i;
431                while i < chars.len() {
432                    let c = chars[i];
433                    let joining_colon = c == ':'
434                        && i + 1 < chars.len()
435                        && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_');
436                    if c.is_alphanumeric() || c == '_' || c == '.' || c == '-' || joining_colon {
437                        i += 1;
438                    } else {
439                        break;
440                    }
441                }
442                tokens.push(chars[start..i].iter().collect());
443                continue;
444            }
445
446            i += 1;
447        }
448
449        tokens
450    }
451
452    fn current(&self) -> Option<&str> {
453        self.tokens.get(self.pos).map(|s| s.as_str())
454    }
455
456    fn advance(&mut self) -> Option<String> {
457        let token = self.tokens.get(self.pos).cloned();
458        self.pos += 1;
459        token
460    }
461
462    fn expect(&mut self, expected: &str) -> Result<String> {
463        let token = self.advance();
464        match token {
465            Some(t) if t.eq_ignore_ascii_case(expected) => Ok(t),
466            Some(t) => Err(GraphError::ParseError(format!("Expected '{}', got '{}'", expected, t))),
467            None => Err(GraphError::ParseError(format!("Expected '{}', got end of query", expected))),
468        }
469    }
470
471    fn match_any(&self, expected: &[&str]) -> bool {
472        if let Some(current) = self.current() {
473            expected.iter().any(|e| current.eq_ignore_ascii_case(e))
474        } else {
475            false
476        }
477    }
478
479    // -------------------------------------------------------------------------
480    // Query Parsers
481    // -------------------------------------------------------------------------
482
483    fn parse_nodes_query(&mut self) -> Result<ParsedQuery> {
484        self.advance(); // Skip 'NODES'
485        let mut query = ParsedQuery {
486            query_type: "NODES".into(),
487            ..Default::default()
488        };
489
490        // Node type (optional)
491        if self.current().is_some() && !self.match_any(&["WHERE", "ORDER", "LIMIT", "RETURN"]) {
492            let node_type = self.advance().unwrap();
493            query.node_type = Some(node_type);
494            if self.match_any(&["("]) {
495                self.advance();
496                let shorthand = self.parse_shorthand_conditions()?;
497                if !shorthand.is_empty() {
498                    query.condition_groups = vec![shorthand];
499                }
500            }
501        }
502
503        // WHERE clause
504        if self.match_any(&["WHERE"]) {
505            self.advance();
506            let where_groups = self.parse_conditions()?;
507            query.condition_groups = Self::and_combine(query.condition_groups, where_groups);
508        }
509
510        // ORDER BY clause
511        if self.match_any(&["ORDER"]) {
512            self.advance();
513            self.expect("BY")?;
514            query.order_by = self.advance();
515            if self.match_any(&["ASC", "DESC"]) {
516                let dir = self.advance().unwrap();
517                query.order_dir = if dir.eq_ignore_ascii_case("DESC") {
518                    SortOrder::Desc
519                } else {
520                    SortOrder::Asc
521                };
522            }
523        }
524
525        // LIMIT clause
526        if self.match_any(&["LIMIT"]) {
527            self.advance();
528            if let Some(n) = self.advance() {
529                query.limit = n.parse().ok();
530            }
531        }
532
533        // OFFSET clause
534        if self.match_any(&["OFFSET"]) {
535            self.advance();
536            if let Some(n) = self.advance() {
537                query.offset = n.parse().unwrap_or(0);
538            }
539        }
540
541        // RETURN clause
542        if self.match_any(&["RETURN"]) {
543            self.advance();
544            query.return_fields = Some(self.parse_field_list());
545        }
546
547        Ok(query)
548    }
549
550    fn parse_edges_query(&mut self) -> Result<ParsedQuery> {
551        self.advance(); // Skip 'EDGES'
552        let mut query = ParsedQuery {
553            query_type: "EDGES".into(),
554            ..Default::default()
555        };
556
557        // Edge type (optional)
558        if self.current().is_some() && !self.match_any(&["WHERE", "LIMIT"]) {
559            query.rel_type = self.advance();
560        }
561
562        // WHERE clause
563        if self.match_any(&["WHERE"]) {
564            self.advance();
565            query.condition_groups = self.parse_conditions()?;
566        }
567
568        // LIMIT clause
569        if self.match_any(&["LIMIT"]) {
570            self.advance();
571            if let Some(n) = self.advance() {
572                query.limit = n.parse().ok();
573            }
574        }
575
576        Ok(query)
577    }
578
579    fn parse_traverse_query(&mut self) -> Result<ParsedQuery> {
580        self.advance(); // Skip 'TRAVERSE'
581        let mut query = ParsedQuery {
582            query_type: "TRAVERSE".into(),
583            ..Default::default()
584        };
585
586        // Start node
587        if let Some(start_token) = self.advance() {
588            query.start = Some(self.parse_node_ref(&start_token)?);
589        }
590
591        // Parse traversal pattern
592        while self.match_any(&["->", "<-", "--"]) {
593            let direction = self.advance().unwrap();
594            let rel_type = self.advance().ok_or_else(|| {
595                GraphError::ParseError("Expected relationship type".into())
596            })?;
597
598            let mut target_type = "*".to_string();
599            let dir2 = if self.match_any(&["->", "<-", "--"]) {
600                let d = self.advance().unwrap();
601                if self.current().is_some() && !self.match_any(&["MAX", "LIMIT"]) {
602                    target_type = self.advance().unwrap();
603                }
604                d
605            } else {
606                direction.clone()
607            };
608
609            query.pattern.push(TraversalStep {
610                direction: self.direction_from_arrows(&direction, &dir2),
611                rel_type,
612                target_type,
613            });
614        }
615
616        // MAX depth
617        if self.match_any(&["MAX"]) {
618            self.advance();
619            if let Some(n) = self.advance() {
620                query.max_depth = n.parse().ok();
621            }
622        }
623
624        // LIMIT
625        if self.match_any(&["LIMIT"]) {
626            self.advance();
627            if let Some(n) = self.advance() {
628                query.limit = n.parse().ok();
629            }
630        }
631
632        Ok(query)
633    }
634
635    fn parse_path_query(&mut self) -> Result<ParsedQuery> {
636        self.advance(); // Skip 'PATH'
637        let mut query = ParsedQuery {
638            query_type: "PATH".into(),
639            ..Default::default()
640        };
641
642        // Source node
643        if let Some(source_token) = self.advance() {
644            query.source = Some(self.parse_node_ref(&source_token)?);
645        }
646
647        // TO keyword
648        self.expect("TO")?;
649
650        // Target node
651        if let Some(target_token) = self.advance() {
652            query.target = Some(self.parse_node_ref(&target_token)?);
653        }
654
655        // VIA
656        if self.match_any(&["VIA"]) {
657            self.advance();
658            query.via = self.advance();
659        }
660
661        // MAX hops
662        if self.match_any(&["MAX"]) {
663            self.advance();
664            if let Some(n) = self.advance() {
665                query.max_hops = n.parse().unwrap_or(10);
666            }
667        }
668
669        Ok(query)
670    }
671
672    fn parse_count_query(&mut self) -> Result<ParsedQuery> {
673        self.advance(); // Skip 'COUNT'
674        let mut query = ParsedQuery {
675            query_type: "COUNT".into(),
676            ..Default::default()
677        };
678
679        // Node type
680        if self.current().is_some() && !self.match_any(&["WHERE"]) {
681            query.node_type = self.advance();
682        }
683
684        // WHERE clause
685        if self.match_any(&["WHERE"]) {
686            self.advance();
687            query.condition_groups = self.parse_conditions()?;
688        }
689
690        Ok(query)
691    }
692
693    fn parse_aggregation_query(&mut self, agg_type: &str) -> Result<ParsedQuery> {
694        self.advance(); // Skip aggregation keyword
695        let mut query = ParsedQuery {
696            query_type: agg_type.to_uppercase(),
697            ..Default::default()
698        };
699
700        // type.property
701        if let Some(type_prop) = self.advance() {
702            if type_prop.contains('.') {
703                let parts: Vec<&str> = type_prop.splitn(2, '.').collect();
704                query.node_type = Some(parts[0].to_string());
705                query.property = Some(parts[1].to_string());
706            } else {
707                query.property = Some(type_prop);
708            }
709        }
710
711        // WHERE clause
712        if self.match_any(&["WHERE"]) {
713            self.advance();
714            query.condition_groups = self.parse_conditions()?;
715        }
716
717        Ok(query)
718    }
719
720    // -------------------------------------------------------------------------
721    // Condition Parsing
722    // -------------------------------------------------------------------------
723
724    /// Parse a WHERE condition sequence into OR-groups of AND-ed conditions
725    /// (AND binds tighter than OR): `a AND b OR c` -> `[[a, b], [c]]`.
726    fn parse_conditions(&mut self) -> Result<Vec<Vec<Condition>>> {
727        let mut groups: Vec<Vec<Condition>> = Vec::new();
728        let mut current_group: Vec<Condition> = Vec::new();
729
730        loop {
731            if let Some(cond) = self.parse_single_condition()? {
732                current_group.push(cond);
733            }
734
735            if self.match_any(&["AND"]) {
736                self.advance();
737            } else if self.match_any(&["OR"]) {
738                self.advance();
739                if !current_group.is_empty() {
740                    groups.push(std::mem::take(&mut current_group));
741                }
742            } else {
743                break;
744            }
745        }
746
747        if !current_group.is_empty() {
748            groups.push(current_group);
749        }
750
751        Ok(groups)
752    }
753
754    /// AND-combine two OR-group sets by distribution:
755    /// `(b1 OR b2) AND (o1 OR o2)` -> `b1 o1 OR b1 o2 OR b2 o1 OR b2 o2`.
756    fn and_combine(
757        base: Vec<Vec<Condition>>,
758        other: Vec<Vec<Condition>>,
759    ) -> Vec<Vec<Condition>> {
760        if base.is_empty() {
761            return other;
762        }
763        if other.is_empty() {
764            return base;
765        }
766
767        let mut result = Vec::with_capacity(base.len() * other.len());
768        for b in &base {
769            for o in &other {
770                let mut group = b.clone();
771                group.extend(o.iter().cloned());
772                result.push(group);
773            }
774        }
775        result
776    }
777
778    fn parse_single_condition(&mut self) -> Result<Option<Condition>> {
779        if self.current().is_none() {
780            return Ok(None);
781        }
782
783        // EXISTS / NOT EXISTS
784        if self.match_any(&["EXISTS"]) {
785            self.advance();
786            if let Some(field) = self.advance() {
787                return Ok(Some(Condition::new(field, Operator::Exists, Value::Null)));
788            }
789        }
790
791        if self.match_any(&["NOT"]) {
792            self.advance();
793            if self.match_any(&["EXISTS"]) {
794                self.advance();
795                if let Some(field) = self.advance() {
796                    return Ok(Some(Condition::new(field, Operator::NotExists, Value::Null)));
797                }
798            }
799        }
800
801        let field = match self.advance() {
802            Some(f) => f,
803            None => return Ok(None),
804        };
805
806        // Check if it's a keyword
807        let keywords = ["WHERE", "AND", "OR", "ORDER", "LIMIT", "OFFSET", "RETURN"];
808        if keywords.iter().any(|k| field.eq_ignore_ascii_case(k)) {
809            self.pos -= 1;
810            return Ok(None);
811        }
812
813        // Operator
814        let op_token = match self.current() {
815            Some(t) => t.to_string(),
816            None => return Ok(None),
817        };
818
819        let operator = if let Some(op) = Operator::from_str(&op_token) {
820            self.advance();
821            op
822        } else {
823            match op_token.to_uppercase().as_str() {
824                "IN" => { self.advance(); Operator::In }
825                "CONTAINS" => { self.advance(); Operator::Contains }
826                "STARTS_WITH" => { self.advance(); Operator::StartsWith }
827                "ENDS_WITH" => { self.advance(); Operator::EndsWith }
828                "MATCHES" => { self.advance(); Operator::Matches }
829                "EXISTS" => {
830                    self.advance();
831                    return Ok(Some(Condition::new(field, Operator::Exists, Value::Null)));
832                }
833                "NOT" => {
834                    let next_upper = self
835                        .tokens
836                        .get(self.pos + 1)
837                        .map(|t| t.to_uppercase())
838                        .unwrap_or_default();
839                    match next_upper.as_str() {
840                        "EXISTS" => {
841                            self.advance();
842                            self.advance();
843                            return Ok(Some(Condition::new(
844                                field,
845                                Operator::NotExists,
846                                Value::Null,
847                            )));
848                        }
849                        "IN" => {
850                            self.advance();
851                            self.advance();
852                            Operator::NotIn
853                        }
854                        _ => {
855                            return Err(GraphError::ParseError(format!(
856                                "Expected EXISTS or IN after NOT, got '{}'",
857                                next_upper
858                            )))
859                        }
860                    }
861                }
862                _ => {
863                    return Err(GraphError::ParseError(format!(
864                        "Unknown operator '{}' in condition",
865                        op_token
866                    )))
867                }
868            }
869        };
870
871        // Value
872        let value = self.parse_value()?;
873
874        Ok(Some(Condition::new(field, operator, value)))
875    }
876
877    fn parse_value(&mut self) -> Result<Value> {
878        if self.match_any(&["("]) {
879            self.advance();
880            let mut values = Vec::new();
881            while !self.match_any(&[")"]) {
882                if self.current().is_none() {
883                    return Err(GraphError::ParseError(
884                        "Unclosed list, expected ')'".into(),
885                    ));
886                }
887                let val = self.parse_single_value()?;
888                values.push(val);
889                if self.match_any(&[","]) {
890                    self.advance();
891                }
892            }
893            self.advance(); // Skip ')'
894            return Ok(Value::List(values));
895        }
896
897        self.parse_single_value()
898    }
899
900    fn parse_single_value(&mut self) -> Result<Value> {
901        let token = match self.advance() {
902            Some(t) => t,
903            None => return Ok(Value::Null),
904        };
905
906        let upper = token.to_uppercase();
907        match upper.as_str() {
908            "TRUE" => Ok(Value::Bool(true)),
909            "FALSE" => Ok(Value::Bool(false)),
910            "NULL" | "NONE" | "NIL" => Ok(Value::Null),
911            _ => {
912                // Try parsing as number
913                if let Ok(i) = token.parse::<i64>() {
914                    Ok(Value::Int(i))
915                } else if let Ok(f) = token.parse::<f64>() {
916                    Ok(Value::Float(f))
917                } else {
918                    Ok(Value::String(token))
919                }
920            }
921        }
922    }
923
924    fn parse_shorthand_conditions(&mut self) -> Result<Vec<Condition>> {
925        let mut conditions = Vec::new();
926
927        while !self.match_any(&[")"]) {
928            if let Some(field) = self.advance() {
929                if self.match_any(&["="]) {
930                    self.advance();
931                    let value = self.parse_single_value()?;
932                    conditions.push(Condition::new(field, Operator::Eq, value));
933                }
934            }
935            if self.match_any(&[","]) {
936                self.advance();
937            }
938        }
939
940        self.advance(); // Skip ')'
941        Ok(conditions)
942    }
943
944    fn parse_field_list(&mut self) -> Vec<String> {
945        let mut fields = Vec::new();
946        while self.current().is_some() {
947            if self.match_any(&["LIMIT", "OFFSET", "ORDER"]) {
948                break;
949            }
950            fields.push(self.advance().unwrap());
951            if self.match_any(&[","]) {
952                self.advance();
953            } else {
954                break;
955            }
956        }
957        fields
958    }
959
960    // -------------------------------------------------------------------------
961    // Helpers
962    // -------------------------------------------------------------------------
963
964    fn parse_node_ref(&self, token: &str) -> Result<NodeId> {
965        let token = token.trim_start_matches(':');
966        let parts: Vec<&str> = token.splitn(2, ':').collect();
967        if parts.len() >= 2 {
968            Ok(NodeId::new(parts[0], parts[1]))
969        } else {
970            Err(GraphError::ParseError(format!(
971                "Invalid node reference: {}. Expected format: type:id",
972                token
973            )))
974        }
975    }
976
977    fn direction_from_arrows(&self, arrow1: &str, arrow2: &str) -> Direction {
978        if arrow1 == "->" || arrow2 == "->" {
979            Direction::Out
980        } else if arrow1 == "<-" || arrow2 == "<-" {
981            Direction::In
982        } else {
983            Direction::Both
984        }
985    }
986}
987
988impl Default for ISONQLParser {
989    fn default() -> Self {
990        Self::new()
991    }
992}
993
994// =============================================================================
995// Query Engine
996// =============================================================================
997
998/// ISONQL Query Engine for ISONGraph
999pub struct QueryEngine<'a> {
1000    graph: &'a ISONGraph,
1001}
1002
1003impl<'a> QueryEngine<'a> {
1004    /// Create a new query engine for the given graph
1005    pub fn new(graph: &'a ISONGraph) -> Self {
1006        Self { graph }
1007    }
1008
1009    /// Execute an ISONQL query string
1010    pub fn execute(&self, query: &str) -> Result<QueryResult> {
1011        let start_time = Instant::now();
1012
1013        let mut parser = ISONQLParser::new();
1014        let parsed = parser.parse(query)?;
1015
1016        let (data, total) = match parsed.query_type.as_str() {
1017            "NODES" => self.execute_nodes(&parsed)?,
1018            "EDGES" => self.execute_edges(&parsed)?,
1019            "TRAVERSE" => self.execute_traverse(&parsed)?,
1020            "PATH" => self.execute_path(&parsed)?,
1021            "COUNT" => self.execute_count(&parsed)?,
1022            "SUM" | "AVG" | "MIN" | "MAX" => self.execute_aggregation(&parsed)?,
1023            _ => return Err(GraphError::ParseError(format!("Unknown query type: {}", parsed.query_type))),
1024        };
1025
1026        let execution_time = start_time.elapsed().as_secs_f64() * 1000.0;
1027
1028        Ok(QueryResult {
1029            count: data.len(),
1030            data,
1031            total_count: total,
1032            execution_time_ms: execution_time,
1033            query: query.to_string(),
1034            query_type: parsed.query_type,
1035        })
1036    }
1037
1038    // -------------------------------------------------------------------------
1039    // Query Executors
1040    // -------------------------------------------------------------------------
1041
1042    fn execute_nodes(&self, parsed: &ParsedQuery) -> Result<(Vec<QueryData>, usize)> {
1043        let node_type = parsed.node_type.as_deref();
1044        let condition_groups = &parsed.condition_groups;
1045
1046        // Get nodes
1047        let mut nodes: Vec<&Node> = if let Some(nt) = node_type {
1048            self.graph.nodes_of_type(nt).collect()
1049        } else {
1050            self.graph.nodes().collect()
1051        };
1052
1053        // Filter
1054        if !condition_groups.is_empty() {
1055            nodes.retain(|n| self.matches_conditions(&n.properties, condition_groups));
1056        }
1057
1058        let total = nodes.len();
1059
1060        // Sort
1061        if let Some(order_by) = &parsed.order_by {
1062            let desc = parsed.order_dir == SortOrder::Desc;
1063            nodes.sort_by(|a, b| {
1064                let a_val = a.properties.get(order_by).map(|s| s.as_str()).unwrap_or("");
1065                let b_val = b.properties.get(order_by).map(|s| s.as_str()).unwrap_or("");
1066
1067                // Try numeric comparison first
1068                if let (Ok(a_num), Ok(b_num)) = (a_val.parse::<f64>(), b_val.parse::<f64>()) {
1069                    if desc {
1070                        b_num.partial_cmp(&a_num).unwrap_or(std::cmp::Ordering::Equal)
1071                    } else {
1072                        a_num.partial_cmp(&b_num).unwrap_or(std::cmp::Ordering::Equal)
1073                    }
1074                } else if desc {
1075                    b_val.cmp(a_val)
1076                } else {
1077                    a_val.cmp(b_val)
1078                }
1079            });
1080        }
1081
1082        // Pagination
1083        let offset = parsed.offset;
1084        let nodes: Vec<&Node> = nodes.into_iter().skip(offset).collect();
1085        let nodes: Vec<&Node> = if let Some(limit) = parsed.limit {
1086            nodes.into_iter().take(limit).collect()
1087        } else {
1088            nodes
1089        };
1090
1091        // Format output
1092        let data: Vec<QueryData> = if let Some(fields) = &parsed.return_fields {
1093            nodes.iter().map(|n| {
1094                let mut props = HashMap::new();
1095                for f in fields {
1096                    if let Some(v) = n.properties.get(f) {
1097                        props.insert(f.clone(), v.clone());
1098                    }
1099                }
1100                QueryData::Fields(props)
1101            }).collect()
1102        } else {
1103            nodes.iter().map(|n| QueryData::Node {
1104                node_type: n.node_type.clone(),
1105                id: n.id.clone(),
1106                properties: n.properties.clone(),
1107            }).collect()
1108        };
1109
1110        Ok((data, total))
1111    }
1112
1113    fn execute_edges(&self, parsed: &ParsedQuery) -> Result<(Vec<QueryData>, usize)> {
1114        let rel_type = parsed.rel_type.as_deref();
1115        let condition_groups = &parsed.condition_groups;
1116
1117        // Get edges
1118        let mut edges: Vec<&Edge> = if let Some(rt) = rel_type {
1119            self.graph.edges_of_type(rt).collect()
1120        } else {
1121            self.graph.edge_types().iter()
1122                .flat_map(|rt| self.graph.edges_of_type(rt))
1123                .collect()
1124        };
1125
1126        // Filter
1127        if !condition_groups.is_empty() {
1128            edges.retain(|e| self.matches_conditions(&e.properties, condition_groups));
1129        }
1130
1131        let total = edges.len();
1132
1133        // Limit
1134        let edges: Vec<&Edge> = if let Some(limit) = parsed.limit {
1135            edges.into_iter().take(limit).collect()
1136        } else {
1137            edges
1138        };
1139
1140        let data: Vec<QueryData> = edges.iter().map(|e| QueryData::Edge {
1141            rel_type: e.rel_type.clone(),
1142            source: e.source.clone(),
1143            target: e.target.clone(),
1144            properties: e.properties.clone(),
1145        }).collect();
1146
1147        Ok((data, total))
1148    }
1149
1150    fn execute_traverse(&self, parsed: &ParsedQuery) -> Result<(Vec<QueryData>, usize)> {
1151        let start = parsed.start.as_ref().ok_or_else(|| {
1152            GraphError::ParseError("TRAVERSE requires start node".into())
1153        })?;
1154
1155        let mut current: HashSet<String> = HashSet::new();
1156        current.insert(start.to_key());
1157        let mut visited: HashSet<String> = HashSet::new();
1158        visited.insert(start.to_key());
1159        let mut node_map: HashMap<String, NodeId> = HashMap::new();
1160        node_map.insert(start.to_key(), start.clone());
1161
1162        for step in &parsed.pattern {
1163            let mut next_level: HashSet<String> = HashSet::new();
1164            let mut next_map: HashMap<String, NodeId> = HashMap::new();
1165
1166            for key in &current {
1167                if let Some(node_id) = node_map.get(key) {
1168                    let neighbors = self.graph.neighbors(
1169                        &node_id.as_ref(),
1170                        Some(&step.rel_type),
1171                        step.direction,
1172                    );
1173                    for neighbor in neighbors {
1174                        let neighbor_key = neighbor.to_key();
1175                        if !visited.contains(&neighbor_key)
1176                            && (step.target_type == "*" || neighbor.node_type == step.target_type)
1177                        {
1178                            next_level.insert(neighbor_key.clone());
1179                            next_map.insert(neighbor_key, neighbor);
1180                        }
1181                    }
1182                }
1183            }
1184
1185            for (k, v) in next_map {
1186                visited.insert(k.clone());
1187                node_map.insert(k, v);
1188            }
1189            current = next_level;
1190
1191            if current.is_empty() {
1192                break;
1193            }
1194        }
1195
1196        // Apply max_depth
1197        if let Some(max_depth) = parsed.max_depth {
1198            if max_depth > parsed.pattern.len() {
1199                let remaining = max_depth - parsed.pattern.len();
1200                let last_rel = parsed.pattern.last().map(|s| s.rel_type.as_str());
1201                let last_dir = parsed.pattern.last().map(|s| s.direction).unwrap_or(Direction::Out);
1202
1203                for _ in 0..remaining {
1204                    let mut next_level: HashSet<String> = HashSet::new();
1205                    let mut next_map: HashMap<String, NodeId> = HashMap::new();
1206
1207                    for key in &current {
1208                        if let Some(node_id) = node_map.get(key) {
1209                            let neighbors = self.graph.neighbors(
1210                                &node_id.as_ref(),
1211                                last_rel,
1212                                last_dir,
1213                            );
1214                            for neighbor in neighbors {
1215                                let neighbor_key = neighbor.to_key();
1216                                if !visited.contains(&neighbor_key) {
1217                                    next_level.insert(neighbor_key.clone());
1218                                    next_map.insert(neighbor_key, neighbor);
1219                                }
1220                            }
1221                        }
1222                    }
1223
1224                    for (k, v) in next_map {
1225                        visited.insert(k.clone());
1226                        current.insert(k.clone());
1227                        node_map.insert(k, v);
1228                    }
1229
1230                    if next_level.is_empty() {
1231                        break;
1232                    }
1233                }
1234            }
1235        }
1236
1237        let mut result: Vec<NodeId> = current.iter()
1238            .filter_map(|k| node_map.get(k).cloned())
1239            .collect();
1240
1241        let total = result.len();
1242
1243        if let Some(limit) = parsed.limit {
1244            result.truncate(limit);
1245        }
1246
1247        let data: Vec<QueryData> = result.into_iter()
1248            .map(QueryData::NodeRef)
1249            .collect();
1250
1251        Ok((data, total))
1252    }
1253
1254    fn execute_path(&self, parsed: &ParsedQuery) -> Result<(Vec<QueryData>, usize)> {
1255        let source = parsed.source.as_ref().ok_or_else(|| {
1256            GraphError::ParseError("PATH requires source node".into())
1257        })?;
1258        let target = parsed.target.as_ref().ok_or_else(|| {
1259            GraphError::ParseError("PATH requires target node".into())
1260        })?;
1261
1262        let path = self.graph.shortest_path(
1263            &source.as_ref(),
1264            &target.as_ref(),
1265            parsed.via.as_deref(),
1266            parsed.max_hops,
1267            Direction::Out,
1268        );
1269
1270        if let Some(path) = path {
1271            let length = path.length();
1272            let edges: Vec<EdgeData> = path.edges.iter().map(|e| EdgeData {
1273                rel_type: e.rel_type.clone(),
1274                source: e.source.clone(),
1275                target: e.target.clone(),
1276            }).collect();
1277
1278            let data = vec![QueryData::Path {
1279                nodes: path.nodes,
1280                edges,
1281                length,
1282            }];
1283            Ok((data, 1))
1284        } else {
1285            Ok((vec![], 0))
1286        }
1287    }
1288
1289    fn execute_count(&self, parsed: &ParsedQuery) -> Result<(Vec<QueryData>, usize)> {
1290        let node_type = parsed.node_type.as_deref();
1291        let condition_groups = &parsed.condition_groups;
1292
1293        let mut nodes: Vec<&Node> = if let Some(nt) = node_type {
1294            self.graph.nodes_of_type(nt).collect()
1295        } else {
1296            self.graph.nodes().collect()
1297        };
1298
1299        if !condition_groups.is_empty() {
1300            nodes.retain(|n| self.matches_conditions(&n.properties, condition_groups));
1301        }
1302
1303        let count = nodes.len();
1304        Ok((vec![QueryData::Count(count)], count))
1305    }
1306
1307    fn execute_aggregation(&self, parsed: &ParsedQuery) -> Result<(Vec<QueryData>, usize)> {
1308        let node_type = parsed.node_type.as_deref();
1309        let prop = parsed.property.as_ref().ok_or_else(|| {
1310            GraphError::ParseError("Aggregation requires property".into())
1311        })?;
1312        let condition_groups = &parsed.condition_groups;
1313
1314        let mut nodes: Vec<&Node> = if let Some(nt) = node_type {
1315            self.graph.nodes_of_type(nt).collect()
1316        } else {
1317            self.graph.nodes().collect()
1318        };
1319
1320        if !condition_groups.is_empty() {
1321            nodes.retain(|n| self.matches_conditions(&n.properties, condition_groups));
1322        }
1323
1324        // Extract numeric values
1325        let values: Vec<f64> = nodes.iter()
1326            .filter_map(|n| n.properties.get(prop))
1327            .filter_map(|v| v.parse::<f64>().ok())
1328            .collect();
1329
1330        if values.is_empty() {
1331            return Ok((vec![QueryData::Aggregate(None)], 0));
1332        }
1333
1334        let result = match parsed.query_type.as_str() {
1335            "SUM" => values.iter().sum(),
1336            "AVG" => values.iter().sum::<f64>() / values.len() as f64,
1337            "MIN" => values.iter().cloned().fold(f64::INFINITY, f64::min),
1338            "MAX" => values.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
1339            _ => return Ok((vec![QueryData::Aggregate(None)], 0)),
1340        };
1341
1342        Ok((vec![QueryData::Aggregate(Some(result))], values.len()))
1343    }
1344
1345    /// A row matches when every condition of at least one OR-group matches.
1346    /// An empty group list matches everything.
1347    fn matches_conditions(
1348        &self,
1349        properties: &HashMap<String, String>,
1350        condition_groups: &[Vec<Condition>],
1351    ) -> bool {
1352        condition_groups.is_empty()
1353            || condition_groups
1354                .iter()
1355                .any(|group| group.iter().all(|c| c.evaluate(properties)))
1356    }
1357}
1358
1359// =============================================================================
1360// Fluent Query Builder
1361// =============================================================================
1362
1363/// Fluent API for building node queries
1364pub struct QueryBuilder<'a> {
1365    engine: &'a QueryEngine<'a>,
1366    node_type: String,
1367    conditions: Vec<Condition>,
1368    order_by: Option<String>,
1369    order_dir: SortOrder,
1370    limit: Option<usize>,
1371    offset: usize,
1372    fields: Option<Vec<String>>,
1373}
1374
1375impl<'a> QueryBuilder<'a> {
1376    pub fn new(engine: &'a QueryEngine<'a>, node_type: impl Into<String>) -> Self {
1377        Self {
1378            engine,
1379            node_type: node_type.into(),
1380            conditions: Vec::new(),
1381            order_by: None,
1382            order_dir: SortOrder::Asc,
1383            limit: None,
1384            offset: 0,
1385            fields: None,
1386        }
1387    }
1388
1389    /// Add a WHERE condition
1390    pub fn where_cond(mut self, field: impl Into<String>, op: &str, value: impl Into<String>) -> Self {
1391        let operator = match op {
1392            "=" | "==" => Operator::Eq,
1393            "!=" | "<>" => Operator::Ne,
1394            ">" => Operator::Gt,
1395            ">=" => Operator::Ge,
1396            "<" => Operator::Lt,
1397            "<=" => Operator::Le,
1398            _ => Operator::Eq,
1399        };
1400        self.conditions.push(Condition::new(field, operator, Value::String(value.into())));
1401        self
1402    }
1403
1404    /// Add numeric WHERE condition
1405    pub fn where_num(mut self, field: impl Into<String>, op: &str, value: i64) -> Self {
1406        let operator = match op {
1407            "=" | "==" => Operator::Eq,
1408            "!=" | "<>" => Operator::Ne,
1409            ">" => Operator::Gt,
1410            ">=" => Operator::Ge,
1411            "<" => Operator::Lt,
1412            "<=" => Operator::Le,
1413            _ => Operator::Eq,
1414        };
1415        self.conditions.push(Condition::new(field, operator, Value::Int(value)));
1416        self
1417    }
1418
1419    /// Set ORDER BY clause
1420    pub fn order_by(mut self, field: impl Into<String>, direction: &str) -> Self {
1421        self.order_by = Some(field.into());
1422        self.order_dir = if direction.eq_ignore_ascii_case("DESC") {
1423            SortOrder::Desc
1424        } else {
1425            SortOrder::Asc
1426        };
1427        self
1428    }
1429
1430    /// Set LIMIT
1431    pub fn limit(mut self, n: usize) -> Self {
1432        self.limit = Some(n);
1433        self
1434    }
1435
1436    /// Set OFFSET
1437    pub fn offset(mut self, n: usize) -> Self {
1438        self.offset = n;
1439        self
1440    }
1441
1442    /// Set fields to return
1443    pub fn return_fields(mut self, fields: Vec<&str>) -> Self {
1444        self.fields = Some(fields.into_iter().map(String::from).collect());
1445        self
1446    }
1447
1448    /// Execute the built query
1449    pub fn execute(self) -> Result<QueryResult> {
1450        let condition_groups = if self.conditions.is_empty() {
1451            Vec::new()
1452        } else {
1453            vec![self.conditions]
1454        };
1455        let parsed = ParsedQuery {
1456            query_type: "NODES".into(),
1457            node_type: Some(self.node_type.clone()),
1458            condition_groups,
1459            order_by: self.order_by,
1460            order_dir: self.order_dir,
1461            limit: self.limit,
1462            offset: self.offset,
1463            return_fields: self.fields,
1464            ..Default::default()
1465        };
1466
1467        let start_time = Instant::now();
1468        let (data, total) = self.engine.execute_nodes(&parsed)?;
1469        let execution_time = start_time.elapsed().as_secs_f64() * 1000.0;
1470
1471        Ok(QueryResult {
1472            count: data.len(),
1473            data,
1474            total_count: total,
1475            execution_time_ms: execution_time,
1476            query: format!("NODES {}", self.node_type),
1477            query_type: "NODES".into(),
1478        })
1479    }
1480
1481    /// Execute count query
1482    pub fn count(self) -> Result<usize> {
1483        let condition_groups = if self.conditions.is_empty() {
1484            Vec::new()
1485        } else {
1486            vec![self.conditions]
1487        };
1488        let parsed = ParsedQuery {
1489            query_type: "COUNT".into(),
1490            node_type: Some(self.node_type),
1491            condition_groups,
1492            ..Default::default()
1493        };
1494
1495        let (data, _) = self.engine.execute_count(&parsed)?;
1496        match data.first() {
1497            Some(QueryData::Count(n)) => Ok(*n),
1498            _ => Ok(0),
1499        }
1500    }
1501}
1502
1503impl<'a> QueryEngine<'a> {
1504    /// Start a fluent query for nodes of a given type
1505    pub fn match_nodes(&'a self, node_type: impl Into<String>) -> QueryBuilder<'a> {
1506        QueryBuilder::new(self, node_type)
1507    }
1508}
1509
1510#[cfg(test)]
1511mod tests {
1512    use super::*;
1513
1514    fn create_test_graph() -> ISONGraph {
1515        let mut graph = ISONGraph::new("test");
1516        graph.add_node("person", "1", vec![("name", "Alice"), ("age", "30"), ("city", "NYC")]).unwrap();
1517        graph.add_node("person", "2", vec![("name", "Bob"), ("age", "25"), ("city", "LA")]).unwrap();
1518        graph.add_node("person", "3", vec![("name", "Charlie"), ("age", "35"), ("city", "NYC")]).unwrap();
1519        graph.add_edge("KNOWS", ("person", "1"), ("person", "2"), vec![("since", "2020")]).unwrap();
1520        graph.add_edge("KNOWS", ("person", "2"), ("person", "3"), vec![("since", "2021")]).unwrap();
1521        graph
1522    }
1523
1524    #[test]
1525    fn test_parse_nodes_query() {
1526        let mut parser = ISONQLParser::new();
1527        let result = parser.parse("NODES person").unwrap();
1528        assert_eq!(result.query_type, "NODES");
1529        assert_eq!(result.node_type, Some("person".into()));
1530    }
1531
1532    #[test]
1533    fn test_parse_nodes_with_where() {
1534        let mut parser = ISONQLParser::new();
1535        let result = parser.parse("NODES person WHERE age > 25").unwrap();
1536        assert_eq!(result.condition_groups.len(), 1);
1537        assert_eq!(result.condition_groups[0].len(), 1);
1538        assert_eq!(result.condition_groups[0][0].field, "age");
1539    }
1540
1541    #[test]
1542    fn test_parse_where_or_groups() {
1543        let mut parser = ISONQLParser::new();
1544        // AND binds tighter than OR: (city=NYC AND age>30) OR (city=LA)
1545        let result = parser
1546            .parse("NODES person WHERE city = NYC AND age > 30 OR city = LA")
1547            .unwrap();
1548        assert_eq!(result.condition_groups.len(), 2);
1549        assert_eq!(result.condition_groups[0].len(), 2);
1550        assert_eq!(result.condition_groups[0][0].field, "city");
1551        assert_eq!(result.condition_groups[0][1].field, "age");
1552        assert_eq!(result.condition_groups[1].len(), 1);
1553        assert_eq!(result.condition_groups[1][0].field, "city");
1554    }
1555
1556    #[test]
1557    fn test_execute_nodes() {
1558        let graph = create_test_graph();
1559        let engine = QueryEngine::new(&graph);
1560        let result = engine.execute("NODES person").unwrap();
1561        assert_eq!(result.count, 3);
1562    }
1563
1564    #[test]
1565    fn test_execute_nodes_with_where() {
1566        let graph = create_test_graph();
1567        let engine = QueryEngine::new(&graph);
1568        let result = engine.execute("NODES person WHERE age > 25").unwrap();
1569        assert_eq!(result.count, 2);
1570    }
1571
1572    #[test]
1573    fn test_execute_nodes_with_or() {
1574        let graph = create_test_graph();
1575        let engine = QueryEngine::new(&graph);
1576        // Alice (NYC), Charlie (NYC) OR Bob (LA) -> all three
1577        let result = engine
1578            .execute("NODES person WHERE city = NYC OR city = LA")
1579            .unwrap();
1580        assert_eq!(result.count, 3);
1581    }
1582
1583    #[test]
1584    fn test_execute_or_with_and_precedence() {
1585        let graph = create_test_graph();
1586        let engine = QueryEngine::new(&graph);
1587        // (city=NYC AND age>30) -> Charlie; OR city=LA -> Bob => 2
1588        let result = engine
1589            .execute("NODES person WHERE city = NYC AND age > 30 OR city = LA")
1590            .unwrap();
1591        assert_eq!(result.count, 2);
1592        // No match on either side
1593        let result = engine
1594            .execute("NODES person WHERE city = SF OR age > 100")
1595            .unwrap();
1596        assert_eq!(result.count, 0);
1597    }
1598
1599    #[test]
1600    fn test_execute_count_with_or() {
1601        let graph = create_test_graph();
1602        let engine = QueryEngine::new(&graph);
1603        let result = engine
1604            .execute("COUNT person WHERE age < 26 OR age > 34")
1605            .unwrap();
1606        match result.first() {
1607            Some(QueryData::Count(n)) => assert_eq!(*n, 2), // Bob (25), Charlie (35)
1608            _ => panic!("Expected count result"),
1609        }
1610    }
1611
1612    #[test]
1613    fn test_execute_edges() {
1614        let graph = create_test_graph();
1615        let engine = QueryEngine::new(&graph);
1616        let result = engine.execute("EDGES KNOWS").unwrap();
1617        assert_eq!(result.count, 2);
1618    }
1619
1620    #[test]
1621    fn test_execute_count() {
1622        let graph = create_test_graph();
1623        let engine = QueryEngine::new(&graph);
1624        let result = engine.execute("COUNT person").unwrap();
1625        match result.first() {
1626            Some(QueryData::Count(n)) => assert_eq!(*n, 3),
1627            _ => panic!("Expected count result"),
1628        }
1629    }
1630
1631    #[test]
1632    fn test_execute_traverse() {
1633        let graph = create_test_graph();
1634        let engine = QueryEngine::new(&graph);
1635        let result = engine.execute("TRAVERSE person:1 -> KNOWS -> person").unwrap();
1636        assert!(result.count >= 1);
1637    }
1638
1639    #[test]
1640    fn test_execute_path() {
1641        let graph = create_test_graph();
1642        let engine = QueryEngine::new(&graph);
1643        let result = engine.execute("PATH person:1 TO person:3 VIA KNOWS").unwrap();
1644        assert_eq!(result.count, 1);
1645    }
1646
1647    #[test]
1648    fn test_fluent_query() {
1649        let graph = create_test_graph();
1650        let engine = QueryEngine::new(&graph);
1651        let result = engine.match_nodes("person")
1652            .where_num("age", ">", 25)
1653            .order_by("age", "ASC")
1654            .limit(2)
1655            .execute()
1656            .unwrap();
1657        assert!(result.count <= 2);
1658    }
1659
1660    #[test]
1661    fn test_condition_evaluation() {
1662        let mut props = HashMap::new();
1663        props.insert("age".into(), "30".into());
1664        props.insert("name".into(), "Alice".into());
1665
1666        let cond = Condition::new("age", Operator::Gt, Value::Int(25));
1667        assert!(cond.evaluate(&props));
1668
1669        let cond = Condition::new("name", Operator::Eq, Value::String("Alice".into()));
1670        assert!(cond.evaluate(&props));
1671
1672        let cond = Condition::new("name", Operator::Contains, Value::String("lic".into()));
1673        assert!(cond.evaluate(&props));
1674    }
1675
1676    #[test]
1677    fn test_exists_postfix_and_not_in() {
1678        let graph = create_test_graph();
1679        let mut extra = graph;
1680        extra.add_node("person", "4", vec![("name", "Dave")]).unwrap();
1681        let engine = QueryEngine::new(&extra);
1682
1683        let r = engine.execute("NODES person WHERE city EXISTS").unwrap();
1684        assert_eq!(r.count, 3);
1685
1686        let r = engine.execute("NODES person WHERE city NOT EXISTS").unwrap();
1687        assert_eq!(r.count, 1);
1688
1689        let r = engine.execute("NODES person WHERE city NOT IN ('NYC')").unwrap();
1690        assert_eq!(r.count, 1);
1691    }
1692
1693    #[test]
1694    fn test_unknown_operator_errors() {
1695        let graph = create_test_graph();
1696        let engine = QueryEngine::new(&graph);
1697        assert!(engine.execute("NODES person WHERE name LIKE 'A'").is_err());
1698    }
1699
1700    #[test]
1701    fn test_unclosed_list_errors() {
1702        let graph = create_test_graph();
1703        let engine = QueryEngine::new(&graph);
1704        assert!(engine.execute("NODES person WHERE city IN ('NYC', 'LA'").is_err());
1705    }
1706}