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
497
498
499
500
501
502
503
504
505
506
507
508
//! The storage side of a [`Rate`] query, behind the `sqlx` feature: the comparison a [`RateFilter`]
//! crosses into, and the crossing that gets it there.
//!
//! ```text
//! RateFilter                              SqlRateComparison<Db>
//!   eq: "FPS_29_97"             ──►         num: eq 30000    ──► WHERE "fps_num" = ?
//!                                           den: eq 1001           AND "fps_den" = ?
//!   in: ["30/1", "FPS_25"]      ──►         members          ──► AND ("fps_num", "fps_den")
//!                                                                    IN ((?, ?), (?, ?))
//!   ne / notIn                  ──►         excluded         ──► AND NOT (( … ) IN (( … )))
//!   contains: "/1001"           ──►         contains         ──► AND CONCAT("fps_num", '/',
//!                                                                    "fps_den") LIKE ?
//!   numerator: { gt: 1000 }     ──►         num: gt 1000     ──► AND "fps_num" > ?
//! ```
//!
//! # It is [`SqlTimebaseComparison`]'s twin, and the differences are exactly three
//!
//! The two citizens are one shape — a rational in two `i32` columns — so the lowering is the same
//! lowering and every argument on that type holds here word for word: only `eq` decomposes
//! conjunctively, membership is the FLAT row value because two column lists match their cartesian
//! product, `ne` and `not_in` merge into one negated key set by De Morgan, and the render facet
//! builds its subject with `CONCAT` and needs no `ESCAPE` because the operand alphabet is checked at
//! the crossing.
//!
//! What differs:
//!
//! - **The columns hold the RATE's reading**, not its reciprocal — see [`storage`](super::storage).
//! - **The refusal sentences are this citizen's**, because a client filtering rates should not be
//!   told about timebases. The shared part is the alphabet RULE, which lives once in
//!   [`rational`](super::super::rational) and wears each caller's error.
//! - **There is no ordering to refuse.** A timebase's whole-value order is meaningless; a rate's is
//!   meaningful and simply unanswerable by two columns that sort lexicographically. Neither reaches
//!   a filter slot, so neither needs an error — but the reasons are different and the type docs say
//!   which is which.
//!
//! Sharing more than the alphabet rule was considered and not taken: the two comparisons differ in
//! their error type, their column semantics and their public names, and a generic
//! `SqlRationalComparison<T>` would have to be parameterised over all three to save a body that is
//! mostly `SqlScalarComparison` delegation already.
//!
//! # The MOUNT was measured and not taken, and the reason is a feature contract
//!
//! `#[crate::fields(…)]` has a seat for exactly this type — `record(<db>(comparison = "…"))`,
//! which hands a named lowering the whole seat at one dialect and writes the
//! [`ToDatabaseComparison`] row for it. This type already answers the three faces such a mount owes:
//! the crossing below, [`Default`], and [`ComplexComparison`] at every SQL backend.
//!
//! **There is no BARE seat, and that is what shuts the door here.** A mount is per DIALECT — a bare
//! `record(comparison = "…")` is refused by name, because a family-generic type's SCOPE would be
//! implicit — so taking it means writing `record(sqlite(comparison = "SqlRateComparison"), postgres(…),
//! mysql(…))` at the declaration. That names three dialects this crate deliberately does not name:
//! its `sqlx` feature is the SQL FAMILY and implies no dialect at all, the carrier rows a lowering
//! needs arriving with whichever of `ingraph`'s dialect features the crate holding the DATABASE
//! turns on. A mount would move that decision into the library and gate this citizen's lowering
//! behind three feature walls the manifest does not have — a change to what `mediagraph`'s features
//! MEAN, which is a ruling of its own rather than a step in a macro migration.
//!
//! So the road taken is the row below, hand-written and unmoved. It is also the road the mount would
//! have left in place: a mounted lowering delegates the per-column questions to the emitted product
//! and spends its own code on the whole-value ones, which is what this type already does with
//! [`SqlScalarComparison`] as its two component members.
//!
//! [`ComplexComparison`]: crate::ComplexComparison
//! [`ToDatabaseComparison`]: crate::ToDatabaseComparison
//!
//! [`RateFilter`]: super::RateFilter
//! [`SqlTimebaseComparison`]: super::super::SqlTimebaseComparison

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

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, CompositeComparison, ToDatabaseComparison,
  TryFromFilter,
  comparison::sql::{
    SqlConjunction, SqlKeyIn, SqlLoweringError, SqlScalarComparison, render_column,
  },
};
use smol_bytes::Utf8Bytes;

