Debian Codegraph @

src/expression_methods/escape_expression_methods.rs

raw
1 use crate::dsl;
2 use crate::expression::grouped::Grouped;
3 use crate::expression::operators::{Escape, Like, NotLike};
4 use crate::expression::IntoSql;
5 use crate::sql_types::VarChar;
6
7 /// Adds the `escape` method to `LIKE` and `NOT LIKE`. This is used to specify
8 /// the escape character for the pattern.
9 ///
10 /// By default, the escape character is `\` on most backends. On SQLite,
11 /// there is no default escape character.
12 ///
13 /// # Example
14 ///
15 /// ```rust
16 /// # include!("../doctest_setup.rs");
17 /// #
18 /// # fn main() {
19 /// # use schema::users::dsl::*;
20 /// # use diesel::insert_into;
21 /// # let connection = &mut establish_connection();
22 /// # insert_into(users).values(name.eq("Ha%%0r"))
23 /// # .execute(connection).unwrap();
24 /// let users_with_percent = users
25 /// .select(name)
26 /// .filter(name.like("%😀%%").escape('😀'))
27 /// .load(connection);
28 /// let users_without_percent = users
29 /// .select(name)
30 /// .filter(name.not_like("%a%%").escape('a'))
31 /// .load(connection);
32 /// assert_eq!(Ok(vec![String::from("Ha%%0r")]), users_with_percent);
33 /// assert_eq!(
34 /// Ok(vec![String::from("Sean"), String::from("Tess")]),
35 /// users_without_percent
36 /// );
37 /// # }
38 /// ```
39 pub trait EscapeExpressionMethods: Sized {
40 #[doc(hidden)]
41 type TextExpression;
42
43 /// See the trait documentation.
44 fn escape(self, _character: char) -> dsl::Escape<Self>;
45 }
46
47 impl<T, U> EscapeExpressionMethods for Grouped<Like<T, U>> {
48 type TextExpression = Like<T, U>;
49
50 fn escape(self, character: char) -> dsl::Escape<Self> {
51 Grouped(Escape::new(
52 self.0,
53 character.to_string().into_sql::<VarChar>(),
54 ))
55 }
56 }
57
58 impl<T, U> EscapeExpressionMethods for Grouped<NotLike<T, U>> {
59 type TextExpression = NotLike<T, U>;
60
61 fn escape(self, character: char) -> dsl::Escape<Self> {
62 Grouped(Escape::new(
63 self.0,
64 character.to_string().into_sql::<VarChar>(),
65 ))
66 }
67 }