rustango 0.40.0

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Typed column references — the compile-time-checked side of the query API.
//!
//! `#[derive(Model)]` emits a zero-sized type per scalar field, attaches a
//! `Column` impl, and re-exports it as an inherent `pub const` on the
//! struct. Users get `User::id`, `User::name`, etc., each carrying its own
//! `Value` type, so `User::id.eq("alice")` is a *compile* error rather than
//! a runtime `TypeMismatch`.

use std::marker::PhantomData;

use super::{Assignment, Filter, Model, Op, SqlValue, WhereExpr};

/// A typed reference to a single scalar column on `Self::Model`.
///
/// Implementations are generated by `#[derive(Model)]`; users normally
/// reach them through `User::<field>` consts, not by naming the trait.
pub trait Column: Copy + 'static {
    /// The model the column belongs to.
    type Model: Model;
    /// The Rust-side type of the column. Must be convertible into `SqlValue`.
    type Value: Into<SqlValue>;
    /// Rust-side field name.
    const NAME: &'static str;
    /// SQL-side column name.
    const COLUMN: &'static str;
    /// Dialect-neutral classification.
    const FIELD_TYPE: super::FieldType;

    /// `column = value`.
    fn eq<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Eq, value.into().into())
    }

    /// `column <> value`.
    fn ne<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Ne, value.into().into())
    }

    /// `column < value`.
    fn lt<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Lt, value.into().into())
    }

    /// `column <= value`.
    fn lte<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Lte, value.into().into())
    }

    /// `column > value`.
    fn gt<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Gt, value.into().into())
    }

    /// `column >= value`.
    fn gte<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Gte, value.into().into())
    }

    /// `column LIKE value` — case-sensitive.
    fn like<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Like, value.into().into())
    }

    /// `column NOT LIKE value` — case-sensitive.
    fn not_like<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::NotLike, value.into().into())
    }

    /// `column ILIKE value` — case-insensitive (Postgres).
    fn ilike<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::ILike, value.into().into())
    }

    /// `column NOT ILIKE value` — case-insensitive (Postgres).
    fn not_ilike<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::NotILike, value.into().into())
    }

    /// `column REGEXP pattern` — POSIX regex match. Django `__regex`
    /// (issue #26). Pattern is bound as a `String` parameter. Emits
    /// PG `~`, MySQL `REGEXP`, SQLite `REGEXP`. SQLite's `REGEXP`
    /// delegates to a `regexp(pattern, value)` user-function the
    /// caller must register — sqlx-sqlite does not register it
    /// automatically (the `regexp` cargo feature on sqlx-sqlite
    /// adds a `.with_regexp()` builder that does).
    fn regex(self, pattern: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Regex, SqlValue::String(pattern.into()))
    }

    /// `NOT column REGEXP pattern`. Django `~Q(field__regex=...)`.
    /// Same SQLite caveat as [`Column::regex`].
    fn not_regex(self, pattern: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::NotRegex, SqlValue::String(pattern.into()))
    }

    /// Case-insensitive POSIX regex match. Django `__iregex` (issue
    /// #26). Emits PG `~*`; MySQL + SQLite fall back to
    /// `LOWER(col) REGEXP LOWER(pattern)` for collation-independent
    /// case folding.
    fn iregex(self, pattern: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::IRegex, SqlValue::String(pattern.into()))
    }

    /// Case-insensitive POSIX regex non-match. Django
    /// `~Q(field__iregex=...)`.
    fn not_iregex(self, pattern: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::NotIRegex,
            SqlValue::String(pattern.into()),
        )
    }

    /// `column % pattern` — pg_trgm trigram similarity. Django's
    /// `__trigram_similar` (issue #29). Whole-string similarity at
    /// the default `pg_trgm.similarity_threshold` (0.3 unless
    /// overridden). **PG-only** — MySQL / SQLite reject at compile
    /// time. Requires `CREATE EXTENSION pg_trgm` on the database.
    fn trigram_similar(self, pattern: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::TrigramSimilar,
            SqlValue::String(pattern.into()),
        )
    }

    /// `column %> pattern` — pg_trgm word-similarity. Django's
    /// `__trigram_word_similar` (issue #29). Matches when **any
    /// word** in `column` is trigram-similar to the pattern.
    /// **PG-only**, same `pg_trgm` extension requirement as
    /// [`Column::trigram_similar`].
    fn trigram_word_similar(self, pattern: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::TrigramWordSimilar,
            SqlValue::String(pattern.into()),
        )
    }

    /// `to_tsvector(column) @@ plainto_tsquery(query)` — Postgres
    /// full-text search. Django's `__search` (issue #28). Uses the
    /// database's default text-search config. **PG-only** — MySQL
    /// and SQLite reject at compile time; their FTS shapes
    /// (MATCH…AGAINST, FTS5 MATCH) have incompatible semantics and
    /// table layouts.
    fn search(self, query: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::Search, SqlValue::String(query.into()))
    }

    /// `column @> value` — PG array containment. Django's `__contains`
    /// lookup on `ArrayField`. Returns rows whose array column fully
    /// contains every element of the value array. **PG-only** —
    /// MySQL and SQLite reject at compile time (no native array
    /// type). Issue #30.
    ///
    /// v1 supports `I32` / `I64` / `String` / `Bool` element types
    /// at bind time; other element kinds panic at bind.
    fn array_contains<V>(self, values: V) -> TypedFilter<Self::Model>
    where
        V: IntoIterator,
        V::Item: Into<SqlValue>,
    {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::ArrayContains,
            SqlValue::Array(values.into_iter().map(Into::into).collect()),
        )
    }

    /// `column <@ value` — PG array containment, inverted. Django's
    /// `__contained_by` lookup. **PG-only**. Issue #30.
    fn array_contained_by<V>(self, values: V) -> TypedFilter<Self::Model>
    where
        V: IntoIterator,
        V::Item: Into<SqlValue>,
    {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::ArrayContainedBy,
            SqlValue::Array(values.into_iter().map(Into::into).collect()),
        )
    }

    /// `column && value` — PG array overlap. Django's `__overlap`
    /// lookup. Returns rows whose array shares at least one element
    /// with the value array. **PG-only**. Issue #30.
    fn array_overlap<V>(self, values: V) -> TypedFilter<Self::Model>
    where
        V: IntoIterator,
        V::Item: Into<SqlValue>,
    {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::ArrayOverlap,
            SqlValue::Array(values.into_iter().map(Into::into).collect()),
        )
    }

    /// `column @> range_literal` — PG range column contains the
    /// given range. Django's `__range_contains` lookup with a range
    /// rhs. `literal` is a PG range literal string (e.g. `"[1, 10)"`,
    /// `"[2025-01-01, 2025-02-01)"`); PG implicit-casts it to the
    /// column's range type. **PG-only**. Issue #31.
    fn range_contains(self, literal: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::RangeContains,
            SqlValue::RangeLiteral(literal.into()),
        )
    }

    /// `column <@ range_literal` — PG range column is contained by
    /// the given range. Django's `__range_contained_by`. **PG-only**.
    /// Issue #31.
    fn range_contained_by(self, literal: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::RangeContainedBy,
            SqlValue::RangeLiteral(literal.into()),
        )
    }

    /// `column && range_literal` — PG range overlap. Django's
    /// `__range_overlap` lookup. **PG-only**. Issue #31.
    fn range_overlap(self, literal: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::RangeOverlap,
            SqlValue::RangeLiteral(literal.into()),
        )
    }

    /// `column << range_literal` — PG strictly-left-of. Issue #31.
    fn range_strictly_left(self, literal: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::RangeStrictlyLeft,
            SqlValue::RangeLiteral(literal.into()),
        )
    }

    /// `column >> range_literal` — PG strictly-right-of. Issue #31.
    fn range_strictly_right(self, literal: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::RangeStrictlyRight,
            SqlValue::RangeLiteral(literal.into()),
        )
    }

    /// `column -|- range_literal` — PG range adjacency. Issue #31.
    fn range_adjacent(self, literal: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::RangeAdjacent,
            SqlValue::RangeLiteral(literal.into()),
        )
    }

    /// `column IS NULL`.
    fn is_null(self) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::IsNull, SqlValue::Bool(true))
    }

    /// `column IS NOT NULL`.
    fn is_not_null(self) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::IsNull, SqlValue::Bool(false))
    }

    /// `column IN (v1, v2, …)`. Empty iterators are allowed at construction
    /// time; the SQL writer rejects them at compile time.
    fn is_in<V, I>(self, values: I) -> TypedFilter<Self::Model>
    where
        V: Into<Self::Value>,
        I: IntoIterator<Item = V>,
    {
        let list: Vec<SqlValue> = values.into_iter().map(|v| v.into().into()).collect();
        TypedFilter::scalar(Self::COLUMN, Op::In, SqlValue::List(list))
    }

    /// `column NOT IN (v1, v2, …)`.
    fn not_in<V, I>(self, values: I) -> TypedFilter<Self::Model>
    where
        V: Into<Self::Value>,
        I: IntoIterator<Item = V>,
    {
        let list: Vec<SqlValue> = values.into_iter().map(|v| v.into().into()).collect();
        TypedFilter::scalar(Self::COLUMN, Op::NotIn, SqlValue::List(list))
    }

    /// `column BETWEEN lo AND hi`. Both bounds are inclusive.
    fn between<V: Into<Self::Value>>(self, lo: V, hi: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(
            Self::COLUMN,
            Op::Between,
            SqlValue::List(vec![lo.into().into(), hi.into().into()]),
        )
    }

    /// `column IS DISTINCT FROM value` — null-safe inequality.
    fn is_distinct_from<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::IsDistinctFrom, value.into().into())
    }

    /// `column IS NOT DISTINCT FROM value` — null-safe equality.
    fn is_not_distinct_from<V: Into<Self::Value>>(self, value: V) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::IsNotDistinctFrom, value.into().into())
    }

    /// JSONB `@>` — column contains the given JSON value.
    /// Bind a `serde_json::Value`.
    fn json_contains(self, value: serde_json::Value) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::JsonContains, SqlValue::Json(value))
    }

    /// JSONB `<@` — column is contained by the given JSON value.
    fn json_contained_by(self, value: serde_json::Value) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::JsonContainedBy, SqlValue::Json(value))
    }

    /// JSONB `?` — the key exists as a top-level key in the column.
    fn json_has_key(self, key: impl Into<String>) -> TypedFilter<Self::Model> {
        TypedFilter::scalar(Self::COLUMN, Op::JsonHasKey, SqlValue::String(key.into()))
    }

    /// JSONB `?|` — any of the given keys exist as top-level keys.
    fn json_has_any_key<I: IntoIterator<Item = impl Into<String>>>(
        self,
        keys: I,
    ) -> TypedFilter<Self::Model> {
        let list: Vec<SqlValue> = keys
            .into_iter()
            .map(|k| SqlValue::String(k.into()))
            .collect();
        TypedFilter::scalar(Self::COLUMN, Op::JsonHasAnyKey, SqlValue::List(list))
    }

    /// JSONB `?&` — all of the given keys exist as top-level keys.
    fn json_has_all_keys<I: IntoIterator<Item = impl Into<String>>>(
        self,
        keys: I,
    ) -> TypedFilter<Self::Model> {
        let list: Vec<SqlValue> = keys
            .into_iter()
            .map(|k| SqlValue::String(k.into()))
            .collect();
        TypedFilter::scalar(Self::COLUMN, Op::JsonHasAllKeys, SqlValue::List(list))
    }

    /// `SET column = value` for an UPDATE.
    fn set<V: Into<Self::Value>>(self, value: V) -> TypedAssignment<Self::Model> {
        // value: V → Self::Value → SqlValue → Expr (each `.into()` step is
        // a registered `From` impl).
        let sql: SqlValue = value.into().into();
        TypedAssignment {
            inner: Assignment {
                column: Self::COLUMN,
                value: sql.into(),
            },
            _model: PhantomData,
        }
    }

    /// `SET column = <expression>` for an UPDATE — full [`Expr`] form,
    /// for `F()` column references and arithmetic. The literal-value
    /// shape stays on [`Column::set`].
    fn set_expr(self, expr: impl Into<crate::core::Expr>) -> TypedAssignment<Self::Model> {
        TypedAssignment {
            inner: Assignment {
                column: Self::COLUMN,
                value: expr.into(),
            },
            _model: PhantomData,
        }
    }

    // ----- Column-vs-expression predicates (Django `F()` rhs) -----

    /// `column = <expr>` — Django's `filter(col=F("other"))` shape.
    /// Accepts a bare [`F`](crate::core::F), a full [`Expr`](crate::core::Expr)
    /// (e.g. `F("a") + 1`), or anything else that lifts via
    /// `Into<Expr>`. Returns a [`TypedExpr`] so it composes with
    /// `.and()`/`.or()` exactly like the literal-rhs variants.
    fn eq_expr(self, rhs: impl Into<crate::core::Expr>) -> TypedExpr<Self::Model> {
        TypedExpr::column_cmp(Self::COLUMN, Op::Eq, rhs.into())
    }

    /// `column <> <expr>`.
    fn ne_expr(self, rhs: impl Into<crate::core::Expr>) -> TypedExpr<Self::Model> {
        TypedExpr::column_cmp(Self::COLUMN, Op::Ne, rhs.into())
    }

    /// `column < <expr>` — the canonical column-vs-column compare
    /// (e.g. `start_date.lt_expr(F("end_date"))`).
    fn lt_expr(self, rhs: impl Into<crate::core::Expr>) -> TypedExpr<Self::Model> {
        TypedExpr::column_cmp(Self::COLUMN, Op::Lt, rhs.into())
    }

    /// `column <= <expr>`.
    fn lte_expr(self, rhs: impl Into<crate::core::Expr>) -> TypedExpr<Self::Model> {
        TypedExpr::column_cmp(Self::COLUMN, Op::Lte, rhs.into())
    }

    /// `column > <expr>`.
    fn gt_expr(self, rhs: impl Into<crate::core::Expr>) -> TypedExpr<Self::Model> {
        TypedExpr::column_cmp(Self::COLUMN, Op::Gt, rhs.into())
    }

    /// `column >= <expr>`.
    fn gte_expr(self, rhs: impl Into<crate::core::Expr>) -> TypedExpr<Self::Model> {
        TypedExpr::column_cmp(Self::COLUMN, Op::Gte, rhs.into())
    }
}

