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 storage side of a [`DetectedLanguage`] query, behind the `sqlx` feature: the comparison a
//! [`DetectedLanguageFilter`] crosses into, and the crossing that gets it there.
//!
//! ```text
//! DetectedLanguageFilter                SqlDetectedLanguageComparison<Db>
//!   eq: "zh-Hans"            ──►          language: <the identity's four>
//!   language: { eq: "zh" }   ──►          language: "…_language" = ?
//!   confidence: { gte: 0.8 } ──►          confidence: "…_confidence" >= ?
//! ```
//!
//! # It is a WRAPPER, and almost nothing here is its own
//!
//! Every question about the identity is [`SqlLanguageIdComparison`]'s — the four columns, the null
//! guards, the disjunction of conjunctions — and this type adds one column beside it. So what this
//! module holds is the ADDRESSING (the identity is FLATTENED and the confidence takes a segment) and
//! the pairing, and nothing else: there is no second spelling of a predicate anywhere in it.
//!
//! That is what the flattened filter buys on the storage side. The identity axis is a whole
//! `LanguageIdFilter`, so its crossing is that filter's crossing and its refusal is that
//! comparison's refusal — [`LanguageIdCrossingError`], reused rather than restated, because it is
//! the same doubled equality being refused for the same reason.
//!
//! # ONE address arrives, and the two parts divide it
//!
//! The identity is applied at `at` UNCHANGED, which is what FLATTENING means: its own four segments
//! attach directly to whatever the caller addressed, so a detection at `detected` reaches
//! `detected_language` and its three siblings. The confidence pushes one segment of its own and
//! reaches `detected_confidence`.
//!
//! [`DetectedLanguageFilter`]: super::DetectedLanguageFilter

use core::fmt::{self, Display};

use crate::{
  At, Backend, Carrier, ComplexComparison, CompositeComparison, Score, ToDatabaseComparison,
  TryFromFilter,
  comparison::sql::{SqlConjunction, SqlScalarComparison},
};

use super::{
  super::{LanguageIdCrossingError, SqlLanguageIdComparison},
  DetectedLanguageFilter,
  storage::{CONFIDENCE, SEGMENTS},
};

// THE DIALECT GATE, and it is the house rule for a test that names one: every assertion below
// crosses a filter into `SqlDetectedLanguageComparison<Sqlite>`, and `sqlx::Sqlite` is a type the
// `sqlite` feature compiles. The CROSSING itself has no `Db` bound — which is exactly what the
// dialect-parity test in there asserts — so what the gate costs a lane without a driver is the
// checking of it and nothing else.
#[cfg(all(test, feature = "sqlite"))]
mod tests;

/// [`DetectedLanguageFilter`]'s storage-side twin: the identity's four columns, and the confidence.
///
/// Generic over the BACKEND and not one type per backend, for the reason its two halves are: the
/// identity's is argued next door, and [`Score`] has a carrier row in all three dialects that binds
/// the wrapped `f32`.
pub struct SqlDetectedLanguageComparison<Db> {
  language: SqlLanguageIdComparison<Db>,
  confidence: SqlScalarComparison<Score, Db>,
}

impl<Db> SqlDetectedLanguageComparison<Db> {
  /// The empty comparison — no operator set on either part.
  #[inline]
  pub const fn new() -> Self {
    Self {
      language: SqlLanguageIdComparison::new(),
      confidence: SqlScalarComparison::new(),
    }
  }

  /// The identity's whole comparison — four columns, and every question this family asks of them.
  #[inline]
  pub const fn language(&self) -> &SqlLanguageIdComparison<Db> {
    &self.language
  }

  /// The operators over the confidence column, whose storage type is [`Score`] itself.
  #[inline]
  pub const fn confidence(&self) -> &SqlScalarComparison<Score, Db> {
    &self.confidence
  }
}

