Skip to main content

khive_query/
ast.rs

1//! Shared query AST for GQL/SPARQL parsing and SQL compilation.
2
3use std::collections::HashMap;
4
5/// A backend-independent SQL parameter emitted by the compiler.
6///
7/// See `crates/khive-query/docs/api/ast.md` for value and precision semantics.
8#[derive(Clone, Debug)]
9pub enum QueryValue {
10    Null,
11    Integer(i64),
12    Float(f64),
13    Text(String),
14    Blob(Vec<u8>),
15}
16
17/// A parsed query: pattern, predicates, projections, ordering, offset, and optional limit.
18#[derive(Debug, Clone)]
19pub struct GqlQuery {
20    /// Required first path; single-path queries leave `additional_patterns` empty.
21    pub pattern: MatchPattern,
22    /// Connected canonical paths following commas in GQL's MATCH clause.
23    pub additional_patterns: Vec<MatchPattern>,
24    pub where_clause: WhereExpr,
25    pub return_items: Vec<ReturnItem>,
26    /// Deduplicate requested result values after grouping and before pagination.
27    pub distinct: bool,
28    /// Caller ordering followed by the compiler's deterministic tie order.
29    ///
30    /// An empty vector uses identity/traversal order for ordinary queries,
31    /// and returned-value order for distinct or grouped queries.
32    pub order_by: Vec<OrderItem>,
33    /// Number of deterministically ordered matches to skip before returning rows.
34    ///
35    /// GQL supplies this through `SKIP`; SPARQL currently always sets it to zero.
36    pub offset: usize,
37    pub limit: Option<usize>,
38}
39
40impl GqlQuery {
41    /// Iterate every MATCH path in textual order, including the required first path.
42    pub fn patterns(&self) -> impl Iterator<Item = &MatchPattern> {
43        std::iter::once(&self.pattern).chain(self.additional_patterns.iter())
44    }
45
46    /// Mutably iterate every MATCH path in textual order.
47    pub fn patterns_mut(&mut self) -> impl Iterator<Item = &mut MatchPattern> {
48        std::iter::once(&mut self.pattern).chain(self.additional_patterns.iter_mut())
49    }
50}
51
52/// A WHERE expression tree that preserves AND/OR grouping.
53#[derive(Debug, Clone)]
54pub enum WhereExpr {
55    /// AND of two sub-expressions.
56    And(Box<WhereExpr>, Box<WhereExpr>),
57    /// OR of two sub-expressions.
58    Or(Box<WhereExpr>, Box<WhereExpr>),
59    /// A single scalar condition.
60    Condition(Condition),
61    /// Absence of one fixed canonical path correlated to outer node bindings.
62    /// Additional names are local to this block, not outer scalar conditions.
63    NotExists(MatchPattern),
64    /// Always-true — used when there is no WHERE clause.
65    True,
66}
67
68impl WhereExpr {
69    /// Iterate outer scalar conditions depth-first, skipping scoped absence paths.
70    pub fn conditions(&self) -> impl Iterator<Item = &Condition> {
71        let mut stack = vec![self];
72        let mut out: Vec<&Condition> = Vec::new();
73        while let Some(expr) = stack.pop() {
74            match expr {
75                WhereExpr::Condition(c) => out.push(c),
76                WhereExpr::And(l, r) | WhereExpr::Or(l, r) => {
77                    stack.push(r);
78                    stack.push(l);
79                }
80                WhereExpr::True | WhereExpr::NotExists(_) => {}
81            }
82        }
83        out.into_iter()
84    }
85
86    /// Apply `f` to each outer scalar condition, skipping scoped absence paths.
87    pub fn for_each_condition_mut(&mut self, f: &mut impl FnMut(&mut Condition)) {
88        match self {
89            WhereExpr::Condition(c) => f(c),
90            WhereExpr::And(l, r) | WhereExpr::Or(l, r) => {
91                l.for_each_condition_mut(f);
92                r.for_each_condition_mut(f);
93            }
94            WhereExpr::True | WhereExpr::NotExists(_) => {}
95        }
96    }
97
98    /// Return `true` only for the explicit always-true expression.
99    pub fn is_true(&self) -> bool {
100        matches!(self, WhereExpr::True)
101    }
102}
103
104/// A bound variable, property, typed JSON path, or binding count in RETURN.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum ReturnItem {
107    Variable(String),
108    Property(String, String),
109    /// A named path below node properties or canonical edge metadata.
110    Path(String, PropertyRef),
111    /// Count matched rows for a binding; a null zero-hop edge contributes zero.
112    Count(String),
113}
114
115impl ReturnItem {
116    /// Returns the variable name bound to this return item.
117    pub fn variable(&self) -> &str {
118        match self {
119            Self::Variable(v) | Self::Property(v, _) | Self::Path(v, _) | Self::Count(v) => v,
120        }
121    }
122}
123
124/// The MATCH pattern of a GQL query, as an alternating sequence of node and edge elements.
125#[derive(Debug, Clone)]
126pub struct MatchPattern {
127    pub elements: Vec<PatternElement>,
128}
129
130impl MatchPattern {
131    /// Iterate over the `NodePattern` elements in this MATCH pattern.
132    pub fn nodes(&self) -> impl Iterator<Item = &NodePattern> {
133        self.elements.iter().filter_map(|e| match e {
134            PatternElement::Node(n) => Some(n),
135            _ => None,
136        })
137    }
138
139    /// Iterate over the `EdgePattern` elements in this MATCH pattern.
140    pub fn edges(&self) -> impl Iterator<Item = &EdgePattern> {
141        self.elements.iter().filter_map(|e| match e {
142            PatternElement::Edge(e) => Some(e),
143            _ => None,
144        })
145    }
146
147    /// Returns whether any edge needs traversal rather than exactly one fixed hop.
148    pub fn has_variable_length(&self) -> bool {
149        self.edges().any(|e| e.min_hops != 1 || e.max_hops != 1)
150    }
151}
152
153/// A single element in the MATCH pattern -- either a node or an edge.
154#[derive(Debug, Clone)]
155pub enum PatternElement {
156    Node(NodePattern),
157    Edge(EdgePattern),
158}
159
160/// A node binding with optional kind, governed subtype, and property filters.
161#[derive(Debug, Clone)]
162pub struct NodePattern {
163    pub variable: Option<String>,
164    pub kind: Option<String>,
165    /// Governed subtype compiled against the dedicated `entity_type` column.
166    pub entity_type: Option<String>,
167    pub properties: HashMap<String, ConditionValue>,
168}
169
170/// An edge binding with relation alternatives, direction, and inclusive hop bounds.
171#[derive(Debug, Clone)]
172pub struct EdgePattern {
173    pub variable: Option<String>,
174    pub relations: Vec<String>,
175    pub direction: EdgeDirection,
176    pub min_hops: usize,
177    pub max_hops: usize,
178}
179
180/// Traversal direction for an edge in the MATCH pattern.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum EdgeDirection {
183    /// Outgoing only — `(a)-->(b)`.
184    Out,
185    /// Incoming only — `(a)<--(b)`.
186    In,
187    /// Either direction — `(a)--(b)`.
188    Both,
189}
190
191/// A field or JSON path referenced by a WHERE condition or ORDER BY term.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub enum PropertyRef {
194    /// A dedicated field on the bound substrate, such as `name` or `created_at`.
195    Field(String),
196    /// A path below the bound record's JSON `properties` object.
197    JsonPath(Vec<String>),
198    /// A path below a canonical edge's JSON `metadata` object.
199    MetadataPath(Vec<String>),
200}
201
202/// One validated field or JSON path in GQL's `ORDER BY` clause.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct OrderItem {
205    /// Binding whose value supplies this ordering term.
206    pub variable: String,
207    /// Dedicated scalar field or nonempty explicit JSON path.
208    pub property: PropertyRef,
209    /// Ascending or descending SQLite value order, without coercion.
210    pub direction: OrderDirection,
211}
212
213/// Direction of a caller-supplied ordering term.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum OrderDirection {
216    /// Ascending order, with null values first.
217    Asc,
218    /// Descending order, with null values last.
219    Desc,
220}
221
222/// A predicate in the WHERE clause: `variable.field op value` or
223/// `variable.properties.path op value`.
224#[derive(Debug, Clone)]
225pub struct Condition {
226    pub variable: String,
227    pub property: PropertyRef,
228    pub op: CompareOp,
229    pub value: ConditionValue,
230}
231
232/// Comparison operator used in WHERE clause conditions.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum CompareOp {
235    Eq,
236    Neq,
237    Gt,
238    Lt,
239    Gte,
240    Lte,
241    Like,
242    Contains,
243    StartsWith,
244    In,
245    IsNotNull,
246    IsNull,
247}
248
249/// A typed condition value; integer and decimal forms remain distinct.
250///
251/// See `crates/khive-query/docs/api/ast.md` for binding and precision details.
252#[derive(Debug, Clone, PartialEq)]
253pub enum ConditionValue {
254    String(String),
255    /// Exact `i64` literal whose source lexeme had no decimal point.
256    Integer(i64),
257    /// A float literal (decimal point present in the source lexeme).
258    Number(f64),
259    Bool(bool),
260    /// A list literal used by the `IN` operator.
261    List(Vec<ConditionValue>),
262    /// The operand marker for the operand-free `IS NOT NULL` operator.
263    Null,
264}