ingraph/primitives/mediatime/timebase/comparison.rs
1//! The storage side of a [`Timebase`] query, behind the `sqlx` feature: the comparison a
2//! [`TimebaseFilter`] crosses into, and the crossing that gets it there.
3//!
4//! ```text
5//! TimebaseFilter SqlTimebaseComparison<Db>
6//! eq: "2/180000" ──► num: eq 1 ──► WHERE "tb_num" = ?
7//! (any of the three shapes) den: eq 90000 AND "tb_den" = ?
8//!
9//! in: ["1/90000", "1/1000"] ──► members ──► AND ("tb_num", "tb_den")
10//! IN ((?, ?), (?, ?))
11//!
12//! ne / notIn ──► excluded ──► AND NOT (( … ) IN (( … )))
13//!
14//! contains: "/90000" ──► contains ──► AND CONCAT("tb_num", '/',
15//! "tb_den") LIKE ?
16//!
17//! numerator: { gt: 1 } ──► num: gt 1 ──► AND "tb_num" > ?
18//! ```
19//!
20//! # Both sides reduce, through one function
21//!
22//! [`Timebase::reduced`] is that function, and it is public so that the WRITE path uses the same
23//! one — see [`storage`](super::storage), where the bind calls it. Reducing on one side only is a
24//! SILENT MISS: `eq: "2/180000"` would fail to match a row written from `1/90000`, with no error and
25//! no wrong value to look at, just rows that never come back. It is the failure shape an index-side
26//! and query-side tokenizer disagreeing has, and it earns the same guard — a test asserting that the
27//! pair a write would store and the pair a query binds are the same pair.
28//!
29//! What reduction buys is that storage equality IS value equality: a reduced pair is unique, so an
30//! index on `(num, den)` answers `eq` exactly. What it costs is the declared spelling, which
31//! [`Display`](core::fmt::Display) keeps and storage does not — and the RENDER facet is the one
32//! place a client can see that cost, since what it matches against is the stored pair's rendering.
33//!
34//! # Every facet crosses, and the row value is why three of them can
35//!
36//! An earlier shape of this comparison refused `ne`, `in` and `not_in` outright, on the ground that
37//! a comparison lowers into an AND accumulator and only `eq` decomposes into one. That ground was
38//! real and the conclusion was too strong: what does not decompose into SEVERAL conjuncts still fits
39//! in ONE, and the ROW VALUE is the spelling that puts it there.
40//!
41//! | facet slot | lowering | why that spelling |
42//! |---|---|---|
43//! | `eq` | `num = ? AND den = ?` | `(a, b) = (1, 10)` IS the conjunction — equality is the one operator that decomposes |
44//! | `in` | `("num", "den") IN ((?, ?), …)` | the disjunction of conjunctions, FLAT — [`SqlKeyIn`]'s own measured spelling |
45//! | `ne`, `not_in` | `NOT (( … ) IN (( … )))` | De Morgan, and it is why the two share ONE slot |
46//! | `starts_with` … | `CONCAT(num, '/', den) LIKE ?` | the stored pair's rendering, built in SQL |
47//! | `numerator`, `denominator` | `num > ?` | one column, one predicate — unchanged |
48//!
49//! **`ne` and `not_in` are ONE slot because excluding is conjunctive where including is not.**
50//! `NOT (x OR y)` is `NOT x AND NOT y`, so excluding one value and excluding a set is excluding
51//! their union — and the union is one `NOT IN`. That is not a shortcut: two separate `NOT IN`
52//! conjuncts would render the same rows, and merging them means the ceiling below is counted once
53//! against the sum rather than twice against the halves.
54//!
55//! The trap this shape exists to make unwritable is the one that LOOKS like it decomposes:
56//! `num IN (1, 2) AND den IN (90000, 1000)` is the CARTESIAN PRODUCT, so `in: ["1/90000", "2/1000"]`
57//! spelled that way also returns `1/1000` and `2/90000` — rows nobody asked for, in valid SQL of the
58//! right shape with the right bind count. Nothing in the rendered text separates the two. The row
59//! value is a type here rather than a rule someone follows, because [`SqlKeyIn`] is what holds the
60//! operands and it has no other spelling.
61//!
62//! What is still refused is the ORDERING of a whole timebase, and it is refused STRUCTURALLY — no
63//! slot on the filter takes one. Rational order is `num₁ · den₂` against `num₂ · den₁`, which is an
64//! expression rather than a column and costs the index, and it is a different order from the stored
65//! pair's lexicographic one: `1/1000` is the larger rational and the lower pair. A filter that
66//! cannot express the question needs no error to refuse it with.
67//!
68//! # The RENDER facet builds its subject in SQL, and the alphabet is what makes that portable
69//!
70//! `CONCAT(num, '/', den)` is the stored pair as text, and `LIKE` over it answers the three affix
71//! questions. Two properties make that one rendering rather than one per dialect:
72//!
73//! - **`CONCAT` is the spelling all three share.** `||` is the SQL-standard concatenation operator
74//! and is what SQLite and PostgreSQL use — and in MySQL it is LOGICAL OR unless `PIPES_AS_CONCAT`
75//! is set, so a `||` rendering would silently mean something else there. `CONCAT` is a function in
76//! all three, and coerces its integer arguments in all three.
77//! - **`LIKE`'s dialect differences cannot be observed on this subject.** SQLite folds ASCII case in
78//! `LIKE` and MySQL folds by collation, which is exactly why `ingraph`'s own text kind renders
79//! three concrete lowerings and reaches for `instr` on SQLite. The subject here is two decimal
80//! integers and a slash — a string with no letters in it — so there is no case to fold and the
81//! three dialects answer alike.
82//!
83//! **The operand's alphabet is checked at this crossing**, and that is what removes the `ESCAPE`
84//! clause the two `LIKE` dialects would otherwise need: `%`, `_` and `\` are refused before a
85//! pattern is built, so no metacharacter can reach one. The refusal is not a narrowing — a rendering
86//! made of `[0-9/]` cannot CONTAIN those characters, so an operand holding one names no row either
87//! way. What the refusal buys over silently matching nothing is that a client hears why, and what it
88//! buys over escaping is that the `ESCAPE` literal — `'\'` on Postgres, `'\\'` on MySQL, one of the
89//! few places their text is genuinely not one text — never has to be spelled here.
90//!
91//! # ONE address arrives, and each half pushes its own segment
92//!
93//! [`ComplexComparison::apply`] takes an [`At`], and a timebase occupies two columns — which is not
94//! the contradiction it reads as. An address carries a PATH rather than a name, so each half pushes
95//! one segment onto whatever it was handed: an address at `timebase` reaches `timebase_num` and
96//! `timebase_den`, and the SAME comparison applied at the TOP LEVEL reaches `num` and `den`, because
97//! the top level is the EMPTY path and a segment pushed onto nothing is the whole column name. A
98//! composite handed a NAME cannot render that second case at all — there is no name that produces a
99//! bare `num` — which is why the address is a path and not a prefix.
100//!
101//! Nothing here invents a spelling rule, because nothing here spells an identifier. The segments go
102//! to [`Backend::write_column`], which runs them together and brackets the result as its own family
103//! does, so both the `_` and the quoting are the backend's — and whatever emits the DDL is the party
104//! that has to agree with them. The segment names themselves are [`SEGMENTS`](super::storage), read
105//! by the width, the bind, the decode and every lowering below.
106//!
107//! What the shape closes is a defect rather than a difference of taste. A lowering handed one name
108//! PER column takes two parameters of one type, which can be passed in the wrong order; both orders
109//! render valid SQL of the same shape, so no assertion over the rendered text can see it.
110//!
111//! # Why the two component slots WRAP `SqlScalarComparison` instead of restating it
112//!
113//! Each is eight operators over one `i32`, which is exactly what [`SqlScalarComparison<i32,
114//! Db>`](SqlScalarComparison) already is. Wrapping takes `ingraph`'s rendering with it — the
115//! `NOT ( … )` spelling of a negation, the `1 = 0` an empty `in` degenerates to — where a struct
116//! with its own sixteen slots would have to reproduce both conventions and could drift from them. It
117//! is also the only route in: the kind's slots are `pub(crate)` to `ingraph` and its constructors are
118//! `new` and the crossing, so a comparison is BUILT by crossing a filter and in no other way.
119//!
120//! [`TimebaseFilter`]: super::TimebaseFilter
121
122use core::fmt::{self, Display};
123
124use smol_bytes::Utf8Bytes;
125
126use crate::{
127 At, Backend, BindCeiling, Carrier, ComplexComparison, CompositeComparison, ToDatabaseComparison,
128 TryFromFilter,
129 comparison::sql::{
130 SqlConjunction, SqlKeyIn, SqlLoweringError, SqlScalarComparison, render_column,
131 },
132};
133
134use super::{
135 super::rational::Affix,
136 Timebase, TimebaseFilter,
137 storage::{DEN, NUM, SEGMENTS},
138};
139
140// The DIALECT this house's crossing tests render against is Postgres — its NUMBERED placeholders are
141// what say which operand reached which column, where a `?` dialect can only say how many there were —
142// so the module names `sqlx::Postgres` and needs that driver rather than the family root alone.
143//
144// The source crate carried a bare `#[cfg(test)]` here and never felt it, its own `sqlx` word arriving
145// with a dialect behind it. In this crate `sqlx` is the family ROOT and a dialect is a word of its
146// own, so the gate has to name the one it spells. It is the divergence the language family recorded
147// on the same move — per-dialect gates replacing a single `sqlx` word — read one dialect over.
148#[cfg(all(test, feature = "postgres"))]
149mod tests;
150
151/// The two column names a key set names, in the order [`SEGMENTS`](super::storage) lists them.
152///
153/// [`SqlKeyIn`] takes its parts as strings rather than as `FieldName`s, so this is the one place the
154/// two segments are spelled in a second vocabulary — and it reads them off the shared constants
155/// rather than repeating the literals, so a rename still has one home.
156const PARTS: [&str; 2] = [NUM.as_str(), DEN.as_str()];
157
158/// [`TimebaseFilter`]'s storage-side twin: the two columns a reduced timebase occupies, the
159/// whole-value memberships over the pair, and the affix questions over its rendering.
160///
161/// Generic over the BACKEND and not one type per backend. Nothing a timebase adds is
162/// dialect-specific — both halves store as `i32`, which every SQL dialect carries natively, and `Db`
163/// selects that carrier at the lowering — and the render facet's own portability is argued in the
164/// module docs rather than assumed. There is no carrier newtype here for the same reason: a carrier
165/// owns an ENCODING a column must hold, and a reduced `i32` needs none.
166pub struct SqlTimebaseComparison<Db> {
167 numerator: SqlScalarComparison<i32, Db>,
168 denominator: SqlScalarComparison<i32, Db>,
169 members: Option<SqlKeyIn<i32, Db, 2>>,
170 excluded: Option<SqlKeyIn<i32, Db, 2>>,
171 starts_with: Option<Utf8Bytes>,
172 ends_with: Option<Utf8Bytes>,
173 contains: Option<Utf8Bytes>,
174}
175
176impl<Db> SqlTimebaseComparison<Db> {
177 /// The empty comparison — no operator set on any facet.
178 #[inline]
179 pub const fn new() -> Self {
180 Self {
181 numerator: SqlScalarComparison::new(),
182 denominator: SqlScalarComparison::new(),
183 members: None,
184 excluded: None,
185 starts_with: None,
186 ends_with: None,
187 contains: None,
188 }
189 }
190
191 /// The operators over the numerator column.
192 ///
193 /// Projected: the wrapped kind, never the field, so what a caller reads is
194 /// `comparison.numerator().eq()` — the storage operand, in the type the column holds and REDUCED,
195 /// which is not always the numerator the client spelled.
196 #[inline]
197 pub const fn numerator(&self) -> &SqlScalarComparison<i32, Db> {
198 &self.numerator
199 }
200
201 /// The operators over the denominator column, reduced alongside the numerator.
202 #[inline]
203 pub const fn denominator(&self) -> &SqlScalarComparison<i32, Db> {
204 &self.denominator
205 }
206
207 /// The reduced pairs this column must be one of, or [`None`] where `in` was not asked.
208 #[inline]
209 pub const fn members(&self) -> Option<&SqlKeyIn<i32, Db, 2>> {
210 self.members.as_ref()
211 }
212
213 /// The reduced pairs this column must be NONE of — `ne` and `not_in` merged, De Morgan having made
214 /// them one question.
215 #[inline]
216 pub const fn excluded(&self) -> Option<&SqlKeyIn<i32, Db, 2>> {
217 self.excluded.as_ref()
218 }
219
220 /// The `LIKE` pattern the rendering must match as a prefix — the operand with its wildcard already
221 /// on, since that is the form the bind takes.
222 ///
223 /// A [`Utf8Bytes`] rather than a `String`, matching the slot it came from: a pattern here is at
224 /// most an operand plus two `%`, so every one this crate can build fits the inline
225 /// representation and touches no heap. It derefs to `str`, so a reader wanting the text pays
226 /// nothing for the choice.
227 #[inline]
228 pub const fn starts_with(&self) -> Option<&Utf8Bytes> {
229 self.starts_with.as_ref()
230 }
231
232 /// The `LIKE` pattern the rendering must match as a suffix.
233 #[inline]
234 pub const fn ends_with(&self) -> Option<&Utf8Bytes> {
235 self.ends_with.as_ref()
236 }
237
238 /// The `LIKE` pattern the rendering must hold.
239 #[inline]
240 pub const fn contains(&self) -> Option<&Utf8Bytes> {
241 self.contains.as_ref()
242 }
243
244 /// True while NO operator slot is set anywhere, so a lowering would emit nothing at all.
245 #[inline]
246 pub const fn is_empty(&self) -> bool {
247 self.numerator.is_empty()
248 && self.denominator.is_empty()
249 && self.members.is_none()
250 && self.excluded.is_none()
251 && self.starts_with.is_none()
252 && self.ends_with.is_none()
253 && self.contains.is_none()
254 }
255
256 /// How many conjuncts this comparison lowers to.
257 ///
258 /// EXACT, and the two column halves report their own rather than this type keeping a number: what
259 /// the lowering opens is what each half opens, so there is no arithmetic here that could describe a
260 /// different rendering than the one that happens. Each whole-value and affix slot is exactly ONE —
261 /// a row-value membership is one predicate however many keys it holds, and a negation is one
262 /// bracket around one.
263 #[inline]
264 pub const fn conjuncts(&self) -> usize {
265 self.numerator.conjuncts()
266 + self.denominator.conjuncts()
267 + self.members.is_some() as usize
268 + self.excluded.is_some() as usize
269 + self.starts_with.is_some() as usize
270 + self.ends_with.is_some() as usize
271 + self.contains.is_some() as usize
272 }
273}
274
275/// The lowering.
276///
277/// # The bound grew when the row value arrived, and it grew to the SQL family's own
278///
279/// An earlier shape asked only that a HALF lowers, because both halves did all of the writing. The
280/// membership slots render text of their own through [`SqlKeyIn`], and the affix slots render a
281/// `CONCAT` — so this type now needs what those need: a bind ceiling to refuse past, the family's own
282/// lowering error to refuse WITH, and a buffer a rendered column name can be pushed out of.
283///
284/// It is [`SqlKeyIn`]'s own bound list, which is the SQL family's, plus one seat of this type's own:
285/// a BORROWED `str` binds. The narrowing costs nothing a caller has — a declaration reaching this
286/// comparison holds one of the three dialects, and each satisfies every row of it.
287///
288/// # The text seat is `&str` rather than `String: Carrier<Db>`, and it is the same capability
289///
290/// `ingraph`'s `String` row IS `qb.push_bind(self.as_str())` — the family binds a borrowed string
291/// and owns one only because the row is keyed on the owned type. There is no `Carrier` row for
292/// `str` or for [`Utf8Bytes`], so naming the owned one would have meant HOLDING a `String` in the
293/// slots above purely to satisfy a bound, which is the allocation those slots exist not to make.
294/// Naming what the bind actually spends is also the wider seat: a dialect able to bind a borrowed
295/// string qualifies whether or not the framework has written it an owned row.
296impl<Db> ComplexComparison<Db> for SqlTimebaseComparison<Db>
297where
298 Db: sqlx::Database
299 + BindCeiling
300 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
301 i32: Carrier<Db>,
302 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
303{
304 #[inline]
305 fn conjuncts(&self) -> usize {
306 Self::conjuncts(self)
307 }
308
309 /// The component halves, then the memberships, then the affixes — into the one accumulator all of
310 /// them are handed.
311 ///
312 /// Each half is applied one segment below `at`, and those two segments are the whole of what this
313 /// layer contributes: `num` and `den` belong to a timebase's SHAPE rather than to a table, and
314 /// where the pair sits is whatever the caller addressed. A frame is bound to a local first because
315 /// the child address BORROWS its path from it, so the link has to outlive the `apply` it is handed
316 /// to.
317 ///
318 /// The accumulator passes through every slot in turn, which is what keeps the groups in one
319 /// clause: each opens its conjuncts through the same counter the last one did, so the ` AND `
320 /// between them is the accumulator's and no slot's.
321 fn apply<'q>(
322 &'q self,
323 at: At<'_>,
324 builder: Db::Builder<'q>,
325 ) -> Result<Db::Builder<'q>, Db::Error> {
326 let num = at.frame(NUM);
327 let builder = self.numerator.apply(num.at(), builder)?;
328 let den = at.frame(DEN);
329 let builder = self.denominator.apply(den.at(), builder)?;
330
331 // The key set pushes ITS OWN frames, from `PARTS` — the same two names, reached the way that
332 // kind reaches them — so it is handed the address unchanged.
333 let mut builder = match &self.members {
334 Some(members) => members.apply(at, builder)?,
335 None => builder,
336 };
337
338 if let Some(excluded) = &self.excluded {
339 builder = negated(excluded, at, builder)?;
340 }
341
342 // Rendered ONCE for the three slots that each name both columns twice over.
343 let rendering =
344 self.starts_with.is_some() || self.ends_with.is_some() || self.contains.is_some();
345 if rendering {
346 let num = render_column::<Db>(at.frame(NUM).at());
347 let den = render_column::<Db>(at.frame(DEN).at());
348
349 for pattern in [&self.starts_with, &self.ends_with, &self.contains]
350 .into_iter()
351 .flatten()
352 {
353 let qb = builder.open();
354 qb.push("CONCAT(");
355 qb.push(&num);
356 qb.push(", '/', ");
357 qb.push(&den);
358 qb.push(") LIKE ");
359 // Bound as a BORROWED `str`, which is what `ingraph`'s own `String` carrier row spends
360 // (`qb.push_bind(self.as_str())`) — reached directly here because the family has no
361 // `Carrier` row for a borrowed string or for `Utf8Bytes`, and going through the row it does
362 // have would mean owning a `String` this slot deliberately does not hold.
363 qb.push_bind(pattern.as_str());
364 }
365 }
366
367 Ok(builder)
368 }
369}
370
371/// `NOT ( … )` around a key set's own rendering.
372///
373/// The nested accumulator leads with `""` rather than ` WHERE ` or ` AND `, which is exactly what
374/// that constructor is for: what goes inside the bracket is a bare PREDICATE and not a clause. The
375/// outer conjunct is opened here, so the negation is an ordinary member of the surrounding `AND`
376/// chain and neither this function nor the key set has to know whether it is the first.
377fn negated<'q, Db>(
378 keys: &'q SqlKeyIn<i32, Db, 2>,
379 at: At<'_>,
380 mut builder: SqlConjunction<'q, Db>,
381) -> Result<SqlConjunction<'q, Db>, SqlLoweringError>
382where
383 Db: sqlx::Database
384 + BindCeiling
385 + for<'a> Backend<Builder<'a> = SqlConjunction<'a, Db>, Error = SqlLoweringError, Buffer: Display>,
386 i32: Carrier<Db>,
387{
388 let qb = builder.open();
389 qb.push("NOT (");
390 // REBORROWED, so the nested accumulator's borrow ends with the statement and the bracket below is
391 // closed through the same buffer it opened. Its own return value is that borrow and is dropped
392 // here for exactly that reason.
393 let _ = keys.apply(at, SqlConjunction::with_lead(&mut *qb, ""))?;
394 qb.push(")");
395
396 Ok(builder)
397}
398
399/// The one place both column lists a timebase spans are stated, read by the predicate and by
400/// whatever emits the DDL.
401///
402/// The entries are [`ColumnShape`](crate::ColumnShape)s rather than words, and each is its own
403/// PART's type answering — so a timebase whose parts were themselves composite would describe itself
404/// here without this declaration changing shape.
405impl<Db> CompositeComparison<Db> for SqlTimebaseComparison<Db>
406where
407 Db: sqlx::Database
408 + BindCeiling
409 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
410 i32: Carrier<Db>,
411 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
412{
413 const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
414}
415
416impl<Db> Default for SqlTimebaseComparison<Db> {
417 #[inline]
418 fn default() -> Self {
419 Self::new()
420 }
421}
422
423/// Written out rather than derived, for the reason `ingraph`'s own comparison kinds write theirs
424/// out: a derive would bound `Db`, which is a marker no dialect type implements anything for.
425impl<Db> fmt::Debug for SqlTimebaseComparison<Db> {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 f.debug_struct("SqlTimebaseComparison")
428 .field("numerator", &self.numerator)
429 .field("denominator", &self.denominator)
430 .field("members", &self.members)
431 .field("excluded", &self.excluded)
432 .field("starts_with", &self.starts_with)
433 .field("ends_with", &self.ends_with)
434 .field("contains", &self.contains)
435 .finish()
436 }
437}
438
439impl<Db> Clone for SqlTimebaseComparison<Db> {
440 fn clone(&self) -> Self {
441 Self {
442 numerator: self.numerator.clone(),
443 denominator: self.denominator.clone(),
444 members: self.members.clone(),
445 excluded: self.excluded.clone(),
446 starts_with: self.starts_with.clone(),
447 ends_with: self.ends_with.clone(),
448 contains: self.contains.clone(),
449 }
450 }
451}
452
453impl<Db> PartialEq for SqlTimebaseComparison<Db> {
454 fn eq(&self, other: &Self) -> bool {
455 self.numerator == other.numerator
456 && self.denominator == other.denominator
457 && self.members == other.members
458 && self.excluded == other.excluded
459 && self.starts_with == other.starts_with
460 && self.ends_with == other.ends_with
461 && self.contains == other.contains
462 }
463}
464
465/// Every SQL dialect takes the timebase filter to the timebase comparison, and the storage type is
466/// `i32` rather than a parameter: both halves of a timebase are `i32` by construction, so a
467/// declaration naming any other column type gets no impl and does not compile. One `V` covers two
468/// columns without compromise here, because the two hold the same type.
469///
470/// The `Db: sqlx::Database` bound is what leaves room beside this for a `MongoTimebaseComparison` —
471/// nothing may implement `sqlx::Database` for a future local `Mongo` marker, so the two impls cannot
472/// overlap.
473///
474/// # The rest of the bounds are the LOWERING's, restated
475///
476/// [`ToDatabaseComparison::Comparison`] promises [`ComplexComparison`], so this row has to PROVE it
477/// rather than assume it — and what proves it is the impl above, whose list this is. Stated as the
478/// DIALECT's capabilities rather than as `SqlTimebaseComparison<Db>: ComplexComparison<Db>` because
479/// this is the row a generated where-struct resolves a projection through: a bound naming a
480/// comparison type would make this the one column whose crossing a caller cannot satisfy by knowing
481/// which database it has.
482impl<Db> ToDatabaseComparison<i32, Db> for TimebaseFilter
483where
484 Db: sqlx::Database
485 + BindCeiling
486 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
487 i32: Carrier<Db>,
488 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
489{
490 type Comparison = SqlTimebaseComparison<Db>;
491}
492
493/// **The same comparison, keyed by the CITIZEN rather than by the column type its halves land in** —
494/// the row that lets `#[ingraph::record]` take a field declared `Timebase` where an author
495/// previously had to hand-flatten it into a `num`/`den` pair.
496///
497/// The row above answers for `i32`, which is what a HAND-FLATTENED declaration names: an author who
498/// writes `timebase_num: i32` and hangs this filter on it is asking about one column, and the map
499/// keyed by that column's type is what serves them. A field declared at the citizen's OWN type asks
500/// the identical question of the identical columns — [`ColumnKind::SEGMENTS`](crate::ColumnKind)
501/// spans the same two and the lowering descends into them by PATH — so the projection is the SAME
502/// comparison, and this row adds a KEY rather than a behaviour. Nothing about the rendered SQL moves.
503///
504/// **The two rows cannot overlap**, which is what makes holding both sound: `V` is the map's first
505/// parameter, and [`Timebase`] is a local newtype that is not `i32`. A declaration reaches exactly
506/// one of them, decided by the type its author wrote.
507impl<Db> ToDatabaseComparison<Timebase, Db> for TimebaseFilter
508where
509 Db: sqlx::Database
510 + BindCeiling
511 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
512 i32: Carrier<Db>,
513 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
514{
515 type Comparison = SqlTimebaseComparison<Db>;
516}
517
518/// The crossing, and the only route into a [`SqlTimebaseComparison`].
519///
520/// [`TryFromFilter`] and never [`FromFilter`](crate::FromFilter): the render facet's alphabet is
521/// checked here, so the crossing can fail, and an infallible half would in any case collide with the
522/// blanket that lifts one into the other.
523///
524/// # No `Db` bound
525///
526/// The crossing turns domain values into storage values, and which dialect eventually binds them
527/// takes no part in that — the dialect is selected at the LOWERING, by `i32: Carrier<Db>`. So this
528/// impl holds for every `Db`, including one that is not a database at all.
529impl<Db> TryFromFilter<TimebaseFilter> for SqlTimebaseComparison<Db> {
530 type Error = TimebaseCrossingError;
531
532 fn try_from_filter(filter: TimebaseFilter) -> Result<Self, Self::Error> {
533 // Destructured rather than read through the getters: every operand is moved into the crossing
534 // whole, so nothing here copies a `Box<[…]>` that a membership list already allocated.
535 let TimebaseFilter {
536 eq,
537 ne,
538 in_,
539 not_in,
540 starts_with,
541 ends_with,
542 contains,
543 numerator,
544 denominator,
545 } = filter;
546
547 // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
548 // filter, exactly what the hand-written parse this replaced wrote for a key a client omitted.
549 let mut numerator = numerator.unwrap_or_default();
550 let mut denominator = denominator.unwrap_or_default();
551
552 if let Some(whole) = eq {
553 // A whole-value equality lands in the halves' OWN equality slots, and a slot holds one
554 // operand. Two equalities over one column are either a restatement or a contradiction, and
555 // assigning over the top would silently keep whichever was written last.
556 if numerator.eq().is_some() {
557 return Err(TimebaseCrossingError::NumeratorConflict);
558 }
559 if denominator.eq().is_some() {
560 return Err(TimebaseCrossingError::DenominatorConflict);
561 }
562
563 let (num, den) = whole.reduced();
564 numerator = numerator.with_eq(num);
565 denominator = denominator.with_eq(den);
566 }
567
568 let members = in_.map(|list| SqlKeyIn::new(PARTS, keys(&list)));
569
570 // De Morgan: excluding one value AND excluding a set is excluding their union, so the two slots
571 // are one key set. An `ne` with no `not_in` is the one-key case of the same predicate.
572 let excluded = match (ne, not_in) {
573 (None, None) => None,
574 (single, list) => {
575 let mut keys = keys(list.as_deref().unwrap_or_default());
576 if let Some(single) = single {
577 let (num, den) = single.reduced();
578 keys.push([num, den.get()]);
579 }
580 Some(SqlKeyIn::new(PARTS, keys))
581 }
582 };
583
584 Ok(Self {
585 numerator: infallible(SqlScalarComparison::try_from_filter(numerator)),
586 denominator: infallible(SqlScalarComparison::try_from_filter(denominator)),
587 members,
588 excluded,
589 starts_with: affix(starts_with.as_deref(), Affix::Prefix)?,
590 ends_with: affix(ends_with.as_deref(), Affix::Suffix)?,
591 contains: affix(contains.as_deref(), Affix::Contains)?,
592 })
593 }
594}
595
596/// The reduced pairs a membership list becomes, in the order the operands were sent.
597///
598/// A `Vec` rather than a boxed slice, because the exclusion path appends `ne`'s own key to it. The
599/// list is NOT de-duplicated: two operands that reduce to one pair are one row of the `IN` list
600/// either way, and removing them would cost a sort or a set to save a bind on an input nobody sends.
601fn keys(operands: &[Timebase]) -> Vec<[i32; 2]> {
602 operands
603 .iter()
604 .map(|operand| {
605 let (num, den) = operand.reduced();
606 [num, den.get()]
607 })
608 .collect()
609}
610
611/// One affix operand as a pattern, with the shared gate's refusal wearing THIS citizen's error.
612///
613/// The alphabet rule and the builder are [`rational::pattern`](super::super::rational), which the
614/// rate citizen spends too — one place for the property that no `LIKE` metacharacter can reach a
615/// pattern. What stays here is the sentence a client filtering TIMEBASES is told.
616fn affix(operand: Option<&str>, affix: Affix) -> Result<Option<Utf8Bytes>, TimebaseCrossingError> {
617 super::super::rational::pattern(operand, affix).map_err(TimebaseCrossingError::RenderAlphabet)
618}
619
620/// The two halves cross with `Error = Infallible` — `i32: TryFrom<i32>` through std's reflexive
621/// blanket, `i32: TryFrom<NonZeroI32>` through that type's `From`. Matched out rather than
622/// unwrapped, so the impossibility stays the compiler's and never becomes a panic that cannot fire.
623fn infallible<T>(crossed: Result<T, core::convert::Infallible>) -> T {
624 match crossed {
625 Ok(crossed) => crossed,
626 Err(never) => match never {},
627 }
628}
629
630/// A [`TimebaseFilter`] did not reach the two columns, and this says which part of it did not.
631///
632/// One variant per way a facet can refuse, rather than one opaque error: the filter came from a
633/// client, and which part was unanswerable is the only half of the answer that tells the client what
634/// to ask instead.
635///
636/// It is three variants where it was seven, and the four that went are the measure of what the row
637/// value bought: `ne`, `in` and `not_in` are answered rather than refused, and the affix operators
638/// are answered over a rendering rather than refused for want of one. What is left is the two ways
639/// of naming one column's equality twice, and the one operand a rendering cannot contain.
640///
641/// [`TimebaseFilter`]: super::TimebaseFilter
642#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
643pub enum TimebaseCrossingError {
644 /// `eq` and `numerator`'s own `eq` both name the numerator's equality, and the column has one.
645 NumeratorConflict,
646 /// `eq` and `denominator`'s own `eq` both name the denominator's equality, and the column has one.
647 DenominatorConflict,
648 /// An affix operand holds a character a `num/den` rendering cannot — carrying the first one found.
649 RenderAlphabet(char),
650}
651
652impl fmt::Display for TimebaseCrossingError {
653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
654 match self {
655 Self::NumeratorConflict => f.write_str("the numerator's equality is named twice"),
656 Self::DenominatorConflict => f.write_str("the denominator's equality is named twice"),
657 Self::RenderAlphabet(outside) => write!(
658 f,
659 "a timebase renders as digits and a slash, so `{outside}` matches no stored value"
660 ),
661 }
662 }
663}
664
665impl core::error::Error for TimebaseCrossingError {}