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 FIVE columns a [`DetectedLanguage`] spans, and the two facts that follow from them.
//!
//! ```text
//!   SEGMENTS   <the identity's four, FLATTENED>, confidence
//!   Carrier    ?, ?, ?, ?, ?
//!   MongoCarrier  the identity's four KEYS, then confidence — one document, five keys
//! ```
//!
//! # The identity is FLATTENED rather than nested, which is what keeps the column names flat
//!
//! [`ColumnShape::Composite`] carries an optional field name, and the difference between naming it
//! and leaving it out is one path segment per column. A detection at `detected` reaches
//! `detected_language`, `detected_script`, `detected_region`, `detected_rest` and
//! `detected_confidence` — five columns, one prefix. Naming the composite's own field would have
//! given `detected_language_language`, which says the same word twice and buys nothing: a detection
//! holds exactly one identity, so there is nothing for that segment to disambiguate.
//!
//! # There is no `Assemble` and no `CursorValue` here, and both absences are the same one
//!
//! [`LanguageId`](super::super::LanguageId) has both because a column of identities is a thing a
//! declaration holds and a page walks. A DETECTION is a member of a `Vec` — see this type's
//! [`DefaultVecMarker`](crate::DefaultVecMarker) row — so what a row holds is the collection, and
//! reading one out of a row and paging past one are both questions asked of the collection's own
//! storage rather than of the element. The day a declaration holds a BARE detection, both rows are
//! written the way `LanguageId`'s are.
//!
//! **The two WRITE rows are here anyway, and that is not an inconsistency.** A decode and a cursor
//! are questions asked ABOUT A COLUMN, so an element that occupies none has neither; a bind and a
//! document form are what one VALUE looks like, which an element has whether or not it is the whole
//! of a field. `Carrier` has always been here for that reason, and `MongoCarrier` joins it under it.

use crate::{ColumnKind, ColumnName, ColumnShape, FieldName, column::column_eq, flattened};

use super::{super::LanguageId, DetectedLanguage};
// The identity's own sub-document reader, shared rather than re-derived — see this file's
// `MongoExtract` row for why a detection reads the SAME four keys `LanguageId`'s own row does.
#[cfg(feature = "mongo")]
use super::super::id::document_seats;

/// The confidence column's segment — the one this type adds to the identity's four.
pub(crate) const CONFIDENCE: &FieldName = FieldName::new("confidence");

/// **The five columns a detection spans**: the identity's four, flattened, then the confidence.
///
/// `confidence` rather than `score`, which is what a CLASSIFIER's degree column is called where one
/// is declared. The two hold the same type and the names differ because the two rulings named them
/// differently — a classifier's is a SCORE, a detector's is a CONFIDENCE. It is recorded rather than
/// quietly unified because a schema with both words in it is a thing a client reads, and whichever
/// way it is eventually settled should be settled deliberately.
pub(super) const SEGMENTS: &[ColumnShape] = &[
  flattened::<LanguageId>(),
  ColumnShape::Plain(ColumnName::of(CONFIDENCE)),
];

/// **The STORAGE half of the width** — five columns, and the identity's four are its own.
impl ColumnKind for DetectedLanguage {
  const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
}

/// **One leaf, and it is the value.** A detected language means its identity then its confidence, as declared.
impl crate::DeclaredLeaves for DetectedLanguage {}

// A detection is one column value when the identity and the confidence both are — the same
// pairing this type's own `PartialEq` already reads: the same language at a different confidence
// is a different detection.
column_eq! { DetectedLanguage }

/// **The DECLARED half — FIVE words, of which the identity's FOUR are read off its own row.**
///
/// The identity's entry above is [`flattened::<LanguageId>()`](crate::flattened), which lends no
/// name but spans four columns all the same, so four of the five words are that type's and this row
/// indexes them rather than restating that a language identity is text four times over. The fifth is
/// the confidence, whose word is [`Score`](crate::Score)'s — a `Confidence<f32>`, declared at the
/// width it measures in.
impl<Db> crate::StoredAs<Db> for DetectedLanguage
where
  LanguageId: crate::StoredAs<Db>,
  crate::Score: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <LanguageId as crate::StoredAs<Db>>::WORDS[0],
    <LanguageId as crate::StoredAs<Db>>::WORDS[1],
    <LanguageId as crate::StoredAs<Db>>::WORDS[2],
    <LanguageId as crate::StoredAs<Db>>::WORDS[3],
    <crate::Score as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION**, written by the declaration because the declaration is the only party that
/// knows.
///
/// [`CollectionElement`](crate::CollectionElement) states one fact a width cannot: whether this type
/// is itself MANY. A detection is a language identity and a number, so it is not — and this row is
/// what says so, exactly as [`Timestamp`](crate::Timestamp)'s does one file over. A record declaring
/// `Vec<DetectedLanguage>` sees two token trees and could not have told.
///
/// It is the first admitted element whose own parts NEST. The identity is
/// [`flattened`](crate::flattened) above, so this element's columns are five LEAVES rather than two
/// parts, and the edge table writes the five under the collection's path — `heard_language`,
/// `heard_script`, `heard_region`, `heard_rest`, `heard_confidence` — which is the same list the
/// DIRECT column of a detection already occupies. That is the whole of what admitting a nested
/// element took: the names were never a second convention, only a walk that had to descend.
impl crate::CollectionElement for DetectedLanguage {}