use super::{
  super::rational::Affix,
  Rate, RateFilter,
  storage::{DEN, NUM, SEGMENTS},
};

// 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 —
// so the module names `sqlx::Postgres` and needs that driver rather than the family root alone.
//
// The source crate carried a bare `#[cfg(test)]` here and never felt it, its own `sqlx` word arriving
// with a dialect behind it. In this crate `sqlx` is the family ROOT and a dialect is a word of its
// own, so the gate has to name the one it spells. It is the divergence the language family recorded
// on the same move — per-dialect gates replacing a single `sqlx` word — read one dialect over.
#[cfg(all(test, feature = "postgres"))]
mod tests;

/// The two column names a key set names, in the order [`SEGMENTS`](super::storage) lists them.
const PARTS: [&str; 2] = [NUM.as_str(), DEN.as_str()];

/// [`RateFilter`]'s storage-side twin: the two columns a reduced rate occupies, the whole-value
/// memberships over the pair, and the affix questions over its rendering.
pub struct SqlRateComparison<Db> {
  numerator: SqlScalarComparison<i32, Db>,
  denominator: SqlScalarComparison<i32, Db>,
  members: Option<SqlKeyIn<i32, Db, 2>>,
  excluded: Option<SqlKeyIn<i32, Db, 2>>,
  starts_with: Option<Utf8Bytes>,
  ends_with: Option<Utf8Bytes>,
  contains: Option<Utf8Bytes>,
}

impl<Db> SqlRateComparison<Db> {
  /// The empty comparison — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      numerator: SqlScalarComparison::new(),
      denominator: SqlScalarComparison::new(),
      members: None,
      excluded: None,
      starts_with: None,
      ends_with: None,
      contains: None,
    }
  }

  /// The operators over the numerator column — the storage operand, REDUCED, which is not always the
  /// numerator the client spelled.
  #[inline]
  pub const fn numerator(&self) -> &SqlScalarComparison<i32, Db> {
    &self.numerator
  }

  /// The operators over the denominator column, reduced alongside the numerator.
  #[inline]
  pub const fn denominator(&self) -> &SqlScalarComparison<i32, Db> {
    &self.denominator
  }

  /// The reduced pairs this column must be one of, or [`None`] where `in` was not asked.
  #[inline]
  pub const fn members(&self) -> Option<&SqlKeyIn<i32, Db, 2>> {
    self.members.as_ref()
  }

  /// The reduced pairs this column must be NONE of — `ne` and `not_in` merged, De Morgan having made
  /// them one question.
  #[inline]
  pub const fn excluded(&self) -> Option<&SqlKeyIn<i32, Db, 2>> {
    self.excluded.as_ref()
  }

  /// The `LIKE` pattern the rendering must match as a prefix, with its wildcard already on.
  #[inline]
  pub const fn starts_with(&self) -> Option<&Utf8Bytes> {
    self.starts_with.as_ref()
  }

  /// The `LIKE` pattern the rendering must match as a suffix.
  #[inline]
  pub const fn ends_with(&self) -> Option<&Utf8Bytes> {
    self.ends_with.as_ref()
  }

  /// The `LIKE` pattern the rendering must hold.
  #[inline]
  pub const fn contains(&self) -> Option<&Utf8Bytes> {
    self.contains.as_ref()
  }

  /// True while NO operator slot is set anywhere.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.numerator.is_empty()
      && self.denominator.is_empty()
      && self.members.is_none()
      && self.excluded.is_none()
      && self.starts_with.is_none()
      && self.ends_with.is_none()
      && self.contains.is_none()
  }

  /// How many conjuncts this comparison lowers to.
  ///
  /// EXACT: the two column halves report their own, and each whole-value and affix slot is one — a
  /// row-value membership is one predicate however many keys it holds, and a negation is one bracket
  /// around one.
  #[inline]
  pub const fn conjuncts(&self) -> usize {
    self.numerator.conjuncts()
      + self.denominator.conjuncts()
      + self.members.is_some() as usize
      + self.excluded.is_some() as usize
      + self.starts_with.is_some() as usize
      + self.ends_with.is_some() as usize
      + self.contains.is_some() as usize
  }
}

