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 interpretation → level-sequence map: [`ToDatabaseOrderBy`], the refinement an emitted order
//! CROSSES through ([`ToCrossedOrderBy`]), and the [`OrderLevel`] both are written in.
//!
//! This is the ORDER axis's twin of [`comparison::lower`](crate::comparison::lower), and the
//! geography is deliberately the same: a marker-keyed map per dialect, and a refinement beside it
//! carrying what an emitted expansion actually CALLS. What differs is the answer's kind. A filter's
//! crossing names a TYPE — the comparison it becomes — so its map carries an associated type and
//! pays the four bound walls that type costs at a generic dialect. An order's crossing names a
//! SEQUENCE, which is data, so this map carries a `const` and there is no projection for a `where`
//! clause to normalise.
//!
//! That difference is recorded rather than glossed, because it decides how much of the comparison
//! family's machinery is REAL here. [`ToCrossedComparison`](crate::comparison::ToCrossedComparison)
//! puts its crossing on METHODS to keep a projection off every bound — four measured errors are why.
//! [`ToCrossedOrderBy`] keeps the method SHAPE without the wall behind it: nothing in its signature
//! is a projection, so a caller at a generic `Db` was never going to be asked what the SQL family
//! demands of one. The shape is kept because the day a level sequence becomes a TYPE — a dialect
//! that lowers an order into its own sort document rather than into this crate's terms — the seat is
//! already the one that survives that change, and a caller written against it does not move.

use crate::{
  ColumnKind,
  comparison::Backend,
  marker::{
    BoolMarker, BytesMarker, CompositeMarker, DurationMarker, EnumMarker, ListMarker, Marker,
    NullableMarker, OptionalMarker, QuantifiedMarker, ScalarMarker, SetMarker, StringMarker,
  },
  state::{Extracted, Inner, State},
};

/// ONE level of the order a single wire term runs in: WHICH of the column type's leaves this level
/// sorts by, as an ordinal into that type's own [`SEGMENTS`](crate::ColumnKind::SEGMENTS).
///
/// # An ordinal rather than a name, and the reason is the joining law
///
/// A leaf's COLUMN NAME is never spelled in this crate: `at_nanos` is
/// [`Backend::write_column`](crate::Backend::write_column)'s join of the field's name and the
/// segment's, made once so that a `SELECT`, a `WHERE` and an `ORDER BY` are one join rather than
/// three concatenations free to differ. A level that named its leaf by string would be a second
/// joining rule and the first thing to drift. An ordinal names the same leaf through the walk that
/// already renders it.
///
/// The numbering is the LEAF numbering — the one [`width`](crate::width) counts and
/// [`OrderTerm::width`](crate::OrderTerm::width) iterates — and NOT the segment-list index. A nested
/// composite contributes its own leaves, so `MediaTimestamp`'s three segments are four levels:
/// `pts` is `0`, the timebase's `num` and `den` are `1` and `2`, and the derived `nanos` is `3`.
///
/// # A newtype rather than a bare `usize`
///
/// A leaf ordinal and a level ordinal are two numberings of one term that are equal only by
/// accident, and both are `usize`. Wrapping the one a type DECLARES is what keeps a sequence written
/// in the wrong numbering from compiling — the house rule a [`TermName`](crate::TermName) beside a
/// [`FieldName`](crate::FieldName) already states one seam over.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct OrderLevel(usize);

impl OrderLevel {
  /// The level sorting by the `leaf`-th column of the type's own segment tree.
  ///
  /// `const`, because a type's order sequence is declared once, with the type, and is read from a
  /// `const` item — the same shape [`ColumnKind::SEGMENTS`](crate::ColumnKind::SEGMENTS) is written
  /// in.
  #[inline]
  #[must_use]
  pub const fn new(leaf: usize) -> Self {
    Self(leaf)
  }

  /// Which leaf this level sorts by.
  #[inline]
  #[must_use]
  pub const fn leaf(self) -> usize {
    self.0
  }
}

