use core::{fmt::Display, marker::PhantomData};
use super::{Carrier, SqlConjunction, push_cmp, push_in};
use crate::{
BooleanFilter,
comparison::{At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter},
graphql::filter::{map_operand, map_operands},
};
comparison_kind! {
SqlBooleanComparison {
one { eq, ne }
many { in_, not_in }
}
}
impl<V, Db> SqlBooleanComparison<V, Db> {
pub fn try_from_filter_with<E, F>(filter: BooleanFilter, mut f: F) -> Result<Self, E>
where
F: FnMut(bool) -> Result<V, E>,
{
Ok(Self {
eq: map_operand(filter.eq, &mut f)?,
ne: map_operand(filter.ne, &mut f)?,
in_: map_operands(filter.in_, &mut f)?,
not_in: map_operands(filter.not_in, &mut f)?,
db: PhantomData,
})
}
}
impl<V, Db> ToDatabaseComparison<V, Db> for BooleanFilter
where
Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
V: Carrier<Db>,
{
type Comparison = SqlBooleanComparison<V, Db>;
}
impl<V, Db> TryFromFilter<BooleanFilter> for SqlBooleanComparison<V, Db>
where
V: TryFrom<bool>,
{
type Error = V::Error;
fn try_from_filter(filter: BooleanFilter) -> Result<Self, Self::Error> {
Self::try_from_filter_with(filter, V::try_from)
}
}
impl<V, Db> ComplexComparison<Db> for SqlBooleanComparison<V, Db>
where
Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
V: Carrier<Db>,
{
#[inline]
fn conjuncts(&self) -> usize {
Self::conjuncts(self)
}
fn apply<'q>(
&'q self,
at: At<'_>,
mut builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error> {
if let Some(value) = &self.eq {
push_cmp(builder.open(), at, " = ", value, false);
}
if let Some(value) = &self.ne {
push_cmp(builder.open(), at, " = ", value, true);
}
if let Some(values) = &self.in_ {
push_in(builder.open(), at, values, false);
}
if let Some(values) = &self.not_in {
push_in(builder.open(), at, values, true);
}
Ok(builder)
}
}
#[cfg(test)]
mod tests;