/// The lowering, whose bound list is [`SqlKeyIn`]'s plus the borrowed-string seat the affix patterns
/// bind through — the timebase comparison's list exactly, and every shipped dialect satisfies it.
impl<Db> ComplexComparison<Db> for SqlRateComparison<Db>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  /// The component halves, then the memberships, then the affixes — into the one accumulator all of
  /// them are handed, so the ` AND ` between any two is the accumulator's and no slot's.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let num = at.frame(NUM);
    let builder = self.numerator.apply(num.at(), builder)?;
    let den = at.frame(DEN);
    let builder = self.denominator.apply(den.at(), builder)?;

    // The key set pushes ITS OWN frames, from `PARTS`, so it is handed the address unchanged.
    let mut builder = match &self.members {
      Some(members) => members.apply(at, builder)?,
      None => builder,
    };

    if let Some(excluded) = &self.excluded {
      builder = negated(excluded, at, builder)?;
    }

    if self.starts_with.is_some() || self.ends_with.is_some() || self.contains.is_some() {
      // Rendered ONCE for the three slots that each name both columns.
      let num = render_column::<Db>(at.frame(NUM).at());
      let den = render_column::<Db>(at.frame(DEN).at());

      for pattern in [&self.starts_with, &self.ends_with, &self.contains]
        .into_iter()
        .flatten()
      {
        let qb = builder.open();
        qb.push("CONCAT(");
        qb.push(&num);
        qb.push(", '/', ");
        qb.push(&den);
        qb.push(") LIKE ");
        qb.push_bind(pattern.as_str());
      }
    }

    Ok(builder)
  }
}

/// `NOT ( … )` around a key set's own rendering — the timebase comparison's helper, over these
/// columns.
///
/// The nested accumulator leads with `""` because what goes inside the bracket is a bare PREDICATE
/// and not a clause; it is REBORROWED, so its borrow ends with the statement and the bracket below
/// is closed through the same buffer it opened.
fn negated<'q, Db>(
  keys: &'q SqlKeyIn<i32, Db, 2>,
  at: At<'_>,
  mut builder: SqlConjunction<'q, Db>,
) -> Result<SqlConjunction<'q, Db>, SqlLoweringError>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'a> Backend<Builder<'a> = SqlConjunction<'a, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
{
  let qb = builder.open();
  qb.push("NOT (");
  let _ = keys.apply(at, SqlConjunction::with_lead(&mut *qb, ""))?;
  qb.push(")");

  Ok(builder)
}

/// The one place both column lists a rate spans are stated, read by the predicate and by whatever
/// emits the DDL.
impl<Db> CompositeComparison<Db> for SqlRateComparison<Db>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

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

/// Written out rather than derived: a derive would bound `Db`, which is a marker no dialect type
/// implements anything for.
impl<Db> fmt::Debug for SqlRateComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlRateComparison")
      .field("numerator", &self.numerator)
      .field("denominator", &self.denominator)
      .field("members", &self.members)
      .field("excluded", &self.excluded)
      .field("starts_with", &self.starts_with)
      .field("ends_with", &self.ends_with)
      .field("contains", &self.contains)
      .finish()
  }
}

impl<Db> Clone for SqlRateComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      numerator: self.numerator.clone(),
      denominator: self.denominator.clone(),
      members: self.members.clone(),
      excluded: self.excluded.clone(),
      starts_with: self.starts_with.clone(),
      ends_with: self.ends_with.clone(),
      contains: self.contains.clone(),
    }
  }
}

impl<Db> PartialEq for SqlRateComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.numerator == other.numerator
      && self.denominator == other.denominator
      && self.members == other.members
      && self.excluded == other.excluded
      && self.starts_with == other.starts_with
      && self.ends_with == other.ends_with
      && self.contains == other.contains
  }
}

/// Every SQL dialect takes the rate filter to the rate comparison, and the storage type is `i32`
/// rather than a parameter: both halves of a rate are `i32` by construction, so a declaration naming
/// any other column type gets no impl and does not compile.
impl<Db> ToDatabaseComparison<i32, Db> for RateFilter
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlRateComparison<Db>;
}

/// **The same comparison, keyed by the CITIZEN** — the row a field declared `Rate` resolves through,
/// where the row above is the one a hand-flattened `fps_num`/`fps_den` pair resolves through.
///
/// It is [`Timebase`](super::super::Timebase)'s arrangement word for word, and for its reason: the
/// columns, the crossing and the rendered SQL are identical, so the second key names the same
/// projection and the two rows cannot overlap because [`Rate`] is not `i32`.
impl<Db> ToDatabaseComparison<Rate, Db> for RateFilter
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlRateComparison<Db>;
}

