Skip to main content

navree_orm/
column.rs

1//! Typed columns ([`Column`]), conditions ([`Filter`]) and assignments
2//! ([`Assignment`]).
3
4use std::borrow::Cow;
5use std::fmt;
6use std::marker::PhantomData;
7
8use crate::ir::{Boolean, ColumnRef, Expr, InValues, Operator, Order, QueryIr, Where, WhereClause};
9use crate::row::Row;
10use crate::value::{Field, FieldError, Value, ValueFor, is_null};
11
12/// Encodes a field value as a column value (with the field's cast, if any).
13pub type Encoder<T> = fn(&T) -> Result<Value, String>;
14
15/// Reads a column value as a field (with the field's cast, if any).
16pub type Decoder<T> = fn(&Row, &str) -> Result<T, FieldError>;
17
18/// The model type of columns that belong to no model: [`col`] and column
19/// names given as strings.
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
21pub struct Untyped;
22
23/// A column of model `M` holding values of type `T`.
24///
25/// `#[derive(Model)]` generates one constant per column, typed like its
26/// field (`Deal::AMOUNT_CENTS: Column<Deal, i64>`, `Deal::CLOSED_AT:
27/// Column<Deal, Option<DateTime<Utc>>>`). Conditions built from a column
28/// take values of its type (a nullable column takes plain values too:
29/// `Deal::CLOSED_AT.gt(now)`) and encode them exactly as the field is
30/// stored (casts included), so `Deal::STAGE.eq(Stage::Won)` compares with
31/// `'won'` when the stage is stored as its name.
32///
33/// Typed columns are qualified by their table in SQL, so they stay
34/// unambiguous in joins and subqueries. [`col`] builds an untyped column
35/// from a name (`"title"`, `"deals.title"`, a JSON path `"meta->status"`).
36///
37/// ```
38/// use navree_orm::{Column, Dialect, Filter, Untyped, Value, col};
39///
40/// struct Deal;
41/// const AMOUNT: Column<Deal, i64> = Column::field("deals", "amount_cents");
42///
43/// let filter: Filter = AMOUNT.gte(10_000).and(col("stage").eq("won"));
44/// let sql = filter.to_sql(Dialect::Postgres).unwrap();
45/// assert_eq!(sql.sql, r#""deals"."amount_cents" >= $1 AND "stage" = $2"#);
46/// assert_eq!(sql.values, [Value::I64(10_000), Value::from("won")]);
47/// ```
48pub struct Column<M, T> {
49    table: Option<Cow<'static, str>>,
50    name: Cow<'static, str>,
51    encode: Encoder<T>,
52    decode: Decoder<T>,
53    _model: PhantomData<fn() -> M>,
54}
55
56impl<M, T> Clone for Column<M, T> {
57    fn clone(&self) -> Self {
58        Column {
59            table: self.table.clone(),
60            name: self.name.clone(),
61            encode: self.encode,
62            decode: self.decode,
63            _model: PhantomData,
64        }
65    }
66}
67
68impl<M, T> fmt::Debug for Column<M, T> {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_tuple("Column")
71            .field(&self.column_ref().to_string())
72            .finish()
73    }
74}
75
76fn encode_field<T: Field>(value: &T) -> Result<Value, String> {
77    Ok(value.to_value())
78}
79
80fn decode_field<T: Field>(row: &Row, column: &str) -> Result<T, FieldError> {
81    row.field(column)
82}
83
84impl<M, T: Field> Column<M, T> {
85    /// The column `name` of `table`, holding a [`Field`] type without a
86    /// cast. (`#[derive(Model)]` writes these.)
87    pub const fn field(table: &'static str, name: &'static str) -> Self {
88        Column {
89            table: Some(Cow::Borrowed(table)),
90            name: Cow::Borrowed(name),
91            encode: encode_field::<T>,
92            decode: decode_field::<T>,
93            _model: PhantomData,
94        }
95    }
96}
97
98impl<M, T> Column<M, T> {
99    /// The column `name` of `table` with its own encoder and decoder (a
100    /// cast's). (`#[derive(Model)]` writes these.)
101    pub const fn with_codec(
102        table: &'static str,
103        name: &'static str,
104        encode: Encoder<T>,
105        decode: Decoder<T>,
106    ) -> Self {
107        Column {
108            table: Some(Cow::Borrowed(table)),
109            name: Cow::Borrowed(name),
110            encode,
111            decode,
112            _model: PhantomData,
113        }
114    }
115
116    /// The column's name.
117    pub fn name(&self) -> &str {
118        &self.name
119    }
120
121    /// The table qualifying the column, if any.
122    pub fn table(&self) -> Option<&str> {
123        self.table.as_deref()
124    }
125
126    /// The column as an IR reference.
127    pub fn column_ref(&self) -> ColumnRef {
128        let mut column = ColumnRef::parse(self.name.clone());
129        if column.table.is_none() {
130            column.table = self.table.clone();
131        }
132        column
133    }
134
135    /// The column as an expression.
136    pub fn expr(&self) -> Expr {
137        Expr::Column(self.column_ref())
138    }
139
140    /// The same column without its table (where an unqualified name is
141    /// needed, e.g. an alias over a subquery).
142    pub fn unqualified(&self) -> Self {
143        Column {
144            table: None,
145            ..self.clone()
146        }
147    }
148
149    /// Encodes `value` as this column stores it.
150    pub fn encode(&self, value: &T) -> Result<Value, String> {
151        (self.encode)(value)
152    }
153
154    /// Reads this column from `row`.
155    pub fn decode(&self, row: &Row) -> Result<T, FieldError> {
156        (self.decode)(row, ColumnRef::parse(self.name.clone()).name.as_ref())
157    }
158
159    /// Reads result column `column` of `row` as this column's type (for a
160    /// value selected under another name).
161    pub fn decode_as(&self, row: &Row, column: &str) -> Result<T, FieldError> {
162        (self.decode)(row, column)
163    }
164
165    /// A path into this JSON column: `Deal::META.json("status")` is
166    /// `deals.meta->status`.
167    pub fn json(&self, path: &str) -> Column<Untyped, Value> {
168        Column {
169            table: self.table.clone(),
170            name: Cow::Owned(format!("{}->{path}", self.name)),
171            encode: encode_field::<Value>,
172            decode: decode_field::<Value>,
173            _model: PhantomData,
174        }
175    }
176
177    fn value_operand(&self, value: &T) -> Result<Expr, String> {
178        (self.encode)(value)
179            .map(Expr::Value)
180            .map_err(|error| format!("cannot use a value for column `{}`: {error}", self.name))
181    }
182
183    fn compare(&self, op: Operator, value: T) -> Filter {
184        match self.value_operand(&value) {
185            Ok(right) => Filter::compare(self.expr(), op, right),
186            Err(error) => Filter(Where::Invalid(error)),
187        }
188    }
189
190    /// `column = value` (`IS NULL` for a NULL value).
191    pub fn eq(&self, value: impl ValueFor<T>) -> Filter {
192        self.compare(Operator::Eq, value.into_value_for())
193    }
194
195    /// `column <> value` (`IS NOT NULL` for a NULL value).
196    pub fn ne(&self, value: impl ValueFor<T>) -> Filter {
197        self.compare(Operator::Ne, value.into_value_for())
198    }
199
200    /// `column > value`.
201    pub fn gt(&self, value: impl ValueFor<T>) -> Filter {
202        self.compare(Operator::Gt, value.into_value_for())
203    }
204
205    /// `column >= value`.
206    pub fn gte(&self, value: impl ValueFor<T>) -> Filter {
207        self.compare(Operator::Gte, value.into_value_for())
208    }
209
210    /// `column < value`.
211    pub fn lt(&self, value: impl ValueFor<T>) -> Filter {
212        self.compare(Operator::Lt, value.into_value_for())
213    }
214
215    /// `column <= value`.
216    pub fn lte(&self, value: impl ValueFor<T>) -> Filter {
217        self.compare(Operator::Lte, value.into_value_for())
218    }
219
220    /// `column <op> value` for any [`Operator`] (`">="`, `"<>"`, `"like"`,
221    /// PostgreSQL's `"@>"`, ...).
222    pub fn op(&self, op: impl Into<Operator>, value: impl ValueFor<T>) -> Filter {
223        self.compare(op.into(), value.into_value_for())
224    }
225
226    /// Null-safe equality: true when both sides are NULL.
227    pub fn null_safe_eq(&self, value: impl ValueFor<T>) -> Filter {
228        match self.value_operand(&value.into_value_for()) {
229            Ok(right) => Filter(Where::Compare {
230                left: self.expr(),
231                op: Operator::NullSafeEq,
232                right,
233            }),
234            Err(error) => Filter(Where::Invalid(error)),
235        }
236    }
237
238    fn list(&self, values: impl IntoIterator<Item = impl ValueFor<T>>, not: bool) -> Filter {
239        let encoded: Result<Vec<Expr>, String> = values
240            .into_iter()
241            .map(|value| self.value_operand(&value.into_value_for()))
242            .collect();
243        match encoded {
244            Ok(values) => Filter(Where::In {
245                expr: self.expr(),
246                values: InValues::List(values),
247                not,
248            }),
249            Err(error) => Filter(Where::Invalid(error)),
250        }
251    }
252
253    /// `column IN (values)`; an empty list matches no row.
254    pub fn is_in(&self, values: impl IntoIterator<Item = impl ValueFor<T>>) -> Filter {
255        self.list(values, false)
256    }
257
258    /// `column NOT IN (values)`; an empty list matches every row.
259    pub fn not_in(&self, values: impl IntoIterator<Item = impl ValueFor<T>>) -> Filter {
260        self.list(values, true)
261    }
262
263    /// `column IN (subquery)`.
264    pub fn in_subquery(&self, query: impl IntoQuery) -> Filter {
265        Filter(Where::In {
266            expr: self.expr(),
267            values: InValues::Subquery(Box::new(query.into_query())),
268            not: false,
269        })
270    }
271
272    /// `column NOT IN (subquery)`.
273    pub fn not_in_subquery(&self, query: impl IntoQuery) -> Filter {
274        Filter(Where::In {
275            expr: self.expr(),
276            values: InValues::Subquery(Box::new(query.into_query())),
277            not: true,
278        })
279    }
280
281    /// `column IS NULL`.
282    pub fn is_null(&self) -> Filter {
283        Filter(Where::Null {
284            expr: self.expr(),
285            not: false,
286        })
287    }
288
289    /// `column IS NOT NULL`.
290    pub fn is_not_null(&self) -> Filter {
291        Filter(Where::Null {
292            expr: self.expr(),
293            not: true,
294        })
295    }
296
297    fn range(&self, low: T, high: T, not: bool) -> Filter {
298        match (self.value_operand(&low), self.value_operand(&high)) {
299            (Ok(low), Ok(high)) => Filter(Where::Between {
300                expr: self.expr(),
301                low,
302                high,
303                not,
304            }),
305            (Err(error), _) | (_, Err(error)) => Filter(Where::Invalid(error)),
306        }
307    }
308
309    /// `column BETWEEN low AND high` (both ends included).
310    pub fn between(&self, low: impl ValueFor<T>, high: impl ValueFor<T>) -> Filter {
311        self.range(low.into_value_for(), high.into_value_for(), false)
312    }
313
314    /// `column NOT BETWEEN low AND high`.
315    pub fn not_between(&self, low: impl ValueFor<T>, high: impl ValueFor<T>) -> Filter {
316        self.range(low.into_value_for(), high.into_value_for(), true)
317    }
318
319    /// `column = other` (another column).
320    pub fn eq_column<N, U>(&self, other: &Column<N, U>) -> Filter {
321        Filter::compare(self.expr(), Operator::Eq, other.expr())
322    }
323
324    /// `column <op> other` (another column).
325    pub fn op_column<N, U>(&self, op: impl Into<Operator>, other: &Column<N, U>) -> Filter {
326        Filter::compare(self.expr(), op.into(), other.expr())
327    }
328
329    /// The column in ascending order.
330    pub fn asc(&self) -> Order {
331        Order::asc(self.expr())
332    }
333
334    /// The column in descending order.
335    pub fn desc(&self) -> Order {
336        Order::desc(self.expr())
337    }
338
339    /// `SET column = value` (mass updates, `first_or_create` attributes).
340    pub fn set(&self, value: impl ValueFor<T>) -> Assignment {
341        match (self.encode)(&value.into_value_for()) {
342            Ok(value) => Assignment::value(self.name.clone(), value),
343            Err(error) => Assignment::invalid(
344                self.name.clone(),
345                format!("cannot use a value for column `{}`: {error}", self.name),
346            ),
347        }
348    }
349
350    /// `SET column = expr` (mass updates only).
351    pub fn set_expr(&self, expr: impl Into<Expr>) -> Assignment {
352        Assignment {
353            column: self.name.clone(),
354            value: AssignedValue::Expr(expr.into()),
355        }
356    }
357
358    /// `SET column = NULL`.
359    pub fn set_null(&self) -> Assignment
360    where
361        T: Field,
362    {
363        Assignment::value(self.name.clone(), T::null())
364    }
365
366    /// `count(column)`.
367    pub fn count(&self) -> Expr {
368        Expr::count(self.expr())
369    }
370
371    /// `sum(column)`.
372    pub fn sum(&self) -> Expr {
373        Expr::sum(self.expr())
374    }
375
376    /// `avg(column)`.
377    pub fn avg(&self) -> Expr {
378        Expr::avg(self.expr())
379    }
380
381    /// `min(column)`.
382    pub fn min(&self) -> Expr {
383        Expr::min(self.expr())
384    }
385
386    /// `max(column)`.
387    pub fn max(&self) -> Expr {
388        Expr::max(self.expr())
389    }
390}
391
392impl<M> Column<M, String> {
393    /// `column LIKE pattern`, ignoring case on every database (`%` and `_`
394    /// are wildcards).
395    pub fn like(&self, pattern: impl Into<String>) -> Filter {
396        Filter::like(self.expr(), pattern.into(), false, false)
397    }
398
399    /// `column NOT LIKE pattern`, ignoring case on every database.
400    pub fn not_like(&self, pattern: impl Into<String>) -> Filter {
401        Filter::like(self.expr(), pattern.into(), false, true)
402    }
403
404    /// `column LIKE pattern`, matching case on every database.
405    pub fn like_case_sensitive(&self, pattern: impl Into<String>) -> Filter {
406        Filter::like(self.expr(), pattern.into(), true, false)
407    }
408}
409
410impl<M> Column<M, Option<String>> {
411    /// `column LIKE pattern`, ignoring case on every database (NULLs never
412    /// match).
413    pub fn like(&self, pattern: impl Into<String>) -> Filter {
414        Filter::like(self.expr(), pattern.into(), false, false)
415    }
416
417    /// `column NOT LIKE pattern`, ignoring case on every database.
418    pub fn not_like(&self, pattern: impl Into<String>) -> Filter {
419        Filter::like(self.expr(), pattern.into(), false, true)
420    }
421
422    /// `column LIKE pattern`, matching case on every database.
423    pub fn like_case_sensitive(&self, pattern: impl Into<String>) -> Filter {
424        Filter::like(self.expr(), pattern.into(), true, false)
425    }
426}
427
428impl<M> Column<M, Value> {
429    /// `column LIKE pattern`, ignoring case on every database.
430    pub fn like(&self, pattern: impl Into<String>) -> Filter {
431        Filter::like(self.expr(), pattern.into(), false, false)
432    }
433
434    /// `column NOT LIKE pattern`, ignoring case on every database.
435    pub fn not_like(&self, pattern: impl Into<String>) -> Filter {
436        Filter::like(self.expr(), pattern.into(), false, true)
437    }
438
439    /// `column LIKE pattern`, matching case on every database.
440    pub fn like_case_sensitive(&self, pattern: impl Into<String>) -> Filter {
441        Filter::like(self.expr(), pattern.into(), true, false)
442    }
443}
444
445/// An untyped column: `"title"`, `"deals.title"`, or a JSON path
446/// `"meta->status"`. Its conditions take any value.
447///
448/// ```
449/// use navree_orm::{Dialect, col};
450///
451/// let sql = col("meta->status").eq("open").to_sql(Dialect::Sqlite).unwrap();
452/// assert_eq!(sql.sql, r#"json_extract("meta", '$."status"') = ?"#);
453/// ```
454pub fn col(name: impl Into<Cow<'static, str>>) -> Column<Untyped, Value> {
455    let column = ColumnRef::parse(name);
456    let name = match column.path.is_empty() {
457        true => column.name.clone(),
458        false => Cow::Owned(column.without_path().name.to_string() + &json_suffix(&column)),
459    };
460    Column {
461        table: column.table,
462        name,
463        encode: encode_field::<Value>,
464        decode: decode_field::<Value>,
465        _model: PhantomData,
466    }
467}
468
469/// An untyped column whose values are read as `T`: for plucks and single
470/// values of tables without a model.
471///
472/// ```no_run
473/// # use navree_orm::__doc_models::*;
474/// # async fn demo(db: Db) -> Result<()> {
475/// let titles: Vec<String> = table("deals").pluck(&db, col_as::<String>("title")).await?;
476/// # Ok(()) }
477/// ```
478pub fn col_as<T: Field>(name: impl Into<Cow<'static, str>>) -> Column<Untyped, T> {
479    let untyped = col(name);
480    Column {
481        table: untyped.table,
482        name: untyped.name,
483        encode: encode_field::<T>,
484        decode: decode_field::<T>,
485        _model: PhantomData,
486    }
487}
488
489fn json_suffix(column: &ColumnRef) -> String {
490    let text = column.to_string();
491    match text.find("->") {
492        Some(at) => text[at..].to_owned(),
493        None => String::new(),
494    }
495}
496
497/// A condition for `where_`, `having` and join clauses.
498///
499/// Built from columns (`Deal::STAGE.eq(Stage::Won)`, `col("x").gt(5)`),
500/// expressions (`Expr::count_all().gt(3)`), raw SQL ([`Filter::raw`]), or a
501/// [render-tree](crate::render::ast) condition, and combined with
502/// [`and`](Filter::and), [`or`](Filter::or) and [`not`](Filter::not).
503#[derive(Clone, Debug)]
504pub struct Filter(pub(crate) Where);
505
506impl Filter {
507    /// `left op right`, turning a comparison with NULL into `IS [NOT] NULL`.
508    pub(crate) fn compare(left: Expr, op: Operator, right: Expr) -> Filter {
509        if let Expr::Value(value) = &right
510            && is_null(value)
511        {
512            return match op {
513                Operator::Eq => Filter(Where::Null {
514                    expr: left,
515                    not: false,
516                }),
517                Operator::Ne => Filter(Where::Null {
518                    expr: left,
519                    not: true,
520                }),
521                Operator::NullSafeEq => Filter(Where::Compare { left, op, right }),
522                other => Filter(Where::Invalid(format!(
523                    "a NULL value cannot be compared with `{other:?}`; use is_null() or is_not_null()"
524                ))),
525            };
526        }
527        Filter(Where::Compare { left, op, right })
528    }
529
530    pub(crate) fn like(expr: Expr, pattern: String, case_sensitive: bool, not: bool) -> Filter {
531        Filter(Where::Like {
532            expr,
533            pattern: Expr::Value(Value::from(pattern)),
534            case_sensitive,
535            not,
536        })
537    }
538
539    /// Raw SQL with `?` placeholders for `values` (`??` for a literal `?`).
540    /// SQL databases only. Beside other conditions (and under `NOT`) the
541    /// fragment is parenthesized, so an `OR` inside it stays its own.
542    ///
543    /// ```
544    /// use navree_orm::{Dialect, Filter};
545    ///
546    /// let sql = Filter::raw("lower(title) = ?", ["renewal"]).to_sql(Dialect::Postgres).unwrap();
547    /// assert_eq!(sql.sql, "lower(title) = $1");
548    ///
549    /// let either = Filter::raw("stage = ? OR stage = ?", ["won", "lost"]).not();
550    /// assert_eq!(either.to_sql(Dialect::Postgres).unwrap().sql, "NOT (stage = $1 OR stage = $2)");
551    /// ```
552    pub fn raw(
553        sql: impl Into<Cow<'static, str>>,
554        values: impl IntoIterator<Item = impl Into<Value>>,
555    ) -> Filter {
556        Filter(Where::Raw {
557            sql: sql.into(),
558            values: values.into_iter().map(Into::into).collect(),
559        })
560    }
561
562    /// `EXISTS (query)`.
563    pub fn exists(query: impl IntoQuery) -> Filter {
564        Filter(Where::Exists {
565            query: Box::new(query.into_query()),
566            not: false,
567        })
568    }
569
570    /// `NOT EXISTS (query)`.
571    pub fn not_exists(query: impl IntoQuery) -> Filter {
572        Filter(Where::Exists {
573            query: Box::new(query.into_query()),
574            not: true,
575        })
576    }
577
578    /// Both conditions.
579    pub fn and(self, other: impl Into<Filter>) -> Filter {
580        Filter(Where::Group(vec![
581            WhereClause::and(self.0),
582            WhereClause::and(other.into().0),
583        ]))
584    }
585
586    /// Either condition.
587    pub fn or(self, other: impl Into<Filter>) -> Filter {
588        Filter(Where::Group(vec![
589            WhereClause::and(self.0),
590            WhereClause::or(other.into().0),
591        ]))
592    }
593
594    /// The opposite condition: `NOT (...)`.
595    #[allow(clippy::should_implement_trait)]
596    pub fn not(self) -> Filter {
597        Filter(Where::Group(vec![WhereClause {
598            boolean: Boolean::And,
599            negated: true,
600            filter: self.0,
601        }]))
602    }
603
604    /// Every condition (`TRUE` when there are none).
605    pub fn all(filters: impl IntoIterator<Item = impl Into<Filter>>) -> Filter {
606        Filter(Where::Group(
607            filters
608                .into_iter()
609                .map(|filter| WhereClause::and(filter.into().0))
610                .collect(),
611        ))
612    }
613
614    /// Any of the conditions (`FALSE` when there are none).
615    pub fn any(filters: impl IntoIterator<Item = impl Into<Filter>>) -> Filter {
616        let clauses: Vec<WhereClause> = filters
617            .into_iter()
618            .map(|filter| WhereClause::or(filter.into().0))
619            .collect();
620        if clauses.is_empty() {
621            return Filter(Where::Raw {
622                sql: Cow::Borrowed("1 = 0"),
623                values: Vec::new(),
624            });
625        }
626        Filter(Where::Group(clauses))
627    }
628
629    /// The condition as an IR node.
630    pub fn into_where(self) -> Where {
631        self.0
632    }
633
634    /// The condition as SQL for `dialect` (for tests and debugging).
635    pub fn to_sql(&self, dialect: crate::Dialect) -> Result<crate::Statement, crate::OrmError> {
636        crate::sql::render_filter(&self.0, dialect)
637    }
638}
639
640impl From<Where> for Filter {
641    fn from(filter: Where) -> Self {
642        Filter(filter)
643    }
644}
645
646/// A render-tree condition, written for each SQL dialect by the renderer.
647///
648/// ```
649/// use navree_orm::render::ast::Expr;
650/// use navree_orm::{Dialect, Filter};
651///
652/// let filter = Filter::from(Expr::col("closed_at").is_null().or(Expr::col("won").eq(Expr::bool(true))));
653/// assert_eq!(filter.to_sql(Dialect::MySql).unwrap().sql, "`closed_at` IS NULL OR `won` = TRUE");
654/// ```
655impl From<crate::render::ast::Expr> for Filter {
656    fn from(condition: crate::render::ast::Expr) -> Self {
657        Filter(Where::Tree(Box::new(condition)))
658    }
659}
660
661/// A portable SQL fragment (navree-db's `Statement::portable`: `?`
662/// placeholders and their values), such as a list filter of navree-access
663/// written by `SqlFilter::to_statement`, embedded as [`Filter::raw`]. A
664/// statement written for one backend's placeholders (`$1`) is refused when
665/// the query runs.
666///
667/// ```
668/// use navree_db::Statement;
669/// use navree_orm::{Dialect, Filter};
670///
671/// let fragment = Statement::portable("stage = ? OR amount > ?", ["won".into(), 100_i64.into()]);
672/// let sql = Filter::from(fragment).not().to_sql(Dialect::Postgres).unwrap();
673/// assert_eq!(sql.sql, "NOT (stage = $1 OR amount > $2)");
674/// ```
675impl From<navree_db::Statement> for Filter {
676    fn from(statement: navree_db::Statement) -> Self {
677        if let Some(backend) = statement.backend() {
678            return Filter(Where::Invalid(format!(
679                "a filter fragment must use portable `?` placeholders; this one was written for {backend}"
680            )));
681        }
682        let (sql, values) = statement.into_parts();
683        Filter(Where::Raw {
684            sql: Cow::Owned(sql),
685            values,
686        })
687    }
688}
689
690/// `SET column = value` in a mass update, or an attribute of
691/// `first_or_create` and friends: [`Column::set`].
692#[derive(Clone, Debug)]
693pub struct Assignment {
694    pub(crate) column: Cow<'static, str>,
695    pub(crate) value: AssignedValue,
696}
697
698/// What an [`Assignment`] sets.
699#[derive(Clone, Debug)]
700pub(crate) enum AssignedValue {
701    Value(Value),
702    Expr(Expr),
703    Invalid(String),
704}
705
706impl Assignment {
707    /// Sets `column` to `value`.
708    pub fn value(column: impl Into<Cow<'static, str>>, value: impl Into<Value>) -> Self {
709        Assignment {
710            column: column.into(),
711            value: AssignedValue::Value(value.into()),
712        }
713    }
714
715    pub(crate) fn invalid(column: Cow<'static, str>, message: String) -> Self {
716        Assignment {
717            column,
718            value: AssignedValue::Invalid(message),
719        }
720    }
721
722    /// The column set.
723    pub fn column(&self) -> &str {
724        &self.column
725    }
726
727    /// The value set, unless it is an expression.
728    pub fn assigned_value(&self) -> Option<&Value> {
729        match &self.value {
730            AssignedValue::Value(value) => Some(value),
731            AssignedValue::Expr(_) | AssignedValue::Invalid(_) => None,
732        }
733    }
734
735    /// The assignment as `SET column = expr`.
736    pub(crate) fn into_set(self) -> Result<(Cow<'static, str>, Expr), String> {
737        match self.value {
738            AssignedValue::Value(value) => Ok((self.column, Expr::Value(value))),
739            AssignedValue::Expr(expr) => Ok((self.column, expr)),
740            AssignedValue::Invalid(error) => Err(error),
741        }
742    }
743
744    /// The assignment as the condition `column = value` (attribute lookups).
745    pub(crate) fn to_filter(&self, table: Option<&'static str>) -> Filter {
746        let mut column = ColumnRef::parse(self.column.clone());
747        if column.table.is_none() {
748            column.table = table.map(Cow::Borrowed);
749        }
750        match &self.value {
751            AssignedValue::Value(value) => Filter::compare(
752                Expr::Column(column),
753                Operator::Eq,
754                Expr::Value(value.clone()),
755            ),
756            AssignedValue::Expr(expr) => {
757                Filter::compare(Expr::Column(column), Operator::Eq, expr.clone())
758            }
759            AssignedValue::Invalid(error) => Filter(Where::Invalid(error.clone())),
760        }
761    }
762}
763
764/// A column given by name or as a typed constant, for methods that only
765/// need its name (`is_dirty_on`, `extra`, ...).
766pub trait ColumnName {
767    /// The column's name (without table or JSON path).
768    fn column_name(&self) -> Cow<'_, str>;
769}
770
771impl<M, T> ColumnName for Column<M, T> {
772    fn column_name(&self) -> Cow<'_, str> {
773        Cow::Owned(ColumnRef::parse(self.name.clone()).name.into_owned())
774    }
775}
776
777impl ColumnName for &str {
778    fn column_name(&self) -> Cow<'_, str> {
779        Cow::Borrowed(self)
780    }
781}
782
783impl ColumnName for String {
784    fn column_name(&self) -> Cow<'_, str> {
785        Cow::Borrowed(self)
786    }
787}
788
789/// A column of values of type `T`, typed ([`Column<M, T>`]) or named by a
790/// string (any value), for the builder methods that take a column and
791/// values: `where_in`, `where_between`, `where_date`, ...
792pub trait ColumnOf<T> {
793    /// The column.
794    fn column_ref(&self) -> ColumnRef;
795
796    /// Encodes a value as the column stores it.
797    fn encode_value(&self, value: &T) -> Result<Value, String>;
798}
799
800impl<M, T> ColumnOf<T> for Column<M, T> {
801    fn column_ref(&self) -> ColumnRef {
802        Column::column_ref(self)
803    }
804
805    fn encode_value(&self, value: &T) -> Result<Value, String> {
806        (self.encode)(value)
807    }
808}
809
810impl ColumnOf<Value> for &str {
811    fn column_ref(&self) -> ColumnRef {
812        ColumnRef::parse(Cow::Owned((*self).to_owned()))
813    }
814
815    fn encode_value(&self, value: &Value) -> Result<Value, String> {
816        Ok(value.clone())
817    }
818}
819
820impl ColumnOf<Value> for String {
821    fn column_ref(&self) -> ColumnRef {
822        ColumnRef::parse(Cow::Owned(self.clone()))
823    }
824
825    fn encode_value(&self, value: &Value) -> Result<Value, String> {
826        Ok(value.clone())
827    }
828}
829
830/// Something that names a column or computes a value in SQL: a typed
831/// [`Column`], a column name (`"title"`, `"deals.title"`,
832/// `"meta->status"`), or an [`Expr`]. Select lists, orders and groups take
833/// these.
834pub trait IntoExpr {
835    /// The expression.
836    fn into_expr(self) -> Expr;
837}
838
839impl<M, T> IntoExpr for Column<M, T> {
840    fn into_expr(self) -> Expr {
841        self.expr()
842    }
843}
844
845impl<M, T> IntoExpr for &Column<M, T> {
846    fn into_expr(self) -> Expr {
847        self.expr()
848    }
849}
850
851impl IntoExpr for &str {
852    fn into_expr(self) -> Expr {
853        column_or_all(Cow::Owned(self.to_owned()))
854    }
855}
856
857impl IntoExpr for String {
858    fn into_expr(self) -> Expr {
859        column_or_all(Cow::Owned(self))
860    }
861}
862
863impl IntoExpr for Expr {
864    fn into_expr(self) -> Expr {
865        self
866    }
867}
868
869impl IntoExpr for ColumnRef {
870    fn into_expr(self) -> Expr {
871        Expr::Column(self)
872    }
873}
874
875/// `*` and `table.*` select every column; anything else names one.
876fn column_or_all(name: Cow<'static, str>) -> Expr {
877    let trimmed = name.trim();
878    if trimmed == "*" {
879        return Expr::All { table: None };
880    }
881    if let Some(table) = trimmed.strip_suffix(".*") {
882        return Expr::All {
883            table: Some(Cow::Owned(table.to_owned())),
884        };
885    }
886    Expr::Column(ColumnRef::parse(name))
887}
888
889/// A query usable as a subquery: model builders, table builders and IR.
890pub trait IntoQuery {
891    /// The query, with any global scopes applied.
892    fn into_query(self) -> QueryIr;
893}
894
895impl IntoQuery for QueryIr {
896    fn into_query(self) -> QueryIr {
897        self
898    }
899}
900
901impl<M, T> From<Column<M, T>> for Expr {
902    fn from(column: Column<M, T>) -> Self {
903        column.expr()
904    }
905}
906
907impl<M, T> From<&Column<M, T>> for Expr {
908    fn from(column: &Column<M, T>) -> Self {
909        column.expr()
910    }
911}
912
913impl<M, T> From<&Column<M, T>> for Order {
914    fn from(column: &Column<M, T>) -> Self {
915        column.asc()
916    }
917}
918
919impl<M, T> From<Column<M, T>> for Order {
920    fn from(column: Column<M, T>) -> Self {
921        column.asc()
922    }
923}
924
925impl From<&str> for Order {
926    fn from(column: &str) -> Self {
927        Order::asc(column.into_expr())
928    }
929}