piqel/sql/
where_cond.rs

1use crate::sql::Env;
2use crate::sql::Expr;
3use crate::sql::Selector;
4use crate::value::PqlValue;
5
6#[derive(Debug, Clone, PartialEq)]
7pub enum WhereCond {
8    Eq { expr: Expr, right: PqlValue },
9    Neq { expr: Expr, right: PqlValue },
10    Like { expr: Expr, right: String },
11}
12
13impl Default for WhereCond {
14    fn default() -> Self {
15        Self::Eq {
16            expr: Expr::default(),
17            right: PqlValue::default(),
18        }
19    }
20}
21
22impl WhereCond {
23    pub fn as_expr(&self) -> Expr {
24        match &self {
25            Self::Eq { expr, right: _ } => expr.to_owned(),
26            Self::Neq { expr, right: _ } => expr.to_owned(),
27            Self::Like { expr, right: _ } => expr.to_owned(),
28        }
29    }
30
31    pub fn expand_fullpath(self, env: &Env) -> Self {
32        match self {
33            Self::Eq { expr, right } => Self::Eq {
34                expr: expr.expand_fullpath(env),
35                right,
36            },
37            Self::Neq { expr, right } => Self::Eq {
38                expr: expr.expand_fullpath(env),
39                right,
40            },
41            Self::Like { expr, right } => Self::Like {
42                expr: expr.expand_fullpath(env),
43                right,
44            },
45        }
46    }
47
48    pub fn to_path(&self) -> Option<Selector> {
49        self.as_expr().to_path()
50    }
51}
52
53pub fn re_from_str(pattern: &str) -> regex::Regex {
54    let regex_pattern = match (pattern.starts_with("%"), pattern.ends_with("%")) {
55        (true, true) => {
56            format!("{}", pattern.trim_start_matches("%").trim_end_matches("%"))
57        }
58        (true, false) => format!("{}$", pattern.trim_start_matches("%")),
59        (false, true) => format!("^{}", pattern.trim_end_matches("%")),
60        (false, false) => format!("^{}$", pattern),
61    };
62    let re = regex::Regex::new(&regex_pattern).unwrap();
63    re
64}