/// The lowering: the identity at the address it was given, then the confidence one segment below.
impl<Db> ComplexComparison<Db> for SqlDetectedLanguageComparison<Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  String: Carrier<Db>,
  Score: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.language)
      + ComplexComparison::<Db>::conjuncts(&self.confidence)
  }

  /// The identity is applied at `at` UNCHANGED — flattening is exactly that — and the confidence one
  /// segment below it.
  ///
  /// Threading one accumulator through both is what makes the two facets guard ONE detection all
  /// the way down: the conjuncts join with ` AND `, so a row satisfies this comparison when its own
  /// identity and its own confidence both answer.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let builder = self.language.apply(at, builder)?;
    let confidence = at.frame(CONFIDENCE);

    self.confidence.apply(confidence.at(), builder)
  }
}

/// The one place all five column lists a detection spans are stated, read by the predicate and by
/// whatever emits the DDL.
impl<Db> CompositeComparison<Db> for SqlDetectedLanguageComparison<Db>
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  String: Carrier<Db>,
  Score: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

impl<Db> Default for SqlDetectedLanguageComparison<Db> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// Written out rather than derived, for the reason this crate's own comparison kinds write theirs
/// out: a derive would bound `Db`, which is a marker no dialect type implements anything for.
impl<Db> fmt::Debug for SqlDetectedLanguageComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlDetectedLanguageComparison")
      .field("language", &self.language)
      .field("confidence", &self.confidence)
      .finish()
  }
}

impl<Db> Clone for SqlDetectedLanguageComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      language: self.language.clone(),
      confidence: self.confidence.clone(),
    }
  }
}

impl<Db> PartialEq for SqlDetectedLanguageComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.language == other.language && self.confidence == other.confidence
  }
}

/// Every SQL dialect takes the detection filter to the detection comparison, and the storage type is
/// the PAIR rather than a parameter.
///
/// `V` is `(String, Score)` because the two halves hold different types, and one scalar `V` would
/// name one of them and hide the other — the shape every PAIRED comparison states. The identity's
/// four columns are all `String`, which is why one word covers them.
impl<Db> ToDatabaseComparison<(String, Score), Db> for DetectedLanguageFilter
where
  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
  String: Carrier<Db>,
  Score: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlDetectedLanguageComparison<Db>;
}

/// The crossing, and the only route into a [`SqlDetectedLanguageComparison`].
///
/// [`TryFromFilter`] because the identity's crossing can refuse, and the error is ITS error rather
/// than a second one wrapping it: the doubled equality is the same mistake in the same place,
/// whether the identity is a column of its own or a detection's half.
impl<Db> TryFromFilter<DetectedLanguageFilter> for SqlDetectedLanguageComparison<Db> {
  type Error = LanguageIdCrossingError;

  fn try_from_filter(filter: DetectedLanguageFilter) -> Result<Self, Self::Error> {
    // Destructured rather than read through the getters, so a field added to the filter tomorrow is
    // an `E0027` here instead of a facet silently not crossing.
    let DetectedLanguageFilter {
      language,
      confidence,
    } = filter;

    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
    // filter. The identity axis is SPLICED and so has no wrapper: its slots are this face's own
    // fields, and each of those already carries its absence.
    let confidence = confidence.unwrap_or_default();

    Ok(Self {
      language: SqlLanguageIdComparison::try_from_filter(language)?,
      // The confidence half's refusal is [`ScoreKind`](crate::ScoreKind)'s, and it belongs to the
      // EXACT width rather than to this one: a `ConfidenceOperand` is a value in `[0.0, 1.0]`
      // judged on its own digits at construction, `0.0` and `1.0` are exactly representable at
      // every binary width, and rounding to nearest never crosses a representable bound — so
      // [`Score`], which is binary, holds every operand that can be built. The arm cannot be taken,
      // and it is NOT folded into `Self::Error`: that error names the identity's doubled equality,
      // and widening it for a refusal no query can produce would publish a failure mode this
      // crossing has not got.
      confidence: SqlScalarComparison::try_from_filter(confidence)
        .expect("a binary width holds every confidence operand"),
    })
  }
}