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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! What a stored [`MediaTimeRange`] occupies, binds and reads back — the value columns, the TWO
//! derived positions the interval algebra is answered on, and the SEQUENCE the six of them mean.
//!
//! ```text
//!   span_start_pts       i64        the counts the stream declared
//!   span_end_pts         i64
//!   span_timebase_num    i32   ┐    the units BOTH endpoints are counted in — one citizen, once
//!   span_timebase_den    i32   ┘
//!   span_start_nanos     i64?       the endpoints on the timeline, DERIVED and NULLABLE
//!   span_end_nanos       i64?
//! ```
//!
//! Those are the columns in the order they are BUILT; [`ORDER`] below states the order they MEAN —
//! the start instant and then the end one — and [`MediaTimeRangeLeaf`] is the per-leaf vocabulary
//! that pairs with it. This is a REORDERING citizen, the second one shipped, and the two consts are
//! what make every judgment over a page of these spans an ordinary per-level one.
//!
//! # ONE timebase, TWO counts — which is why the components are not two timestamps
//!
//! A range is not a pair of timestamps in storage and its filter does not pretend otherwise. Both
//! endpoints are counted in ONE timebase, which `mediatime`'s own type enforces, so there is one
//! pair of timebase columns and a per-endpoint timebase facet would have to address columns that do
//! not exist. What the filter offers instead is `startPts`, `endPts` and the whole timebase citizen
//! — the three things a row actually holds.
//!
//! The derived pair follows [`MediaTimestamp`](super::super::MediaTimestamp)'s posture exactly, per endpoint:
//! an endpoint past `i64` nanoseconds binds `NULL` and the value columns stay exact, so a range with
//! one unplaceable endpoint is absent from the algebra on that side and readable throughout. The
//! whole posture is written up on the timestamp's own storage face; nothing here differs from it but
//! the arity.
//!
//! # The decode re-checks the invariant it cannot assume
//!
//! `mediatime::TimeRange::try_new` refuses `start > end`, and a database is exactly the place that
//! can hand back a pair it was never asked to keep in order — a hand-written UPDATE, a restore, a
//! migration that swapped two columns. So the read goes through the fallible constructor and refuses
//! rather than through the panicking one.

use crate::{
  ColumnKind, ColumnName, ColumnShape, CursorValue, FieldName, OrderLevel, column::column_eq,
};
use mediatime as mt;

use super::{super::Timebase, MediaTimeRange};

#[cfg(test)]
mod tests;

/// The declared start count's segment.
pub(super) const START_PTS: &FieldName = FieldName::new("start_pts");

/// The declared end count's segment.
pub(super) const END_PTS: &FieldName = FieldName::new("end_pts");

/// The shared timebase's segment — the frame the citizen below pushes its own two onto.
pub(super) const TIMEBASE: &FieldName = FieldName::new("timebase");

/// The derived start position's segment.
pub(super) const START_NANOS: &FieldName = FieldName::new("start_nanos");

/// The derived end position's segment.
pub(super) const END_NANOS: &FieldName = FieldName::new("end_nanos");

/// **The columns a range spans**, and the one authority every half of the crossing reads.
///
/// The derived pair is [`Nullable`](ColumnShape::Nullable) for the reason the timestamp's single one
/// is, doubled: the posture is PER ENDPOINT, so a range with one unplaceable endpoint declares both
/// index columns nullable and keeps all four value columns exact. Under a nullability that was the
/// field's, a required `span: MediaTimeRange` could not store such a range at all.
pub(super) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(START_PTS)),
  ColumnShape::Plain(ColumnName::of(END_PTS)),
  ColumnShape::Composite {
    field: Some(ColumnName::of(TIMEBASE)),
    segments: <Timebase as ColumnKind>::SEGMENTS,
  },
  ColumnShape::Nullable(ColumnName::of(START_NANOS)),
  ColumnShape::Nullable(ColumnName::of(END_NANOS)),
];

