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