ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! The cardinality comparison: [`MongoCountComparison`], and the `$expr` a collection renders it
//! through.

use bson::{Bson, Document};

use super::{EXPR, MongoCarrier, MongoConjunction, membership};
use crate::{ScalarFilter, comparison::TryFromFilter};

mongo_comparison_kind! {
  /// How many elements a collection holds, asked through the eight operators a number is asked —
  /// [`ScalarFilter`]'s, over the integer this family compares a cardinality as.
  ///
  /// # `$size` answers ONE of the eight, so this kind does not use it
  ///
  /// `{tags: {$size: 3}}` is the whole of MongoDB's query-language cardinality: the operand is a
  /// NUMBER and nothing else parses. Measured on 8.2.12 — `{$size: {$gt: 1}}` is *Failed to parse
  /// $size. Expected a number*, `2.5` is *Expected an integer*, `-1` is *Expected a non-negative
  /// number* — so `count: { gt: 3 }` has no spelling through it at all.
  ///
  /// That leaves two honest answers: refuse the seven operators `$size` cannot reach, or reach all
  /// eight another way. This kind takes the second, and four measurements decide it.
  ///
  /// **The index argument is not an argument.** `$size` cannot use an index either. An index on the
  /// collection column is MULTIKEY — it indexes the ELEMENTS, and a length is not one of them — so
  /// `{tags: {$size: 2}}` plans a `COLLSCAN` with `keysExamined: 0`, exactly as the `$expr` form
  /// does. Both are residual filters that a sargable predicate elsewhere in the same query still
  /// narrows. Whatever this decision costs, it does not cost a seek.
  ///
  /// **A partial answer would disagree with itself.** Splitting the slots — `$size` for `eq` and a
  /// refusal for the rest — leaves two renderings of one question, and a rendering that answers
  /// `count: { eq: 0 }` differently from `count: { lt: 1 }` is worse than either alone. One form for
  /// all eight cannot.
  ///
  /// **`$size` has a ceiling and the expression has none.** `{$size: 2147483648}` is *Cannot
  /// represent $size in an int*: the query operand is a 32-bit integer. The aggregation `$size`
  /// compares against whatever the expression yields, and the same operand goes through it without
  /// complaint.
  ///
  /// **The refusal it would replace has nowhere honest to stand.** A `count` refusal is not a
  /// property of the column or of the operand — every `gt` is unanswerable and every `eq` is fine —
  /// so it would be a whole operator group declined by this backend alone, for a reason no other
  /// backend has. All three SQL dialects answer all eight.
  ///
  /// # The guard is REQUIRED, and `$ifNull` is not it
  ///
  /// The aggregation `$size` takes an array and RAISES on anything else, which in a `find` is a
  /// query-fatal executor error rather than a non-match: measured, `{$expr: {$gt: [{$size:
  /// "$tags"}, 1]}}` against a collection holding one document with no `tags` field fails the whole
  /// query with *Location17124 … The argument to $size must be an array, but was of type: missing*.
  /// A single unrelated document is enough to break every query this kind writes.
  ///
  /// `{$ifNull: ["$tags", []]}` does not close it — measured, a document whose `tags` is a STRING
  /// still raises — and it is wrong even where it works: it counts a missing field as an empty
  /// collection, so `count: { eq: 0 }` would answer documents that have no such collection at all,
  /// where `{$size: 0}` answers only the empty array.
  ///
  /// What closes it is `$and`, whose aggregation form short-circuits: `{$and: [{$isArray: "$tags"},
  /// …]}` never evaluates the second expression for a document that would raise. Measured on
  /// 8.2.12, and the agreement is exact — the guarded `$expr` for `eq: 0` returns the same single
  /// document `{$size: 0}` does, where the `$ifNull` form returns three more.
  ///
  /// # So every operator is TYPE-BRACKETED, including `ne`
  ///
  /// A document whose field is absent or is not an array answers NO to all eight, `ne` included.
  /// That is the guard being uniform rather than an oversight, and it is where a cardinality parts
  /// from a field's own [`$ne`](super::MongoOperator::Ne), which matches an absent field. The
  /// question here presupposes a collection to have a length; whether the collection is there at
  /// all is [`MongoNullable`](super::MongoNullable)'s, and it is asked about the FIELD rather than
  /// about its length.
  ///
  /// # It is a KIND rather than a [`MongoScalarComparison`](super::MongoScalarComparison)
  ///
  /// The operators are the same eight and the operands the same shape, so the difference is not what
  /// it holds — it is what it is compared AGAINST. Every other comparison in this family names a
  /// FIELD and merges its operators under that key; this one names an EXPRESSION over a field, which
  /// no field's key can hold and which the collection strategy supplies.
  ///
  /// So it implements no [`ComplexComparison`](crate::ComplexComparison), and the absence is the
  /// point rather than an omission: `apply` takes an [`At`](crate::At) and would render
  /// `{tags: {$eq: 3}}`, a well-formed predicate asking whether the collection CONTAINS three. A
  /// scalar comparison in this slot could be applied that way by anyone holding it; this one cannot
  /// be applied at all, and reaches a filter only through `push_count_slots`, which has no spelling
  /// without a field path.
  ///
  /// The absence is visible from outside (`E0599`):
  ///
  /// ```compile_fail,E0599
  /// use ingraph::{
  ///   At, ComplexComparison, FieldName, RecordAddress, ScalarFilter, TryFromFilter,
  ///   comparison::mongo::{MongoConjunction, MongoCountComparison},
  /// };
  ///
  /// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
  /// let c = MongoCountComparison::<i64>::try_from_filter(ScalarFilter::<usize>::new().with_eq(3))
  ///   .unwrap();
  /// let frame = At::new(&ROW).frame(FieldName::new("tags"));
  /// let _ = c.apply(frame.at(), MongoConjunction::new());
  /// ```
  ///
  /// Its twin, which must COMPILE — stable rustdoc runs a `compile_fail` block just far enough to
  /// see it fail and never checks why, so the pair shares its call shape and one half has to be
  /// positive:
  ///
  /// ```
  /// use ingraph::{
  ///   At, ComplexComparison, FieldName, RecordAddress, ScalarFilter, TryFromFilter,
  ///   comparison::mongo::{MongoConjunction, MongoScalarComparison},
  /// };
  ///
  /// const ROW: RecordAddress = RecordAddress::new(FieldName::new("t"), &[FieldName::new("id")]);
  /// let c = MongoScalarComparison::<i64>::try_from_filter(ScalarFilter::<i64>::new().with_eq(3))
  ///   .unwrap();
  /// let frame = At::new(&ROW).frame(FieldName::new("tags"));
  /// let _ = c.apply(frame.at(), MongoConjunction::new());
  /// ```
  ///
  /// # `V` is the integer the CARDINALITY is compared as, not the element's
  ///
  /// A collection of any element type counts the same way, so this parameter never follows the
  /// element. Both collection kinds name `i64` for it — the width BSON's own `Int64` is — and the
  /// parameter is what leaves a backend whose cardinality is some other integer a type to name.
  MongoCountComparison {
    one { eq, ne, gt, gte, lt, lte }
    many { in_, not_in }
  }
}