/// **The order those six columns MEAN**, which is not the order they are written in: the START
/// instant, then the END one.
///
/// The leaves are numbered as [`width`](crate::width) counts them — `start_pts` is `0`, `end_pts` is
/// `1`, the timebase's `num` and `den` are `2` and `3`, and the derived `start_nanos` and `end_nanos`
/// are `4` and `5` — so this sequence is
/// *start_nanos, start_pts, timebase_num, timebase_den, end_nanos, end_pts*.
///
/// # It is [`MediaTimestamp`](super::super::MediaTimestamp)'s sequence, COMPOSED
///
/// The instant citizen means *nanos, pts, num, den*, and a range means its two instants in order. So
/// the start half is that citizen's own four leaves and the end half follows it — a derived position
/// leading its value spelling, twice, for the reason stated one type down: `pts` is a count in a unit
/// the row itself declares, and two rows on different timebases are not comparable through it at all.
///
/// # SIX levels rather than eight, and the shared timebase is why
///
/// A range is NOT a pair of timestamps in storage — see this module's own note — and this is the
/// second face of that fact. Both endpoints are counted in ONE timebase, so there is one pair of
/// timebase columns and the composition of two four-leaf sequences names them twice. The second
/// naming would be INERT: a level is reached only when every level above it tied, and the pair is
/// already fixed by the start half's own two, so an end-half repetition could never separate two
/// rows. It would also widen every cursor over this citizen by two slots for a boundary that decides
/// nothing. So the shared pair is named ONCE, where it is first needed, and the sequence is a
/// permutation of the leaves rather than a walk that visits two of them twice.
///
/// The end half keeps both of its own leaves and needs both: `end_nanos` is `NULL` past the
/// ±292-year ceiling whatever the timebase, so `end_pts` is what separates two rows sharing that
/// column's `NULL` group.
///
/// # It is the 2026-08-29 law's SEMANTIC half, at the second citizen
///
/// *A derived leaf serves the semantic order only; every structural judgment walks value leaves
/// only.* Stating this const is what makes the structural half TRUE here: a term over a citizen with
/// a sequence EXPANDS through [`OrderTerm::levels`](crate::OrderTerm::levels) into one
/// one-column term per level, so no row value a keyset renders can contain a derived leaf. While
/// this type wore the non-reordering word instead, its term stayed wide and the keyset's tie-break
/// arm read
///
/// ```text
///   (…, "span_start_nanos", "span_end_nanos") = (?, ?, ?, ?, NULL, NULL)
/// ```
///
/// which is UNKNOWN for every row — so the key tail below it could never fire, and two rows holding
/// one span with an unplaceable endpoint were a page apart with one of them unreachable. That is
/// ingraph #454/#455's class read on the pagination side, and the expansion is the repair.
pub(super) const ORDER: &[OrderLevel] = &[
  OrderLevel::new(4),
  OrderLevel::new(0),
  OrderLevel::new(2),
  OrderLevel::new(3),
  OrderLevel::new(5),
  OrderLevel::new(1),
];

impl ColumnKind for MediaTimeRange {
  const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
  const ORDER: &'static [OrderLevel] = ORDER;
}

// A span is one column value when its ENCODING is — `mediatime` documents `TimeRange`'s own
// `PartialEq` as STRUCTURAL: both counts compared as written and the timebase by value, which is
// exactly what the four value columns hold. Unlike the instant one house over, there is no
// semantic twin here to diverge from `==`.
column_eq! { MediaTimeRange }

