ingraph/primitives/mediatime/timestamp/comparison.rs
1//! The storage side of a [`MediaTimestamp`] query, behind the `sqlx` feature.
2//!
3//! ```text
4//! MediaTimestampFilter SqlMediaTimestampComparison<Db>
5//! eq: "12345 @ 1/90000" ──► nanos: eq 137166666 ──► WHERE "ts_nanos" = ?
6//! gte: "0:01:30.5" ──► nanos: gte 90500000000 ──► AND "ts_nanos" >= ?
7//! pts: { gt: 0 } ──► pts: gt 0 ──► AND "ts_pts" > ?
8//! timebase: "MPEG_90K" ──► the nested citizen ──► AND "ts_timebase_num" = ?
9//! AND "ts_timebase_den" = ?
10//! ```
11//!
12//! # The eight whole-value operators cross into ONE scalar comparison
13//!
14//! Identity and ordering are four operators each and they are the eight
15//! [`SqlScalarComparison`](crate::comparison::sql::SqlScalarComparison) has — over one column, in
16//! one unit. That is not a coincidence to exploit but the shape the design already had: both groups
17//! ask about a POSITION, and the only difference between them is which operands the wire admits,
18//! which is settled a layer earlier and leaves nothing for the crossing to distinguish.
19//!
20//! So the identity/bound split has no trace here, and it should not: by the time a filter reaches
21//! this crossing it holds [`MediaTimestamp`]s either way, and every one of them goes through
22//! [`MediaTimestamp::to_nanos`] — the SAME function the write path binds the derived column with. That is
23//! the law the timebase's reduction states, and it is why an identity operand is required to be an
24//! exact pair: a pair goes through that function; a clock string arrives at a number by a different
25//! road, and two roads to one column is the silent-miss shape.
26//!
27//! # What each facet reaches
28//!
29//! | facet | column | why there |
30//! |---|---|---|
31//! | identity + bound | `nanos` | the one unit every stored row shares |
32//! | `pts` | `pts` | the declared count, which is a question about the encoding |
33//! | `timebase` | `timebase_num`, `timebase_den` | the nested citizen, applied one frame down |
34//!
35//! The timebase facet is a whole [`SqlTimebaseComparison`] rather than two scalar slots, so
36//! everything that citizen can answer is answerable here — its row-value memberships and its render
37//! facet included — and none of it is restated. A composite holding a composite addresses it the way
38//! any other holder does: one frame, and the citizen pushes its own segments below it.
39//!
40//! # Refusals
41//!
42//! Two, and both are inherited rather than invented. An OPERAND past `i64` nanoseconds is refused
43//! here, at the last place it can be, rather than saturating into a bound nobody wrote — the same
44//! posture the write path takes when it binds `NULL` for a value it cannot place. And the nested
45//! citizen's own refusals arrive whole, carrying which part of the timebase filter was
46//! unanswerable.
47//!
48//! [`MediaTimestampFilter`]: super::MediaTimestampFilter
49
50use core::fmt::{self, Display};
51
52use crate::{
53 At, Backend, BindCeiling, Carrier, ComplexComparison, CompositeComparison, ScalarFilter,
54 ToDatabaseComparison, TryFromFilter,
55 comparison::sql::{SqlConjunction, SqlLoweringError, SqlScalarComparison, push_column},
56};
57
58use super::{
59 super::{
60 NanosecondOverflow, SqlTimebaseComparison, Timebase, TimebaseCrossingError,
61 timebase::{TIMEBASE_DEN, TIMEBASE_NUM},
62 },
63 MediaTimestamp, MediaTimestampFilter,
64 storage::{NANOS, PTS, SEGMENTS, TIMEBASE},
65};
66
67// The DIALECT this house's crossing tests render against is Postgres — its NUMBERED placeholders are
68// what say which operand reached which column, where a `?` dialect can only say how many there were —
69// so the module names `sqlx::Postgres` and needs that driver rather than the family root alone.
70//
71// The source crate carried a bare `#[cfg(test)]` here and never felt it, its own `sqlx` word arriving
72// with a dialect behind it. In this crate `sqlx` is the family ROOT and a dialect is a word of its
73// own, so the gate has to name the one it spells. It is the divergence the language family recorded
74// on the same move — per-dialect gates replacing a single `sqlx` word — read one dialect over.
75#[cfg(all(test, feature = "postgres"))]
76mod tests;
77
78/// [`MediaTimestampFilter`]'s storage-side twin: the derived position column, the declared count, and the
79/// timebase citizen nested inside.
80pub struct SqlMediaTimestampComparison<Db> {
81 exact: Option<Encoding>,
82 nanos: SqlScalarComparison<i64, Db>,
83 pts: SqlScalarComparison<i64, Db>,
84 timebase: SqlTimebaseComparison<Db>,
85}
86
87/// One encoding, in the three columns that hold it: the declared count and the REDUCED timebase.
88///
89/// Reduced because that is what the columns hold — the timebase citizen's own storage law, met one
90/// level up. It costs nothing a client can observe: two spellings of one timebase are one value to
91/// `mediatime`, so `2 @ 2/180000` and `2 @ 1/90000` are one timestamp and one row, and this facet
92/// separates encodings that differ in their `pts` or in their timebase's VALUE — which is exactly
93/// what the columns can tell apart.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95struct Encoding {
96 pts: i64,
97 num: i32,
98 den: i32,
99}
100
101impl<Db> SqlMediaTimestampComparison<Db> {
102 /// The empty comparison — no operator set on any facet.
103 #[inline]
104 pub const fn new() -> Self {
105 Self {
106 exact: None,
107 nanos: SqlScalarComparison::new(),
108 pts: SqlScalarComparison::new(),
109 timebase: SqlTimebaseComparison::new(),
110 }
111 }
112
113 /// The encoding the value columns must hold, or [`None`] where `exact` was not asked.
114 ///
115 /// Projected as the three storage numbers rather than as the domain value: the timebase half is
116 /// REDUCED here, which is not always the timebase the client spelled.
117 #[inline]
118 pub const fn exact(&self) -> Option<(i64, i32, i32)> {
119 match self.exact {
120 Some(Encoding { pts, num, den }) => Some((pts, num, den)),
121 None => None,
122 }
123 }
124
125 /// The operators over the derived position column, in nanoseconds — where BOTH whole-value groups
126 /// land, the identity four and the bound four alike.
127 #[inline]
128 pub const fn nanos(&self) -> &SqlScalarComparison<i64, Db> {
129 &self.nanos
130 }
131
132 /// The operators over the declared count.
133 #[inline]
134 pub const fn pts(&self) -> &SqlScalarComparison<i64, Db> {
135 &self.pts
136 }
137
138 /// The nested citizen's own comparison.
139 #[inline]
140 pub const fn timebase(&self) -> &SqlTimebaseComparison<Db> {
141 &self.timebase
142 }
143
144 /// True while NO operator slot is set anywhere.
145 #[inline]
146 pub const fn is_empty(&self) -> bool {
147 self.exact.is_none() && self.nanos.is_empty() && self.pts.is_empty() && self.timebase.is_empty()
148 }
149
150 /// How many conjuncts this comparison lowers to — the sum of what each facet opens, so the
151 /// arithmetic here cannot describe a different rendering than the one that happens.
152 #[inline]
153 pub const fn conjuncts(&self) -> usize {
154 self.exact.is_some() as usize * 3
155 + self.nanos.conjuncts()
156 + self.pts.conjuncts()
157 + self.timebase.conjuncts()
158 }
159}
160
161/// The lowering: three frames, in the order [`SEGMENTS`](super::storage) lists them.
162///
163/// The bound list is the nested citizen's own — a timebase filter can carry a row-value membership
164/// and an affix pattern, so reaching one costs exactly what reaching one costs. `i64: Carrier<Db>`
165/// is this type's only addition.
166impl<Db> ComplexComparison<Db> for SqlMediaTimestampComparison<Db>
167where
168 Db: sqlx::Database
169 + BindCeiling
170 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
171 i32: Carrier<Db>,
172 i64: Carrier<Db>,
173 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
174{
175 #[inline]
176 fn conjuncts(&self) -> usize {
177 Self::conjuncts(self)
178 }
179
180 fn apply<'q>(
181 &'q self,
182 at: At<'_>,
183 builder: Db::Builder<'q>,
184 ) -> Result<Db::Builder<'q>, Db::Error> {
185 let mut builder = builder;
186
187 // Rendered as its OWN three conjuncts rather than assigned into the `pts` and `timebase` slots
188 // below. Assigning would make `exact` and a component's own `eq` collide over one slot, and the
189 // choice would be between refusing a legitimate pair and keeping whichever was written last —
190 // the interaction the range citizen's algebra already renders its way out of. Three independent
191 // conjuncts have no such question: a contradiction returns no rows, which is the right answer.
192 if let Some(Encoding { pts, num, den }) = self.exact {
193 equals::<Db, i64>(&mut builder, at.frame(PTS).at(), pts);
194
195 let timebase = at.frame(TIMEBASE);
196 equals::<Db, i32>(&mut builder, timebase.at().frame(TIMEBASE_NUM).at(), num);
197 equals::<Db, i32>(&mut builder, timebase.at().frame(TIMEBASE_DEN).at(), den);
198 }
199
200 let pts = at.frame(PTS);
201 let builder = self.pts.apply(pts.at(), builder)?;
202 let timebase = at.frame(TIMEBASE);
203 let builder = self.timebase.apply(timebase.at(), builder)?;
204 let nanos = at.frame(NANOS);
205 self.nanos.apply(nanos.at(), builder)
206 }
207}
208
209/// One column equal to one operand — the whole of what the structural facet renders.
210///
211/// The column is rendered through [`push_column`], as every leaf in the SQL family renders one, so
212/// the joining and the bracketing stay the backend's.
213fn equals<'q, Db, V>(builder: &mut SqlConjunction<'q, Db>, at: At<'_>, operand: V)
214where
215 Db: sqlx::Database + Backend<Buffer: Display>,
216 V: Carrier<Db>,
217{
218 let qb = builder.open();
219 push_column(qb, at);
220 qb.push(" = ");
221 operand.push_bind(qb);
222}
223
224/// The claim `flatten` needs, read off the one list the storage face states.
225impl<Db> CompositeComparison<Db> for SqlMediaTimestampComparison<Db>
226where
227 Db: sqlx::Database
228 + BindCeiling
229 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
230 i32: Carrier<Db>,
231 i64: Carrier<Db>,
232 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
233{
234 const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
235}
236
237impl<Db> Default for SqlMediaTimestampComparison<Db> {
238 #[inline]
239 fn default() -> Self {
240 Self::new()
241 }
242}
243
244/// Written out rather than derived, for the reason `ingraph`'s own kinds write theirs out: a derive
245/// would bound `Db`, which is a marker no dialect type implements anything for.
246impl<Db> fmt::Debug for SqlMediaTimestampComparison<Db> {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 f.debug_struct("SqlMediaTimestampComparison")
249 .field("exact", &self.exact)
250 .field("nanos", &self.nanos)
251 .field("pts", &self.pts)
252 .field("timebase", &self.timebase)
253 .finish()
254 }
255}
256
257impl<Db> Clone for SqlMediaTimestampComparison<Db> {
258 fn clone(&self) -> Self {
259 Self {
260 exact: self.exact,
261 nanos: self.nanos.clone(),
262 pts: self.pts.clone(),
263 timebase: self.timebase.clone(),
264 }
265 }
266}
267
268impl<Db> PartialEq for SqlMediaTimestampComparison<Db> {
269 fn eq(&self, other: &Self) -> bool {
270 self.exact == other.exact
271 && self.nanos == other.nanos
272 && self.pts == other.pts
273 && self.timebase == other.timebase
274 }
275}
276
277/// Every SQL dialect takes the timestamp filter to the timestamp comparison, and the storage type is
278/// `i64` — the derived column's, which is the one a declaration names.
279impl<Db> ToDatabaseComparison<i64, Db> for MediaTimestampFilter
280where
281 Db: sqlx::Database
282 + BindCeiling
283 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
284 i32: Carrier<Db>,
285 i64: Carrier<Db>,
286 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
287{
288 type Comparison = SqlMediaTimestampComparison<Db>;
289}
290
291/// **The same comparison, keyed by the CITIZEN** — the row a field declared `MediaTimestamp`
292/// resolves through, where the row above is the one findit's hand-flattened `at_pts` column
293/// resolved through.
294///
295/// The comparison already reaches FOUR columns by path — the declared count, the nested timebase's
296/// two, and the derived position — so what a whole-value declaration changes is which map entry the
297/// expansion looks up and nothing about the statement it lowers into. That is why this row states
298/// the identical projection rather than a second one: a composite field and a hand-flattened field
299/// ask the same SQL, and the only thing that ever differed was who wrote the column names.
300///
301/// The two rows cannot overlap — [`MediaTimestamp`] is not `i64` — so an author reaches whichever
302/// one their declaration names.
303impl<Db> ToDatabaseComparison<MediaTimestamp, Db> for MediaTimestampFilter
304where
305 Db: sqlx::Database
306 + BindCeiling
307 + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
308 i32: Carrier<Db>,
309 i64: Carrier<Db>,
310 for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
311{
312 type Comparison = SqlMediaTimestampComparison<Db>;
313}
314
315/// The crossing, and the only route into a [`SqlMediaTimestampComparison`].
316///
317/// # No `Db` bound
318///
319/// The crossing turns domain values into storage values, and which dialect eventually binds them
320/// takes no part in that. So this impl holds for every `Db`, including one that is not a database.
321impl<Db> TryFromFilter<MediaTimestampFilter> for SqlMediaTimestampComparison<Db> {
322 type Error = MediaTimestampCrossingError;
323
324 fn try_from_filter(filter: MediaTimestampFilter) -> Result<Self, Self::Error> {
325 let MediaTimestampFilter {
326 exact,
327 eq,
328 ne,
329 in_,
330 not_in,
331 gt,
332 gte,
333 lt,
334 lte,
335 pts,
336 timebase,
337 } = filter;
338
339 // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
340 // filter, exactly what the hand-written parse this replaced wrote for a key a client omitted.
341 let pts = pts.unwrap_or_default();
342 let timebase = timebase.unwrap_or_default();
343
344 // Both whole-value groups land in ONE scalar filter over the derived column, which is what the
345 // eight slots ARE. Every operand crosses through `to_nanos`, the write path's own function.
346 let mut nanos = ScalarFilter::<i64>::new();
347 nanos.update_eq(position(eq)?);
348 nanos.update_ne(position(ne)?);
349 nanos.update_gt(position(gt.map(MediaTimestamp::from))?);
350 nanos.update_gte(position(gte.map(MediaTimestamp::from))?);
351 nanos.update_lt(position(lt.map(MediaTimestamp::from))?);
352 nanos.update_lte(position(lte.map(MediaTimestamp::from))?);
353 nanos.update_in_(positions(in_)?);
354 nanos.update_not_in(positions(not_in)?);
355
356 // The structural facet needs NO conversion and can refuse nothing: the value columns hold what
357 // the operand already is. It is the only slot here that never meets the nanosecond ceiling, so
358 // an instant past ±292 years is still findable by the encoding that wrote it.
359 let exact = exact.map(|operand| {
360 let (num, den) = Timebase::new(operand.get().timebase()).reduced();
361 Encoding {
362 pts: operand.get().pts(),
363 num,
364 den: den.get(),
365 }
366 });
367
368 Ok(Self {
369 exact,
370 nanos: infallible(SqlScalarComparison::try_from_filter(nanos)),
371 pts: infallible(SqlScalarComparison::try_from_filter(pts)),
372 timebase: SqlTimebaseComparison::try_from_filter(timebase)
373 .map_err(MediaTimestampCrossingError::Timebase)?,
374 })
375 }
376}
377
378/// One operand's position on the timeline, or the overflow that has none.
379fn position(operand: Option<MediaTimestamp>) -> Result<Option<i64>, MediaTimestampCrossingError> {
380 operand
381 .map(|operand| operand.to_nanos())
382 .transpose()
383 .map_err(MediaTimestampCrossingError::Overflow)
384}
385
386/// A membership list's positions, element by element. The FIRST refusal is the answer, and an empty
387/// list stays an empty list — `in: []` keeps asking for no rows.
388fn positions(
389 operands: Option<Box<[MediaTimestamp]>>,
390) -> Result<Option<Box<[i64]>>, MediaTimestampCrossingError> {
391 operands
392 .map(|operands| {
393 operands
394 .iter()
395 .map(|operand| operand.to_nanos())
396 .collect::<Result<Box<[i64]>, _>>()
397 .map_err(MediaTimestampCrossingError::Overflow)
398 })
399 .transpose()
400}
401
402/// The scalar halves cross with `Error = Infallible` — `i64: TryFrom<i64>` through std's reflexive
403/// blanket. Matched out rather than unwrapped, so the impossibility stays the compiler's.
404fn infallible<T>(crossed: Result<T, core::convert::Infallible>) -> T {
405 match crossed {
406 Ok(crossed) => crossed,
407 Err(never) => match never {},
408 }
409}
410
411/// A [`MediaTimestampFilter`] did not reach its columns, and this says which part of it did not.
412///
413/// Two variants, and neither is this layer's own invention: one is the nanosecond ceiling the
414/// storage face already states, and the other is the nested citizen's refusal passed through whole.
415///
416/// [`MediaTimestampFilter`]: super::MediaTimestampFilter
417#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
418pub enum MediaTimestampCrossingError {
419 /// An operand is further from zero than `i64` nanoseconds reach — about ±292 years.
420 ///
421 /// Refused rather than saturated. A bound clamped to the ceiling is a different bound, and it
422 /// would select rows the client did not ask for while reporting success.
423 Overflow(NanosecondOverflow),
424 /// The `timebase` facet did not cross — carrying the nested citizen's own refusal.
425 Timebase(TimebaseCrossingError),
426}
427
428impl fmt::Display for MediaTimestampCrossingError {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 match self {
431 Self::Overflow(overflow) => overflow.fmt(f),
432 Self::Timebase(timebase) => timebase.fmt(f),
433 }
434 }
435}
436
437impl core::error::Error for MediaTimestampCrossingError {
438 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
439 match self {
440 Self::Overflow(overflow) => Some(overflow),
441 Self::Timebase(timebase) => Some(timebase),
442 }
443 }
444}