/// The crossing, and the only route into a [`SqlRateComparison`].
///
/// # No `Db` bound
///
/// 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`, including one that is not a database.
impl<Db> TryFromFilter<RateFilter> for SqlRateComparison<Db> {
  type Error = RateCrossingError;

  fn try_from_filter(filter: RateFilter) -> Result<Self, Self::Error> {
    let RateFilter {
      eq,
      ne,
      in_,
      not_in,
      starts_with,
      ends_with,
      contains,
      numerator,
      denominator,
    } = filter;

    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
    // filter, exactly what the hand-written parse this replaced wrote for a key a client omitted.
    let mut numerator = numerator.unwrap_or_default();
    let mut denominator = denominator.unwrap_or_default();

    if let Some(whole) = eq {
      // A whole-value equality lands in the halves' OWN equality slots, and a slot holds one
      // operand. Two equalities over one column are either a restatement or a contradiction, and
      // assigning over the top would silently keep whichever was written last.
      if numerator.eq().is_some() {
        return Err(RateCrossingError::NumeratorConflict);
      }
      if denominator.eq().is_some() {
        return Err(RateCrossingError::DenominatorConflict);
      }

      let (num, den) = whole.reduced();
      numerator = numerator.with_eq(num);
      denominator = denominator.with_eq(den);
    }

    let members = in_.map(|list| SqlKeyIn::new(PARTS, keys(&list)));

    // De Morgan: excluding one value AND excluding a set is excluding their union, so the two slots
    // are one key set and the ceiling below is counted once against the sum.
    let excluded = match (ne, not_in) {
      (None, None) => None,
      (single, list) => {
        let mut keys = keys(list.as_deref().unwrap_or_default());
        if let Some(single) = single {
          let (num, den) = single.reduced();
          keys.push([num, den.get()]);
        }
        Some(SqlKeyIn::new(PARTS, keys))
      }
    };

    Ok(Self {
      numerator: infallible(SqlScalarComparison::try_from_filter(numerator)),
      denominator: infallible(SqlScalarComparison::try_from_filter(denominator)),
      members,
      excluded,
      starts_with: affix(starts_with.as_deref(), Affix::Prefix)?,
      ends_with: affix(ends_with.as_deref(), Affix::Suffix)?,
      contains: affix(contains.as_deref(), Affix::Contains)?,
    })
  }
}

/// The reduced pairs a membership list becomes, in the order the operands were sent.
///
/// NOT de-duplicated: two operands that reduce to one pair are one row of the `IN` list either way,
/// and removing them would cost a sort to save a bind on an input nobody sends.
fn keys(operands: &[Rate]) -> Vec<[i32; 2]> {
  operands
    .iter()
    .map(|operand| {
      let (num, den) = operand.reduced();
      [num, den.get()]
    })
    .collect()
}

/// One affix operand as a pattern, with the shared gate's refusal wearing THIS citizen's error.
fn affix(operand: Option<&str>, affix: Affix) -> Result<Option<Utf8Bytes>, RateCrossingError> {
  super::super::rational::pattern(operand, affix).map_err(RateCrossingError::RenderAlphabet)
}

/// The two halves cross with `Error = Infallible`; matched out so the impossibility stays the
/// compiler's and never becomes a panic that cannot fire.
fn infallible<T>(crossed: Result<T, core::convert::Infallible>) -> T {
  match crossed {
    Ok(crossed) => crossed,
    Err(never) => match never {},
  }
}

/// A [`RateFilter`] did not reach the two columns, and this says which part of it did not.
///
/// Three variants, the timebase citizen's three — the two ways of naming one column's equality
/// twice, and the one operand a rendering cannot contain. A separate TYPE from that citizen's, with
/// the same shape, because a client filtering rates is asking about rates: the sentences below say
/// so, and sharing the type would have said the opposite.
///
/// [`RateFilter`]: super::RateFilter
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RateCrossingError {
  /// `eq` and `numerator`'s own `eq` both name the numerator's equality, and the column has one.
  NumeratorConflict,
  /// `eq` and `denominator`'s own `eq` both name the denominator's equality, and the column has one.
  DenominatorConflict,
  /// An affix operand holds a character a `num/den` rendering cannot — carrying the first one found.
  RenderAlphabet(char),
}

impl fmt::Display for RateCrossingError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::NumeratorConflict => f.write_str("the rate's numerator equality is named twice"),
      Self::DenominatorConflict => f.write_str("the rate's denominator equality is named twice"),
      Self::RenderAlphabet(outside) => write!(
        f,
        "a rate renders as digits and a slash, so `{outside}` matches no stored value"
      ),
    }
  }
}

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