/// A `Filter` tagged with the model it applies to.
///
/// Constructed by [`Column`] methods. `QuerySet<M>::where_` accepts only
/// `TypedFilter<M>`, so you can't accidentally apply a filter from one
/// model to a queryset for another.
pub struct TypedFilter<M: Model> {
    pub(crate) inner: Filter,
    _model: PhantomData<fn() -> M>,
}

impl<M: Model> TypedFilter<M> {
    fn scalar(column: &'static str, op: Op, value: SqlValue) -> Self {
        Self {
            inner: Filter { column, op, value },
            _model: PhantomData,
        }
    }

    /// Unwrap to the dialect-neutral filter form.
    #[must_use]
    pub fn into_filter(self) -> Filter {
        self.inner
    }

    /// Compose with another predicate or expression via SQL `AND`.
    /// Returns a [`TypedExpr`] so further `.and()` / `.or()` calls
    /// can chain on the result.
    #[must_use]
    pub fn and<E: Into<TypedExpr<M>>>(self, rhs: E) -> TypedExpr<M> {
        TypedExpr::from(self).and(rhs)
    }

    /// Compose with another predicate or expression via SQL `OR`.
    /// Returns a [`TypedExpr`] so further `.and()` / `.or()` calls
    /// can chain on the result.
    #[must_use]
    pub fn or<E: Into<TypedExpr<M>>>(self, rhs: E) -> TypedExpr<M> {
        TypedExpr::from(self).or(rhs)
    }

