Skip to main content

zero_client/ast/
coding.rs

1//! The JSON form of the AST, following `astSchema`.
2
3use super::*;
4use crate::decode::{self, Builder, DecodeError, JsonCodable, Reader, Result, strings_json};
5
6impl JsonCodable for Ast {
7    fn from_json(v: &Value) -> Result<Self> {
8        let r = Reader::new(v, "AST")?;
9        Ok(Ast {
10            schema: r.optional_string("schema")?,
11            table: r.string("table")?,
12            alias: r.optional_string("alias")?,
13            where_: r.optional("where", Condition::from_json)?,
14            related: r.optional("related", |v| {
15                decode::array(v, CorrelatedSubquery::from_json)
16            })?,
17            limit: r.optional_number("limit")?,
18            order_by: r.optional("orderBy", |v| {
19                decode::array(v, |e| match e.as_array().map(Vec::as_slice) {
20                    Some([Value::String(field), Value::String(dir)]) => Direction::parse(dir)
21                        .map(|direction| OrderPart {
22                            field: field.clone(),
23                            direction,
24                        })
25                        .ok_or_else(|| DecodeError::new("Expected [field, 'asc' | 'desc']")),
26                    _ => Err(DecodeError::new("Expected [field, 'asc' | 'desc']")),
27                })
28            })?,
29            start: r.optional("start", |v| {
30                let b = Reader::new(v, "bound")?;
31                Ok(Bound {
32                    row: b.required("row", decode::object)?,
33                    exclusive: b.bool("exclusive")?,
34                })
35            })?,
36            aggregate: r.optional("aggregate", Aggregate::from_json)?,
37            group_by: r.optional("groupBy", |v| {
38                let columns = decode::strings(v)?;
39                if columns.is_empty() {
40                    return Err(DecodeError::new("expected groupBy to name a column"));
41                }
42                Ok(columns)
43            })?,
44        })
45    }
46
47    fn to_json(&self) -> Value {
48        Builder::new()
49            .opt("schema", self.schema.clone())
50            .set("table", self.table.clone())
51            .opt("alias", self.alias.clone())
52            .opt("where", self.where_.as_ref().map(Condition::to_json))
53            .opt(
54                "related",
55                self.related
56                    .as_ref()
57                    .map(|r| Value::Array(r.iter().map(CorrelatedSubquery::to_json).collect())),
58            )
59            .opt(
60                "start",
61                self.start.as_ref().map(|b| {
62                    Builder::new()
63                        .set("row", b.row.clone())
64                        .set("exclusive", b.exclusive)
65                        .build()
66                }),
67            )
68            .opt("limit", self.limit)
69            .opt(
70                "orderBy",
71                self.order_by.as_ref().map(|o| {
72                    Value::Array(
73                        o.iter()
74                            .map(|p| {
75                                Value::Array(vec![
76                                    p.field.as_str().into(),
77                                    p.direction.as_str().into(),
78                                ])
79                            })
80                            .collect(),
81                    )
82                }),
83            )
84            .opt("aggregate", self.aggregate.as_ref().map(Aggregate::to_json))
85            .opt("groupBy", self.group_by.as_deref().map(strings_json))
86            .build()
87    }
88}
89
90/// `jsonPathSchema`: a non-empty list of keys and array indices.
91pub(crate) fn path_from_json(v: &Value) -> Result<Vec<JsonPathSegment>> {
92    let path = decode::array(v, |e| match e {
93        Value::String(k) => Ok(JsonPathSegment::Key(k.clone())),
94        Value::Number(n)
95            if n.trunc() == *n && *n >= 0.0 && *n <= f64::from(MAX_JSON_PATH_INDEX) =>
96        {
97            Ok(JsonPathSegment::Index(*n as u32))
98        }
99        Value::Number(_) => Err(DecodeError::new(
100            "expected a non-negative integer array index",
101        )),
102        _ => Err(DecodeError::new("Expected string or number")),
103    })?;
104    if path.is_empty() {
105        return Err(DecodeError::new("expected a non-empty JSON path"));
106    }
107    Ok(path)
108}
109
110pub(crate) fn path_to_json(path: &[JsonPathSegment]) -> Value {
111    Value::Array(path.iter().map(JsonPathSegment::to_json).collect())
112}
113
114impl JsonCodable for Aggregate {
115    fn from_json(v: &Value) -> Result<Self> {
116        let r = Reader::new(v, "aggregate")?;
117        let name = r.string("fn")?;
118        let fn_ = AggregateFunction::parse(&name).ok_or_else(|| {
119            DecodeError::new(format!("Invalid aggregate function \"{name}\"")).at("fn")
120        })?;
121        let a = Aggregate {
122            fn_,
123            field: r.optional_string("field")?,
124            path: r.optional("path", path_from_json)?,
125            distinct: r.optional("distinct", decode::strings)?,
126        };
127        if a.path.is_some() && (a.field.is_none() || fn_ == AggregateFunction::Count) {
128            return Err(DecodeError::new(
129                "expected an aggregate JSON path to have a field and not be a count",
130            ));
131        }
132        if let Some(distinct) = &a.distinct
133            && (fn_ != AggregateFunction::Count || a.field.is_some() || distinct.is_empty())
134        {
135            return Err(DecodeError::new(
136                "expected an aggregate over distinct columns to be a count of at least one",
137            ));
138        }
139        Ok(a)
140    }
141
142    fn to_json(&self) -> Value {
143        Builder::new()
144            .set("fn", self.fn_.as_str())
145            .opt("field", self.field.clone())
146            .opt("path", self.path.as_deref().map(path_to_json))
147            .opt("distinct", self.distinct.as_deref().map(strings_json))
148            .build()
149    }
150}
151
152impl JsonCodable for CorrelatedSubquery {
153    fn from_json(v: &Value) -> Result<Self> {
154        let r = Reader::new(v, "correlated subquery")?;
155        Ok(CorrelatedSubquery {
156            correlation: r.required("correlation", |v| {
157                let c = Reader::new(v, "correlation")?;
158                Ok(Correlation {
159                    parent_field: c.required("parentField", decode::compound_key)?,
160                    child_field: c.required("childField", decode::compound_key)?,
161                })
162            })?,
163            subquery: Box::new(r.required("subquery", Ast::from_json)?),
164            system: r.optional("system", |v| {
165                let s = decode::string(v)?;
166                System::parse(&s).ok_or_else(|| DecodeError::new(format!("Invalid system \"{s}\"")))
167            })?,
168            hidden: r.optional_bool("hidden")?,
169            aggregate: r.optional("aggregate", Aggregate::from_json)?,
170        })
171    }
172
173    fn to_json(&self) -> Value {
174        Builder::new()
175            .set(
176                "correlation",
177                Builder::new()
178                    .set("parentField", strings_json(&self.correlation.parent_field))
179                    .set("childField", strings_json(&self.correlation.child_field))
180                    .build(),
181            )
182            .set("subquery", self.subquery.to_json())
183            .opt("system", self.system.map(System::as_str))
184            .opt("hidden", self.hidden)
185            .opt("aggregate", self.aggregate.as_ref().map(Aggregate::to_json))
186            .build()
187    }
188}
189
190impl JsonCodable for ValuePosition {
191    fn from_json(v: &Value) -> Result<Self> {
192        let r = Reader::new(v, "value position")?;
193        let ty = r.string("type")?;
194        match ty.as_str() {
195            "literal" => Ok(ValuePosition::Literal(r.required(
196                "value",
197                |v| match v {
198                    Value::String(_) | Value::Number(_) | Value::Bool(_) | Value::Null => {
199                        Ok(v.clone())
200                    }
201                    Value::Array(a) => {
202                        for e in a {
203                            if !matches!(e, Value::String(_) | Value::Number(_) | Value::Bool(_)) {
204                                return Err(DecodeError::new("Invalid literal array element"));
205                            }
206                        }
207                        Ok(v.clone())
208                    }
209                    Value::Object(_) => Err(DecodeError::new("Invalid literal value")),
210                },
211            )?)),
212            "column" => Ok(ValuePosition::Column(r.string("name")?)),
213            "json" => {
214                let column = r.required("value", |v| {
215                    let c = Reader::new(v, "column reference")?;
216                    c.literal("type", "column")?;
217                    c.string("name")
218                })?;
219                Ok(ValuePosition::Json {
220                    column,
221                    path: r.required("path", path_from_json)?,
222                })
223            }
224            "static" => {
225                let name = r.string("anchor")?;
226                let anchor = Anchor::parse(&name).ok_or_else(|| {
227                    DecodeError::new(format!("Invalid anchor \"{name}\"")).at("anchor")
228                })?;
229                let field = r.required("field", |v| match v {
230                    Value::String(s) => Ok(StaticField::Single(s.clone())),
231                    Value::Array(_) => Ok(StaticField::Path(decode::strings(v)?)),
232                    _ => Err(DecodeError::new("Expected string or string array")),
233                })?;
234                Ok(ValuePosition::Static { anchor, field })
235            }
236            _ => Err(DecodeError::new(format!("Invalid value position type \"{ty}\"")).at("type")),
237        }
238    }
239
240    fn to_json(&self) -> Value {
241        match self {
242            ValuePosition::Literal(v) => Builder::new()
243                .set("type", "literal")
244                .set("value", v.clone())
245                .build(),
246            ValuePosition::Column(name) => Builder::new()
247                .set("type", "column")
248                .set("name", name.clone())
249                .build(),
250            ValuePosition::Json { column, path } => Builder::new()
251                .set("type", "json")
252                .set(
253                    "value",
254                    Builder::new()
255                        .set("type", "column")
256                        .set("name", column.clone())
257                        .build(),
258                )
259                .set("path", path_to_json(path))
260                .build(),
261            ValuePosition::Static { anchor, field } => Builder::new()
262                .set("type", "static")
263                .set("anchor", anchor.as_str())
264                .set("field", field.to_json())
265                .build(),
266        }
267    }
268}
269
270/// `isHomogeneousList`: every element has the JS type of the first.
271pub(crate) fn is_homogeneous(list: &[Value]) -> bool {
272    list.first()
273        .is_none_or(|first| list.iter().all(|v| v.type_name() == first.type_name()))
274}
275
276impl JsonCodable for Condition {
277    fn from_json(v: &Value) -> Result<Self> {
278        let r = Reader::new(v, "condition")?;
279        let ty = r.string("type")?;
280        match ty.as_str() {
281            "simple" => {
282                let name = r.string("op")?;
283                let op = SimpleOperator::parse(&name).ok_or_else(|| {
284                    DecodeError::new(format!("Invalid operator \"{name}\"")).at("op")
285                })?;
286                let left = r.required("left", ValuePosition::from_json)?;
287                let right = r.required("right", ValuePosition::from_json)?;
288                if matches!(right, ValuePosition::Column(_) | ValuePosition::Json { .. }) {
289                    return Err(DecodeError::new(
290                        "The right side of a condition can't be a column",
291                    )
292                    .at("right"));
293                }
294                // `hasJsonLeafLiteralShape` and `hasHomogeneousJsonInList`.
295                if let (ValuePosition::Json { .. }, ValuePosition::Literal(value)) = (&left, &right)
296                {
297                    let is_in = matches!(op, SimpleOperator::In | SimpleOperator::NotIn);
298                    let list = value.as_array();
299                    let bad_shape = if is_in {
300                        !(list.is_some() || value.is_null())
301                    } else {
302                        list.is_some()
303                    };
304                    if bad_shape {
305                        return Err(DecodeError::new(
306                            "expected a list for IN/NOT IN against a JSON path and a scalar for other operators",
307                        ));
308                    }
309                    if is_in && list.is_some_and(|l| !is_homogeneous(l)) {
310                        return Err(DecodeError::new(
311                            "expected a list of values of one type for IN/NOT IN against a JSON path",
312                        ));
313                    }
314                }
315                Ok(Condition::Simple { op, left, right })
316            }
317            "and" | "or" => {
318                let conditions =
319                    r.required("conditions", |v| decode::array(v, Condition::from_json))?;
320                Ok(if ty == "and" {
321                    Condition::And(conditions)
322                } else {
323                    Condition::Or(conditions)
324                })
325            }
326            "correlatedSubquery" => {
327                let name = r.string("op")?;
328                let op = CorrelatedSubqueryOperator::parse(&name).ok_or_else(|| {
329                    DecodeError::new(format!("Invalid operator \"{name}\"")).at("op")
330                })?;
331                Ok(Condition::CorrelatedSubquery {
332                    related: r.required("related", CorrelatedSubquery::from_json)?,
333                    op,
334                    flip: r.optional_bool("flip")?,
335                    scalar: r.optional_bool("scalar")?,
336                })
337            }
338            _ => Err(DecodeError::new(format!("Invalid condition type \"{ty}\"")).at("type")),
339        }
340    }
341
342    fn to_json(&self) -> Value {
343        match self {
344            Condition::Simple { op, left, right } => Builder::new()
345                .set("type", "simple")
346                .set("op", op.as_str())
347                .set("left", left.to_json())
348                .set("right", right.to_json())
349                .build(),
350            Condition::And(c) | Condition::Or(c) => Builder::new()
351                .set(
352                    "type",
353                    if matches!(self, Condition::And(_)) {
354                        "and"
355                    } else {
356                        "or"
357                    },
358                )
359                .set(
360                    "conditions",
361                    Value::Array(c.iter().map(Condition::to_json).collect()),
362                )
363                .build(),
364            Condition::CorrelatedSubquery {
365                related,
366                op,
367                flip,
368                scalar,
369            } => Builder::new()
370                .set("type", "correlatedSubquery")
371                .set("related", related.to_json())
372                .set("op", op.as_str())
373                .opt("flip", *flip)
374                .opt("scalar", *scalar)
375                .build(),
376        }
377    }
378}