Skip to main content

rws_server/model/
query.rs

1//! Async fluent `QueryBuilder<T>` for constructing SQL queries.
2
3use std::marker::PhantomData;
4
5use super::backend::Backend;
6use super::pool::DbPool;
7use super::repository::{extract_count, live_condition, placeholder, timestamp_placeholder};
8use super::timestamp::Timestamp;
9use super::{DbError, Model, ToColumn, Value};
10use crate::pagination::{CursorPage, Page};
11
12// ── Order ─────────────────────────────────────────────────────────────────────
13
14/// Sort direction for `order_by`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Order {
17    Asc,
18    Desc,
19}
20
21impl Order {
22    fn as_sql(self) -> &'static str {
23        match self {
24            Order::Asc => "ASC",
25            Order::Desc => "DESC",
26        }
27    }
28}
29
30// ── Deleted ───────────────────────────────────────────────────────────────────
31
32/// Which rows of a soft-delete model a query sees.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34enum Deleted {
35    /// Not soft-deleted (the default).
36    Exclude,
37    /// All.
38    Include,
39    /// Soft-deleted only.
40    Only,
41}
42
43// ── QueryBuilder ──────────────────────────────────────────────────────────────
44
45/// Fluent async query builder for `SELECT`, `COUNT`, `DELETE`, and `UPDATE`.
46///
47/// For a model with a soft-delete column (`#[soft_delete]`) every operation
48/// sees only rows not deleted, unless the chain has
49/// [`with_deleted`](Self::with_deleted) or
50/// [`only_deleted`](Self::only_deleted); [`delete`](Self::delete) sets the
51/// column and [`force_delete`](Self::force_delete) removes rows. With
52/// `#[timestamps]` / `#[version]`, [`update`](Self::update) also sets
53/// `updated_at` and increments the version (18.30.0).
54///
55/// ```rust,no_run
56/// # extern crate rws_server as rust_web_server;
57/// # #[cfg(feature = "model-sqlite")]
58/// # async fn example() -> Result<(), rust_web_server::model::DbError> {
59/// use rust_web_server::model::{DbPool, Order, QueryBuilder};
60///
61/// let pool = DbPool::memory().await?;
62/// // pool.execute("CREATE TABLE users …", &[]).await?;
63///
64/// // let users: Vec<User> = QueryBuilder::<User>::new(&pool)
65/// //     .where_eq("active", true)
66/// //     .order_by("name", Order::Asc)
67/// //     .limit(10)
68/// //     .fetch_all()
69/// //     .await?;
70/// # Ok(())
71/// # }
72/// ```
73pub struct QueryBuilder<'a, T: Model> {
74    pool: &'a DbPool,
75    /// Each filter is a (sql_fragment, params) pair.
76    /// sql_fragment may contain `__placeholder__` (from `where_eq`) or raw `?`.
77    filters: Vec<(String, Vec<Value>)>,
78    order: Option<(String, Order)>,
79    limit: Option<u64>,
80    offset: Option<u64>,
81    deleted: Deleted,
82    _phantom: PhantomData<T>,
83}
84
85// Implemented by hand rather than `#[derive(Clone)]`: the derive macro adds a
86// `T: Clone` bound even though `T` only appears behind `PhantomData`, which
87// would force every `QueryBuilder<T>` user's model type to be `Clone` just to
88// call `.paginate()`.
89impl<'a, T: Model> Clone for QueryBuilder<'a, T> {
90    fn clone(&self) -> Self {
91        QueryBuilder {
92            pool: self.pool,
93            filters: self.filters.clone(),
94            order: self.order.clone(),
95            limit: self.limit,
96            offset: self.offset,
97            deleted: self.deleted,
98            _phantom: PhantomData,
99        }
100    }
101}
102
103impl<'a, T: Model> QueryBuilder<'a, T> {
104    pub fn new(pool: &'a DbPool) -> Self {
105        QueryBuilder {
106            pool,
107            filters: Vec::new(),
108            order: None,
109            limit: None,
110            offset: None,
111            deleted: Deleted::Exclude,
112            _phantom: PhantomData,
113        }
114    }
115
116    /// Soft-deleted rows too (no effect on a model without `#[soft_delete]`).
117    pub fn with_deleted(mut self) -> Self {
118        self.deleted = Deleted::Include;
119        self
120    }
121
122    /// Soft-deleted rows only (none for a model without `#[soft_delete]`).
123    pub fn only_deleted(mut self) -> Self {
124        self.deleted = Deleted::Only;
125        self
126    }
127
128    /// The filters plus the soft-delete scope.
129    fn scoped_filters(&self) -> Vec<(String, Vec<Value>)> {
130        let mut filters = self.filters.clone();
131        if let Some(col) = T::soft_delete_column() {
132            match self.deleted {
133                Deleted::Exclude => filters.extend(live_condition::<T>().map(|c| (c, Vec::new()))),
134                Deleted::Include => {}
135                Deleted::Only => filters.push((format!("{col} IS NOT NULL"), Vec::new())),
136            }
137        } else if self.deleted == Deleted::Only {
138            filters.push(("1 = 0".to_string(), Vec::new()));
139        }
140        filters
141    }
142
143    /// Add a `col = ?` equality filter.
144    pub fn where_eq(mut self, col: &str, val: impl ToColumn) -> Self {
145        self.filters.push((
146            format!("{} = __placeholder__", col),
147            vec![val.to_column()],
148        ));
149        self
150    }
151
152    /// Add a raw SQL filter fragment with bind parameters.
153    ///
154    /// ```ignore
155    /// .filter("age >= ?", vec![Value::Int(18)])
156    /// ```
157    pub fn filter(mut self, expr: &str, params: Vec<Value>) -> Self {
158        self.filters.push((expr.to_owned(), params));
159        self
160    }
161
162    /// Set the ORDER BY clause.
163    pub fn order_by(mut self, col: &str, order: Order) -> Self {
164        self.order = Some((col.to_owned(), order));
165        self
166    }
167
168    /// Set the LIMIT clause.
169    pub fn limit(mut self, n: u64) -> Self {
170        self.limit = Some(n);
171        self
172    }
173
174    /// Set the OFFSET clause.
175    pub fn offset(mut self, n: u64) -> Self {
176        self.offset = Some(n);
177        self
178    }
179
180    // ── Terminal operations ───────────────────────────────────────────────────
181
182    /// Execute `SELECT * FROM table WHERE … ORDER BY … LIMIT … OFFSET …`.
183    pub async fn fetch_all(self) -> Result<Vec<T>, DbError> {
184        let backend = self.pool.backend();
185        let filters = self.scoped_filters();
186        let (sql, params) = build_select::<T>(
187            filters, self.order, self.limit, self.offset, "*", backend,
188        );
189        let rows = self.pool.query_rows(&sql, &params).await?;
190        rows.iter().map(|r| T::from_row(r)).collect()
191    }
192
193    /// Execute `SELECT * … LIMIT 1` and return the first result.
194    pub async fn fetch_one(self) -> Result<Option<T>, DbError> {
195        let backend = self.pool.backend();
196        let filters = self.scoped_filters();
197        let (sql, params) = build_select::<T>(
198            filters, self.order, Some(1), self.offset, "*", backend,
199        );
200        let rows = self.pool.query_rows(&sql, &params).await?;
201        match rows.into_iter().next() {
202            Some(row) => Ok(Some(T::from_row(&row)?)),
203            None => Ok(None),
204        }
205    }
206
207    /// Execute `SELECT COUNT(*) FROM table WHERE …` (without the chain's
208    /// `ORDER BY`, which PostgreSQL refuses next to an aggregate).
209    pub async fn count(self) -> Result<i64, DbError> {
210        let backend = self.pool.backend();
211        let filters = self.scoped_filters();
212        let (sql, params) = build_select::<T>(
213            filters, None, self.limit, self.offset, "COUNT(*)", backend,
214        );
215        let rows = self.pool.query_rows(&sql, &params).await?;
216        extract_count(rows)
217    }
218
219    /// Execute `DELETE FROM table WHERE …` — for a soft-delete model,
220    /// `UPDATE table SET deleted_at = now WHERE … AND deleted_at IS NULL`
221    /// instead ([`force_delete`](Self::force_delete) removes the rows).
222    pub async fn delete(self) -> Result<(), DbError> {
223        let Some(col) = T::soft_delete_column() else {
224            return self.force_delete().await.map(|_| ());
225        };
226        let backend = self.pool.backend();
227        let mut filters = self.filters.clone();
228        filters.extend(live_condition::<T>().map(|c| (c, Vec::new())));
229        let (where_clause, where_params, _) = build_where(filters, 1, backend);
230        let mut params = vec![Timestamp::now().to_value(backend)];
231        params.extend(where_params);
232        let sql = format!("UPDATE {} SET {} = {}{}", T::table_name(), col, timestamp_placeholder(backend, 1), where_clause);
233        self.pool.execute(&sql, &params).await?;
234        Ok(())
235    }
236
237    /// Execute `DELETE FROM table WHERE …`, removing the rows whatever the
238    /// soft-delete column says (within the query's scope: add
239    /// [`with_deleted`](Self::with_deleted) to include deleted rows).
240    /// Answers the number of rows removed.
241    pub async fn force_delete(self) -> Result<u64, DbError> {
242        let backend = self.pool.backend();
243        let (where_clause, params, _) = build_where(self.scoped_filters(), 0, backend);
244        let sql = format!("DELETE FROM {}{}", T::table_name(), where_clause);
245        self.pool.execute(&sql, &params).await
246    }
247
248    /// Clear the soft-delete column of the matching deleted rows; answers
249    /// how many. An error for a model without `#[soft_delete]`.
250    pub async fn restore(self) -> Result<u64, DbError> {
251        let Some(col) = T::soft_delete_column() else {
252            return Err(DbError::new(format!(
253                "restore: {} has no soft-delete column (add #[soft_delete] and a deleted_at field)",
254                T::table_name()
255            )));
256        };
257        let backend = self.pool.backend();
258        let mut filters = self.filters.clone();
259        filters.push((format!("{col} IS NOT NULL"), Vec::new()));
260        let (where_clause, params, _) = build_where(filters, 0, backend);
261        let sql = format!("UPDATE {} SET {} = NULL{}", T::table_name(), col, where_clause);
262        self.pool.execute(&sql, &params).await
263    }
264
265    /// Execute `UPDATE table SET col = ? WHERE …` (also `updated_at = now`
266    /// and `version = version + 1` when the model has them).
267    pub async fn update(self, col: &str, val: impl ToColumn) -> Result<(), DbError> {
268        let backend = self.pool.backend();
269        let (mut sets, mut params) = match val.to_column() {
270            // A literal NULL: PostgreSQL won't assign one bound as text to
271            // a column of another type.
272            Value::Null => (vec![format!("{col} = NULL")], Vec::new()),
273            value => (vec![format!("{} = {}", col, placeholder(backend, 1))], vec![value]),
274        };
275        if let Some(updated) = T::updated_at_column().filter(|c| *c != col) {
276            params.push(Timestamp::now().to_value(backend));
277            sets.push(format!("{} = {}", updated, timestamp_placeholder(backend, params.len())));
278        }
279        if let Some(version) = T::version_column().filter(|c| *c != col) {
280            sets.push(format!("{version} = {version} + 1"));
281        }
282        let (where_clause, where_params, _) = build_where(self.scoped_filters(), params.len(), backend);
283        params.extend(where_params);
284        let sql = format!("UPDATE {} SET {}{}", T::table_name(), sets.join(", "), where_clause);
285        self.pool.execute(&sql, &params).await?;
286        Ok(())
287    }
288
289    /// Offset-paginated fetch: runs a `COUNT(*)` (with the same filters, no
290    /// limit/offset) and a `SELECT … LIMIT … OFFSET …`, and wraps both into a
291    /// [`Page`]. `page` is 1-based; both `page` and `per_page` are clamped to
292    /// a minimum of `1`. Overrides any `.limit()`/`.offset()` set earlier in
293    /// the chain — `page`/`per_page` are authoritative.
294    ///
295    /// Two queries, not one — if you're paginating a very large, frequently
296    /// appended-to table and don't need `total_pages`, [`Self::paginate_after`]
297    /// (keyset pagination) needs only one.
298    pub async fn paginate(self, page: u64, per_page: u64) -> Result<Page<T>, DbError> {
299        let page = page.max(1);
300        let per_page = per_page.max(1);
301        let offset = (page - 1) * per_page;
302
303        let total_items = self.clone().count().await? as u64;
304        let items = self.limit(per_page).offset(offset).fetch_all().await?;
305
306        Ok(Page::new(items, page, per_page, total_items))
307    }
308
309    /// Cursor (keyset) paginated fetch: orders by the primary key ascending,
310    /// fetches `per_page + 1` rows to cheaply detect whether there's a next
311    /// page, and returns a [`CursorPage`] whose `next_cursor` is the last
312    /// returned row's primary key (as a string) — pass it back as `cursor` to
313    /// get the next page. `cursor: None` fetches the first page.
314    ///
315    /// A single query, unlike [`Self::paginate`] — no `COUNT(*)`, and no
316    /// `OFFSET` to skip over on every subsequent page, which is what makes
317    /// keyset pagination scale on large tables where offset pagination gets
318    /// slower page by page. The tradeoff: no `total_items`/`total_pages`, and
319    /// only forward iteration (no jumping to an arbitrary page).
320    ///
321    /// Overrides any `.order_by()` set earlier in the chain — keyset
322    /// pagination requires ordering by the cursor column. Requires the
323    /// primary key to be numeric (parsed as `i64`); returns `Err` if `cursor`
324    /// isn't a valid integer.
325    pub async fn paginate_after(self, cursor: Option<&str>, per_page: u64) -> Result<CursorPage<T>, DbError> {
326        let per_page = per_page.max(1);
327        let pk_col = T::primary_key_name();
328
329        let mut builder = self;
330        if let Some(cursor_str) = cursor {
331            let cursor_val: i64 = cursor_str
332                .parse()
333                .map_err(|_| DbError::new(format!("invalid cursor '{}': expected an integer primary key", cursor_str)))?;
334            builder = builder.filter(&format!("{} > __placeholder__", pk_col), vec![Value::Int(cursor_val)]);
335        }
336
337        let mut rows = builder.order_by(pk_col, Order::Asc).limit(per_page + 1).fetch_all().await?;
338
339        let has_more = rows.len() as u64 > per_page;
340        if has_more {
341            rows.truncate(per_page as usize);
342        }
343
344        let next_cursor = if has_more {
345            rows.last().map(|item| match item.primary_key_value() {
346                Value::Int(n) => n.to_string(),
347                Value::Text(s) => s,
348                other => format!("{:?}", other),
349            })
350        } else {
351            None
352        };
353
354        Ok(CursorPage { items: rows, next_cursor })
355    }
356}
357
358// ── Internal SQL builders ─────────────────────────────────────────────────────
359
360fn build_select<T: Model>(
361    filters: Vec<(String, Vec<Value>)>,
362    order: Option<(String, Order)>,
363    limit: Option<u64>,
364    offset: Option<u64>,
365    projection: &str,
366    backend: Backend,
367) -> (String, Vec<Value>) {
368    let (where_clause, params, _) = build_where(filters, 0, backend);
369    let mut sql = format!("SELECT {} FROM {}{}", projection, T::table_name(), where_clause);
370    if let Some((col, ord)) = order {
371        sql.push_str(&format!(" ORDER BY {} {}", col, ord.as_sql()));
372    }
373    if let Some(n) = limit {
374        sql.push_str(&format!(" LIMIT {}", n));
375    }
376    if let Some(n) = offset {
377        sql.push_str(&format!(" OFFSET {}", n));
378    }
379    (sql, params)
380}
381
382/// Build the WHERE clause. `start_idx` offsets PostgreSQL `$N` placeholders.
383#[doc(hidden)]
384pub fn build_where(
385    filters: Vec<(String, Vec<Value>)>,
386    start_idx: usize,
387    backend: Backend,
388) -> (String, Vec<Value>, usize) {
389    let mut all_params: Vec<Value> = Vec::new();
390    let mut conditions: Vec<String> = Vec::new();
391    let mut idx = start_idx;
392
393    for (mut fragment, params) in filters {
394        for param in params {
395            idx += 1;
396            if fragment.contains("__placeholder__") {
397                fragment = fragment.replacen("__placeholder__", &placeholder(backend, idx), 1);
398            } else {
399                // A raw fragment written with a literal `?` (e.g. from
400                // `.filter("age >= ?", ...)`) — no-op on backends that
401                // already use `?`, rewrites it to `$N` on PostgreSQL.
402                fragment = fragment.replacen("?", &placeholder(backend, idx), 1);
403            }
404            all_params.push(param);
405        }
406        conditions.push(fragment);
407    }
408
409    let where_clause = if conditions.is_empty() {
410        String::new()
411    } else {
412        format!(" WHERE {}", conditions.join(" AND "))
413    };
414
415    (where_clause, all_params, idx)
416}