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
//! The storage side of a [`LocalTimestamp`] query, behind the `sqlx` feature.
//!
//! ```text
//! LocalTimestampFilter                       SqlLocalTimestampComparison<Db>
//!   exact: "…T16:45:09+09:00"  ──►   the three VALUE columns  ──► WHERE "at_local" = $1
//!                                                                 AND "at_offset_seconds" = $2
//!                                                                 AND "at_offset_stated" = $3
//!   gte: "2021-08-14T00:00:00Z" ──►  utc_nanos: gte …          ──► AND "at_utc_nanos" >= $4
//!   local: { gte: "…T00:00:00" } ──► local: gte …              ──► AND "at_local" >= $5
//!   offset: { eq: "+09:00" }    ──►  offset: eq … + the guard  ──► AND "at_offset_stated" = $6
//!                                                                 AND "at_offset_seconds" = $7
//!   zoned: false                ──►  the presence bit          ──► AND "at_offset_stated" = $8
//! ```
//!
//! # The eight whole-value operators cross into ONE scalar comparison
//!
//! Identity and ordering are four operators each and they are the eight
//! [`SqlScalarComparison`](crate::comparison::sql::SqlScalarComparison) has — over one column, in
//! one unit. Both groups ask about a POSITION, and by the time a filter reaches this crossing both
//! hold a [`Timestamp`](crate::Timestamp), so there is nothing left for the crossing to distinguish.
//!
//! # NOTHING HERE CAN REFUSE, and that is the operand's doing
//!
//! The media instant's crossing has two refusals because its operand is a value that has to be
//! DERIVED into a position. This one's operand is already a position: a `Timestamp` IS a UTC instant,
//! so the only conversion left is `i64` nanoseconds, which jiff's own range makes total —
//! `Timestamp::MIN`/`MAX` are ±9999 years, and their nanosecond counts are outside `i64`.
//!
//! That last sentence is the one place this house has to be careful, and it is careful in the
//! CROSSING rather than in a refusal: an operand past ±292 years is CLAMPED to the ceiling it
//! exceeds, because as a bound it means the same thing — *everything before the end of time* selects
//! every row — and as an identity it means *no row*, which is what a saturated equality against a
//! column that can never hold that value already answers. See [`nanos_of`], where the two readings
//! are argued.
//!
//! # `offset` carries a GUARD, and it is the two-leaf spelling's whole cost
//!
//! `offset_seconds` holds `0` for a value that stated no zone, which is not the offset `+00:00`. So
//! every non-empty `offset` component lowers with an `offset_stated = TRUE` conjunct beside it, and
//! that conjunct is counted here rather than in the component's own arithmetic — the component is an
//! ordinary [`SqlScalarComparison`](crate::comparison::sql::SqlScalarComparison) and knows nothing
//! about the leaf beside it.
//!
//! [`LocalTimestampFilter`]: super::LocalTimestampFilter

use core::fmt::{self, Display};

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, CompositeComparison, Temporal,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlLoweringError, SqlScalarComparison, push_column},
};

use super::{
  LocalTimestamp, LocalTimestampFilter,
  storage::{LOCAL, OFFSET_SECONDS, OFFSET_STATED, SEGMENTS, UTC_NANOS},
};

// The DIALECT this house's crossing tests render against is Postgres — its NUMBERED placeholders are
// what say which operand reached which column, where a `?` dialect can only say how many there were.
#[cfg(all(test, feature = "postgres"))]
mod tests;

/// The wall clock's storage form, named once so the three places that spell it agree.
type StoredLocal = Temporal<time::PrimitiveDateTime>;

/// [`LocalTimestampFilter`]'s storage-side twin: the derived instant column, the wall clock, the
/// displacement, and the presence bit.
pub struct SqlLocalTimestampComparison<Db> {
  exact: Option<Stored>,
  utc: SqlScalarComparison<i64, Db>,
  local: SqlScalarComparison<StoredLocal, Db>,
  offset: SqlScalarComparison<Temporal<i32>, Db>,
  zoned: Option<bool>,
}

/// One capture time in the three columns that hold it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Stored {
  local: StoredLocal,
  seconds: i32,
  stated: bool,
}

