Skip to main content

zero_client/ast/
mod.rs

1//! The ZQL abstract syntax tree (`packages/zero-protocol/src/ast.ts`).
2
3mod coding;
4mod normalize;
5pub mod strict;
6
7pub(crate) use coding::is_homogeneous;
8pub(crate) use normalize::cmp_related;
9pub use normalize::normalize_condition;
10
11use crate::json::{Object, Value};
12
13/// A query: a table, its filters, relationships, order, and bounds.
14#[derive(Clone, Debug, PartialEq, Default)]
15pub struct Ast {
16    pub schema: Option<String>,
17    pub table: String,
18    /// Set on subqueries, to tell apart two subqueries of the same table.
19    pub alias: Option<String>,
20    pub where_: Option<Condition>,
21    pub related: Option<Vec<CorrelatedSubquery>>,
22    pub start: Option<Bound>,
23    pub limit: Option<f64>,
24    pub order_by: Option<Vec<OrderPart>>,
25    /// Reduces the query to one aggregate over the rows left after `where`,
26    /// `start`, and `limit`; with `group_by`, to one per group.
27    pub aggregate: Option<Aggregate>,
28    /// Groups the rows that pass `where` by these columns: alone a
29    /// `SELECT DISTINCT` of them, with `aggregate` that aggregate per group.
30    pub group_by: Option<Vec<String>>,
31}
32
33impl Ast {
34    pub fn new(table: impl Into<String>) -> Self {
35        Ast {
36            table: table.into(),
37            ..Ast::default()
38        }
39    }
40}
41
42macro_rules! string_enum {
43    ($(#[$m:meta])* $name:ident { $($variant:ident = $s:literal),* $(,)? }) => {
44        $(#[$m])*
45        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
46        pub enum $name { $(#[doc = concat!("`", $s, "`")] $variant),* }
47
48        impl $name {
49            /// Every value, in declaration order.
50            pub const ALL: &[$name] = &[$($name::$variant),*];
51
52            /// The value as JS writes it.
53            pub fn as_str(self) -> &'static str {
54                match self { $($name::$variant => $s),* }
55            }
56
57            /// The value JS writes as `s`, if any.
58            pub fn parse(s: &str) -> Option<$name> {
59                match s { $($s => Some($name::$variant),)* _ => None }
60            }
61        }
62    };
63}
64pub(crate) use string_enum;
65
66string_enum!(
67    /// An aggregate function (`AggregateFunction`).
68    AggregateFunction { Count = "count", Sum = "sum", Avg = "avg", Min = "min", Max = "max" }
69);
70
71string_enum!(System { Permissions = "permissions", Client = "client", Test = "test" });
72
73string_enum!(Direction { Asc = "asc", Desc = "desc" });
74
75string_enum!(SimpleOperator {
76    Eq = "=",
77    Ne = "!=",
78    Is = "IS",
79    IsNot = "IS NOT",
80    Lt = "<",
81    Gt = ">",
82    Le = "<=",
83    Ge = ">=",
84    Like = "LIKE",
85    NotLike = "NOT LIKE",
86    Ilike = "ILIKE",
87    NotIlike = "NOT ILIKE",
88    In = "IN",
89    NotIn = "NOT IN",
90});
91
92string_enum!(CorrelatedSubqueryOperator { Exists = "EXISTS", NotExists = "NOT EXISTS" });
93
94string_enum!(Anchor { AuthData = "authData", PreMutationRow = "preMutationRow" });
95
96/// One step of a JSON path: an object key or an array index.
97#[derive(Clone, Debug, PartialEq, Eq, Hash)]
98pub enum JsonPathSegment {
99    Key(String),
100    Index(u32),
101}
102
103impl JsonPathSegment {
104    pub fn to_json(&self) -> Value {
105        match self {
106            JsonPathSegment::Key(k) => Value::String(k.clone()),
107            JsonPathSegment::Index(i) => Value::Number(f64::from(*i)),
108        }
109    }
110}
111
112/// `MAX_JSON_PATH_INDEX`: the largest array index a path may hold.
113pub const MAX_JSON_PATH_INDEX: u32 = i32::MAX as u32;
114
115/// An aggregate of a query or a relationship (`Aggregate`).
116#[derive(Clone, Debug, PartialEq)]
117pub struct Aggregate {
118    pub fn_: AggregateFunction,
119    /// The column to aggregate; `None` for `count`.
120    pub field: Option<String>,
121    /// A path into `field`, then a `json` column, to a scalar leaf.
122    pub path: Option<Vec<JsonPathSegment>>,
123    /// For `count`: counts the distinct combinations of these columns.
124    pub distinct: Option<Vec<String>>,
125}
126
127impl Aggregate {
128    pub fn new(fn_: AggregateFunction) -> Self {
129        Aggregate {
130            fn_,
131            field: None,
132            path: None,
133            distinct: None,
134        }
135    }
136}
137
138#[derive(Clone, Debug, PartialEq)]
139pub struct Bound {
140    /// The cursor's columns: those the query orders by.
141    pub row: Object,
142    pub exclusive: bool,
143}
144
145#[derive(Clone, Debug, PartialEq)]
146pub struct OrderPart {
147    pub field: String,
148    pub direction: Direction,
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub enum StaticField {
153    Single(String),
154    Path(Vec<String>),
155}
156
157impl StaticField {
158    pub fn to_json(&self) -> Value {
159        match self {
160            StaticField::Single(s) => Value::String(s.clone()),
161            StaticField::Path(p) => crate::decode::strings_json(p),
162        }
163    }
164}
165
166/// One side of a simple condition. A literal is a string, number, boolean,
167/// null, or an array of strings, numbers, and booleans.
168#[derive(Clone, Debug, PartialEq)]
169pub enum ValuePosition {
170    Literal(Value),
171    Column(String),
172    /// A value inside the `json` column `column`, at `path`.
173    Json {
174        column: String,
175        path: Vec<JsonPathSegment>,
176    },
177    Static {
178        anchor: Anchor,
179        field: StaticField,
180    },
181}
182
183#[derive(Clone, Debug, PartialEq)]
184pub enum Condition {
185    Simple {
186        op: SimpleOperator,
187        left: ValuePosition,
188        right: ValuePosition,
189    },
190    And(Vec<Condition>),
191    Or(Vec<Condition>),
192    CorrelatedSubquery {
193        related: CorrelatedSubquery,
194        op: CorrelatedSubqueryOperator,
195        flip: Option<bool>,
196        scalar: Option<bool>,
197    },
198}
199
200impl Condition {
201    /// The conditions of a conjunction or disjunction.
202    pub fn conditions(&self) -> Option<&[Condition]> {
203        match self {
204            Condition::And(c) | Condition::Or(c) => Some(c),
205            _ => None,
206        }
207    }
208}
209
210#[derive(Clone, Debug, PartialEq)]
211pub struct Correlation {
212    pub parent_field: Vec<String>,
213    pub child_field: Vec<String>,
214}
215
216#[derive(Clone, Debug, PartialEq)]
217pub struct CorrelatedSubquery {
218    pub correlation: Correlation,
219    pub subquery: Box<Ast>,
220    pub system: Option<System>,
221    /// Hidden hops (junction tables) are left out of the output view; their
222    /// children are not.
223    pub hidden: Option<bool>,
224    /// Reduces the subquery to one aggregate per parent row.
225    pub aggregate: Option<Aggregate>,
226}
227
228/// `jsonValueAtPath`: the value at `path` in `value`, strictly: a key reads
229/// an object's own key and an index an array's element. Any other step, and
230/// a missing value, is null.
231pub fn json_value_at<'a>(path: &[JsonPathSegment], value: Option<&'a Value>) -> &'a Value {
232    static NULL: Value = Value::Null;
233    let mut v = value.unwrap_or(&NULL);
234    for segment in path {
235        v = match (v, segment) {
236            (Value::Object(o), JsonPathSegment::Key(k)) => o.get(k).unwrap_or(&NULL),
237            (Value::Array(a), JsonPathSegment::Index(i)) => a.get(*i as usize).unwrap_or(&NULL),
238            _ => &NULL,
239        };
240    }
241    v
242}
243
244/// `formatJsonPathReference`: `metadata.tags[0]`.
245pub fn format_json_path(column: &str, path: &[JsonPathSegment]) -> String {
246    let mut out = column.to_owned();
247    for segment in path {
248        match segment {
249            JsonPathSegment::Key(k) => {
250                out.push('.');
251                out.push_str(k);
252            }
253            JsonPathSegment::Index(i) => out.push_str(&format!("[{i}]")),
254        }
255    }
256    out
257}