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
use super::{ColumnName, ColumnShape, distinct, joins, width};
use crate::{FieldName, comparison::Path};

const NUM: &FieldName = FieldName::new("num");
const DEN: &FieldName = FieldName::new("den");
const TB: &FieldName = FieldName::new("tb");
const TIMEBASE: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(NUM)),
  ColumnShape::Plain(ColumnName::of(DEN)),
];

/// A field is ONE entry and its type decides how many columns it is, which is the whole of what the
/// nested list buys — a party sizing a statement asks a different question from one indexing binds.
#[test]
fn a_composite_is_one_entry_and_several_columns() {
  const COLUMNS: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("id")),
    ColumnShape::Composite {
      field: Some(ColumnName::of(TB)),
      segments: TIMEBASE,
    },
  ];
  assert_eq!(COLUMNS.len(), 2);
  assert_eq!(width(COLUMNS), 3);
}

/// Nesting counts LEAVES rather than parts: a composite holding a composite is still as many columns
/// as it has scalars at the bottom.
#[test]
fn width_counts_leaves_through_any_depth() {
  const RATIO: &[ColumnShape] = &[ColumnShape::Composite {
    field: Some(ColumnName::new("rate")),
    segments: TIMEBASE,
  }];
  const COLUMNS: &[ColumnShape] = &[ColumnShape::Composite {
    field: Some(ColumnName::of(TB)),
    segments: RATIO,
  }];
  assert_eq!(COLUMNS.len(), 1);
  assert_eq!(width(COLUMNS), 2);
}

/// A FLATTENED field lends no name, so it costs its holder nothing in width and everything in
/// namespace: the segments arrive at the holder's own level.
#[test]
fn a_flattened_composite_is_as_wide_as_a_prefixed_one() {
  const FLATTEN: &[ColumnShape] = &[ColumnShape::Composite {
    field: None,
    segments: TIMEBASE,
  }];
  const PREFIXED: &[ColumnShape] = &[ColumnShape::Composite {
    field: Some(ColumnName::of(TB)),
    segments: TIMEBASE,
  }];
  assert_eq!(width(FLATTEN), width(PREFIXED));
}

/// [`joins`] answers the question a `const` audit asks without building the joined name — and the
/// three refusals are the three ways a hand-written descriptor gets a prefixed column wrong.
#[test]
fn joins_compares_against_the_name_the_renderer_will_send() {
  let tb = Path::under(TB, None);
  let num = Path::under(NUM, Some(&tb));
  assert!(joins(&num, FieldName::new("tb_num")));
  // The separator is not optional.
  assert!(!joins(&num, FieldName::new("tbnum")));
  // A prefix nothing pushed is not one this row would render.
  assert!(!joins(&num, FieldName::new("clip_tb_num")));
  // The tail has to be the segment, not merely end in its letters.
  assert!(!joins(&num, FieldName::new("tb_denum")));
}

/// The TOP level joins to the field's own name — which is what makes a scalar's audit the
/// degenerate case of the composite's rather than a second rule.
#[test]
fn a_top_level_segment_joins_to_itself() {
  let tb = Path::under(TB, None);
  assert!(joins(&tb, TB));
  assert!(!joins(&tb, FieldName::new("t")));
}

/// **`flatten` is the word that makes a collision reachable**, and the twin one entry apart is what
/// attributes it: the same composite prefixed takes `tb_num`, so the holder's own `num` meets
/// nothing.
#[test]
fn a_flattened_segment_meets_a_column_the_holder_already_has() {
  const PREFIXED: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::of(NUM)),
    ColumnShape::Composite {
      field: Some(ColumnName::of(TB)),
      segments: TIMEBASE,
    },
  ];
  const FLATTENED: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::of(NUM)),
    ColumnShape::Composite {
      field: None,
      segments: TIMEBASE,
    },
  ];
  assert!(distinct(PREFIXED, 1));
  assert!(!distinct(FLATTENED, 1));
  // The fence is asked per FIELD, and the field that introduced the collision is the one that
  // answers: `num` alone is still a row with one column in it.
  assert!(distinct(FLATTENED, 0));
}

/// TWO flattened composites both lending nothing collide with each other, which is the case no plain
/// column is involved in at all.
#[test]
fn two_flattened_composites_collide_with_each_other() {
  const COLUMNS: &[ColumnShape] = &[
    ColumnShape::Composite {
      field: None,
      segments: TIMEBASE,
    },
    ColumnShape::Composite {
      field: None,
      segments: TIMEBASE,
    },
  ];
  assert!(distinct(COLUMNS, 0));
  assert!(!distinct(COLUMNS, 1));
}