/// **The VALUE one of those six levels compares** — the per-leaf vocabulary this citizen publishes
/// beside its sequence, and the type an emitted cursor's slot is minted with for a column of this
/// type.
///
/// One member per leaf, each carrying that leaf's own Rust type, in the SEGMENT numbering rather
/// than the level one — the permutation is spent by the expansion, so one numbering serves the tree,
/// the vocabulary and the renderer. It is [`MediaTimestampLeaf`](super::super::MediaTimestampLeaf)'s
/// shape at this arity, with the timebase pair shared rather than doubled, exactly as the columns
/// are.
///
/// # It binds ONE placeholder, through the leaf type's own row
///
/// Which is why a level's operand needs nothing new: a `pts` is an `i64` and binds as an `i64` always
/// has. Nothing here is a second bind face — the [`Carrier`](crate::Carrier) below dispatches to the
/// scalar row the leaf's type already had, and both of that trait's faces are the same one
/// placeholder, a leaf having no derived leaf of its own to leave out.
///
/// # The timebase's halves are the REDUCED pair
///
/// What the columns hold, which is what [`Carrier`](crate::Carrier) binds and what
/// [`CursorValue`](crate::CursorValue) writes for the whole range. A boundary carrying the DECLARED
/// pair would compare against a value no column has.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MediaTimeRangeLeaf {
  /// Leaf `0` — the count the stream declared for the START endpoint.
  StartPts(i64),
  /// Leaf `1` — the count the stream declared for the END endpoint.
  EndPts(i64),
  /// Leaf `2` — the shared reduced timebase's numerator.
  TimebaseNum(i32),
  /// Leaf `3` — the shared reduced timebase's denominator.
  TimebaseDen(i32),
  /// Leaf `4` — the DERIVED position of the START endpoint, recomputed rather than carried.
  StartNanos(i64),
  /// Leaf `5` — the DERIVED position of the END endpoint, recomputed rather than carried.
  EndNanos(i64),
}

// One leaf is the same as another leaf when it is the SAME leaf holding the same bytes — each
// member already a plain reduced scalar by the time it is built, so the derived `PartialEq` is
// exactly this row.
column_eq! { MediaTimeRangeLeaf }

/// **The six leaves, and the derived pair RECOMPUTED at the call — PER ENDPOINT.**
///
/// Neither position is stored by anybody: not by the decode, not by the whole range's own
/// [`CursorValue`] row. A level over one asks that ENDPOINT's own
/// [`MediaTimestamp::to_nanos`](super::super::MediaTimestamp::to_nanos), which is the computation the
/// write binds one endpoint at a time, so a boundary is the value the statement sorted by.
///
/// It asks the endpoint rather than [`MediaTimeRange::to_nanos`], and the difference is the whole
/// per-endpoint posture: the pair-returning method refuses when EITHER end is past the ±292-year
/// ceiling, so routing both leaves through it would answer [`None`] for a start the write bound
/// exactly — a boundary that lost a column the `ORDER BY` still sorts on.
impl crate::OrderLeaves for MediaTimeRange {
  type Leaf = MediaTimeRangeLeaf;

  fn leaf(&self, at: usize) -> Option<MediaTimeRangeLeaf> {
    let (num, den) = Timebase::new(self.get().timebase()).reduced();
    match at {
      0 => Some(MediaTimeRangeLeaf::StartPts(self.get().start_pts())),
      1 => Some(MediaTimeRangeLeaf::EndPts(self.get().end_pts())),
      2 => Some(MediaTimeRangeLeaf::TimebaseNum(num)),
      3 => Some(MediaTimeRangeLeaf::TimebaseDen(den.get())),
      4 => self
        .start()
        .to_nanos()
        .ok()
        .map(MediaTimeRangeLeaf::StartNanos),
      5 => self.end().to_nanos().ok().map(MediaTimeRangeLeaf::EndNanos),
      _ => None,
    }
  }
}

