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, Typed};
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        Expr::adhoc(move |b| sea_query::Expr::expr(lhs.build_expr(b)).if_null(rhs.build_expr(b)))
202    }
203
204    /// Check that the expression is [Some].
205    ///
206    /// ```
207    /// # use rust_query::IntoExpr;
208    /// # rust_query::private::doctest::get_txn(|txn| {
209    /// assert_eq!(txn.query_one(Some(10).into_expr().is_some()), true);
210    /// assert_eq!(txn.query_one(None::<i64>.into_expr().is_some()), false);
211    /// # });
212    /// ```
213    pub fn is_some(&self) -> Expr<'column, S, bool> {
214        let val = self.inner.clone();
215        Expr::adhoc(move |b| val.build_expr(b).is_not_null())
216    }
217
218    /// Check that the expression is [None].
219    ///
220    /// ```
221    /// # use rust_query::IntoExpr;
222    /// # rust_query::private::doctest::get_txn(|txn| {
223    /// assert_eq!(txn.query_one(Some(10).into_expr().is_none()), false);
224    /// assert_eq!(txn.query_one(None::<i64>.into_expr().is_none()), true);
225    /// # });
226    /// ```
227    pub fn is_none(&self) -> Expr<'column, S, bool> {
228        let val = self.inner.clone();
229        Expr::adhoc(move |b| val.build_expr(b).is_null())
230    }
231}
232
233impl<'column, S> Expr<'column, S, i64> {
234    /// Convert the [i64] expression to [f64] type.
235    ///
236    /// ```
237    /// # use rust_query::IntoExpr;
238    /// # rust_query::private::doctest::get_txn(|txn| {
239    /// assert_eq!(txn.query_one(10.into_expr().as_float()), 10.0);
240    /// # });
241    /// ```
242    pub fn as_float(&self) -> Expr<'column, S, f64> {
243        let val = self.inner.clone();
244        Expr::adhoc(move |b| val.build_expr(b).cast_as(Alias::new("real")))
245    }
246}
247
248impl<'column, S> Expr<'column, S, String> {
249    /// Check if the expression starts with the string pattern.
250    ///
251    /// Matches case-sensitive. The pattern gets automatically escaped.
252    ///
253    /// ```
254    /// # use rust_query::IntoExpr;
255    /// # rust_query::private::doctest::get_txn(|txn| {
256    /// assert_eq!(txn.query_one("hello world".into_expr().starts_with("hello")), true);
257    /// assert_eq!(txn.query_one("hello world".into_expr().starts_with("Hello")), false);
258    /// # });
259    /// ```
260    pub fn starts_with(&self, pattern: impl AsRef<str>) -> Expr<'column, S, bool> {
261        self.glob(format!("{}*", escape_glob(pattern)))
262    }
263
264    /// Check if the expression ends with the string pattern.
265    ///
266    /// Matches case-sensitive. The pattern gets automatically escaped.
267    ///
268    /// ```
269    /// # use rust_query::IntoExpr;
270    /// # rust_query::private::doctest::get_txn(|txn| {
271    /// assert_eq!(txn.query_one("hello world".into_expr().ends_with("world")), true);
272    /// assert_eq!(txn.query_one("hello world".into_expr().ends_with("World")), false);
273    /// # });
274    /// ```
275    pub fn ends_with(&self, pattern: impl AsRef<str>) -> Expr<'column, S, bool> {
276        self.glob(format!("*{}", escape_glob(pattern)))
277    }
278
279    /// Check if the expression contains the string pattern.
280    ///
281    /// Matches case-sensitive. The pattern gets automatically escaped.
282    ///
283    /// ```
284    /// # use rust_query::IntoExpr;
285    /// # rust_query::private::doctest::get_txn(|txn| {
286    /// assert_eq!(txn.query_one("rhubarb".into_expr().contains("bar")), true);
287    /// assert_eq!(txn.query_one("rhubarb".into_expr().contains("Bar")), false);
288    /// # });
289    /// ```
290    pub fn contains(&self, pattern: impl AsRef<str>) -> Expr<'column, S, bool> {
291        self.glob(format!("*{}*", escape_glob(pattern)))
292    }
293
294    /// Check if the expression matches the pattern [sqlite docs](https://www.sqlite.org/lang_expr.html#like).
295    ///
296    /// This is a case-sensitive version of [like](Self::like). It uses Unix file globbing syntax for wild
297    /// cards. `*` matches any sequence of characters and `?` matches any single character. `[0-9]` matches
298    /// any single digit and `[a-z]` matches any single lowercase letter. `^` negates the pattern.
299    ///
300    /// ```
301    /// # use rust_query::IntoExpr;
302    /// # rust_query::private::doctest::get_txn(|txn| {
303    /// assert_eq!(txn.query_one("hello world".into_expr().glob("?ello*")), true);
304    /// assert_eq!(txn.query_one("hello world".into_expr().glob("Hell*")), false);
305    /// # });
306    /// ```
307    pub fn glob(&self, rhs: impl IntoExpr<'column, S, Typ = String>) -> Expr<'column, S, bool> {
308        let lhs = self.inner.clone();
309        let rhs = rhs.into_expr().inner;
310        Expr::adhoc(move |b| sea_query::Expr::expr(lhs.build_expr(b)).glob(rhs.build_expr(b)))
311    }
312
313    /// Check if the expression matches the pattern [sqlite docs](https://www.sqlite.org/lang_expr.html#like).
314    ///
315    /// As noted in the docs, it is **case-insensitive** for ASCII characters. Other characters are case-sensitive.
316    /// For creating patterns it uses `%` as a wildcard for any sequence of characters and `_` for any single character.
317    /// Special characters should be escaped with `\`.
318    ///
319    /// ```
320    /// # use rust_query::IntoExpr;
321    /// # rust_query::private::doctest::get_txn(|txn| {
322    /// assert_eq!(txn.query_one("hello world".into_expr().like("HELLO%")), true);
323    /// assert_eq!(txn.query_one("hello world".into_expr().like("he_o%")), false);
324    /// # });
325    /// ```
326    pub fn like(&self, pattern: impl Into<String>) -> Expr<'column, S, bool> {
327        let lhs = self.inner.clone();
328        let rhs = pattern.into();
329        Expr::adhoc(move |b| {
330            sea_query::Expr::expr(lhs.build_expr(b))
331                .like(sea_query::LikeExpr::new(&rhs).escape('\\'))
332        })
333    }
334}
335
336// This is a copy of the function from the glob crate https://github.com/rust-lang/glob/blob/49ee1e92bd6e8c5854c0b339634f9b4b733aba4f/src/lib.rs#L720-L737.
337fn escape_glob(s: impl AsRef<str>) -> String {
338    let mut escaped = String::new();
339    for c in s.as_ref().chars() {
340        match c {
341            // note that ! does not need escaping because it is only special
342            // inside brackets
343            '?' | '*' | '[' | ']' => {
344                escaped.push('[');
345                escaped.push(c);
346                escaped.push(']');
347            }
348            c => {
349                escaped.push(c);
350            }
351        }
352    }
353    escaped
354}