    /// Compose with another predicate or expression via SQL `XOR` —
    /// Django 4.1+ `Q(a) ^ Q(b)` (issue #27). Returns a [`TypedExpr`]
    /// so further `.and()` / `.or()` / `.xor()` calls can chain.
    #[must_use]
    pub fn xor<E: Into<TypedExpr<M>>>(self, rhs: E) -> TypedExpr<M> {
        TypedExpr::from(self).xor(rhs)
    }

    /// Negate this predicate — emits `NOT (col op val)`.
    #[must_use]
    pub fn not(self) -> TypedExpr<M> {
        TypedExpr::from(self).not()
    }
}

impl<M: Model> From<TypedFilter<M>> for TypedExpr<M> {
    fn from(tf: TypedFilter<M>) -> Self {
        Self {
            inner: WhereExpr::Predicate(tf.inner),
            _model: PhantomData,
        }
    }
}

// --- Untyped lowering for `case().when(...)` and similar untyped
//     consumers (issue #4). Drops the model tag — callers are
//     responsible for using the right model's columns; schema
//     validation happens at `compile()` time on the queryset.

impl<M: Model> From<TypedFilter<M>> for WhereExpr {
    fn from(tf: TypedFilter<M>) -> Self {
        Self::Predicate(tf.inner)
    }
}