/// **The KEYSET position of ONE leaf**: which leaf, then that leaf's own bytes.
///
/// The tag is what makes the read total, for [`MediaTimestampLeaf`](super::super::MediaTimestampLeaf)'s
/// reason: a slot is length-delimited by the cursor and holds nothing else, so a sum has to say which
/// member it is — and the bytes are a CLIENT's, so a byte naming no leaf is refused rather than read
/// as the nearest one.
impl CursorValue for MediaTimeRangeLeaf {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::StartPts(pts) => {
        out.push(0);
        CursorValue::write_cursor(pts, out);
      }
      Self::EndPts(pts) => {
        out.push(1);
        CursorValue::write_cursor(pts, out);
      }
      Self::TimebaseNum(num) => {
        out.push(2);
        CursorValue::write_cursor(num, out);
      }
      Self::TimebaseDen(den) => {
        out.push(3);
        CursorValue::write_cursor(den, out);
      }
      Self::StartNanos(nanos) => {
        out.push(4);
        CursorValue::write_cursor(nanos, out);
      }
      Self::EndNanos(nanos) => {
        out.push(5);
        CursorValue::write_cursor(nanos, out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, value) = bytes.split_first()?;
    match tag {
      0 => <i64 as CursorValue>::read_cursor(value).map(Self::StartPts),
      1 => <i64 as CursorValue>::read_cursor(value).map(Self::EndPts),
      2 => <i32 as CursorValue>::read_cursor(value).map(Self::TimebaseNum),
      3 => <i32 as CursorValue>::read_cursor(value).map(Self::TimebaseDen),
      4 => <i64 as CursorValue>::read_cursor(value).map(Self::StartNanos),
      5 => <i64 as CursorValue>::read_cursor(value).map(Self::EndNanos),
      _ => None,
    }
  }
}

/// **ONE BIND OUT**, through the row the leaf's own type already had.
///
/// A level names one column, so its operand is one placeholder — and which scalar row answers is the
/// member's, dispatched here and nowhere else. [`push_value_bind`](crate::Carrier::push_value_bind)
/// takes its default: a leaf has no derived leaf inside it to leave out, so the value bind and the
/// whole bind are the same one placeholder.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for MediaTimeRangeLeaf
where
  Db: sqlx::Database,
  i32: crate::Carrier<Db>,
  i64: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    match self {
      Self::StartPts(value)
      | Self::EndPts(value)
      | Self::StartNanos(value)
      | Self::EndNanos(value) => <i64 as crate::Carrier<Db>>::push_bind(value, qb),
      Self::TimebaseNum(value) | Self::TimebaseDen(value) => {
        <i32 as crate::Carrier<Db>>::push_bind(value, qb);
      }
    }
  }
}

/// **The DECLARED half — SIX words**, in the order the segments above state: the two tick counts,
/// the timebase's own two, then the two derived nanosecond columns.
///
/// The order is the SEGMENTS' rather than the struct's, which is why this is written beside them: a
/// range's timebase sits BETWEEN its extents and its derived sort keys, so a declaration that
/// grouped the `i64`s together would have named six columns in the wrong order and typed every one
/// of them plausibly.
impl<Db> crate::StoredAs<Db> for MediaTimeRange
where
  i64: crate::StoredAs<Db>,
  Timebase: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <i64 as crate::StoredAs<Db>>::WORDS[0],
    <i64 as crate::StoredAs<Db>>::WORDS[0],
    <Timebase as crate::StoredAs<Db>>::WORDS[0],
    <Timebase as crate::StoredAs<Db>>::WORDS[1],
    <i64 as crate::StoredAs<Db>>::WORDS[0],
    <i64 as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION.** A span is two tick counts and a timebase, and it carries no collection of its
/// own — so it is one element of one, and this row is what says so.
///
/// The parts are themselves composite, which the wall-clock stretch's own admission is the precedent
/// for: an edge table of `Vec<MediaTimeRange>` writes
/// `(key…, ordinal, start_pts, end_pts, timebase_num, timebase_den, …)`, and the descent that
/// reaches those is the same one a DIRECT column takes.
///
/// It is the row a SEGMENTATION needs: a speech-span list, a scene list and a cue list are each a
/// `Vec` of this type, which is why the quantified marker beside it has a road to run on.
impl crate::CollectionElement for MediaTimeRange {}