/// A field is checked against ITSELF, so a composite whose own segments render alike is refused with
/// no second field involved — here through a NESTED one, which is the shape that has no flat
/// spelling to notice.
#[test]
fn a_composite_can_collide_with_its_own_segment() {
  const INNER: &[ColumnShape] = &[ColumnShape::Plain(ColumnName::new("num"))];
  const SELF_COLLIDING: &[ColumnShape] = &[ColumnShape::Composite {
    field: None,
    segments: &[
      ColumnShape::Composite {
        field: Some(ColumnName::of(TB)),
        segments: INNER,
      },
      ColumnShape::Plain(ColumnName::new("tb_num")),
    ],
  }];
  assert!(!distinct(SELF_COLLIDING, 0));
}

/// **The name a DECODE asks for is the name the `SELECT` renders.** Two joins exist — the render's,
/// bracketed for a dialect, and the read's, bare — and this is the pinning that keeps them one rule:
/// a change to either that the other did not make shows up here.
#[cfg(feature = "sqlite")]
#[test]
fn the_decode_asks_for_the_name_the_select_renders() {
  use crate::comparison::sql::{column_name, fold_columns};

  const ID: &FieldName = FieldName::new("id");
  const COLUMNS: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::of(ID)),
    ColumnShape::Composite {
      field: Some(ColumnName::of(TB)),
      segments: TIMEBASE,
    },
  ];

  let rendered =
    fold_columns::<sqlx::Sqlite, Vec<String>>(COLUMNS, Vec::new(), &mut |mut names, column| {
      names.push(column.as_str().to_owned());
      names
    });
  let tb = Path::under(TB, None);
  let read = [
    column_name(&Path::under(ID, None)),
    column_name(&Path::under(NUM, Some(&tb))),
    column_name(&Path::under(DEN, Some(&tb))),
  ];

  assert_eq!(rendered, [r#""id""#, r#""tb_num""#, r#""tb_den""#]);
  assert_eq!(
    rendered,
    read
      .iter()
      .map(|name| format!("\"{name}\""))
      .collect::<Vec<_>>(),
    "the read's name is the rendered one with the dialect's brackets taken off"
  );
}

/// A PLAIN field's name is already a `&'static str` the path holds, so the read borrows it; only a
/// composite's leaf has a name that exists nowhere and has to be built.
#[cfg(feature = "sqlx")]
#[test]
fn only_a_composites_leaf_allocates_its_name() {
  use std::borrow::Cow;

  use crate::comparison::sql::column_name;

  let tb = Path::under(TB, None);
  assert!(matches!(column_name(&tb), Cow::Borrowed("tb")));
  assert!(matches!(
    column_name(&Path::under(NUM, Some(&tb))),
    Cow::Owned(_)
  ));
}

/// **The framework's OWN composite, and the shape it answers.** Two columns, named `secs` and
/// `nanos`, under whatever field a declaration gives it — which is the same walk a declared
/// composite takes and is why the rows above needed no new machinery.
#[test]
fn the_shipped_instant_is_two_columns() {
  use crate::{ColumnKind, Timestamp, shape};

  const AT: &FieldName = FieldName::new("at");
  const COLUMNS: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("id")),
    shape::<Timestamp>(ColumnName::of(AT)),
  ];

  assert_eq!(COLUMNS.len(), 2, "an id and an instant");
  assert_eq!(width(COLUMNS), 3, "which is three columns");
  assert_eq!(<Timestamp as ColumnKind>::SEGMENTS.len(), 2);

  let at = Path::under(AT, None);
  assert!(joins(
    &Path::under(FieldName::new("secs"), Some(&at)),
    FieldName::new("at_secs")
  ));
  assert!(joins(
    &Path::under(FieldName::new("nanos"), Some(&at)),
    FieldName::new("at_nanos")
  ));
}

