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