Skip to main content

zero_client/
typed.rs

1//! The typed query builder that `zero-rust codegen` generates code for: row
2//! structs read from views, columns and relationships named by typed
3//! constants, and [`Query`], a typed wrapper of [`AnyQuery`] (`Query` in
4//! `packages/zql/src/query/query.ts`).
5//!
6//! The generated code holds a row struct per table with a [`Column`]
7//! constant per column and a [`Relationship`] constant per relationship,
8//! and a function per table that starts a query:
9//!
10//! ```ignore
11//! zql::issue()
12//!     .where_eq(Issue::STATUS, IssueStatus::Open)
13//!     .where_expr(|e| e.or(vec![Issue::PRIORITY.ge(2.0), Issue::ASSIGNEE_ID.eq(None)]))
14//!     .where_exists(Issue::LABELS, ExistsOptions::default(), |q| q.where_eq(Label::NAME, "bug".into()))
15//!     .related(Issue::COMMENTS, |q| q.order_by(Comment::CREATED, Direction::Desc).limit(10))
16//!     .order_by(Issue::MODIFIED, Direction::Desc)
17//!     .limit(50)
18//! ```
19//!
20//! A typed query builds the same AST as the [`AnyQuery`] calls with the
21//! same names; [`Query::read`] reads a view of it as the query's result
22//! type. In a mutator, the generated `mutate` functions return a
23//! [`TypedTableMutator`] per table, whose updates and deletes take the
24//! generated `<Row>Update` and `<Row>Key` structs. The items marked "for generated code" are what the generated
25//! `from_entry`s and value conversions call.
26
27pub use crate::ast::{Condition, Direction, JsonPathSegment, SimpleOperator};
28pub use crate::client::Transaction;
29pub use crate::ivm::{ViewEntry, ViewValue};
30pub use crate::json::{Object, Value};
31pub use crate::query::{AnyGroupedQuery, AnyQuery, ExistsOptions, StaticParameter};
32pub use crate::schema::Schema;
33
34use crate::ast::{System, ValuePosition};
35use crate::client::Error;
36use crate::query::{ExpressionBuilder, JsonPathReference};
37use std::fmt;
38use std::marker::PhantomData;
39use std::rc::Rc;
40use std::sync::Arc;
41
42/// A value that doesn't fit the Rust type a row declares for it.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct ZeroValueError(pub String);
45
46impl ZeroValueError {
47    /// A value that isn't the `expected` one.
48    pub fn mismatch(expected: &str, value: &Value) -> Self {
49        ZeroValueError(format!(
50            "expected {expected}, got {} {}",
51            value.type_name(),
52            crate::json::stringify(value)
53        ))
54    }
55}
56
57impl fmt::Display for ZeroValueError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(&self.0)
60    }
61}
62
63impl std::error::Error for ZeroValueError {}
64
65/// A Rust type a column holds. Generated row structs use these for their
66/// columns, and the query builder encodes compared values with them.
67pub trait ZeroValue: Sized {
68    /// Reads a value from a row; a missing column reads as `null`.
69    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError>;
70    /// Writes the value as the row and the query builder hold it.
71    fn to_zero_value(&self) -> Value;
72    /// What a row's `null` reads as when the schema says the column can't
73    /// be null; `None` to fail. Databases drift from schemas, and JS shows
74    /// such a row with the null rather than failing, so strings, numbers,
75    /// and booleans read as `""`, `0`, and `false`. Declare the column
76    /// `optional()` to read the null.
77    fn value_for_null() -> Option<Self> {
78        None
79    }
80}
81
82impl ZeroValue for String {
83    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
84        value
85            .as_str()
86            .map(str::to_owned)
87            .ok_or_else(|| ZeroValueError::mismatch("a string", value))
88    }
89    fn to_zero_value(&self) -> Value {
90        Value::String(self.clone())
91    }
92    fn value_for_null() -> Option<Self> {
93        Some(String::new())
94    }
95}
96
97impl ZeroValue for f64 {
98    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
99        value
100            .as_f64()
101            .ok_or_else(|| ZeroValueError::mismatch("a number", value))
102    }
103    fn to_zero_value(&self) -> Value {
104        Value::Number(*self)
105    }
106    fn value_for_null() -> Option<Self> {
107        Some(0.0)
108    }
109}
110
111/// For a `number()` column the codegen config declares an integer: the
112/// value must be exact, which every integer up to 2^53 is.
113impl ZeroValue for i64 {
114    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
115        const MAX_SAFE: f64 = 9_007_199_254_740_992.0;
116        match value.as_f64() {
117            Some(n) if n.fract() == 0.0 && n.abs() <= MAX_SAFE => Ok(n as i64),
118            _ => Err(ZeroValueError::mismatch("an integer", value)),
119        }
120    }
121    fn to_zero_value(&self) -> Value {
122        Value::Number(*self as f64)
123    }
124    fn value_for_null() -> Option<Self> {
125        Some(0)
126    }
127}
128
129impl ZeroValue for bool {
130    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
131        value
132            .as_bool()
133            .ok_or_else(|| ZeroValueError::mismatch("a boolean", value))
134    }
135    fn to_zero_value(&self) -> Value {
136        Value::Bool(*self)
137    }
138    fn value_for_null() -> Option<Self> {
139        Some(false)
140    }
141}
142
143impl ZeroValue for Value {
144    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
145        Ok(value.clone())
146    }
147    fn to_zero_value(&self) -> Value {
148        self.clone()
149    }
150}
151
152/// An optional column: `null` reads as `None`.
153impl<T: ZeroValue> ZeroValue for Option<T> {
154    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
155        if value.is_null() {
156            Ok(None)
157        } else {
158            T::from_zero_value(value).map(Some)
159        }
160    }
161    fn to_zero_value(&self) -> Value {
162        self.as_ref().map_or(Value::Null, T::to_zero_value)
163    }
164}
165
166/// The JSON arrays a `json()` column can hold.
167impl<T: ZeroValue> ZeroValue for Vec<T> {
168    fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
169        value
170            .as_array()
171            .ok_or_else(|| ZeroValueError::mismatch("an array", value))?
172            .iter()
173            .map(T::from_zero_value)
174            .collect()
175    }
176    fn to_zero_value(&self) -> Value {
177        Value::Array(self.iter().map(T::to_zero_value).collect())
178    }
179}
180
181/// A column `sum` and `avg` can reduce: a number (`NumericSelector`).
182pub trait NumericZeroValue: ZeroValue {}
183impl NumericZeroValue for f64 {}
184impl NumericZeroValue for i64 {}
185impl<T: NumericZeroValue> NumericZeroValue for Option<T> {}
186
187/// A column `min` and `max` can reduce: a number or a string, enumerations
188/// included (`OrderedSelector`). `Unwrapped` is the type of its non-null
189/// values, the aggregate's type.
190pub trait OrderedZeroValue: ZeroValue {
191    /// The type of the column's non-null values.
192    type Unwrapped: ZeroValue + OptionalQueryElement;
193}
194impl OrderedZeroValue for f64 {
195    type Unwrapped = f64;
196}
197impl OrderedZeroValue for i64 {
198    type Unwrapped = i64;
199}
200impl OrderedZeroValue for String {
201    type Unwrapped = String;
202}
203impl<T: OrderedZeroValue> OrderedZeroValue for Option<T> {
204    type Unwrapped = T::Unwrapped;
205}
206
207/// Reads `name`'s value of a row or object, for generated code. A `null`
208/// in a column that can't be null reads as [`ZeroValue::value_for_null`].
209pub fn decode<V: ZeroValue>(name: &str, value: Option<&Value>) -> Result<V, ZeroValueError> {
210    let value = value.unwrap_or(&Value::Null);
211    if value.is_null()
212        && let Some(fallback) = V::value_for_null()
213    {
214        return Ok(fallback);
215    }
216    V::from_zero_value(value).map_err(|e| ZeroValueError(format!("{name}: {e}")))
217}
218
219/// A column of a row, for generated `from_entry`s: `index` is its position
220/// in the table's schema, where the row has it unless it came from
221/// elsewhere. Reading it there skips looking the name up.
222pub fn column<V: ZeroValue>(
223    entry: &ViewEntry,
224    name: &str,
225    index: usize,
226) -> Result<V, ZeroValueError> {
227    match entry.row.get_index(index) {
228        Some((k, v)) if k == name => decode(name, Some(v)),
229        _ => decode(name, entry.row.get(name)),
230    }
231}
232
233/// A many relationship of a row, for generated `from_entry`s: `None` when
234/// the query didn't ask for its rows, also when it asked for an aggregate
235/// of them.
236pub fn many<R: QueryElement>(
237    entry: &ViewEntry,
238    name: &str,
239) -> Result<Option<Vec<R>>, ZeroValueError> {
240    match entry.relationship(name) {
241        None | Some(ViewValue::Value(_)) => Ok(None),
242        Some(v) => v
243            .entries()
244            .into_iter()
245            .map(R::from_entry)
246            .collect::<Result<_, _>>()
247            .map(Some),
248    }
249}
250
251/// A one relationship of a row, for generated `from_entry`s: `None` when
252/// the query didn't ask for it or no row matches.
253pub fn one<R: QueryElement>(
254    entry: &ViewEntry,
255    name: &str,
256) -> Result<Option<Box<R>>, ZeroValueError> {
257    match entry
258        .relationship(name)
259        .and_then(|v| v.entries().first().copied())
260    {
261        Some(e) => R::from_entry(e).map(|r| Some(Box::new(r))),
262        None => Ok(None),
263    }
264}
265
266/// The object a generated `json<T>()` type reads its fields from.
267pub fn object<'a>(value: &'a Value, type_name: &str) -> Result<&'a Object, ZeroValueError> {
268    value
269        .as_object()
270        .ok_or_else(|| ZeroValueError::mismatch(&format!("a {type_name} object"), value))
271}
272
273/// A field of a `json<T>()` object; a missing one reads as `null`, so only
274/// an `Option` takes it.
275pub fn field<V: ZeroValue>(object: &Object, name: &str) -> Result<V, ZeroValueError> {
276    V::from_zero_value(object.get(name).unwrap_or(&Value::Null))
277        .map_err(|e| ZeroValueError(format!("{name}: {e}")))
278}
279
280/// The schema of generated code, from the JSON form [`Schema::from_json`]
281/// reads. Panics when it isn't one, which generated code never is.
282pub fn schema_from_json(json: &str) -> Arc<Schema> {
283    let value = crate::json::parse(json).expect("the generated schema is JSON");
284    Arc::new(Schema::from_json(&value).expect("the generated schema is a schema"))
285}
286
287/// A row of a query's result: a row struct, or a row of `group_by` or
288/// `distinct`.
289pub trait QueryElement: Sized {
290    /// Reads the row from a view's entry.
291    fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError>;
292}
293
294/// A row struct of a table, as `zero-rust codegen` generates it: the
295/// table's columns as fields, and a field per relationship that a query
296/// fills when it asks for it with `related`.
297pub trait ZeroRow: QueryElement {
298    /// The client name of the row's table.
299    const TABLE: &'static str;
300    /// What [`TypedTableMutator::update`] takes: the primary key, and the
301    /// other columns to set.
302    type Update: ColumnValues;
303    /// What [`TypedTableMutator::delete`] takes: the primary key.
304    type Key: ColumnValues;
305    /// The row's columns, by client column name.
306    fn column_values(&self) -> Object;
307}
308
309/// Some of a row's columns, by client column name: what an update or a
310/// delete writes. For generated code.
311pub trait ColumnValues {
312    /// The columns, by client column name.
313    fn column_values(&self) -> Object;
314}
315
316/// The typed CRUD operations of a table in a mutator (`tx.mutate.<table>`
317/// in JS), which the generated `mutate` module returns:
318///
319/// ```ignore
320/// mutate::issue(tx).insert(&issue)?;
321/// mutate::issue(tx).update(&IssueUpdate { closed: Some(true), ..IssueUpdate::new(id) })?;
322/// ```
323pub struct TypedTableMutator<'tx, R> {
324    tx: &'tx Transaction,
325    row: PhantomData<fn() -> R>,
326}
327
328impl<'tx, R: ZeroRow> TypedTableMutator<'tx, R> {
329    /// For generated code.
330    pub fn new(tx: &'tx Transaction) -> Self {
331        TypedTableMutator {
332            tx,
333            row: PhantomData,
334        }
335    }
336
337    /// Inserts a row unless one with its primary key exists.
338    pub fn insert(&self, row: &R) -> Result<(), Error> {
339        self.tx.table(R::TABLE).insert(&row.column_values())
340    }
341
342    /// Inserts a row, or replaces the columns of the existing one. Every
343    /// column is written, so an optional one that is `None` sets null; JS
344    /// keeps a column the value leaves out. Use `update` to set only some
345    /// columns.
346    pub fn upsert(&self, row: &R) -> Result<(), Error> {
347        self.tx.table(R::TABLE).upsert(&row.column_values())
348    }
349
350    /// Sets the columns that `value` sets, of the row with its primary key,
351    /// if the row exists.
352    pub fn update(&self, value: &R::Update) -> Result<(), Error> {
353        self.tx.table(R::TABLE).update(&value.column_values())
354    }
355
356    /// Deletes the row with the primary key `key`, if any.
357    pub fn delete(&self, key: &R::Key) -> Result<(), Error> {
358        self.tx.table(R::TABLE).delete(&key.column_values())
359    }
360}
361
362/// A column in an update that can be null: left as it is (the default),
363/// set to null, or set to a value. A column that can't be null is an
364/// `Option` in an update instead, `None` leaving it.
365#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
366pub enum ColumnUpdate<V> {
367    #[default]
368    /// Leaves the column as it is.
369    Unchanged,
370    /// Sets the column to null.
371    Null,
372    /// Sets the column to the value.
373    Set(V),
374}
375
376impl<V> From<Option<V>> for ColumnUpdate<V> {
377    /// Sets the column to the value, or to null for `None`.
378    fn from(value: Option<V>) -> Self {
379        value.map_or(ColumnUpdate::Null, ColumnUpdate::Set)
380    }
381}
382
383impl<V: ZeroValue> ColumnUpdate<V> {
384    /// What the update writes to the column; `None` when it leaves it. For
385    /// generated code.
386    pub fn to_zero_value(&self) -> Option<Value> {
387        match self {
388            ColumnUpdate::Unchanged => None,
389            ColumnUpdate::Null => Some(Value::Null),
390            ColumnUpdate::Set(v) => Some(v.to_zero_value()),
391        }
392    }
393}
394
395/// What a query materializes to: its rows (`Vec<Row>`, `Option<Row>` after
396/// `one()`), or the value of an aggregate, such as the `i64` of `count()`.
397pub trait QueryValue: Sized {
398    /// Reads the query's result from its view.
399    fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError>;
400
401    /// Reads `view` into `self`, which was read from `previous`, as
402    /// [`from_view`](QueryValue::from_view) would, keeping what it can of
403    /// `self`, and makes `previous` what was read: a
404    /// [`LiveView`](crate::client::LiveView) reads each update so. On an
405    /// error both are left as they were. By default it reads `view` anew;
406    /// rows (`Vec<E>`) read only the entries that changed.
407    fn update_from_view(
408        &mut self,
409        previous: &mut ViewValue,
410        view: &ViewValue,
411    ) -> Result<(), ZeroValueError> {
412        *self = Self::from_view(view)?;
413        *previous = view.clone();
414        Ok(())
415    }
416}
417
418impl<E: QueryElement> QueryValue for Vec<E> {
419    fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
420        view.entries().into_iter().map(E::from_entry).collect()
421    }
422
423    /// Keeps the rows whose entries are equal, and reads the others (the
424    /// Swift client's `RowCache`). Most updates change a few rows in place,
425    /// or insert or remove one, so the entries are matched in order,
426    /// skipping at most one. `previous` becomes a copy of the entries
427    /// changed in the same way, so the view, which then shares its rows with
428    /// nothing, changes them in place.
429    fn update_from_view(
430        &mut self,
431        previous: &mut ViewValue,
432        view: &ViewValue,
433    ) -> Result<(), ZeroValueError> {
434        let (ViewValue::Many(old), ViewValue::Many(new)) = (&mut *previous, view) else {
435            *self = Self::from_view(view)?;
436            *previous = view.clone();
437            return Ok(());
438        };
439        if old.len() != self.len() {
440            *self = Self::from_view(view)?;
441            *previous = view.clone();
442            return Ok(());
443        }
444        // What the rows become, in order: runs of old rows kept, by index,
445        // and of rows read anew. Rows are read before anything changes, so a
446        // row that fails leaves both as they were.
447        let mut runs: Vec<Run> = Vec::new();
448        let mut fresh = Vec::new();
449        // Whether every row kept stays at its index, so the rows read anew
450        // replace the others where they are.
451        let mut in_place = old.len() == new.len();
452        let mut j = 0;
453        for (i, entry) in new.iter().enumerate() {
454            let kept = if old.get(j).is_some_and(|o| same_entry(o, entry)) {
455                Some(j)
456            } else if old.get(j + 1).is_some_and(|o| same_entry(o, entry)) {
457                Some(j + 1)
458            } else {
459                None
460            };
461            match (kept, runs.last_mut()) {
462                (Some(k), Some(Run::Keep { from, len })) if *from + *len == k => *len += 1,
463                (Some(k), _) => runs.push(Run::Keep { from: k, len: 1 }),
464                (None, Some(Run::Fresh(len))) => *len += 1,
465                (None, _) => runs.push(Run::Fresh(1)),
466            }
467            match kept {
468                Some(k) => {
469                    in_place &= k == i;
470                    j = k + 1;
471                }
472                None => fresh.push(E::from_entry(entry)?),
473            }
474        }
475        if in_place && fresh.is_empty() {
476            return Ok(());
477        }
478        let mut fresh = fresh.into_iter();
479        apply_runs(self, &runs, in_place, new.len(), |_| {
480            fresh.next().expect("a row read for each new entry")
481        });
482        apply_runs(Rc::make_mut(old), &runs, in_place, new.len(), |i| {
483            new[i].clone()
484        });
485        Ok(())
486    }
487}
488
489/// Whether two entries are equal, as `==` says, comparing the rows and the
490/// lists they share by address first: an entry a view didn't change shares
491/// them with the copy read before.
492fn same_entry(a: &ViewEntry, b: &ViewEntry) -> bool {
493    (Rc::ptr_eq(&a.row, &b.row) || a.row == b.row)
494        && a.relationships.len() == b.relationships.len()
495        && a.relationships
496            .iter()
497            .zip(&b.relationships)
498            .all(|((m, a), (n, b))| m == n && same_value(a, b))
499}
500
501fn same_value(a: &ViewValue, b: &ViewValue) -> bool {
502    match (a, b) {
503        (ViewValue::Many(a), ViewValue::Many(b)) => {
504            Rc::ptr_eq(a, b)
505                || (a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| same_entry(a, b)))
506        }
507        (ViewValue::One(Some(a)), ViewValue::One(Some(b))) => same_entry(a, b),
508        (a, b) => a == b,
509    }
510}
511
512/// A run of `Vec::update_from_view`'s rows.
513enum Run {
514    /// `len` old rows from `from`.
515    Keep { from: usize, len: usize },
516    /// `len` rows read anew.
517    Fresh(usize),
518}
519
520/// Makes `items` the `len` items `runs` lists: the old ones kept, and
521/// `fresh(i)` for the `i`th, read anew. `in_place`: each item kept stays
522/// where it is.
523fn apply_runs<X>(
524    items: &mut Vec<X>,
525    runs: &[Run],
526    in_place: bool,
527    len: usize,
528    mut fresh: impl FnMut(usize) -> X,
529) {
530    if in_place {
531        let mut at = 0;
532        for run in runs {
533            match *run {
534                Run::Keep { len, .. } => at += len,
535                Run::Fresh(n) => {
536                    for (i, item) in items[at..at + n].iter_mut().enumerate() {
537                        *item = fresh(at + i);
538                    }
539                    at += n;
540                }
541            }
542        }
543        return;
544    }
545    let mut out = Vec::with_capacity(len);
546    let mut old = std::mem::take(items).into_iter();
547    let mut next = 0;
548    for run in runs {
549        match *run {
550            Run::Keep { from, len } => {
551                if from > next {
552                    old.nth(from - next - 1);
553                }
554                out.extend(old.by_ref().take(len));
555                next = from + len;
556            }
557            Run::Fresh(n) => {
558                let at = out.len();
559                out.extend((at..at + n).map(&mut fresh));
560            }
561        }
562    }
563    *items = out;
564}
565
566/// What an `Option` query value holds: the row of `one()`, or the value of
567/// `sum`, `avg`, `min` or `max`, which is `None` over no rows. Generated
568/// rows implement it with [`optional_row`], generated enumerations with
569/// [`optional_value`].
570pub trait OptionalQueryElement: Sized {
571    /// Reads the query's result from its view: `None` for no row, or for an
572    /// aggregate over no rows.
573    fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError>;
574}
575
576impl<T: OptionalQueryElement> QueryValue for Option<T> {
577    fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
578        T::optional_from_view(view)
579    }
580}
581
582/// The value of `count()`.
583impl QueryValue for i64 {
584    fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
585        i64::from_zero_value(aggregate_value(view)?)
586    }
587}
588
589fn aggregate_value(view: &ViewValue) -> Result<&Value, ZeroValueError> {
590    match view {
591        ViewValue::Value(v) => Ok(v),
592        _ => Err(ZeroValueError(
593            "expected the value of an aggregate, got rows".into(),
594        )),
595    }
596}
597
598/// The row of a `one()` view, for generated rows' [`OptionalQueryElement`].
599pub fn optional_row<R: QueryElement>(view: &ViewValue) -> Result<Option<R>, ZeroValueError> {
600    view.entries().first().map(|e| R::from_entry(e)).transpose()
601}
602
603/// The value of an aggregate's view: `None` when it's null.
604pub fn optional_value<V: ZeroValue>(view: &ViewValue) -> Result<Option<V>, ZeroValueError> {
605    let value = aggregate_value(view)?;
606    if value.is_null() {
607        Ok(None)
608    } else {
609        V::from_zero_value(value).map(Some)
610    }
611}
612
613macro_rules! optional_values {
614    ($($t:ty),*) => {$(
615        impl OptionalQueryElement for $t {
616            fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError> {
617                optional_value(view)
618            }
619        }
620    )*};
621}
622optional_values!(f64, i64, String, bool, Value);
623
624/// A column of the row type `R`, holding `V`s: generated as a constant of
625/// the row struct, such as `Issue::TITLE`.
626pub struct Column<R, V> {
627    name: &'static str,
628    types: PhantomData<fn() -> (R, V)>,
629}
630
631impl<R, V> Clone for Column<R, V> {
632    fn clone(&self) -> Self {
633        *self
634    }
635}
636impl<R, V> Copy for Column<R, V> {}
637
638impl<R, V> fmt::Debug for Column<R, V> {
639    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640        f.debug_tuple("Column").field(&self.name).finish()
641    }
642}
643
644impl<R, V> Column<R, V> {
645    /// The column named `name` (its client name). For generated code.
646    pub const fn new(name: &'static str) -> Self {
647        Column {
648            name,
649            types: PhantomData,
650        }
651    }
652
653    /// The column's client name.
654    pub fn name(&self) -> &'static str {
655        self.name
656    }
657
658    fn compare(self, op: SimpleOperator, right: ValuePosition) -> Condition {
659        Condition::Simple {
660            op,
661            left: ValuePosition::Column(self.name.to_owned()),
662            right,
663        }
664    }
665
666    /// Compares the column with a value of the context, such as the auth
667    /// data.
668    pub fn cmp_param(self, op: SimpleOperator, param: &StaticParameter) -> Condition {
669        self.compare(
670            op,
671            ValuePosition::Static {
672                anchor: param.anchor,
673                field: param.field.clone(),
674            },
675        )
676    }
677}
678
679impl<R, V: ZeroValue> Column<R, V> {
680    /// Compares the column with `value` by `op`.
681    pub fn cmp(self, op: SimpleOperator, value: V) -> Condition {
682        self.compare(op, ValuePosition::Literal(value.to_zero_value()))
683    }
684
685    /// Equal to `value`. Comparing with null uses `IS`, since `= NULL`
686    /// matches nothing.
687    pub fn eq(self, value: V) -> Condition {
688        let value = value.to_zero_value();
689        let op = if value.is_null() {
690            SimpleOperator::Is
691        } else {
692            SimpleOperator::Eq
693        };
694        self.compare(op, ValuePosition::Literal(value))
695    }
696
697    /// Not equal to `value`; with null, `IS NOT`.
698    pub fn ne(self, value: V) -> Condition {
699        let value = value.to_zero_value();
700        let op = if value.is_null() {
701            SimpleOperator::IsNot
702        } else {
703            SimpleOperator::Ne
704        };
705        self.compare(op, ValuePosition::Literal(value))
706    }
707
708    /// The column is less than `value`.
709    pub fn lt(self, value: V) -> Condition {
710        self.cmp(SimpleOperator::Lt, value)
711    }
712    /// The column is at most `value`.
713    pub fn le(self, value: V) -> Condition {
714        self.cmp(SimpleOperator::Le, value)
715    }
716    /// The column is greater than `value`.
717    pub fn gt(self, value: V) -> Condition {
718        self.cmp(SimpleOperator::Gt, value)
719    }
720    /// The column is at least `value`.
721    pub fn ge(self, value: V) -> Condition {
722        self.cmp(SimpleOperator::Ge, value)
723    }
724    /// The column `IS` `value`: as `=`, but null matches null.
725    pub fn is(self, value: V) -> Condition {
726        self.cmp(SimpleOperator::Is, value)
727    }
728    /// The column `IS NOT` `value`: as `!=`, but null matches non-null values.
729    pub fn is_not(self, value: V) -> Condition {
730        self.cmp(SimpleOperator::IsNot, value)
731    }
732
733    /// `IN`.
734    pub fn is_in(self, values: Vec<V>) -> Condition {
735        self.compare(SimpleOperator::In, ValuePosition::Literal(array(values)))
736    }
737
738    /// `NOT IN`.
739    pub fn not_in(self, values: Vec<V>) -> Condition {
740        self.compare(SimpleOperator::NotIn, ValuePosition::Literal(array(values)))
741    }
742}
743
744fn array<V: ZeroValue>(values: Vec<V>) -> Value {
745    Value::Array(values.iter().map(V::to_zero_value).collect())
746}
747
748macro_rules! like {
749    ($t:ty) => {
750        impl<R> Column<R, $t> {
751            /// The column matches the SQL `LIKE` pattern, with `%` and `_` as
752            /// wildcards (`like::escape_like` escapes them).
753            pub fn like(self, pattern: &str) -> Condition {
754                self.pattern(SimpleOperator::Like, pattern)
755            }
756            /// The column doesn't match the `LIKE` pattern.
757            pub fn not_like(self, pattern: &str) -> Condition {
758                self.pattern(SimpleOperator::NotLike, pattern)
759            }
760            /// The column matches the pattern ignoring case (`ILIKE`).
761            pub fn ilike(self, pattern: &str) -> Condition {
762                self.pattern(SimpleOperator::Ilike, pattern)
763            }
764            /// The column doesn't match the pattern ignoring case (`NOT
765            /// ILIKE`).
766            pub fn not_ilike(self, pattern: &str) -> Condition {
767                self.pattern(SimpleOperator::NotIlike, pattern)
768            }
769            fn pattern(self, op: SimpleOperator, pattern: &str) -> Condition {
770                self.compare(
771                    op,
772                    ValuePosition::Literal(Value::String(pattern.to_owned())),
773                )
774            }
775        }
776    };
777}
778like!(String);
779like!(Option<String>);
780
781/// A column of `R` of any type, for the lists of `group_by`, `distinct`
782/// and `start_values`: `Issue::OWNER_ID.into()`.
783pub struct ColumnRef<R> {
784    name: &'static str,
785    row: PhantomData<fn() -> R>,
786}
787
788impl<R> Clone for ColumnRef<R> {
789    fn clone(&self) -> Self {
790        *self
791    }
792}
793impl<R> Copy for ColumnRef<R> {}
794
795impl<R> fmt::Debug for ColumnRef<R> {
796    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
797        f.debug_tuple("ColumnRef").field(&self.name).finish()
798    }
799}
800
801impl<R> ColumnRef<R> {
802    /// The column's client name.
803    pub fn name(&self) -> &'static str {
804        self.name
805    }
806}
807
808impl<R, V> From<Column<R, V>> for ColumnRef<R> {
809    fn from(c: Column<R, V>) -> Self {
810        ColumnRef {
811            name: c.name,
812            row: PhantomData,
813        }
814    }
815}
816
817/// A relationship from the row type `R` to the row type `D`: generated as a
818/// constant of the row struct, such as `Issue::COMMENTS`.
819pub struct Relationship<R, D> {
820    name: &'static str,
821    types: PhantomData<fn() -> (R, D)>,
822}
823
824impl<R, D> Clone for Relationship<R, D> {
825    fn clone(&self) -> Self {
826        *self
827    }
828}
829impl<R, D> Copy for Relationship<R, D> {}
830
831impl<R, D> fmt::Debug for Relationship<R, D> {
832    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833        f.debug_tuple("Relationship").field(&self.name).finish()
834    }
835}
836
837impl<R, D> Relationship<R, D> {
838    /// The relationship named `name`. For generated code.
839    pub const fn new(name: &'static str) -> Self {
840        Relationship {
841            name,
842            types: PhantomData,
843        }
844    }
845
846    /// The relationship's name.
847    pub fn name(&self) -> &'static str {
848        self.name
849    }
850}
851
852/// The aggregates a row's query asked for in `related`, by relationship:
853/// `related(Issue::COMMENTS, |q| q.count())` gives
854/// `issue.aggregates.count(Issue::COMMENTS)`. The relationship's own field
855/// stays `None`.
856pub struct RelationshipAggregates<R> {
857    /// The values by relationship name.
858    pub values: Vec<(String, Value)>,
859    row: PhantomData<fn() -> R>,
860}
861
862impl<R> Clone for RelationshipAggregates<R> {
863    fn clone(&self) -> Self {
864        RelationshipAggregates {
865            values: self.values.clone(),
866            row: PhantomData,
867        }
868    }
869}
870
871impl<R> fmt::Debug for RelationshipAggregates<R> {
872    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873        f.debug_map()
874            .entries(self.values.iter().map(|(k, v)| (k, v)))
875            .finish()
876    }
877}
878
879impl<R> PartialEq for RelationshipAggregates<R> {
880    fn eq(&self, other: &Self) -> bool {
881        self.values == other.values
882    }
883}
884
885impl<R> Default for RelationshipAggregates<R> {
886    fn default() -> Self {
887        RelationshipAggregates {
888            values: Vec::new(),
889            row: PhantomData,
890        }
891    }
892}
893
894impl<R> RelationshipAggregates<R> {
895    /// The aggregates of `entry`'s relationships, for generated
896    /// `from_entry`s.
897    pub fn from_entry(entry: &ViewEntry) -> Self {
898        RelationshipAggregates {
899            values: entry
900                .relationships
901                .iter()
902                .filter_map(|(name, v)| match v {
903                    ViewValue::Value(v) => Some((name.clone(), v.clone())),
904                    _ => None,
905                })
906                .collect(),
907            row: PhantomData,
908        }
909    }
910
911    /// Whether the query asked for no aggregates.
912    pub fn is_empty(&self) -> bool {
913        self.values.is_empty()
914    }
915
916    /// The `count()` of a relationship; `None` when the query didn't ask
917    /// for it.
918    pub fn count<D>(&self, relationship: Relationship<R, D>) -> Option<i64> {
919        self.value(relationship)
920    }
921
922    /// The `sum` of a relationship; `None` when the query didn't ask for it
923    /// or it has no rows.
924    pub fn sum<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
925        self.value(relationship)
926    }
927
928    /// The `avg` of a relationship; `None` when the query didn't ask for it
929    /// or it has no rows.
930    pub fn avg<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
931        self.value(relationship)
932    }
933
934    /// The aggregate of a relationship read as `V`, as for `min` and `max`;
935    /// `None` when the query didn't ask for it, it's null, or it isn't a
936    /// `V`.
937    pub fn value<V: ZeroValue, D>(&self, relationship: Relationship<R, D>) -> Option<V> {
938        let (_, v) = self.values.iter().find(|(k, _)| k == relationship.name)?;
939        if v.is_null() {
940            return None;
941        }
942        V::from_zero_value(v).ok()
943    }
944}
945
946/// A query over the rows of `R`'s table that materializes to a `T`: the
947/// rows (`Vec<R>`), the row of `one()` (`Option<R>`), or an aggregate.
948pub struct Query<R, T = Vec<R>> {
949    any: AnyQuery,
950    types: PhantomData<fn() -> (R, T)>,
951}
952
953impl<R, T> Clone for Query<R, T> {
954    fn clone(&self) -> Self {
955        Query::from_any(self.any.clone())
956    }
957}
958
959impl<R, T> fmt::Debug for Query<R, T> {
960    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
961        f.debug_tuple("Query").field(&self.any).finish()
962    }
963}
964
965impl<R, T> Query<R, T> {
966    /// The typed form of an untyped query of `R`'s table.
967    pub fn from_any(any: AnyQuery) -> Self {
968        Query {
969            any,
970            types: PhantomData,
971        }
972    }
973
974    /// The untyped query this one builds.
975    pub fn any(&self) -> &AnyQuery {
976        &self.any
977    }
978
979    /// The untyped query this one wraps.
980    pub fn into_any(self) -> AnyQuery {
981        self.any
982    }
983
984    fn map(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Self {
985        Query::from_any(f(self.any))
986    }
987
988    fn to<U>(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Query<R, U> {
989        Query::from_any(f(self.any))
990    }
991}
992
993impl<R: ZeroRow> Query<R> {
994    /// All rows of `R`'s table, for the generated query functions.
995    pub fn table(schema: Arc<Schema>) -> Self {
996        Query::from_any(AnyQuery::new(schema, R::TABLE, System::Client))
997    }
998}
999
1000impl<R: ZeroRow, T> Query<R, T> {
1001    /// Rows whose `column` equals `value`; with null, `IS`.
1002    pub fn where_eq<V: ZeroValue>(self, column: Column<R, V>, value: V) -> Self {
1003        self.where_condition(column.eq(value))
1004    }
1005
1006    /// Rows whose `column` compares to `value` by `op`.
1007    pub fn where_<V: ZeroValue>(self, column: Column<R, V>, op: SimpleOperator, value: V) -> Self {
1008        self.map(|q| q.where_(column.name, op, value.to_zero_value()))
1009    }
1010
1011    /// Rows whose `column` is `IN` or `NOT IN` `values`.
1012    pub fn where_in<V: ZeroValue>(
1013        self,
1014        column: Column<R, V>,
1015        op: SimpleOperator,
1016        values: Vec<V>,
1017    ) -> Self {
1018        self.map(|q| q.where_(column.name, op, array(values)))
1019    }
1020
1021    /// Rows whose `column` compares to a value of the context by `op`.
1022    pub fn where_param<V>(
1023        self,
1024        column: Column<R, V>,
1025        op: SimpleOperator,
1026        param: &StaticParameter,
1027    ) -> Self {
1028        self.map(|q| q.where_param(column.name, op, param))
1029    }
1030
1031    /// Rows that match `condition`, and any earlier `where`.
1032    pub fn where_condition(self, condition: Condition) -> Self {
1033        self.map(|q| q.where_condition(condition))
1034    }
1035
1036    /// Rows that match the condition `factory` builds from the row's
1037    /// expression: its JSON paths, `exists`, and `and`, `or` and `not`.
1038    pub fn where_expr(self, factory: impl FnOnce(&RowExpression<'_, '_, R>) -> Condition) -> Self {
1039        self.map(|q| {
1040            q.where_expr(|eb| {
1041                factory(&RowExpression {
1042                    builder: eb,
1043                    row: PhantomData,
1044                })
1045            })
1046        })
1047    }
1048
1049    /// Rows with a related row in `relationship` that `sub` matches.
1050    pub fn where_exists<D: ZeroRow>(
1051        self,
1052        relationship: Relationship<R, D>,
1053        options: ExistsOptions,
1054        sub: impl FnOnce(Query<D>) -> Query<D>,
1055    ) -> Self {
1056        self.map(|q| q.where_exists(relationship.name, options, untyped(sub)))
1057    }
1058
1059    /// Fills `relationship` of each row, or, when `sub` ends in an
1060    /// aggregate, sets the row's aggregate of it: `related(Issue::COMMENTS,
1061    /// |q| q.count())` gives `aggregates.count(Issue::COMMENTS)`.
1062    pub fn related<D: ZeroRow, S>(
1063        self,
1064        relationship: Relationship<R, D>,
1065        sub: impl FnOnce(Query<D>) -> Query<D, S>,
1066    ) -> Self {
1067        self.map(|q| q.related(relationship.name, |a| sub(Query::from_any(a)).any))
1068    }
1069
1070    /// Orders the rows by `column`, after any earlier `order_by`; the primary
1071    /// key breaks ties.
1072    pub fn order_by<V>(self, column: Column<R, V>, direction: Direction) -> Self {
1073        self.map(|q| q.order_by(column.name, direction))
1074    }
1075
1076    /// At most `limit` rows.
1077    pub fn limit(self, limit: i64) -> Self {
1078        self.map(|q| q.limit(limit))
1079    }
1080
1081    /// Starts after `row`, or at it when `inclusive`.
1082    pub fn start(self, row: &R, inclusive: bool) -> Self {
1083        self.map(|q| q.start(row.column_values(), inclusive))
1084    }
1085
1086    /// Starts after the row with these column values, or at it when
1087    /// `inclusive`: a cursor that holds only the columns the query orders
1088    /// by.
1089    pub fn start_values(self, values: Vec<(ColumnRef<R>, Value)>, inclusive: bool) -> Self {
1090        let row = values.into_iter().map(|(c, v)| (c.name, v)).collect();
1091        self.map(|q| q.start(row, inclusive))
1092    }
1093
1094    /// At most one row.
1095    pub fn one(self) -> Query<R, Option<R>> {
1096        self.to(AnyQuery::one)
1097    }
1098
1099    /// Reduces the query to a count of the rows left after `where`, `start`
1100    /// and `limit`.
1101    pub fn count(self) -> Query<R, i64> {
1102        self.to(AnyQuery::count)
1103    }
1104
1105    /// The sum of a number column; `None` over no rows.
1106    pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
1107        self.to(|q| q.sum(column.name))
1108    }
1109
1110    /// The sum of the numbers at `path` in a `json` column. A missing path,
1111    /// or a value that isn't a number, is skipped.
1112    pub fn sum_json<V>(
1113        self,
1114        column: Column<R, V>,
1115        path: Vec<JsonPathSegment>,
1116    ) -> Query<R, Option<f64>> {
1117        self.to(|q| q.sum_json(column.name, path))
1118    }
1119
1120    /// The average of a number column; `None` over no rows.
1121    pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
1122        self.to(|q| q.avg(column.name))
1123    }
1124
1125    /// Reduces the query to the average of the numbers at `path` in the JSON
1126    /// `column`.
1127    pub fn avg_json<V>(
1128        self,
1129        column: Column<R, V>,
1130        path: Vec<JsonPathSegment>,
1131    ) -> Query<R, Option<f64>> {
1132        self.to(|q| q.avg_json(column.name, path))
1133    }
1134
1135    /// The least value of a number or string column; `None` over no rows.
1136    pub fn min<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
1137        self.to(|q| q.min(column.name))
1138    }
1139
1140    /// Reduces the query to the least value at `path` in the JSON `column`.
1141    pub fn min_json<V>(
1142        self,
1143        column: Column<R, V>,
1144        path: Vec<JsonPathSegment>,
1145    ) -> Query<R, Option<Value>> {
1146        self.to(|q| q.min_json(column.name, path))
1147    }
1148
1149    /// The greatest value of a number or string column; `None` over no
1150    /// rows.
1151    pub fn max<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
1152        self.to(|q| q.max(column.name))
1153    }
1154
1155    /// Reduces the query to the greatest value at `path` in the JSON `column`.
1156    pub fn max_json<V>(
1157        self,
1158        column: Column<R, V>,
1159        path: Vec<JsonPathSegment>,
1160    ) -> Query<R, Option<Value>> {
1161        self.to(|q| q.max_json(column.name, path))
1162    }
1163
1164    /// The distinct combinations of `columns` among the rows `where` keeps.
1165    /// `count()` after it counts the combinations.
1166    pub fn distinct(self, columns: Vec<ColumnRef<R>>) -> Query<R, Vec<DistinctRow<R>>> {
1167        self.to(|q| q.distinct(names(columns)))
1168    }
1169
1170    /// Groups the rows by `columns`, for the aggregate that reduces each
1171    /// group.
1172    pub fn group_by(self, columns: Vec<ColumnRef<R>>) -> GroupedQuery<R> {
1173        GroupedQuery {
1174            any: self.any.group_by(names(columns)),
1175            row: PhantomData,
1176        }
1177    }
1178}
1179
1180impl<C, R, T> crate::query::ZeroQuery<C> for Query<R, T> {
1181    fn any_query(&self, _: &C) -> std::borrow::Cow<'_, AnyQuery> {
1182        std::borrow::Cow::Borrowed(&self.any)
1183    }
1184}
1185
1186impl<R, T: QueryValue> Query<R, T> {
1187    /// Reads a view of this query as its result.
1188    pub fn read(&self, view: &ViewValue) -> Result<T, ZeroValueError> {
1189        T::from_view(view)
1190    }
1191}
1192
1193/// A query whose view reads as a [`QueryValue`]: a typed [`Query`], or a
1194/// named query's `QueryRequest`. What
1195/// [`Zero::live`](crate::client::Zero::live) takes.
1196pub trait TypedQuery<C>: crate::query::ZeroQuery<C> {
1197    /// What the query's view reads as.
1198    type Value: QueryValue;
1199}
1200
1201impl<C, R, T: QueryValue> TypedQuery<C> for Query<R, T> {
1202    type Value = T;
1203}
1204
1205fn names<R>(columns: Vec<ColumnRef<R>>) -> Vec<String> {
1206    columns.into_iter().map(|c| c.name.to_owned()).collect()
1207}
1208
1209fn untyped<D>(sub: impl FnOnce(Query<D>) -> Query<D>) -> impl FnOnce(AnyQuery) -> AnyQuery {
1210    |a| sub(Query::from_any(a)).any
1211}
1212
1213/// The row a `where_expr` condition is about: JSON paths into its columns,
1214/// `exists` over its relationships, and the connectives. Compare columns
1215/// with their constants' methods, such as `Issue::TITLE.like("%bug%")`.
1216pub struct RowExpression<'a, 'q, R> {
1217    builder: &'a ExpressionBuilder<'q>,
1218    row: PhantomData<fn() -> R>,
1219}
1220
1221impl<R> RowExpression<'_, '_, R> {
1222    /// A value inside a `json` column: `e.json(Issue::METADATA,
1223    /// vec!["tags".into(), 0.into()]).eq("bug".into())`.
1224    pub fn json<V>(&self, column: Column<R, V>, path: Vec<JsonPathSegment>) -> JsonPath<'_, '_> {
1225        JsonPath {
1226            builder: self.builder,
1227            reference: self.builder.json(column.name, path),
1228        }
1229    }
1230
1231    /// Whether a related row in `relationship` matches `sub`.
1232    pub fn exists<D: ZeroRow>(
1233        &self,
1234        relationship: Relationship<R, D>,
1235        options: ExistsOptions,
1236        sub: impl FnOnce(Query<D>) -> Query<D>,
1237    ) -> Condition {
1238        self.builder
1239            .exists(relationship.name, options, untyped(sub))
1240    }
1241
1242    /// All of `conditions`; true when there are none.
1243    pub fn and(&self, conditions: Vec<Condition>) -> Condition {
1244        self.builder.and(conditions)
1245    }
1246
1247    /// Any of `conditions`; false when there are none.
1248    pub fn or(&self, conditions: Vec<Condition>) -> Condition {
1249        self.builder.or(conditions)
1250    }
1251
1252    /// Rows that `condition` doesn't match.
1253    pub fn not(&self, condition: Condition) -> Condition {
1254        self.builder.not(condition)
1255    }
1256}
1257
1258/// A value inside a `json` column in a `where_expr`. Its JSON type isn't
1259/// known, so it compares with any [`Value`]: one of another type never
1260/// equals it. Comparing with null uses `IS`.
1261pub struct JsonPath<'a, 'q> {
1262    builder: &'a ExpressionBuilder<'q>,
1263    reference: JsonPathReference,
1264}
1265
1266impl JsonPath<'_, '_> {
1267    /// The value at the path compares to `value` by `op`.
1268    pub fn cmp(&self, op: SimpleOperator, value: Value) -> Condition {
1269        self.builder.cmp_json(&self.reference, op, value)
1270    }
1271
1272    /// The value at the path compares to a value of the context by `op`.
1273    pub fn cmp_param(&self, op: SimpleOperator, param: &StaticParameter) -> Condition {
1274        self.builder.cmp_json_param(&self.reference, op, param)
1275    }
1276
1277    /// The value at the path equals `value` (`IS` for null).
1278    pub fn eq(&self, value: Value) -> Condition {
1279        let op = if value.is_null() {
1280            SimpleOperator::Is
1281        } else {
1282            SimpleOperator::Eq
1283        };
1284        self.cmp(op, value)
1285    }
1286
1287    /// The value at the path differs from `value` (`IS NOT` for null).
1288    pub fn ne(&self, value: Value) -> Condition {
1289        let op = if value.is_null() {
1290            SimpleOperator::IsNot
1291        } else {
1292            SimpleOperator::Ne
1293        };
1294        self.cmp(op, value)
1295    }
1296
1297    /// The value at the path is less than `value`.
1298    pub fn lt(&self, value: Value) -> Condition {
1299        self.cmp(SimpleOperator::Lt, value)
1300    }
1301    /// The value at the path is at most `value`.
1302    pub fn le(&self, value: Value) -> Condition {
1303        self.cmp(SimpleOperator::Le, value)
1304    }
1305    /// The value at the path is greater than `value`.
1306    pub fn gt(&self, value: Value) -> Condition {
1307        self.cmp(SimpleOperator::Gt, value)
1308    }
1309    /// The value at the path is at least `value`.
1310    pub fn ge(&self, value: Value) -> Condition {
1311        self.cmp(SimpleOperator::Ge, value)
1312    }
1313    /// The value at the path `IS` `value`.
1314    pub fn is(&self, value: Value) -> Condition {
1315        self.cmp(SimpleOperator::Is, value)
1316    }
1317    /// The value at the path `IS NOT` `value`.
1318    pub fn is_not(&self, value: Value) -> Condition {
1319        self.cmp(SimpleOperator::IsNot, value)
1320    }
1321    /// `values` must be of one JSON type.
1322    pub fn is_in(&self, values: Vec<Value>) -> Condition {
1323        self.cmp(SimpleOperator::In, Value::Array(values))
1324    }
1325    /// The value at the path is none of `values`.
1326    pub fn not_in(&self, values: Vec<Value>) -> Condition {
1327        self.cmp(SimpleOperator::NotIn, Value::Array(values))
1328    }
1329    /// The value at the path matches the `LIKE` pattern.
1330    pub fn like(&self, pattern: &str) -> Condition {
1331        self.cmp(SimpleOperator::Like, Value::String(pattern.to_owned()))
1332    }
1333    /// The value at the path doesn't match the `LIKE` pattern.
1334    pub fn not_like(&self, pattern: &str) -> Condition {
1335        self.cmp(SimpleOperator::NotLike, Value::String(pattern.to_owned()))
1336    }
1337    /// The value at the path matches the pattern ignoring case (`ILIKE`).
1338    pub fn ilike(&self, pattern: &str) -> Condition {
1339        self.cmp(SimpleOperator::Ilike, Value::String(pattern.to_owned()))
1340    }
1341    /// The value at the path doesn't match the pattern ignoring case.
1342    pub fn not_ilike(&self, pattern: &str) -> Condition {
1343        self.cmp(SimpleOperator::NotIlike, Value::String(pattern.to_owned()))
1344    }
1345}
1346
1347/// A query of the [`GroupRow`]s of `group_by` and an aggregate.
1348pub type Grouped<R, V> = Query<R, Vec<GroupRow<R, V>>>;
1349
1350/// A query grouped by columns, waiting for the aggregate that reduces each
1351/// group (`GroupedQuery` in `packages/zql/src/query/query.ts`): one
1352/// [`GroupRow`] per group.
1353pub struct GroupedQuery<R> {
1354    any: AnyGroupedQuery,
1355    row: PhantomData<fn() -> R>,
1356}
1357
1358impl<R> GroupedQuery<R> {
1359    /// The untyped grouped query this one wraps.
1360    pub fn any(&self) -> &AnyGroupedQuery {
1361        &self.any
1362    }
1363
1364    /// Each group's row count.
1365    pub fn count(self) -> Grouped<R, i64> {
1366        Query::from_any(self.any.count())
1367    }
1368
1369    /// Each group's sum of `column`.
1370    pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
1371        Query::from_any(self.any.sum(column.name))
1372    }
1373
1374    /// Each group's sum of the numbers at `path` in the JSON `column`.
1375    pub fn sum_json<V>(
1376        self,
1377        column: Column<R, V>,
1378        path: Vec<JsonPathSegment>,
1379    ) -> Grouped<R, Option<f64>> {
1380        Query::from_any(self.any.sum_json(column.name, path))
1381    }
1382
1383    /// Each group's average of `column`.
1384    pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
1385        Query::from_any(self.any.avg(column.name))
1386    }
1387
1388    /// Each group's average of the numbers at `path` in the JSON `column`.
1389    pub fn avg_json<V>(
1390        self,
1391        column: Column<R, V>,
1392        path: Vec<JsonPathSegment>,
1393    ) -> Grouped<R, Option<f64>> {
1394        Query::from_any(self.any.avg_json(column.name, path))
1395    }
1396
1397    /// Each group's least value of `column`.
1398    pub fn min<V: OrderedZeroValue>(
1399        self,
1400        column: Column<R, V>,
1401    ) -> Grouped<R, Option<V::Unwrapped>> {
1402        Query::from_any(self.any.min(column.name))
1403    }
1404
1405    /// Each group's least value at `path` in the JSON `column`.
1406    pub fn min_json<V>(
1407        self,
1408        column: Column<R, V>,
1409        path: Vec<JsonPathSegment>,
1410    ) -> Grouped<R, Option<Value>> {
1411        Query::from_any(self.any.min_json(column.name, path))
1412    }
1413
1414    /// Each group's greatest value of `column`.
1415    pub fn max<V: OrderedZeroValue>(
1416        self,
1417        column: Column<R, V>,
1418    ) -> Grouped<R, Option<V::Unwrapped>> {
1419        Query::from_any(self.any.max(column.name))
1420    }
1421
1422    /// Each group's greatest value at `path` in the JSON `column`.
1423    pub fn max_json<V>(
1424        self,
1425        column: Column<R, V>,
1426        path: Vec<JsonPathSegment>,
1427    ) -> Grouped<R, Option<Value>> {
1428        Query::from_any(self.any.max_json(column.name, path))
1429    }
1430}
1431
1432/// A row of `group_by(...)` and an aggregate: the group's columns, read with
1433/// [`GroupRow::get`], and the aggregate's `value`.
1434pub struct GroupRow<R, V> {
1435    /// The aggregate of the group's rows.
1436    pub value: V,
1437    /// The group's columns by client name.
1438    pub columns: Object,
1439    row: PhantomData<fn() -> R>,
1440}
1441
1442impl<R, V: Clone> Clone for GroupRow<R, V> {
1443    fn clone(&self) -> Self {
1444        GroupRow {
1445            value: self.value.clone(),
1446            columns: self.columns.clone(),
1447            row: PhantomData,
1448        }
1449    }
1450}
1451
1452impl<R, V: fmt::Debug> fmt::Debug for GroupRow<R, V> {
1453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454        f.debug_struct("GroupRow")
1455            .field("value", &self.value)
1456            .field("columns", &self.columns)
1457            .finish()
1458    }
1459}
1460
1461impl<R, V: PartialEq> PartialEq for GroupRow<R, V> {
1462    fn eq(&self, other: &Self) -> bool {
1463        self.value == other.value && self.columns == other.columns
1464    }
1465}
1466
1467impl<R, V: ZeroValue> QueryElement for GroupRow<R, V> {
1468    fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
1469        // `GroupProjection` puts the value after the group columns. Its name
1470        // is the function's, which can be another group column's.
1471        let mut columns: Object = (*entry.row).clone();
1472        let last = columns
1473            .get_index(columns.len().wrapping_sub(1))
1474            .map(|(k, v)| (k.clone(), v.clone()))
1475            .ok_or_else(|| ZeroValueError("a group row has no value".into()))?;
1476        columns.remove(&last.0);
1477        Ok(GroupRow {
1478            value: decode(&last.0, Some(&last.1))?,
1479            columns,
1480            row: PhantomData,
1481        })
1482    }
1483}
1484
1485impl<R, V> GroupRow<R, V> {
1486    /// A column the query groups by, read as a row's column is.
1487    pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
1488        group_column(&self.columns, column)
1489    }
1490}
1491
1492/// A row of `distinct(...)`: the values of its columns, read with
1493/// [`DistinctRow::get`].
1494pub struct DistinctRow<R> {
1495    /// The columns by client name.
1496    pub columns: Object,
1497    row: PhantomData<fn() -> R>,
1498}
1499
1500impl<R> Clone for DistinctRow<R> {
1501    fn clone(&self) -> Self {
1502        DistinctRow {
1503            columns: self.columns.clone(),
1504            row: PhantomData,
1505        }
1506    }
1507}
1508
1509impl<R> fmt::Debug for DistinctRow<R> {
1510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1511        f.debug_tuple("DistinctRow").field(&self.columns).finish()
1512    }
1513}
1514
1515impl<R> PartialEq for DistinctRow<R> {
1516    fn eq(&self, other: &Self) -> bool {
1517        self.columns == other.columns
1518    }
1519}
1520
1521impl<R> QueryElement for DistinctRow<R> {
1522    fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
1523        Ok(DistinctRow {
1524            columns: (*entry.row).clone(),
1525            row: PhantomData,
1526        })
1527    }
1528}
1529
1530impl<R> DistinctRow<R> {
1531    /// A column of the `distinct`, read as a row's column is.
1532    pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
1533        group_column(&self.columns, column)
1534    }
1535}
1536
1537fn group_column<R, C: ZeroValue>(
1538    columns: &Object,
1539    column: Column<R, C>,
1540) -> Result<C, ZeroValueError> {
1541    match columns.get(column.name) {
1542        Some(v) => decode(column.name, Some(v)),
1543        None => Err(ZeroValueError(format!(
1544            "{} is not a column of the group",
1545            column.name
1546        ))),
1547    }
1548}