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