use core::marker::PhantomData;
use smol_bytes::Utf8BytesMut;
use super::{
Carrier, ELEMENT_ALIAS, ELEMENT_VALUE, ListCrossingError, QuoteIdent, SetCrossingError,
SqlConjunction, SqlCountComparison, SqlLoweringError, StrategyOver,
collection::{cross_count, cross_element, flatten_list, flatten_set},
dialect::{push_quoted_ident, push_quoted_qualified, push_quoted_scope},
not_wrapped, push_count_slots, push_element_scope, quote_ident, quote_qualified,
};
use crate::{
FieldName, ListFilter, QuantifiedFilter, SetFilter, TryMapFilter,
comparison::{At, Backend, ComplexComparison, Path, TryFromFilter},
};
comparison_kind! {
SqlEdgeComparison {
one { has_element }
many { eq, ne, gt, gte, lt, lte }
element { any: C }
cardinality { count }
}
}
comparison_kind! {
SqlEdgeSetComparison {
one { has_element }
many { eq, ne, encloses, enclosed_by, overlaps }
element { any: C }
cardinality { count }
}
}
impl<V, C, Db> SqlEdgeComparison<V, C, Db> {
pub fn try_from_filter_with<D, VF, E, F>(
filter: ListFilter<D, VF>,
f: F,
) -> Result<Self, ListCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
where
F: Fn(D) -> Result<V, E>,
VF: TryMapFilter<D, V>,
C: TryFromFilter<VF::Mapped>,
{
Self::try_from_filter_with_element(filter, &f, |element| {
let stored = element
.try_map_filter(&f)
.map_err(ListCrossingError::Operand)?;
C::try_from_filter(stored).map_err(ListCrossingError::Element)
})
.map_err(flatten_list)
}
pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
filter: ListFilter<D, VF>,
f: F,
g: G,
) -> Result<Self, ListCrossingError<E, X>>
where
F: FnMut(D) -> Result<V, E>,
G: FnOnce(VF) -> Result<C, X>,
{
let stored = filter.try_map(f).map_err(ListCrossingError::Operand)?;
let any = cross_element(stored.any, g).map_err(ListCrossingError::Element)?;
let count = cross_count(stored.count).map_err(ListCrossingError::Cardinality)?;
Ok(Self {
has_element: stored.has_element,
eq: stored.eq,
ne: stored.ne,
gt: stored.gt,
gte: stored.gte,
lt: stored.lt,
lte: stored.lte,
any,
count,
db: PhantomData,
})
}
}
impl<V, C, Db> SqlEdgeSetComparison<V, C, Db> {
pub fn try_from_filter_with<D, VF, E, F>(
filter: SetFilter<D, VF>,
f: F,
) -> Result<Self, SetCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
where
F: Fn(D) -> Result<V, E>,
VF: TryMapFilter<D, V>,
C: TryFromFilter<VF::Mapped>,
{
Self::try_from_filter_with_element(filter, &f, |element| {
let stored = element
.try_map_filter(&f)
.map_err(SetCrossingError::Operand)?;
C::try_from_filter(stored).map_err(SetCrossingError::Element)
})
.map_err(flatten_set)
}
pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
filter: SetFilter<D, VF>,
f: F,
g: G,
) -> Result<Self, SetCrossingError<E, X>>
where
F: FnMut(D) -> Result<V, E>,
G: FnOnce(VF) -> Result<C, X>,
{
let stored = filter.try_map(f).map_err(SetCrossingError::Operand)?;
let any = cross_element(stored.any, g).map_err(SetCrossingError::Element)?;
let count = cross_count(stored.count).map_err(SetCrossingError::Cardinality)?;
Ok(Self {
has_element: stored.has_element,
eq: stored.eq,
ne: stored.ne,
encloses: stored.encloses,
enclosed_by: stored.enclosed_by,
overlaps: stored.overlaps,
any,
count,
db: PhantomData,
})
}
}
impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlEdgeComparison<V, C, Db> {
type Comparison = SqlEdgeComparison<W, C::Comparison, Db>;
}
impl<V, C: StrategyOver<W>, Db, W> StrategyOver<W> for SqlEdgeSetComparison<V, C, Db> {
type Comparison = SqlEdgeSetComparison<W, C::Comparison, Db>;
}
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>, Db> TryFromFilter<ListFilter<D, VF>>
for SqlEdgeComparison<V, C, Db>
{
type Error = ListCrossingError<V::Error, C::Error>;
fn try_from_filter(filter: ListFilter<D, VF>) -> Result<Self, Self::Error> {
Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
}
}
impl<D, VF, V, C: TryFromFilter<VF>, Db> TryFromFilter<QuantifiedFilter<D, VF>>
for SqlEdgeComparison<V, C, Db>
{
type Error = ListCrossingError<core::convert::Infallible, C::Error>;
fn try_from_filter(filter: QuantifiedFilter<D, VF>) -> Result<Self, Self::Error> {
let mut crossed = Self::new();
crossed.any =
cross_element(filter.any, C::try_from_filter).map_err(ListCrossingError::Element)?;
crossed.count = cross_count(filter.count).map_err(ListCrossingError::Cardinality)?;
Ok(crossed)
}
}
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>, Db> TryFromFilter<SetFilter<D, VF>>
for SqlEdgeSetComparison<V, C, Db>
{
type Error = SetCrossingError<V::Error, C::Error>;
fn try_from_filter(filter: SetFilter<D, VF>) -> Result<Self, Self::Error> {
Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
}
}
impl<V, C, Db> ComplexComparison<Db> for SqlEdgeComparison<V, C, Db>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<
Builder<'q> = SqlConjunction<'q, Db>,
Error = SqlLoweringError,
Buffer = Utf8BytesMut,
>,
V: Carrier<Db>,
C: ComplexComparison<Db>,
i64: 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> {
let scope = OrderedScope::new::<Db>(at)?;
push_sequence_slots(self, &scope, &mut builder);
push_edge_any::<C, Db>(self.any.as_ref(), at, &scope.scope, &mut builder)?;
push_edge_count(self.count.as_ref(), &scope.scope, &mut builder);
Ok(builder)
}
}
impl<V, C, Db> ComplexComparison<Db> for SqlEdgeSetComparison<V, C, Db>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<
Builder<'q> = SqlConjunction<'q, Db>,
Error = SqlLoweringError,
Buffer = Utf8BytesMut,
>,
V: Carrier<Db>,
C: ComplexComparison<Db>,
i64: 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> {
let scope = Scope::new::<Db>(at)?;
push_set_slots(self, &scope, &mut builder);
push_edge_any::<C, Db>(self.any.as_ref(), at, &scope, &mut builder)?;
push_edge_count(self.count.as_ref(), &scope, &mut builder);
Ok(builder)
}
}
pub(super) struct Scope {
pub(super) table: Utf8BytesMut,
value: Utf8BytesMut,
pub(super) correlation: Utf8BytesMut,
}
struct OrderedScope {
scope: Scope,
ordinal: Utf8BytesMut,
}
const OPERAND_ALIAS: &str = "__ig_operand_0__";
const OPERAND_ORDINAL: &str = "ordinal";
const OPERAND_VALUE: &str = "value";
impl Scope {
fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
at: At<'_>,
) -> Result<Self, SqlLoweringError> {
let edge = edge_table(at)?;
let mut names = Db::buffer();
Ok(Self::with_edge::<Db>(
at,
FieldName::new(&edge),
at.parent_keys(),
&mut names,
))
}
fn with_edge<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
at: At<'_>,
edge: &FieldName,
parent: Option<&[&'static FieldName]>,
names: &mut Utf8BytesMut,
) -> Self {
push_quoted_ident::<Db>(edge, names);
let table = names.split();
for (i, key) in at.record().keys().iter().enumerate() {
if i > 0 {
names.push_str(" AND ");
}
push_quoted_qualified::<Db>(edge, key, names);
names.push_str(" = ");
push_quoted_scope::<Db>(at.qualifier(), parent_key(parent, i, key), names);
}
let correlation = names.split();
push_qualified_column::<Db>(edge, at, names);
let value = names.split();
Self {
table,
value,
correlation,
}
}
}
impl OrderedScope {
fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
at: At<'_>,
) -> Result<Self, SqlLoweringError> {
let edge = edge_table(at)?;
let edge = FieldName::new(&edge);
let ordinal = at.frame(FieldName::new("ordinal"));
let mut names = Db::buffer();
let scope = Scope::with_edge::<Db>(at, edge, at.parent_keys(), &mut names);
push_qualified_column::<Db>(edge, ordinal.at(), &mut names);
Ok(Self {
scope,
ordinal: names.split(),
})
}
}
pub(super) struct SegmentScope {
pub(super) scope: Scope,
pub(super) columns: Vec<Utf8BytesMut>,
}
impl SegmentScope {
pub(super) fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
at: At<'_>,
segments: &[crate::ColumnShape],
) -> Result<Self, SqlLoweringError> {
let edge = edge_table(at)?;
let edge = FieldName::new(&edge);
let mut names = Db::buffer();
let scope = Scope::with_edge::<Db>(at, edge, at.parent_keys(), &mut names);
let mut columns = Vec::with_capacity(crate::width(segments));
super::fold_leaves(at, segments, (), &mut |(), leaf| {
push_qualified_column::<Db>(edge, leaf, &mut names);
columns.push(names.split());
});
Ok(Self { scope, columns })
}
}
pub fn edge_table(at: At<'_>) -> Result<Utf8BytesMut, SqlLoweringError> {
let Some(path) = at.path() else {
return Err(SqlLoweringError::EdgeWithoutField(at.record().table()));
};
let mut name = Utf8BytesMut::new();
name.push_str(at.record().table());
extend(path, &mut name);
Ok(name)
}
#[inline]
fn parent_key<'a>(
parent: Option<&[&'a FieldName]>,
index: usize,
own: &'a FieldName,
) -> &'a FieldName {
match parent.and_then(|keys| keys.get(index)) {
Some(key) => key,
None => own,
}
}
fn extend(path: &Path<'_>, out: &mut Utf8BytesMut) {
if let Some(parent) = path.parent() {
extend(parent, out);
}
out.push('_');
out.push_str(path.name());
}
fn push_qualified_column<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
edge: &FieldName,
at: At<'_>,
out: &mut Utf8BytesMut,
) {
push_quoted_ident::<Db>(edge, out);
out.push('.');
Db::write_column(at, out);
}
fn push_sequence_slots<V, C, Db>(
comparison: &SqlEdgeComparison<V, C, Db>,
scope: &OrderedScope,
out: &mut SqlConjunction<'_, Db>,
) where
Db: sqlx::Database + QuoteIdent,
V: Carrier<Db>,
i64: Carrier<Db>,
{
for (slot, negated) in [(&comparison.eq, false), (&comparison.ne, true)] {
if let Some(values) = slot {
push_positional_whole(out.open(), scope, values, negated);
}
}
for (slot, order) in [
(&comparison.gt, CollectionOrder::Gt),
(&comparison.gte, CollectionOrder::Gte),
(&comparison.lt, CollectionOrder::Lt),
(&comparison.lte, CollectionOrder::Lte),
] {
if let Some(values) = slot {
push_ordering(out.open(), scope, values, order);
}
}
push_membership(comparison.has_element.as_ref(), &scope.scope, out);
}
fn push_set_slots<V, C, Db>(
comparison: &SqlEdgeSetComparison<V, C, Db>,
scope: &Scope,
out: &mut SqlConjunction<'_, Db>,
) where
Db: sqlx::Database + QuoteIdent,
V: Carrier<Db>,
{
for (slot, negated) in [(&comparison.eq, false), (&comparison.ne, true)] {
if let Some(values) = slot {
push_mutual_containment(out.open(), scope, values, negated);
}
}
if let Some(values) = &comparison.encloses {
push_encloses(out.open(), scope, values);
}
if let Some(values) = &comparison.enclosed_by {
push_enclosed_by(out.open(), scope, values);
}
if let Some(values) = &comparison.overlaps {
push_overlaps(out.open(), scope, values);
}
push_membership(comparison.has_element.as_ref(), scope, out);
}
fn push_membership<V, Db>(element: Option<&V>, scope: &Scope, out: &mut SqlConjunction<'_, Db>)
where
Db: sqlx::Database,
V: Carrier<Db>,
{
if let Some(element) = element {
push_encloses(out.open(), scope, core::slice::from_ref(element));
}
}
fn push_edge_any<C, Db>(
element: Option<&C>,
at: At<'_>,
scope: &Scope,
out: &mut SqlConjunction<'_, Db>,
) -> Result<(), Db::Error>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer = Utf8BytesMut>,
C: ComplexComparison<Db>,
{
let Some(element) = element else {
return Ok(());
};
push_element_scope(out.open(), element, at, |qb| {
qb.push("( SELECT ");
qb.push(&scope.value);
qb.push(" AS ");
qb.push(quote_ident::<Db>(ELEMENT_VALUE));
qb.push(" FROM ");
qb.push(&scope.table);
qb.push(" WHERE ");
qb.push(&scope.correlation);
qb.push(" ) AS ");
qb.push(quote_ident::<Db>(ELEMENT_ALIAS));
})
}
pub(super) fn push_edge_count<Db>(
count: Option<&SqlCountComparison<i64, Db>>,
scope: &Scope,
out: &mut SqlConjunction<'_, Db>,
) where
Db: sqlx::Database,
i64: Carrier<Db>,
{
let Some(count) = count else {
return;
};
push_count_slots(count, out, |qb| push_count(qb, scope));
}
fn push_exists<Db>(
qb: &mut sqlx::QueryBuilder<Db>,
scope: &Scope,
negated: bool,
rest: impl FnOnce(&mut sqlx::QueryBuilder<Db>),
) where
Db: sqlx::Database,
{
qb.push(if negated { "NOT EXISTS (" } else { "EXISTS (" });
qb.push("SELECT 1 FROM ");
qb.push(&scope.table);
qb.push(" WHERE ");
qb.push(&scope.correlation);
rest(qb);
qb.push(")");
}
fn push_count<Db: sqlx::Database>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope) {
qb.push("(SELECT COUNT(*) FROM ");
qb.push(&scope.table);
qb.push(" WHERE ");
qb.push(&scope.correlation);
qb.push(")");
}
fn push_value_in<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V], negated: bool)
where
Db: sqlx::Database,
V: Carrier<Db>,
{
qb.push(&scope.value);
qb.push(if negated { " NOT IN (" } else { " IN (" });
for (i, value) in values.iter().enumerate() {
if i > 0 {
qb.push(", ");
}
value.push_bind(qb);
}
qb.push(")");
}
fn push_encloses<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V])
where
Db: sqlx::Database,
V: Carrier<Db>,
{
if values.is_empty() {
qb.push("1 = 1");
return;
}
let bracketed = values.len() > 1;
if bracketed {
qb.push("( ");
}
for (i, value) in values.iter().enumerate() {
if i > 0 {
qb.push(" AND ");
}
push_exists(qb, scope, false, |qb| {
qb.push(" AND ");
qb.push(&scope.value);
qb.push(" = ");
value.push_bind(qb);
});
}
if bracketed {
qb.push(" )");
}
}
fn push_enclosed_by<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V])
where
Db: sqlx::Database,
V: Carrier<Db>,
{
push_exists(qb, scope, true, |qb| {
if !values.is_empty() {
qb.push(" AND ");
push_value_in(qb, scope, values, true);
}
});
}
fn push_overlaps<V, Db>(qb: &mut sqlx::QueryBuilder<Db>, scope: &Scope, values: &[V])
where
Db: sqlx::Database,
V: Carrier<Db>,
{
if values.is_empty() {
qb.push("1 = 0");
return;
}
push_exists(qb, scope, false, |qb| {
qb.push(" AND ");
push_value_in(qb, scope, values, false);
});
}
fn push_mutual_containment<V, Db>(
qb: &mut sqlx::QueryBuilder<Db>,
scope: &Scope,
values: &[V],
negated: bool,
) where
Db: sqlx::Database,
V: Carrier<Db>,
{
not_wrapped(qb, negated, |qb| {
if values.is_empty() {
push_exists(qb, scope, true, |_| ());
} else {
qb.push("( ");
push_encloses(qb, scope, values);
qb.push(" AND ");
push_enclosed_by(qb, scope, values);
qb.push(" )");
}
});
}
fn push_positional_whole<V, Db>(
qb: &mut sqlx::QueryBuilder<Db>,
scope: &OrderedScope,
values: &[V],
negated: bool,
) where
Db: sqlx::Database,
V: Carrier<Db>,
i64: Carrier<Db>,
{
not_wrapped(qb, negated, |qb| {
if values.is_empty() {
push_exists(qb, &scope.scope, true, |_| ());
return;
}
qb.push("( ");
push_exists(qb, &scope.scope, true, |qb| {
qb.push(" AND (");
qb.push(&scope.ordinal);
qb.push(", ");
qb.push(&scope.scope.value);
qb.push(") NOT IN (");
for (i, value) in values.iter().enumerate() {
if i > 0 {
qb.push(", ");
}
qb.push("(");
push_ordinal(qb, i);
qb.push(", ");
value.push_bind(qb);
qb.push(")");
}
qb.push(")");
});
qb.push(" AND ");
push_count(qb, &scope.scope);
qb.push(" = ");
push_ordinal(qb, values.len());
qb.push(" )");
});
}
fn push_ordering<V, Db>(
qb: &mut sqlx::QueryBuilder<Db>,
scope: &OrderedScope,
values: &[V],
order: CollectionOrder,
) where
Db: sqlx::Database + QuoteIdent,
V: Carrier<Db>,
i64: Carrier<Db>,
{
if values.is_empty() {
match order {
CollectionOrder::Gt => push_exists(qb, &scope.scope, false, |_| ()),
CollectionOrder::Lte => push_exists(qb, &scope.scope, true, |_| ()),
CollectionOrder::Gte => {
qb.push("1 = 1");
}
CollectionOrder::Lt => {
qb.push("1 = 0");
}
}
return;
}
let alias = FieldName::new(OPERAND_ALIAS);
let operand = quote_ident::<Db>(alias);
let operand_ordinal = quote_qualified::<Db>(alias, FieldName::new(OPERAND_ORDINAL));
let operand_value = quote_qualified::<Db>(alias, FieldName::new(OPERAND_VALUE));
qb.push("COALESCE((SELECT ");
qb.push(&scope.scope.value);
qb.push(order.element());
qb.push(&operand_value);
qb.push(" FROM ");
qb.push(&scope.scope.table);
qb.push(" JOIN ( ");
for (i, value) in values.iter().enumerate() {
if i > 0 {
qb.push(" UNION ALL ");
}
qb.push("SELECT ");
push_ordinal(qb, i);
if i == 0 {
qb.push(" AS ");
qb.push(quote_ident::<Db>(FieldName::new(OPERAND_ORDINAL)));
}
qb.push(", ");
value.push_bind(qb);
if i == 0 {
qb.push(" AS ");
qb.push(quote_ident::<Db>(FieldName::new(OPERAND_VALUE)));
}
}
qb.push(" ) AS ");
qb.push(&operand);
qb.push(" ON ");
qb.push(&operand_ordinal);
qb.push(" = ");
qb.push(&scope.ordinal);
qb.push(" WHERE ");
qb.push(&scope.scope.correlation);
qb.push(" AND ");
qb.push(&scope.scope.value);
qb.push(" <> ");
qb.push(&operand_value);
qb.push(" ORDER BY ");
qb.push(&scope.ordinal);
qb.push(" LIMIT 1), ");
push_count(qb, &scope.scope);
qb.push(order.length());
push_ordinal(qb, values.len());
qb.push(")");
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CollectionOrder {
Gt,
Gte,
Lt,
Lte,
}
impl CollectionOrder {
const fn element(self) -> &'static str {
match self {
Self::Gt | Self::Gte => " > ",
Self::Lt | Self::Lte => " < ",
}
}
const fn length(self) -> &'static str {
match self {
Self::Gt => " > ",
Self::Gte => " >= ",
Self::Lt => " < ",
Self::Lte => " <= ",
}
}
}
pub(crate) fn push_ordinal<Db: sqlx::Database>(qb: &mut sqlx::QueryBuilder<Db>, position: usize)
where
i64: Carrier<Db>,
{
let position = i64::try_from(position).unwrap_or(i64::MAX);
position.push_bind(qb);
}
#[cfg(test)]
mod tests;