use cot::db::query::expr::{FieldRef, SqlQueryBuilder};
use cot::db::query::{Expr, QueryBuildingError};
use sea_query::{ExprTrait, SimpleExpr};
use crate::db::TextField;
pub(crate) const LIKE_ESCAPE_CHAR: char = '\\';
pub trait ExprLike<T> {
fn contains<V: Into<String>>(self, other: V) -> Expr;
fn icontains<V: Into<String>>(self, other: V) -> Expr;
fn starts_with<V: Into<String>>(self, other: V) -> Expr;
fn istarts_with<V: Into<String>>(self, other: V) -> Expr;
fn ends_with<V: Into<String>>(self, other: V) -> Expr;
fn iends_with<V: Into<String>>(self, other: V) -> Expr;
fn raw_like<V: Into<String>>(self, other: V) -> Expr;
fn iraw_like<V: Into<String>>(self, other: V) -> Expr;
}
impl<T: TextField + 'static> ExprLike<T> for FieldRef<T> {
fn contains<V: Into<String>>(self, other: V) -> Expr {
Expr::contains(self.as_expr(), Expr::value(other.into()))
}
fn icontains<V: Into<String>>(self, other: V) -> Expr {
Expr::icontains(self.as_expr(), Expr::value(other.into()))
}
fn starts_with<V: Into<String>>(self, other: V) -> Expr {
Expr::starts_with(self.as_expr(), Expr::value(other.into()))
}
fn istarts_with<V: Into<String>>(self, other: V) -> Expr {
Expr::istarts_with(self.as_expr(), Expr::value(other.into()))
}
fn ends_with<V: Into<String>>(self, other: V) -> Expr {
Expr::ends_with(self.as_expr(), Expr::value(other.into()))
}
fn iends_with<V: Into<String>>(self, other: V) -> Expr {
Expr::iends_with(self.as_expr(), Expr::value(other.into()))
}
fn raw_like<V: Into<String>>(self, other: V) -> Expr {
Expr::raw_like(self.as_expr(), Expr::value(other.into()))
}
fn iraw_like<V: Into<String>>(self, other: V) -> Expr {
Expr::iraw_like(self.as_expr(), Expr::value(other.into()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum LikeMode {
Contains,
StartsWith,
EndsWith,
Raw,
}
fn escape_literal(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for c in value.chars() {
if matches!(c, '*' | '?' | LIKE_ESCAPE_CHAR) {
escaped.push(LIKE_ESCAPE_CHAR);
}
escaped.push(c);
}
escaped
}
pub(crate) fn to_sql_like(glob: &str) -> String {
let mut escaped = String::with_capacity(glob.len());
let mut chars = glob.chars();
while let Some(ch) = chars.next() {
match ch {
LIKE_ESCAPE_CHAR => {
if let Some(ch) = chars.next() {
push_like_literal(&mut escaped, ch);
}
}
'*' => escaped.push('%'),
'?' => escaped.push('_'),
other => push_like_literal(&mut escaped, other),
}
}
escaped
}
fn push_like_literal(out: &mut String, ch: char) {
if matches!(ch, '%' | '_' | LIKE_ESCAPE_CHAR) {
out.push(LIKE_ESCAPE_CHAR);
}
out.push(ch);
}
pub(crate) fn like_expr(
sql_builder: &dyn SqlQueryBuilder,
lhs: &Expr,
rhs: &Expr,
mode: LikeMode,
case_sensitivity: CaseSensitivity,
) -> Result<SimpleExpr, QueryBuildingError> {
let lhs_expr = lhs.as_sea_query_expr(sql_builder)?;
let Expr::Value(value) = rhs else {
return Ok(sea_query::Expr::val(1).eq(0));
};
let sea_value: sea_query::Value = value.clone();
let sea_query::Value::String(Some(text)) = sea_value else {
return Ok(sea_query::Expr::val(1).eq(0));
};
let glob_pattern = match mode {
LikeMode::Contains => format!("*{}*", escape_literal(&text)),
LikeMode::EndsWith => format!("*{}", escape_literal(&text)),
LikeMode::StartsWith => format!("{}*", escape_literal(&text)),
LikeMode::Raw => text.clone(),
};
sql_builder.like_expr(lhs_expr, &glob_pattern, case_sensitivity)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CaseSensitivity {
Sensitive,
Insensitive,
}
pub trait LikeExprBuilder {
fn like_expr(
&self,
lhs: SimpleExpr,
glob_pattern: &str,
case_sensitivity: CaseSensitivity,
) -> Result<SimpleExpr, QueryBuildingError>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_glob_wildcards_to_sql_wildcards() {
assert_eq!(to_sql_like("*foo*"), "%foo%");
assert_eq!(to_sql_like("foo*"), "foo%");
assert_eq!(to_sql_like("*foo"), "%foo");
assert_eq!(to_sql_like("f?o"), "f_o");
assert_eq!(to_sql_like("f??o"), "f__o");
assert_eq!(to_sql_like("100% off"), "100\\% off");
assert_eq!(to_sql_like("under_score"), "under\\_score");
assert_eq!(to_sql_like("a\\*b"), "a*b");
assert_eq!(to_sql_like("a\\?b"), "a?b");
assert_eq!(to_sql_like("C:\\\\Users"), "C:\\\\Users");
assert_eq!(to_sql_like(""), "");
assert_eq!(to_sql_like("foo\\"), "foo");
assert_eq!(to_sql_like("café*"), "café%");
assert_eq!(to_sql_like("日本語"), "日本語");
}
}