impl<V> MongoCountComparison<V> {
  /// Cross a [`ScalarFilter`] over a cardinality into this comparison, converting each operand with
  /// `f`.
  ///
  /// The entry point the collection crossings reach, and the trait crossing below is this same call
  /// with the storage type's own [`TryFrom`] supplied — the arrangement
  /// [`MongoScalarComparison::try_from_filter_with`](super::MongoScalarComparison::try_from_filter_with)
  /// has, for the same reason.
  ///
  /// # Errors
  ///
  /// Whatever `f` refuses an operand with.
  pub fn try_from_filter_with<D, I, E, F>(filter: ScalarFilter<D, I>, f: F) -> Result<Self, E>
  where
    F: FnMut(D) -> Result<V, E>,
  {
    let stored = filter.try_map(f)?;
    Ok(Self {
      eq: stored.eq,
      ne: stored.ne,
      gt: stored.gt,
      gte: stored.gte,
      lt: stored.lt,
      lte: stored.lte,
      in_: stored.in_,
      not_in: stored.not_in,
    })
  }
}

/// The crossing with no declared converter: the storage type's own [`TryFrom`].
///
/// A cardinality filter's operands are `usize` — a collection's length is one — and this family
/// compares a cardinality as `i64`, so the crossing every collection makes is `i64: TryFrom<usize>`
/// and its error is [`TryFromIntError`](core::num::TryFromIntError). It REFUSES rather than
/// saturating: a `count` operand is a client's number, and a substituted one is a wrong result set
/// reported as a right one.
impl<D, I, V: TryFrom<D>> TryFromFilter<ScalarFilter<D, I>> for MongoCountComparison<V> {
  type Error = V::Error;

  fn try_from_filter(filter: ScalarFilter<D, I>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with(filter, V::try_from)
  }
}

