sql_builder/query/condition.rs
1mod conditional;
2mod constant;
3mod holder;
4
5pub use conditional::*;
6
7use crate::{ExprTrait, expr::Expr, types::LogicalChainOper};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ConditionType {
11 Any,
12 All,
13}
14
15/// Represents the value of an [`Condition::any`] or [`Condition::all`]: a set of disjunctive or conjunctive conditions.
16#[derive(Debug, Clone, PartialEq)]
17pub struct Condition {
18 pub(crate) negate: bool,
19 pub(crate) condition_type: ConditionType,
20 pub(crate) conditions: Vec<ConditionExpression>,
21}
22
23pub type Cond = Condition;
24
25impl From<Expr> for Condition {
26 fn from(expr: Expr) -> Self {
27 Condition {
28 negate: false,
29 condition_type: ConditionType::All,
30 conditions: vec![ConditionExpression::Expr(expr)],
31 }
32 }
33}
34
35impl From<ConditionExpression> for Condition {
36 fn from(ce: ConditionExpression) -> Self {
37 Condition {
38 negate: false,
39 condition_type: ConditionType::All,
40 conditions: vec![ce],
41 }
42 }
43}
44
45/// A helper trait.
46///
47/// You shouldn't implement this manually.
48pub trait IntoCondition: Into<Condition> {
49 #[inline(always)]
50 fn into_condition(self) -> Condition {
51 self.into()
52 }
53}
54
55impl<T> IntoCondition for T where T: Into<Condition> {}
56
57/// An internal representation of conditions, either an expression or a nested condition.
58#[derive(Debug, Clone, PartialEq)]
59pub(crate) enum ConditionExpression {
60 Condition(Condition),
61 Expr(Expr),
62}
63
64#[derive(Default, Debug, Clone, PartialEq)]
65pub enum ConditionHolderContents {
66 #[default]
67 Empty,
68 Chain(Vec<LogicalChainOper>),
69 Condition(Condition),
70}
71
72#[derive(Default, Debug, Clone, PartialEq)]
73pub struct ConditionHolder {
74 pub contents: ConditionHolderContents,
75}
76
77impl Condition {
78 /// Add a condition to the set.
79 ///
80 /// If it's an [`Condition::any`], it will be separated from the others by an `" OR "` in the query. If it's
81 /// an [`Condition::all`], it will be separated by an `" AND "`.
82 ///
83 /// ```
84 /// use sql_builder::*;
85 ///
86 /// let statement = Query::select()
87 /// .column("id")
88 /// .from("glyph")
89 /// .cond_where(
90 /// Cond::all()
91 /// .add(Expr::col("aspect").eq(0).into_condition().not())
92 /// .add(Expr::col("id").eq(0).into_condition().not()),
93 /// )
94 /// .to_string(PostgresQueryBuilder).unwrap();
95 /// assert_eq!(
96 /// statement,
97 /// r#"SELECT "id" FROM "glyph" WHERE (NOT "aspect" = 0) AND (NOT "id" = 0)"#
98 /// );
99 /// ```
100 #[allow(clippy::should_implement_trait)]
101 pub fn add<C>(mut self, condition: C) -> Self
102 where
103 C: Into<Condition>,
104 {
105 let condition: Condition = condition.into();
106 let condition: ConditionExpression = condition.into();
107 self.conditions.push(condition);
108 self
109 }
110
111 /// Add an optional condition to the set.
112 ///
113 /// Shorthand for `if o.is_some() { self.add(o) }`
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use sql_builder::*;
119 ///
120 /// let query = Query::select()
121 /// .column("image")
122 /// .from("glyph")
123 /// .cond_where(
124 /// Cond::all()
125 /// .add_option(Some(Expr::col(("glyph", "image")).like("A%")))
126 /// .add_option(None::<Expr>),
127 /// )
128 /// .to_owned();
129 ///
130 /// assert_eq!(
131 /// query.to_string(MysqlQueryBuilder).unwrap(),
132 /// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`image` LIKE 'A%'"#
133 /// );
134 /// ```
135 pub fn add_option<C>(self, other: Option<C>) -> Self
136 where
137 C: Into<Condition>,
138 {
139 if let Some(other) = other {
140 self.add(other)
141 } else {
142 self
143 }
144 }
145
146 /// Create a condition that is true if any of the conditions is true.
147 ///
148 /// # Examples
149 ///
150 /// ```
151 /// use sql_builder::*;
152 ///
153 /// let query = Query::select()
154 /// .column("image")
155 /// .from("glyph")
156 /// .cond_where(
157 /// Cond::any()
158 /// .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
159 /// .add(Expr::col(("glyph", "image")).like("A%"))
160 /// )
161 /// .to_owned();
162 ///
163 /// assert_eq!(
164 /// query.to_string(MysqlQueryBuilder).unwrap(),
165 /// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) OR `glyph`.`image` LIKE 'A%'"#
166 /// );
167 /// ```
168 pub fn any() -> Condition {
169 Condition {
170 negate: false,
171 condition_type: ConditionType::Any,
172 conditions: Vec::new(),
173 }
174 }
175
176 /// Create a condition that is false if any of the conditions is false.
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// use sql_builder::*;
182 ///
183 /// let query = Query::select()
184 /// .column("image")
185 /// .from("glyph")
186 /// .cond_where(
187 /// Cond::all()
188 /// .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
189 /// .add(Expr::col(("glyph", "image")).like("A%"))
190 /// )
191 /// .to_owned();
192 ///
193 /// assert_eq!(
194 /// query.to_string(MysqlQueryBuilder).unwrap(),
195 /// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%'"#
196 /// );
197 /// ```
198 pub fn all() -> Condition {
199 Condition {
200 negate: false,
201 condition_type: ConditionType::All,
202 conditions: Vec::new(),
203 }
204 }
205
206 /// Negates a condition.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use sql_builder::*;
212 ///
213 /// let query = Query::select()
214 /// .column("image")
215 /// .from("glyph")
216 /// .cond_where(
217 /// Cond::all()
218 /// .not()
219 /// .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
220 /// .add(Expr::col(("glyph", "image")).like("A%"))
221 /// )
222 /// .to_owned();
223 ///
224 /// assert_eq!(
225 /// query.to_string(MysqlQueryBuilder).unwrap(),
226 /// r#"SELECT `image` FROM `glyph` WHERE NOT (`glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%')"#
227 /// );
228 /// ```
229 ///
230 /// # More Examples
231 ///
232 /// ```
233 /// use sql_builder::*;
234 ///
235 /// let query = Query::select()
236 /// .column("id")
237 /// .cond_where(
238 /// Cond::all()
239 /// .add(
240 /// Cond::all()
241 /// .not()
242 /// .add(Expr::val(1).eq(1))
243 /// .add(Expr::val(2).eq(2)),
244 /// )
245 /// .add(Cond::any().add(Expr::val(3).eq(3)).add(Expr::val(4).eq(4))),
246 /// )
247 /// .to_owned();
248 ///
249 /// assert_eq!(
250 /// query.to_string(MysqlQueryBuilder).unwrap(),
251 /// r#"SELECT `id` WHERE (NOT (1 = 1 AND 2 = 2)) AND (3 = 3 OR 4 = 4)"#
252 /// );
253 /// ```
254 #[allow(clippy::should_implement_trait)]
255 pub fn not(mut self) -> Self {
256 self.negate = !self.negate;
257 self
258 }
259
260 /// Whether or not any condition has been added
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use sql_builder::*;
266 ///
267 /// let is_empty = Cond::all().is_empty();
268 ///
269 /// assert!(is_empty);
270 /// ```
271 pub fn is_empty(&self) -> bool {
272 self.conditions.is_empty()
273 }
274
275 /// How many conditions were added
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// use sql_builder::*;
281 ///
282 /// let len = Cond::all().len();
283 ///
284 /// assert_eq!(len, 0);
285 /// ```
286 pub fn len(&self) -> usize {
287 self.conditions.len()
288 }
289}
290
291impl From<Condition> for Expr {
292 fn from(cond: Condition) -> Self {
293 let mut inner_exprs = vec![];
294 for ce in cond.conditions {
295 inner_exprs.push(match ce {
296 ConditionExpression::Condition(c) => c.into(),
297 ConditionExpression::Expr(e) => e,
298 });
299 }
300 let mut inner_exprs_into_iter = inner_exprs.into_iter();
301 let expr = if let Some(first_expr) = inner_exprs_into_iter.next() {
302 let mut out_expr = first_expr;
303 for e in inner_exprs_into_iter {
304 out_expr = match cond.condition_type {
305 ConditionType::Any => out_expr.or(e),
306 ConditionType::All => out_expr.and(e),
307 };
308 }
309 out_expr
310 } else {
311 Expr::Constant(match cond.condition_type {
312 ConditionType::Any => false.into(),
313 ConditionType::All => true.into(),
314 })
315 };
316 if cond.negate { expr.not() } else { expr }
317 }
318}
319
320impl From<ConditionExpression> for Expr {
321 fn from(ce: ConditionExpression) -> Self {
322 match ce {
323 ConditionExpression::Condition(c) => c.into(),
324 ConditionExpression::Expr(e) => e,
325 }
326 }
327}
328
329impl From<Condition> for ConditionExpression {
330 fn from(condition: Condition) -> Self {
331 ConditionExpression::Condition(condition)
332 }
333}
334
335impl From<Expr> for ConditionExpression {
336 fn from(condition: Expr) -> Self {
337 ConditionExpression::Expr(condition)
338 }
339}
340
341/// Macro to easily create an [`Condition::any`].
342///
343/// # Examples
344///
345/// ```
346/// use sql_builder::*;
347///
348/// let query = Query::select()
349/// .column("image")
350/// .from("glyph")
351/// .cond_where(
352/// any![
353/// Expr::col(("glyph", "aspect")).is_in([3, 4]),
354/// Expr::col(("glyph", "image")).like("A%")
355/// ]
356/// )
357/// .to_owned();
358///
359/// assert_eq!(
360/// query.to_string(MysqlQueryBuilder).unwrap(),
361/// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) OR `glyph`.`image` LIKE 'A%'"#
362/// );
363/// ```
364#[macro_export]
365macro_rules! any {
366 ( $( $x:expr ),* $(,)?) => {
367 {
368 let mut tmp = $crate::Condition::any();
369 $(
370 tmp = tmp.add($x);
371 )*
372 tmp
373 }
374 };
375}
376
377/// Macro to easily create an [`Condition::all`].
378///
379/// # Examples
380///
381/// ```
382/// use sql_builder::*;
383///
384/// let query = Query::select()
385/// .column("image")
386/// .from("glyph")
387/// .cond_where(
388/// all![
389/// Expr::col(("glyph", "aspect")).is_in([3, 4]),
390/// Expr::col(("glyph", "image")).like("A%")
391/// ]
392/// )
393/// .to_owned();
394///
395/// assert_eq!(
396/// query.to_string(MysqlQueryBuilder).unwrap(),
397/// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%'"#
398/// );
399#[macro_export]
400macro_rules! all {
401 ( $( $x:expr ),* $(,)?) => {
402 {
403 let mut tmp = $crate::Condition::all();
404 $(
405 tmp = tmp.add($x);
406 )*
407 tmp
408 }
409 };
410}