impl<M: Model> From<TypedExpr<M>> for WhereExpr {
    fn from(te: TypedExpr<M>) -> Self {
        te.inner
    }
}

/// Typed boolean expression — a [`TypedFilter`] tree composed with
/// `.and()` / `.or()`. Constructed implicitly from any `TypedFilter`
/// via `Into`, so callers usually never name this type:
///
/// ```ignore
/// User::objects()
///     .where_(User::name.eq("alice").or(User::name.eq("bob")))
///     .where_(User::active.eq(true))
///     .fetch(&pool).await?;
/// // → WHERE ("name" = $1 OR "name" = $2) AND "active" = $3
/// ```
///
/// Each `.where_(…)` call AND-joins its expression into the
/// queryset's accumulated WHERE clause; OR is contained inside the
/// expression you pass to a single `.where_()` call.
pub struct TypedExpr<M: Model> {
    pub(crate) inner: WhereExpr,
    _model: PhantomData<fn() -> M>,
}

impl<M: Model> TypedExpr<M> {
    /// Build a [`WhereExpr::ColumnCompare`] leaf — the `F()`-style
    /// "column <op> expr" predicate. Used by [`Column::eq_expr`] &
    /// friends; not normally constructed directly by user code.
    #[must_use]
    pub(crate) fn column_cmp(column: &'static str, op: Op, rhs: crate::core::Expr) -> Self {
        Self {
            inner: WhereExpr::ColumnCompare(super::query::ColumnFilter { column, op, rhs }),
            _model: PhantomData,
        }
    }

