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