/// **The instant's decode, against a LIVE driver, both ways.**
///
/// Compiling proves the row exists; only reading a real pair back proves it reads the right column
/// into the right half. The two columns are returned in an order the shape does not declare and both
/// are integers, so a positional decode would pass while transposing — and the values are chosen so
/// a transposition is not an instant at all.
///
/// The second half is THE TEETH at the place they exist for: a row holding a pair jiff would have
/// normalised is refused as [`ColumnDecode`](sqlx::Error::ColumnDecode) naming `at_nanos`, rather
/// than decoded into an instant nothing stored.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn an_instant_decodes_from_both_of_its_columns_and_refuses_a_pair_it_did_not_write() {
  use sqlx::Connection as _;

  use crate::{Assemble, Timestamp, assembled};

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  for statement in [
    r#"CREATE TABLE "stamps" ("id" INTEGER, "at_secs" BIGINT, "at_nanos" INT)"#,
    r#"INSERT INTO "stamps" VALUES (1, 1786310043, 123456789)"#,
    // The pair jiff resolves rather than refuses — written here by something that is not this
    // encoding, which is the whole situation the check exists for.
    r#"INSERT INTO "stamps" VALUES (2, 2, -999999999)"#,
  ] {
    sqlx::query(statement)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");
  }

  let read = |id: i64| {
    // Returned in the order the row does not declare, and both columns are integers.
    sqlx::query(r#"SELECT "at_nanos", "id", "at_secs" FROM "stamps" WHERE "id" = ?"#).bind(id)
  };
  let stored = read(1).fetch_one(&mut db).await.expect("one row");
  let at: Timestamp = assembled(&stored, FieldName::new("at"), None).expect("the pair decodes");
  assert_eq!(at.to_string(), "2026-08-09T21:14:03.123456789Z");

  let forged = read(2).fetch_one(&mut db).await.expect("one row");
  let refused =
    <Timestamp as Assemble<_>>::assemble(&forged, Some(&Path::under(FieldName::new("at"), None)))
      .expect_err("a sign-crossing pair is not an instant");
  assert!(
    matches!(&refused, sqlx::Error::ColumnDecode { index, .. } if index == "at_nanos"),
    "{refused:?}"
  );
}

/// **THE THREE WORDS' TRUTH TABLE**, read off the enum rather than off any one reader.
///
/// Two independent bits over three variants, and the table is what says they are independent:
/// `holds_value` is VALUE against INDEX, `self_nullable` is *may this column be `NULL` on its own*,
/// and only [`ColumnShape::Derived`] answers `false` to both. Before the third word existed
/// `holds_value` was `self_nullable`'s complement, so the row below could not be written — and a
/// regression that restored the complement would fail here rather than in a `CREATE TABLE` nobody
/// reads.
///
/// [`width`] and [`value_width`](super::value_width) are the counted readings of the same two bits
/// and are asserted beside them: every leaf is one COLUMN, and only the plain one is part of the
/// VALUE.
#[test]
fn the_three_leaf_words_answer_two_independent_bits() {
  const PLAIN: ColumnShape = ColumnShape::Plain(ColumnName::new("pts"));
  const NULLABLE: ColumnShape = ColumnShape::Nullable(ColumnName::new("nanos"));
  const DERIVED: ColumnShape = ColumnShape::Derived(ColumnName::new("area"));

  let table: Vec<_> = [PLAIN, NULLABLE, DERIVED]
    .into_iter()
    .map(|shape| (shape.holds_value(), shape.self_nullable()))
    .collect();

  assert_eq!(
    table,
    [(true, false), (false, true), (false, false)],
    "plain: value, never null · nullable: index, may be null · derived: index, never null"
  );

  assert_eq!(
    [PLAIN, NULLABLE, DERIVED].map(|shape| shape.width()),
    [1, 1, 1],
    "all three are ONE column the DDL creates and the write binds"
  );

  const LEAVES: &[ColumnShape] = &[PLAIN, NULLABLE, DERIVED];
  const _: () = assert!(width(LEAVES) == 3);
  const _: () = assert!(super::value_width(LEAVES) == 1);

  // A composite is neither leaf answer: it is no column, so it holds no `NULL` of its own, and its
  // leaves each answer for themselves.
  const COMPOSITE: ColumnShape = ColumnShape::Composite {
    field: Some(ColumnName::of(TB)),
    segments: TIMEBASE,
  };
  assert!(COMPOSITE.holds_value());
  assert!(!COMPOSITE.self_nullable());
  assert_eq!(super::value_width(&[COMPOSITE]), 2);
}

/// **A DERIVED LEAF IS INSIDE EVERY NAME WALK AND OUTSIDE EVERY VALUE WALK**, under BOTH of its
/// words — the pairing the third variant had to join rather than escape.
///
/// The two derived words are asserted to render alike and count alike, because the whole hazard of
/// adding one is a walk that branched on nullability where the question was about the value: such a
/// walk would have kept the area inside a row-value equality while dropping the nanos.
#[test]
fn the_two_derived_words_are_named_alike_and_counted_alike() {
  const PARTIAL: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("pts")),
    ColumnShape::Nullable(ColumnName::new("index")),
  ];
  const TOTAL: &[ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("pts")),
    ColumnShape::Derived(ColumnName::new("index")),
  ];

  assert_eq!(width(PARTIAL), width(TOTAL), "both are two COLUMNS");
  assert_eq!(
    super::value_width(PARTIAL),
    super::value_width(TOTAL),
    "and one VALUE column apiece"
  );
  assert_eq!(
    super::stored_column(TOTAL, "index").map(FieldName::as_str),
    Some("index"),
    "a lookup answers a total index's stored spelling as it answers a partial one's"
  );
  assert!(
    distinct(TOTAL, 1),
    "and a derived leaf takes part in the collision fence like any other column"
  );
}

