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