use bson::{Bson, Document};
use super::{
MATCH, Mongo, MongoConjunction, MongoCountComparison, MongoLoweringError, MongoOperator,
MongoPredicate, NOR, PROJECT, count::push_count_slots, field_key, field_path,
};
use crate::{
FieldName, RecordAddress,
comparison::{
At, Backend, CollapsibleComparison, ComplexComparison, RelationDepthError, RelationWidthError,
},
query::mongo::MongoQuery,
};
const LOOKUP: &str = "$lookup";
const FROM: &str = "from";
const LOCAL_FIELD: &str = "localField";
const FOREIGN_FIELD: &str = "foreignField";
const AS: &str = "as";
const PIPELINE: &str = "pipeline";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MongoRelatedDocument {
address: RecordAddress,
aliases: &'static [&'static str],
}
impl MongoRelatedDocument {
#[inline]
#[must_use]
pub const fn of<Row: MongoQuery>() -> Self {
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
}
pub(crate) fn scope(&self, enclosing: usize) -> Result<&'static str, MongoLoweringError> {
let depth = enclosing + 1;
match self.aliases.get(depth) {
Some(field) => Ok(field),
None => Err(MongoLoweringError::RelationDepth(RelationDepthError::new(
self.address.table(),
depth,
self.aliases.len(),
))),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MongoRefComparison<C> {
target: MongoRelatedDocument,
nested: C,
}
impl<C> MongoRefComparison<C> {
#[inline]
pub const fn new(target: MongoRelatedDocument, nested: C) -> Self {
Self { target, nested }
}
#[inline]
pub const fn target(&self) -> &MongoRelatedDocument {
&self.target
}
#[inline]
pub const fn nested(&self) -> &C {
&self.nested
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MongoDerivedComparison<C> {
source: MongoRelatedDocument,
points_back: &'static FieldName,
any: Option<C>,
all: Option<C>,
none: Option<C>,
count: Option<MongoCountComparison<i64>>,
}
impl<C> MongoDerivedComparison<C> {
#[inline]
pub const fn new(source: MongoRelatedDocument, 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: MongoCountComparison<i64>) -> Self {
self.count = Some(count);
self
}
#[inline]
pub const fn source(&self) -> (&MongoRelatedDocument, &'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<&MongoCountComparison<i64>> {
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: CollapsibleComparison<Mongo>> ComplexComparison<Mongo> for MongoRefComparison<C> {
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<'_>,
mut builder: <Mongo as Backend>::Builder<'q>,
) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
let target = one_key(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 field = self.target.scope(at.depth())?;
let lookup = Lookup {
from: self.target.address().table(),
local: field_path(at),
foreign: field_key(self.target.address(), target),
field,
};
let (pipeline, reads) = sub_pipeline(
self
.nested
.apply(
At::nested(self.target.address(), at.depth(), field),
MongoConjunction::new(),
)?
.into_predicate(),
);
builder.join(
lookup.stages(pipeline, populated(field)).into(),
lookup.reads(reads),
);
Ok(builder)
}
}
impl<F, C> crate::ToRelatedComparison<C, Mongo> for crate::RelatedFilter<F> {
type Comparison = MongoDerivedComparison<C>;
}
impl<F, R, C> crate::ToRelatedComparison<C, Mongo> for crate::RefFilter<F, R> {
type Comparison = Option<MongoRefComparison<C>>;
}
impl<F, C: ComplexComparison<Mongo>> crate::comparison::ToLoweredRelatedComparison<C, Mongo>
for crate::RelatedFilter<F>
{
#[inline]
fn conjuncts(comparison: &Self::Comparison) -> usize {
ComplexComparison::<Mongo>::conjuncts(comparison)
}
#[inline]
fn apply<'q>(
comparison: &'q Self::Comparison,
at: At<'_>,
builder: <Mongo as Backend>::Builder<'q>,
) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
ComplexComparison::<Mongo>::apply(comparison, at, builder)
}
}
impl<F, R, C: CollapsibleComparison<Mongo>> crate::comparison::ToLoweredRelatedComparison<C, Mongo>
for crate::RefFilter<F, R>
{
#[inline]
fn conjuncts(comparison: &Self::Comparison) -> usize {
ComplexComparison::<Mongo>::conjuncts(comparison)
}
#[inline]
fn apply<'q>(
comparison: &'q Self::Comparison,
at: At<'_>,
builder: <Mongo as Backend>::Builder<'q>,
) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
ComplexComparison::<Mongo>::apply(comparison, at, builder)
}
}
impl<C: ComplexComparison<Mongo>> ComplexComparison<Mongo> for MongoDerivedComparison<C> {
#[inline]
fn conjuncts(&self) -> usize {
Self::conjuncts(self)
}
fn apply<'q>(
&'q self,
at: At<'_>,
mut builder: <Mongo as Backend>::Builder<'q>,
) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
let parent = one_key(at.record())?;
if self.is_empty() {
return Ok(builder);
}
let field = self.source.scope(at.depth())?;
let lookup = Lookup {
from: self.source.address().table(),
local: field_key(at.record(), parent).to_owned(),
foreign: field_key(self.source.address(), self.points_back),
field,
};
let inner = At::nested(self.source.address(), at.depth(), field);
push_quantifiers(self, &lookup, inner, &mut builder)?;
push_related_count(self.count.as_ref(), &lookup, &mut builder);
Ok(builder)
}
}
pub(crate) struct Lookup<'a> {
pub(crate) from: &'static FieldName,
pub(crate) local: String,
pub(crate) foreign: &'a str,
pub(crate) field: &'a str,
}
impl Lookup<'_> {
pub(crate) fn lookup(&self, pipeline: Vec<Document>) -> Document {
let mut lookup = Document::new();
lookup.insert(FROM, Bson::String(self.from.as_str().to_owned()));
lookup.insert(LOCAL_FIELD, Bson::String(self.local.clone()));
lookup.insert(FOREIGN_FIELD, Bson::String(self.foreign.to_owned()));
lookup.insert(AS, Bson::String(self.field.to_owned()));
if !pipeline.is_empty() {
lookup.insert(
PIPELINE,
Bson::Array(pipeline.into_iter().map(Bson::Document).collect()),
);
}
stage(LOOKUP, lookup)
}
fn stages(&self, pipeline: Vec<Document>, test: Document) -> [Document; 3] {
let mut dropped = Document::new();
dropped.insert(self.field, Bson::Int32(0));
[
self.lookup(pipeline),
stage(MATCH, test),
stage(PROJECT, dropped),
]
}
fn reads(&self, nested: Vec<&'static FieldName>) -> Vec<&'static FieldName> {
let mut reads = Vec::with_capacity(nested.len() + 1);
reads.push(self.from);
reads.extend(nested);
reads
}
}
fn push_quantifiers<C: ComplexComparison<Mongo>>(
comparison: &MongoDerivedComparison<C>,
lookup: &Lookup<'_>,
at: At<'_>,
out: &mut MongoConjunction,
) -> Result<(), MongoLoweringError> {
if let Some(nested) = &comparison.any {
let (pipeline, reads) = sub_pipeline(inner(nested, at)?);
out.join(
lookup.stages(pipeline, populated(lookup.field)).into(),
lookup.reads(reads),
);
}
if let Some(nested) = &comparison.all {
let (pipeline, reads) = negated_pipeline(inner(nested, at)?)?;
out.join(
lookup.stages(pipeline, empty(lookup.field)).into(),
lookup.reads(reads),
);
}
if let Some(nested) = &comparison.none {
let (pipeline, reads) = sub_pipeline(inner(nested, at)?);
out.join(
lookup.stages(pipeline, empty(lookup.field)).into(),
lookup.reads(reads),
);
}
Ok(())
}
fn push_related_count(
count: Option<&MongoCountComparison<i64>>,
lookup: &Lookup<'_>,
out: &mut MongoConjunction,
) {
let Some(count) = count.filter(|count| !count.is_empty()) else {
return;
};
let mut expressions = MongoConjunction::new();
push_count_slots(count, lookup.field, &mut expressions);
out.join(
lookup
.stages(Vec::new(), expressions.into_document())
.into(),
lookup.reads(Vec::new()),
);
}
fn inner<C: ComplexComparison<Mongo>>(
nested: &C,
at: At<'_>,
) -> Result<MongoPredicate, MongoLoweringError> {
Ok(nested.apply(at, MongoConjunction::new())?.into_predicate())
}
fn sub_pipeline(predicate: MongoPredicate) -> (Vec<Document>, Vec<&'static FieldName>) {
let (filter, joins, reads) = predicate.into_parts();
let mut pipeline = Vec::with_capacity(joins.len() + 1);
if !filter.is_empty() {
pipeline.push(stage(MATCH, filter));
}
pipeline.extend(joins);
(pipeline, reads)
}
fn negated_pipeline(
predicate: MongoPredicate,
) -> Result<(Vec<Document>, Vec<&'static FieldName>), MongoLoweringError> {
let (filter, joins, reads) = predicate.into_parts();
if !joins.is_empty() {
return Err(MongoLoweringError::NegatedRelation);
}
let mut negation = Document::new();
negation.insert(NOR, Bson::Array(vec![Bson::Document(filter)]));
Ok((vec![stage(MATCH, negation)], reads))
}
fn populated(field: &str) -> Document {
test(field, MongoOperator::Ne)
}
fn empty(field: &str) -> Document {
test(field, MongoOperator::Eq)
}
fn test(field: &str, op: MongoOperator) -> Document {
let mut operators = Document::new();
operators.insert(op.as_str(), Bson::Array(Vec::new()));
let mut predicate = Document::new();
predicate.insert(field, Bson::Document(operators));
predicate
}
fn stage(name: &str, body: Document) -> Document {
let mut stage = Document::new();
stage.insert(name, Bson::Document(body));
stage
}
pub(crate) fn one_key(row: &RecordAddress) -> Result<&'static FieldName, MongoLoweringError> {
match row.keys() {
[only] => Ok(only),
fields => Err(MongoLoweringError::RelationWidth(RelationWidthError::new(
row.table(),
fields.len(),
))),
}
}
#[cfg(test)]
mod tests;