/// An INTERPRETATION mapped to the LEVEL SEQUENCE one wire term over it sorts by, at one backend.
///
/// Implemented for the markers in [`crate::marker`] and for nothing else — [`ToGraphqlFilter`]'s
/// keying, for [`ToGraphqlFilter`]'s reason: a type does not determine its own reading, so a trait
/// keyed on the type would answer once, for the declarer. A declaration reaches this through
/// [`DefaultMarker`](crate::DefaultMarker).
///
/// # The EMPTY sequence is the DECLARATION ORDER, and it is the default for that reason
///
/// Almost every reading sorts by its leaves in the sequence the type declares them, and a scalar —
/// one leaf — cannot sort any other way. So `&[]` is the answer that means *the segments, as
/// declared*, exactly as an empty [`SEGMENTS`](crate::ColumnKind::SEGMENTS) is the answer that means
/// *one column*. A reading that states nothing here is behaviourally identical to what this
/// framework rendered before the map existed, which is what makes the map's arrival a
/// no-op for every existing declaration.
///
/// # Where a NON-default sequence comes from, and why it is not stated here
///
/// The type's own, through [`ColumnKind::ORDER`](crate::ColumnKind::ORDER). A composite citizen
/// declares what it is stored as and, beside it, what ORDER those columns mean — which is one fact
/// about one type, written where the other one is. A row here that named a citizen would be this
/// map deciding a downstream type's semantics, which is the closed surface the framework refuses
/// everywhere else: a downstream citizen teaches its own order by overriding a const in the
/// [`ColumnKind`](crate::ColumnKind) impl it already writes, with no second registration to
/// remember.
///
/// # `Db` is a parameter even where every dialect agrees today
///
/// All three shipped SQL dialects sort a composite's leaves the same way, so every row below ignores
/// its parameter. It is carried all the same, for
/// [`ToDatabaseComparison`](crate::ToDatabaseComparison)'s reason one axis over: what a dialect
/// SORTS BY is a dialect's answer, and a document family that nests a composite rather than
/// flattening it has a genuinely different sequence to give. A map without the parameter would have
/// to grow one the day that row is written, and every caller would move with it.
///
/// [`ToGraphqlFilter`]: crate::ToGraphqlFilter
pub trait ToDatabaseOrderBy<Db: Backend> {
  /// The leaves one wire term over this reading sorts by, in ORDER sequence — EMPTY for the
  /// declaration order, which is every reading's answer but a semantic citizen's.
  const LEVELS: &'static [OrderLevel] = &[];
}

// The FLAT readings, and every one of them takes the declaration order. A scalar, a string, a byte
// string, an enum, a boolean and a duration are each ONE column, so there is no sequence for a row
// here to permute — the empty answer is not a deferral but the only order one column has.
impl<T, Db: Backend> ToDatabaseOrderBy<Db> for ScalarMarker<T> {}

impl<T, Db: Backend> ToDatabaseOrderBy<Db> for StringMarker<T> {}

impl<T, Db: Backend> ToDatabaseOrderBy<Db> for BytesMarker<T> {}

impl<T, Db: Backend> ToDatabaseOrderBy<Db> for EnumMarker<T> {}

impl<T, Db: Backend> ToDatabaseOrderBy<Db> for BoolMarker<T> {}

impl<T, Db: Backend> ToDatabaseOrderBy<Db> for DurationMarker<T> {}

#[cfg(feature = "flags")]
impl<T, Db: Backend> ToDatabaseOrderBy<Db> for crate::FlagsMarker<T> {}

/// The ONE reading whose sequence can differ from its declaration, and the whole reason this map is
/// not a constant.
///
/// It reads [`ColumnKind::ORDER`] rather than carrying a table of citizens, which is the
/// framework-open half of the design: what a composite MEANS is the composite's, so the type that
/// declares what it is stored as declares what order those columns are in, and a downstream citizen
/// joins by overriding one const in an impl it already writes.
impl<T: ColumnKind, Db: Backend> ToDatabaseOrderBy<Db> for CompositeMarker<T> {
  const LEVELS: &'static [OrderLevel] = <T as ColumnKind>::ORDER;
}

// The three COLLECTION readings. A collection is ONE column of the row whatever it holds — the width
// `impl<T> ColumnKind for Vec<T>` states — so like the flat readings it has no sequence to permute.
// That holds for all three storage forms: a native array is one column, an edge-stored collection is
// no column of this row at all, and a `sortable` one is its companion's single blob.
impl<T, VM, Db: Backend> ToDatabaseOrderBy<Db> for ListMarker<T, VM>
where
  VM: Marker,
  T: State<Extracted<Inner>, Output = VM::Marked>,
{
}

impl<T, VM, Db: Backend> ToDatabaseOrderBy<Db> for SetMarker<T, VM>
where
  VM: Marker,
  T: State<Extracted<Inner>, Output = VM::Marked>,
{
}

impl<T, VM, Db: Backend> ToDatabaseOrderBy<Db> for QuantifiedMarker<T, VM>
where
  VM: Marker,
  T: State<Extracted<Inner>, Output = VM::Marked>,
{
}