/// A pair of columns does not hold a range.
///
/// One variant, because there is one rule a stored pair can break that the types do not already
/// rule out: the endpoints run backwards. The timebase's own two rules are refused by
/// [`TimebaseColumnError`](super::super::TimebaseColumnError) one level down and arrive as a decode
/// failure from there.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InvertedMediaTimeRange;

impl core::fmt::Display for InvertedMediaTimeRange {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("a stored range's end must not precede its start")
  }
}

impl core::error::Error for InvertedMediaTimeRange {}

/// **The KEYSET position**: the VALUE columns, big-endian — both counts, then the shared timebase.
///
/// The derived pair is absent for [`MediaTimestamp`](super::super::MediaTimestamp)'s reason: a boundary has to
/// exist for every value a page can be cut at, and the counts always do.
impl CursorValue for MediaTimeRange {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    CursorValue::write_cursor(&self.get().start_pts(), out);
    CursorValue::write_cursor(&self.get().end_pts(), out);
    CursorValue::write_cursor(&Timebase::new(self.get().timebase()), out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (start, rest) = bytes.split_at_checked(size_of::<i64>())?;
    let (end, timebase) = rest.split_at_checked(size_of::<i64>())?;

    let start = <i64 as CursorValue>::read_cursor(start)?;
    let end = <i64 as CursorValue>::read_cursor(end)?;
    let timebase = <Timebase as CursorValue>::read_cursor(timebase)?;

    // The ordering invariant is checked here as it is at the decode: a cursor is a string a CLIENT
    // hands back, so a forged one must not become a range the type says cannot exist.
    mt::TimeRange::try_new(start, end, timebase.get()).map(Self::new)
  }
}

/// **SIX BINDS OUT** — four that carry the value and two that carry its endpoints' positions.
///
/// **AND FOUR FOR A STRUCTURAL JUDGMENT**, for the instant house's reason read at this arity: either
/// derived column can be `NULL` while the range is stored exactly, so an equality spending them
/// could not match the extent that wrote them. The narrow bind is the two counts and the shared
/// timebase — the same four columns the cursor carries and the decode reads, which is not a
/// coincidence but the law: a range's identity is what it HOLDS.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for MediaTimeRange
where
  Db: sqlx::Database,
  i64: crate::Carrier<Db>,
  Timebase: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    self.push_value_bind(qb);

    // Per ENDPOINT rather than per range: one unplaceable endpoint costs the other nothing, and a
    // range with a placeable start still answers `after`.
    for endpoint in [self.start(), self.end()] {
      qb.push(", ");
      match endpoint.to_nanos() {
        Ok(nanos) => <i64 as crate::Carrier<Db>>::push_bind(&nanos, qb),
        Err(_) => {
          qb.push("NULL");
        }
      }
    }
  }

  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <i64 as crate::Carrier<Db>>::push_bind(&self.get().start_pts(), qb);
    qb.push(", ");
    <i64 as crate::Carrier<Db>>::push_bind(&self.get().end_pts(), qb);
    qb.push(", ");
    <Timebase as crate::Carrier<Db>>::push_bind(&Timebase::new(self.get().timebase()), qb);
  }
}

/// **AND THE VALUE BACK IN** — two counts and the shared timebase, by name, and never the derived
/// pair.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for MediaTimeRange
where
  i64: crate::Assemble<'a, R>,
  Timebase: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let start: i64 = crate::assembled(row, START_PTS, under)?;
    let end: i64 = crate::assembled(row, END_PTS, under)?;
    let timebase: Timebase = crate::assembled(row, TIMEBASE, under)?;

    mt::TimeRange::try_new(start, end, timebase.get())
      .map(Self::new)
      .ok_or_else(|| sqlx::Error::Decode(Box::new(InvertedMediaTimeRange)))
  }
}