switchy_database/
query.rs

1use std::fmt::Debug;
2
3use crate::{Database, DatabaseError, DatabaseValue, Row};
4
5#[derive(Debug, Clone, Copy)]
6pub enum SortDirection {
7    Asc,
8    Desc,
9}
10
11#[derive(Debug)]
12pub struct Sort {
13    pub expression: Box<dyn Expression>,
14    pub direction: SortDirection,
15}
16
17impl Expression for Sort {
18    fn expression_type(&self) -> ExpressionType {
19        ExpressionType::Sort(self)
20    }
21}
22
23#[derive(Debug, Clone)]
24pub struct Join<'a> {
25    pub table_name: &'a str,
26    pub on: &'a str,
27    pub left: bool,
28}
29
30impl Expression for Join<'_> {
31    fn expression_type(&self) -> ExpressionType {
32        ExpressionType::Join(self)
33    }
34}
35
36pub enum ExpressionType<'a> {
37    Eq(&'a Eq),
38    Gt(&'a Gt),
39    In(&'a In<'a>),
40    Lt(&'a Lt),
41    Or(&'a Or),
42    And(&'a And),
43    Gte(&'a Gte),
44    Lte(&'a Lte),
45    Join(&'a Join<'a>),
46    Sort(&'a Sort),
47    NotIn(&'a NotIn<'a>),
48    NotEq(&'a NotEq),
49    InList(&'a InList),
50    Literal(&'a Literal),
51    Coalesce(&'a Coalesce),
52    Identifier(&'a Identifier),
53    SelectQuery(&'a SelectQuery<'a>),
54    DatabaseValue(&'a DatabaseValue),
55}
56
57pub trait Expression: Send + Sync + Debug {
58    fn expression_type(&self) -> ExpressionType;
59
60    fn params(&self) -> Option<Vec<&DatabaseValue>> {
61        self.values().map(|x| {
62            x.into_iter()
63                .filter(|value| {
64                    !value.is_null()
65                        && !matches!(value, DatabaseValue::Now | DatabaseValue::NowAdd(_))
66                })
67                .collect::<Vec<_>>()
68        })
69    }
70
71    fn values(&self) -> Option<Vec<&DatabaseValue>> {
72        None
73    }
74
75    fn is_null(&self) -> bool {
76        false
77    }
78}
79
80#[derive(Debug)]
81pub struct Literal {
82    pub value: String,
83}
84
85impl From<&str> for Literal {
86    fn from(val: &str) -> Self {
87        Self {
88            value: val.to_string(),
89        }
90    }
91}
92
93impl From<&String> for Literal {
94    fn from(val: &String) -> Self {
95        Self {
96            value: val.to_string(),
97        }
98    }
99}
100
101impl From<String> for Literal {
102    fn from(val: String) -> Self {
103        Self { value: val }
104    }
105}
106
107impl From<Literal> for Box<dyn Expression> {
108    fn from(val: Literal) -> Self {
109        Box::new(val)
110    }
111}
112
113impl Expression for Literal {
114    fn expression_type(&self) -> ExpressionType {
115        ExpressionType::Literal(self)
116    }
117}
118
119#[must_use]
120pub fn literal(value: &str) -> Literal {
121    Literal {
122        value: value.to_string(),
123    }
124}
125
126#[derive(Debug)]
127pub struct Identifier {
128    pub value: String,
129}
130
131impl From<&str> for Identifier {
132    fn from(val: &str) -> Self {
133        Self {
134            value: val.to_string(),
135        }
136    }
137}
138
139impl From<String> for Identifier {
140    fn from(val: String) -> Self {
141        Self { value: val }
142    }
143}
144
145impl From<Identifier> for Box<dyn Expression> {
146    fn from(val: Identifier) -> Self {
147        Box::new(val)
148    }
149}
150
151impl Expression for Identifier {
152    fn expression_type(&self) -> ExpressionType {
153        ExpressionType::Identifier(self)
154    }
155}
156
157#[must_use]
158pub fn identifier(value: &str) -> Identifier {
159    Identifier {
160        value: value.to_string(),
161    }
162}
163
164impl Expression for DatabaseValue {
165    fn expression_type(&self) -> ExpressionType {
166        ExpressionType::DatabaseValue(self)
167    }
168
169    fn values(&self) -> Option<Vec<&DatabaseValue>> {
170        Some(vec![self])
171    }
172
173    fn is_null(&self) -> bool {
174        matches!(
175            self,
176            Self::Null
177                | Self::BoolOpt(None)
178                | Self::RealOpt(None)
179                | Self::StringOpt(None)
180                | Self::NumberOpt(None)
181                | Self::UNumberOpt(None)
182        )
183    }
184}
185
186impl<T: Into<DatabaseValue>> From<T> for Box<dyn Expression> {
187    fn from(value: T) -> Self {
188        Box::new(value.into())
189    }
190}
191
192pub trait BooleanExpression: Expression {}
193
194#[derive(Debug)]
195pub struct And {
196    pub(crate) conditions: Vec<Box<dyn BooleanExpression>>,
197}
198
199impl BooleanExpression for And {}
200impl Expression for And {
201    fn expression_type(&self) -> ExpressionType {
202        ExpressionType::And(self)
203    }
204
205    fn values(&self) -> Option<Vec<&DatabaseValue>> {
206        let values = self
207            .conditions
208            .iter()
209            .filter_map(|x| x.values())
210            .collect::<Vec<_>>()
211            .concat();
212
213        if values.is_empty() {
214            None
215        } else {
216            Some(values)
217        }
218    }
219}
220
221#[derive(Debug)]
222pub struct Or {
223    pub conditions: Vec<Box<dyn BooleanExpression>>,
224}
225
226impl BooleanExpression for Or {}
227impl Expression for Or {
228    fn expression_type(&self) -> ExpressionType {
229        ExpressionType::Or(self)
230    }
231
232    fn values(&self) -> Option<Vec<&DatabaseValue>> {
233        let values = self
234            .conditions
235            .iter()
236            .filter_map(|x| x.values())
237            .collect::<Vec<_>>()
238            .concat();
239
240        if values.is_empty() {
241            None
242        } else {
243            Some(values)
244        }
245    }
246}
247
248#[derive(Debug)]
249pub struct NotEq {
250    pub left: Identifier,
251    pub right: Box<dyn Expression>,
252}
253
254impl BooleanExpression for NotEq {}
255impl Expression for NotEq {
256    fn expression_type(&self) -> ExpressionType {
257        ExpressionType::NotEq(self)
258    }
259
260    fn values(&self) -> Option<Vec<&DatabaseValue>> {
261        self.right.values()
262    }
263}
264
265#[derive(Debug)]
266pub struct Eq {
267    pub left: Identifier,
268    pub right: Box<dyn Expression>,
269}
270
271impl BooleanExpression for Eq {}
272impl Expression for Eq {
273    fn expression_type(&self) -> ExpressionType {
274        ExpressionType::Eq(self)
275    }
276
277    fn values(&self) -> Option<Vec<&DatabaseValue>> {
278        self.right.values()
279    }
280}
281
282#[derive(Debug)]
283pub struct Gt {
284    pub left: Identifier,
285    pub right: Box<dyn Expression>,
286}
287
288impl BooleanExpression for Gt {}
289impl Expression for Gt {
290    fn expression_type(&self) -> ExpressionType {
291        ExpressionType::Gt(self)
292    }
293
294    fn values(&self) -> Option<Vec<&DatabaseValue>> {
295        self.right.values()
296    }
297}
298
299#[derive(Debug)]
300pub struct Gte {
301    pub left: Identifier,
302    pub right: Box<dyn Expression>,
303}
304
305impl BooleanExpression for Gte {}
306impl Expression for Gte {
307    fn expression_type(&self) -> ExpressionType {
308        ExpressionType::Gte(self)
309    }
310
311    fn values(&self) -> Option<Vec<&DatabaseValue>> {
312        self.right.values()
313    }
314}
315
316#[derive(Debug)]
317pub struct Lt {
318    pub left: Identifier,
319    pub right: Box<dyn Expression>,
320}
321
322impl BooleanExpression for Lt {}
323impl Expression for Lt {
324    fn expression_type(&self) -> ExpressionType {
325        ExpressionType::Lt(self)
326    }
327
328    fn values(&self) -> Option<Vec<&DatabaseValue>> {
329        self.right.values()
330    }
331}
332
333#[derive(Debug)]
334pub struct Lte {
335    pub left: Identifier,
336    pub right: Box<dyn Expression>,
337}
338
339impl BooleanExpression for Lte {}
340impl Expression for Lte {
341    fn expression_type(&self) -> ExpressionType {
342        ExpressionType::Lte(self)
343    }
344
345    fn values(&self) -> Option<Vec<&DatabaseValue>> {
346        self.right.values()
347    }
348}
349
350#[derive(Debug)]
351pub struct In<'a> {
352    pub left: Identifier,
353    pub values: Box<dyn List + 'a>,
354}
355
356impl BooleanExpression for In<'_> {}
357impl Expression for In<'_> {
358    fn expression_type(&self) -> ExpressionType {
359        ExpressionType::In(self)
360    }
361
362    fn values(&self) -> Option<Vec<&DatabaseValue>> {
363        let values = [
364            self.left.values().unwrap_or_default(),
365            self.values.values().unwrap_or_default(),
366        ]
367        .concat();
368
369        if values.is_empty() {
370            None
371        } else {
372            Some(values)
373        }
374    }
375}
376
377#[derive(Debug)]
378pub struct NotIn<'a> {
379    pub left: Identifier,
380    pub values: Box<dyn List + 'a>,
381}
382
383impl BooleanExpression for NotIn<'_> {}
384impl Expression for NotIn<'_> {
385    fn expression_type(&self) -> ExpressionType {
386        ExpressionType::NotIn(self)
387    }
388
389    fn values(&self) -> Option<Vec<&DatabaseValue>> {
390        let values = [
391            self.left.values().unwrap_or_default(),
392            self.values.values().unwrap_or_default(),
393        ]
394        .concat();
395
396        if values.is_empty() {
397            None
398        } else {
399            Some(values)
400        }
401    }
402}
403
404pub fn sort<T>(expression: T, direction: SortDirection) -> Sort
405where
406    T: Into<Box<dyn Expression>>,
407{
408    Sort {
409        expression: expression.into(),
410        direction,
411    }
412}
413
414pub fn where_eq<L, R>(left: L, right: R) -> Eq
415where
416    L: Into<Identifier>,
417    R: Into<Box<dyn Expression>>,
418{
419    Eq {
420        left: left.into(),
421        right: right.into(),
422    }
423}
424
425pub fn where_not_eq<L, R>(left: L, right: R) -> NotEq
426where
427    L: Into<Identifier>,
428    R: Into<Box<dyn Expression>>,
429{
430    NotEq {
431        left: left.into(),
432        right: right.into(),
433    }
434}
435
436pub fn where_gt<L, R>(left: L, right: R) -> Gt
437where
438    L: Into<Identifier>,
439    R: Into<Box<dyn Expression>>,
440{
441    Gt {
442        left: left.into(),
443        right: right.into(),
444    }
445}
446
447pub fn where_gte<L, R>(left: L, right: R) -> Gte
448where
449    L: Into<Identifier>,
450    R: Into<Box<dyn Expression>>,
451{
452    Gte {
453        left: left.into(),
454        right: right.into(),
455    }
456}
457
458pub fn where_lt<L, R>(left: L, right: R) -> Lt
459where
460    L: Into<Identifier>,
461    R: Into<Box<dyn Expression>>,
462{
463    Lt {
464        left: left.into(),
465        right: right.into(),
466    }
467}
468
469pub fn where_lte<L, R>(left: L, right: R) -> Lte
470where
471    L: Into<Identifier>,
472    R: Into<Box<dyn Expression>>,
473{
474    Lte {
475        left: left.into(),
476        right: right.into(),
477    }
478}
479
480#[must_use]
481pub fn where_and(conditions: Vec<Box<dyn BooleanExpression>>) -> And {
482    And { conditions }
483}
484
485#[must_use]
486pub fn where_or(conditions: Vec<Box<dyn BooleanExpression>>) -> Or {
487    Or { conditions }
488}
489
490#[must_use]
491pub const fn join<'a>(table_name: &'a str, on: &'a str) -> Join<'a> {
492    Join {
493        table_name,
494        on,
495        left: false,
496    }
497}
498
499#[must_use]
500pub const fn left_join<'a>(table_name: &'a str, on: &'a str) -> Join<'a> {
501    Join {
502        table_name,
503        on,
504        left: true,
505    }
506}
507
508#[derive(Debug)]
509pub struct Coalesce {
510    pub values: Vec<Box<dyn Expression>>,
511}
512
513impl List for Coalesce {}
514impl Expression for Coalesce {
515    fn expression_type(&self) -> ExpressionType {
516        ExpressionType::Coalesce(self)
517    }
518
519    fn values(&self) -> Option<Vec<&DatabaseValue>> {
520        let values = self
521            .values
522            .iter()
523            .flat_map(|x| x.values().unwrap_or_default())
524            .collect::<Vec<_>>();
525
526        if values.is_empty() {
527            None
528        } else {
529            Some(values)
530        }
531    }
532}
533
534#[must_use]
535pub fn coalesce(values: Vec<Box<dyn Expression>>) -> Coalesce {
536    Coalesce { values }
537}
538
539#[derive(Debug)]
540pub struct InList {
541    pub values: Vec<Box<dyn Expression>>,
542}
543
544impl List for InList {}
545impl Expression for InList {
546    fn expression_type(&self) -> ExpressionType {
547        ExpressionType::InList(self)
548    }
549
550    fn values(&self) -> Option<Vec<&DatabaseValue>> {
551        let values = self
552            .values
553            .iter()
554            .flat_map(|x| x.values().unwrap_or_default())
555            .collect::<Vec<_>>();
556
557        if values.is_empty() {
558            None
559        } else {
560            Some(values)
561        }
562    }
563}
564
565pub trait List: Expression {}
566
567impl<T> From<Vec<T>> for Box<dyn List>
568where
569    T: Into<Box<dyn Expression>> + Send + Sync,
570{
571    fn from(val: Vec<T>) -> Self {
572        Box::new(InList {
573            values: val.into_iter().map(std::convert::Into::into).collect(),
574        })
575    }
576}
577
578pub fn where_in<'a, L, V>(left: L, values: V) -> In<'a>
579where
580    L: Into<Identifier>,
581    V: Into<Box<dyn List + 'a>>,
582{
583    In {
584        left: left.into(),
585        values: values.into(),
586    }
587}
588
589pub fn where_not_in<'a, L, V>(left: L, values: V) -> NotIn<'a>
590where
591    L: Into<Identifier>,
592    V: Into<Box<dyn List + 'a>>,
593{
594    NotIn {
595        left: left.into(),
596        values: values.into(),
597    }
598}
599
600#[macro_export]
601macro_rules! boxed {
602    () => (
603        Vec::new()
604    );
605    ($($x:expr),+ $(,)?) => (
606        vec![$(Box::new($x)),+]
607    );
608}
609
610#[allow(clippy::module_name_repetitions)]
611pub trait FilterableQuery
612where
613    Self: Sized,
614{
615    #[must_use]
616    fn filters(self, filters: Vec<Box<dyn BooleanExpression>>) -> Self {
617        let mut this = self;
618        for filter in filters {
619            this = this.filter(filter);
620        }
621        this
622    }
623
624    #[must_use]
625    fn filter(self, filter: Box<dyn BooleanExpression>) -> Self;
626
627    #[must_use]
628    fn filter_if_some<T: BooleanExpression + 'static>(self, filter: Option<T>) -> Self {
629        if let Some(filter) = filter {
630            self.filter(Box::new(filter))
631        } else {
632            self
633        }
634    }
635
636    #[must_use]
637    fn where_in<L, V>(self, left: L, values: V) -> Self
638    where
639        L: Into<Identifier>,
640        V: Into<Box<dyn List>>,
641    {
642        self.filter(Box::new(where_in(left, values)))
643    }
644
645    #[must_use]
646    fn where_not_in<L, V>(self, left: L, values: V) -> Self
647    where
648        L: Into<Identifier>,
649        V: Into<Box<dyn List>>,
650    {
651        self.filter(Box::new(where_not_in(left, values)))
652    }
653
654    #[must_use]
655    fn where_and(self, conditions: Vec<Box<dyn BooleanExpression>>) -> Self {
656        self.filter(Box::new(where_and(conditions)))
657    }
658
659    #[must_use]
660    fn where_or(self, conditions: Vec<Box<dyn BooleanExpression>>) -> Self {
661        self.filter(Box::new(where_or(conditions)))
662    }
663
664    #[must_use]
665    fn where_eq<L, R>(self, left: L, right: R) -> Self
666    where
667        L: Into<Identifier>,
668        R: Into<Box<dyn Expression>>,
669    {
670        self.filter(Box::new(where_eq(left, right)))
671    }
672
673    #[must_use]
674    fn where_not_eq<L, R>(self, left: L, right: R) -> Self
675    where
676        L: Into<Identifier>,
677        R: Into<Box<dyn Expression>>,
678    {
679        self.filter(Box::new(where_not_eq(left, right)))
680    }
681
682    #[must_use]
683    fn where_gt<L, R>(self, left: L, right: R) -> Self
684    where
685        L: Into<Identifier>,
686        R: Into<Box<dyn Expression>>,
687    {
688        self.filter(Box::new(where_gt(left, right)))
689    }
690
691    #[must_use]
692    fn where_gte<L, R>(self, left: L, right: R) -> Self
693    where
694        L: Into<Identifier>,
695        R: Into<Box<dyn Expression>>,
696    {
697        self.filter(Box::new(where_gte(left, right)))
698    }
699
700    #[must_use]
701    fn where_lt<L, R>(self, left: L, right: R) -> Self
702    where
703        L: Into<Identifier>,
704        R: Into<Box<dyn Expression>>,
705    {
706        self.filter(Box::new(where_lt(left, right)))
707    }
708
709    #[must_use]
710    fn where_lte<L, R>(self, left: L, right: R) -> Self
711    where
712        L: Into<Identifier>,
713        R: Into<Box<dyn Expression>>,
714    {
715        self.filter(Box::new(where_lte(left, right)))
716    }
717}
718
719impl<'a> From<SelectQuery<'a>> for Box<dyn List + 'a> {
720    fn from(val: SelectQuery<'a>) -> Self {
721        Box::new(val)
722    }
723}
724
725#[allow(clippy::module_name_repetitions)]
726#[derive(Debug)]
727pub struct SelectQuery<'a> {
728    pub table_name: &'a str,
729    pub distinct: bool,
730    pub columns: &'a [&'a str],
731    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
732    pub joins: Option<Vec<Join<'a>>>,
733    pub sorts: Option<Vec<Sort>>,
734    pub limit: Option<usize>,
735}
736
737impl List for SelectQuery<'_> {}
738impl Expression for SelectQuery<'_> {
739    fn expression_type(&self) -> ExpressionType {
740        ExpressionType::SelectQuery(self)
741    }
742
743    fn values(&self) -> Option<Vec<&DatabaseValue>> {
744        let joins_values = self
745            .joins
746            .as_ref()
747            .map(|x| {
748                x.iter()
749                    .flat_map(|j| j.values().unwrap_or_default())
750                    .collect::<Vec<_>>()
751            })
752            .unwrap_or_default();
753        let filters_values = self
754            .filters
755            .as_ref()
756            .map(|x| {
757                x.iter()
758                    .flat_map(|j| j.values().unwrap_or_default())
759                    .collect::<Vec<_>>()
760            })
761            .unwrap_or_default();
762        let sorts_values = self
763            .sorts
764            .as_ref()
765            .map(|x| {
766                x.iter()
767                    .flat_map(|j| j.values().unwrap_or_default())
768                    .collect::<Vec<_>>()
769            })
770            .unwrap_or_default();
771
772        let values: Vec<_> = [joins_values, filters_values, sorts_values].concat();
773
774        if values.is_empty() {
775            None
776        } else {
777            Some(values)
778        }
779    }
780}
781
782#[must_use]
783pub fn select(table_name: &str) -> SelectQuery<'_> {
784    SelectQuery {
785        table_name,
786        distinct: false,
787        columns: &["*"],
788        filters: None,
789        joins: None,
790        sorts: None,
791        limit: None,
792    }
793}
794
795impl FilterableQuery for SelectQuery<'_> {
796    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
797        if let Some(filters) = &mut self.filters {
798            filters.push(filter);
799        } else {
800            self.filters.replace(vec![filter]);
801        }
802        self
803    }
804}
805
806impl<'a> SelectQuery<'a> {
807    #[must_use]
808    pub const fn distinct(mut self) -> Self {
809        self.distinct = true;
810        self
811    }
812
813    #[must_use]
814    pub const fn columns(mut self, columns: &'a [&'a str]) -> Self {
815        self.columns = columns;
816        self
817    }
818
819    #[must_use]
820    pub fn joins(mut self, joins: Vec<Join<'a>>) -> Self {
821        for join in joins {
822            if let Some(joins) = &mut self.joins {
823                joins.push(join);
824            } else {
825                self.joins.replace(vec![join]);
826            }
827        }
828        self
829    }
830
831    #[must_use]
832    pub fn join(mut self, table_name: &'a str, on: &'a str) -> Self {
833        if let Some(joins) = &mut self.joins {
834            joins.push(join(table_name, on));
835        } else {
836            self.joins.replace(vec![join(table_name, on)]);
837        }
838        self
839    }
840
841    #[must_use]
842    pub fn left_joins(mut self, left_joins: Vec<Join<'a>>) -> Self {
843        for left_join in left_joins {
844            if let Some(left_joins) = &mut self.joins {
845                left_joins.push(left_join);
846            } else {
847                self.joins.replace(vec![left_join]);
848            }
849        }
850        self
851    }
852
853    #[must_use]
854    pub fn left_join(mut self, table_name: &'a str, on: &'a str) -> Self {
855        if let Some(left_joins) = &mut self.joins {
856            left_joins.push(left_join(table_name, on));
857        } else {
858            self.joins.replace(vec![left_join(table_name, on)]);
859        }
860        self
861    }
862
863    #[must_use]
864    pub fn sorts(mut self, sorts: Vec<Sort>) -> Self {
865        for sort in sorts {
866            if let Some(sorts) = &mut self.sorts {
867                sorts.push(sort);
868            } else {
869                self.sorts.replace(vec![sort]);
870            }
871        }
872        self
873    }
874
875    #[must_use]
876    pub fn sort<T>(mut self, expression: T, direction: SortDirection) -> Self
877    where
878        T: Into<Identifier>,
879    {
880        if let Some(sorts) = &mut self.sorts {
881            sorts.push(sort(expression.into(), direction));
882        } else {
883            self.sorts.replace(vec![sort(expression.into(), direction)]);
884        }
885        self
886    }
887
888    #[must_use]
889    pub const fn limit(mut self, limit: usize) -> Self {
890        self.limit.replace(limit);
891        self
892    }
893
894    /// # Errors
895    ///
896    /// Will return `Err` if the select query execution failed.
897    pub async fn execute(self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
898        db.query(&self).await
899    }
900
901    /// # Errors
902    ///
903    /// Will return `Err` if the select query execution failed.
904    pub async fn execute_first(self, db: &dyn Database) -> Result<Option<Row>, DatabaseError> {
905        let this = if self.limit.is_none() {
906            self.limit(1)
907        } else {
908            self
909        };
910
911        db.query_first(&this).await
912    }
913}
914
915pub struct UpsertMultiStatement<'a> {
916    pub table_name: &'a str,
917    pub values: Vec<Vec<(&'a str, Box<dyn Expression>)>>,
918    pub unique: Option<Vec<Box<dyn Expression>>>,
919}
920
921#[must_use]
922pub fn upsert_multi(table_name: &str) -> UpsertMultiStatement<'_> {
923    UpsertMultiStatement {
924        table_name,
925        values: vec![],
926        unique: None,
927    }
928}
929
930impl<'a> UpsertMultiStatement<'a> {
931    pub fn values<T: Into<Box<dyn Expression>>>(
932        &mut self,
933        values: Vec<Vec<(&'a str, T)>>,
934    ) -> &mut Self {
935        self.values.extend(values.into_iter().map(|values| {
936            values
937                .into_iter()
938                .map(|(key, value)| (key, value.into()))
939                .collect()
940        }));
941        self
942    }
943
944    pub fn unique(&mut self, unique: Vec<Box<dyn Expression>>) -> &mut Self {
945        self.unique.replace(unique);
946        self
947    }
948
949    /// # Errors
950    ///
951    /// Will return `Err` if the upsert multi execution failed.
952    pub async fn execute(&self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
953        db.exec_upsert_multi(self).await
954    }
955}
956
957pub struct InsertStatement<'a> {
958    pub table_name: &'a str,
959    pub values: Vec<(&'a str, Box<dyn Expression>)>,
960}
961
962#[must_use]
963pub fn insert(table_name: &str) -> InsertStatement<'_> {
964    InsertStatement {
965        table_name,
966        values: vec![],
967    }
968}
969
970impl<'a> InsertStatement<'a> {
971    #[must_use]
972    pub fn values<T: Into<Box<dyn Expression>>>(mut self, values: Vec<(&'a str, T)>) -> Self {
973        for value in values {
974            self.values.push((value.0, value.1.into()));
975        }
976        self
977    }
978
979    #[must_use]
980    pub fn value<T: Into<Box<dyn Expression>>>(mut self, name: &'a str, value: T) -> Self {
981        self.values.push((name, value.into()));
982        self
983    }
984
985    /// # Errors
986    ///
987    /// Will return `Err` if the insert execution failed.
988    pub async fn execute(&self, db: &dyn Database) -> Result<Row, DatabaseError> {
989        db.exec_insert(self).await
990    }
991}
992
993pub struct UpdateStatement<'a> {
994    pub table_name: &'a str,
995    pub values: Vec<(&'a str, Box<dyn Expression>)>,
996    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
997    pub unique: Option<&'a [&'a str]>,
998    pub limit: Option<usize>,
999}
1000
1001#[must_use]
1002pub fn update(table_name: &str) -> UpdateStatement<'_> {
1003    UpdateStatement {
1004        table_name,
1005        values: vec![],
1006        filters: None,
1007        unique: None,
1008        limit: None,
1009    }
1010}
1011
1012impl FilterableQuery for UpdateStatement<'_> {
1013    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
1014        if let Some(filters) = &mut self.filters {
1015            filters.push(filter);
1016        } else {
1017            self.filters.replace(vec![filter]);
1018        }
1019        self
1020    }
1021}
1022
1023impl<'a> UpdateStatement<'a> {
1024    #[must_use]
1025    pub fn values<T: Into<Box<dyn Expression>>>(mut self, values: Vec<(&'a str, T)>) -> Self {
1026        for value in values {
1027            self.values.push((value.0, value.1.into()));
1028        }
1029        self
1030    }
1031
1032    #[must_use]
1033    pub fn value<T: Into<Box<dyn Expression>>>(mut self, name: &'a str, value: T) -> Self {
1034        self.values.push((name, value.into()));
1035        self
1036    }
1037
1038    #[must_use]
1039    pub const fn unique(mut self, unique: &'a [&'a str]) -> Self {
1040        self.unique.replace(unique);
1041        self
1042    }
1043
1044    #[must_use]
1045    pub const fn limit(mut self, limit: usize) -> Self {
1046        self.limit.replace(limit);
1047        self
1048    }
1049
1050    /// # Errors
1051    ///
1052    /// Will return `Err` if the update execution failed.
1053    pub async fn execute(&self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
1054        db.exec_update(self).await
1055    }
1056
1057    /// # Errors
1058    ///
1059    /// Will return `Err` if the update execution failed.
1060    pub async fn execute_first(&self, db: &dyn Database) -> Result<Option<Row>, DatabaseError> {
1061        db.exec_update_first(self).await
1062    }
1063}
1064
1065pub struct UpsertStatement<'a> {
1066    pub table_name: &'a str,
1067    pub values: Vec<(&'a str, Box<dyn Expression>)>,
1068    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
1069    pub unique: Option<&'a [&'a str]>,
1070    pub limit: Option<usize>,
1071}
1072
1073#[must_use]
1074pub fn upsert(table_name: &str) -> UpsertStatement<'_> {
1075    UpsertStatement {
1076        table_name,
1077        values: vec![],
1078        filters: None,
1079        unique: None,
1080        limit: None,
1081    }
1082}
1083
1084impl FilterableQuery for UpsertStatement<'_> {
1085    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
1086        if let Some(filters) = &mut self.filters {
1087            filters.push(filter);
1088        } else {
1089            self.filters.replace(vec![filter]);
1090        }
1091        self
1092    }
1093}
1094
1095impl<'a> UpsertStatement<'a> {
1096    #[must_use]
1097    pub fn values<T: Into<Box<dyn Expression>>>(mut self, values: Vec<(&'a str, T)>) -> Self {
1098        for value in values {
1099            self.values.push((value.0, value.1.into()));
1100        }
1101        self
1102    }
1103
1104    #[must_use]
1105    pub fn value<T: Into<Box<dyn Expression>>>(mut self, name: &'a str, value: T) -> Self {
1106        self.values.push((name, value.into()));
1107        self
1108    }
1109
1110    #[must_use]
1111    pub fn value_opt<T: Into<Box<dyn Expression>>>(
1112        mut self,
1113        name: &'a str,
1114        value: Option<T>,
1115    ) -> Self {
1116        if let Some(value) = value {
1117            self.values.push((name, value.into()));
1118        }
1119        self
1120    }
1121
1122    #[must_use]
1123    pub const fn unique(mut self, unique: &'a [&'a str]) -> Self {
1124        self.unique.replace(unique);
1125        self
1126    }
1127
1128    #[must_use]
1129    pub const fn limit(mut self, limit: usize) -> Self {
1130        self.limit.replace(limit);
1131        self
1132    }
1133
1134    /// # Errors
1135    ///
1136    /// Will return `Err` if the upsert execution failed.
1137    pub async fn execute(self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
1138        if self.values.is_empty() {
1139            return db.query(&self.into()).await;
1140        }
1141        db.exec_upsert(&self).await
1142    }
1143
1144    /// # Errors
1145    ///
1146    /// Will return `Err` if the upsert execution failed.
1147    pub async fn execute_first(self, db: &dyn Database) -> Result<Row, DatabaseError> {
1148        if self.values.is_empty() {
1149            return db
1150                .query_first(&self.into())
1151                .await?
1152                .ok_or(DatabaseError::NoRow);
1153        }
1154        db.exec_upsert_first(&self).await
1155    }
1156}
1157
1158impl<'a> From<UpsertStatement<'a>> for SelectQuery<'a> {
1159    fn from(value: UpsertStatement<'a>) -> Self {
1160        Self {
1161            table_name: value.table_name,
1162            distinct: false,
1163            columns: &["*"],
1164            filters: value.filters,
1165            joins: None,
1166            sorts: None,
1167            limit: value.limit,
1168        }
1169    }
1170}
1171
1172pub struct DeleteStatement<'a> {
1173    pub table_name: &'a str,
1174    pub filters: Option<Vec<Box<dyn BooleanExpression>>>,
1175    pub limit: Option<usize>,
1176}
1177
1178#[must_use]
1179pub fn delete(table_name: &str) -> DeleteStatement<'_> {
1180    DeleteStatement {
1181        table_name,
1182        filters: None,
1183        limit: None,
1184    }
1185}
1186
1187impl FilterableQuery for DeleteStatement<'_> {
1188    fn filter(mut self, filter: Box<dyn BooleanExpression>) -> Self {
1189        if let Some(filters) = &mut self.filters {
1190            filters.push(filter);
1191        } else {
1192            self.filters.replace(vec![filter]);
1193        }
1194        self
1195    }
1196}
1197
1198impl DeleteStatement<'_> {
1199    #[must_use]
1200    pub const fn limit(mut self, limit: usize) -> Self {
1201        self.limit.replace(limit);
1202        self
1203    }
1204
1205    /// # Errors
1206    ///
1207    /// Will return `Err` if the delete execution failed.
1208    pub async fn execute(&self, db: &dyn Database) -> Result<Vec<Row>, DatabaseError> {
1209        db.exec_delete(self).await
1210    }
1211
1212    /// # Errors
1213    ///
1214    /// Will return `Err` if the delete execution failed.
1215    pub async fn execute_first(&self, db: &dyn Database) -> Result<Option<Row>, DatabaseError> {
1216        db.exec_delete_first(self).await
1217    }
1218}