Skip to main content

ingraph/primitives/lang/detected/
comparison.rs

1//! The storage side of a [`DetectedLanguage`] query, behind the `sqlx` feature: the comparison a
2//! [`DetectedLanguageFilter`] crosses into, and the crossing that gets it there.
3//!
4//! ```text
5//! DetectedLanguageFilter                SqlDetectedLanguageComparison<Db>
6//!   eq: "zh-Hans"            ──►          language: <the identity's four>
7//!   language: { eq: "zh" }   ──►          language: "…_language" = ?
8//!   confidence: { gte: 0.8 } ──►          confidence: "…_confidence" >= ?
9//! ```
10//!
11//! # It is a WRAPPER, and almost nothing here is its own
12//!
13//! Every question about the identity is [`SqlLanguageIdComparison`]'s — the four columns, the null
14//! guards, the disjunction of conjunctions — and this type adds one column beside it. So what this
15//! module holds is the ADDRESSING (the identity is FLATTENED and the confidence takes a segment) and
16//! the pairing, and nothing else: there is no second spelling of a predicate anywhere in it.
17//!
18//! That is what the flattened filter buys on the storage side. The identity axis is a whole
19//! `LanguageIdFilter`, so its crossing is that filter's crossing and its refusal is that
20//! comparison's refusal — [`LanguageIdCrossingError`], reused rather than restated, because it is
21//! the same doubled equality being refused for the same reason.
22//!
23//! # ONE address arrives, and the two parts divide it
24//!
25//! The identity is applied at `at` UNCHANGED, which is what FLATTENING means: its own four segments
26//! attach directly to whatever the caller addressed, so a detection at `detected` reaches
27//! `detected_language` and its three siblings. The confidence pushes one segment of its own and
28//! reaches `detected_confidence`.
29//!
30//! [`DetectedLanguageFilter`]: super::DetectedLanguageFilter
31
32use core::fmt::{self, Display};
33
34use crate::{
35  At, Backend, Carrier, ComplexComparison, CompositeComparison, Score, ToDatabaseComparison,
36  TryFromFilter,
37  comparison::sql::{SqlConjunction, SqlScalarComparison},
38};
39
40use super::{
41  super::{LanguageIdCrossingError, SqlLanguageIdComparison},
42  DetectedLanguageFilter,
43  storage::{CONFIDENCE, SEGMENTS},
44};
45
46// THE DIALECT GATE, and it is the house rule for a test that names one: every assertion below
47// crosses a filter into `SqlDetectedLanguageComparison<Sqlite>`, and `sqlx::Sqlite` is a type the
48// `sqlite` feature compiles. The CROSSING itself has no `Db` bound — which is exactly what the
49// dialect-parity test in there asserts — so what the gate costs a lane without a driver is the
50// checking of it and nothing else.
51#[cfg(all(test, feature = "sqlite"))]
52mod tests;
53
54/// [`DetectedLanguageFilter`]'s storage-side twin: the identity's four columns, and the confidence.
55///
56/// Generic over the BACKEND and not one type per backend, for the reason its two halves are: the
57/// identity's is argued next door, and [`Score`] has a carrier row in all three dialects that binds
58/// the wrapped `f32`.
59pub struct SqlDetectedLanguageComparison<Db> {
60  language: SqlLanguageIdComparison<Db>,
61  confidence: SqlScalarComparison<Score, Db>,
62}
63
64impl<Db> SqlDetectedLanguageComparison<Db> {
65  /// The empty comparison — no operator set on either part.
66  #[inline]
67  pub const fn new() -> Self {
68    Self {
69      language: SqlLanguageIdComparison::new(),
70      confidence: SqlScalarComparison::new(),
71    }
72  }
73
74  /// The identity's whole comparison — four columns, and every question this family asks of them.
75  #[inline]
76  pub const fn language(&self) -> &SqlLanguageIdComparison<Db> {
77    &self.language
78  }
79
80  /// The operators over the confidence column, whose storage type is [`Score`] itself.
81  #[inline]
82  pub const fn confidence(&self) -> &SqlScalarComparison<Score, Db> {
83    &self.confidence
84  }
85}
86
87/// The lowering: the identity at the address it was given, then the confidence one segment below.
88impl<Db> ComplexComparison<Db> for SqlDetectedLanguageComparison<Db>
89where
90  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
91  String: Carrier<Db>,
92  Score: Carrier<Db>,
93  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
94{
95  #[inline]
96  fn conjuncts(&self) -> usize {
97    ComplexComparison::<Db>::conjuncts(&self.language)
98      + ComplexComparison::<Db>::conjuncts(&self.confidence)
99  }
100
101  /// The identity is applied at `at` UNCHANGED — flattening is exactly that — and the confidence one
102  /// segment below it.
103  ///
104  /// Threading one accumulator through both is what makes the two facets guard ONE detection all
105  /// the way down: the conjuncts join with ` AND `, so a row satisfies this comparison when its own
106  /// identity and its own confidence both answer.
107  fn apply<'q>(
108    &'q self,
109    at: At<'_>,
110    builder: Db::Builder<'q>,
111  ) -> Result<Db::Builder<'q>, Db::Error> {
112    let builder = self.language.apply(at, builder)?;
113    let confidence = at.frame(CONFIDENCE);
114
115    self.confidence.apply(confidence.at(), builder)
116  }
117}
118
119/// The one place all five column lists a detection spans are stated, read by the predicate and by
120/// whatever emits the DDL.
121impl<Db> CompositeComparison<Db> for SqlDetectedLanguageComparison<Db>
122where
123  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
124  String: Carrier<Db>,
125  Score: Carrier<Db>,
126  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
127{
128  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
129}
130
131impl<Db> Default for SqlDetectedLanguageComparison<Db> {
132  #[inline]
133  fn default() -> Self {
134    Self::new()
135  }
136}
137
138/// Written out rather than derived, for the reason this crate's own comparison kinds write theirs
139/// out: a derive would bound `Db`, which is a marker no dialect type implements anything for.
140impl<Db> fmt::Debug for SqlDetectedLanguageComparison<Db> {
141  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142    f.debug_struct("SqlDetectedLanguageComparison")
143      .field("language", &self.language)
144      .field("confidence", &self.confidence)
145      .finish()
146  }
147}
148
149impl<Db> Clone for SqlDetectedLanguageComparison<Db> {
150  fn clone(&self) -> Self {
151    Self {
152      language: self.language.clone(),
153      confidence: self.confidence.clone(),
154    }
155  }
156}
157
158impl<Db> PartialEq for SqlDetectedLanguageComparison<Db> {
159  fn eq(&self, other: &Self) -> bool {
160    self.language == other.language && self.confidence == other.confidence
161  }
162}
163
164/// Every SQL dialect takes the detection filter to the detection comparison, and the storage type is
165/// the PAIR rather than a parameter.
166///
167/// `V` is `(String, Score)` because the two halves hold different types, and one scalar `V` would
168/// name one of them and hide the other — the shape every PAIRED comparison states. The identity's
169/// four columns are all `String`, which is why one word covers them.
170impl<Db> ToDatabaseComparison<(String, Score), Db> for DetectedLanguageFilter
171where
172  Db: sqlx::Database + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Buffer: Display>,
173  String: Carrier<Db>,
174  Score: Carrier<Db>,
175  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
176{
177  type Comparison = SqlDetectedLanguageComparison<Db>;
178}
179
180/// The crossing, and the only route into a [`SqlDetectedLanguageComparison`].
181///
182/// [`TryFromFilter`] because the identity's crossing can refuse, and the error is ITS error rather
183/// than a second one wrapping it: the doubled equality is the same mistake in the same place,
184/// whether the identity is a column of its own or a detection's half.
185impl<Db> TryFromFilter<DetectedLanguageFilter> for SqlDetectedLanguageComparison<Db> {
186  type Error = LanguageIdCrossingError;
187
188  fn try_from_filter(filter: DetectedLanguageFilter) -> Result<Self, Self::Error> {
189    // Destructured rather than read through the getters, so a field added to the filter tomorrow is
190    // an `E0027` here instead of a facet silently not crossing.
191    let DetectedLanguageFilter {
192      language,
193      confidence,
194    } = filter;
195
196    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
197    // filter. The identity axis is SPLICED and so has no wrapper: its slots are this face's own
198    // fields, and each of those already carries its absence.
199    let confidence = confidence.unwrap_or_default();
200
201    Ok(Self {
202      language: SqlLanguageIdComparison::try_from_filter(language)?,
203      // The confidence half's refusal is [`ScoreKind`](crate::ScoreKind)'s, and it belongs to the
204      // EXACT width rather than to this one: a `ConfidenceOperand` is a value in `[0.0, 1.0]`
205      // judged on its own digits at construction, `0.0` and `1.0` are exactly representable at
206      // every binary width, and rounding to nearest never crosses a representable bound — so
207      // [`Score`], which is binary, holds every operand that can be built. The arm cannot be taken,
208      // and it is NOT folded into `Self::Error`: that error names the identity's doubled equality,
209      // and widening it for a refusal no query can produce would publish a failure mode this
210      // crossing has not got.
211      confidence: SqlScalarComparison::try_from_filter(confidence)
212        .expect("a binary width holds every confidence operand"),
213    })
214  }
215}