use core::{fmt::Display, marker::PhantomData};
use smol_bytes::Utf8BytesMut;
use super::{
Carrier, QuoteIdent, RelationDepthError, RelationWidthError, SqlConjunction, SqlCountComparison,
SqlLoweringError,
dialect::{push_quoted_ident, push_quoted_scope},
push_column, push_count_slots,
};
use crate::{
FieldName,
comparison::{At, Backend, CollapsibleComparison, ComplexComparison, RecordAddress},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RelatedRow {
address: RecordAddress,
aliases: &'static [&'static str],
}
impl RelatedRow {
#[inline]
#[must_use]
pub const fn of<Row, Db>() -> Self
where
Row: crate::query::sql::SqlQuery<Db>,
Db: Backend + sqlx::Database,
{
Self {
address: Row::ADDRESS,
aliases: Row::ALIASES,
}
}
#[inline]
#[must_use]
pub const fn new(address: RecordAddress, aliases: &'static [&'static str]) -> Self {
Self { address, aliases }
}
#[inline]
#[must_use]
pub const fn address(&self) -> &RecordAddress {
&self.address
}
fn scope(&self, enclosing: usize) -> Result<&'static str, SqlLoweringError> {
let depth = enclosing + 1;
match self.aliases.get(depth) {
Some(alias) => Ok(alias),
None => Err(SqlLoweringError::RelationDepth(RelationDepthError::new(
self.address.table(),
depth,
self.aliases.len(),
))),
}
}
fn row_source<Db: QuoteIdent>(&self, alias: &str) -> Utf8BytesMut {
let mut item = Utf8BytesMut::new();
push_quoted_ident::<Db>(self.address.table(), &mut item);
item.push(' ');
push_quoted_ident::<Db>(FieldName::new(alias), &mut item);
item
}
}
pub struct SqlRefComparison<C, Db> {
target: RelatedRow,
nested: C,
db: PhantomData<fn() -> Db>,
}
impl<C, Db> SqlRefComparison<C, Db> {
#[inline]
pub const fn new(target: RelatedRow, nested: C) -> Self {
Self {
target,
nested,
db: PhantomData,
}
}
#[inline]
pub const fn target(&self) -> &RelatedRow {
&self.target
}
#[inline]
pub const fn nested(&self) -> &C {
&self.nested
}
}
pub struct SqlDerivedComparison<C, Db> {
source: RelatedRow,
points_back: &'static FieldName,
any: Option<C>,
all: Option<C>,
none: Option<C>,
count: Option<SqlCountComparison<i64, Db>>,
}
impl<C, Db> SqlDerivedComparison<C, Db> {
#[inline]
pub const fn new(source: RelatedRow, points_back: &'static FieldName) -> Self {
Self {
source,
points_back,
any: None,
all: None,
none: None,
count: None,
}
}
#[inline]
#[must_use]
pub fn with_any(mut self, nested: C) -> Self {
self.any = Some(nested);
self
}
#[inline]
#[must_use]
pub fn with_all(mut self, nested: C) -> Self {
self.all = Some(nested);
self
}
#[inline]
#[must_use]
pub fn with_none(mut self, nested: C) -> Self {
self.none = Some(nested);
self
}
#[inline]
#[must_use]
pub fn with_count(mut self, count: SqlCountComparison<i64, Db>) -> Self {
self.count = Some(count);
self
}
#[inline]
pub const fn source(&self) -> (&RelatedRow, &'static FieldName) {
(&self.source, self.points_back)
}
#[inline]
pub const fn any(&self) -> Option<&C> {
self.any.as_ref()
}
#[inline]
pub const fn all(&self) -> Option<&C> {
self.all.as_ref()
}
#[inline]
pub const fn none(&self) -> Option<&C> {
self.none.as_ref()
}
#[inline]
pub const fn count(&self) -> Option<&SqlCountComparison<i64, Db>> {
self.count.as_ref()
}
#[inline]
pub const fn conjuncts(&self) -> usize {
(self.any.is_some() as usize)
+ (self.all.is_some() as usize)
+ (self.none.is_some() as usize)
+ match &self.count {
Some(count) => count.conjuncts(),
None => 0,
}
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.conjuncts() == 0
}
}
impl<C: core::fmt::Debug, Db> core::fmt::Debug for SqlRefComparison<C, Db> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("SqlRefComparison")
.field("target", &self.target)
.field("nested", &self.nested)
.finish()
}
}
impl<C: Clone, Db> Clone for SqlRefComparison<C, Db> {
fn clone(&self) -> Self {
Self {
target: self.target,
nested: self.nested.clone(),
db: PhantomData,
}
}
}
impl<C: PartialEq, Db> PartialEq for SqlRefComparison<C, Db> {
fn eq(&self, other: &Self) -> bool {
self.target == other.target && self.nested == other.nested
}
}
impl<C: core::fmt::Debug, Db> core::fmt::Debug for SqlDerivedComparison<C, Db> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("SqlDerivedComparison")
.field("source", &self.source)
.field("points_back", &self.points_back)
.field("any", &self.any)
.field("all", &self.all)
.field("none", &self.none)
.field("count", &self.count)
.finish()
}
}
impl<C: Clone, Db> Clone for SqlDerivedComparison<C, Db> {
fn clone(&self) -> Self {
Self {
source: self.source,
points_back: self.points_back,
any: self.any.clone(),
all: self.all.clone(),
none: self.none.clone(),
count: self.count.clone(),
}
}
}
impl<C: PartialEq, Db> PartialEq for SqlDerivedComparison<C, Db> {
fn eq(&self, other: &Self) -> bool {
self.source == other.source
&& self.points_back == other.points_back
&& self.any == other.any
&& self.all == other.all
&& self.none == other.none
&& self.count == other.count
}
}
impl<C, Db> ComplexComparison<Db> for SqlRefComparison<C, Db>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
C: CollapsibleComparison<Db>,
{
fn conjuncts(&self) -> usize {
match self.nested.only_id() {
Some(id) => id.conjuncts(),
None => usize::from(!self.nested.is_empty()),
}
}
fn apply<'q>(
&'q self,
at: At<'_>,
builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error> {
let id = one_column(self.target.address())?;
if let Some(collapsed) = self.nested.only_id() {
return collapsed.apply(at, builder);
}
if self.nested.is_empty() {
return Ok(builder);
}
let scope = self.target.scope(at.depth())?;
let from = self.target.row_source::<Db>(scope);
let mut inner = builder
.sub_select_with(|qb| push_column(qb, at))
.push_field_with(|qb| {
let mut projected = Utf8BytesMut::new();
push_quoted_scope::<Db>(scope, id, &mut projected);
qb.push(projected.as_str());
})
.from(from.as_str())
.begin_where();
{
let nested = SqlConjunction::new(inner.inner_mut());
self
.nested
.apply(At::nested(self.target.address(), at.depth(), scope), nested)?;
}
Ok(inner.finalize())
}
}
impl<F, R, C, Db: sqlx::Database + Backend> crate::ToRelatedComparison<C, Db>
for crate::RefFilter<F, R>
{
type Comparison = Option<SqlRefComparison<C, Db>>;
}
impl<F, R, C, Db> crate::comparison::ToLoweredRelatedComparison<C, Db> for crate::RefFilter<F, R>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
C: CollapsibleComparison<Db>,
{
#[inline]
fn conjuncts(comparison: &Self::Comparison) -> usize {
ComplexComparison::<Db>::conjuncts(comparison)
}
#[inline]
fn apply<'q>(
comparison: &'q Self::Comparison,
at: At<'_>,
builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error> {
ComplexComparison::<Db>::apply(comparison, at, builder)
}
}
impl<F, C, Db: sqlx::Database + Backend> crate::ToRelatedComparison<C, Db>
for crate::RelatedFilter<F>
{
type Comparison = SqlDerivedComparison<C, Db>;
}
impl<F, C, Db> crate::comparison::ToLoweredRelatedComparison<C, Db> for crate::RelatedFilter<F>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<
Builder<'q> = SqlConjunction<'q, Db>,
Error = SqlLoweringError,
Buffer = Utf8BytesMut,
>,
C: ComplexComparison<Db>,
i64: Carrier<Db>,
{
#[inline]
fn conjuncts(comparison: &Self::Comparison) -> usize {
ComplexComparison::<Db>::conjuncts(comparison)
}
#[inline]
fn apply<'q>(
comparison: &'q Self::Comparison,
at: At<'_>,
builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error> {
ComplexComparison::<Db>::apply(comparison, at, builder)
}
}
impl<C, Db> ComplexComparison<Db> for SqlDerivedComparison<C, Db>
where
Db: sqlx::Database
+ QuoteIdent
+ for<'q> Backend<
Builder<'q> = SqlConjunction<'q, Db>,
Error = SqlLoweringError,
Buffer = Utf8BytesMut,
>,
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 alias = self.source.scope(at.depth())?;
let scope = Correlation::new::<Db>(at, &self.source, self.points_back, alias)?;
let inner = At::nested(self.source.address(), at.depth(), alias);
push_quantifiers(self, &scope, inner, &mut builder)?;
push_related_count(self.count.as_ref(), &scope, &mut builder);
Ok(builder)
}
}
struct Correlation {
table: Utf8BytesMut,
correlation: Utf8BytesMut,
}
impl Correlation {
fn new<Db: QuoteIdent + Backend<Buffer = Utf8BytesMut>>(
at: At<'_>,
source: &RelatedRow,
points_back: &'static FieldName,
alias: &str,
) -> Result<Self, SqlLoweringError> {
let id = one_column(at.record())?;
let mut names = Db::buffer();
push_quoted_ident::<Db>(source.address().table(), &mut names);
names.push(' ');
push_quoted_ident::<Db>(FieldName::new(alias), &mut names);
let table = names.split();
push_quoted_scope::<Db>(alias, points_back, &mut names);
names.push_str(" = ");
push_quoted_scope::<Db>(at.qualifier(), id, &mut names);
Ok(Self {
table,
correlation: names.split(),
})
}
}
fn one_column(row: &RecordAddress) -> Result<&'static FieldName, SqlLoweringError> {
match row.keys() {
[only] => Ok(only),
columns => Err(SqlLoweringError::RelationWidth(RelationWidthError::new(
row.table(),
columns.len(),
))),
}
}
fn push_quantifiers<C, Db>(
comparison: &SqlDerivedComparison<C, Db>,
scope: &Correlation,
at: At<'_>,
out: &mut SqlConjunction<'_, Db>,
) -> Result<(), Db::Error>
where
Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
C: ComplexComparison<Db>,
{
if let Some(nested) = &comparison.any {
push_quantified(out.open(), scope, at, nested, false)?;
}
if let Some(nested) = &comparison.all {
push_all(out.open(), scope, at, nested)?;
}
if let Some(nested) = &comparison.none {
push_quantified(out.open(), scope, at, nested, true)?;
}
Ok(())
}
fn push_quantified<C, Db>(
qb: &mut sqlx::QueryBuilder<Db>,
scope: &Correlation,
at: At<'_>,
nested: &C,
negated: bool,
) -> Result<(), Db::Error>
where
Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
C: ComplexComparison<Db>,
{
qb.push(if negated {
"NOT EXISTS (SELECT 1 FROM "
} else {
"EXISTS (SELECT 1 FROM "
});
qb.push(&scope.table);
qb.push(" WHERE ");
qb.push(&scope.correlation);
nested.apply(at, SqlConjunction::with_lead(qb, " AND "))?;
qb.push(")");
Ok(())
}
fn push_all<C, Db>(
qb: &mut sqlx::QueryBuilder<Db>,
scope: &Correlation,
at: At<'_>,
nested: &C,
) -> Result<(), Db::Error>
where
Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
C: ComplexComparison<Db>,
{
if nested.is_empty() {
qb.push("1 = 1");
return Ok(());
}
qb.push("NOT EXISTS (SELECT 1 FROM ");
qb.push(&scope.table);
qb.push(" WHERE ");
qb.push(&scope.correlation);
qb.push(" AND NOT ( ");
nested.apply(at, SqlConjunction::with_lead(qb, ""))?;
qb.push(" ))");
Ok(())
}
fn push_related_count<Db>(
count: Option<&SqlCountComparison<i64, Db>>,
scope: &Correlation,
out: &mut SqlConjunction<'_, Db>,
) where
Db: sqlx::Database,
i64: Carrier<Db>,
{
let Some(count) = count else {
return;
};
push_count_slots(count, out, |qb| {
qb.push("(SELECT COUNT(*) FROM ");
qb.push(&scope.table);
qb.push(" WHERE ");
qb.push(&scope.correlation);
qb.push(")");
});
}
#[cfg(test)]
mod tests;