rust_query/value/
operations.rs

1use sea_query::{Alias, ExprTrait, extension::sqlite::SqliteExpr};
2
3use crate::value::MyTyp;
4
5use super::{EqTyp, Expr, IntoExpr, NumTyp};
6
7impl<'column, S, T: NumTyp> Expr<'column, S, T> {
8    /// Add two expressions together.
9    ///
10    /// ```
11    /// # use rust_query::IntoExpr;
12    /// # rust_query::private::doctest::get_txn(|txn| {
13    /// assert_eq!(txn.query_one(1.into_expr().add(2)), 3);
14    /// assert_eq!(txn.query_one(1.0.into_expr().add(2.0)), 3.0);
15    /// # });
16    /// ```
17    pub fn add(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, T> {
18        let lhs = self.inner.clone();
19        let rhs = rhs.into_expr().inner;
20        Expr::adhoc(move |b| lhs.build_expr(b).add(rhs.build_expr(b)))
21    }
22
23    /// Subtract one expression from another.
24    ///
25    /// ```
26    /// # use rust_query::IntoExpr;
27    /// # rust_query::private::doctest::get_txn(|txn| {
28    /// assert_eq!(txn.query_one(1.into_expr().sub(2)), -1);
29    /// assert_eq!(txn.query_one(1.0.into_expr().sub(2.0)), -1.0);
30    /// # });
31    /// ```
32    pub fn sub(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, T> {
33        let lhs = self.inner.clone();
34        let rhs = rhs.into_expr().inner;
35        Expr::adhoc(move |b| lhs.build_expr(b).sub(rhs.build_expr(b)))
36    }
37
38    /// Multiply two expressions together.
39    ///
40    /// ```
41    /// # use rust_query::IntoExpr;
42    /// # rust_query::private::doctest::get_txn(|txn| {
43    /// assert_eq!(txn.query_one(2.into_expr().mul(3)), 6);
44    /// assert_eq!(txn.query_one(2.0.into_expr().mul(3.0)), 6.0);
45    /// # });
46    /// ```
47    pub fn mul(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, T> {
48        let lhs = self.inner.clone();
49        let rhs = rhs.into_expr().inner;
50        Expr::adhoc(move |b| lhs.build_expr(b).mul(rhs.build_expr(b)))
51    }
52
53    /// Compute the less than operator (<) of two expressions.
54    ///
55    /// ```
56    /// # use rust_query::IntoExpr;
57    /// # rust_query::private::doctest::get_txn(|txn| {
58    /// assert_eq!(txn.query_one(2.into_expr().lt(3)), true);
59    /// assert_eq!(txn.query_one(1.into_expr().lt(1)), false);
60    /// assert_eq!(txn.query_one(3.0.into_expr().lt(1.0)), false);
61    /// # });
62    /// ```
63    pub fn lt(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, bool> {
64        let lhs = self.inner.clone();
65        let rhs = rhs.into_expr().inner;
66        Expr::adhoc(move |b| lhs.build_expr(b).lt(rhs.build_expr(b)))
67    }
68
69    /// Compute the less than or equal operator (<=) of two expressions.
70    ///
71    /// ```
72    /// # use rust_query::IntoExpr;
73    /// # rust_query::private::doctest::get_txn(|txn| {
74    /// assert_eq!(txn.query_one(2.into_expr().lte(2)), true);
75    /// assert_eq!(txn.query_one(3.0.into_expr().lte(1.0)), false);
76    /// # });
77    /// ```
78    pub fn lte(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, bool> {
79        let lhs = self.inner.clone();
80        let rhs = rhs.into_expr().inner;
81        Expr::adhoc(move |b| lhs.build_expr(b).lte(rhs.build_expr(b)))
82    }
83
84    /// Compute the greater than operator (>) of two expressions.
85    ///
86    /// ```
87    /// # use rust_query::IntoExpr;
88    /// # rust_query::private::doctest::get_txn(|txn| {
89    /// assert_eq!(txn.query_one(2.into_expr().gt(2)), false);
90    /// assert_eq!(txn.query_one(3.0.into_expr().gt(1.0)), true);
91    /// # });
92    /// ```
93    pub fn gt(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, bool> {
94        let lhs = self.inner.clone();
95        let rhs = rhs.into_expr().inner;
96        Expr::adhoc(move |b| lhs.build_expr(b).gt(rhs.build_expr(b)))
97    }
98
99    /// Compute the greater than or equal (>=) operator of two expressions.
100    ///
101    /// ```
102    /// # use rust_query::IntoExpr;
103    /// # rust_query::private::doctest::get_txn(|txn| {
104    /// assert_eq!(txn.query_one(2.into_expr().gte(3)), false);
105    /// assert_eq!(txn.query_one(3.0.into_expr().gte(3.0)), true);
106    /// # });
107    /// ```
108    pub fn gte(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, bool> {
109        let lhs = self.inner.clone();
110        let rhs = rhs.into_expr().inner;
111        Expr::adhoc(move |b| lhs.build_expr(b).gte(rhs.build_expr(b)))
112    }
113}
114
115impl<'column, S, T: EqTyp + 'static> Expr<'column, S, T> {
116    /// Check whether two expressions are equal.
117    ///
118    /// ```
119    /// # use rust_query::IntoExpr;
120    /// # rust_query::private::doctest::get_txn(|txn| {
121    /// assert_eq!(txn.query_one(2.into_expr().eq(2)), true);
122    /// assert_eq!(txn.query_one(3.0.into_expr().eq(3.0)), true);
123    /// assert_eq!(txn.query_one("test".into_expr().eq("test")), true);
124    /// assert_eq!(txn.query_one(b"test".into_expr().eq(b"test" as &[u8])), true);
125    /// assert_eq!(txn.query_one(false.into_expr().eq(false)), true);
126    ///
127    /// assert_eq!(txn.query_one(1.into_expr().eq(2)), false);
128    /// # });
129    /// ```
130    pub fn eq(&self, rhs: impl IntoExpr<'column, S, Typ = T>) -> Expr<'column, S, bool> {
131        let lhs = self.inner.clone();
132        let rhs = rhs.into_expr().inner;
133        Expr::adhoc(move |b| lhs.build_expr(b).eq(rhs.build_expr(b)))
134    }
135}
136
137impl<'column, S> Expr<'column, S, bool> {
138    /// Checks whether an expression is false.
139    ///
140    /// ```
141    /// # use rust_query::IntoExpr;
142    /// # rust_query::private::doctest::get_txn(|txn| {
143    /// assert_eq!(txn.query_one(true.into_expr().not()), false);
144    /// assert_eq!(txn.query_one(false.into_expr().not()), true);
145    /// # });
146    /// ```
147    pub fn not(&self) -> Expr<'column, S, bool> {
148        let val = self.inner.clone();
149        Expr::adhoc(move |b| val.build_expr(b).not())
150    }
151
152    /// Check if two expressions are both true.
153    ///
154    /// ```
155    /// # use rust_query::IntoExpr;
156    /// # rust_query::private::doctest::get_txn(|txn| {
157    /// assert_eq!(txn.query_one(true.into_expr().and(true)), true);
158    /// assert_eq!(txn.query_one(false.into_expr().and(true)), false);
159    /// assert_eq!(txn.query_one(false.into_expr().and(false)), false);
160    /// # });
161    /// ```
162    pub fn and(&self, rhs: impl IntoExpr<'column, S, Typ = bool>) -> Expr<'column, S, bool> {
163        let lhs = self.inner.clone();
164        let rhs = rhs.into_expr().inner;
165        Expr::adhoc(move |b| lhs.build_expr(b).and(rhs.build_expr(b)))
166    }
167
168    /// Check if one of two expressions is true.
169    ///
170    /// ```
171    /// # use rust_query::IntoExpr;
172    /// # rust_query::private::doctest::get_txn(|txn| {
173    /// assert_eq!(txn.query_one(true.into_expr().or(true)), true);
174    /// assert_eq!(txn.query_one(false.into_expr().or(true)), true);
175    /// assert_eq!(txn.query_one(false.into_expr().or(false)), false);
176    /// # });
177    /// ```
178    pub fn or(&self, rhs: impl IntoExpr<'column, S, Typ = bool>) -> Expr<'column, S, bool> {
179        let lhs = self.inner.clone();
180        let rhs = rhs.into_expr().inner;
181        Expr::adhoc(move |b| lhs.build_expr(b).or(rhs.build_expr(b)))
182    }
183}
184
185impl<'column, S, Typ: MyTyp> Expr<'column, S, Option<Typ>> {
186    /// Use the first expression if it is [Some], otherwise use the second expression.
187    ///
188    /// ```
189    /// # use rust_query::IntoExpr;
190    /// # rust_query::private::doctest::get_txn(|txn| {
191    /// assert_eq!(txn.query_one(Some(10).into_expr().unwrap_or(5)), 10);
192    /// assert_eq!(txn.query_one(None::<String>.into_expr().unwrap_or("foo")), "foo");
193    /// # });
194    /// ```
195    pub fn unwrap_or(&self, rhs: impl IntoExpr<'column, S, Typ = Typ>) -> Expr<'column, S, Typ>
196    where
197        Self: IntoExpr<'column, S, Typ = Option<Typ>>,
198    {
199        let lhs = self.inner.clone();
200        let rhs = rhs.into_expr().inner;
201        let maybe_optional = rhs.maybe_optional();
202        Expr::adhoc_promise(
203            move |b| sea_query::Expr::expr(lhs.build_expr(b)).if_null(rhs.build_expr(b)),
204            maybe_optional,
205        )
206    }
207
208    /// Check that the expression is [Some].
209    ///
210    /// ```
211    /// # use rust_query::IntoExpr;
212    /// # rust_query::private::doctest::get_txn(|txn| {
213    /// assert_eq!(txn.query_one(Some(10).into_expr().is_some()), true);
214    /// assert_eq!(txn.query_one(None::<i64>.into_expr().is_some()), false);
215    /// # });
216    /// ```
217    pub fn is_some(&self) -> Expr<'column, S, bool> {
218        let val = self.inner.clone();
219        Expr::adhoc(move |b| val.build_expr(b).is_not_null())
220    }
221
222    /// Check that the expression is [None].
223    ///
224    /// ```
225    /// # use rust_query::IntoExpr;
226    /// # rust_query::private::doctest::get_txn(|txn| {
227    /// assert_eq!(txn.query_one(Some(10).into_expr().is_none()), false);
228    /// assert_eq!(txn.query_one(None::<i64>.into_expr().is_none()), true);
229    /// # });
230    /// ```
231    pub fn is_none(&self) -> Expr<'column, S, bool> {
232        let val = self.inner.clone();
233        Expr::adhoc(move |b| val.build_expr(b).is_null())
234    }
235}
236
237impl<'column, S> Expr<'column, S, i64> {
238    /// Convert the [i64] expression to [f64] type.
239    ///
240    /// ```
241    /// # use rust_query::IntoExpr;
242    /// # rust_query::private::doctest::get_txn(|txn| {
243    /// assert_eq!(txn.query_one(10.into_expr().as_float()), 10.0);
244    /// # });
245    /// ```
246    pub fn as_float(&self) -> Expr<'column, S, f64> {
247        let val = self.inner.clone();
248        Expr::adhoc(move |b| val.build_expr(b).cast_as(Alias::new("real")))
249    }
250}
251
252impl<'column, S> Expr<'column, S, String> {
253    /// Check if the expression starts with the string pattern.
254    ///
255    /// Matches case-sensitive. The pattern gets automatically escaped.
256    ///
257    /// ```
258    /// # use rust_query::IntoExpr;
259    /// # rust_query::private::doctest::get_txn(|txn| {
260    /// assert_eq!(txn.query_one("hello world".into_expr().starts_with("hello")), true);
261    /// assert_eq!(txn.query_one("hello world".into_expr().starts_with("Hello")), false);
262    /// # });
263    /// ```
264    pub fn starts_with(&self, pattern: impl AsRef<str>) -> Expr<'column, S, bool> {
265        self.glob(format!("{}*", escape_glob(pattern)))
266    }
267
268    /// Check if the expression ends with the string pattern.
269    ///
270    /// Matches case-sensitive. The pattern gets automatically escaped.
271    ///
272    /// ```
273    /// # use rust_query::IntoExpr;
274    /// # rust_query::private::doctest::get_txn(|txn| {
275    /// assert_eq!(txn.query_one("hello world".into_expr().ends_with("world")), true);
276    /// assert_eq!(txn.query_one("hello world".into_expr().ends_with("World")), false);
277    /// # });
278    /// ```
279    pub fn ends_with(&self, pattern: impl AsRef<str>) -> Expr<'column, S, bool> {
280        self.glob(format!("*{}", escape_glob(pattern)))
281    }
282
283    /// Check if the expression contains the string pattern.
284    ///
285    /// Matches case-sensitive. The pattern gets automatically escaped.
286    ///
287    /// ```
288    /// # use rust_query::IntoExpr;
289    /// # rust_query::private::doctest::get_txn(|txn| {
290    /// assert_eq!(txn.query_one("rhubarb".into_expr().contains("bar")), true);
291    /// assert_eq!(txn.query_one("rhubarb".into_expr().contains("Bar")), false);
292    /// # });
293    /// ```
294    pub fn contains(&self, pattern: impl AsRef<str>) -> Expr<'column, S, bool> {
295        self.glob(format!("*{}*", escape_glob(pattern)))
296    }
297
298    /// Check if the expression matches the pattern [sqlite docs](https://www.sqlite.org/lang_expr.html#like).
299    ///
300    /// This is a case-sensitive version of [like](Self::like). It uses Unix file globbing syntax for wild
301    /// cards. `*` matches any sequence of characters and `?` matches any single character. `[0-9]` matches
302    /// any single digit and `[a-z]` matches any single lowercase letter. `^` negates the pattern.
303    ///
304    /// ```
305    /// # use rust_query::IntoExpr;
306    /// # rust_query::private::doctest::get_txn(|txn| {
307    /// assert_eq!(txn.query_one("hello world".into_expr().glob("?ello*")), true);
308    /// assert_eq!(txn.query_one("hello world".into_expr().glob("Hell*")), false);
309    /// # });
310    /// ```
311    pub fn glob(&self, rhs: impl IntoExpr<'column, S, Typ = String>) -> Expr<'column, S, bool> {
312        let lhs = self.inner.clone();
313        let rhs = rhs.into_expr().inner;
314        Expr::adhoc(move |b| sea_query::Expr::expr(lhs.build_expr(b)).glob(rhs.build_expr(b)))
315    }
316
317    /// Check if the expression matches the pattern [sqlite docs](https://www.sqlite.org/lang_expr.html#like).
318    ///
319    /// As noted in the docs, it is **case-insensitive** for ASCII characters. Other characters are case-sensitive.
320    /// For creating patterns it uses `%` as a wildcard for any sequence of characters and `_` for any single character.
321    /// Special characters should be escaped with `\`.
322    ///
323    /// ```
324    /// # use rust_query::IntoExpr;
325    /// # rust_query::private::doctest::get_txn(|txn| {
326    /// assert_eq!(txn.query_one("hello world".into_expr().like("HELLO%")), true);
327    /// assert_eq!(txn.query_one("hello world".into_expr().like("he_o%")), false);
328    /// # });
329    /// ```
330    pub fn like(&self, pattern: impl Into<String>) -> Expr<'column, S, bool> {
331        let lhs = self.inner.clone();
332        let rhs = pattern.into();
333        Expr::adhoc(move |b| {
334            sea_query::Expr::expr(lhs.build_expr(b))
335                .like(sea_query::LikeExpr::new(&rhs).escape('\\'))
336        })
337    }
338}
339
340// This is a copy of the function from the glob crate https://github.com/rust-lang/glob/blob/49ee1e92bd6e8c5854c0b339634f9b4b733aba4f/src/lib.rs#L720-L737.
341fn escape_glob(s: impl AsRef<str>) -> String {
342    let mut escaped = String::new();
343    for c in s.as_ref().chars() {
344        match c {
345            // note that ! does not need escaping because it is only special
346            // inside brackets
347            '?' | '*' | '[' | ']' => {
348                escaped.push('[');
349                escaped.push(c);
350                escaped.push(']');
351            }
352            c => {
353                escaped.push(c);
354            }
355        }
356    }
357    escaped
358}