Skip to main content

glacier/db/
query.rs

1//! Typed query building.
2//!
3//! Columns come from the model's generated `…Columns` struct, handed to a
4//! closure, so filters are checked by the compiler and complete in the IDE:
5//!
6//! ```no_run
7//! # use glacier::prelude::*;
8//! # #[derive(Model)] struct Post { id: i64, title: String, views: i64 }
9//! # async fn demo() -> glacier::Result<()> {
10//! let popular = Post::filter(|p| p.views.gt(100).and(p.title.like("%rust%")))
11//!     .order(|p| p.views.desc())
12//!     .limit(10)
13//!     .await?;
14//! # Ok(()) }
15//! ```
16
17use std::future::{Future, IntoFuture};
18use std::marker::PhantomData;
19use std::pin::Pin;
20
21use super::assoc::Preload;
22use super::sql::{Dialect, Sql};
23use super::value::{FromColumn, ToValue, Value};
24use super::{Connection, current_in};
25use crate::error::{Error, Result};
26use crate::model::Model;
27
28/// A column of model `M` holding values of type `T`.
29pub struct Col<M, T> {
30    name: &'static str,
31    _marker: PhantomData<fn() -> (M, T)>,
32}
33
34impl<M, T> Clone for Col<M, T> {
35    fn clone(&self) -> Self {
36        *self
37    }
38}
39
40impl<M, T> Copy for Col<M, T> {}
41
42impl<M, T> Col<M, T> {
43    #[doc(hidden)]
44    pub const fn new(name: &'static str) -> Self {
45        Self {
46            name,
47            _marker: PhantomData,
48        }
49    }
50
51    pub fn name(&self) -> &'static str {
52        self.name
53    }
54
55    pub fn asc(self) -> Order {
56        Order {
57            column: self.name,
58            descending: false,
59        }
60    }
61
62    pub fn desc(self) -> Order {
63        Order {
64            column: self.name,
65            descending: true,
66        }
67    }
68}
69
70impl<M, T: ToValue> Col<M, T> {
71    fn compare(self, op: &'static str, value: impl Into<T>) -> Expr {
72        Expr::Compare {
73            column: self.name,
74            op,
75            value: value.into().to_value(),
76        }
77    }
78
79    pub fn eq(self, value: impl Into<T>) -> Expr {
80        self.compare("=", value)
81    }
82
83    /// `eq` converting as a field assignment does (`"x"` for an
84    /// `Option<String>` column), for `.glacier`'s `where(status: "x")`.
85    #[doc(hidden)]
86    pub fn eq_field(self, value: impl crate::db::IntoField<T>) -> Expr {
87        Expr::Compare {
88            column: self.name,
89            op: "=",
90            value: value.into_field().to_value(),
91        }
92    }
93
94    /// `to` converting as a field assignment does, for `update_all(…)`.
95    #[doc(hidden)]
96    pub fn to_field(self, value: impl crate::db::IntoField<T>) -> Assign {
97        Assign {
98            column: self.name,
99            value: value.into_field().to_value(),
100        }
101    }
102
103    /// An assignment for [`Query::update_all`]: `p.published.to(false)`.
104    pub fn to(self, value: impl Into<T>) -> Assign {
105        Assign {
106            column: self.name,
107            value: value.into().to_value(),
108        }
109    }
110
111    pub fn ne(self, value: impl Into<T>) -> Expr {
112        self.compare("<>", value)
113    }
114
115    pub fn lt(self, value: impl Into<T>) -> Expr {
116        self.compare("<", value)
117    }
118
119    pub fn le(self, value: impl Into<T>) -> Expr {
120        self.compare("<=", value)
121    }
122
123    pub fn gt(self, value: impl Into<T>) -> Expr {
124        self.compare(">", value)
125    }
126
127    pub fn ge(self, value: impl Into<T>) -> Expr {
128        self.compare(">=", value)
129    }
130
131    /// `column IN (…)`. An empty list matches nothing.
132    pub fn is_in<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Expr {
133        Expr::In {
134            column: self.name,
135            values: values.into_iter().map(|v| v.into().to_value()).collect(),
136        }
137    }
138}
139
140impl<M> Col<M, String> {
141    /// SQL `LIKE`: `%` matches any run of characters, `_` any one.
142    pub fn like(self, pattern: impl Into<String>) -> Expr {
143        self.compare("LIKE", pattern.into())
144    }
145}
146
147impl<M, T> Col<M, Option<T>> {
148    pub fn is_null(self) -> Expr {
149        Expr::Null {
150            column: self.name,
151            negated: false,
152        }
153    }
154
155    pub fn is_not_null(self) -> Expr {
156        Expr::Null {
157            column: self.name,
158            negated: true,
159        }
160    }
161}
162
163/// A `WHERE` condition. Combine with `.and(..)`, `.or(..)` and `.not()`.
164#[derive(Debug, Clone, PartialEq)]
165pub enum Expr {
166    #[doc(hidden)]
167    Compare {
168        column: &'static str,
169        op: &'static str,
170        value: Value,
171    },
172    #[doc(hidden)]
173    In {
174        column: &'static str,
175        values: Vec<Value>,
176    },
177    #[doc(hidden)]
178    Null { column: &'static str, negated: bool },
179    #[doc(hidden)]
180    And(Box<Expr>, Box<Expr>),
181    #[doc(hidden)]
182    Or(Box<Expr>, Box<Expr>),
183    #[doc(hidden)]
184    Not(Box<Expr>),
185    #[doc(hidden)]
186    Raw(Sql),
187}
188
189impl Expr {
190    /// A raw SQL condition with `?` placeholders, for anything the typed
191    /// columns can't express.
192    pub fn raw(sql: &str, values: impl IntoIterator<Item = Value>) -> Expr {
193        Expr::Raw(Sql::raw(sql, values))
194    }
195
196    pub fn and(self, other: Expr) -> Expr {
197        Expr::And(Box::new(self), Box::new(other))
198    }
199
200    pub fn or(self, other: Expr) -> Expr {
201        Expr::Or(Box::new(self), Box::new(other))
202    }
203
204    #[allow(clippy::should_implement_trait)]
205    pub fn not(self) -> Expr {
206        Expr::Not(Box::new(self))
207    }
208
209    /// Writes the condition, its columns qualified with `table` when given
210    /// (`"posts"."title"`), as a query with joins needs.
211    fn write_in(&self, sql: &mut Sql, table: Option<&str>) {
212        let column = |sql: &mut Sql, name: &str| {
213            if let Some(table) = table {
214                sql.push_ident(table).push(".");
215            }
216            sql.push_ident(name);
217        };
218        match self {
219            // `= NULL` is never true in SQL; mean what the code says.
220            Expr::Compare {
221                column: column_name,
222                op,
223                value: Value::Null,
224            } if matches!(*op, "=" | "<>") => {
225                column(sql, column_name);
226                sql.push(if *op == "=" {
227                    " IS NULL"
228                } else {
229                    " IS NOT NULL"
230                });
231            }
232            Expr::Compare {
233                column: column_name,
234                op,
235                value,
236            } => {
237                column(sql, column_name);
238                sql.push(&format!(" {op} "));
239                sql.push_value(value.clone());
240            }
241            Expr::In { values, .. } if values.is_empty() => {
242                sql.push("1 = 0");
243            }
244            Expr::In {
245                column: column_name,
246                values,
247            } => {
248                column(sql, column_name);
249                sql.push_in(values.clone());
250            }
251            Expr::Null {
252                column: column_name,
253                negated,
254            } => {
255                column(sql, column_name);
256                sql.push(if *negated { " IS NOT NULL" } else { " IS NULL" });
257            }
258            Expr::And(a, b) | Expr::Or(a, b) => {
259                let op = if matches!(self, Expr::And(..)) {
260                    " AND "
261                } else {
262                    " OR "
263                };
264                sql.push("(");
265                a.write_in(sql, table);
266                sql.push(op);
267                b.write_in(sql, table);
268                sql.push(")");
269            }
270            Expr::Not(e) => {
271                sql.push("NOT (");
272                e.write_in(sql, table);
273                sql.push(")");
274            }
275            Expr::Raw(raw) => {
276                sql.push("(");
277                sql.append(raw.clone());
278                sql.push(")");
279            }
280        }
281    }
282}
283
284/// An `ORDER BY` term, from `column.asc()` or `column.desc()`.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub struct Order {
287    column: &'static str,
288    descending: bool,
289}
290
291/// `column = value` in [`Query::update_all`]; made with `Col::to`.
292#[derive(Debug, Clone)]
293pub struct Assign {
294    column: &'static str,
295    value: Value,
296}
297
298impl Assign {
299    /// `column = value`, by the column's name.
300    pub(crate) fn new(column: &'static str, value: Value) -> Self {
301        Assign { column, value }
302    }
303}
304
305impl Order {
306    pub(crate) fn by(column: &'static str, descending: bool) -> Self {
307        Self { column, descending }
308    }
309}
310
311/// A query for records of `M`. Build it up, then `.await` it for a
312/// `Vec<M>`, or finish with `.first()`, `.one()`, `.count()`,
313/// `.exists()` or `.delete_all()`.
314pub struct Query<M> {
315    filter: Option<Expr>,
316    order: Vec<Order>,
317    limit: Option<u64>,
318    offset: Option<u64>,
319    conn: Option<Connection>,
320    preloads: Vec<Preload<M>>,
321    /// `order_raw` clauses, after the typed ones.
322    raw_order: Vec<String>,
323    /// `SELECT DISTINCT`.
324    distinct: bool,
325    /// Associated tables joined in, with conditions on their columns.
326    joins: Vec<Join>,
327    /// The owner columns and values from `Model::for(access)`, which
328    /// records built from the query get.
329    owners: Vec<(&'static str, Value)>,
330    /// Through `Model::for(access)`, or an association from a record that
331    /// was: what the unscoped-read check looks for.
332    scoped: bool,
333    /// For a `soft_deletes` model: which rows, by `deleted_at`.
334    trashed: Trashed,
335    _model: PhantomData<fn() -> M>,
336}
337
338/// Soft-deleted rows in a query: left out (the default), with the rest,
339/// or only them.
340#[derive(Clone, Copy, PartialEq)]
341enum Trashed {
342    Without,
343    With,
344    Only,
345}
346
347/// An `INNER JOIN` from `Query::join`.
348#[derive(Clone)]
349struct Join {
350    table: &'static str,
351    /// The table it joins to: the query's model's, or for a join table's
352    /// far side, the join table.
353    from: &'static str,
354    /// The joining columns: `from`'s, then the joined table's.
355    own: &'static str,
356    other: &'static str,
357    condition: Option<Expr>,
358}
359
360/// A query can be reused: count it, then fetch a page of it.
361impl<M> Clone for Query<M> {
362    fn clone(&self) -> Self {
363        Self {
364            filter: self.filter.clone(),
365            order: self.order.clone(),
366            limit: self.limit,
367            offset: self.offset,
368            conn: self.conn.clone(),
369            preloads: self.preloads.clone(),
370            raw_order: self.raw_order.clone(),
371            distinct: self.distinct,
372            joins: self.joins.clone(),
373            owners: self.owners.clone(),
374            scoped: self.scoped,
375            trashed: self.trashed,
376            _model: PhantomData,
377        }
378    }
379}
380
381impl<M: Model> Default for Query<M> {
382    fn default() -> Self {
383        Self::new()
384    }
385}
386
387impl<M: Model> Query<M> {
388    /// All records, with the model's default scope (`default_scope …` in
389    /// `.glacier`) applied, as every query starts.
390    pub fn new() -> Self {
391        M::default_scope(Self::unscoped())
392    }
393
394    /// All records, ignoring the model's default scope.
395    pub fn unscoped() -> Self {
396        Self {
397            filter: None,
398            order: Vec::new(),
399            limit: None,
400            offset: None,
401            conn: None,
402            preloads: Vec::new(),
403            raw_order: Vec::new(),
404            distinct: false,
405            joins: Vec::new(),
406            owners: Vec::new(),
407            scoped: false,
408            trashed: Trashed::Without,
409            _model: PhantomData,
410        }
411    }
412
413    /// Soft-deleted records too (`soft_deletes`).
414    pub fn with_trashed(mut self) -> Self {
415        self.trashed = Trashed::With;
416        self
417    }
418
419    /// Only soft-deleted records.
420    pub fn only_trashed(mut self) -> Self {
421        self.trashed = Trashed::Only;
422        self
423    }
424
425    /// Only the rows `access` owns: each of the model's owner columns
426    /// equal to the access's value for it. When the access has no value
427    /// for one (a user's access, for an org's rows), nothing matches.
428    pub fn owned_by(mut self, access: &dyn crate::access::Access) -> Self {
429        self.scoped = true;
430        for &(column, key) in M::OWNER {
431            match access.owns(key) {
432                Some(value) => {
433                    self.owners.push((column, value.clone()));
434                    let own = Expr::Compare {
435                        column,
436                        op: "=",
437                        value,
438                    };
439                    // `global: true`: the tenant's rows and the shared ones.
440                    self = if M::GLOBAL_ROWS {
441                        self.filter(|_| {
442                            own.or(Expr::Null {
443                                column,
444                                negated: false,
445                            })
446                        })
447                    } else {
448                        self.filter(|_| own)
449                    };
450                }
451                None => self = self.filter(|_| Expr::raw("1 = 0", [])),
452            }
453        }
454        self
455    }
456
457    /// For a write under a tenant's access, the tenant's rows only: shared
458    /// rows (`global: true`) change only `unscoped`.
459    fn without_shared(self) -> Self {
460        if !M::GLOBAL_ROWS || !self.scoped || crate::access::may_change_shared() {
461            return self;
462        }
463        let mut query = self;
464        for &(column, _) in M::OWNER {
465            query = query.filter(|_| Expr::Null {
466                column,
467                negated: true,
468            });
469        }
470        query
471    }
472
473    /// The record with this primary key among the query's, or `404 Not
474    /// Found`: `Post.for(access).find(params[:id])!` finds another org's
475    /// post no more than a missing one.
476    pub async fn find(self, id: impl crate::db::ToValue) -> Result<M> {
477        let id = match id.to_value() {
478            Value::Text(text) if M::INTEGER_KEY => match text.trim().parse::<i64>() {
479                Ok(id) => Value::Int(id),
480                Err(_) => return Err(Error::not_found()),
481            },
482            value => value,
483        };
484        self.filter(|_| Expr::Compare {
485            column: M::PRIMARY_KEY,
486            op: "=",
487            value: id,
488        })
489        .one()
490        .await
491    }
492
493    /// A new record with `change` setting its fields, and the query's owner
494    /// columns set: `Note.for(access).build(title: "…")` in `.glacier`.
495    pub fn build_with(&self, change: impl FnOnce(&mut M)) -> M
496    where
497        M: Default,
498    {
499        let mut record = M::default();
500        change(&mut record);
501        for (column, value) in &self.owners {
502            record.set_owner(column, &value_text(value));
503        }
504        record
505    }
506
507    /// A new record from params, with the query's owner columns set (the
508    /// org's id), as Rails' `current_org.posts.build(params)`.
509    pub fn build(&self, params: impl Into<crate::Params>) -> M
510    where
511        M: Default,
512    {
513        let mut record = M::build(params);
514        for (column, value) in &self.owners {
515            record.set_owner(column, &value_text(value));
516        }
517        record
518    }
519
520    /// Adds a condition; several `filter` calls are combined with `AND`.
521    pub fn filter(mut self, condition: impl FnOnce(&M::Columns) -> Expr) -> Self {
522        // Values for `encrypted(deterministic)` columns, as they're stored.
523        let expr = crate::encryption::query_condition::<M>(condition(&M::columns()));
524        self.filter = Some(match self.filter.take() {
525            Some(existing) => existing.and(expr),
526            None => expr,
527        });
528        self
529    }
530
531    /// Adds a condition in SQL, `?` for each of `values`, as Rails'
532    /// `where("…", …)`: `Post.where_sql("NOT EXISTS (SELECT 1 FROM comments
533    /// WHERE comments.post_id = posts.id)", [])`.
534    pub fn where_sql(self, sql: &str, values: impl IntoIterator<Item = Value>) -> Self {
535        let expr = Expr::raw(sql, values);
536        self.filter(|_| expr)
537    }
538
539    /// Adds an ordering; earlier `order` calls take precedence.
540    pub fn order(mut self, order: impl FnOnce(&M::Columns) -> Order) -> Self {
541        self.order.push(order(&M::columns()));
542        self
543    }
544
545    /// Orders by the request's `sort` param, as JSON:API has it:
546    /// `?sort=-inserted_at,title` sorts by `inserted_at` descending, then
547    /// `title`. Only the columns in `allowed` can be named; anything else is
548    /// a `400 Bad Request`. Given, it replaces the query's own order;
549    /// absent or empty, the query keeps it:
550    ///
551    /// ```ignore
552    /// let books = Book::order(|b| b.title.asc())
553    ///     .sort(&params, ["title", "inserted_at"])?
554    ///     .await?;
555    /// ```
556    ///
557    /// # Errors
558    ///
559    /// `400 Bad Request` naming the column that can't be sorted by.
560    ///
561    /// # Panics
562    ///
563    /// If `allowed` names a column the model doesn't have.
564    pub fn sort(
565        mut self,
566        params: &crate::context::Params,
567        allowed: impl AsRef<[&'static str]>,
568    ) -> Result<Self> {
569        let allowed = allowed.as_ref();
570        for column in allowed {
571            assert!(
572                M::COLUMNS.contains(column),
573                "sort: `{}` has no column `{column}`",
574                M::TABLE
575            );
576        }
577        let Some(text) = params.get("sort").map(str::trim).filter(|t| !t.is_empty()) else {
578            return Ok(self);
579        };
580        let mut order = Vec::new();
581        for field in text.split(',').map(str::trim) {
582            let (name, descending) = match field.strip_prefix('-') {
583                Some(name) => (name, true),
584                None => (field, false),
585            };
586            let column = allowed.iter().find(|c| **c == name).ok_or_else(|| {
587                Error::bad_request(format!(
588                    "can't sort by `{name}`; sort by {}",
589                    allowed
590                        .iter()
591                        .map(|c| format!("`{c}`"))
592                        .collect::<Vec<_>>()
593                        .join(", ")
594                ))
595            })?;
596            order.push(Order { column, descending });
597        }
598        self.order = order;
599        self.raw_order.clear();
600        Ok(self)
601    }
602
603    /// Orders by raw SQL, as Rails' `.order("first_name ASC, last_name
604    /// ASC")`, after any typed orders. Never pass it user input: build it
605    /// from fixed choices.
606    pub fn order_raw(mut self, sql: impl Into<String>) -> Self {
607        self.raw_order.push(sql.into());
608        self
609    }
610
611    pub fn limit(mut self, limit: u64) -> Self {
612        self.limit = Some(limit);
613        self
614    }
615
616    pub fn offset(mut self, offset: u64) -> Self {
617        self.offset = Some(offset);
618        self
619    }
620
621    /// One page of the results: `Post.order(id: :desc).page(page)`.
622    pub fn page(self, page: crate::pagination::Page) -> Self {
623        self.limit(page.per_page)
624            .offset((page.number.max(1) - 1) * page.per_page)
625    }
626
627    /// Runs on `conn` instead of the ambient connection.
628    pub fn on(mut self, conn: impl Into<Connection>) -> Self {
629        self.conn = Some(conn.into());
630        self
631    }
632
633    /// Loads an association for every record with one extra query.
634    pub fn preload<P: Into<Preload<M>>>(
635        mut self,
636        association: impl FnOnce(&M::Columns) -> P,
637    ) -> Self {
638        self.preloads.push(association(&M::columns()).into());
639        self
640    }
641
642    /// Counts a `has_many` association for each record loaded, without
643    /// loading its records: `Author.with_count(:books)`, then
644    /// `author.books.count()`, in one grouped query.
645    ///
646    /// # Panics
647    ///
648    /// For an association that isn't a `has_many` (without `through`).
649    pub fn with_count<C>(
650        mut self,
651        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
652    ) -> Self
653    where
654        M: 'static,
655    {
656        let preload = association(&M::columns())
657            .counting()
658            .expect("with_count counts a `has_many` association (not one `through` a join table)");
659        self.preloads.push(preload);
660        self
661    }
662
663    /// How many matches each value of `column` has, the values as text:
664    /// an association counted per parent.
665    pub(crate) async fn count_by(self, column: &'static str) -> Result<Vec<(String, i64)>> {
666        let conn = self.connection()?;
667        let col = self.col(column);
668        let mut sql = Sql::new();
669        sql.push(&format!(
670            "SELECT CAST({col} AS TEXT) AS key, COUNT(*) AS value FROM "
671        ));
672        self.write_from(&mut sql);
673        self.write_where(&mut sql);
674        sql.push(&format!(" GROUP BY {col}"));
675        let rows = conn.read_all(&sql).await?;
676        rows.iter()
677            .map(|row| Ok((row.get("key")?, row.get("value")?)))
678            .collect()
679    }
680
681    /// A loaded record's own query (deleting or reloading it): the record
682    /// was read already, so this isn't another read.
683    pub(crate) fn of_record(mut self) -> Self {
684        self.scoped = true;
685        self
686    }
687
688    /// Loading an association: scoped by the record it's loaded from.
689    pub(crate) fn via_association(mut self) -> Self {
690        self.scoped = true;
691        self
692    }
693
694    /// A constrained preload's query (`preload(books: Book.where(…))`),
695    /// to which the association adds its own conditions. A limit or
696    /// offset would count across every record's children together, so
697    /// they're refused.
698    pub(crate) fn for_association(self) -> Result<Self> {
699        if self.limit.is_some() || self.offset.is_some() {
700            return Err(Error::internal(format!(
701                "a preload's query can't take `limit` or `offset` (they'd count every {}'s \
702                 children together); filter or order it instead",
703                std::any::type_name::<M>()
704            )));
705        }
706        Ok(self.via_association())
707    }
708
709    /// Whether the query has an order of its own.
710    pub(crate) fn is_ordered(&self) -> bool {
711        !self.order.is_empty() || !self.raw_order.is_empty()
712    }
713
714    fn connection(&self) -> Result<Connection> {
715        if !M::OWNER.is_empty() && !self.scoped {
716            crate::access::check_unscoped(M::TABLE)?;
717        }
718        match &self.conn {
719            Some(conn) => Ok(conn.clone()),
720            None => current_in(M::DATABASE),
721        }
722    }
723
724    fn write_where(&self, sql: &mut Sql) {
725        let own = if self.joins.is_empty() {
726            None
727        } else {
728            Some(M::TABLE)
729        };
730        let mut conditions = Vec::new();
731        if let Some(filter) = &self.filter {
732            conditions.push((filter, own));
733        }
734        // `soft_deletes`: the rows still here, unless asked otherwise.
735        let trashed = M::SOFT_DELETE.and_then(|column| match self.trashed {
736            Trashed::Without => Some(Expr::Null {
737                column,
738                negated: false,
739            }),
740            Trashed::Only => Some(Expr::Null {
741                column,
742                negated: true,
743            }),
744            Trashed::With => None,
745        });
746        if let Some(trashed) = &trashed {
747            conditions.push((trashed, own));
748        }
749        for join in &self.joins {
750            if let Some(condition) = &join.condition {
751                conditions.push((condition, Some(join.table)));
752            }
753        }
754        for (i, (condition, table)) in conditions.into_iter().enumerate() {
755            sql.push(if i == 0 { " WHERE " } else { " AND " });
756            condition.write_in(sql, table);
757        }
758    }
759
760    /// The table, and any joined tables.
761    fn write_from(&self, sql: &mut Sql) {
762        sql.push_ident(M::TABLE);
763        for join in &self.joins {
764            sql.push(" INNER JOIN ")
765                .push_ident(join.table)
766                .push(" ON ")
767                .push_ident(join.table)
768                .push(".")
769                .push_ident(join.other)
770                .push(" = ")
771                .push_ident(join.from)
772                .push(".")
773                .push_ident(join.own);
774        }
775    }
776
777    /// One of the model's columns as SQL: qualified when tables are joined,
778    /// so a shared name (`id`) isn't ambiguous.
779    fn col(&self, name: &str) -> String {
780        let quoted = super::sql::quote_ident(name);
781        if self.joins.is_empty() {
782            quoted
783        } else {
784            format!("{}.{quoted}", super::sql::quote_ident(M::TABLE))
785        }
786    }
787
788    /// One page of the matches by cursor (keyset) pagination, in the
789    /// query's order with the primary key as the tie-breaker:
790    /// `Post::order(|p| p.inserted_at.desc()).cursor(page).await?`. Fast at
791    /// any depth, and no row is skipped or repeated when rows change between
792    /// pages. Order by columns that are never NULL; `order_raw` can't be
793    /// paged this way.
794    pub async fn cursor(
795        mut self,
796        page: crate::pagination::CursorPage,
797    ) -> Result<crate::pagination::Cursored<M>> {
798        use crate::pagination::{Cursor, Cursored};
799        if !self.raw_order.is_empty() {
800            return Err(Error::internal(
801                "cursor pagination needs typed order columns: use order(), not order_raw()",
802            ));
803        }
804        if let Some(first) = self.order.first()
805            && first.column != M::PRIMARY_KEY
806        {
807            crate::db::warn_unindexed(&self.connection()?, M::TABLE, first.column).await;
808        }
809        // The keys: the query's order, then the primary key.
810        let mut keys = self.order.clone();
811        if !keys.iter().any(|o| o.column == M::PRIMARY_KEY) {
812            let descending = keys.last().is_some_and(|o| o.descending);
813            keys.push(Order {
814                column: M::PRIMARY_KEY,
815                descending,
816            });
817        }
818        let backwards = page.cursor.as_ref().is_some_and(|c| c.backwards);
819        // Going back, read the other way and turn the rows round after.
820        let order: Vec<Order> = keys
821            .iter()
822            .map(|o| Order {
823                column: o.column,
824                descending: o.descending != backwards,
825            })
826            .collect();
827        if let Some(cursor) = &page.cursor {
828            if cursor.keys.len() != order.len() {
829                return Err(Error::unprocessable("invalid cursor"));
830            }
831            let after = self.keyset_after(&order, &cursor.keys);
832            self = self.filter(|_| after);
833        }
834        self.order = order;
835        self.limit = Some(page.per_page + 1);
836        self.offset = None;
837        let mut records = self.all().await?;
838        let more = records.len() as u64 > page.per_page;
839        records.truncate(page.per_page as usize);
840        if backwards {
841            records.reverse();
842        }
843        let key_values = |record: &M| -> Vec<Value> {
844            let values = record.values();
845            keys.iter()
846                .map(|o| {
847                    if o.column == M::PRIMARY_KEY {
848                        record.id_value()
849                    } else {
850                        values
851                            .iter()
852                            .find(|(column, _)| *column == o.column)
853                            .map_or(Value::Null, |(_, v)| v.clone())
854                    }
855                })
856                .collect()
857        };
858        let cursor = |record: &M, backwards: bool| {
859            Cursor {
860                keys: key_values(record),
861                backwards,
862            }
863            .encode()
864        };
865        let (next, prev) = if backwards {
866            // Come back from a later page: there's always a next one.
867            (
868                records.last().map(|r| cursor(r, false)),
869                records.first().filter(|_| more).map(|r| cursor(r, true)),
870            )
871        } else {
872            (
873                records.last().filter(|_| more).map(|r| cursor(r, false)),
874                records
875                    .first()
876                    .filter(|_| page.cursor.is_some())
877                    .map(|r| cursor(r, true)),
878            )
879        };
880        Ok(Cursored {
881            records,
882            next,
883            prev,
884            per_page: page.per_page,
885        })
886    }
887
888    /// The matches in batches of `size`, by the same keyset paging as
889    /// `cursor` (so rows changing meanwhile are neither skipped nor
890    /// repeated), as Rails' `in_batches`/`find_each`:
891    ///
892    /// ```ignore
893    /// let mut batches = Post::all().batches(1000);
894    /// while let Some(posts) = batches.next().await? { … }
895    /// ```
896    pub fn batches(self, size: u64) -> Batches<M> {
897        Batches {
898            query: Some(self),
899            page: crate::pagination::CursorPage::first(size),
900        }
901    }
902
903    /// How many rows match, cheaply: for a whole Postgres table, the
904    /// planner's estimate (from its statistics, so approximate); otherwise
905    /// an exact count.
906    pub async fn estimated_count(self) -> Result<i64> {
907        let conn = self.connection()?;
908        if conn.dialect() == Dialect::Postgres && self.filter.is_none() && self.joins.is_empty() {
909            let mut sql = Sql::new();
910            sql.push("SELECT reltuples::bigint AS estimate FROM pg_class WHERE relname = ");
911            sql.push_value(Value::Text(M::TABLE.to_owned()));
912            let rows = conn.read_all(&sql).await?;
913            // -1 (or none) until the table has been analyzed.
914            if let Some(estimate) = rows.first().and_then(|r| r.get::<i64>("estimate").ok())
915                && estimate >= 0
916            {
917                return Ok(estimate);
918            }
919        }
920        self.count().await
921    }
922
923    /// The rows after `keys` in `order`: `(a > ?) OR (a = ? AND b > ?) OR …`,
924    /// each column compared the way it's sorted.
925    fn keyset_after(&self, order: &[Order], keys: &[Value]) -> Expr {
926        let mut terms = Vec::new();
927        let mut values = Vec::new();
928        for i in 0..order.len() {
929            let mut parts = Vec::new();
930            for j in 0..i {
931                parts.push(format!("{} = ?", self.col(order[j].column)));
932                values.push(keys[j].clone());
933            }
934            let op = if order[i].descending { "<" } else { ">" };
935            parts.push(format!("{} {op} ?", self.col(order[i].column)));
936            values.push(keys[i].clone());
937            terms.push(format!("({})", parts.join(" AND ")));
938        }
939        Expr::raw(&terms.join(" OR "), values)
940    }
941
942    /// Joins an association's table, keeping the matches with a related
943    /// record that meets `condition`, as Rails' `joins(:author).where(users:
944    /// {…})`: `Post::all().join(|p| p.author, |a| a.name.eq("Ada"))`. A
945    /// `has_many` join gives a match per related record; add `distinct()`.
946    ///
947    /// Through a join table (`has_many :tags, through: :book_tags`), it
948    /// joins that table, then the other model's.
949    pub fn join<C: Model>(
950        mut self,
951        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
952        condition: impl FnOnce(&C::Columns) -> Expr,
953    ) -> Self {
954        let association = association(&M::columns());
955        let condition = condition(&C::columns());
956        let condition = match association.kind {
957            Some(kind) => condition.and(super::assoc::of_kind(kind)),
958            None => condition,
959        };
960        self.push_join(&association, Some(condition));
961        self
962    }
963
964    /// The joins for an association: its table, or a join table and then
965    /// the other model's.
966    fn push_join<C: Model>(
967        &mut self,
968        association: &super::Association<M, C>,
969        condition: Option<Expr>,
970    ) {
971        match (association.join, association.through) {
972            (Some((own, other)), _) => self.joins.push(Join {
973                table: C::TABLE,
974                from: M::TABLE,
975                own,
976                other,
977                condition,
978            }),
979            (None, Some((table, mine, theirs))) => {
980                self.joins.push(Join {
981                    table,
982                    from: M::TABLE,
983                    own: M::PRIMARY_KEY,
984                    other: mine,
985                    condition: None,
986                });
987                self.joins.push(Join {
988                    table: C::TABLE,
989                    from: table,
990                    own: theirs,
991                    other: C::PRIMARY_KEY,
992                    condition,
993                });
994            }
995            (None, None) => unreachable!("an association joins directly or through a table"),
996        }
997    }
998
999    /// The records with at least one associated record matching `inner`,
1000    /// as Laravel's `whereHas`: `Author.where_has(:books, published:
1001    /// true)` in `.glacier`. One `EXISTS` subquery, so each record comes
1002    /// once, and the associated model's default scope (and soft deletes)
1003    /// apply.
1004    pub fn where_has<C: Model>(
1005        self,
1006        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
1007        inner: impl FnOnce(Query<C>) -> Query<C>,
1008    ) -> Self {
1009        let exists = self.exists_in(association(&M::columns()), inner(Query::new()));
1010        self.filter(|_| exists)
1011    }
1012
1013    /// The records with no associated record at all, as Laravel's
1014    /// `doesntHave`: `Author.without(:books)`.
1015    pub fn without<C: Model>(
1016        self,
1017        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
1018    ) -> Self {
1019        let exists = self.exists_in(association(&M::columns()), Query::new());
1020        self.filter(|_| exists.not())
1021    }
1022
1023    /// `EXISTS (SELECT 1 FROM child WHERE child.key = parent.key AND …)`.
1024    fn exists_in<C: Model>(&self, association: super::Association<M, C>, inner: Query<C>) -> Expr {
1025        let quote = super::sql::quote_ident;
1026        let correlated = match (association.join, association.through) {
1027            (Some((own, other)), _) => format!(
1028                "{}.{} = {}.{}",
1029                quote(C::TABLE),
1030                quote(other),
1031                quote(M::TABLE),
1032                quote(own)
1033            ),
1034            // Through a join table: the other's id among this record's rows.
1035            (None, Some((table, mine, theirs))) => format!(
1036                "{}.{} IN (SELECT {}.{} FROM {} WHERE {}.{} = {}.{})",
1037                quote(C::TABLE),
1038                quote(C::PRIMARY_KEY),
1039                quote(table),
1040                quote(theirs),
1041                quote(table),
1042                quote(table),
1043                quote(mine),
1044                quote(M::TABLE),
1045                quote(M::PRIMARY_KEY)
1046            ),
1047            (None, None) => unreachable!("an association joins directly or through a table"),
1048        };
1049        let mut inner = inner.filter(|_| Expr::raw(&correlated, []));
1050        if let Some(kind) = association.kind {
1051            inner = inner.filter(|_| super::assoc::of_kind(kind));
1052        }
1053        let mut sql = Sql::new();
1054        sql.push("EXISTS (");
1055        sql.append(inner.select("1"));
1056        sql.push(")");
1057        Expr::Raw(sql)
1058    }
1059
1060    /// Joins an association's table: the matches with at least one related
1061    /// record, as Rails' `joins(:comments)`.
1062    pub fn joins<C: Model>(
1063        mut self,
1064        association: impl FnOnce(&M::Columns) -> super::Association<M, C>,
1065    ) -> Self {
1066        let association = association(&M::columns());
1067        let condition = association.kind.map(super::assoc::of_kind);
1068        self.push_join(&association, condition);
1069        self
1070    }
1071
1072    fn select(&self, columns: &str) -> Sql {
1073        let mut sql = Sql::new();
1074        let distinct = if self.distinct { "DISTINCT " } else { "" };
1075        let columns = if columns == "*" && !self.joins.is_empty() {
1076            format!("{}.*", super::sql::quote_ident(M::TABLE))
1077        } else {
1078            columns.to_owned()
1079        };
1080        sql.push(&format!("SELECT {distinct}{columns} FROM "));
1081        self.write_from(&mut sql);
1082        self.write_where(&mut sql);
1083        if !self.order.is_empty() || !self.raw_order.is_empty() {
1084            sql.push(" ORDER BY ");
1085            for (i, order) in self.order.iter().enumerate() {
1086                if i > 0 {
1087                    sql.push(", ");
1088                }
1089                sql.push(&self.col(order.column)).push(if order.descending {
1090                    " DESC"
1091                } else {
1092                    " ASC"
1093                });
1094            }
1095            for (i, order) in self.raw_order.iter().enumerate() {
1096                if i > 0 || !self.order.is_empty() {
1097                    sql.push(", ");
1098                }
1099                sql.push(order);
1100            }
1101        }
1102        match (self.limit, self.offset) {
1103            (Some(limit), Some(offset)) => {
1104                sql.push(&format!(" LIMIT {limit} OFFSET {offset}"));
1105            }
1106            (Some(limit), None) => {
1107                sql.push(&format!(" LIMIT {limit}"));
1108            }
1109            // SQLite requires a LIMIT before OFFSET (-1 means none);
1110            // Postgres rejects a negative LIMIT.
1111            (None, Some(offset)) => {
1112                sql.push_dialect(
1113                    &format!(" OFFSET {offset}"),
1114                    &format!(" LIMIT -1 OFFSET {offset}"),
1115                );
1116            }
1117            (None, None) => {}
1118        }
1119        sql
1120    }
1121
1122    /// The SQL this query would run, for debugging and tests.
1123    pub fn to_sql(&self, dialect: Dialect) -> (String, Vec<Value>) {
1124        self.select("*").render(dialect)
1125    }
1126
1127    pub async fn all(self) -> Result<Vec<M>> {
1128        let conn = self.connection()?;
1129        let rows = conn.read_all(&self.select("*")).await?;
1130        let mut records = rows.iter().map(M::from_row).collect::<Result<Vec<M>>>()?;
1131        for preload in &self.preloads {
1132            preload.run(&mut records, conn.clone()).await?;
1133        }
1134        Ok(records)
1135    }
1136
1137    /// The first match (by primary key unless ordered otherwise).
1138    pub async fn first(mut self) -> Result<Option<M>> {
1139        if self.order.is_empty() {
1140            self.order.push(Order {
1141                column: M::PRIMARY_KEY,
1142                descending: false,
1143            });
1144        }
1145        Ok(self.limit(1).all().await?.into_iter().next())
1146    }
1147
1148    /// The last match: the ordering reversed, or the highest primary key.
1149    pub async fn last(mut self) -> Result<Option<M>> {
1150        if self.order.is_empty() {
1151            self.order.push(Order {
1152                column: M::PRIMARY_KEY,
1153                descending: true,
1154            });
1155        } else {
1156            for order in &mut self.order {
1157                order.descending = !order.descending;
1158            }
1159        }
1160        Ok(self.limit(1).all().await?.into_iter().next())
1161    }
1162
1163    /// The first `n` matches.
1164    pub async fn take(self, n: u64) -> Result<Vec<M>> {
1165        self.limit(n).all().await
1166    }
1167
1168    /// One column of every match, without loading records:
1169    /// `Post::all().pluck(|p| p.title).await?` → `Vec<String>`.
1170    pub async fn pluck<T: FromColumn>(
1171        self,
1172        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1173    ) -> Result<Vec<T>> {
1174        let name = column(&M::columns()).name();
1175        let conn = self.connection()?;
1176        let selected = format!("{} AS {}", self.col(name), super::sql::quote_ident(name));
1177        let rows = conn.read_all(&self.select(&selected)).await?;
1178        rows.iter().map(|row| row.get(name)).collect()
1179    }
1180
1181    /// The primary keys of every match.
1182    pub async fn ids(self) -> Result<Vec<i64>> {
1183        let conn = self.connection()?;
1184        let selected = format!(
1185            "{} AS {}",
1186            self.col(M::PRIMARY_KEY),
1187            super::sql::quote_ident(M::PRIMARY_KEY)
1188        );
1189        let rows = conn.read_all(&self.select(&selected)).await?;
1190        // `bigint` keys, or Rails' `integer` ones.
1191        rows.iter()
1192            .map(|row| {
1193                row.get::<i64>(M::PRIMARY_KEY)
1194                    .or_else(|_| row.get::<i32>(M::PRIMARY_KEY).map(i64::from))
1195            })
1196            .collect()
1197    }
1198
1199    /// Sets columns on every match in one statement, returning how many
1200    /// changed. Like Rails' `update_all`, it skips validations and
1201    /// callbacks: `Post::filter(…).update_all(|p| [p.published.to(false)])`.
1202    pub async fn update_all<I>(self, assignments: impl FnOnce(&M::Columns) -> I) -> Result<u64>
1203    where
1204        I: IntoIterator<Item = Assign>,
1205    {
1206        self.refuse_joins("update_all")?;
1207        let query = self.without_shared();
1208        let conn = query.connection()?;
1209        let mut sql = Sql::new();
1210        sql.push("UPDATE ").push_ident(M::TABLE).push(" SET ");
1211        let mut any = false;
1212        for (i, assign) in assignments(&M::columns()).into_iter().enumerate() {
1213            if i > 0 {
1214                sql.push(", ");
1215            }
1216            sql.push_ident(assign.column).push(" = ");
1217            sql.push_value(crate::encryption::stored::<M>(assign.column, assign.value)?);
1218            any = true;
1219        }
1220        if !any {
1221            return Ok(0);
1222        }
1223        query.write_target(&mut sql);
1224        Ok(conn.execute(&sql).await?)
1225    }
1226
1227    /// The rows an `update_all` or `delete_all` changes: those matching,
1228    /// or with a `limit` or `offset`, only the rows the query would load
1229    /// (`WHERE id IN (SELECT id … ORDER BY … LIMIT 1)`), as Rails does.
1230    fn write_target(&self, sql: &mut Sql) {
1231        if self.limit.is_none() && self.offset.is_none() {
1232            self.write_where(sql);
1233            return;
1234        }
1235        sql.push(" WHERE ").push_ident(M::PRIMARY_KEY).push(" IN (");
1236        sql.append(self.select(&super::sql::quote_ident(M::PRIMARY_KEY)));
1237        sql.push(")");
1238    }
1239
1240    /// Only distinct rows, as Rails' `distinct`: with `pluck`, each value
1241    /// once (`Post::all().distinct().pluck(|p| p.status)`).
1242    pub fn distinct(mut self) -> Self {
1243        self.distinct = true;
1244        self
1245    }
1246
1247    /// The sum of a numeric column over the matches, 0 when there are none,
1248    /// as Rails' `sum`: `Post::all().sum(|p| p.views)`. Integer columns sum
1249    /// to an `i64`.
1250    pub fn sum<T: Summable>(
1251        self,
1252        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1253    ) -> impl Future<Output = Result<T::Sum>> + Send {
1254        let column = self.col(column(&M::columns()).name());
1255        let expression = T::sum(&column);
1256        async move {
1257            // SQLite adds decimals as floats (29.990000000000002): add
1258            // them here, exactly.
1259            if T::EXACT_ON_SQLITE && self.connection()?.dialect() == super::Dialect::Sqlite {
1260                let conn = self.connection()?;
1261                let mut sql = Sql::new();
1262                sql.push(&format!("SELECT {column} AS value FROM "));
1263                self.write_from(&mut sql);
1264                self.write_where(&mut sql);
1265                let mut total = T::Sum::default();
1266                for row in conn.read_all(&sql).await?.iter() {
1267                    if let Some(value) = row.get::<Option<T::Sum>>("value")? {
1268                        total = T::add(total, value);
1269                    }
1270                }
1271                return Ok(total);
1272            }
1273            let value = self.aggregate::<Option<T::Sum>>(&expression).await?;
1274            Ok(value.unwrap_or_default())
1275        }
1276    }
1277
1278    /// The mean of a numeric column, `None` without matches. A float,
1279    /// whatever the column (Rails returns a `BigDecimal`).
1280    pub fn average<T: Summable>(
1281        self,
1282        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1283    ) -> impl Future<Output = Result<Option<f64>>> + Send {
1284        let expression = average_sql(&self.col(column(&M::columns()).name()));
1285        async move { self.aggregate(&expression).await }
1286    }
1287
1288    /// The smallest value of a column, `None` without matches.
1289    pub fn minimum<T: Aggregable>(
1290        self,
1291        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1292    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
1293        let expression = format!("MIN({})", self.col(column(&M::columns()).name()));
1294        async move { self.aggregate(&expression).await }
1295    }
1296
1297    /// The largest value of a column, `None` without matches.
1298    pub fn maximum<T: Aggregable>(
1299        self,
1300        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1301    ) -> impl Future<Output = Result<Option<T::Value>>> + Send {
1302        let expression = format!("MAX({})", self.col(column(&M::columns()).name()));
1303        async move { self.aggregate(&expression).await }
1304    }
1305
1306    /// Groups the matches by a column, to count or total each group:
1307    /// `Post::all().group(|p| p.status).count()` → `[("draft", 3), …]`,
1308    /// in the order of the column's values.
1309    pub fn group<K: FromColumn>(
1310        self,
1311        column: impl FnOnce(&M::Columns) -> Col<M, K>,
1312    ) -> Grouped<M, K> {
1313        Grouped {
1314            query: self,
1315            key: column(&M::columns()).name(),
1316            _key: PhantomData,
1317        }
1318    }
1319
1320    /// One aggregate (`SUM("views")`) over the matches, ignoring any order
1321    /// or limit.
1322    async fn aggregate<T: FromColumn>(&self, expression: &str) -> Result<T> {
1323        let conn = self.connection()?;
1324        let mut sql = Sql::new();
1325        sql.push(&format!("SELECT {expression} AS value FROM "));
1326        self.write_from(&mut sql);
1327        self.write_where(&mut sql);
1328        let rows = conn.read_all(&sql).await?;
1329        rows[0].get("value")
1330    }
1331
1332    /// A joined query's writes would need its joins: refused, rather than
1333    /// touch records the joins were meant to rule out.
1334    fn refuse_joins(&self, method: &str) -> Result<()> {
1335        if self.joins.is_empty() {
1336            Ok(())
1337        } else {
1338            Err(Error::internal(format!(
1339                "{method} can't run on a query with joins; filter by ids instead"
1340            )))
1341        }
1342    }
1343
1344    /// The first match that also meets `condition`, or `None`: a scope's
1345    /// `find_by`, as `User.active().find_by(email_address: …)`.
1346    pub async fn find_by(self, condition: impl FnOnce(&M::Columns) -> Expr) -> Result<Option<M>> {
1347        self.filter(condition).first().await
1348    }
1349
1350    /// Like `first`, but a missing record is a `404 Not Found`.
1351    pub async fn one(self) -> Result<M> {
1352        self.first().await?.ok_or_else(Error::not_found)
1353    }
1354
1355    pub async fn count(self) -> Result<i64> {
1356        let conn = self.connection()?;
1357        let mut sql = Sql::new();
1358        if self.distinct && !self.joins.is_empty() {
1359            sql.push(&format!(
1360                "SELECT COUNT(DISTINCT {}) AS count FROM ",
1361                self.col(M::PRIMARY_KEY)
1362            ));
1363        } else {
1364            // DISTINCT rows of one table are its rows: the count is the same.
1365            sql.push("SELECT COUNT(*) AS count FROM ");
1366        }
1367        self.write_from(&mut sql);
1368        self.write_where(&mut sql);
1369        let rows = conn.read_all(&sql).await?;
1370        rows[0].get("count")
1371    }
1372
1373    pub async fn exists(self) -> Result<bool> {
1374        Ok(self.count().await? > 0)
1375    }
1376
1377    /// Destroys every matching record one by one, running each one's
1378    /// destroy callbacks (and `dependent` children), as Rails'
1379    /// `destroy_all`; returns how many. `delete_all` is one `DELETE`.
1380    pub async fn destroy_all(self) -> Result<u64> {
1381        let records = self.all().await?;
1382        let count = records.len() as u64;
1383        for record in records {
1384            record.destroy().await?;
1385        }
1386        Ok(count)
1387    }
1388
1389    /// Deletes every matching record, returning how many there were. For
1390    /// a `soft_deletes` model it sets their `deleted_at` instead;
1391    /// `force_delete_all` deletes them.
1392    pub async fn delete_all(self) -> Result<u64> {
1393        if let Some(column) = M::SOFT_DELETE {
1394            let now = crate::time::now();
1395            return self
1396                .update_all(|_| [Assign::new(column, Value::Timestamp(now))])
1397                .await;
1398        }
1399        self.force_delete_all().await
1400    }
1401
1402    /// Deletes every matching record for good, even a `soft_deletes`
1403    /// model's.
1404    pub async fn force_delete_all(self) -> Result<u64> {
1405        self.refuse_joins("delete_all")?;
1406        let query = self.without_shared();
1407        let conn = query.connection()?;
1408        let mut sql = Sql::new();
1409        sql.push("DELETE FROM ").push_ident(M::TABLE);
1410        query.write_target(&mut sql);
1411        Ok(conn.execute(&sql).await?)
1412    }
1413}
1414
1415impl<M: Model> IntoFuture for Query<M> {
1416    type Output = Result<Vec<M>>;
1417    type IntoFuture = Pin<Box<dyn Future<Output = Result<Vec<M>>> + Send>>;
1418
1419    fn into_future(self) -> Self::IntoFuture {
1420        Box::pin(self.all())
1421    }
1422}
1423
1424/// A query grouped by a column (`Query::group`), to aggregate per group.
1425/// Each result is `(key, value)`, ordered by key.
1426pub struct Grouped<M, K> {
1427    query: Query<M>,
1428    key: &'static str,
1429    _key: PhantomData<fn() -> K>,
1430}
1431
1432impl<M: Model, K: FromColumn> Grouped<M, K> {
1433    /// How many matches each group has, as Rails' `group(:x).count`.
1434    pub async fn count(self) -> Result<Vec<(K, i64)>> {
1435        self.aggregate("COUNT(*)").await
1436    }
1437
1438    /// Each group's sum of a column.
1439    pub async fn sum<T: Summable>(
1440        self,
1441        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1442    ) -> Result<Vec<(K, T::Sum)>> {
1443        let name = column(&M::columns()).name();
1444        let column = self.query.col(name);
1445        if T::EXACT_ON_SQLITE && self.query.connection()?.dialect() == super::Dialect::Sqlite {
1446            return self.exact_sums::<T>(&column).await;
1447        }
1448        let rows: Vec<(K, Option<T::Sum>)> = self.aggregate(&T::sum(&column)).await?;
1449        Ok(rows
1450            .into_iter()
1451            .map(|(key, sum)| (key, sum.unwrap_or_default()))
1452            .collect())
1453    }
1454
1455    /// Each group's sum added here, exactly (SQLite's `SUM` adds decimals
1456    /// as floats): the rows in key order, grouped by the key's text.
1457    async fn exact_sums<T: Summable>(self, column: &str) -> Result<Vec<(K, T::Sum)>> {
1458        let conn = self.query.connection()?;
1459        let key = self.query.col(self.key);
1460        let mut sql = Sql::new();
1461        sql.push(&format!(
1462            "SELECT {key} AS key, CAST({key} AS TEXT) AS key_text, {column} AS value FROM "
1463        ));
1464        self.query.write_from(&mut sql);
1465        self.query.write_where(&mut sql);
1466        sql.push(&format!(" ORDER BY {key}"));
1467        let mut sums: Vec<(Option<String>, K, T::Sum)> = Vec::new();
1468        for row in conn.read_all(&sql).await?.iter() {
1469            let text: Option<String> = row.get("key_text")?;
1470            let value: Option<T::Sum> = row.get("value")?;
1471            match sums.last_mut() {
1472                Some((last, _, total)) if *last == text => {
1473                    if let Some(value) = value {
1474                        *total = T::add(std::mem::take(total), value);
1475                    }
1476                }
1477                _ => sums.push((text, row.get("key")?, value.unwrap_or_default())),
1478            }
1479        }
1480        Ok(sums
1481            .into_iter()
1482            .map(|(_, key, total)| (key, total))
1483            .collect())
1484    }
1485
1486    /// Each group's mean of a column.
1487    pub async fn average<T: Summable>(
1488        self,
1489        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1490    ) -> Result<Vec<(K, Option<f64>)>> {
1491        let name = column(&M::columns()).name();
1492        let column = self.query.col(name);
1493        self.aggregate(&average_sql(&column)).await
1494    }
1495
1496    /// Each group's smallest value of a column.
1497    pub async fn minimum<T: Aggregable>(
1498        self,
1499        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1500    ) -> Result<Vec<(K, Option<T::Value>)>> {
1501        let name = column(&M::columns()).name();
1502        let column = self.query.col(name);
1503        self.aggregate(&format!("MIN({column})")).await
1504    }
1505
1506    /// Each group's largest value of a column.
1507    pub async fn maximum<T: Aggregable>(
1508        self,
1509        column: impl FnOnce(&M::Columns) -> Col<M, T>,
1510    ) -> Result<Vec<(K, Option<T::Value>)>> {
1511        let name = column(&M::columns()).name();
1512        let column = self.query.col(name);
1513        self.aggregate(&format!("MAX({column})")).await
1514    }
1515
1516    async fn aggregate<V: FromColumn>(self, expression: &str) -> Result<Vec<(K, V)>> {
1517        let conn = self.query.connection()?;
1518        let key = self.query.col(self.key);
1519        let mut sql = Sql::new();
1520        sql.push(&format!("SELECT {key} AS key, {expression} AS value FROM "));
1521        self.query.write_from(&mut sql);
1522        self.query.write_where(&mut sql);
1523        sql.push(&format!(" GROUP BY {key} ORDER BY {key}"));
1524        let rows = conn.read_all(&sql).await?;
1525        rows.iter()
1526            .map(|row| Ok((row.get("key")?, row.get("value")?)))
1527            .collect()
1528    }
1529}
1530
1531/// `column` is SQL: a quoted, perhaps qualified, column.
1532fn average_sql(column: &str) -> String {
1533    format!("CAST(AVG({column}) AS DOUBLE PRECISION)")
1534}
1535
1536/// A column type that `minimum` and `maximum` work on; nullable columns
1537/// aggregate their values.
1538pub trait Aggregable {
1539    type Value: FromColumn;
1540}
1541
1542/// A numeric column type `sum` and `average` work on: integers sum to an
1543/// `i64`, floats to an `f64`, decimals to a `Decimal`.
1544pub trait Summable {
1545    type Sum: FromColumn + Default;
1546    /// `SUM` of `column`, which is SQL (quoted, perhaps qualified).
1547    #[doc(hidden)]
1548    fn sum(column: &str) -> String;
1549    /// Whether SQLite's `SUM` would round it (it adds decimals as
1550    /// floats), so the values are added here instead.
1551    #[doc(hidden)]
1552    const EXACT_ON_SQLITE: bool = false;
1553    #[doc(hidden)]
1554    fn add(a: Self::Sum, _b: Self::Sum) -> Self::Sum {
1555        a
1556    }
1557}
1558
1559macro_rules! aggregable {
1560    ($($t:ty),*) => {$(
1561        impl Aggregable for $t {
1562            type Value = $t;
1563        }
1564    )*};
1565}
1566
1567aggregable!(
1568    i16,
1569    i32,
1570    i64,
1571    f32,
1572    f64,
1573    bool,
1574    String,
1575    super::Decimal,
1576    super::Date,
1577    super::NaiveTimestamp,
1578    super::Timestamp
1579);
1580
1581impl<T: Aggregable> Aggregable for Option<T> {
1582    type Value = T::Value;
1583}
1584
1585macro_rules! summable_integer {
1586    ($($t:ty),*) => {$(
1587        impl Summable for $t {
1588            type Sum = i64;
1589            fn sum(column: &str) -> String {
1590                format!("CAST(SUM({column}) AS BIGINT)")
1591            }
1592        }
1593    )*};
1594}
1595
1596summable_integer!(i16, i32, i64);
1597
1598impl Summable for f64 {
1599    type Sum = f64;
1600    fn sum(column: &str) -> String {
1601        format!("CAST(SUM({column}) AS DOUBLE PRECISION)")
1602    }
1603}
1604
1605impl Summable for super::Decimal {
1606    type Sum = super::Decimal;
1607    fn sum(column: &str) -> String {
1608        format!("SUM({column})")
1609    }
1610    const EXACT_ON_SQLITE: bool = true;
1611    fn add(a: Self::Sum, b: Self::Sum) -> Self::Sum {
1612        a + b
1613    }
1614}
1615
1616impl<T: Summable> Summable for Option<T> {
1617    type Sum = T::Sum;
1618    fn sum(column: &str) -> String {
1619        T::sum(column)
1620    }
1621    const EXACT_ON_SQLITE: bool = T::EXACT_ON_SQLITE;
1622    fn add(a: Self::Sum, b: Self::Sum) -> Self::Sum {
1623        T::add(a, b)
1624    }
1625}
1626
1627/// A query read in batches (`Query::batches`).
1628pub struct Batches<M> {
1629    query: Option<Query<M>>,
1630    page: crate::pagination::CursorPage,
1631}
1632
1633impl<M: Model> Batches<M> {
1634    /// The next batch, or `None` when they're all read.
1635    pub async fn next(&mut self) -> Result<Option<Vec<M>>> {
1636        let Some(query) = self.query.take() else {
1637            return Ok(None);
1638        };
1639        let page = query.clone().cursor(self.page.clone()).await?;
1640        if page.records.is_empty() {
1641            return Ok(None);
1642        }
1643        if let Some(next) = page.next {
1644            self.page = crate::pagination::CursorPage::after(self.page.per_page, &next);
1645            self.query = Some(query);
1646        }
1647        Ok(Some(page.records))
1648    }
1649}
1650
1651/// An owner column's value as text, for `Model::set_owner`.
1652fn value_text(value: &Value) -> String {
1653    match value {
1654        Value::Int(v) => v.to_string(),
1655        Value::Text(v) => v.clone(),
1656        Value::Uuid(v) => v.to_string(),
1657        other => format!("{other:?}"),
1658    }
1659}