Skip to main content

renox_core/db/
query.rs

1use std::marker::PhantomData;
2
3use super::column::{CondKind, Condition, IntoColumn, JsonOp};
4use super::json::JsonPath;
5use super::paginate::{CursorPage, SimplePage};
6use super::{Db, DbValue, Dialect, Executor, FromDb, Model, Paginated, ToDbValue, now, quote, sql};
7use crate::Result;
8use anyhow::anyhow;
9
10const OPERATORS: &[&str] = &["=", "!=", "<>", "<", "<=", ">", ">=", "like", "not like"];
11
12#[derive(Clone, Copy, PartialEq)]
13enum Trashed {
14    Without,
15    With,
16    Only,
17}
18
19/// `where_in` lists longer than this are sent as one JSON array.
20const LARGE_IN: usize = 1000;
21
22/// A number type `Query::sum` can return.
23pub trait Number: FromDb + sealed::Sealed {
24    #[doc(hidden)]
25    const SQL_TYPE: &'static str;
26}
27
28impl Number for i64 {
29    const SQL_TYPE: &'static str = "BIGINT";
30}
31
32impl Number for f64 {
33    const SQL_TYPE: &'static str = "DOUBLE PRECISION";
34}
35
36/// The sum of a `Quantity` column stays a `Quantity` of the same scale.
37impl<const S: u32> Number for crate::quantity::Quantity<S> {
38    const SQL_TYPE: &'static str = "BIGINT";
39}
40
41mod sealed {
42    pub trait Sealed {}
43    impl<const S: u32> Sealed for crate::quantity::Quantity<S> {}
44    impl Sealed for i64 {}
45    impl Sealed for f64 {}
46}
47
48/// One condition of a query, rendered per database.
49#[derive(Clone)]
50enum Filter {
51    /// SQL with `?` placeholders.
52    Sql(String),
53    /// `column LIKE ?` (ILIKE on PostgreSQL); `not` for NOT LIKE.
54    Like { column: String, not: bool },
55    /// `column IN (…)` for a long list sent as one JSON array.
56    JsonIn { kind: &'static str, column: String },
57    /// Conditions joined with OR (`any`) or AND, in parentheses.
58    Group { any: bool, filters: Vec<Filter> },
59    /// `NOT (…)`.
60    Not(Box<Filter>),
61    /// `[NOT] EXISTS (SELECT 1 FROM table WHERE correlation AND …)`.
62    Exists {
63        not: bool,
64        table: &'static str,
65        correlation: String,
66        filters: Vec<Filter>,
67    },
68    /// `column IN (SELECT sub_column FROM table WHERE …)`.
69    InQuery {
70        column: String,
71        table: &'static str,
72        sub_column: String,
73        filters: Vec<Filter>,
74    },
75    /// A full-text search on a model's index, already rendered per
76    /// database (`search::filter_sql`), with one `?`.
77    Search { sqlite: String, postgres: String },
78    /// A key of a JSON column; `key` matches `[a-z][a-z0-9_]*`. `cast` is the
79    /// PostgreSQL type the text is compared as (`numeric`, `boolean`).
80    JsonKey {
81        column: String,
82        key: String,
83        op: JsonOp,
84        marks: usize,
85        cast: Option<&'static str>,
86    },
87}
88
89/// The SQL of a key of a JSON column. `key` was checked by `is_valid_key`, so
90/// it is safe inside the literal.
91fn json_key_sql(dialect: Dialect, column: &str, key: &str, cast: Option<&str>) -> String {
92    match (dialect, cast) {
93        (Dialect::Sqlite, _) => format!("json_extract({column}, '$.{key}')"),
94        (Dialect::Postgres, None) => format!("({column}::jsonb ->> '{key}')"),
95        (Dialect::Postgres, Some(cast)) => format!("({column}::jsonb ->> '{key}')::{cast}"),
96    }
97}
98
99/// The type a custom field of this kind is compared as on PostgreSQL.
100fn json_cast(kind: crate::custom_fields::FieldKind) -> Option<&'static str> {
101    use crate::custom_fields::FieldKind;
102    match kind {
103        FieldKind::Number => Some("numeric"),
104        FieldKind::Bool => Some("boolean"),
105        _ => None,
106    }
107}
108
109/// The type a bound value is compared as when no definition says.
110fn value_cast(value: &DbValue) -> Option<&'static str> {
111    match value {
112        DbValue::Integer(_) | DbValue::Real(_) => Some("numeric"),
113        DbValue::Bool(_) => Some("boolean"),
114        _ => None,
115    }
116}
117
118/// One `ORDER BY` term.
119#[derive(Clone)]
120enum Order {
121    /// SQL without values.
122    Sql(String),
123    /// Full-text relevance (`search::rank_sql`) per database, with one `?`
124    /// in `order_binds`.
125    Relevance { sqlite: String, postgres: String },
126    /// A key of a JSON column (see `Filter::JsonKey`).
127    JsonKey {
128        column: String,
129        key: String,
130        desc: bool,
131        cast: Option<&'static str>,
132    },
133}
134
135impl Order {
136    fn render(&self, dialect: Dialect) -> String {
137        match (self, dialect) {
138            (Order::Sql(sql), _) => sql.clone(),
139            (Order::Relevance { sqlite, .. }, Dialect::Sqlite) => sqlite.clone(),
140            (Order::Relevance { postgres, .. }, Dialect::Postgres) => postgres.clone(),
141            (
142                Order::JsonKey {
143                    column,
144                    key,
145                    desc,
146                    cast,
147                },
148                _,
149            ) => format!(
150                "{} {}",
151                json_key_sql(dialect, column, key, *cast),
152                if *desc { "DESC" } else { "ASC" }
153            ),
154        }
155    }
156}
157
158impl Filter {
159    /// Calls `f` with the key and cast of every JSON key condition inside.
160    fn visit_json(&mut self, f: &mut dyn FnMut(&str, &mut Option<&'static str>)) {
161        match self {
162            Filter::JsonKey { key, cast, .. } => f(key, cast),
163            Filter::Group { filters, .. } => filters.iter_mut().for_each(|x| x.visit_json(f)),
164            Filter::Not(filter) => filter.visit_json(f),
165            _ => {}
166        }
167    }
168
169    fn render(&self, dialect: Dialect) -> String {
170        match self {
171            Filter::Sql(sql) => sql.clone(),
172            Filter::Like { column, not } => {
173                let op = match (dialect, not) {
174                    (Dialect::Postgres, false) => "ILIKE",
175                    (Dialect::Postgres, true) => "NOT ILIKE",
176                    (_, false) => "LIKE",
177                    (_, true) => "NOT LIKE",
178                };
179                format!("{column} {op} ?")
180            }
181            Filter::JsonIn { kind, column } => json_in(kind, column, dialect),
182            Filter::JsonKey {
183                column,
184                key,
185                op,
186                marks,
187                cast,
188            } => {
189                let expr = json_key_sql(dialect, column, key, *cast);
190                match op {
191                    JsonOp::Cmp("like") if dialect == Dialect::Postgres => {
192                        format!("{expr} ILIKE ?")
193                    }
194                    JsonOp::Cmp(op) => format!("{expr} {} ?", op.to_uppercase()),
195                    JsonOp::Null(true) => format!("{expr} IS NULL"),
196                    JsonOp::Null(false) => format!("{expr} IS NOT NULL"),
197                    JsonOp::In => format!("{expr} IN ({})", vec!["?"; *marks].join(", ")),
198                }
199            }
200            Filter::Group { any, filters } => {
201                if filters.is_empty() {
202                    // Nothing to match for `any`, nothing to restrict for AND.
203                    return if *any { "0 = 1".into() } else { "1 = 1".into() };
204                }
205                let joiner = if *any { " OR " } else { " AND " };
206                let parts: Vec<String> = filters.iter().map(|f| f.render(dialect)).collect();
207                format!("({})", parts.join(joiner))
208            }
209            Filter::Not(filter) => format!("NOT ({})", filter.render(dialect)),
210            Filter::Exists {
211                not,
212                table,
213                correlation,
214                filters,
215            } => {
216                let mut parts = vec![correlation.clone()];
217                parts.extend(filters.iter().map(|f| f.render(dialect)));
218                format!(
219                    "{}EXISTS (SELECT 1 FROM {} WHERE {})",
220                    if *not { "NOT " } else { "" },
221                    quote(table),
222                    parts.join(" AND ")
223                )
224            }
225            Filter::InQuery {
226                column,
227                table,
228                sub_column,
229                filters,
230            } => {
231                let condition = if filters.is_empty() {
232                    String::new()
233                } else {
234                    let parts: Vec<String> = filters.iter().map(|f| f.render(dialect)).collect();
235                    format!(" WHERE {}", parts.join(" AND "))
236                };
237                format!(
238                    "{column} IN (SELECT {sub_column} FROM {}{condition})",
239                    quote(table)
240                )
241            }
242            Filter::Search { sqlite, postgres } => match dialect {
243                Dialect::Sqlite => sqlite.clone(),
244                Dialect::Postgres => postgres.clone(),
245            },
246        }
247    }
248}
249
250/// A long list of integers or of strings, as a JSON array.
251fn large_list(values: &[DbValue]) -> Option<(&'static str, serde_json::Value)> {
252    if values.len() <= LARGE_IN {
253        return None;
254    }
255    if let Some(ints) = values
256        .iter()
257        .map(|v| match v {
258            DbValue::Integer(n) => Some(serde_json::Value::from(*n)),
259            _ => None,
260        })
261        .collect::<Option<Vec<_>>>()
262    {
263        return Some(("int", ints.into()));
264    }
265    values
266        .iter()
267        .map(|v| match v {
268            DbValue::Text(s) => Some(serde_json::Value::from(s.clone())),
269            _ => None,
270        })
271        .collect::<Option<Vec<_>>>()
272        .map(|texts| ("text", texts.into()))
273}
274
275fn json_in(kind: &str, column: &str, dialect: Dialect) -> String {
276    match (dialect, kind) {
277        (Dialect::Sqlite, _) => format!("{column} IN (SELECT value FROM json_each(?))"),
278        (Dialect::Postgres, "int") => format!(
279            "{column} IN (SELECT CAST(x AS BIGINT) FROM jsonb_array_elements_text(CAST(? AS JSONB)) AS t(x))"
280        ),
281        (Dialect::Postgres, _) => format!(
282            "{column} IN (SELECT x FROM jsonb_array_elements_text(CAST(? AS JSONB)) AS t(x))"
283        ),
284    }
285}
286
287/// A query on a model's table, built with chained filters.
288///
289/// ```
290/// # #[derive(Model, serde::Serialize, Default)]
291/// # #[model(table = "products")]
292/// # struct Product { id: i64, name: String, price: i64, category: Option<String>, user_id: i64 }
293/// # use renox::prelude::*;
294/// # async fn demo(db: Db, page: u32) -> Result {
295/// let products = Product::query()
296///     .where_eq("category", "coffee")
297///     .where_op("price", "<", 25_000)
298///     .order_by("name")
299///     .paginate(&db, page, 20)
300///     .await?;
301/// # let _ = products; Ok(()) }
302/// ```
303///
304/// Column names are checked against the model; an unknown column or operator
305/// makes the query return an error instead of running.
306pub struct Query<M> {
307    filters: Vec<Filter>,
308    binds: Vec<DbValue>,
309    group: Vec<String>,
310    having: Vec<String>,
311    having_binds: Vec<DbValue>,
312    order: Vec<Order>,
313    /// Values of the `ORDER BY` terms, bound after the WHERE and HAVING ones.
314    order_binds: Vec<DbValue>,
315    limit: Option<u64>,
316    offset: Option<u64>,
317    lock: Option<&'static str>,
318    trashed: Trashed,
319    error: Option<String>,
320    model: PhantomData<fn() -> M>,
321}
322
323impl<M> Clone for Query<M> {
324    fn clone(&self) -> Self {
325        Self {
326            filters: self.filters.clone(),
327            binds: self.binds.clone(),
328            group: self.group.clone(),
329            having: self.having.clone(),
330            having_binds: self.having_binds.clone(),
331            order: self.order.clone(),
332            order_binds: self.order_binds.clone(),
333            limit: self.limit,
334            offset: self.offset,
335            lock: self.lock,
336            trashed: self.trashed,
337            error: self.error.clone(),
338            model: PhantomData,
339        }
340    }
341}
342
343impl<M: Model> Query<M> {
344    pub(crate) fn new() -> Self {
345        Self {
346            filters: Vec::new(),
347            binds: Vec::new(),
348            group: Vec::new(),
349            having: Vec::new(),
350            having_binds: Vec::new(),
351            order: Vec::new(),
352            order_binds: Vec::new(),
353            limit: None,
354            offset: None,
355            lock: None,
356            trashed: Trashed::Without,
357            error: None,
358            model: PhantomData,
359        }
360    }
361
362    fn column(&mut self, column: &str) -> Option<String> {
363        let plain = !column.is_empty()
364            && column
365                .chars()
366                .all(|c| c.is_ascii_alphanumeric() || c == '_');
367        if M::COLUMNS.contains(&column) || (M::SELECT_ALL && plain) {
368            Some(quote(column))
369        } else {
370            self.error
371                .get_or_insert_with(|| format!("`{}` has no column `{column}`", M::TABLE));
372            None
373        }
374    }
375
376    /// Filters on `column = value`.
377    pub fn where_eq(self, column: &str, value: impl ToDbValue) -> Self {
378        self.where_op(column, "=", value)
379    }
380
381    /// Filters on a typed [`Condition`] made by a [`Col`](super::Col), like
382    /// `Product::PRICE.lt(20_000)`.
383    pub fn where_(self, condition: Condition<M>) -> Self {
384        match condition.kind {
385            CondKind::Op(column, op, value) => self.where_op(column, op, value),
386            CondKind::Null(column, true) => self.where_null(column),
387            CondKind::Null(column, false) => self.where_not_null(column),
388            CondKind::In(column, values) => self.where_in(column, values),
389            CondKind::Json(column, key, op, values) => self.where_json(column, key, op, values),
390        }
391    }
392
393    fn where_json(
394        mut self,
395        column: &'static str,
396        key: String,
397        op: JsonOp,
398        values: Vec<DbValue>,
399    ) -> Self {
400        let Some(column) = self.column(column) else {
401            return self;
402        };
403        if !crate::custom_fields::is_valid_key(&key) {
404            self.error
405                .get_or_insert_with(|| format!("`{}` is not a valid JSON key", key.escape_debug()));
406            return self;
407        }
408        if matches!(op, JsonOp::In) && values.is_empty() {
409            self.filters.push(Filter::Sql("0 = 1".into()));
410            return self;
411        }
412        let cast = values.first().and_then(value_cast);
413        self.filters.push(Filter::JsonKey {
414            column,
415            key,
416            op,
417            marks: values.len(),
418            cast,
419        });
420        self.binds.extend(values);
421        self
422    }
423
424    /// Sorts by a key of a JSON column, ascending, like
425    /// `Party::EXTRA.json("segment")`.
426    pub fn order_by_json(self, path: JsonPath<M>) -> Self {
427        self.order_json(path, false)
428    }
429
430    /// Sorts by a key of a JSON column, descending.
431    pub fn order_by_json_desc(self, path: JsonPath<M>) -> Self {
432        self.order_json(path, true)
433    }
434
435    fn order_json(mut self, path: JsonPath<M>, desc: bool) -> Self {
436        if let Some(column) = self.column(path.column) {
437            if crate::custom_fields::is_valid_key(&path.key) {
438                self.order.push(Order::JsonKey {
439                    column,
440                    key: path.key,
441                    desc,
442                    cast: None,
443                });
444            } else {
445                let key = path.key;
446                self.error.get_or_insert_with(|| {
447                    format!("`{}` is not a valid JSON key", key.escape_debug())
448                });
449            }
450        }
451        self
452    }
453
454    /// Checks the JSON keys of the query's conditions and ordering against the
455    /// active custom field definitions of the model (its table name), and
456    /// compares numbers and booleans as such on PostgreSQL. A key without a
457    /// definition makes the query return an error. A key whose definition is
458    /// sensitive (its values are sealed) cannot be filtered or sorted on:
459    /// this returns [`DbError::sealed_custom_field`](super::DbError::sealed_custom_field)
460    /// (400 in a response), whatever the stored rows hold. The definitions are cached
461    /// (`CustomField::for_model`), so calling this on every query is cheap.
462    pub async fn with_custom_fields(mut self, db: &Db) -> Result<Self> {
463        let fields = crate::custom_fields::CustomField::for_model(db, M::TABLE).await?;
464        let mut missing = None;
465        let mut sealed: Option<String> = None;
466        let mut resolve = |key: &str, cast: &mut Option<&'static str>| match fields
467            .iter()
468            .find(|f| f.key == key)
469        {
470            Some(field) if field.rules.sensitive => {
471                sealed.get_or_insert_with(|| key.to_owned());
472            }
473            Some(field) => *cast = json_cast(field.kind),
474            None => {
475                missing
476                    .get_or_insert_with(|| format!("`{}` has no custom field `{key}`", M::TABLE));
477            }
478        };
479        for filter in &mut self.filters {
480            filter.visit_json(&mut resolve);
481        }
482        for order in &mut self.order {
483            if let Order::JsonKey { key, cast, .. } = order {
484                resolve(key, cast);
485            }
486        }
487        if let Some(key) = sealed {
488            return Err(super::DbError::sealed_custom_field(&key).into());
489        }
490        if let Some(missing) = missing {
491            self.error.get_or_insert(missing);
492        }
493        Ok(self)
494    }
495
496    /// Filters with a comparison: `=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`, `like`, `not like`.
497    /// `like` ignores ASCII case on both databases (`ILIKE` on PostgreSQL, as
498    /// SQLite's `LIKE` already does).
499    pub fn where_op(mut self, column: &str, op: &str, value: impl ToDbValue) -> Self {
500        let op = op.to_ascii_lowercase();
501        if !OPERATORS.contains(&op.as_str()) {
502            self.error
503                .get_or_insert_with(|| format!("unsupported operator `{op}`"));
504            return self;
505        }
506        if let Some(column) = self.column(column) {
507            self.filters.push(match op.as_str() {
508                "like" => Filter::Like { column, not: false },
509                "not like" => Filter::Like { column, not: true },
510                _ => Filter::Sql(format!("{column} {} ?", op.to_uppercase())),
511            });
512            self.binds.push(value.to_db_value());
513        }
514        self
515    }
516
517    /// Filters on `column LIKE pattern`, ignoring ASCII case (`%` and `_` are wildcards).
518    pub fn where_like(self, column: &str, pattern: impl ToDbValue) -> Self {
519        self.where_op(column, "like", pattern)
520    }
521
522    /// Filters on `column IS NULL`.
523    pub fn where_null(mut self, column: &str) -> Self {
524        if let Some(column) = self.column(column) {
525            self.filters.push(Filter::Sql(format!("{column} IS NULL")));
526        }
527        self
528    }
529
530    /// Filters on `column IS NOT NULL`.
531    pub fn where_not_null(mut self, column: &str) -> Self {
532        if let Some(column) = self.column(column) {
533            self.filters
534                .push(Filter::Sql(format!("{column} IS NOT NULL")));
535        }
536        self
537    }
538
539    /// Filters on `column IN (…)`; an empty list matches no rows.
540    pub fn where_in<V: ToDbValue>(self, column: &str, values: impl IntoIterator<Item = V>) -> Self {
541        self.in_list(column, values, false)
542    }
543
544    /// Filters on `column NOT IN (…)`; an empty list matches every row.
545    pub fn where_not_in<V: ToDbValue>(
546        self,
547        column: &str,
548        values: impl IntoIterator<Item = V>,
549    ) -> Self {
550        self.in_list(column, values, true)
551    }
552
553    fn in_list<V: ToDbValue>(
554        mut self,
555        column: &str,
556        values: impl IntoIterator<Item = V>,
557        not: bool,
558    ) -> Self {
559        let values: Vec<DbValue> = values.into_iter().map(|v| v.to_db_value()).collect();
560        if let Some(column) = self.column(column) {
561            let filter = if values.is_empty() {
562                // Nothing is in an empty list.
563                Filter::Sql("0 = 1".into())
564            } else if let Some((kind, list)) = large_list(&values) {
565                // Over the databases' bind limits: one JSON array instead.
566                self.binds.push(DbValue::Json(list));
567                Filter::JsonIn { kind, column }
568            } else {
569                let marks = vec!["?"; values.len()].join(", ");
570                self.binds.extend(values);
571                Filter::Sql(format!("{column} IN ({marks})"))
572            };
573            self.filters.push(if not {
574                Filter::Not(Box::new(filter))
575            } else {
576                filter
577            });
578        }
579        self
580    }
581
582    /// `low <= column <= high`.
583    pub fn where_between(
584        mut self,
585        column: &str,
586        low: impl ToDbValue,
587        high: impl ToDbValue,
588    ) -> Self {
589        if let Some(column) = self.column(column) {
590            self.filters
591                .push(Filter::Sql(format!("{column} BETWEEN ? AND ?")));
592            self.binds.push(low.to_db_value());
593            self.binds.push(high.to_db_value());
594        }
595        self
596    }
597
598    /// Rows whose `column` is among `sub_column`'s values in another model's
599    /// query, e.g. products in active categories:
600    ///
601    /// ```
602    /// # use renox::prelude::*;
603    /// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, category_id: i64 }
604    /// # #[derive(Model, serde::Serialize, Default)] struct Category { id: i64, active: bool }
605    /// # async fn demo(db: Db) -> Result {
606    /// let products = Product::query()
607    ///     .where_in_query("category_id", Category::where_eq("active", true), "id")
608    ///     .get(&db)
609    ///     .await?;
610    /// # let _ = products; Ok(()) }
611    /// ```
612    pub fn where_in_query<N: Model>(
613        mut self,
614        column: &str,
615        mut sub: Query<N>,
616        sub_column: &str,
617    ) -> Self {
618        let sub_column = sub.column(sub_column);
619        let column = self.column(column);
620        if let Some(error) = sub.error.take() {
621            self.error.get_or_insert(error);
622        }
623        if let (Some(column), Some(sub_column)) = (column, sub_column) {
624            let trashed = sub.trashed_filter();
625            let mut filters = sub.filters;
626            filters.extend(trashed);
627            self.filters.push(Filter::InQuery {
628                column,
629                table: N::TABLE,
630                sub_column,
631                filters,
632            });
633            self.binds.extend(sub.binds);
634        }
635        self
636    }
637
638    /// Like `where_in_query`, keeping the rows whose `column` is *not* among
639    /// the sub-query's values.
640    pub fn where_not_in_query<N: Model>(
641        self,
642        column: &str,
643        sub: Query<N>,
644        sub_column: &str,
645    ) -> Self {
646        let before = self.filters.len();
647        let mut query = self.where_in_query(column, sub, sub_column);
648        if query.filters.len() > before
649            && let Some(last) = query.filters.pop()
650        {
651            query.filters.push(Filter::Not(Box::new(last)));
652        }
653        query
654    }
655
656    /// Rows that have at least one related row in `children`, joined by the
657    /// children's `foreign_key` column to this model's `id` (`EXISTS`):
658    /// products with a 5-star review.
659    ///
660    /// ```
661    /// # use renox::prelude::*;
662    /// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64, name: String }
663    /// # #[derive(Model, serde::Serialize, Default)] struct Review { id: i64, product_id: i64, stars: i64 }
664    /// # async fn demo(db: Db) -> Result {
665    /// let loved = Product::query()
666    ///     .where_has(Review::where_eq("stars", 5), "product_id")
667    ///     .get(&db)
668    ///     .await?;
669    /// let unreviewed = Product::query().where_doesnt_have(Review::query(), "product_id").count(&db).await?;
670    /// # let _ = (loved, unreviewed); Ok(()) }
671    /// ```
672    pub fn where_has<N: Model>(self, children: Query<N>, foreign_key: &str) -> Self {
673        self.related(children, foreign_key, false)
674    }
675
676    /// Rows without any related row in `children` (`NOT EXISTS`).
677    pub fn where_doesnt_have<N: Model>(self, children: Query<N>, foreign_key: &str) -> Self {
678        self.related(children, foreign_key, true)
679    }
680
681    fn related<N: Model>(mut self, mut children: Query<N>, foreign_key: &str, not: bool) -> Self {
682        let foreign_key = children.column(foreign_key);
683        if let Some(error) = children.error.take() {
684            self.error.get_or_insert(error);
685        }
686        if let Some(foreign_key) = foreign_key {
687            let trashed = children.trashed_filter();
688            let mut filters = children.filters;
689            filters.extend(trashed);
690            self.filters.push(Filter::Exists {
691                not,
692                table: N::TABLE,
693                correlation: format!(
694                    "{}.{foreign_key} = {}.\"id\"",
695                    quote(N::TABLE),
696                    quote(M::TABLE)
697                ),
698                filters,
699            });
700            self.binds.extend(children.binds);
701        }
702        self
703    }
704
705    /// Any of the conditions `group` adds must hold (`OR`), in parentheses:
706    /// `.where_any(|q| q.where_eq("status", "new").where_op("total", ">", 100))`.
707    pub fn where_any(self, group: impl FnOnce(Self) -> Self) -> Self {
708        self.group(true, group)
709    }
710
711    /// All of the conditions `group` adds must hold, in parentheses; useful
712    /// inside `where_any`: `.where_any(|q| q.where_eq("a", 1).where_all(|q| …))`.
713    pub fn where_all(self, group: impl FnOnce(Self) -> Self) -> Self {
714        self.group(false, group)
715    }
716
717    fn group(mut self, any: bool, group: impl FnOnce(Self) -> Self) -> Self {
718        let mut inner = group(Self::new());
719        if let Some(error) = inner.error.take() {
720            self.error.get_or_insert(error);
721        }
722        self.filters.push(Filter::Group {
723            any,
724            filters: inner.filters,
725        });
726        self.binds.extend(inner.binds);
727        self
728    }
729
730    /// Applies `add` only when `condition` holds, e.g. an optional search:
731    /// `.when(!q.is_empty(), |query| query.where_like("name", format!("%{q}%")))`.
732    pub fn when(self, condition: bool, add: impl FnOnce(Self) -> Self) -> Self {
733        if condition { add(self) } else { self }
734    }
735
736    /// The rows matching a full-text search, best matches first (as
737    /// [`where_search`](Self::where_search) then
738    /// [`order_by_relevance`](Self::order_by_relevance)); more `order_by`
739    /// calls break ties. The model needs `#[model(search = "…")]` and its
740    /// index: see [`renox::db::search`](super::search). A text without any
741    /// word changes nothing.
742    ///
743    /// ```
744    /// # use renox::prelude::*;
745    /// #[derive(Model, serde::Serialize, Default)]
746    /// #[model(table = "posts", search = "title, body", soft_deletes)]
747    /// struct Post {
748    ///     id: i64,
749    ///     title: String,
750    ///     body: String,
751    ///     author_id: i64,
752    ///     deleted_at: Option<DateTime>,
753    /// }
754    ///
755    /// # async fn demo(db: Db, q: String) -> Result {
756    /// let page = Post::query()
757    ///     .where_eq("author_id", 7)
758    ///     .search(&q)
759    ///     .order_by_desc("id")
760    ///     .paginate(&db, 1, 20)
761    ///     .await?;
762    /// # let _ = page; Ok(()) }
763    /// ```
764    pub fn search(self, words: &str) -> Self {
765        self.where_search(words).order_by_relevance(words)
766    }
767
768    /// Keeps the rows matching a full-text search (every word, as a word
769    /// or the start of one), without ordering them. User input is safe
770    /// here: only its words reach the database, bound as a value.
771    pub fn where_search(mut self, words: &str) -> Self {
772        if let Some(problem) = super::search::unsearchable::<M>() {
773            self.error.get_or_insert(problem);
774            return self;
775        }
776        if let Some(terms) = super::search::bound::<M>(words) {
777            self.filters.push(Filter::Search {
778                sqlite: super::search::filter_sql::<M>(Dialect::Sqlite),
779                postgres: super::search::filter_sql::<M>(Dialect::Postgres),
780            });
781            self.binds.push(DbValue::Text(terms));
782        }
783        self
784    }
785
786    /// Sorts by how well rows match a full-text search, best first (rows
787    /// that don't match last); call `order_by` after it to break ties.
788    pub fn order_by_relevance(mut self, words: &str) -> Self {
789        if let Some(problem) = super::search::unsearchable::<M>() {
790            self.error.get_or_insert(problem);
791            return self;
792        }
793        if let Some(terms) = super::search::bound::<M>(words) {
794            self.order.push(Order::Relevance {
795                sqlite: super::search::rank_sql::<M>(Dialect::Sqlite),
796                postgres: super::search::rank_sql::<M>(Dialect::Postgres),
797            });
798            self.order_binds.push(DbValue::Text(terms));
799        }
800        self
801    }
802
803    /// Sorts by `column`, ascending; call again to add tie-breakers.
804    pub fn order_by(mut self, column: impl IntoColumn<M>) -> Self {
805        if let Some(column) = self.column(column.column_name()) {
806            self.order.push(Order::Sql(format!("{column} ASC")));
807        }
808        self
809    }
810
811    /// Sorts by `column`, descending; call again to add tie-breakers.
812    pub fn order_by_desc(mut self, column: impl IntoColumn<M>) -> Self {
813        if let Some(column) = self.column(column.column_name()) {
814            self.order.push(Order::Sql(format!("{column} DESC")));
815        }
816        self
817    }
818
819    /// Newest first, by `created_at` when the model has it, otherwise by `id`.
820    pub fn latest(self) -> Self {
821        let column = if M::COLUMNS.contains(&"created_at") {
822            "created_at"
823        } else {
824            "id"
825        };
826        self.order_by_desc(column).order_by_desc("id")
827    }
828
829    /// At most `limit` rows (a limit past `i64::MAX` means no limit).
830    pub fn limit(mut self, limit: u64) -> Self {
831        self.limit = Some(limit.min(i64::MAX as u64));
832        self
833    }
834
835    /// Skips the first `offset` rows.
836    pub fn offset(mut self, offset: u64) -> Self {
837        self.offset = Some(offset.min(i64::MAX as u64));
838        self
839    }
840
841    /// A condition in SQL, for what the builder doesn't cover (dates, JSON,
842    /// full-text search, …), with `?` for each value. Column names are yours
843    /// to quote; never build `sql` from user input.
844    ///
845    /// ```
846    /// # use renox::prelude::*;
847    /// # #[derive(Model, serde::Serialize, Default)] struct Order { id: i64, total: i64, created_at: Option<DateTime> }
848    /// # async fn demo(db: Db) -> Result {
849    /// let today = Order::query()
850    ///     .where_raw("DATE(created_at) = DATE(?)", [renox::db::now()])
851    ///     .order_by_raw("total DESC, id")
852    ///     .get(&db)
853    ///     .await?;
854    /// # let _ = today; Ok(()) }
855    /// ```
856    pub fn where_raw<V: ToDbValue>(
857        mut self,
858        sql: &str,
859        values: impl IntoIterator<Item = V>,
860    ) -> Self {
861        self.filters.push(Filter::Sql(format!("({sql})")));
862        self.binds
863            .extend(values.into_iter().map(|v| v.to_db_value()));
864        self
865    }
866
867    /// An `ORDER BY` term in SQL, e.g. `"total DESC, id"` (no values; never
868    /// from user input).
869    pub fn order_by_raw(mut self, sql: &str) -> Self {
870        self.order.push(Order::Sql(sql.to_owned()));
871        self
872    }
873
874    /// Groups rows by `column`, for `select_as` and `count`:
875    /// `.group_by("user_id").select_as::<(i64, i64), _>(&db, "user_id, COUNT(*)")`.
876    pub fn group_by(mut self, column: &str) -> Self {
877        if let Some(column) = self.column(column) {
878            self.group.push(column);
879        }
880        self
881    }
882
883    /// Groups rows by a SQL expression (written by the app, never from a
884    /// request): `.group_by_raw("CAST(\"price\" / 100 AS INTEGER)")`.
885    pub fn group_by_raw(mut self, sql: &str) -> Self {
886        self.group.push(sql.to_owned());
887        self
888    }
889
890    /// A condition on the groups, in SQL with `?` for each value:
891    /// `.having_raw("COUNT(*) > ?", [2])`.
892    pub fn having_raw<V: ToDbValue>(
893        mut self,
894        sql: &str,
895        values: impl IntoIterator<Item = V>,
896    ) -> Self {
897        self.having.push(format!("({sql})"));
898        self.having_binds
899            .extend(values.into_iter().map(|v| v.to_db_value()));
900        self
901    }
902
903    /// Locks the matching rows until the transaction ends (`FOR UPDATE`),
904    /// e.g. to read a balance and write it back safely. Use it on `&mut tx`.
905    /// PostgreSQL only: on SQLite a write transaction already holds the whole
906    /// database, so start it with `db.begin_immediate()` instead.
907    pub fn lock_for_update(mut self) -> Self {
908        self.lock = Some("FOR UPDATE");
909        self
910    }
911
912    /// Like `lock_for_update`, but others may still read-lock (`FOR SHARE`).
913    pub fn shared_lock(mut self) -> Self {
914        self.lock = Some("FOR SHARE");
915        self
916    }
917
918    /// Matches no rows at all, e.g. a default scope when no tenant is set.
919    pub fn none(mut self) -> Self {
920        self.filters.push(Filter::Sql("1 = 0".into()));
921        self
922    }
923
924    /// Include soft-deleted rows.
925    pub fn with_trashed(mut self) -> Self {
926        self.trashed = Trashed::With;
927        self
928    }
929
930    /// Only soft-deleted rows.
931    pub fn only_trashed(mut self) -> Self {
932        self.trashed = Trashed::Only;
933        self
934    }
935
936    fn check(&self) -> Result {
937        match &self.error {
938            Some(error) => Err(anyhow!("invalid query: {error}").into()),
939            None => Ok(()),
940        }
941    }
942
943    /// The soft-delete condition, if the model has soft deletes.
944    fn trashed_filter(&self) -> Option<Filter> {
945        if !M::SOFT_DELETES {
946            return None;
947        }
948        match self.trashed {
949            Trashed::Without => Some(Filter::Sql("\"deleted_at\" IS NULL".into())),
950            Trashed::Only => Some(Filter::Sql("\"deleted_at\" IS NOT NULL".into())),
951            Trashed::With => None,
952        }
953    }
954
955    fn where_sql(&self, dialect: Dialect) -> String {
956        let mut filters: Vec<String> = self.filters.iter().map(|f| f.render(dialect)).collect();
957        filters.extend(self.trashed_filter().map(|f| f.render(dialect)));
958        if filters.is_empty() {
959            String::new()
960        } else {
961            format!(" WHERE {}", filters.join(" AND "))
962        }
963    }
964
965    fn select_sql(&self, dialect: Dialect) -> String {
966        let columns: Vec<String> = if M::SELECT_ALL {
967            vec!["*".to_owned()]
968        } else {
969            M::COLUMNS.iter().map(|c| quote(c)).collect()
970        };
971        self.select_columns_sql(dialect, &columns.join(", "))
972    }
973
974    fn select_columns_sql(&self, dialect: Dialect, columns: &str) -> String {
975        let mut sql = format!(
976            "SELECT {columns} FROM {}{}",
977            quote(M::TABLE),
978            self.where_sql(dialect)
979        );
980        sql.push_str(&self.group_sql());
981        if !self.order.is_empty() {
982            let terms: Vec<String> = self.order.iter().map(|o| o.render(dialect)).collect();
983            sql.push_str(&format!(" ORDER BY {}", terms.join(", ")));
984        }
985        match (self.limit, self.offset) {
986            (Some(limit), Some(offset)) => sql.push_str(&format!(" LIMIT {limit} OFFSET {offset}")),
987            (Some(limit), None) => sql.push_str(&format!(" LIMIT {limit}")),
988            // SQLite needs a LIMIT before OFFSET; -1 means none.
989            (None, Some(offset)) if dialect == Dialect::Sqlite => {
990                sql.push_str(&format!(" LIMIT -1 OFFSET {offset}"))
991            }
992            (None, Some(offset)) => sql.push_str(&format!(" OFFSET {offset}")),
993            (None, None) => {}
994        }
995        if let (Some(lock), Dialect::Postgres) = (self.lock, dialect) {
996            sql.push(' ');
997            sql.push_str(lock);
998        }
999        sql
1000    }
1001
1002    fn group_sql(&self) -> String {
1003        let mut sql = String::new();
1004        if !self.group.is_empty() {
1005            sql.push_str(&format!(" GROUP BY {}", self.group.join(", ")));
1006        }
1007        if !self.having.is_empty() {
1008            sql.push_str(&format!(" HAVING {}", self.having.join(" AND ")));
1009        }
1010        sql
1011    }
1012
1013    /// The query's values in the order its SQL uses them (without the
1014    /// `ORDER BY` ones: see `select_binds`).
1015    fn all_binds(&self) -> Vec<DbValue> {
1016        let mut binds = self.binds.clone();
1017        binds.extend(self.having_binds.iter().cloned());
1018        binds
1019    }
1020
1021    /// The values of a SELECT with its `ORDER BY` (`select_columns_sql`).
1022    fn select_binds(&self) -> Vec<DbValue> {
1023        let mut binds = self.all_binds();
1024        binds.extend(self.order_binds.iter().cloned());
1025        binds
1026    }
1027
1028    fn clear_order(&mut self) {
1029        self.order.clear();
1030        self.order_binds.clear();
1031    }
1032
1033    /// Records an error if `column` isn't one of the model's.
1034    pub(crate) fn check_column(mut self, column: &str) -> Self {
1035        let _ = self.column(column);
1036        self
1037    }
1038
1039    /// The SELECT this query runs and its values, e.g. to log or debug it.
1040    pub fn to_sql(&self, dialect: Dialect) -> Result<(String, Vec<DbValue>)> {
1041        self.check()?;
1042        Ok((self.select_sql(dialect), self.select_binds()))
1043    }
1044
1045    /// Selects `columns` (SQL, e.g. `"user_id, COUNT(*) AS orders"`) of the
1046    /// matching rows, with `group_by`/`having_raw`, read into a
1047    /// `#[derive(FromRow)]` struct or a tuple:
1048    ///
1049    /// ```
1050    /// # use renox::prelude::*;
1051    /// # #[derive(Model, serde::Serialize, Default)] struct Order { id: i64, user_id: i64, total: i64, status: String }
1052    /// # async fn demo(db: Db) -> Result {
1053    /// let big_spenders: Vec<(i64, i64)> = Order::where_eq("status", "paid")
1054    ///     .group_by("user_id")
1055    ///     .having_raw("SUM(total) > ?", [1_000_000])
1056    ///     .order_by_raw("2 DESC")
1057    ///     .select_as(&db, "user_id, CAST(SUM(total) AS BIGINT)")
1058    ///     .await?;
1059    /// # let _ = big_spenders; Ok(()) }
1060    /// ```
1061    pub async fn select_as<'c, T: super::FromRow, E: Executor<'c>>(
1062        self,
1063        db: E,
1064        columns: &str,
1065    ) -> Result<Vec<T>> {
1066        self.check()?;
1067        let db = db.into_conn();
1068        let statement = self.select_columns_sql(db.dialect(), columns);
1069        Ok(sql(statement)
1070            .bind_all(self.select_binds())
1071            .fetch_as(db)
1072            .await?)
1073    }
1074
1075    /// `bucket` and an aggregate per bucket (`chart::Trend`): the query's
1076    /// conditions, grouped by the first column; its order, limit, groups
1077    /// and lock don't apply.
1078    pub(crate) async fn buckets<'c, E: Executor<'c>>(
1079        mut self,
1080        db: E,
1081        bucket: &(dyn Fn(Dialect) -> String + Send + Sync),
1082        aggregate: &str,
1083    ) -> Result<Vec<(String, Option<f64>)>> {
1084        self.check()?;
1085        self.clear_order();
1086        self.group = vec!["1".to_owned()];
1087        self.having.clear();
1088        self.having_binds.clear();
1089        self.limit = None;
1090        self.offset = None;
1091        self.lock = None;
1092        let db = db.into_conn();
1093        let dialect = db.dialect();
1094        let statement = self.select_columns_sql(
1095            dialect,
1096            &format!("{}, CAST({aggregate} AS DOUBLE PRECISION)", bucket(dialect)),
1097        );
1098        Ok(sql(statement)
1099            .bind_all(self.all_binds())
1100            .fetch_as(db)
1101            .await?)
1102    }
1103
1104    /// One aggregate over the matching rows (order and limit don't apply).
1105    async fn aggregate<'c, T: FromDb, E: Executor<'c>>(
1106        self,
1107        db: E,
1108        expression: String,
1109    ) -> Result<T> {
1110        self.check()?;
1111        let db = db.into_conn();
1112        let statement = format!(
1113            "SELECT {expression} FROM {}{}",
1114            quote(M::TABLE),
1115            self.where_sql(db.dialect())
1116        );
1117        Ok(sql(statement).bind_all(self.binds).scalar(db).await?)
1118    }
1119
1120    /// The sum of `column`, 0 without rows: `sum::<i64>(…)` for whole
1121    /// numbers (money in its smallest unit), `sum::<Quantity<S>>(…)` for a
1122    /// `Quantity` column, `sum::<f64>(…)` for measures.
1123    pub async fn sum<'c, T: Number, E: Executor<'c>>(mut self, db: E, column: &str) -> Result<T> {
1124        let Some(column) = self.column(column) else {
1125            return Err(self.check().unwrap_err());
1126        };
1127        let expression = format!("CAST(COALESCE(SUM({column}), 0) AS {})", T::SQL_TYPE);
1128        self.aggregate(db, expression).await
1129    }
1130
1131    /// The average of `column`, or `None` without rows.
1132    pub async fn avg<'c, E: Executor<'c>>(mut self, db: E, column: &str) -> Result<Option<f64>> {
1133        let Some(column) = self.column(column) else {
1134            return Err(self.check().unwrap_err());
1135        };
1136        self.aggregate(db, format!("CAST(AVG({column}) AS DOUBLE PRECISION)"))
1137            .await
1138    }
1139
1140    /// The smallest value of `column`, or `None` without rows.
1141    pub async fn min<'c, T: FromDb, E: Executor<'c>>(
1142        mut self,
1143        db: E,
1144        column: &str,
1145    ) -> Result<Option<T>>
1146    where
1147        Option<T>: FromDb,
1148    {
1149        let Some(column) = self.column(column) else {
1150            return Err(self.check().unwrap_err());
1151        };
1152        self.aggregate(db, format!("MIN({column})")).await
1153    }
1154
1155    /// The largest value of `column`, or `None` without rows.
1156    pub async fn max<'c, T: FromDb, E: Executor<'c>>(
1157        mut self,
1158        db: E,
1159        column: &str,
1160    ) -> Result<Option<T>>
1161    where
1162        Option<T>: FromDb,
1163    {
1164        let Some(column) = self.column(column) else {
1165            return Err(self.check().unwrap_err());
1166        };
1167        self.aggregate(db, format!("MAX({column})")).await
1168    }
1169
1170    /// One column of the matching rows, in the query's order:
1171    /// `Product::query().order_by("name").pluck::<String, _>(&db, "name")`.
1172    pub async fn pluck<'c, T: FromDb, E: Executor<'c>>(
1173        mut self,
1174        db: E,
1175        column: impl IntoColumn<M>,
1176    ) -> Result<Vec<T>> {
1177        let Some(column) = self.column(column.column_name()) else {
1178            return Err(self.check().unwrap_err());
1179        };
1180        self.check()?;
1181        let db = db.into_conn();
1182        let statement = self.select_columns_sql(db.dialect(), &column);
1183        Ok(sql(statement)
1184            .bind_all(self.select_binds())
1185            .scalars(db)
1186            .await?)
1187    }
1188
1189    /// Sets columns on every matching row (and `updated_at` when the model
1190    /// has it); returns how many changed.
1191    ///
1192    /// ```
1193    /// # use renox::prelude::*;
1194    /// # #[derive(Model, serde::Serialize, Default)] struct Order { id: i64, status: String, paid_at: Option<DateTime> }
1195    /// # async fn demo(db: Db) -> Result {
1196    /// Order::where_eq("status", "pending")
1197    ///     .update(&db, &[("status", &"paid"), ("paid_at", &renox::db::now())])
1198    ///     .await?;
1199    /// # Ok(()) }
1200    /// ```
1201    pub async fn update<'c, E: Executor<'c>>(
1202        mut self,
1203        db: E,
1204        values: &[(&str, &(dyn ToDbValue + Sync))],
1205    ) -> Result<u64> {
1206        let mut sets = Vec::new();
1207        let mut binds = Vec::new();
1208        for (column, value) in values {
1209            if *column == "id" {
1210                self.error
1211                    .get_or_insert_with(|| "update can't change `id`".into());
1212            }
1213            if let Some(quoted) = self.column(column) {
1214                sets.push(format!("{quoted} = ?"));
1215                binds.push(value.to_db_value());
1216            }
1217        }
1218        if M::COLUMNS.contains(&"updated_at") && !values.iter().any(|(c, _)| *c == "updated_at") {
1219            sets.push(format!("{} = ?", quote("updated_at")));
1220            binds.push(now().to_db_value());
1221        }
1222        if sets.is_empty() {
1223            self.check()?;
1224            return Ok(0);
1225        }
1226        self.set_rows(db, sets.join(", "), binds).await
1227    }
1228
1229    /// Adds `by` to `column` on every matching row (negative to subtract),
1230    /// in the database, so concurrent changes aren't lost:
1231    /// `Product::where_eq("id", id).increment(&db, "stock", -1)`.
1232    pub async fn increment<'c, E: Executor<'c>>(
1233        mut self,
1234        db: E,
1235        column: &str,
1236        by: i64,
1237    ) -> Result<u64> {
1238        let Some(quoted) = self.column(column) else {
1239            return Err(self.check().unwrap_err());
1240        };
1241        let mut sets = format!("{quoted} = {quoted} + ?");
1242        let mut binds = vec![DbValue::Integer(by)];
1243        if M::COLUMNS.contains(&"updated_at") {
1244            sets.push_str(&format!(", {} = ?", quote("updated_at")));
1245            binds.push(now().to_db_value());
1246        }
1247        self.set_rows(db, sets, binds).await
1248    }
1249
1250    async fn set_rows<'c, E: Executor<'c>>(
1251        self,
1252        db: E,
1253        sets: String,
1254        binds: Vec<DbValue>,
1255    ) -> Result<u64> {
1256        self.check()?;
1257        let db = db.into_conn();
1258        let statement = format!(
1259            "UPDATE {} SET {sets}{}",
1260            quote(M::TABLE),
1261            self.where_sql(db.dialect())
1262        );
1263        Ok(sql(statement)
1264            .bind_all(binds)
1265            .bind_all(self.binds)
1266            .execute(db)
1267            .await?)
1268    }
1269
1270    /// Like `first`, but no row becomes a 404 response.
1271    pub async fn first_or_404<'c, E: Executor<'c>>(self, db: E) -> Result<M> {
1272        self.first(db).await?.ok_or(crate::Error::NotFound)
1273    }
1274
1275    /// The first matching row, or `make()` saved as a new one. If another
1276    /// request creates it at the same moment (a unique index stops the
1277    /// second insert), the row it created is returned.
1278    //
1279    // Not an `async fn`: written that way, a handler awaiting it failed
1280    // axum's `Send` check (rustc issue #100013; see it/send_handlers.rs).
1281    #[allow(clippy::manual_async_fn)] // the `+ Send` in the signature is the point
1282    pub fn first_or_create<'a>(
1283        self,
1284        db: &'a Db,
1285        make: impl FnOnce() -> M + Send + 'a,
1286    ) -> impl Future<Output = Result<M>> + Send + 'a {
1287        async move {
1288            if let Some(found) = self.clone().first(db).await? {
1289                return Ok(found);
1290            }
1291            match M::create(db, make()).await {
1292                Ok(created) => Ok(created),
1293                Err(err) if err.is_unique_violation() => self.first(db).await?.ok_or(err),
1294                Err(err) => Err(err),
1295            }
1296        }
1297    }
1298
1299    /// Runs `each` on the matching rows `size` at a time, in id order, so a
1300    /// large table never sits in memory at once. (The query's own order and
1301    /// limit don't apply.)
1302    pub async fn chunk<F, Fut>(self, db: &Db, size: u64, mut each: F) -> Result<u64>
1303    where
1304        F: FnMut(Vec<M>) -> Fut,
1305        Fut: std::future::Future<Output = Result>,
1306    {
1307        let mut last: Option<M::Key> = None;
1308        let mut seen = 0_u64;
1309        loop {
1310            let mut page = self.clone();
1311            page.clear_order();
1312            page.limit = None;
1313            page.offset = None;
1314            if let Some(last) = last.take() {
1315                page = page.where_op("id", ">", last);
1316            }
1317            let rows = page.order_by("id").limit(size.max(1)).get(db).await?;
1318            let Some(tail) = rows.last() else { break };
1319            last = Some(tail.id());
1320            let full = rows.len() as u64 == size.max(1);
1321            seen += rows.len() as u64;
1322            each(rows).await?;
1323            if !full {
1324                break;
1325            }
1326        }
1327        Ok(seen)
1328    }
1329
1330    /// Runs the query and returns every matching row.
1331    pub async fn get<'c, E: Executor<'c>>(self, db: E) -> Result<Vec<M>> {
1332        self.check()?;
1333        let db = db.into_conn();
1334        let rows = sql(self.select_sql(db.dialect()))
1335            .bind_all(self.select_binds())
1336            .fetch_all(db)
1337            .await?;
1338        Ok(rows
1339            .iter()
1340            .map(M::from_row)
1341            .collect::<std::result::Result<_, _>>()?)
1342    }
1343
1344    /// The first matching row (in the query's order), or `None`.
1345    pub async fn first<'c, E: Executor<'c>>(self, db: E) -> Result<Option<M>> {
1346        Ok(self.limit(1).get(db).await?.into_iter().next())
1347    }
1348
1349    /// How many rows match (with `group_by`: how many groups).
1350    pub async fn count<'c, E: Executor<'c>>(self, db: E) -> Result<u64> {
1351        self.check()?;
1352        let db = db.into_conn();
1353        let statement = if self.group.is_empty() {
1354            format!(
1355                "SELECT COUNT(*) FROM {}{}",
1356                quote(M::TABLE),
1357                self.where_sql(db.dialect())
1358            )
1359        } else {
1360            format!(
1361                "SELECT COUNT(*) FROM (SELECT 1 AS one FROM {}{}{}) AS groups",
1362                quote(M::TABLE),
1363                self.where_sql(db.dialect()),
1364                self.group_sql()
1365            )
1366        };
1367        let count: i64 = sql(statement).bind_all(self.all_binds()).scalar(db).await?;
1368        Ok(count as u64)
1369    }
1370
1371    /// Whether any row matches.
1372    pub async fn exists<'c, E: Executor<'c>>(self, db: E) -> Result<bool> {
1373        Ok(self.count(db).await? > 0)
1374    }
1375
1376    /// One page of results plus the numbers needed to render page links.
1377    /// `page` starts at 1; `per_page` is capped at 1000.
1378    pub async fn paginate(self, db: &Db, page: u32, per_page: u32) -> Result<Paginated<M>> {
1379        let page = page.max(1);
1380        let per_page = per_page.clamp(1, 1000);
1381        let total = self.clone().count(db).await?;
1382        let items = self
1383            .limit(u64::from(per_page))
1384            .offset(u64::from(page - 1) * u64::from(per_page))
1385            .get(db)
1386            .await?;
1387        Ok(Paginated::new(items, page, per_page, total))
1388    }
1389
1390    /// One page without counting the rows (one query instead of two): for
1391    /// "previous / next" links on large tables. `page` starts at 1.
1392    pub async fn simple_paginate(self, db: &Db, page: u32, per_page: u32) -> Result<SimplePage<M>> {
1393        let page = page.max(1);
1394        let per_page = per_page.clamp(1, 1000);
1395        let mut items = self
1396            .limit(u64::from(per_page) + 1)
1397            .offset(u64::from(page - 1) * u64::from(per_page))
1398            .get(db)
1399            .await?;
1400        let has_next = items.len() > per_page as usize;
1401        items.truncate(per_page as usize);
1402        Ok(SimplePage {
1403            items,
1404            page,
1405            per_page,
1406            has_prev: page > 1,
1407            has_next,
1408        })
1409    }
1410
1411    /// The `per_page` newest rows after `cursor` (by id; the query's own
1412    /// order doesn't apply), for APIs and infinite scroll on big tables:
1413    /// unlike page numbers, rows added meanwhile don't shift the pages.
1414    /// "Newest" is the key's order: creation order for `i64`, ULIDs and
1415    /// UUID v7s; a `String` key pages in text order.
1416    ///
1417    /// ```
1418    /// # use renox::prelude::*;
1419    /// # #[derive(Model, serde::Serialize, Default)] struct Event { id: i64, name: String }
1420    /// #[derive(serde::Deserialize)]
1421    /// struct Params { cursor: Option<String> }
1422    ///
1423    /// async fn events(State(db): State<Db>, Query(p): Query<Params>) -> Result<Json<renox::db::CursorPage<Event>>> {
1424    ///     Ok(Json(Event::query().cursor_paginate(&db, p.cursor.as_deref(), 50).await?))
1425    /// }
1426    /// ```
1427    pub async fn cursor_paginate(
1428        mut self,
1429        db: &Db,
1430        cursor: Option<&str>,
1431        per_page: u32,
1432    ) -> Result<CursorPage<M>> {
1433        let per_page = per_page.clamp(1, 1000);
1434        if let Some(cursor) = cursor {
1435            let Ok(after) = cursor.parse::<M::Key>() else {
1436                return Err(crate::Error::BadRequest("invalid cursor".into()));
1437            };
1438            self = self.where_op("id", "<", after);
1439        }
1440        self.clear_order();
1441        let mut items = self
1442            .order_by_desc("id")
1443            .limit(u64::from(per_page) + 1)
1444            .get(db)
1445            .await?;
1446        let more = items.len() > per_page as usize;
1447        items.truncate(per_page as usize);
1448        let next_cursor = more
1449            .then(|| items.last().map(|last| last.id().to_string()))
1450            .flatten();
1451        Ok(CursorPage {
1452            items,
1453            per_page,
1454            next_cursor,
1455        })
1456    }
1457
1458    /// The first matching row, or `make()` unsaved (`firstOrNew`).
1459    pub async fn first_or_new(self, db: &Db, make: impl FnOnce() -> M + Send) -> Result<M> {
1460        Ok(match self.first(db).await? {
1461            Some(found) => found,
1462            None => make(),
1463        })
1464    }
1465
1466    /// Changes the first matching row with `change`, or creates `make()`
1467    /// with `change` applied (`updateOrCreate`); returns it saved.
1468    ///
1469    /// ```
1470    /// # use renox::prelude::*;
1471    /// # #[derive(Model, serde::Serialize, Default)] struct Setting { id: i64, user_id: i64, key: String, value: String }
1472    /// # async fn demo(db: Db) -> Result {
1473    /// let theme = Setting::where_eq("user_id", 7)
1474    ///     .where_eq("key", "theme")
1475    ///     .update_or_create(
1476    ///         &db,
1477    ///         || Setting { user_id: 7, key: "theme".into(), ..Default::default() },
1478    ///         |s| s.value = "dark".into(),
1479    ///     )
1480    ///     .await?;
1481    /// # let _ = theme; Ok(()) }
1482    /// ```
1483    #[allow(clippy::manual_async_fn)] // the `+ Send` in the signature is the point
1484    pub fn update_or_create<'a>(
1485        self,
1486        db: &'a Db,
1487        make: impl FnOnce() -> M + Send + 'a,
1488        change: impl FnOnce(&mut M) + Send + 'a,
1489    ) -> impl Future<Output = Result<M>> + Send + 'a {
1490        async move {
1491            let mut model = match self.first(db).await? {
1492                Some(found) => found,
1493                None => make(),
1494            };
1495            change(&mut model);
1496            model.save(db).await?;
1497            Ok(model)
1498        }
1499    }
1500
1501    /// Deletes every matching row (soft-deletes them for models with soft deletes).
1502    pub async fn delete<'c, E: Executor<'c>>(self, db: E) -> Result<u64> {
1503        if M::SOFT_DELETES {
1504            self.check()?;
1505            let db = db.into_conn();
1506            return Ok(sql(format!(
1507                "UPDATE {} SET \"deleted_at\" = ?{}",
1508                quote(M::TABLE),
1509                self.where_sql(db.dialect())
1510            ))
1511            .bind(now())
1512            .bind_all(self.binds)
1513            .execute(db)
1514            .await?);
1515        }
1516        self.force_delete(db).await
1517    }
1518
1519    /// Removes every matching row, even for models with soft deletes.
1520    pub async fn force_delete<'c, E: Executor<'c>>(self, db: E) -> Result<u64> {
1521        self.check()?;
1522        let db = db.into_conn();
1523        Ok(sql(format!(
1524            "DELETE FROM {}{}",
1525            quote(M::TABLE),
1526            self.where_sql(db.dialect())
1527        ))
1528        .bind_all(self.binds)
1529        .execute(db)
1530        .await?)
1531    }
1532}