/// The aggregation-expression names this kind writes, which are a THIRD vocabulary beside
/// [`MongoOperator`](super::MongoOperator) and the top-level keys.
///
/// Written as literals in one table rather than as a type, where a field operator is a type, and the
/// hazard is what separates them: `{a: {gt: 1}}` with the sigil dropped is a well-formed exact match
/// against a subdocument — a different question answered without complaint — while a `$expr` body is
/// read as an expression whose every key must be an operator, so `{gt: […]}` inside one is
/// *Unrecognized expression 'gt'*. The failure mode a type exists to prevent does not exist here.
///
/// Seven of them are spelled exactly as the field operator of the same name, and one has no twin:
/// there is no aggregation `$nin`, so `not_in` is `$not` around `$in`.
const IS_ARRAY: &str = "$isArray";
const SIZE: &str = "$size";
const AGGREGATE_AND: &str = "$and";
const AGGREGATE_NOT: &str = "$not";
const AGGREGATE_IN: &str = "$in";

/// Walk the eight slots against the cardinality of `field`, contributing one `$expr` per set
/// operator.
///
/// `field` is the RENDERED path — what [`field_path`](super::field_path) answers — and it becomes an
/// expression by taking a `$` prefix, which is how an aggregation names a field. The EMPTY path
/// therefore reaches the server as `$$`, and it is refused there loudly: *empty variable names are
/// not allowed*, since `$$` opens a variable reference. That is `ABSENT_FIELD`'s standard holding in
/// the one position where the standard's usual rendering would not — a top-level `$` is an unknown
/// operator, and a `$`-prefixed one inside an expression is an unknown variable.
///
/// The operator set and its ORDER are
/// [`MongoScalarComparison`](super::MongoScalarComparison)'s own, so a cardinality is asked in the
/// order a number is asked anywhere in this crate.
///
/// # ONE `$expr` per operator, and the guard is repeated inside each
///
/// A comparison setting `gt` and `lt` contributes two `$and` branches rather than one `$expr`
/// holding both, which is what makes a cardinality's conjuncts count the same way every other
/// kind's do. The `$isArray` guard is inside each because it is not a separate predicate — it is
/// what makes that expression evaluable at all, and a guard hoisted out of the expression it guards
/// is a guard that a later edit can leave behind.
///
/// # An EMPTY comparison contributes nothing, and nothing here checks for one
///
/// Every slot is guarded by its own `if let`, so a comparison with no operator set walks all eight
/// and writes nothing — the honest reading of the empty case, since a cardinality is not quantified
/// and asking nothing about one excludes no document. That is [`Nullable`](crate::Nullable)'s
/// fold-in rather than the element scope's quantifier, and it is why the collection kinds add what
/// this counts rather than one.
pub(super) fn push_count_slots<V: MongoCarrier>(
  comparison: &MongoCountComparison<V>,
  field: &str,
  out: &mut MongoConjunction,
) {
  let path = Bson::String(format!("${field}"));
  let size = || {
    let mut expression = Document::new();
    expression.insert(SIZE, path.clone());
    Bson::Document(expression)
  };
  for (slot, name) in [
    (&comparison.eq, "$eq"),
    (&comparison.ne, "$ne"),
    (&comparison.gt, "$gt"),
    (&comparison.gte, "$gte"),
    (&comparison.lt, "$lt"),
    (&comparison.lte, "$lte"),
  ] {
    if let Some(value) = slot {
      out.and(guarded(&path, compare(name, size(), value.to_bson())));
    }
  }
  if let Some(values) = &comparison.in_ {
    out.and(guarded(
      &path,
      compare(AGGREGATE_IN, size(), membership(values)),
    ));
  }
  if let Some(values) = &comparison.not_in {
    let mut negated = Document::new();
    negated.insert(
      AGGREGATE_NOT,
      Bson::Document(compare(AGGREGATE_IN, size(), membership(values))),
    );
    out.and(guarded(&path, negated));
  }
}

/// `{name: [subject, operand]}` — one aggregation comparison.
fn compare(name: &str, subject: Bson, operand: Bson) -> Document {
  let mut comparison = Document::new();
  comparison.insert(name, Bson::Array(vec![subject, operand]));
  comparison
}

/// `{$expr: {$and: [{$isArray: <path>}, <comparison>]}}` — one whole filter document, which is what
/// a top-level operator contributes.
fn guarded(path: &Bson, comparison: Document) -> Document {
  let mut guard = Document::new();
  guard.insert(IS_ARRAY, path.clone());

  let mut conjunction = Document::new();
  conjunction.insert(
    AGGREGATE_AND,
    Bson::Array(vec![Bson::Document(guard), Bson::Document(comparison)]),
  );

  let mut expression = Document::new();
  expression.insert(EXPR, Bson::Document(conjunction));
  expression
}

#[cfg(test)]
mod tests;