/// **A PATTERN COLUMN ROUND-TRIPS THROUGH ITS TEXT, AN ABSENT ONE COMES BACK ABSENT, AND A STORED
/// PATTERN THAT NO LONGER COMPILES REFUSES BY NAME** — the three facts a pattern column states, on
/// the one dialect an in-memory database gives this test for free.
///
/// The third is why the row exists. A uuid reads back as the bytes it wrote and cannot fail; a
/// pattern reads back by being RE-COMPILED, so the read does real work and has a failure mode — and
/// the whole point of the citizen's decode row is that the failure is a
/// [`ColumnDecode`](sqlx::Error::ColumnDecode) naming the column, never a panic and never a value
/// minted around the hole. The forged row here is what a hand edit, a shared column or a dependency
/// whose grammar moved would leave behind.
///
/// `Option<regex::Regex>` is asserted beside it because it is the shape an application actually
/// declares — a watch's `include`/`exclude` are each a pattern or nothing — so a citizen that landed
/// only unwrapped would have landed for nobody.
#[cfg(all(feature = "sqlite", feature = "regex"))]
#[tokio::test]
async fn a_pattern_column_round_trips_as_text_and_refuses_one_that_no_longer_compiles() {
  use sqlx::Connection as _;

  use crate::Assemble;

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  for statement in [
    r#"CREATE TABLE "watches" ("id" INTEGER, "include" TEXT)"#,
    r#"INSERT INTO "watches" VALUES (1, '^[a-z]+(?:-[0-9]+)?$')"#,
    r#"INSERT INTO "watches" VALUES (2, NULL)"#,
    // The row this code did not write: a pattern the engine refuses. An unclosed group is the
    // shortest such text and reads identically to a truncated one.
    r#"INSERT INTO "watches" VALUES (3, 'a(b')"#,
  ] {
    sqlx::query(statement)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");
  }

  let read = |id: i64| sqlx::query(r#"SELECT "include" FROM "watches" WHERE "id" = ?"#).bind(id);
  let under = Path::under(FieldName::new("include"), None);

  let stored = read(1).fetch_one(&mut db).await.expect("one row");
  let pattern =
    <regex::Regex as Assemble<_>>::assemble(&stored, Some(&under)).expect("the pattern compiles");
  assert_eq!(
    pattern.as_str(),
    "^[a-z]+(?:-[0-9]+)?$",
    "what comes back is the text that was stored"
  );
  assert!(
    pattern.is_match("alpha-7") && !pattern.is_match("Alpha"),
    "and the value that comes back is the automaton that text names"
  );

  let absent = read(2).fetch_one(&mut db).await.expect("one row");
  let none = <Option<regex::Regex> as Assemble<_>>::assemble(&absent, Some(&under))
    .expect("a NULL is a value of the optional column");
  assert!(none.is_none(), "an absent pattern comes back absent");

  let forged = read(3).fetch_one(&mut db).await.expect("one row");
  let refused = <regex::Regex as Assemble<_>>::assemble(&forged, Some(&under))
    .expect_err("`a(b` is not a pattern this build compiles");
  assert!(
    matches!(&refused, sqlx::Error::ColumnDecode { index, .. } if index == "include"),
    "the refusal names the COLUMN: {refused:?}"
  );
  let source = std::error::Error::source(&refused).expect("the refusal carries its cause");
  assert!(
    source
      .to_string()
      .contains("the stored pattern does not compile"),
    "and the cause says what went wrong: {source}"
  );

  // The optional column refuses on exactly the same text — `Option` decides what a column may HOLD
  // and never what a stored value MEANS, so the teeth are the same teeth.
  let refused_optional = <Option<regex::Regex> as Assemble<_>>::assemble(&forged, Some(&under))
    .expect_err("an optional pattern column has the same teeth");
  assert!(
    matches!(&refused_optional, sqlx::Error::ColumnDecode { index, .. } if index == "include"),
    "{refused_optional:?}"
  );
}

/// A pattern is ONE column wide, and an optional one is the same one column: nullability decides
/// what a column may hold, not how many there are.
#[cfg(feature = "regex")]
#[test]
fn a_pattern_is_one_column_wide_whether_or_not_it_is_optional() {
  use crate::{ColumnKind, ColumnName, shape, width};

  assert!(
    <regex::Regex as ColumnKind>::SEGMENTS.is_empty(),
    "a pattern is a SCALAR"
  );
  const FIELD: ColumnName = ColumnName::new("include");
  assert_eq!(width(&[shape::<regex::Regex>(FIELD)]), 1);
  assert_eq!(width(&[shape::<Option<regex::Regex>>(FIELD)]), 1);
}