    /// Unwrap to the dialect-neutral expression form.
    #[must_use]
    pub fn into_expr(self) -> WhereExpr {
        self.inner
    }

    /// Compose with `AND`. Adjacent `And` nodes are flattened so the
    /// resulting tree stays shallow:
    /// `a.and(b).and(c)` → `And(vec![a, b, c])`, not `And(And(a, b), c)`.
    #[must_use]
    pub fn and<E: Into<Self>>(self, rhs: E) -> Self {
        let rhs = rhs.into();
        let inner = match (self.inner, rhs.inner) {
            (WhereExpr::And(mut a), WhereExpr::And(b)) => {
                a.extend(b);
                WhereExpr::And(a)
            }
            (WhereExpr::And(mut a), b) => {
                a.push(b);
                WhereExpr::And(a)
            }
            (a, WhereExpr::And(mut b)) => {
                b.insert(0, a);
                WhereExpr::And(b)
            }
            (a, b) => WhereExpr::And(vec![a, b]),
        };
        Self {
            inner,
            _model: PhantomData,
        }
    }

    /// Compose with `OR`. Adjacent `Or` nodes are flattened so the
    /// resulting tree stays shallow.
    #[must_use]
    pub fn or<E: Into<Self>>(self, rhs: E) -> Self {
        let rhs = rhs.into();
        let inner = match (self.inner, rhs.inner) {
            (WhereExpr::Or(mut a), WhereExpr::Or(b)) => {
                a.extend(b);
                WhereExpr::Or(a)
            }
            (WhereExpr::Or(mut a), b) => {
                a.push(b);
                WhereExpr::Or(a)
            }
            (a, WhereExpr::Or(mut b)) => {
                b.insert(0, a);
                WhereExpr::Or(b)
            }
            (a, b) => WhereExpr::Or(vec![a, b]),
        };
        Self {
            inner,
            _model: PhantomData,
        }
    }

