toasty_core/stmt/expr_like.rs
1use super::Expr;
2
3/// A SQL `LIKE` pattern-match expression: `expr LIKE pattern`.
4///
5/// Returns `true` if `expr` matches `pattern`. The user is responsible for
6/// including any `%` or `_` wildcard characters in `pattern`.
7///
8/// # Examples
9///
10/// ```text
11/// name LIKE 'Al%' // true if name starts with "Al"
12/// name LIKE '%son' // true if name ends with "son"
13/// ```
14#[derive(Debug, Clone, PartialEq)]
15pub struct ExprLike {
16 /// The attribute to test.
17 pub expr: Box<Expr>,
18
19 /// The LIKE pattern (including any % or _ wildcards).
20 pub pattern: Box<Expr>,
21
22 /// Optional escape character. When `Some(c)`, occurrences of `c` in the
23 /// pattern make the following `%`, `_`, or `c` match literally, and the
24 /// serializer emits an `ESCAPE 'c'` clause.
25 pub escape: Option<char>,
26
27 /// Whether the match is case-insensitive.
28 pub case_insensitive: bool,
29}
30
31impl Expr {
32 /// Creates a `expr LIKE pattern` expression with no escape character.
33 pub fn like(expr: impl Into<Self>, pattern: impl Into<Self>) -> Self {
34 ExprLike {
35 expr: Box::new(expr.into()),
36 pattern: Box::new(pattern.into()),
37 escape: None,
38 case_insensitive: false,
39 }
40 .into()
41 }
42
43 /// Creates a `expr ILIKE pattern` expression with no escape character.
44 pub fn ilike(expr: impl Into<Self>, pattern: impl Into<Self>) -> Self {
45 ExprLike {
46 expr: Box::new(expr.into()),
47 pattern: Box::new(pattern.into()),
48 escape: None,
49 case_insensitive: true,
50 }
51 .into()
52 }
53
54 /// Creates a `expr LIKE pattern` expression with escape character.
55 pub fn like_with_escape(expr: impl Into<Self>, pattern: impl Into<Self>, escape: char) -> Self {
56 ExprLike {
57 expr: Box::new(expr.into()),
58 pattern: Box::new(pattern.into()),
59 escape: Some(escape),
60 case_insensitive: false,
61 }
62 .into()
63 }
64
65 /// Creates a `expr ILIKE pattern` expression with escape character.
66 pub fn ilike_with_escape(
67 expr: impl Into<Self>,
68 pattern: impl Into<Self>,
69 escape: char,
70 ) -> Self {
71 ExprLike {
72 expr: Box::new(expr.into()),
73 pattern: Box::new(pattern.into()),
74 escape: Some(escape),
75 case_insensitive: true,
76 }
77 .into()
78 }
79}
80
81impl From<ExprLike> for Expr {
82 fn from(value: ExprLike) -> Self {
83 Self::Like(value)
84 }
85}