/// **N BINDS OUT** — the identity's four placeholders, then the confidence.
///
/// The identity writes its own three commas, which is the arrangement
/// [`Carrier`](crate::Carrier) documents: how many columns a value spans is the value's own
/// answer, so a composite pushes several placeholders with its own separators and the caller counts
/// FIELDS.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for DetectedLanguage
where
  Db: sqlx::Database,
  LanguageId: crate::Carrier<Db>,
  crate::Score: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <LanguageId as crate::Carrier<Db>>::push_bind(self.language(), qb);
    qb.push(", ");
    <crate::Score as crate::Carrier<Db>>::push_bind(&self.confidence(), qb);
  }
}

/// **THE DOCUMENT'S FORM: FIVE KEYS AT ONE LEVEL** — the identity's four, then the confidence.
///
/// ```text
///   { "language": "zh", "script": "Hans", "region": null, "rest": null, "confidence": 0.94 }
/// ```
///
/// # The identity is SPLICED here and NESTED when it is a field of its own, and that is one rule
///
/// [`LanguageId`]'s own row writes a sub-document, because MongoDB's default for a composite IS the
/// nested one — its declaration block has no `flatten` word at all, there being no rendered prefix
/// to drop. What decides the shape here is not a second policy but the SEGMENTS above: the identity's
/// entry is [`flattened::<LanguageId>()`](crate::flattened), which lends NO NAME, and a key set is
/// built out of names. There is no key to nest under, so its four join this document's own — which is
/// the same thing the SQL side does with the same entry, in the spelling that family has for it.
///
/// It is also the addressing the comparison next door already writes.
/// [`SqlDetectedLanguageComparison`](super::SqlDetectedLanguageComparison) applies the identity at
/// `at` UNCHANGED and pushes one segment for the confidence, so a detection at `heard` is asked about
/// as `heard_language` and `heard_confidence` in a table and would be asked as `heard.language` and
/// `heard.confidence` in a document. Nesting the identity under a name would have made those
/// `heard.language.language` — the doubled word this file's `SEGMENTS` note already refused once, in
/// the other family's spelling.
///
/// # The CONFIDENCE is a `Double`, through the width's own row
///
/// [`Score`](crate::Score) is a `Confidence<f32>` and the register's confidence row carries every
/// width that has one: BSON's only binary float is 64 bits, and an `f32` widens into it exactly. The
/// `[0.0, 1.0]` invariant is the DOMAIN's rather than the column's, so nothing about it is encoded —
/// which is the same sentence the SQL bind makes by binding the wrapped float.
///
/// # What SPENDS this row today, stated rather than implied
///
/// No operand of [`DetectedLanguageFilter`](super::DetectedLanguageFilter) is a whole detection —
/// the identity axis crosses on a [`LanguageIdOperand`](super::super::LanguageIdOperand) and the
/// confidence on a threshold — so nothing in this family's own filter compares against the shape
/// below. What it states is what a DOCUMENT holding a detection looks like, which is the fact a
/// `Vec<DetectedLanguage>` field needs and the one a comparison over a whole collection would bind.
/// It is written now for the reason the whole family's faces are: a shape decided beside its own
/// SEGMENTS is a shape one authority produced, and a shape decided later is one invented twice.
///
/// As with every other row here, this is the FILTER OPERAND's form and not a serde row — see
/// [`LanguageId`]'s, where the `E0277` a bare column earns at the declaration is named.
#[cfg(feature = "mongo")]
impl crate::MongoCarrier for DetectedLanguage {
  fn to_bson(&self) -> bson::Bson {
    let bson::Bson::Document(mut detection) = crate::MongoCarrier::to_bson(self.language()) else {
      // Unreachable: `LanguageId`'s row above writes a document and nothing else. Answering with the
      // identity's own value rather than panicking keeps an impossible case a wrong shape a reader
      // can see instead of a process that stopped.
      return crate::MongoCarrier::to_bson(self.language());
    };

    detection.insert(
      CONFIDENCE.as_str(),
      crate::MongoCarrier::to_bson(&self.confidence()),
    );

    bson::Bson::Document(detection)
  }
}

/// **THE READ: the identity's four keys back through their own door, then the confidence** —
/// [`MongoCarrier`](crate::MongoCarrier)'s mirror, splicing where that row splices and nowhere
/// nesting where it does not.
///
/// # The four identity keys are [`document_seats`]'s, unchanged
///
/// The write above builds a detection's document by taking the identity's OWN document and adding
/// one key, because there is no key to nest the identity under. The read takes the same document
/// ONCE and reads five keys out of it: the same [`document_seats`] `LanguageId`'s own row calls,
/// handed the whole document rather than a sub-document of it, and then `confidence` beside it.
/// Nothing here re-derives what a key means or what refuses it — a `script` holding the wrong BSON
/// type is refused by the exact same sentence whether it arrived on a bare identity or a detection.
///
/// # The CONFIDENCE reads through [`Score`](crate::Score)'s own row, which already exists
///
/// [`Score`](crate::Score) is [`Confidence<f32>`](crate::Confidence) and the register's generic
/// `MongoExtract` row for [`Confidence`](crate::Confidence) already covers it — an out-of-domain
/// double is refused the same way any other confidence's is. Nothing new is written for this key;
/// it is read exactly as a bare `Score` column would be.
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for DetectedLanguage {
  const BSON: &'static str = "object";

  fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
    let held = match value {
      Some(bson::Bson::Document(held)) => held,
      Some(other) => {
        return Err(crate::query::mongo::MongoTypeError::wrong_type(
          Self::BSON,
          crate::query::mongo::alias(other),
        ));
      }
      None => return Err(crate::query::mongo::MongoTypeError::Absent),
    };

    let language = document_seats(held)?;
    let confidence = crate::Score::extract(held.get(CONFIDENCE.as_str()))?;

    Ok(DetectedLanguage::new(language, confidence))
  }
}