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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! The [`LocalTimestamp`] primitive: a WALL CLOCK and the zone it was on, where the zone may not
//! have been written down.
//!
//! ```text
//!   local     2021-08-14T16:45:09     what the camera's face said
//!   offset    +09:00  |  (none)       which zone that face was on, IF the file said
//!   utc       DERIVED                 the instant, where the two above compose into one
//! ```
//!
//! # The invariant is the one an `Option` alone cannot state
//!
//! A wall clock is not an instant and a wall clock with an offset is. Held as two independent
//! fields — the shape a record reaches for first — that fact is a convention every reader has to
//! remember: *the instant is derivable exactly when the second field is there*, and a reader that
//! forgets it invents a zone. Held as ONE value, the derivation is the type's and there is nowhere
//! for the convention to be forgotten.
//!
//! That is what makes it a citizen here rather than two fields in the crate that asked. The caller
//! is `findit`'s `capture_info`, whose four hand-written columns — a local text, an offset text, and
//! the two halves of a derived instant — are this type's four leaves with the invariant taken out of
//! the doc comments and put in the type. See the module note in [`primitives`](super::super) for the
//! rule a name arrives here by; this one arrives by the FRAMEWORK asking, having an ordering to
//! answer that neither half can answer alone.
//!
//! # THE OFFSET IS OPTIONAL AND EVERY VALUE LEAF IS `NOT NULL` — the two facts, and how they compose
//!
//! [`ColumnShape`](crate::ColumnShape)'s vocabulary is a 2×2 with one corner deliberately empty:
//! there is no word for *a leaf that is part of the value AND may hold `NULL` on its own*, and the
//! reason is stated at the enum — row-value equality over a `NULL` leaf is UNKNOWN, so a row could
//! never be matched by the very tuple that wrote it (ingraph #455, over the media instant's derived
//! column, is that bug found once already).
//!
//! So the absence is spelled INSIDE the value, in a leaf of its own:
//!
//! ```text
//!   offset_seconds   i32     the displacement east of UTC, in seconds — 0 when unstated
//!   offset_stated    bool    whether the source named a zone at all
//! ```
//!
//! **A flag rather than a sentinel**, and that is this crate's own law rather than a preference: a
//! reserved `i32` would put a magic number in a column and every reader would have to know it.
//! The pair has no such secret, and the one arrangement it admits that the type does not —
//! `offset_stated = false` beside a non-zero `offset_seconds` — is REFUSED at the decode, exactly as
//! [`Timestamp::from_parts`](crate::Timestamp::from_parts) refuses a sign-crossing `(secs, nanos)`
//! pair rather than resolving it.
//!
//! # The DERIVED leaf, and the two reasons it declines
//!
//! `utc_nanos` is [`Nullable`](crate::ColumnShape::Nullable) — an INDEX beside the value, read by no
//! decode and compared by no equality — and it is `NULL` when:
//!
//! | reason | why the honest answer is `NULL` |
//! |---|---|
//! | the offset was never stated | a UTC instant guessed from the indexing machine's zone is a claim about WHERE the photograph was taken, made silently, in a column an `ORDER BY` would then believe |
//! | the instant is outside `i64` nanoseconds — about ±292 years | the same ceiling and the same posture the media instant's own derived column takes |
//!
//! SQL's three-valued logic does the rest for free: `utc_nanos > ?` is UNKNOWN for such a row, so it
//! is absent from every ordering predicate while the row stays present, readable, and reachable
//! through the component facets. A cursor carries the VALUE leaves and never this one, so a page
//! boundary is exact for every value including the ones with no key.
//!
//! # Why the name is `LocalTimestamp`
//!
//! `Timestamp` is taken and means the other thing — an instant on the UTC timeline, with no zone to
//! carry. `LocalDateTime` is the WIRE word for one of this type's leaves and would put two names on
//! one thing. What this type is, is a timestamp read on a LOCAL clock, which is the qualifier the
//! media-time house puts on its own position names for the same reason: the value and the frame it
//! is measured in are one type, and the name says which frame.

use core::fmt;

