Skip to main content

larust_orm/
query_builder.rs

1use crate::pool::{backend, pool, Backend};
2use larust_core::{axum, AppError};
3use sqlx::any::{Any, AnyArguments};
4use sqlx::query::QueryAs;
5use sqlx::AnyPool;
6use std::marker::PhantomData;
7
8/// A dynamically-typed bind value - `where_eq` accepts any of these via
9/// `Into<BindValue>` so the builder can accumulate heterogeneous
10/// conditions (`where_eq(Post::TITLE, "x").where_eq(Post::ID, 1)`) in one
11/// `Vec` before binding them to the query at execution time.
12#[derive(Clone)]
13pub enum BindValue {
14    Text(String),
15    Int(i64),
16    Bool(bool),
17}
18
19impl From<String> for BindValue {
20    fn from(v: String) -> Self {
21        BindValue::Text(v)
22    }
23}
24
25impl From<&str> for BindValue {
26    fn from(v: &str) -> Self {
27        BindValue::Text(v.to_string())
28    }
29}
30
31impl From<i64> for BindValue {
32    fn from(v: i64) -> Self {
33        BindValue::Int(v)
34    }
35}
36
37impl From<bool> for BindValue {
38    fn from(v: bool) -> Self {
39        BindValue::Bool(v)
40    }
41}
42
43/// `WHERE column <op> ?` - richer comparisons than `where_eq`'s plain
44/// equality (Laravel's 3-argument `->where($col, '>', $val)`).
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Op {
47    Ne,
48    Gt,
49    Gte,
50    Lt,
51    Lte,
52    Like,
53}
54
55impl Op {
56    fn as_sql(self) -> &'static str {
57        match self {
58            Op::Ne => "!=",
59            Op::Gt => ">",
60            Op::Gte => ">=",
61            Op::Lt => "<",
62            Op::Lte => "<=",
63            Op::Like => "LIKE",
64        }
65    }
66}
67
68/// `.order_by(column, Order::Desc)` - Laravel's `->orderBy($col, 'desc')`.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum Order {
71    Asc,
72    Desc,
73}
74
75/// How a condition joins to the one before it. The very first entry in a
76/// `wheres` list never actually renders its own `Conj` (there's nothing
77/// before it to join to) - stored anyway so every entry has the same
78/// shape, rather than special-casing the first element's type.
79#[derive(Clone, Copy)]
80enum Conj {
81    And,
82    Or,
83}
84
85/// One accumulated `WHERE` condition - private, built only through the
86/// builder's own `where_*`/`or_where_*`/`scope`/`*_group` methods, so
87/// callers never construct one directly.
88#[derive(Clone)]
89enum Condition {
90    Eq(&'static str, BindValue),
91    Op(&'static str, Op, BindValue),
92    In(&'static str, Vec<BindValue>),
93    Null(&'static str),
94    NotNull(&'static str),
95    /// `where_group`/`or_where_group`/`scope` - a parenthesized
96    /// sub-clause. Carries a full nested `wheres` list (not just a single
97    /// `Condition`) because a group's own contents can themselves mix
98    /// `AND`/`OR`.
99    Group(Vec<(Conj, Condition)>),
100    /// `where_in_query` - "col" IN (SELECT sub_column FROM sub_table
101    /// [WHERE ...]). Deliberately a subquery, not a real `JOIN`:
102    /// `QueryBuilder` decodes every row into one `sqlx::FromRow` struct
103    /// via `SELECT *`, and its column constants (`Post::TITLE`) are bare,
104    /// unqualified names - both assumptions a real multi-table `JOIN`
105    /// would break (ambiguous `id`, ambiguous bare column names across
106    /// tables) without a breaking redesign (a qualified `Column{table,
107    /// name}` type everywhere). A subquery filter needs neither change
108    /// and covers the same "filter by a related table's rows"(`hasManyThrough`,
109    /// Eloquent's `whereHas`) use case this was added for.
110    InQuery {
111        column: &'static str,
112        sub_table: &'static str,
113        sub_column: &'static str,
114        sub_wheres: Vec<(Conj, Condition)>,
115    },
116}
117
118/// How a soft-deletable `QueryBuilder` filters on its own soft-delete
119/// column - only ever set to anything but `Normal` via
120/// `with_trashed`/`only_trashed`, both gated to `T: SoftDeletes` (see
121/// that trait's own doc comment).
122#[derive(Clone, Copy)]
123enum SoftDeleteFilter {
124    Normal,
125    WithTrashed,
126    OnlyTrashed,
127}
128
129/// Laravel-shaped query builder (`Post::query().where_eq(...).latest(...)`)
130/// over `sqlx`. Column names passed in (`Post::TITLE`) are `&'static str`
131/// constants generated by `#[derive(Model)]`, never user input, so they're
132/// interpolated directly into the SQL string; bound *values* always go
133/// through placeholders - never string-formatted into the query.
134pub struct QueryBuilder<T> {
135    table: &'static str,
136    wheres: Vec<(Conj, Condition)>,
137    order_by: Vec<(&'static str, Order)>,
138    limit: Option<i64>,
139    /// `None` for the overwhelming majority of models (never marked
140    /// `#[soft_deletes]`) - set only by the hidden setter below, which
141    /// only the *generated* `query()` for a soft-deletable model calls.
142    soft_delete: Option<(&'static str, SoftDeleteFilter)>,
143    _marker: PhantomData<fn() -> T>,
144}
145
146/// **Known gap: a `bool`-typed field on a `#[derive(Model, sqlx::FromRow)]`
147/// struct doesn't decode through `AnyRow` on SQLite.** SQLite has no native
148/// boolean column type (it stores `0`/`1` as an `INTEGER`); the concrete
149/// `sqlx::Sqlite` driver knows to coerce that into `bool`, but `sqlx`'s
150/// backend-agnostic `Any` driver tags the column as its own generic
151/// `BigInt` kind instead and refuses the conversion (confirmed
152/// empirically: decoding fails with "Rust type `bool` is not compatible
153/// with SQL type `BIGINT`" - MySQL's own `Any` adapter doesn't have this
154/// problem, since MySQL's `TINYINT(1)`/`BOOLEAN` gets tagged correctly).
155/// No current app model in this workspace has a `bool` field, so this
156/// hasn't needed a real fix yet - if one ever does, decode the column as
157/// `i64` and compare `!= 0` by hand instead (see
158/// `larust-permissions::has_role`/`has_permission_to` for the exact
159/// pattern, needed for their own `SELECT EXISTS(...)` queries).
160///
161/// **A second, more consequential known gap in the same family: a
162/// `String`-typed field backed by a MySQL `TEXT` (or `TINYTEXT`/
163/// `MEDIUMTEXT`/`LONGTEXT`) column doesn't decode through `Any` at all,
164/// on *any* app model - not just framework-internal ones.** Confirmed
165/// empirically against a real MySQL server: `sqlx-mysql`'s own `Any`
166/// adapter maps every one of those column types to its own generic
167/// `Blob` kind unconditionally (it keys off the wire-protocol
168/// `ColumnType` alone, which doesn't distinguish TEXT from BLOB the way
169/// the column's actual charset does), and `Decode<Any> for String` only
170/// ever accepts `Text`-kind values - decoding fails with "Rust type
171/// `String` is not compatible with SQL type `BLOB`". Only `CHAR`/
172/// `VARCHAR` map to `Any`'s `Text` kind. **A MySQL-targeted app's own
173/// migrations need `VARCHAR(n)` for any column a model reads back as
174/// `String`, not `TEXT`** - every framework-owned table with its own
175/// bootstrap SQL (`larust-http::session`'s `sessions.data`,
176/// `larust-cache`'s `cache_items.value`, `larust-queue`'s `jobs.payload`/
177/// `failed_jobs.error`, `larust-notifications`'s `notifications.data`/
178/// `notification_type`, `larust-sanctum`'s `personal_access_tokens.name`)
179/// already had to make this exact switch, each landing on a generous but
180/// bounded `VARCHAR(4000)` (kept well under MySQL's ~65,535-byte
181/// combined-row-size limit even at `utf8mb4`'s worst-case 4 bytes/char,
182/// confirmed empirically against a real server - `VARCHAR(16383)` alone
183/// already exceeds it once more than one such column shares a row).
184/// There is no known workaround for genuinely unbounded content (a long
185/// blog post body, say) beyond raising that cap and accepting the
186/// row-size math, or waiting for an upstream `sqlx` fix - MySQL/`Any`
187/// support in this framework is not a byte-for-byte drop-in replacement
188/// for SQLite's own effectively-unlimited `TEXT` in that one specific
189/// respect.
190///
191/// **Postgres has neither gap - confirmed empirically against a real
192/// server, not just inferred from its type system.** A native `BOOLEAN`
193/// column decodes straight into `bool` through `Any` with no `i64`
194/// workaround needed, and a `TEXT` column of several thousand characters
195/// decodes straight into `String` with no `VARCHAR(n)` cap needed -
196/// Postgres's own `Any` adapter tags both correctly (`Bool`/`Text` kind),
197/// unlike SQLite's/MySQL's own adapters. Every framework-owned table's
198/// Postgres arm (see `larust-cache`/`larust-queue`/`larust-sanctum`/
199/// `larust-notifications`/`larust-http::session`) uses plain `TEXT`, not
200/// a MySQL-style `VARCHAR(4000)` cap, on the strength of this.
201impl<T> QueryBuilder<T>
202where
203    T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin,
204{
205    pub fn new(table: &'static str) -> Self {
206        Self {
207            table,
208            wheres: Vec::new(),
209            order_by: Vec::new(),
210            limit: None,
211            soft_delete: None,
212            _marker: PhantomData,
213        }
214    }
215
216    /// Not part of the public API (hence `#[doc(hidden)]`, not a true
217    /// visibility restriction - it has to be `pub` so macro-generated
218    /// code in a *different* crate, an app's own, can call it). Only
219    /// `#[derive(Model)]`'s generated `query()` calls this, and only for
220    /// a struct marked `#[soft_deletes]` - every other call site never
221    /// touches it, leaving `soft_delete` at its default `None`.
222    #[doc(hidden)]
223    #[must_use]
224    pub fn __with_soft_delete_column(mut self, column: &'static str) -> Self {
225        self.soft_delete = Some((column, SoftDeleteFilter::Normal));
226        self
227    }
228
229    #[must_use]
230    pub fn where_eq(mut self, column: &'static str, value: impl Into<BindValue>) -> Self {
231        self.wheres
232            .push((Conj::And, Condition::Eq(column, value.into())));
233        self
234    }
235
236    /// `WHERE column <op> value` (Laravel's 3-argument `->where(...)`) -
237    /// for comparisons `where_eq` can't express (`!=`, `>`, `>=`, `<`,
238    /// `<=`, `LIKE`).
239    #[must_use]
240    pub fn where_op(mut self, column: &'static str, op: Op, value: impl Into<BindValue>) -> Self {
241        self.wheres
242            .push((Conj::And, Condition::Op(column, op, value.into())));
243        self
244    }
245
246    /// `WHERE column IS NULL`.
247    #[must_use]
248    pub fn where_null(mut self, column: &'static str) -> Self {
249        self.wheres.push((Conj::And, Condition::Null(column)));
250        self
251    }
252
253    /// `WHERE column IS NOT NULL`.
254    #[must_use]
255    pub fn where_not_null(mut self, column: &'static str) -> Self {
256        self.wheres.push((Conj::And, Condition::NotNull(column)));
257        self
258    }
259
260    /// `WHERE column IN (values...)` (Laravel's `->whereIn(...)`) - used by
261    /// relationship batch loaders (`load_*`, see `larust-macros`'
262    /// `relations.rs`) to fetch every related row for a whole batch of
263    /// already-loaded rows in one query instead of one query per row.
264    /// `values` empty is a real case (batch-loading relations for an empty
265    /// input slice), not just a hypothetical - rendering treats it as a
266    /// condition that matches nothing (`1=0`), since `"col" IN ()` is
267    /// invalid SQL in SQLite (a syntax error, not an empty-result query).
268    #[must_use]
269    pub fn where_in<V: Into<BindValue>>(mut self, column: &'static str, values: Vec<V>) -> Self {
270        self.wheres.push((
271            Conj::And,
272            Condition::In(column, values.into_iter().map(Into::into).collect()),
273        ));
274        self
275    }
276
277    /// `OR column = value`.
278    #[must_use]
279    pub fn or_where_eq(mut self, column: &'static str, value: impl Into<BindValue>) -> Self {
280        self.wheres
281            .push((Conj::Or, Condition::Eq(column, value.into())));
282        self
283    }
284
285    /// `OR column <op> value`.
286    #[must_use]
287    pub fn or_where_op(
288        mut self,
289        column: &'static str,
290        op: Op,
291        value: impl Into<BindValue>,
292    ) -> Self {
293        self.wheres
294            .push((Conj::Or, Condition::Op(column, op, value.into())));
295        self
296    }
297
298    /// `OR column IN (values...)`.
299    #[must_use]
300    pub fn or_where_in<V: Into<BindValue>>(mut self, column: &'static str, values: Vec<V>) -> Self {
301        self.wheres.push((
302            Conj::Or,
303            Condition::In(column, values.into_iter().map(Into::into).collect()),
304        ));
305        self
306    }
307
308    /// `OR column IS NULL`.
309    #[must_use]
310    pub fn or_where_null(mut self, column: &'static str) -> Self {
311        self.wheres.push((Conj::Or, Condition::Null(column)));
312        self
313    }
314
315    /// A parenthesized `AND (...)` group - `f` receives an empty builder
316    /// over this same table and whatever conditions it adds (via its own
317    /// return value) become the group's contents; nothing else about the
318    /// builder `f` receives (table/order/limit) is used. Exists so an
319    /// `OR` added *inside* the group doesn't leak out and change the
320    /// precedence of conditions already on `self` - see `scope`'s own doc
321    /// comment for the same concern, solved automatically there.
322    #[must_use]
323    pub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
324        self.push_group(Conj::And, f)
325    }
326
327    /// `OR (...)` - see `where_group`.
328    #[must_use]
329    pub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
330        self.push_group(Conj::Or, f)
331    }
332
333    fn push_group(mut self, conj: Conj, f: impl FnOnce(Self) -> Self) -> Self {
334        let group_wheres = f(Self::new(self.table)).wheres;
335        self.wheres.push((conj, Condition::Group(group_wheres)));
336        self
337    }
338
339    /// A reusable, named `WHERE` preset (Eloquent's local scopes), e.g.:
340    ///
341    /// ```ignore
342    /// impl Post {
343    ///     pub fn published(q: QueryBuilder<Self>) -> QueryBuilder<Self> {
344    ///         q.where_not_null(Self::PUBLISHED_AT)
345    ///     }
346    /// }
347    /// Post::query().scope(Post::published).latest(Post::ID).get().await?;
348    /// ```
349    ///
350    /// Unlike `where_group`, a scope's own conditions are only wrapped in
351    /// a parenthesized group when they actually contain an `OR` - an
352    /// all-`AND` scope body is flattened directly into `self` instead,
353    /// since plain `AND`s are associative with whatever else is on
354    /// `self` and don't need the parens. This is specifically what
355    /// prevents the classic Eloquent scope-precedence leak: a scope whose
356    /// own body uses `OR` (`Post::recent_or_pinned`, say) can be combined
357    /// with other conditions on `self` without that internal `OR`
358    /// silently changing what the *rest* of the query matches.
359    #[must_use]
360    pub fn scope(mut self, f: impl FnOnce(Self) -> Self) -> Self {
361        let scope_wheres = f(Self::new(self.table)).wheres;
362        let needs_group = scope_wheres
363            .iter()
364            .any(|(conj, _)| matches!(conj, Conj::Or));
365        if needs_group {
366            self.wheres
367                .push((Conj::And, Condition::Group(scope_wheres)));
368        } else {
369            self.wheres.extend(scope_wheres);
370        }
371        self
372    }
373
374    /// `WHERE column IN (SELECT sub_column FROM ... [WHERE ...])` - a
375    /// subquery filter against a *different* model's table, built from
376    /// `sub`'s own current state (table + whatever `where_*` it's already
377    /// chained) - its own conditions, not `self`'s, become the
378    /// subquery's `WHERE` clause. See `Condition::InQuery`'s own doc
379    /// comment for why this is a subquery, not a real `JOIN`.
380    #[must_use]
381    pub fn where_in_query<U>(
382        mut self,
383        column: &'static str,
384        sub_column: &'static str,
385        sub: QueryBuilder<U>,
386    ) -> Self {
387        self.wheres.push((
388            Conj::And,
389            Condition::InQuery {
390                column,
391                sub_table: sub.table,
392                sub_column,
393                sub_wheres: sub.wheres,
394            },
395        ));
396        self
397    }
398
399    /// Orders by `column` descending (Laravel's `->latest($column)`).
400    /// Each call *adds* a sort key rather than replacing the last one -
401    /// matching Eloquent's own `->orderBy(...)` chaining.
402    #[must_use]
403    pub fn latest(mut self, column: &'static str) -> Self {
404        self.order_by.push((column, Order::Desc));
405        self
406    }
407
408    /// Orders by `column` ascending (Laravel's `->oldest($column)`).
409    #[must_use]
410    pub fn oldest(mut self, column: &'static str) -> Self {
411        self.order_by.push((column, Order::Asc));
412        self
413    }
414
415    /// `->orderBy($column, $direction)` - `latest`/`oldest` are sugar for
416    /// this with a fixed direction.
417    #[must_use]
418    pub fn order_by(mut self, column: &'static str, direction: Order) -> Self {
419        self.order_by.push((column, direction));
420        self
421    }
422
423    /// Caps the number of rows returned, independent of `paginate` (which
424    /// sets this internally). No public `.offset()` yet - SQLite/MySQL/
425    /// Postgres disagree on whether `OFFSET` needs a `LIMIT` alongside it
426    /// (MySQL requires one; Postgres doesn't), and nothing in this
427    /// codebase needs offset-without-limit yet to justify picking one of
428    /// the backend-specific workarounds.
429    #[must_use]
430    pub fn limit(mut self, n: i64) -> Self {
431        self.limit = Some(n);
432        self
433    }
434
435    /// A stand-in for Laravel's `->paginate($perPage)` - limits to
436    /// `per_page` rows. Page-number/metadata support (current page, total
437    /// count, links) is a later addition; for now this is equivalent to
438    /// `.limit(per_page).get()`.
439    pub async fn paginate(mut self, per_page: i64) -> Result<Vec<T>, AppError> {
440        if per_page <= 0 {
441            return Err(AppError::Http {
442                status: axum::http::StatusCode::UNPROCESSABLE_ENTITY,
443                message: "pagination size must be greater than zero".to_string(),
444            });
445        }
446        self.limit = Some(per_page);
447        self.get().await
448    }
449
450    pub async fn get(self) -> Result<Vec<T>, AppError> {
451        self.get_on(pool()?).await
452    }
453
454    /// Executes this query against an explicit pool. This is the preferred
455    /// building block for applications moving away from process-wide ORM
456    /// state, while `get()` remains compatible with existing models.
457    pub async fn get_on(self, database: &AnyPool) -> Result<Vec<T>, AppError> {
458        let sql = self.build_sql(backend(), None);
459        let combined = self.soft_delete_combined_wheres();
460        let wheres = combined.as_deref().unwrap_or(&self.wheres);
461        let query = bind_all(sqlx::query_as::<_, T>(&sql), wheres);
462        query
463            .fetch_all(database)
464            .await
465            .map_err(|e| AppError::Internal(Box::new(e)))
466    }
467
468    pub async fn first(self) -> Result<Option<T>, AppError> {
469        self.first_on(pool()?).await
470    }
471
472    pub async fn first_on(self, database: &AnyPool) -> Result<Option<T>, AppError> {
473        let sql = self.build_sql(backend(), Some(1));
474        let combined = self.soft_delete_combined_wheres();
475        let wheres = combined.as_deref().unwrap_or(&self.wheres);
476        let query = bind_all(sqlx::query_as::<_, T>(&sql), wheres);
477        query
478            .fetch_optional(database)
479            .await
480            .map_err(|e| AppError::Internal(Box::new(e)))
481    }
482
483    pub async fn count(self) -> Result<i64, AppError> {
484        self.count_on(pool()?).await
485    }
486
487    pub async fn count_on(self, database: &AnyPool) -> Result<i64, AppError> {
488        let sql = self.build_count_sql(backend());
489        let combined = self.soft_delete_combined_wheres();
490        let wheres = combined.as_deref().unwrap_or(&self.wheres);
491        let query = bind_all(sqlx::query_as::<_, (i64,)>(&sql), wheres);
492        query
493            .fetch_one(database)
494            .await
495            .map(|(count,)| count)
496            .map_err(|e| AppError::Internal(Box::new(e)))
497    }
498
499    pub async fn exists(self) -> Result<bool, AppError> {
500        Ok(self.first().await?.is_some())
501    }
502
503    /// `backend` is passed in explicitly (rather than read from the
504    /// process-wide `larust_orm::backend()` singleton internally) purely so
505    /// this stays unit-testable - that singleton's `OnceLock` can only be
506    /// set once per process, so a single test binary could never otherwise
507    /// exercise both the `?` (SQLite/MySQL) and `$N` (Postgres) render
508    /// paths side by side. Every real caller (`get_on`/`first_on`/
509    /// `count_on` above) still resolves it from the same global `backend()`
510    /// every other framework crate already reads.
511    fn build_sql(&self, backend: Backend, first_limit: Option<i64>) -> String {
512        // Every identifier here is quoted (`"..."`) - `self.table` and each
513        // `column` are always `&'static str` constants generated by
514        // `#[derive(Model)]` from a table/field name, never runtime data,
515        // so quoting is about not colliding with a SQL reserved keyword
516        // (a field named `order`, say), not about injection.
517        let mut sql = format!("SELECT * FROM \"{}\"", self.table);
518
519        let combined = self.soft_delete_combined_wheres();
520        let wheres = combined.as_deref().unwrap_or(&self.wheres);
521        if !wheres.is_empty() {
522            let mut next_placeholder = 1usize;
523            sql.push_str(" WHERE ");
524            sql.push_str(&render_wheres(wheres, backend, &mut next_placeholder));
525        }
526
527        if !self.order_by.is_empty() {
528            let parts: Vec<String> = self
529                .order_by
530                .iter()
531                .map(|(column, direction)| {
532                    let direction = match direction {
533                        Order::Asc => "ASC",
534                        Order::Desc => "DESC",
535                    };
536                    format!("\"{column}\" {direction}")
537                })
538                .collect();
539            sql.push_str(&format!(" ORDER BY {}", parts.join(", ")));
540        }
541
542        if let Some(limit) = first_limit.or(self.limit) {
543            sql.push_str(&format!(" LIMIT {limit}"));
544        }
545
546        sql
547    }
548
549    fn build_count_sql(&self, backend: Backend) -> String {
550        let mut sql = format!("SELECT COUNT(*) FROM \"{}\"", self.table);
551        let combined = self.soft_delete_combined_wheres();
552        let wheres = combined.as_deref().unwrap_or(&self.wheres);
553        if !wheres.is_empty() {
554            let mut next_placeholder = 1usize;
555            sql.push_str(" WHERE ");
556            sql.push_str(&render_wheres(wheres, backend, &mut next_placeholder));
557        }
558        sql
559    }
560
561    /// `None` when nothing needs combining (the common case: most models
562    /// aren't soft-deletable at all, or the caller explicitly asked for
563    /// every row via `with_trashed()`) - callers then use `&self.wheres`
564    /// directly with no extra allocation. `Some(combined)` otherwise: the
565    /// soft-delete filter condition, combined with `self.wheres` -
566    /// wrapped in a `Group` only if `self.wheres` itself has a top-level
567    /// `OR` (same reasoning as `scope`'s own precedence-safe grouping),
568    /// since a bare, un-parenthesized `"deleted_at" IS NULL AND a OR b`
569    /// would otherwise only bind to `a`, not the whole clause.
570    fn soft_delete_combined_wheres(&self) -> Option<Vec<(Conj, Condition)>> {
571        let (column, filter) = self.soft_delete?;
572        let filter_condition = match filter {
573            SoftDeleteFilter::WithTrashed => return None,
574            SoftDeleteFilter::Normal => Condition::Null(column),
575            SoftDeleteFilter::OnlyTrashed => Condition::NotNull(column),
576        };
577        if self.wheres.is_empty() {
578            return Some(vec![(Conj::And, filter_condition)]);
579        }
580        let has_top_level_or = self.wheres.iter().any(|(conj, _)| matches!(conj, Conj::Or));
581        let mut combined = vec![(Conj::And, filter_condition)];
582        if has_top_level_or {
583            combined.push((Conj::And, Condition::Group(self.wheres.clone())));
584        } else {
585            combined.extend(self.wheres.iter().cloned());
586        }
587        Some(combined)
588    }
589}
590
591/// Implemented automatically, only for a `#[derive(Model)]` struct marked
592/// `#[soft_deletes]` - gates `with_trashed`/`only_trashed` (below) at
593/// *compile* time, so calling either on a model that never opted in is a
594/// compile error (no such method exists on `QueryBuilder<NotSoftDeleted>`),
595/// not a silent no-op or a runtime error.
596pub trait SoftDeletes: crate::Model {}
597
598impl<T> QueryBuilder<T>
599where
600    T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin + SoftDeletes,
601{
602    /// Includes soft-deleted rows alongside normal ones (Eloquent's
603    /// `withTrashed()`).
604    #[must_use]
605    pub fn with_trashed(mut self) -> Self {
606        if let Some((column, _)) = self.soft_delete {
607            self.soft_delete = Some((column, SoftDeleteFilter::WithTrashed));
608        }
609        self
610    }
611
612    /// Only soft-deleted rows (Eloquent's `onlyTrashed()`).
613    #[must_use]
614    pub fn only_trashed(mut self) -> Self {
615        if let Some((column, _)) = self.soft_delete {
616            self.soft_delete = Some((column, SoftDeleteFilter::OnlyTrashed));
617        }
618        self
619    }
620}
621
622/// One `?` (SQLite/MySQL) or `$N` (Postgres, `next_placeholder`
623/// incrementing left-to-right across the whole clause) - see `sqlx-core`'s
624/// own doc comment (confirmed by reading its vendored source): Postgres and
625/// SQLite accept `$1, $2, ...`; MySQL/MariaDB require `?`. SQLite is kept on
626/// `?` here (not switched to `$N` even though it would also accept it) to
627/// match this codebase's existing MySQL-sharing convention and avoid
628/// touching working SQL text with no behavioral need to.
629fn next_placeholder_str(backend: Backend, next_placeholder: &mut usize) -> String {
630    match backend {
631        Backend::Sqlite | Backend::MySql => "?".to_string(),
632        Backend::Postgres => {
633            let n = *next_placeholder;
634            *next_placeholder += 1;
635            format!("${n}")
636        }
637    }
638}
639
640/// Renders a full `AND`/`OR`-joined clause list with no surrounding
641/// parens (the caller adds those for a `Group`) - shared by the
642/// top-level `WHERE`, a `Group`'s own contents, and an `InQuery`'s
643/// subquery `WHERE`, all of which are "a `wheres` list rendered in
644/// order," recursively.
645fn render_wheres(
646    wheres: &[(Conj, Condition)],
647    backend: Backend,
648    next_placeholder: &mut usize,
649) -> String {
650    let mut out = String::new();
651    for (i, (conj, condition)) in wheres.iter().enumerate() {
652        if i > 0 {
653            out.push_str(match conj {
654                Conj::And => " AND ",
655                Conj::Or => " OR ",
656            });
657        }
658        out.push_str(&render_condition(condition, backend, next_placeholder));
659    }
660    out
661}
662
663/// Renders one condition's SQL fragment (no values - those are bound
664/// separately by `bind_all`, in the same left-to-right order this
665/// function's placeholders appear in - bind order is positional, so it
666/// doesn't matter whether the SQL text says `?` or `$3`).
667fn render_condition(
668    condition: &Condition,
669    backend: Backend,
670    next_placeholder: &mut usize,
671) -> String {
672    match condition {
673        Condition::Eq(column, _) => {
674            format!(
675                "\"{column}\" = {}",
676                next_placeholder_str(backend, next_placeholder)
677            )
678        }
679        Condition::Op(column, op, _) => {
680            format!(
681                "\"{column}\" {} {}",
682                op.as_sql(),
683                next_placeholder_str(backend, next_placeholder)
684            )
685        }
686        // Empty IN-list: "col" IN () is a SQLite syntax error, not an
687        // empty-result query - 1=0 is the standard always-false
688        // substitute, so `where_in(col, vec![])` correctly yields zero
689        // rows instead of failing the whole query.
690        Condition::In(_, values) if values.is_empty() => "1=0".to_string(),
691        Condition::In(column, values) => {
692            let placeholders = values
693                .iter()
694                .map(|_| next_placeholder_str(backend, next_placeholder))
695                .collect::<Vec<_>>()
696                .join(", ");
697            format!("\"{column}\" IN ({placeholders})")
698        }
699        Condition::Null(column) => format!("\"{column}\" IS NULL"),
700        Condition::NotNull(column) => format!("\"{column}\" IS NOT NULL"),
701        Condition::Group(inner) => {
702            format!("({})", render_wheres(inner, backend, next_placeholder))
703        }
704        Condition::InQuery {
705            column,
706            sub_table,
707            sub_column,
708            sub_wheres,
709        } => {
710            let sub_where = if sub_wheres.is_empty() {
711                String::new()
712            } else {
713                format!(
714                    " WHERE {}",
715                    render_wheres(sub_wheres, backend, next_placeholder)
716                )
717            };
718            format!("\"{column}\" IN (SELECT \"{sub_column}\" FROM \"{sub_table}\"{sub_where})")
719        }
720    }
721}
722
723fn bind_all<'q, T>(
724    mut query: QueryAs<'q, Any, T, AnyArguments<'q>>,
725    wheres: &'q [(Conj, Condition)],
726) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
727    for (_, condition) in wheres {
728        query = bind_condition(query, condition);
729    }
730    query
731}
732
733/// Recurses into `Group`/`InQuery` in the same left-to-right order
734/// `render_condition`/`render_wheres` render them, so bind order (purely
735/// positional - `sqlx` doesn't care whether the SQL text said `?` or
736/// `$3`) always lines up with the placeholders those functions emitted.
737fn bind_condition<'q, T>(
738    mut query: QueryAs<'q, Any, T, AnyArguments<'q>>,
739    condition: &'q Condition,
740) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
741    match condition {
742        Condition::Eq(_, value) | Condition::Op(_, _, value) => {
743            query = bind_value(query, value);
744        }
745        Condition::In(_, values) => {
746            for value in values {
747                query = bind_value(query, value);
748            }
749        }
750        Condition::Null(_) | Condition::NotNull(_) => {}
751        Condition::Group(inner) => {
752            query = bind_all(query, inner);
753        }
754        Condition::InQuery { sub_wheres, .. } => {
755            query = bind_all(query, sub_wheres);
756        }
757    }
758    query
759}
760
761fn bind_value<'q, T>(
762    query: QueryAs<'q, Any, T, AnyArguments<'q>>,
763    value: &'q BindValue,
764) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
765    match value {
766        BindValue::Text(s) => query.bind(s),
767        BindValue::Int(i) => query.bind(i),
768        BindValue::Bool(b) => query.bind(b),
769    }
770}
771
772#[cfg(test)]
773mod tests {
774    use super::*;
775
776    #[derive(sqlx::FromRow)]
777    struct Dummy {
778        #[allow(dead_code)]
779        id: i64,
780    }
781
782    #[derive(sqlx::FromRow)]
783    struct SoftDeletedDummy {
784        #[allow(dead_code)]
785        id: i64,
786    }
787
788    impl crate::Model for SoftDeletedDummy {
789        type New = ();
790        const TABLE: &'static str = "soft_deleted_dummies";
791        const SOFT_DELETE_COLUMN: Option<&'static str> = Some("deleted_at");
792
793        async fn create(_data: Self::New) -> Result<Self, AppError> {
794            unimplemented!("not exercised by these tests")
795        }
796    }
797
798    impl SoftDeletes for SoftDeletedDummy {}
799
800    #[test]
801    fn quotes_table_and_column_identifiers_so_reserved_keywords_are_safe() {
802        let qb: QueryBuilder<Dummy> = QueryBuilder::new("order")
803            .where_eq("group", 1i64)
804            .latest("select");
805
806        assert_eq!(
807            qb.build_sql(Backend::Sqlite, None),
808            "SELECT * FROM \"order\" WHERE \"group\" = ? ORDER BY \"select\" DESC"
809        );
810    }
811
812    #[test]
813    fn build_sql_with_no_conditions() {
814        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts");
815        assert_eq!(
816            qb.build_sql(Backend::Sqlite, None),
817            "SELECT * FROM \"posts\""
818        );
819        assert_eq!(
820            qb.build_sql(Backend::Sqlite, Some(1)),
821            "SELECT * FROM \"posts\" LIMIT 1"
822        );
823    }
824
825    #[test]
826    fn where_in_renders_one_placeholder_per_value() {
827        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", vec![1i64, 2, 3]);
828        assert_eq!(
829            qb.build_sql(Backend::Sqlite, None),
830            "SELECT * FROM \"posts\" WHERE \"id\" IN (?, ?, ?)"
831        );
832    }
833
834    #[test]
835    fn where_in_with_a_single_value() {
836        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", vec![1i64]);
837        assert_eq!(
838            qb.build_sql(Backend::Sqlite, None),
839            "SELECT * FROM \"posts\" WHERE \"id\" IN (?)"
840        );
841    }
842
843    #[test]
844    fn where_in_with_an_empty_list_renders_an_always_false_condition() {
845        // "id" IN () is a SQLite syntax error, not an empty-result query -
846        // this must render as something SQLite accepts and that matches
847        // zero rows.
848        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", Vec::<i64>::new());
849        assert_eq!(
850            qb.build_sql(Backend::Sqlite, None),
851            "SELECT * FROM \"posts\" WHERE 1=0"
852        );
853    }
854
855    #[test]
856    fn where_in_quotes_the_column_identifier() {
857        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("order", vec![1i64]);
858        assert_eq!(
859            qb.build_sql(Backend::Sqlite, None),
860            "SELECT * FROM \"posts\" WHERE \"order\" IN (?)"
861        );
862    }
863
864    #[test]
865    fn where_eq_and_where_in_combine_with_and() {
866        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
867            .where_eq("title", "hi")
868            .where_in("id", vec![1i64, 2]);
869        assert_eq!(
870            qb.build_sql(Backend::Sqlite, None),
871            "SELECT * FROM \"posts\" WHERE \"title\" = ? AND \"id\" IN (?, ?)"
872        );
873    }
874
875    #[test]
876    fn mysql_renders_the_same_question_mark_placeholders_as_sqlite() {
877        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
878            .where_eq("title", "hi")
879            .where_in("id", vec![1i64, 2]);
880        assert_eq!(
881            qb.build_sql(Backend::MySql, None),
882            "SELECT * FROM \"posts\" WHERE \"title\" = ? AND \"id\" IN (?, ?)"
883        );
884    }
885
886    #[test]
887    fn postgres_renders_numbered_placeholders_incrementing_across_the_whole_where_clause() {
888        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
889            .where_eq("title", "hi")
890            .where_in("id", vec![1i64, 2, 3]);
891        assert_eq!(
892            qb.build_sql(Backend::Postgres, None),
893            "SELECT * FROM \"posts\" WHERE \"title\" = $1 AND \"id\" IN ($2, $3, $4)"
894        );
895    }
896
897    #[test]
898    fn postgres_where_in_with_an_empty_list_still_renders_an_always_false_condition() {
899        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", Vec::<i64>::new());
900        assert_eq!(
901            qb.build_sql(Backend::Postgres, None),
902            "SELECT * FROM \"posts\" WHERE 1=0"
903        );
904    }
905
906    #[test]
907    fn build_count_sql_renders_numbered_placeholders_for_postgres() {
908        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_eq("title", "hi");
909        assert_eq!(
910            qb.build_count_sql(Backend::Postgres),
911            "SELECT COUNT(*) FROM \"posts\" WHERE \"title\" = $1"
912        );
913    }
914
915    #[test]
916    fn where_op_renders_the_chosen_comparison() {
917        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_op("views", Op::Gt, 10i64);
918        assert_eq!(
919            qb.build_sql(Backend::Sqlite, None),
920            "SELECT * FROM \"posts\" WHERE \"views\" > ?"
921        );
922    }
923
924    #[test]
925    fn where_null_and_where_not_null_render_with_no_placeholder() {
926        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
927            .where_null("deleted_at")
928            .where_not_null("published_at");
929        assert_eq!(
930            qb.build_sql(Backend::Sqlite, None),
931            "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND \"published_at\" IS NOT NULL"
932        );
933    }
934
935    #[test]
936    fn or_where_variants_join_with_or_instead_of_and() {
937        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
938            .where_eq("status", "draft")
939            .or_where_eq("status", "published")
940            .or_where_null("archived_at");
941        assert_eq!(
942            qb.build_sql(Backend::Sqlite, None),
943            "SELECT * FROM \"posts\" WHERE \"status\" = ? OR \"status\" = ? OR \"archived_at\" IS NULL"
944        );
945    }
946
947    #[test]
948    fn where_group_parenthesizes_only_its_own_conditions() {
949        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
950            .where_eq("user_id", 1i64)
951            .where_group(|q| {
952                q.where_eq("status", "draft")
953                    .or_where_eq("status", "published")
954            });
955        assert_eq!(
956            qb.build_sql(Backend::Sqlite, None),
957            "SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND (\"status\" = ? OR \"status\" = ?)"
958        );
959    }
960
961    #[test]
962    fn scope_flattens_an_all_and_scope_with_no_parens() {
963        fn published(q: QueryBuilder<Dummy>) -> QueryBuilder<Dummy> {
964            q.where_not_null("published_at")
965        }
966        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
967            .where_eq("user_id", 1i64)
968            .scope(published);
969        assert_eq!(
970            qb.build_sql(Backend::Sqlite, None),
971            "SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND \"published_at\" IS NOT NULL"
972        );
973    }
974
975    #[test]
976    fn scope_groups_a_scope_that_uses_or_so_it_cannot_leak_precedence() {
977        fn recent_or_pinned(q: QueryBuilder<Dummy>) -> QueryBuilder<Dummy> {
978            q.where_eq("pinned", true).or_where_eq("recent", true)
979        }
980        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
981            .where_eq("user_id", 1i64)
982            .scope(recent_or_pinned);
983        assert_eq!(
984            qb.build_sql(Backend::Sqlite, None),
985            "SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND (\"pinned\" = ? OR \"recent\" = ?)"
986        );
987    }
988
989    #[test]
990    fn where_in_query_renders_a_subquery_with_its_own_where() {
991        let sub: QueryBuilder<Dummy> = QueryBuilder::new("users").where_eq("country_id", 7i64);
992        let qb: QueryBuilder<Dummy> =
993            QueryBuilder::new("posts").where_in_query("user_id", "id", sub);
994        assert_eq!(
995            qb.build_sql(Backend::Sqlite, None),
996            "SELECT * FROM \"posts\" WHERE \"user_id\" IN (SELECT \"id\" FROM \"users\" WHERE \"country_id\" = ?)"
997        );
998    }
999
1000    #[test]
1001    fn where_in_query_with_no_sub_conditions_omits_the_subquerys_where() {
1002        let sub: QueryBuilder<Dummy> = QueryBuilder::new("users");
1003        let qb: QueryBuilder<Dummy> =
1004            QueryBuilder::new("posts").where_in_query("user_id", "id", sub);
1005        assert_eq!(
1006            qb.build_sql(Backend::Sqlite, None),
1007            "SELECT * FROM \"posts\" WHERE \"user_id\" IN (SELECT \"id\" FROM \"users\")"
1008        );
1009    }
1010
1011    #[test]
1012    fn postgres_numbers_placeholders_in_order_across_a_group_and_a_subquery() {
1013        let sub: QueryBuilder<Dummy> = QueryBuilder::new("users").where_eq("country_id", 7i64);
1014        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
1015            .where_eq("archived", false)
1016            .where_group(|q| {
1017                q.where_eq("status", "draft")
1018                    .or_where_eq("status", "published")
1019            })
1020            .where_in_query("user_id", "id", sub);
1021        assert_eq!(
1022            qb.build_sql(Backend::Postgres, None),
1023            "SELECT * FROM \"posts\" WHERE \"archived\" = $1 AND (\"status\" = $2 OR \"status\" = $3) AND \"user_id\" IN (SELECT \"id\" FROM \"users\" WHERE \"country_id\" = $4)"
1024        );
1025    }
1026
1027    #[test]
1028    fn order_by_chains_multiple_sort_keys_in_call_order() {
1029        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
1030            .order_by("priority", Order::Desc)
1031            .oldest("created_at");
1032        assert_eq!(
1033            qb.build_sql(Backend::Sqlite, None),
1034            "SELECT * FROM \"posts\" ORDER BY \"priority\" DESC, \"created_at\" ASC"
1035        );
1036    }
1037
1038    #[test]
1039    fn limit_sets_the_same_clause_paginate_does() {
1040        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").limit(5);
1041        assert_eq!(
1042            qb.build_sql(Backend::Sqlite, None),
1043            "SELECT * FROM \"posts\" LIMIT 5"
1044        );
1045    }
1046
1047    #[test]
1048    fn a_non_soft_delete_model_renders_with_no_filter_at_all() {
1049        let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts");
1050        assert_eq!(
1051            qb.build_sql(Backend::Sqlite, None),
1052            "SELECT * FROM \"posts\""
1053        );
1054    }
1055
1056    #[test]
1057    fn soft_deletable_query_excludes_trashed_rows_by_default() {
1058        let qb: QueryBuilder<SoftDeletedDummy> =
1059            QueryBuilder::new("posts").__with_soft_delete_column("deleted_at");
1060        assert_eq!(
1061            qb.build_sql(Backend::Sqlite, None),
1062            "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL"
1063        );
1064    }
1065
1066    #[test]
1067    fn soft_delete_filter_prepends_plainly_when_no_or_is_present() {
1068        let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1069            .__with_soft_delete_column("deleted_at")
1070            .where_eq("status", "draft");
1071        assert_eq!(
1072            qb.build_sql(Backend::Sqlite, None),
1073            "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND \"status\" = ?"
1074        );
1075    }
1076
1077    #[test]
1078    fn soft_delete_filter_wraps_an_or_containing_where_clause_in_parens() {
1079        let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1080            .__with_soft_delete_column("deleted_at")
1081            .where_eq("status", "draft")
1082            .or_where_eq("status", "published");
1083        assert_eq!(
1084            qb.build_sql(Backend::Sqlite, None),
1085            "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND (\"status\" = ? OR \"status\" = ?)"
1086        );
1087    }
1088
1089    #[test]
1090    fn with_trashed_removes_the_default_exclusion_filter() {
1091        let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1092            .__with_soft_delete_column("deleted_at")
1093            .with_trashed();
1094        assert_eq!(
1095            qb.build_sql(Backend::Sqlite, None),
1096            "SELECT * FROM \"posts\""
1097        );
1098    }
1099
1100    #[test]
1101    fn only_trashed_filters_to_deleted_rows_only() {
1102        let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1103            .__with_soft_delete_column("deleted_at")
1104            .only_trashed();
1105        assert_eq!(
1106            qb.build_sql(Backend::Sqlite, None),
1107            "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NOT NULL"
1108        );
1109    }
1110}