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