use jiff::{civil, tz};

use crate::{CompositeFilterMarker, CompositeMarker, DefaultMarker, ScalarFilter, ToGraphqlInput};

use crate::graphql::filter::opt_accessor;

#[cfg(feature = "sqlx")]
mod comparison;
#[cfg(feature = "async-graphql")]
mod graphql;
mod storage;

pub use storage::{LocalTimestampLeaf, LocalTimestampPartsError};

#[cfg(test)]
mod tests;

#[cfg(feature = "sqlx")]
pub use comparison::SqlLocalTimestampComparison;

/// A wall clock and the zone it was on, where the zone may be absent — the EXIF capture-time shape,
/// as one value.
///
/// [`Ord`] is the DECLARED one and it is the STORAGE order rather than the chronological one: a
/// wall clock, then a displacement. It has to be, because the chronological order is PARTIAL — two
/// values with no offset between them are not comparable as instants at all — and a `PartialOrd`
/// that answered [`None`] for the commonest pair in a photo library would be a trap in every sort.
/// The total order the database sorts by is [`ColumnKind::ORDER`](crate::ColumnKind::ORDER), which
/// leads with the derived instant and falls back on exactly these fields; see the storage face,
/// where the two are reconciled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LocalTimestamp {
  local: civil::DateTime,
  offset: Option<tz::Offset>,
}

impl LocalTimestamp {
  /// A wall clock with NO zone — what a camera that never wrote `OffsetTimeOriginal` gives.
  ///
  /// The commonest shape in a photograph library, and the one this type exists to keep honest: it
  /// names a moment on a clock face and no instant at all.
  #[inline]
  #[must_use]
  pub const fn wall(local: civil::DateTime) -> Self {
    Self {
      local,
      offset: None,
    }
  }

  /// A wall clock AND the zone it was on — the pair that composes into an instant.
  #[inline]
  #[must_use]
  pub const fn at(local: civil::DateTime, offset: tz::Offset) -> Self {
    Self {
      local,
      offset: Some(offset),
    }
  }

  /// Either shape, from an [`Option`] a caller already holds.
  ///
  /// The route a reader taking two independent EXIF tags goes through: the local clock is the one
  /// that must be there, and the offset is the one that usually is not.
  #[inline]
  #[must_use]
  pub const fn new(local: civil::DateTime, offset: Option<tz::Offset>) -> Self {
    Self { local, offset }
  }

  /// The wall clock — always present.
  #[inline]
  #[must_use]
  pub const fn local(&self) -> civil::DateTime {
    self.local
  }

  /// The zone the wall clock was on, where the source said.
  #[inline]
  #[must_use]
  pub const fn offset(&self) -> Option<tz::Offset> {
    self.offset
  }

  /// Whether the source named a zone — the bit the `offset_stated` leaf holds.
  ///
  /// Named as a question rather than read off [`offset`](Self::offset) at every call site, because
  /// it is what the wire's `zoned` slot and the storage's third leaf both ask, and one answer keeps
  /// the three from drifting.
  #[inline]
  #[must_use]
  pub const fn is_zoned(&self) -> bool {
    self.offset.is_some()
  }

  /// The UTC instant this value names, or why it names none.
  ///
  /// # Errors
  ///
  /// [`NoUtcPosition::Unzoned`] where the source stated no offset — REFUSED rather than assumed,
  /// which is the whole of this type's posture. [`NoUtcPosition::OutOfRange`] where the wall clock
  /// and the offset compose into an instant jiff cannot represent, which is reachable only at the
  /// very edges of the ±9999-year civil span.
  pub fn to_utc(&self) -> Result<jiff::Timestamp, NoUtcPosition> {
    let offset = self.offset.ok_or(NoUtcPosition::Unzoned)?;
    offset
      .to_timestamp(self.local)
      .map_err(|_| NoUtcPosition::OutOfRange)
  }

