Skip to main content

che_orm/
query.rs

1use std::collections::HashSet;
2use std::marker::PhantomData;
3
4use crate::{
5    ColumnRef, CompareOp, CreateTableQuery, DatabaseValue, Expr, ModelField, QueryValue, TableRef,
6    TableSchema,
7};
8
9#[derive(Debug, Clone, Copy)]
10pub enum OrderDirection {
11    Asc,
12    Desc,
13}
14
15#[derive(Debug, Clone, Copy)]
16pub struct OrderBy {
17    pub column: ColumnRef,
18    pub direction: OrderDirection,
19}
20
21#[derive(Debug, Clone, Copy)]
22pub struct JoinedField<T> {
23    column: ColumnRef,
24    _marker: PhantomData<T>,
25}
26
27impl<T> JoinedField<T> {
28    pub const fn new(column: ColumnRef) -> Self {
29        Self {
30            column,
31            _marker: PhantomData,
32        }
33    }
34
35    fn comparison<V>(self, op: CompareOp, value: V) -> Expr
36    where
37        V: QueryValue<T>,
38    {
39        Expr::Compare {
40            left: Box::new(Expr::Column(self.column)),
41            op,
42            right: Box::new(Expr::Value(value.into_query_value())),
43        }
44    }
45
46    pub fn eq<V>(self, value: V) -> Expr
47    where
48        V: QueryValue<T>,
49    {
50        self.comparison(CompareOp::Eq, value)
51    }
52
53    pub fn ne<V>(self, value: V) -> Expr
54    where
55        V: QueryValue<T>,
56    {
57        self.comparison(CompareOp::Ne, value)
58    }
59
60    pub fn gt<V>(self, value: V) -> Expr
61    where
62        V: QueryValue<T>,
63    {
64        self.comparison(CompareOp::Gt, value)
65    }
66
67    pub fn gte<V>(self, value: V) -> Expr
68    where
69        V: QueryValue<T>,
70    {
71        self.comparison(CompareOp::Gte, value)
72    }
73
74    pub fn lt<V>(self, value: V) -> Expr
75    where
76        V: QueryValue<T>,
77    {
78        self.comparison(CompareOp::Lt, value)
79    }
80
81    pub fn lte<V>(self, value: V) -> Expr
82    where
83        V: QueryValue<T>,
84    {
85        self.comparison(CompareOp::Lte, value)
86    }
87
88    pub fn is_null(self) -> Expr {
89        Expr::IsNull(Box::new(Expr::Column(self.column)))
90    }
91
92    pub fn is_not_null(self) -> Expr {
93        Expr::IsNotNull(Box::new(Expr::Column(self.column)))
94    }
95
96    pub const fn asc(self) -> OrderBy {
97        OrderBy {
98            column: self.column,
99            direction: OrderDirection::Asc,
100        }
101    }
102
103    pub const fn desc(self) -> OrderBy {
104        OrderBy {
105            column: self.column,
106            direction: OrderDirection::Desc,
107        }
108    }
109}
110
111#[derive(Debug, Clone)]
112pub struct SelectAst {
113    pub table: TableRef,
114    pub columns: Vec<ColumnRef>,
115    pub joins: Vec<JoinAst>,
116    pub filter: Option<Expr>,
117    pub order_by: Vec<OrderBy>,
118    pub limit: Option<u64>,
119    pub offset: Option<u64>,
120}
121
122#[derive(Debug, Clone)]
123pub struct JoinAst {
124    pub table: TableRef,
125    pub alias: &'static str,
126    pub kind: JoinType,
127    pub on: Expr,
128}
129
130#[derive(Debug, Clone, Copy)]
131pub enum JoinType {
132    Inner,
133    Left,
134}
135
136#[derive(Debug, Clone)]
137pub struct InsertValue {
138    pub column: ColumnRef,
139    pub value: DatabaseValue,
140}
141
142#[derive(Debug, Clone)]
143pub struct InsertAst {
144    pub table: TableRef,
145    pub values: Vec<InsertValue>,
146    pub returning: Vec<ColumnRef>,
147}
148
149#[derive(Debug, Clone)]
150pub struct Assignment {
151    pub column: ColumnRef,
152    pub value: DatabaseValue,
153}
154
155#[derive(Debug, Clone)]
156pub struct UpdateAst {
157    pub table: TableRef,
158    pub assignments: Vec<Assignment>,
159    pub filter: Option<Expr>,
160    pub returning: Vec<ColumnRef>,
161    pub allow_all: bool,
162}
163
164#[derive(Debug, Clone)]
165pub struct DeleteAst {
166    pub table: TableRef,
167    pub filter: Option<Expr>,
168    pub allow_all: bool,
169}
170
171#[derive(Debug, Clone)]
172pub enum QueryAst {
173    Select(SelectAst),
174    Insert(InsertAst),
175    Update(UpdateAst),
176    Delete(DeleteAst),
177    CreateTable(crate::CreateTableAst),
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181/// Errors detected while finalizing a query builder.
182pub enum QueryBuildError {
183    EmptyUpdate,
184    PrimaryKeyUpdate,
185    MissingFilter,
186    DuplicateColumn(&'static str),
187    ForeignTableColumn {
188        column: &'static str,
189        table: &'static str,
190        expected_table: &'static str,
191    },
192    InvalidSchema(String),
193}
194
195impl QueryAst {
196    /// Validates a query before it is sent to a database.
197    pub fn validate(&self) -> Result<(), QueryBuildError> {
198        match self {
199            Self::Select(query) => {
200                let mut tables = vec![query.table.name];
201                for join in &query.joins {
202                    tables.extend([join.table.name, join.alias]);
203                }
204                validate_expr_tables(query.filter.as_ref(), &tables)?;
205                for join in &query.joins {
206                    validate_expr_tables(Some(&join.on), &tables)?;
207                }
208                for order in &query.order_by {
209                    validate_expr_tables(Some(&Expr::Column(order.column)), &tables)?;
210                }
211                Ok(())
212            }
213            Self::Insert(query) => {
214                validate_unique_columns(query.values.iter().map(|value| &value.column))?;
215                validate_columns_table(
216                    query.table.name,
217                    query.values.iter().map(|value| &value.column),
218                )
219            }
220            Self::Update(query) => {
221                if query.assignments.is_empty() {
222                    return Err(QueryBuildError::EmptyUpdate);
223                }
224                if query.filter.is_none() && !query.allow_all {
225                    return Err(QueryBuildError::MissingFilter);
226                }
227                validate_unique_columns(
228                    query
229                        .assignments
230                        .iter()
231                        .map(|assignment| &assignment.column),
232                )?;
233                validate_columns_table(
234                    query.table.name,
235                    query
236                        .assignments
237                        .iter()
238                        .map(|assignment| &assignment.column),
239                )?;
240                validate_expr_table(query.filter.as_ref(), query.table.name)
241            }
242            Self::Delete(query) => {
243                if query.filter.is_none() && !query.allow_all {
244                    return Err(QueryBuildError::MissingFilter);
245                }
246                validate_expr_table(query.filter.as_ref(), query.table.name)
247            }
248            Self::CreateTable(query) => query
249                .schema
250                .validate()
251                .map_err(|error| QueryBuildError::InvalidSchema(format!("{error:?}"))),
252        }
253    }
254}
255
256/// Trait implemented by `#[derive(Model)]` for ORM models.
257pub trait Model: Sized {
258    type PrimaryKey: crate::PrimaryKey;
259    /// Stable Rust model name used by migration state. It is deliberately
260    /// independent from `table_name()` so table renames keep model identity.
261    fn model_name() -> &'static str {
262        std::any::type_name::<Self>()
263            .rsplit("::")
264            .next()
265            .unwrap_or("Model")
266    }
267    fn table_name() -> &'static str;
268    fn columns() -> &'static [&'static str];
269    /// Returns the model's typed primary-key field.
270    fn primary_key() -> ModelField<Self, Self::PrimaryKey>;
271    fn primary_key_value(&self) -> Self::PrimaryKey;
272    fn schema() -> TableSchema;
273    fn from_row(row: &crate::Row) -> Result<Self, crate::DecodeError>;
274    fn from_row_at(row: &crate::Row, offset: usize) -> Result<Self, crate::DecodeError> {
275        if offset == 0 {
276            Self::from_row(row)
277        } else {
278            Err(crate::DecodeError::InvalidColumnIndex(offset))
279        }
280    }
281    /// Adapter for direct SQLite driver queries.
282    #[cfg(feature = "sqlite")]
283    fn from_sqlite_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
284        Self::from_row(&crate::Row::from_sqlite(row)?).map_err(|error| {
285            rusqlite::Error::FromSqlConversionFailure(
286                0,
287                rusqlite::types::Type::Null,
288                Box::new(error),
289            )
290        })
291    }
292    fn insert_values(&self) -> Vec<InsertValue>;
293    /// Materialized field values keyed by physical SQL column, independently of
294    /// Serde naming. Unlike insert values, these include generated keys and
295    /// managed timestamps. The derive generates a complete implementation;
296    /// manual models with managed fields should override this method.
297    fn field_values(&self) -> Vec<InsertValue> {
298        let mut values = self.insert_values();
299        let column = Self::primary_key().column();
300        if !values.iter().any(|value| value.column == column) {
301            values.push(InsertValue {
302                column,
303                value: self.primary_key_value().into_query_value(),
304            });
305        }
306        values
307    }
308    fn managed_update_values() -> Vec<Assignment> {
309        Vec::new()
310    }
311    fn query() -> SelectQuery<Self> {
312        SelectQuery::new()
313    }
314    fn insert() -> InsertQuery<Self> {
315        InsertQuery::new()
316    }
317    fn update() -> UpdateQuery<Self> {
318        UpdateQuery::new()
319    }
320    fn delete() -> DeleteQuery<Self> {
321        DeleteQuery::new()
322    }
323    fn create_table() -> CreateTableQuery<Self> {
324        CreateTableQuery::new(Self::schema())
325    }
326}
327
328/// Converts a materialized ORM model into an API representation.
329pub trait ModelSerializer: serde::Serialize + Sized {
330    type Model: Model;
331    type Input;
332
333    fn from_input(input: Self::Input) -> Self;
334
335    fn to_json(input: Self::Input) -> Result<serde_json::Value, serde_json::Error> {
336        serde_json::to_value(Self::from_input(input))
337    }
338
339    fn fields() -> &'static [SerializerField] {
340        &[]
341    }
342}
343
344/// Identifies the actual foreign-key column behind a serializer relation.
345pub trait RelationSource {
346    const SOURCE: &'static str;
347}
348
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350pub struct SerializerField {
351    pub name: &'static str,
352    pub source: &'static str,
353    pub read_only: bool,
354    pub write_only: bool,
355    pub rust_type: &'static str,
356    pub related_model: Option<&'static str>,
357    pub many: bool,
358}
359
360/// A typed forward foreign-key relation from one model to another.
361#[derive(Debug, Clone, Copy)]
362pub struct BelongsTo<From, To, Relation = (), Key = i64> {
363    field: ColumnRef,
364    getter: fn(&From) -> Key,
365    alias: &'static str,
366    related_name: &'static str,
367    _marker: PhantomData<fn() -> (From, To, Relation, Key)>,
368}
369
370impl<From, To, Relation, Key> BelongsTo<From, To, Relation, Key> {
371    pub const fn new(
372        table: &'static str,
373        column: &'static str,
374        getter: fn(&From) -> Key,
375        alias: &'static str,
376        related_name: &'static str,
377    ) -> Self {
378        Self {
379            field: ColumnRef::new(table, column),
380            getter,
381            alias,
382            related_name,
383            _marker: PhantomData,
384        }
385    }
386
387    pub const fn field(&self) -> ColumnRef {
388        self.field
389    }
390
391    pub const fn alias(&self) -> &'static str {
392        self.alias
393    }
394
395    pub const fn related_field<T>(&self, field: ModelField<To, T>) -> JoinedField<T> {
396        JoinedField::new(ColumnRef::new(self.alias, field.column().name))
397    }
398
399    pub fn foreign_key(&self, model: &From) -> Key {
400        (self.getter)(model)
401    }
402
403    pub const fn reverse(&self) -> HasMany<To, From, Relation, Key> {
404        HasMany {
405            field: self.field,
406            getter: self.getter,
407            related_name: self.related_name,
408            _marker: PhantomData,
409        }
410    }
411}
412
413/// A typed reverse foreign-key relation from one model to many related models.
414#[derive(Debug, Clone, Copy)]
415pub struct HasMany<From, To, Relation = (), Key = i64> {
416    field: ColumnRef,
417    getter: fn(&To) -> Key,
418    related_name: &'static str,
419    _marker: PhantomData<fn() -> (From, To, Relation, Key)>,
420}
421
422impl<From, To, Relation, Key> HasMany<From, To, Relation, Key> {
423    pub const fn field(&self) -> ColumnRef {
424        self.field
425    }
426
427    pub fn foreign_key(&self, model: &To) -> Key {
428        (self.getter)(model)
429    }
430
431    pub const fn related_name(&self) -> &'static str {
432        self.related_name
433    }
434}
435
436pub struct SelectQuery<M> {
437    ast: SelectAst,
438    _model: PhantomData<M>,
439}
440
441impl<M: Model> SelectQuery<M> {
442    pub fn new() -> Self {
443        let table = M::table_name();
444        let columns = M::columns()
445            .iter()
446            .map(|column| ColumnRef::new(table, column))
447            .collect();
448        Self {
449            ast: SelectAst {
450                table: TableRef::new(table),
451                columns,
452                joins: Vec::new(),
453                filter: None,
454                order_by: Vec::new(),
455                limit: None,
456                offset: None,
457            },
458            _model: PhantomData,
459        }
460    }
461    pub fn filter(mut self, expr: Expr) -> Self {
462        self.ast.filter = Some(
463            self.ast
464                .filter
465                .map_or(expr.clone(), |previous| previous.and(expr)),
466        );
467        self
468    }
469    pub fn order_by(mut self, order: OrderBy) -> Self {
470        self.ast.order_by.push(order);
471        self
472    }
473    pub fn limit(mut self, limit: u64) -> Self {
474        self.ast.limit = Some(limit);
475        self
476    }
477    pub fn offset(mut self, offset: u64) -> Self {
478        self.ast.offset = Some(offset);
479        self
480    }
481    pub fn into_ast(self) -> Result<QueryAst, QueryBuildError> {
482        let mut tables = vec![self.ast.table.name];
483        for join in &self.ast.joins {
484            tables.push(join.table.name);
485            tables.push(join.alias);
486        }
487        validate_expr_tables(self.ast.filter.as_ref(), &tables)?;
488        for join in &self.ast.joins {
489            validate_expr_tables(Some(&join.on), &tables)?;
490        }
491        Ok(QueryAst::Select(self.ast))
492    }
493
494    pub(crate) fn into_select_ast(self) -> Result<SelectAst, QueryBuildError> {
495        match self.into_ast()? {
496            QueryAst::Select(select) => Ok(select),
497            _ => unreachable!(),
498        }
499    }
500
501    pub fn into_joined_ast<R: Model, Relation, Key>(
502        self,
503        relation: BelongsTo<M, R, Relation, Key>,
504    ) -> Result<QueryAst, QueryBuildError> {
505        self.into_joined_ast_with_kind(relation, JoinType::Inner)
506    }
507
508    pub fn into_optional_joined_ast<R: Model, Relation, Key>(
509        self,
510        relation: BelongsTo<M, R, Relation, Option<Key>>,
511    ) -> Result<QueryAst, QueryBuildError> {
512        self.into_joined_ast_with_kind(relation, JoinType::Left)
513    }
514
515    pub(crate) fn into_joined_ast_with_kind<R: Model, Relation, Key>(
516        mut self,
517        relation: BelongsTo<M, R, Relation, Key>,
518        kind: JoinType,
519    ) -> Result<QueryAst, QueryBuildError> {
520        self.ast.columns.extend(
521            R::columns()
522                .iter()
523                .map(|column| ColumnRef::new(relation.alias(), column)),
524        );
525        self.ast.joins.push(JoinAst {
526            table: TableRef::new(R::table_name()),
527            alias: relation.alias(),
528            kind,
529            on: Expr::Compare {
530                left: Box::new(Expr::Column(relation.field())),
531                op: CompareOp::Eq,
532                right: Box::new(Expr::Column(ColumnRef::new(
533                    relation.alias(),
534                    R::primary_key().column().name,
535                ))),
536            },
537        });
538        self.into_ast()
539    }
540}
541
542pub struct InsertQuery<M> {
543    ast: InsertAst,
544    _model: PhantomData<M>,
545}
546
547impl<M: Model> InsertQuery<M> {
548    pub fn new() -> Self {
549        Self {
550            ast: InsertAst {
551                table: TableRef::new(M::table_name()),
552                values: Vec::new(),
553                returning: Vec::new(),
554            },
555            _model: PhantomData,
556        }
557    }
558    pub fn set<T, V>(mut self, field: ModelField<M, T>, value: V) -> Self
559    where
560        V: QueryValue<T>,
561    {
562        self.ast.values.push(InsertValue {
563            column: field.column(),
564            value: value.into_query_value(),
565        });
566        self
567    }
568    pub fn returning_all(mut self) -> Self {
569        self.ast.returning = M::columns()
570            .iter()
571            .map(|column| ColumnRef::new(M::table_name(), column))
572            .collect();
573        self
574    }
575    pub fn into_ast(mut self) -> Result<QueryAst, QueryBuildError> {
576        let column = M::primary_key().column();
577        if !self.ast.values.iter().any(|value| value.column == column)
578            && let Some(value) = <M::PrimaryKey as crate::PrimaryKey>::generated_value()
579        {
580            self.ast.values.push(InsertValue { column, value });
581        }
582        validate_unique_columns(self.ast.values.iter().map(|value| &value.column))?;
583        Ok(QueryAst::Insert(self.ast))
584    }
585}
586
587pub struct UpdateQuery<M> {
588    ast: UpdateAst,
589    allow_all: bool,
590    _model: PhantomData<M>,
591}
592
593impl<M: Model> UpdateQuery<M> {
594    pub fn new() -> Self {
595        Self {
596            ast: UpdateAst {
597                table: TableRef::new(M::table_name()),
598                assignments: Vec::new(),
599                filter: None,
600                returning: Vec::new(),
601                allow_all: false,
602            },
603            allow_all: false,
604            _model: PhantomData,
605        }
606    }
607    pub fn set<T, V>(mut self, field: ModelField<M, T>, value: V) -> Self
608    where
609        V: QueryValue<T>,
610    {
611        self.ast.assignments.push(Assignment {
612            column: field.column(),
613            value: value.into_query_value(),
614        });
615        self
616    }
617    pub fn filter(mut self, expr: Expr) -> Self {
618        self.ast.filter = Some(
619            self.ast
620                .filter
621                .map_or(expr.clone(), |previous| previous.and(expr)),
622        );
623        self
624    }
625    pub fn returning_all(mut self) -> Self {
626        self.ast.returning = M::columns()
627            .iter()
628            .map(|column| ColumnRef::new(M::table_name(), column))
629            .collect();
630        self
631    }
632    pub fn allow_all(mut self) -> Self {
633        self.allow_all = true;
634        self
635    }
636    pub fn into_ast(mut self) -> Result<QueryAst, QueryBuildError> {
637        for managed in M::managed_update_values() {
638            self.ast
639                .assignments
640                .retain(|assignment| assignment.column.name != managed.column.name);
641            self.ast.assignments.push(managed);
642        }
643        if self.ast.assignments.is_empty() {
644            return Err(QueryBuildError::EmptyUpdate);
645        }
646        if self.ast.filter.is_none() && !self.allow_all {
647            return Err(QueryBuildError::MissingFilter);
648        }
649        let primary_key = M::primary_key().column();
650        if self
651            .ast
652            .assignments
653            .iter()
654            .any(|assignment| assignment.column == primary_key)
655        {
656            return Err(QueryBuildError::PrimaryKeyUpdate);
657        }
658        validate_unique_columns(
659            self.ast
660                .assignments
661                .iter()
662                .map(|assignment| &assignment.column),
663        )?;
664        validate_expr_table(self.ast.filter.as_ref(), self.ast.table.name)?;
665        self.ast.allow_all = self.allow_all;
666        Ok(QueryAst::Update(self.ast))
667    }
668}
669
670pub struct DeleteQuery<M> {
671    ast: DeleteAst,
672    allow_all: bool,
673    _model: PhantomData<M>,
674}
675
676impl<M: Model> DeleteQuery<M> {
677    pub fn new() -> Self {
678        Self {
679            ast: DeleteAst {
680                table: TableRef::new(M::table_name()),
681                filter: None,
682                allow_all: false,
683            },
684            allow_all: false,
685            _model: PhantomData,
686        }
687    }
688    pub fn filter(mut self, expr: Expr) -> Self {
689        self.ast.filter = Some(
690            self.ast
691                .filter
692                .map_or(expr.clone(), |previous| previous.and(expr)),
693        );
694        self
695    }
696    pub fn allow_all(mut self) -> Self {
697        self.allow_all = true;
698        self
699    }
700    pub fn into_ast(mut self) -> Result<QueryAst, QueryBuildError> {
701        if self.ast.filter.is_none() && !self.allow_all {
702            return Err(QueryBuildError::MissingFilter);
703        }
704        validate_expr_table(self.ast.filter.as_ref(), self.ast.table.name)?;
705        self.ast.allow_all = self.allow_all;
706        Ok(QueryAst::Delete(self.ast))
707    }
708}
709
710fn validate_unique_columns<'a>(
711    columns: impl Iterator<Item = &'a ColumnRef>,
712) -> Result<(), QueryBuildError> {
713    let mut names = HashSet::new();
714    for column in columns {
715        if !names.insert(column.name) {
716            return Err(QueryBuildError::DuplicateColumn(column.name));
717        }
718    }
719    Ok(())
720}
721
722fn validate_columns_table<'a>(
723    table: &'static str,
724    columns: impl Iterator<Item = &'a ColumnRef>,
725) -> Result<(), QueryBuildError> {
726    for column in columns {
727        validate_column_table(column, table)?;
728    }
729    Ok(())
730}
731
732fn validate_expr_table(expr: Option<&Expr>, table: &'static str) -> Result<(), QueryBuildError> {
733    let Some(expr) = expr else {
734        return Ok(());
735    };
736    match expr {
737        Expr::Column(column) => validate_column_table(column, table),
738        Expr::Value(_) => Ok(()),
739        Expr::Like { left, pattern } => {
740            validate_expr_table(Some(left), table)?;
741            validate_expr_table(Some(pattern), table)
742        }
743        Expr::Compare { left, right, .. }
744        | Expr::And { left, right }
745        | Expr::Or { left, right } => {
746            validate_expr_table(Some(left), table)?;
747            validate_expr_table(Some(right), table)
748        }
749        Expr::In { left, .. } => validate_expr_table(Some(left), table),
750        Expr::Not(expr) | Expr::IsNull(expr) | Expr::IsNotNull(expr) => {
751            validate_expr_table(Some(expr), table)
752        }
753    }
754}
755
756fn validate_column_table(column: &ColumnRef, table: &'static str) -> Result<(), QueryBuildError> {
757    if column.table == table {
758        Ok(())
759    } else {
760        Err(QueryBuildError::ForeignTableColumn {
761            column: column.name,
762            table: column.table,
763            expected_table: table,
764        })
765    }
766}
767
768fn validate_expr_tables(
769    expr: Option<&Expr>,
770    tables: &[&'static str],
771) -> Result<(), QueryBuildError> {
772    let Some(expr) = expr else {
773        return Ok(());
774    };
775    match expr {
776        Expr::Column(column) => {
777            if tables.contains(&column.table) {
778                Ok(())
779            } else {
780                Err(QueryBuildError::ForeignTableColumn {
781                    column: column.name,
782                    table: column.table,
783                    expected_table: tables[0],
784                })
785            }
786        }
787        Expr::Like { left, pattern } => {
788            validate_expr_tables(Some(left), tables)?;
789            validate_expr_tables(Some(pattern), tables)
790        }
791        Expr::Value(_) => Ok(()),
792        Expr::Compare { left, right, .. }
793        | Expr::And { left, right }
794        | Expr::Or { left, right } => {
795            validate_expr_tables(Some(left), tables)?;
796            validate_expr_tables(Some(right), tables)
797        }
798        Expr::In { left, .. } => validate_expr_tables(Some(left), tables),
799        Expr::Not(expr) | Expr::IsNull(expr) | Expr::IsNotNull(expr) => {
800            validate_expr_tables(Some(expr), tables)
801        }
802    }
803}