// The two TRANSPARENT readings, which add no column and therefore no level: an optional or nullable
// composite is stored in exactly the columns the composite is, with the same meaning in the same
// sequence, and what the wrapper changes is whether they may be `NULL` rather than what order they
// run in. So each forwards its inner reading's sequence and states none of its own — the same
// transparency `ToGraphqlFilter` gives the pair one axis over.
impl<T, VM, Db: Backend> ToDatabaseOrderBy<Db> for NullableMarker<T, VM>
where
  VM: ToDatabaseOrderBy<Db> + Marker,
  T: State<Extracted<Inner>, Output = VM::Marked>,
{
  const LEVELS: &'static [OrderLevel] = <VM as ToDatabaseOrderBy<Db>>::LEVELS;
}

impl<T, VM, Db: Backend> ToDatabaseOrderBy<Db> for OptionalMarker<T, VM>
where
  VM: ToDatabaseOrderBy<Db> + Marker,
  T: State<Extracted<Inner>, Output = VM::Marked>,
{
  const LEVELS: &'static [OrderLevel] = <VM as ToDatabaseOrderBy<Db>>::LEVELS;
}

/// **The level sequence an emitted order SPENDS on one column, reached without naming a numbering**
/// — the map above refined to the two questions a lowering actually asks it.
///
/// # Why the facts are METHODS, and what is honestly NOT the reason
///
/// [`ToCrossedComparison`](crate::comparison::ToCrossedComparison) puts its crossing on methods to
/// keep a projection off every bound, and its note carries the four measured errors that forced it.
/// **That wall does not bite here**, and saying so is worth more than borrowing the argument: this
/// map's answer is a `const`, not an associated type, so there is no projection for a `where` clause
/// to resolve and nothing for a generic `Db` to be asked about.
///
/// What the methods buy instead is the SPELLING. A caller wants *the `at`-th leaf of this column's
/// order*, and reading it off the const means writing the empty-sequence fallback at every call
/// site — the `if LEVELS.is_empty() { at } else { LEVELS[at].leaf() }` that turns one convention
/// into N copies of it. One method is that convention held in one place, which is the same reason
/// [`OrderTerm::width`](crate::OrderTerm::width) exists beside
/// [`segments`](crate::OrderTerm::segments).
///
/// # Blanket-implemented, deliberately — a downstream joins one level down
///
/// [`ToCrossedComparison`](crate::comparison::ToCrossedComparison)'s arrangement, for its reason:
/// nothing implements this by hand, and a reading joins by having a [`ToDatabaseOrderBy`] row. There
/// is no second registration, and no way for the refinement to disagree with the map it refines.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no order at `{Db}` — nothing says which leaves one term over it sorts by",
  label = "this column's reading cannot be ordered at that database",
  note = "a reading is orderable where it has a `ToDatabaseOrderBy<{Db}>` row; a composite citizen \
          states a non-default sequence through `ColumnKind::ORDER`"
)]
pub trait ToCrossedOrderBy<Db: Backend>: ToDatabaseOrderBy<Db> {
  /// The `at`-th leaf this reading's one wire term sorts by.
  ///
  /// `at` is a LEVEL ordinal and the answer is a LEAF ordinal; for the declaration order the two are
  /// equal, which is exactly what the empty sequence means. Out of range for a declared sequence is
  /// `at` itself — the identity — rather than a panic: a caller iterating a term's own
  /// [`width`](crate::OrderTerm::width) cannot reach it, and a sequence shorter than the type is
  /// a declaration bug that should surface as the leaf it forgot rather than as a crash inside a
  /// statement.
  #[inline]
  fn level(at: usize) -> usize {
    match <Self as ToDatabaseOrderBy<Db>>::LEVELS.get(at) {
      Some(level) => level.leaf(),
      None => at,
    }
  }

  /// Whether this reading states an order of its own, rather than taking its leaves as declared.
  ///
  /// What a renderer asks before it walks: a reading that answers `false` needs no permutation at
  /// all, which is the case every scalar and every non-semantic composite is in.
  #[inline]
  fn reorders() -> bool {
    !<Self as ToDatabaseOrderBy<Db>>::LEVELS.is_empty()
  }
}

/// The row itself — see the trait's note for why nothing implements it by hand.
impl<M, Db> ToCrossedOrderBy<Db> for M
where
  Db: Backend,
  M: ToDatabaseOrderBy<Db>,
{
}

#[cfg(test)]
mod tests;