  /// The derived index leaf: the UTC instant in NANOSECONDS since the epoch.
  ///
  /// The one quantity every stored value that HAS an instant shares, and therefore the one an
  /// ordering operator can mean what it says over — the position [`ORDER`](crate::ColumnKind::ORDER)
  /// leads with and the value the write binds into `utc_nanos`.
  ///
  /// # Errors
  ///
  /// [`to_utc`](Self::to_utc)'s two, plus [`NoUtcPosition::NanosecondOverflow`] where the instant
  /// does not fit `i64` nanoseconds — about ±292 years, so `1678` to `2262`. A photograph outside
  /// that span keeps every value column exact and takes `NULL` in the index; nothing about it
  /// becomes unstorable, unreadable or unfindable, only unordered.
  pub fn to_utc_nanos(&self) -> Result<i64, NoUtcPosition> {
    let nanos = self.to_utc()?.as_nanosecond();
    i64::try_from(nanos).map_err(|_| NoUtcPosition::NanosecondOverflow { nanos })
  }
}

/// Why a [`LocalTimestamp`] has no UTC position.
///
/// Three variants and only the first is ordinary — a file that did not say which zone it was on is
/// the commonest thing in a photograph library, and it is not an error about the VALUE, only about a
/// question the value cannot answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NoUtcPosition {
  /// The source stated no zone, so there is no instant to compute.
  ///
  /// Refused rather than guessed. A UTC instant invented by assuming the indexing machine's zone
  /// would be a claim about where the photograph was taken, made silently, in a column an
  /// `ORDER BY` would then believe.
  Unzoned,
  /// The wall clock and the offset compose into an instant outside jiff's own ±9999-year range.
  ///
  /// Reachable only at the edges: `9999-12-31T23:59:59` at `-25:59:59` is past the end of the
  /// timeline, and the mirror of it is past the start.
  OutOfRange,
  /// The instant exists but does not fit `i64` nanoseconds — about ±292 years.
  ///
  /// Carries the exact count, which is an `i128` and therefore the number the caller asked for
  /// rather than a clamped one — the media instant's own overflow takes the same line.
  NanosecondOverflow {
    /// The nanosecond count that did not fit.
    nanos: i128,
  },
}

impl fmt::Display for NoUtcPosition {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Unzoned => f.write_str(
        "this wall clock states no zone offset, so it names no instant — and one assumed from the \
         reading machine's own zone would be a claim about where the value came from",
      ),
      Self::OutOfRange => f.write_str(
        "the wall clock and its offset compose into an instant outside the -9999..=9999 year range",
      ),
      Self::NanosecondOverflow { nanos } => {
        write!(f, "{nanos} nanoseconds does not fit an i64")
      }
    }
  }
}

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

/// A whole [`LocalTimestamp`] on its way IN as an operand — the exact pair, wall clock and zone
/// together.
///
/// A type of its own rather than [`LocalTimestamp`], and GraphQL's shared name namespace is what
/// forces it: the OBJECT a client reads back is `LocalTimestamp`, so the scalar a client sends
/// cannot also be. It is the wall the media-instant house's own two operands are on the other side
/// of.
///
/// Declared UNGATED beside the type it carries, on that house's ungated-operand rule: a crossing
/// says which FORM an operand takes and asks nothing about who parses that form. The binding's half
/// — the `#[Scalar]` that reads the arms and writes the canonical one — is in `graphql`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LocalTimestampOperand(LocalTimestamp);

impl LocalTimestampOperand {
  /// Wrap a [`LocalTimestamp`] as an operand.
  #[inline]
  #[must_use]
  pub const fn new(timestamp: LocalTimestamp) -> Self {
    Self(timestamp)
  }

  /// The wrapped [`LocalTimestamp`].
  #[inline]
  #[must_use]
  pub const fn get(&self) -> LocalTimestamp {
    self.0
  }
}

impl From<LocalTimestamp> for LocalTimestampOperand {
  #[inline]
  fn from(timestamp: LocalTimestamp) -> Self {
    Self(timestamp)
  }
}

impl From<LocalTimestampOperand> for LocalTimestamp {
  #[inline]
  fn from(operand: LocalTimestampOperand) -> Self {
    operand.0
  }
}

