ingraph/primitives/mediatime/timebase/storage.rs
1//! The three facts a STORED composite states about itself, and the one authority all of them read:
2//! how many columns a [`Timebase`] spans, how those columns are bound out, and how they are read
3//! back in.
4//!
5//! ```text
6//! SEGMENTS num, den the width — what a holder's INSERT list and DDL name
7//! Carrier ?, ? the bind — one placeholder per segment, the comma between them ours
8//! Assemble num → i32 ← den the decode — read by NAME, so a transposition cannot typecheck away
9//! CursorValue 8 bytes the keyset position, big-endian, exactly as the columns hold it
10//! ```
11//!
12//! # ONE list, read four ways
13//!
14//! [`SEGMENTS`] is the whole of what makes those four agree. The comparison pushes a frame per
15//! entry, the row puts a column per entry, the bind pushes a placeholder per entry and the decode
16//! reads one per entry — so a rename here moves `WHERE tb_num = ?`, `SELECT tb_num`, the `VALUES`
17//! width and the read together. Nothing counts the columns; the list is the count.
18//!
19//! # What is gated and what is not
20//!
21//! The width and the cursor position are UNGATED, because neither names a database: a composite
22//! spans two columns wherever it is stored, and a keyset position is bytes. The bind and the decode
23//! ride the `sqlx` feature, because both are written against sqlx's own types — a `QueryBuilder` and
24//! a `Row` — and a build with no SQL family has neither.
25//!
26//! # The bind writes the REDUCED pair, and it is the same reduction the crossing binds
27//!
28//! [`Timebase::reduced`] is THE authority, and it is public so that this path and the query path can
29//! call the same one rather than each dividing correctly. Reducing on one side only is a SILENT
30//! MISS: a row written from `2/180000` and a filter binding `1/90000` simply never meet, with no
31//! error and no wrong value to look at.
32//!
33//! What that costs is the pair the stream DECLARED, which storage does not keep — see
34//! [`Timebase`]'s [`Display`](core::fmt::Display), which does.
35
36use core::{fmt, num::NonZeroI32};
37
38use crate::{ColumnKind, ColumnName, ColumnShape, CursorValue, FieldName, column::column_eq};
39use mediatime as mt;
40
41use super::Timebase;
42
43#[cfg(test)]
44mod tests;
45
46/// The numerator's segment — the name a frame pushes and a column carries.
47///
48/// `pub(crate)` rather than `pub(super)`, because the citizens that NEST this one address these
49/// columns directly: a timestamp's `exact` facet binds the timebase halves beside the `pts`, and it
50/// reads the names from here rather than respelling them — one authority, at every depth.
51pub(crate) const NUM: &FieldName = FieldName::new("num");
52
53/// The denominator's segment.
54pub(crate) const DEN: &FieldName = FieldName::new("den");
55
56/// **The two columns a timebase spans**, and the one authority every half of the crossing reads.
57///
58/// `num` and `den` rather than the wire's `numerator`/`denominator`, and the difference is which
59/// side of the crossing each vocabulary belongs to: a column name is DDL a database already holds,
60/// where a field name is a schema commitment to a client. The wire took the longer spelling because
61/// `mediatime`'s own serde face publishes those two names; the columns keep the short ones because
62/// renaming a column is a migration and this cut is not one.
63pub(super) const SEGMENTS: &[ColumnShape] = &[
64 ColumnShape::Plain(ColumnName::of(NUM)),
65 ColumnShape::Plain(ColumnName::of(DEN)),
66];
67
68/// **The STORAGE half of the width** — what a holder's row reads to know this field is two columns
69/// and not one. It names no dialect, because a width has none.
70impl ColumnKind for Timebase {
71 const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
72}
73
74/// **One leaf, and it is the value.** A timebase means numerator then denominator, which is the sequence it is written in — the
75/// citizen that NESTS this one is the one with a sequence to state, and it states its own.
76impl crate::DeclaredLeaves for Timebase {}
77
78// Two timebases are one column value when they are the same rational — `mediatime`'s own
79// `PartialEq` cross-multiplies rather than comparing the pair as written, so `2/180000` and
80// `1/90000` already answer equal here exactly as `reduced()` makes them one row.
81column_eq! { Timebase }
82
83/// **The DECLARED half of the same two columns** — the words a `CREATE TABLE` spells them with, one
84/// per segment above.
85///
86/// Both halves are `i32`, so the words are that width's own in whichever dialect is asked rather
87/// than a spelling written here: the numerator and a non-zero denominator are what the
88/// [`Carrier`](crate::Carrier) row binds, and a dialect that stores an `i32` differently moves this
89/// row with it. Generic over the dialect for the reason the carrier row is — nothing in the
90/// delegation is per-dialect, and the arity is fixed at two.
91impl<Db> crate::StoredAs<Db> for Timebase
92where
93 i32: crate::StoredAs<Db>,
94{
95 const WORDS: &'static [&'static str] = &[
96 <i32 as crate::StoredAs<Db>>::WORDS[0],
97 <i32 as crate::StoredAs<Db>>::WORDS[0],
98 ];
99}
100
101/// A pair of columns does not hold a timebase, and this says which invariant they broke.
102///
103/// The two are the constructor's two, met on the way IN from a database rather than on the way in
104/// from a client: `mediatime` refuses a negative half and [`NonZeroI32`] refuses a zero denominator,
105/// and a column is an `INTEGER` that can hold either. So a decode has to test what the type
106/// guarantees, and the alternative — trusting the column — is a `Timebase` whose invariants are a
107/// hope about someone else's DDL.
108///
109/// It is a decode error rather than a parse error, and it is a separate type from
110/// [`ParseTimebaseError`](super::ParseTimebaseError) for that reason: nothing here was spelled, so
111/// there is no separator to be missing and no half that failed to be an integer. What is left is
112/// exactly the two domain rules.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114pub enum TimebaseColumnError {
115 /// The denominator column holds zero, which [`NonZeroI32`] forbids.
116 ZeroDenominator,
117 /// A column holds a negative value, which `mediatime`'s constructor refuses.
118 NegativeHalf,
119}
120
121impl fmt::Display for TimebaseColumnError {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 let reason = match self {
124 Self::ZeroDenominator => "the stored denominator must not be zero",
125 Self::NegativeHalf => "neither stored half may be negative",
126 };
127
128 f.write_str(reason)
129 }
130}
131
132impl core::error::Error for TimebaseColumnError {}
133
134/// The two columns as one value, or the invariant they broke.
135///
136/// Shared by the two readers below — the row decode and the cursor — so that a timebase arriving
137/// from a database and one arriving from a client's page token are admitted by the same rule.
138fn assembled(num: i32, den: i32) -> Result<Timebase, TimebaseColumnError> {
139 let den = NonZeroI32::new(den).ok_or(TimebaseColumnError::ZeroDenominator)?;
140
141 mt::Timebase::try_new(num, den)
142 .map(Timebase::new)
143 .ok_or(TimebaseColumnError::NegativeHalf)
144}
145
146/// **The KEYSET position**: eight bytes, two big-endian `i32`s, in the order [`SEGMENTS`] names.
147///
148/// A page resumes by binding the last row's values back, so what is written here is what the COLUMNS
149/// hold — the reduced pair — and not the declared one. A cursor carrying `2/180000` where the row
150/// holds `1/90000` would compare against a value no column has.
151///
152/// FIXED WIDTH, which is what makes the read total, and the DOMAIN is checked on top of the width: a
153/// cursor is a string a CLIENT hands back, so seven bytes are refused rather than zero-extended, and
154/// a forged `den` of zero is refused rather than turned into a `Timebase` whose type says it cannot
155/// exist.
156impl CursorValue for Timebase {
157 fn write_cursor(&self, out: &mut Vec<u8>) {
158 let (num, den) = self.reduced();
159 CursorValue::write_cursor(&num, out);
160 CursorValue::write_cursor(&den.get(), out);
161 }
162
163 fn read_cursor(bytes: &[u8]) -> Option<Self> {
164 let (num, den) = bytes.split_at_checked(size_of::<i32>())?;
165 let num = <i32 as CursorValue>::read_cursor(num)?;
166 let den = <i32 as CursorValue>::read_cursor(den)?;
167
168 assembled(num, den).ok()
169 }
170}
171
172/// **N BINDS OUT.** The engine's `VALUES` loop writes the comma between FIELDS; the comma between a
173/// field's own columns is this one, because the count is this type's — so a holder's `INSERT` names
174/// `tb_num, tb_den` and binds `?, ?` with neither list told the number.
175///
176/// Generic over the dialect where the fixture that models this names one concretely, and the
177/// difference is coherence rather than taste: that fixture also serves MongoDB, whose marker is
178/// foreign to it, so its two headers would overlap. This crate ships one family, so one header
179/// serves it — and `i32: Carrier<Db>` is the whole requirement, both halves being `i32` by
180/// construction.
181#[cfg(feature = "sqlx")]
182impl<Db> crate::Carrier<Db> for Timebase
183where
184 Db: sqlx::Database,
185 i32: crate::Carrier<Db>,
186{
187 fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
188 let (num, den) = self.reduced();
189 <i32 as crate::Carrier<Db>>::push_bind(&num, qb);
190 qb.push(", ");
191 <i32 as crate::Carrier<Db>>::push_bind(&den.get(), qb);
192 }
193}
194
195/// **AND N COLUMNS BACK IN** — the bind above read the other way, and the third fact a stored
196/// composite states.
197///
198/// Generic over the ROW where the bind is generic over the DIALECT, and the asymmetry is the two
199/// traits' parameters rather than a choice made here: a bind is a dialect's fact, while a read is
200/// [`sqlx::Row`]'s method.
201///
202/// `under` arrives carrying the holder's own segment for a field that lends its name, and carrying
203/// nothing extra for one marked `flatten` — so this one body serves both without knowing which it is
204/// reading. By NAME in both cases, which is what a transposition cannot survive: both columns are
205/// integers, so `num` and `den` read positionally would swap without a type error anywhere.
206#[cfg(feature = "sqlx")]
207impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for Timebase
208where
209 i32: crate::Assemble<'a, R>,
210{
211 fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
212 let num: i32 = crate::assembled(row, NUM, under)?;
213 let den: i32 = crate::assembled(row, DEN, under)?;
214
215 assembled(num, den).map_err(|refused| sqlx::Error::Decode(Box::new(refused)))
216 }
217}