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/// # fn main() {
20/// # use schema::users::dsl::*;
21/// # use diesel::insert_into;
22/// # let connection = &mut establish_connection();
23/// # insert_into(users).values(name.eq("Ha%%0r"))
24/// # .execute(connection).unwrap();
25/// let users_with_percent = users
26/// .select(name)
27/// .filter(name.like("%😀%%").escape('😀'))
28/// .load(connection);
29/// let users_without_percent = users
30/// .select(name)
31/// .filter(name.not_like("%a%%").escape('a'))
32/// .load(connection);
33/// assert_eq!(Ok(vec![String::from("Ha%%0r")]), users_with_percent);
34/// assert_eq!(
35/// Ok(vec![String::from("Sean"), String::from("Tess")]),
36/// users_without_percent
37/// );
38/// # }
39/// ```
40pub trait EscapeExpressionMethods: Sized {
41 #[doc(hidden)]
42 type TextExpression;
43
44 /// See the trait documentation.
45 fn escape(self, _character: char) -> dsl::Escape<Self>;
46}
47
48impl<T, U> EscapeExpressionMethods for Grouped<Like<T, U>> {
49 type TextExpression = Like<T, U>;
50
51 fn escape(self, character: char) -> dsl::Escape<Self> {
52 Grouped(Escape::new(
53 self.0,
54 character.to_string().into_sql::<VarChar>(),
55 ))
56 }
57}
58
59impl<T, U> EscapeExpressionMethods for Grouped<NotLike<T, U>> {
60 type TextExpression = NotLike<T, U>;
61
62 fn escape(self, character: char) -> dsl::Escape<Self> {
63 Grouped(Escape::new(
64 self.0,
65 character.to_string().into_sql::<VarChar>(),
66 ))
67 }
68}