/// The operand's own crossing, so a `[LocalTimestamp]` column knows what one element looks like.
impl ToGraphqlInput for LocalTimestamp {
  type Input = LocalTimestampOperand;
  type Error = core::convert::Infallible;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Ok(input.into())
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    LocalTimestampOperand::new(*operand)
  }
}

/// What guards a [`LocalTimestamp`] column — one filter for both seats, a value storing every field
/// it declares.
impl CompositeFilterMarker for LocalTimestamp {
  type Filter = LocalTimestampFilter;
  type ColumnFilter = LocalTimestampFilter;
}

/// The interpretation a [`LocalTimestamp`] field is read under: it occupies columns of its own and
/// all of them can be absent together, which is exactly the VALUE family [`CompositeMarker`] names.
impl DefaultMarker for LocalTimestamp {
  type Marker = CompositeMarker<LocalTimestamp>;
}

/// **A COLLECTION of capture times is asked through the QUANTIFIERS**, on the media instant's own
/// argument: a [`ListFilter`](crate::ListFilter)'s operators hold a whole element as a single value,
/// and this element's identity question already has TWO answers — `exact` on the stored pair, `eq`
/// on the derived instant — so a list operator would have to pick one silently.
impl crate::DefaultVecMarker for LocalTimestamp {
  type Marker = crate::QuantifiedMarker<Vec<LocalTimestamp>>;
}

/// The filter that guards a [`LocalTimestamp`] column: a STRUCTURAL identity, a SEMANTIC one, a
/// bound facet, and the components a capture time is made of.
///
/// # Four groups, and TWO of them are identities
///
/// | facet | slots | operand | columns | asks |
/// |---|---|---|---|---|
/// | STRUCTURAL | `exact` | a whole [`LocalTimestamp`] | `local`, `offset_seconds`, `offset_stated` | which VALUE a row holds |
/// | SEMANTIC | `eq`, `ne`, `in_`, `not_in` | a UTC [`Timestamp`](crate::Timestamp) | `utc_nanos` | which INSTANT it is at |
/// | BOUND | `gt`, `gte`, `lt`, `lte` | a UTC [`Timestamp`](crate::Timestamp) | `utc_nanos` | where it sits on the timeline |
/// | COMPONENT | `local`, `offset`, `zoned` | that leaf's own filter | one column each | one leaf, on its own terms |
///
/// # `exact` and `eq` are two identities, and neither is the other's approximation
///
/// | | `exact: "2021-08-14T16:45:09+09:00"` | `eq: "2021-08-14T07:45:09Z"` |
/// |---|---|---|
/// | lowers to | `local = ? AND offset_seconds = ? AND offset_stated = TRUE` | `utc_nanos = ?` |
/// | admits `2021-08-14T09:45:09+02:00` | **no** — a different wall clock | **yes** — the same instant |
/// | admits a value with NO offset | **yes**, if the operand has none either | **never** — it has no key |
///
/// It is the general law's two sides, stated at [`ColumnShape`](crate::ColumnShape) and executed
/// here: *a derived leaf serves the SEMANTIC order only; every STRUCTURAL judgment walks VALUE
/// leaves only*. `exact` is *find the row I wrote*; `eq` is *find what happened then*.
///
/// # The SEMANTIC four cannot reach an unzoned row, and that is the answer rather than a gap
///
/// A value with no offset has no `utc_nanos`, so `utc_nanos = ?` is UNKNOWN for it and it is absent
/// from every one of the eight. That is exactly right — the row does not claim to have happened at
/// any instant — and it is why `local` and `zoned` are components rather than conveniences: *every
/// photograph shot on the afternoon of the 14th* is `local`, answerable for every file, and *every
/// photograph shot in this one hour across zones* is `eq`/`gt`, answerable only for the files that
/// said which zone they were on.
///
/// # `offset` implies `zoned: true`, and the implication is the component's own
///
/// The `offset_seconds` column holds `0` for a value that stated no zone, which is not the offset
/// `+00:00` and must not answer to it. So every operator in the `offset` component lowers WITH an
/// `offset_stated = TRUE` conjunct beside it, and `offset: { eq: "+00" }` selects the values that
/// said UTC rather than the values that said nothing.
///
/// # The wire face is DECLARED, not written
///
/// `#[ingraph(composed)]` reads the twelve slots below once and emits the registration, the parse
/// and the render from them.
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed)]
pub struct LocalTimestampFilter {
  exact: Option<LocalTimestamp>,
  eq: Option<crate::Timestamp>,
  ne: Option<crate::Timestamp>,
  in_: Option<Box<[crate::Timestamp]>>,
  not_in: Option<Box<[crate::Timestamp]>>,
  gt: Option<crate::Timestamp>,
  gte: Option<crate::Timestamp>,
  lt: Option<crate::Timestamp>,
  lte: Option<crate::Timestamp>,
  local: Option<ScalarFilter<civil::DateTime>>,
  offset: Option<ScalarFilter<tz::Offset>>,
  zoned: Option<bool>,
}

