pub mod like;
mod order_by;
use std::marker::PhantomData;
use std::ops::{Add, Div, Mul, Sub};
use cot::db::query::{IntoField, QueryBuildingError};
use cot::db::{DbFieldValue, DbValue, FromDbValue, Identifier, ToDbFieldValue};
pub use like::ExprLike;
use like::{CaseSensitivity, LikeExprBuilder, LikeMode};
pub use order_by::{ExprSort, NullsOrder, OrderByExpr, SortOrder};
use sea_query::{ExprTrait, IntoColumnRef, SimpleExpr};
use crate::db::ToDbValue;
use crate::db::query::expr::order_by::OrderTarget;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Expr {
Field(Identifier),
Value(DbValue),
And(Box<Expr>, Box<Expr>),
Or(Box<Expr>, Box<Expr>),
Eq(Box<Expr>, Box<Expr>),
Ne(Box<Expr>, Box<Expr>),
Lt(Box<Expr>, Box<Expr>),
Lte(Box<Expr>, Box<Expr>),
Gt(Box<Expr>, Box<Expr>),
Gte(Box<Expr>, Box<Expr>),
Add(Box<Expr>, Box<Expr>),
Sub(Box<Expr>, Box<Expr>),
Mul(Box<Expr>, Box<Expr>),
Div(Box<Expr>, Box<Expr>),
Contains(Box<Expr>, Box<Expr>, CaseSensitivity),
StartsWith(Box<Expr>, Box<Expr>, CaseSensitivity),
EndsWith(Box<Expr>, Box<Expr>, CaseSensitivity),
RawLike(Box<Expr>, Box<Expr>, CaseSensitivity),
}
impl Expr {
#[must_use]
pub fn field<T: Into<Identifier>>(identifier: T) -> Self {
Self::Field(identifier.into())
}
#[must_use]
#[expect(clippy::needless_pass_by_value)]
pub fn value<T: ToDbFieldValue>(value: T) -> Self {
match value.to_db_field_value() {
DbFieldValue::Value(value) => Self::Value(value),
DbFieldValue::Auto => panic!("Cannot create query with a non-value field"),
}
}
#[must_use]
pub fn and(lhs: Self, rhs: Self) -> Self {
Self::And(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn or(lhs: Self, rhs: Self) -> Self {
Self::Or(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn eq(lhs: Self, rhs: Self) -> Self {
Self::Eq(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn ne(lhs: Self, rhs: Self) -> Self {
Self::Ne(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn lt(lhs: Self, rhs: Self) -> Self {
Self::Lt(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn lte(lhs: Self, rhs: Self) -> Self {
Self::Lte(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn gt(lhs: Self, rhs: Self) -> Self {
Self::Gt(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn gte(lhs: Self, rhs: Self) -> Self {
Self::Gte(Box::new(lhs), Box::new(rhs))
}
#[expect(clippy::should_implement_trait)]
#[must_use]
pub fn add(lhs: Self, rhs: Self) -> Self {
Self::Add(Box::new(lhs), Box::new(rhs))
}
#[expect(clippy::should_implement_trait)]
#[must_use]
pub fn sub(lhs: Self, rhs: Self) -> Self {
Self::Sub(Box::new(lhs), Box::new(rhs))
}
#[expect(clippy::should_implement_trait)]
#[must_use]
pub fn mul(lhs: Self, rhs: Self) -> Self {
Self::Mul(Box::new(lhs), Box::new(rhs))
}
#[expect(clippy::should_implement_trait)]
#[must_use]
pub fn div(lhs: Self, rhs: Self) -> Self {
Self::Div(Box::new(lhs), Box::new(rhs))
}
#[must_use]
pub fn contains(lhs: Self, rhs: Self) -> Self {
Self::Contains(Box::new(lhs), Box::new(rhs), CaseSensitivity::Sensitive)
}
#[must_use]
pub fn icontains(lhs: Self, rhs: Self) -> Self {
Self::Contains(Box::new(lhs), Box::new(rhs), CaseSensitivity::Insensitive)
}
#[must_use]
pub fn starts_with(lhs: Self, rhs: Self) -> Self {
Self::StartsWith(Box::new(lhs), Box::new(rhs), CaseSensitivity::Sensitive)
}
#[must_use]
pub fn istarts_with(lhs: Self, rhs: Self) -> Self {
Self::StartsWith(Box::new(lhs), Box::new(rhs), CaseSensitivity::Insensitive)
}
#[must_use]
pub fn ends_with(lhs: Self, rhs: Self) -> Self {
Self::EndsWith(Box::new(lhs), Box::new(rhs), CaseSensitivity::Sensitive)
}
#[must_use]
pub fn iends_with(lhs: Self, rhs: Self) -> Self {
Self::EndsWith(Box::new(lhs), Box::new(rhs), CaseSensitivity::Insensitive)
}
#[must_use]
pub fn raw_like(lhs: Self, rhs: Self) -> Self {
Self::RawLike(Box::new(lhs), Box::new(rhs), CaseSensitivity::Sensitive)
}
#[must_use]
pub fn iraw_like(lhs: Self, rhs: Self) -> Self {
Self::RawLike(Box::new(lhs), Box::new(rhs), CaseSensitivity::Insensitive)
}
#[must_use]
pub fn asc(self) -> OrderByExpr {
OrderByExpr::directional(OrderTarget::Expression(self), SortOrder::Asc)
}
#[must_use]
pub fn desc(self) -> OrderByExpr {
OrderByExpr::directional(OrderTarget::Expression(self), SortOrder::Desc)
}
#[must_use]
pub fn by_values<I>(self, values: I) -> OrderByExpr
where
I: IntoIterator,
I::Item: ToDbValue,
{
let values = values.into_iter().map(|v| v.to_db_value()).collect();
OrderByExpr::by_values(OrderTarget::Expression(self), sea_query::Values(values))
}
pub fn as_sea_query_expr(
&self,
sql_builder: &dyn SqlQueryBuilder,
) -> Result<SimpleExpr, QueryBuildingError> {
match self {
Self::Field(identifier) => Ok((*identifier).into_column_ref().into()),
Self::Value(value) => Ok((*value).clone().into()),
Self::And(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.and(rhs.as_sea_query_expr(sql_builder)?)),
Self::Or(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.or(rhs.as_sea_query_expr(sql_builder)?)),
Self::Eq(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.eq(rhs.as_sea_query_expr(sql_builder)?)),
Self::Ne(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.ne(rhs.as_sea_query_expr(sql_builder)?)),
Self::Lt(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.lt(rhs.as_sea_query_expr(sql_builder)?)),
Self::Lte(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.lte(rhs.as_sea_query_expr(sql_builder)?)),
Self::Gt(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.gt(rhs.as_sea_query_expr(sql_builder)?)),
Self::Gte(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.gte(rhs.as_sea_query_expr(sql_builder)?)),
Self::Add(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.add(rhs.as_sea_query_expr(sql_builder)?)),
Self::Sub(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.sub(rhs.as_sea_query_expr(sql_builder)?)),
Self::Mul(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.mul(rhs.as_sea_query_expr(sql_builder)?)),
Self::Div(lhs, rhs) => Ok(lhs
.as_sea_query_expr(sql_builder)?
.div(rhs.as_sea_query_expr(sql_builder)?)),
Self::Contains(lhs, rhs, case_sensitivity) => {
like::like_expr(sql_builder, lhs, rhs, LikeMode::Contains, *case_sensitivity)
}
Self::StartsWith(lhs, rhs, case_sensitivity) => like::like_expr(
sql_builder,
lhs,
rhs,
LikeMode::StartsWith,
*case_sensitivity,
),
Self::EndsWith(lhs, rhs, case_sensitivity) => {
like::like_expr(sql_builder, lhs, rhs, LikeMode::EndsWith, *case_sensitivity)
}
Self::RawLike(lhs, rhs, case_sensitivity) => {
like::like_expr(sql_builder, lhs, rhs, LikeMode::Raw, *case_sensitivity)
}
}
}
}
#[derive(Debug)]
pub struct FieldRef<T> {
identifier: Identifier,
phantom_data: PhantomData<T>,
}
impl<T: FromDbValue + ToDbFieldValue> FieldRef<T> {
#[must_use]
pub const fn new(identifier: Identifier) -> Self {
Self {
identifier,
phantom_data: PhantomData,
}
}
}
impl<T> FieldRef<T> {
#[must_use]
pub fn as_expr(&self) -> Expr {
Expr::Field(self.identifier)
}
pub(crate) fn identifier(&self) -> Identifier {
self.identifier
}
}
impl<Lhs, Rhs> Add<FieldRef<Rhs>> for FieldRef<Lhs> {
type Output = Expr;
fn add(self, rhs: FieldRef<Rhs>) -> Self::Output {
Expr::add(self.as_expr(), rhs.as_expr())
}
}
impl<Lhs, Rhs> Sub<FieldRef<Rhs>> for FieldRef<Lhs> {
type Output = Expr;
fn sub(self, rhs: FieldRef<Rhs>) -> Self::Output {
Expr::sub(self.as_expr(), rhs.as_expr())
}
}
impl<Lhs, Rhs> Mul<FieldRef<Rhs>> for FieldRef<Lhs> {
type Output = Expr;
fn mul(self, rhs: FieldRef<Rhs>) -> Self::Output {
Expr::mul(self.as_expr(), rhs.as_expr())
}
}
impl<Lhs, Rhs> Div<FieldRef<Rhs>> for FieldRef<Lhs> {
type Output = Expr;
fn div(self, rhs: FieldRef<Rhs>) -> Self::Output {
Expr::div(self.as_expr(), rhs.as_expr())
}
}
pub trait ExprEq<T> {
fn eq<V: IntoField<T>>(self, other: V) -> Expr;
fn ne<V: IntoField<T>>(self, other: V) -> Expr;
}
impl<T: ToDbFieldValue + 'static> ExprEq<T> for FieldRef<T> {
fn eq<V: IntoField<T>>(self, other: V) -> Expr {
Expr::eq(self.as_expr(), Expr::value(other.into_field()))
}
fn ne<V: IntoField<T>>(self, other: V) -> Expr {
Expr::ne(self.as_expr(), Expr::value(other.into_field()))
}
}
pub trait ExprAdd<T> {
fn add<V: Into<T>>(self, other: V) -> Expr;
}
pub trait ExprSub<T> {
fn sub<V: Into<T>>(self, other: V) -> Expr;
}
pub trait ExprMul<T> {
fn mul<V: Into<T>>(self, other: V) -> Expr;
}
pub trait ExprDiv<T> {
fn div<V: Into<T>>(self, other: V) -> Expr;
}
pub trait ExprOrd<T> {
fn lt<V: IntoField<T>>(self, other: V) -> Expr;
fn lte<V: IntoField<T>>(self, other: V) -> Expr;
fn gt<V: IntoField<T>>(self, other: V) -> Expr;
fn gte<V: IntoField<T>>(self, other: V) -> Expr;
}
impl<T: ToDbFieldValue + Ord + 'static> ExprOrd<T> for FieldRef<T> {
fn lt<V: IntoField<T>>(self, other: V) -> Expr {
Expr::lt(self.as_expr(), Expr::value(other.into_field()))
}
fn lte<V: IntoField<T>>(self, other: V) -> Expr {
Expr::lte(self.as_expr(), Expr::value(other.into_field()))
}
fn gt<V: IntoField<T>>(self, other: V) -> Expr {
Expr::gt(self.as_expr(), Expr::value(other.into_field()))
}
fn gte<V: IntoField<T>>(self, other: V) -> Expr {
Expr::gte(self.as_expr(), Expr::value(other.into_field()))
}
}
pub trait SqlQueryBuilder: LikeExprBuilder {}
impl<T> SqlQueryBuilder for T where T: LikeExprBuilder {}
macro_rules! impl_expr {
($ty:ty, $trait:ident, $method:ident) => {
impl $trait<$ty> for FieldRef<$ty> {
fn $method<V: Into<$ty>>(self, other: V) -> Expr {
Expr::$method(self.as_expr(), Expr::value(other.into()))
}
}
};
}
macro_rules! impl_num_expr {
($ty:ty) => {
impl_expr!($ty, ExprAdd, add);
impl_expr!($ty, ExprSub, sub);
impl_expr!($ty, ExprMul, mul);
impl_expr!($ty, ExprDiv, div);
};
}
impl_num_expr!(i8);
impl_num_expr!(i16);
impl_num_expr!(i32);
impl_num_expr!(i64);
impl_num_expr!(u8);
impl_num_expr!(u16);
impl_num_expr!(u32);
impl_num_expr!(u64);
impl_num_expr!(f32);
impl_num_expr!(f64);
#[cfg(test)]
mod test {
use super::*;
#[test]
fn expr_field() {
let expr = Expr::field("name");
if let Expr::Field(identifier) = expr {
assert_eq!(identifier.to_string(), "name");
} else {
panic!("Expected Expr::Field");
}
}
#[test]
fn expr_value() {
let expr = Expr::value(30);
if let Expr::Value(value) = expr {
assert_eq!(value.to_string(), "30");
} else {
panic!("Expected Expr::Value");
}
}
macro_rules! test_expr_constructor {
($test_name:ident, $match:ident, $constructor:ident) => {
#[test]
fn $test_name() {
let expr = Expr::$constructor(Expr::field("name"), Expr::value("John"));
if let Expr::$match(lhs, rhs) = expr {
assert!(matches!(*lhs, Expr::Field(_)));
assert!(matches!(*rhs, Expr::Value(_)));
} else {
panic!(concat!("Expected Expr::", stringify!($match)));
}
}
};
}
test_expr_constructor!(expr_and, And, and);
test_expr_constructor!(expr_or, Or, or);
test_expr_constructor!(expr_eq, Eq, eq);
test_expr_constructor!(expr_ne, Ne, ne);
test_expr_constructor!(expr_lt, Lt, lt);
test_expr_constructor!(expr_lte, Lte, lte);
test_expr_constructor!(expr_gt, Gt, gt);
test_expr_constructor!(expr_gte, Gte, gte);
test_expr_constructor!(expr_add, Add, add);
test_expr_constructor!(expr_sub, Sub, sub);
test_expr_constructor!(expr_mul, Mul, mul);
test_expr_constructor!(expr_div, Div, div);
#[test]
fn field_ref_sub_operator_builds_sub_expr() {
let x: FieldRef<i32> = FieldRef::new(Identifier::new("x"));
let y: FieldRef<i32> = FieldRef::new(Identifier::new("y"));
assert!(matches!(x - y, Expr::Sub(_, _)));
}
#[test]
fn field_ref_mul_operator_builds_mul_expr() {
let x: FieldRef<i32> = FieldRef::new(Identifier::new("x"));
let y: FieldRef<i32> = FieldRef::new(Identifier::new("y"));
assert!(matches!(x * y, Expr::Mul(_, _)));
}
#[test]
fn field_ref_div_operator_builds_div_expr() {
let x: FieldRef<i32> = FieldRef::new(Identifier::new("x"));
let y: FieldRef<i32> = FieldRef::new(Identifier::new("y"));
assert!(matches!(x / y, Expr::Div(_, _)));
}
}