    /// Compose with `XOR` — Django 4.1+ `Q(a) ^ Q(b)` (issue #27).
    /// Matches rows for which an odd number of operands evaluate to
    /// `true`. Adjacent `Xor` nodes flatten the same way `.and()` /
    /// `.or()` do, so chains like `a.xor(b).xor(c)` stay shallow and
    /// emit Django's N-ary semantic (odd parity) rather than the
    /// nested `(a^b)^c` form.
    #[must_use]
    pub fn xor<E: Into<Self>>(self, rhs: E) -> Self {
        let rhs = rhs.into();
        let inner = match (self.inner, rhs.inner) {
            (WhereExpr::Xor(mut a), WhereExpr::Xor(b)) => {
                a.extend(b);
                WhereExpr::Xor(a)
            }
            (WhereExpr::Xor(mut a), b) => {
                a.push(b);
                WhereExpr::Xor(a)
            }
            (a, WhereExpr::Xor(mut b)) => {
                b.insert(0, a);
                WhereExpr::Xor(b)
            }
            (a, b) => WhereExpr::Xor(vec![a, b]),
        };
        Self {
            inner,
            _model: PhantomData,
        }
    }

    /// Negate this expression — emits `NOT (…)`.
    #[must_use]
    pub fn not(self) -> Self {
        Self {
            inner: WhereExpr::Not(Box::new(self.inner)),
            _model: PhantomData,
        }
    }
}

/// An `Assignment` tagged with the model it applies to.
pub struct TypedAssignment<M: Model> {
    pub(crate) inner: Assignment,
    _model: PhantomData<fn() -> M>,
}

impl<M: Model> TypedAssignment<M> {
    /// Unwrap to the dialect-neutral assignment form.
    #[must_use]
    pub fn into_assignment(self) -> Assignment {
        self.inner
    }
}

/// Heterogeneous list of typed [`Column`] references for the same model.
/// Issue #67 — drives `Model::save_partial_typed(...)`.
///
/// Each `#[derive(Model)]` field is its own zero-sized type, so
/// `&[Post::title, Post::slug]` doesn't type-check (mixed element types).
/// A tuple does — every element keeps its own concrete type, and the
/// trait bound `Column<Model = M>` on each slot enforces same-model
/// at compile time:
///
/// ```ignore
/// post.save_partial_typed((Post::title, Post::slug), &pool).await?;
/// //                       ──────────  ──────────
/// //                       title_col   slug_col   ← distinct ZSTs
/// //
/// // (Post::title, Author::name)  →  compile error: Author::name's
/// //                                  Model = Author, not Post.
/// ```
///
/// The trait is sealed — only the built-in tuple impls implement it,
/// so user code can't accidentally collide with future variants.
pub trait TypedFieldList<M: Model>: sealed::Sealed {
    /// Rust-side field names in the order the tuple was declared.
    /// Forwarded directly to [`crate::core::ModelSchema::field`] for
    /// SQL-column resolution, matching the string-keyed
    /// [`Model::save_partial`] path.
    ///
    /// [`Model::save_partial`]: crate::core::Model
    fn rust_field_names(&self) -> Vec<&'static str>;
}

mod sealed {
    pub trait Sealed {}
}

/// Single-element tuple — supports the `(Post::title,)` one-field call.
impl<M: Model, A: Column<Model = M>> TypedFieldList<M> for (A,) {
    fn rust_field_names(&self) -> Vec<&'static str> {
        vec![A::NAME]
    }
}
impl<A> sealed::Sealed for (A,) {}

// Tuple impls up to 12 elements — covers every realistic update_fields
// shape (Django's analogue is unbounded, but if you're writing more
// than 12 distinct fields, dropping to `save_partial(&[&str], _)` is
// cheap and probably clearer at the call site).
macro_rules! impl_typed_field_list_tuple {
    ( $( ( $($T:ident),+ ) ),+ $(,)? ) => {
        $(
            impl<M: Model, $($T: Column<Model = M>),+> TypedFieldList<M> for ($($T,)+) {
                fn rust_field_names(&self) -> Vec<&'static str> {
                    vec![$($T::NAME),+]
                }
            }
            impl<$($T),+> sealed::Sealed for ($($T,)+) {}
        )+
    };
}

impl_typed_field_list_tuple!(
    (A, B),
    (A, B, C),
    (A, B, C, D),
    (A, B, C, D, E),
    (A, B, C, D, E, F),
    (A, B, C, D, E, F, G),
    (A, B, C, D, E, F, G, H),
    (A, B, C, D, E, F, G, H, I),
    (A, B, C, D, E, F, G, H, I, J),
    (A, B, C, D, E, F, G, H, I, J, K),
    (A, B, C, D, E, F, G, H, I, J, K, L),
);