Skip to main content

sql_builder/query/condition/
conditional.rs

1use super::*;
2
3pub trait ConditionalStatement {
4    /// And where condition.
5    /// Calling `or_where` after `and_where` will panic.
6    ///
7    /// # Examples
8    ///
9    /// ```
10    /// use sql_builder::*;
11    ///
12    /// let query = Query::select()
13    ///     .column("image")
14    ///     .from("glyph")
15    ///     .and_where(Expr::col(("glyph", "aspect")).is_in([3, 4]))
16    ///     .and_where(Expr::col(("glyph", "image")).like("A%"))
17    ///     .to_owned();
18    ///
19    /// assert_eq!(
20    ///     query.to_string(MysqlQueryBuilder).unwrap(),
21    ///     r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%'"#
22    /// );
23    /// ```
24    fn and_where(&mut self, other: Expr) -> &mut Self {
25        self.cond_where(other)
26    }
27
28    /// Optional and where, short hand for `if c.is_some() q.and_where(c)`.
29    ///
30    /// ```
31    /// use sql_builder::*;
32    ///
33    /// let query = Query::select()
34    ///     .column("image")
35    ///     .from("glyph")
36    ///     .and_where(Expr::col("aspect").is_in([3, 4]))
37    ///     .and_where_option(Some(Expr::col("image").like("A%")))
38    ///     .and_where_option(None)
39    ///     .to_owned();
40    ///
41    /// assert_eq!(
42    ///     query.to_string(MysqlQueryBuilder).unwrap(),
43    ///     r#"SELECT `image` FROM `glyph` WHERE `aspect` IN (3, 4) AND `image` LIKE 'A%'"#
44    /// );
45    /// ```
46    fn and_where_option(&mut self, other: Option<Expr>) -> &mut Self {
47        if let Some(other) = other {
48            self.and_where(other);
49        }
50        self
51    }
52
53    #[doc(hidden)]
54    // Trait implementation.
55    fn and_or_where(&mut self, condition: LogicalChainOper) -> &mut Self;
56
57    /// Where condition, expressed with `any` and `all`.
58    /// Calling `cond_where` multiple times will conjoin them.
59    /// Calling `or_where` after `cond_where` will panic.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use sql_builder::*;
65    ///
66    /// let query = Query::select()
67    ///     .column("image")
68    ///     .from("glyph")
69    ///     .cond_where(
70    ///         Cond::all()
71    ///             .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
72    ///             .add(Cond::any()
73    ///                 .add(Expr::col(("glyph", "image")).like("A%"))
74    ///                 .add(Expr::col(("glyph", "image")).like("B%"))
75    ///             )
76    ///     )
77    ///     .to_owned();
78    ///
79    /// assert_eq!(
80    ///     query.to_string(PostgresQueryBuilder).unwrap(),
81    ///     r#"SELECT "image" FROM "glyph" WHERE "glyph"."aspect" IN (3, 4) AND ("glyph"."image" LIKE 'A%' OR "glyph"."image" LIKE 'B%')"#
82    /// );
83    /// ```
84    ///
85    /// Using macro
86    ///
87    /// ```
88    /// use sql_builder::*;
89    ///
90    /// let query = Query::select()
91    ///     .column("image")
92    ///     .from("glyph")
93    ///     .cond_where(
94    ///         all![
95    ///             Expr::col(("glyph", "aspect")).is_in([3, 4]),
96    ///             any![
97    ///                 Expr::col(("glyph", "image")).like("A%"),
98    ///                 Expr::col(("glyph", "image")).like("B%"),
99    ///             ]
100    ///         ])
101    ///     .to_owned();
102    ///
103    /// assert_eq!(
104    ///     query.to_string(PostgresQueryBuilder).unwrap(),
105    ///     r#"SELECT "image" FROM "glyph" WHERE "glyph"."aspect" IN (3, 4) AND ("glyph"."image" LIKE 'A%' OR "glyph"."image" LIKE 'B%')"#
106    /// );
107    /// ```
108    ///
109    /// Calling multiple times; the following two are equivalent:
110    ///
111    /// ```
112    /// use sql_builder::*;
113    ///
114    /// assert_eq!(
115    ///     Query::select()
116    ///         .column("id")
117    ///         .from("glyph")
118    ///         .cond_where(Expr::col("id").eq(1))
119    ///         .cond_where(any![Expr::col("id").eq(2), Expr::col("id").eq(3)])
120    ///         .to_owned()
121    ///         .to_string(PostgresQueryBuilder).unwrap(),
122    ///     r#"SELECT "id" FROM "glyph" WHERE "id" = 1 AND ("id" = 2 OR "id" = 3)"#
123    /// );
124    ///
125    /// assert_eq!(
126    ///     Query::select()
127    ///         .column("id")
128    ///         .from("glyph")
129    ///         .cond_where(any![Expr::col("id").eq(2), Expr::col("id").eq(3)])
130    ///         .cond_where(Expr::col("id").eq(1))
131    ///         .to_owned()
132    ///         .to_string(PostgresQueryBuilder).unwrap(),
133    ///     r#"SELECT "id" FROM "glyph" WHERE ("id" = 2 OR "id" = 3) AND "id" = 1"#
134    /// );
135    /// ```
136    ///
137    /// Calling multiple times; will be ANDed togother
138    ///
139    /// ```
140    /// use sql_builder::*;
141    ///
142    /// assert_eq!(
143    ///     Query::select()
144    ///         .column("id")
145    ///         .from("glyph")
146    ///         .cond_where(any![Expr::col("id").eq(1), Expr::col("id").eq(2)])
147    ///         .cond_where(any![Expr::col("id").eq(3), Expr::col("id").eq(4)])
148    ///         .to_owned()
149    ///         .to_string(PostgresQueryBuilder).unwrap(),
150    ///     r#"SELECT "id" FROM "glyph" WHERE ("id" = 1 OR "id" = 2) AND ("id" = 3 OR "id" = 4)"#
151    /// );
152    ///
153    /// assert_eq!(
154    ///     Query::select()
155    ///         .column("id")
156    ///         .from("glyph")
157    ///         .cond_where(all![Expr::col("id").eq(1), Expr::col("id").eq(2)])
158    ///         .cond_where(all![Expr::col("id").eq(3), Expr::col("id").eq(4)])
159    ///         .to_owned()
160    ///         .to_string(PostgresQueryBuilder).unwrap(),
161    ///     r#"SELECT "id" FROM "glyph" WHERE "id" = 1 AND "id" = 2 AND "id" = 3 AND "id" = 4"#
162    /// );
163    /// ```
164    ///
165    /// Some more test cases involving negation
166    ///
167    /// ```
168    /// use sql_builder::*;
169    ///
170    /// assert_eq!(
171    ///     Query::select()
172    ///         .column("id")
173    ///         .from("glyph")
174    ///         .cond_where(
175    ///             Cond::all()
176    ///                 .not()
177    ///                 .add(Expr::col("id").eq(1))
178    ///                 .add(Expr::col("id").eq(2)),
179    ///         )
180    ///         .cond_where(
181    ///             Cond::all()
182    ///                 .add(Expr::col("id").eq(3))
183    ///                 .add(Expr::col("id").eq(4)),
184    ///         )
185    ///         .to_owned()
186    ///         .to_string(PostgresQueryBuilder).unwrap(),
187    ///     r#"SELECT "id" FROM "glyph" WHERE (NOT ("id" = 1 AND "id" = 2)) AND ("id" = 3 AND "id" = 4)"#
188    /// );
189    ///
190    /// assert_eq!(
191    ///     Query::select()
192    ///         .column("id")
193    ///         .from("glyph")
194    ///         .cond_where(
195    ///             Cond::all()
196    ///                 .add(Expr::col("id").eq(3))
197    ///                 .add(Expr::col("id").eq(4)),
198    ///         )
199    ///         .cond_where(
200    ///             Cond::all()
201    ///                 .not()
202    ///                 .add(Expr::col("id").eq(1))
203    ///                 .add(Expr::col("id").eq(2)),
204    ///         )
205    ///         .to_owned()
206    ///         .to_string(PostgresQueryBuilder).unwrap(),
207    ///     r#"SELECT "id" FROM "glyph" WHERE "id" = 3 AND "id" = 4 AND (NOT ("id" = 1 AND "id" = 2))"#
208    /// );
209    /// ```
210    fn cond_where<C>(&mut self, condition: C) -> &mut Self
211    where
212        C: IntoCondition;
213}
214
215/// Implements [`ConditionalStatement`] over the statement's `r#where` holder, with inherent
216/// copies of the trait's methods so callers need not import it.
217macro_rules! conditional_statement {
218    ($statement:ty) => {
219        impl $crate::ConditionalStatement for $statement {
220            fn and_or_where(&mut self, condition: $crate::LogicalChainOper) -> &mut Self {
221                self.r#where.add_and_or(condition);
222                self
223            }
224
225            fn cond_where<C>(&mut self, condition: C) -> &mut Self
226            where
227                C: $crate::IntoCondition,
228            {
229                self.r#where.add_condition(condition.into_condition());
230                self
231            }
232        }
233
234        impl $statement {
235            pub fn and_where(&mut self, other: $crate::Expr) -> &mut Self {
236                <Self as $crate::ConditionalStatement>::and_where(self, other)
237            }
238
239            pub fn and_where_option(&mut self, other: Option<$crate::Expr>) -> &mut Self {
240                <Self as $crate::ConditionalStatement>::and_where_option(self, other)
241            }
242
243            pub fn and_or_where(&mut self, condition: $crate::LogicalChainOper) -> &mut Self {
244                <Self as $crate::ConditionalStatement>::and_or_where(self, condition)
245            }
246
247            pub fn cond_where<C: $crate::IntoCondition>(&mut self, condition: C) -> &mut Self {
248                <Self as $crate::ConditionalStatement>::cond_where(self, condition)
249            }
250        }
251    };
252}
253pub(crate) use conditional_statement;