Skip to main content

sql_builder/expr/enum/
conversions.rs

1//! What converts into an [`Expr`]: any value, the parts an expression is built from, and
2//! whole statements, which become subqueries.
3
4use super::*;
5
6/// Anything that is a [`Value`] is a bound value.
7impl<T> From<T> for Expr
8where
9    T: Into<Value>,
10{
11    fn from(v: T) -> Self {
12        Self::Value(v.into())
13    }
14}
15
16/// Each type is the payload of one `Expr` variant.
17macro_rules! into_variant {
18    ($($ty:ty => $variant:ident),+ $(,)?) => {$(
19        impl From<$ty> for Expr {
20            fn from(v: $ty) -> Self {
21                Self::$variant(v)
22            }
23        }
24    )+};
25}
26
27into_variant! {
28    Vec<Value> => Values,
29    FunctionCall => FunctionCall,
30    ColumnRef => Column,
31    Keyword => Keyword,
32    TypeRef => TypeName,
33}
34
35/// A statement used as an expression is an unnamed subquery.
36impl From<SubQueryStatement> for Expr {
37    fn from(v: SubQueryStatement) -> Self {
38        Self::SubQuery(None, Box::new(v))
39    }
40}
41
42macro_rules! into_subquery {
43    ($($ty:ty),+ $(,)?) => {$(
44        impl From<$ty> for Expr {
45            fn from(v: $ty) -> Self {
46                SubQueryStatement::from(v).into()
47            }
48        }
49    )+};
50}
51
52into_subquery!(
53    SelectStatement,
54    InsertStatement,
55    UpdateStatement,
56    DeleteStatement,
57    WithQuery,
58);
59
60/// The pattern, followed by `ESCAPE '<char>'` when it names an escape character.
61impl From<LikeExpr> for Expr {
62    fn from(like: LikeExpr) -> Self {
63        let pattern = like.pattern.into();
64        match like.escape {
65            Some(escape) => Self::Binary(
66                Box::new(pattern),
67                BinOper::Escape,
68                Box::new(Self::Constant(escape.into())),
69            ),
70            None => pattern,
71        }
72    }
73}