impl LocalTimestampFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      exact: None,
      eq: None,
      ne: None,
      in_: None,
      not_in: None,
      gt: None,
      gte: None,
      lt: None,
      lte: None,
      local: None,
      offset: None,
      zoned: None,
    }
  }

  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
  /// field.
  #[inline]
  #[must_use]
  pub const fn is_empty(&self) -> bool {
    self.exact.is_none()
      && self.eq.is_none()
      && self.ne.is_none()
      && self.in_.is_none()
      && self.not_in.is_none()
      && self.gt.is_none()
      && self.gte.is_none()
      && self.lt.is_none()
      && self.lte.is_none()
      && self.zoned.is_none()
      && match &self.local {
        Some(local) => local.is_empty(),
        None => true,
      }
      && match &self.offset {
        Some(offset) => offset.is_empty(),
        None => true,
      }
  }

  /// The wall clock's own filter — the question every value can answer.
  #[inline]
  #[must_use]
  pub const fn local(&self) -> Option<&ScalarFilter<civil::DateTime>> {
    self.local.as_ref()
  }

  /// The zone offset's own filter, which carries its `offset_stated = TRUE` guard.
  #[inline]
  #[must_use]
  pub const fn offset(&self) -> Option<&ScalarFilter<tz::Offset>> {
    self.offset.as_ref()
  }

  opt_accessor!(exact: LocalTimestamp => with_exact, set_exact, maybe_exact, update_exact);
  opt_accessor!(eq: crate::Timestamp => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: crate::Timestamp => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(in_: [crate::Timestamp] => with_in_, set_in_, maybe_in_, update_in_);
  opt_accessor!(not_in: [crate::Timestamp] => with_not_in, set_not_in, maybe_not_in, update_not_in);
  opt_accessor!(gt: crate::Timestamp => with_gt, set_gt, maybe_gt, update_gt);
  opt_accessor!(gte: crate::Timestamp => with_gte, set_gte, maybe_gte, update_gte);
  opt_accessor!(lt: crate::Timestamp => with_lt, set_lt, maybe_lt, update_lt);
  opt_accessor!(lte: crate::Timestamp => with_lte, set_lte, maybe_lte, update_lte);
  opt_accessor!(zoned: bool => with_zoned, set_zoned, maybe_zoned, update_zoned);

  /// Replace the wall clock's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_local(mut self, local: ScalarFilter<civil::DateTime>) -> Self {
    self.set_local(local);
    self
  }

  /// Replace the wall clock's filter (in place).
  #[inline]
  pub fn set_local(&mut self, local: ScalarFilter<civil::DateTime>) -> &mut Self {
    self.local = Some(local);
    self
  }

  /// Replace the zone offset's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_offset(mut self, offset: ScalarFilter<tz::Offset>) -> Self {
    self.set_offset(offset);
    self
  }

  /// Replace the zone offset's filter (in place).
  #[inline]
  pub fn set_offset(&mut self, offset: ScalarFilter<tz::Offset>) -> &mut Self {
    self.offset = Some(offset);
    self
  }
}

impl Default for LocalTimestampFilter {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}