impl<Db> SqlLocalTimestampComparison<Db> {
  /// The empty comparison — no operator set on any facet.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      exact: None,
      utc: SqlScalarComparison::new(),
      local: SqlScalarComparison::new(),
      offset: SqlScalarComparison::new(),
      zoned: None,
    }
  }

  /// The operators over the derived instant column, in nanoseconds — where BOTH whole-value groups
  /// land, the identity four and the bound four alike.
  #[inline]
  #[must_use]
  pub const fn utc(&self) -> &SqlScalarComparison<i64, Db> {
    &self.utc
  }

  /// The operators over the wall clock column.
  #[inline]
  #[must_use]
  pub const fn local(&self) -> &SqlScalarComparison<StoredLocal, Db> {
    &self.local
  }

  /// The operators over the displacement column — which never render without their guard.
  #[inline]
  #[must_use]
  pub const fn offset(&self) -> &SqlScalarComparison<Temporal<i32>, Db> {
    &self.offset
  }

  /// The presence bit asked directly, or [`None`] where `zoned` was not asked.
  #[inline]
  #[must_use]
  pub const fn zoned(&self) -> Option<bool> {
    self.zoned
  }

  /// True while NO operator slot is set anywhere.
  #[inline]
  #[must_use]
  pub const fn is_empty(&self) -> bool {
    self.exact.is_none()
      && self.utc.is_empty()
      && self.local.is_empty()
      && self.offset.is_empty()
      && self.zoned.is_none()
  }

  /// How many conjuncts this comparison lowers to — the sum of what each facet opens, plus the
  /// offset component's guard, so the arithmetic here cannot describe a different rendering than the
  /// one that happens.
  #[inline]
  #[must_use]
  pub const fn conjuncts(&self) -> usize {
    self.exact.is_some() as usize * 3
      + self.utc.conjuncts()
      + self.local.conjuncts()
      + self.offset.conjuncts()
      + !self.offset.is_empty() as usize
      + self.zoned.is_some() as usize
  }
}

/// The lowering: four frames, in the order [`SEGMENTS`](super::storage) lists them, with the derived
/// one last.
impl<Db> ComplexComparison<Db> for SqlLocalTimestampComparison<Db>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  bool: Carrier<Db>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  StoredLocal: Carrier<Db>,
  Temporal<i32>: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let mut builder = builder;

    // Rendered as its OWN three conjuncts rather than assigned into the component slots below.
    // Assigning would make `exact` and a component's own `eq` collide over one slot, and the choice
    // would be between refusing a legitimate pair and keeping whichever was written last. Three
    // independent conjuncts have no such question: a contradiction returns no rows, which is right.
    if let Some(Stored {
      local,
      seconds,
      stated,
    }) = self.exact
    {
      equals::<Db, StoredLocal>(&mut builder, at.frame(LOCAL).at(), local);
      equals::<Db, i32>(&mut builder, at.frame(OFFSET_SECONDS).at(), seconds);
      equals::<Db, bool>(&mut builder, at.frame(OFFSET_STATED).at(), stated);
    }

    // THE GUARD, and it goes FIRST so that a reader of the rendered statement meets the question
    // before the answer: *did this row state a zone at all*, and only then *which one*.
    if !self.offset.is_empty() {
      equals::<Db, bool>(&mut builder, at.frame(OFFSET_STATED).at(), true);
    }
    if let Some(zoned) = self.zoned {
      equals::<Db, bool>(&mut builder, at.frame(OFFSET_STATED).at(), zoned);
    }

    let local = at.frame(LOCAL);
    let builder = self.local.apply(local.at(), builder)?;
    let offset = at.frame(OFFSET_SECONDS);
    let builder = self.offset.apply(offset.at(), builder)?;
    let utc = at.frame(UTC_NANOS);
    self.utc.apply(utc.at(), builder)
  }
}

/// One column equal to one operand — the whole of what the structural facet and the two guards
/// render.
///
/// The column is rendered through [`push_column`], as every leaf in the SQL family renders one, so
/// the joining and the bracketing stay the backend's.
fn equals<'q, Db, V>(builder: &mut SqlConjunction<'q, Db>, at: At<'_>, operand: V)
where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: Carrier<Db>,
{
  let qb = builder.open();
  push_column(qb, at);
  qb.push(" = ");
  operand.push_bind(qb);
}

/// The claim `flatten` needs, read off the one list the storage face states.
impl<Db> CompositeComparison<Db> for SqlLocalTimestampComparison<Db>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  bool: Carrier<Db>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  StoredLocal: Carrier<Db>,
  Temporal<i32>: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

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

/// Written out rather than derived, for the reason `ingraph`'s own kinds write theirs out: a derive
/// would bound `Db`, which is a marker no dialect type implements anything for.
impl<Db> fmt::Debug for SqlLocalTimestampComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlLocalTimestampComparison")
      .field("exact", &self.exact)
      .field("utc", &self.utc)
      .field("local", &self.local)
      .field("offset", &self.offset)
      .field("zoned", &self.zoned)
      .finish()
  }
}

impl<Db> Clone for SqlLocalTimestampComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      exact: self.exact,
      utc: self.utc.clone(),
      local: self.local.clone(),
      offset: self.offset.clone(),
      zoned: self.zoned,
    }
  }
}

