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 #[allow(clippy::should_implement_trait)]
136 pub fn add_option<C>(self, other: Option<C>) -> Self
137 where
138 C: Into<Condition>,
139 {
140 if let Some(other) = other {
141 self.add(other)
142 } else {
143 self
144 }
145 }
146
147 /// Create a condition that is true if any of the conditions is true.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use sql_builder::*;
153 ///
154 /// let query = Query::select()
155 /// .column("image")
156 /// .from("glyph")
157 /// .cond_where(
158 /// Cond::any()
159 /// .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
160 /// .add(Expr::col(("glyph", "image")).like("A%"))
161 /// )
162 /// .to_owned();
163 ///
164 /// assert_eq!(
165 /// query.to_string(MysqlQueryBuilder).unwrap(),
166 /// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) OR `glyph`.`image` LIKE 'A%'"#
167 /// );
168 /// ```
169 pub fn any() -> Condition {
170 Condition {
171 negate: false,
172 condition_type: ConditionType::Any,
173 conditions: Vec::new(),
174 }
175 }
176
177 /// Create a condition that is false if any of the conditions is false.
178 ///
179 /// # Examples
180 ///
181 /// ```
182 /// use sql_builder::*;
183 ///
184 /// let query = Query::select()
185 /// .column("image")
186 /// .from("glyph")
187 /// .cond_where(
188 /// Cond::all()
189 /// .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
190 /// .add(Expr::col(("glyph", "image")).like("A%"))
191 /// )
192 /// .to_owned();
193 ///
194 /// assert_eq!(
195 /// query.to_string(MysqlQueryBuilder).unwrap(),
196 /// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%'"#
197 /// );
198 /// ```
199 pub fn all() -> Condition {
200 Condition {
201 negate: false,
202 condition_type: ConditionType::All,
203 conditions: Vec::new(),
204 }
205 }
206
207 /// Negates a condition.
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// use sql_builder::*;
213 ///
214 /// let query = Query::select()
215 /// .column("image")
216 /// .from("glyph")
217 /// .cond_where(
218 /// Cond::all()
219 /// .not()
220 /// .add(Expr::col(("glyph", "aspect")).is_in([3, 4]))
221 /// .add(Expr::col(("glyph", "image")).like("A%"))
222 /// )
223 /// .to_owned();
224 ///
225 /// assert_eq!(
226 /// query.to_string(MysqlQueryBuilder).unwrap(),
227 /// r#"SELECT `image` FROM `glyph` WHERE NOT (`glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%')"#
228 /// );
229 /// ```
230 ///
231 /// # More Examples
232 ///
233 /// ```
234 /// use sql_builder::*;
235 ///
236 /// let query = Query::select()
237 /// .column("id")
238 /// .cond_where(
239 /// Cond::all()
240 /// .add(
241 /// Cond::all()
242 /// .not()
243 /// .add(Expr::val(1).eq(1))
244 /// .add(Expr::val(2).eq(2)),
245 /// )
246 /// .add(Cond::any().add(Expr::val(3).eq(3)).add(Expr::val(4).eq(4))),
247 /// )
248 /// .to_owned();
249 ///
250 /// assert_eq!(
251 /// query.to_string(MysqlQueryBuilder).unwrap(),
252 /// r#"SELECT `id` WHERE (NOT (1 = 1 AND 2 = 2)) AND (3 = 3 OR 4 = 4)"#
253 /// );
254 /// ```
255 #[allow(clippy::should_implement_trait)]
256 pub fn not(mut self) -> Self {
257 self.negate = !self.negate;
258 self
259 }
260
261 /// Whether or not any condition has been added
262 ///
263 /// # Examples
264 ///
265 /// ```
266 /// use sql_builder::*;
267 ///
268 /// let is_empty = Cond::all().is_empty();
269 ///
270 /// assert!(is_empty);
271 /// ```
272 pub fn is_empty(&self) -> bool {
273 self.conditions.is_empty()
274 }
275
276 /// How many conditions were added
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use sql_builder::*;
282 ///
283 /// let len = Cond::all().len();
284 ///
285 /// assert_eq!(len, 0);
286 /// ```
287 pub fn len(&self) -> usize {
288 self.conditions.len()
289 }
290}
291
292impl From<Condition> for Expr {
293 fn from(cond: Condition) -> Self {
294 let mut inner_exprs = vec![];
295 for ce in cond.conditions {
296 inner_exprs.push(match ce {
297 ConditionExpression::Condition(c) => c.into(),
298 ConditionExpression::Expr(e) => e,
299 });
300 }
301 let mut inner_exprs_into_iter = inner_exprs.into_iter();
302 let expr = if let Some(first_expr) = inner_exprs_into_iter.next() {
303 let mut out_expr = first_expr;
304 for e in inner_exprs_into_iter {
305 out_expr = match cond.condition_type {
306 ConditionType::Any => out_expr.or(e),
307 ConditionType::All => out_expr.and(e),
308 };
309 }
310 out_expr
311 } else {
312 Expr::Constant(match cond.condition_type {
313 ConditionType::Any => false.into(),
314 ConditionType::All => true.into(),
315 })
316 };
317 if cond.negate { expr.not() } else { expr }
318 }
319}
320
321impl From<ConditionExpression> for Expr {
322 fn from(ce: ConditionExpression) -> Self {
323 match ce {
324 ConditionExpression::Condition(c) => c.into(),
325 ConditionExpression::Expr(e) => e,
326 }
327 }
328}
329
330impl From<Condition> for ConditionExpression {
331 fn from(condition: Condition) -> Self {
332 ConditionExpression::Condition(condition)
333 }
334}
335
336impl From<Expr> for ConditionExpression {
337 fn from(condition: Expr) -> Self {
338 ConditionExpression::Expr(condition)
339 }
340}
341
342/// Macro to easily create an [`Condition::any`].
343///
344/// # Examples
345///
346/// ```
347/// use sql_builder::*;
348///
349/// let query = Query::select()
350/// .column("image")
351/// .from("glyph")
352/// .cond_where(
353/// any![
354/// Expr::col(("glyph", "aspect")).is_in([3, 4]),
355/// Expr::col(("glyph", "image")).like("A%")
356/// ]
357/// )
358/// .to_owned();
359///
360/// assert_eq!(
361/// query.to_string(MysqlQueryBuilder).unwrap(),
362/// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) OR `glyph`.`image` LIKE 'A%'"#
363/// );
364/// ```
365#[macro_export]
366macro_rules! any {
367 ( $( $x:expr ),* $(,)?) => {
368 {
369 let mut tmp = $crate::Condition::any();
370 $(
371 tmp = tmp.add($x);
372 )*
373 tmp
374 }
375 };
376}
377
378/// Macro to easily create an [`Condition::all`].
379///
380/// # Examples
381///
382/// ```
383/// use sql_builder::*;
384///
385/// let query = Query::select()
386/// .column("image")
387/// .from("glyph")
388/// .cond_where(
389/// all![
390/// Expr::col(("glyph", "aspect")).is_in([3, 4]),
391/// Expr::col(("glyph", "image")).like("A%")
392/// ]
393/// )
394/// .to_owned();
395///
396/// assert_eq!(
397/// query.to_string(MysqlQueryBuilder).unwrap(),
398/// r#"SELECT `image` FROM `glyph` WHERE `glyph`.`aspect` IN (3, 4) AND `glyph`.`image` LIKE 'A%'"#
399/// );
400#[macro_export]
401macro_rules! all {
402 ( $( $x:expr ),* $(,)?) => {
403 {
404 let mut tmp = $crate::Condition::all();
405 $(
406 tmp = tmp.add($x);
407 )*
408 tmp
409 }
410 };
411}