impl<Db> PartialEq for SqlLocalTimestampComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.exact == other.exact
      && self.utc == other.utc
      && self.local == other.local
      && self.offset == other.offset
      && self.zoned == other.zoned
  }
}

/// **The comparison, keyed by the CITIZEN** — the row a field declared [`LocalTimestamp`] resolves
/// through.
impl<Db> ToDatabaseComparison<LocalTimestamp, Db> for LocalTimestampFilter
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  bool: Carrier<Db>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  StoredLocal: Carrier<Db>,
  Temporal<i32>: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlLocalTimestampComparison<Db>;
}

/// The crossing, and the only route into a [`SqlLocalTimestampComparison`].
///
/// # No `Db` bound, and no error
///
/// The crossing turns domain values into storage values, and which dialect eventually binds them
/// takes no part in that — so this impl holds for every `Db`. It is also
/// [`Infallible`](core::convert::Infallible), which the module note argues: every operand this
/// filter can hold already has a storage form, so there is nothing left to refuse.
impl<Db> TryFromFilter<LocalTimestampFilter> for SqlLocalTimestampComparison<Db> {
  type Error = core::convert::Infallible;

  fn try_from_filter(filter: LocalTimestampFilter) -> Result<Self, Self::Error> {
    let LocalTimestampFilter {
      exact,
      eq,
      ne,
      in_,
      not_in,
      gt,
      gte,
      lt,
      lte,
      local,
      offset,
      zoned,
    } = filter;

    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
    // filter, exactly what a key a client omitted means.
    let local = local.unwrap_or_default();
    let offset = offset.unwrap_or_default();

    // Both whole-value groups land in ONE scalar filter over the derived column, which is what the
    // eight slots ARE.
    let mut utc = crate::ScalarFilter::<i64>::new();
    utc.update_eq(eq.map(nanos_of));
    utc.update_ne(ne.map(nanos_of));
    utc.update_gt(gt.map(nanos_of));
    utc.update_gte(gte.map(nanos_of));
    utc.update_lt(lt.map(nanos_of));
    utc.update_lte(lte.map(nanos_of));
    utc.update_in_(in_.as_deref().map(positions));
    utc.update_not_in(not_in.as_deref().map(positions));

    // The structural facet needs no derivation: the value columns hold what the operand already is.
    // It is the only slot here that reaches an UNZONED row, which is the point of having it.
    let exact = exact.map(|operand| Stored {
      local: Temporal::from(operand.local()),
      seconds: operand.offset().map_or(0, |offset| offset.seconds()),
      stated: operand.is_zoned(),
    });

    Ok(Self {
      exact,
      utc: infallible(SqlScalarComparison::try_from_filter(utc)),
      local: infallible(SqlScalarComparison::try_from_filter(local)),
      offset: infallible(SqlScalarComparison::try_from_filter(offset)),
      zoned,
    })
  }
}

/// One UTC operand as the nanosecond position the derived column holds.
///
/// # It SATURATES, and the two readings agree about what that means
///
/// `Timestamp` spans ±9999 years and `i64` nanoseconds span about ±292, so an operand outside 1678
/// ..= 2262 has no exact position. Both readings of a saturated bound are the reading the client
/// asked for:
///
/// - as a BOUND — `lt: "9999-01-01T00:00:00Z"` means *everything before the end of time*, and
///   `lt: i64::MAX` selects exactly the same rows, every stored position being inside the ceiling by
///   construction.
/// - as an IDENTITY — `eq: "9999-01-01T00:00:00Z"` means *the rows at that instant*, of which there
///   are none, and `eq: i64::MAX` also matches none: no write can bind that value, because a
///   `LocalTimestamp` whose position reaches the ceiling binds `NULL` instead.
///
/// So the clamp is not an approximation a client could observe. It is refused NOWHERE, which is what
/// makes this whole crossing [`Infallible`](core::convert::Infallible) — and the alternative, a
/// refusal, would reject a perfectly sensible open-ended bound.
fn nanos_of(operand: crate::Timestamp) -> i64 {
  let nanos = operand.get().as_nanosecond();
  if nanos > i128::from(i64::MAX) {
    i64::MAX
  } else if nanos < i128::from(i64::MIN) {
    i64::MIN
  } else {
    nanos as i64
  }
}

/// A membership list's positions, element by element. An empty list stays an empty list — `in: []`
/// keeps asking for no rows.
fn positions(operands: &[crate::Timestamp]) -> Box<[i64]> {
  operands.iter().copied().map(nanos_of).collect()
}

/// The scalar halves cross with `Error = Infallible`. Matched out rather than unwrapped, so the
/// impossibility stays the compiler's.
fn infallible<T>(crossed: Result<T, core::convert::Infallible>) -> T {
  match crossed {
    Ok(crossed) => crossed,
    Err(never) => match never {},
  }
}