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
//! The trait's own properties: the default emptiness, what a comparison that renders nothing leaves
//! behind, and the path a composite builds for the columns it occupies.
//!
//! The ADDRESSING half is two pointers and names no dialect, so it is checked in every lane. The
//! RENDERING half carries the `sqlite` gate, because the only implementors are the SQL family's and
//! a rendering is a thing a dialect does.

use super::{At, RecordAddress};
#[cfg(feature = "sqlite")]
use super::{ComplexComparison, Frame};
use crate::FieldName;
#[cfg(feature = "sqlite")]
use crate::{
  Backend, Carrier, Nullable, ScalarFilter,
  comparison::{
    TryFromFilter,
    sql::{
      QueryBuilder, SelectClause, SqlConjunction, SqlLoweringError, SqlNullable,
      SqlScalarComparison,
    },
  },
};

/// The row every lowering here constrains, and the address of one of its columns.
///
/// Nothing below reads the row — none of these comparisons is correlated — so it is wrapped once
/// here rather than at each assertion, which is what keeps the tests about the naming they are
/// actually asserting.
#[cfg(feature = "sqlite")]
const ROW: RecordAddress = RecordAddress::new(FieldName::new("p"), &[FieldName::new("id")]);

/// One column of [`ROW`], as a frame the caller holds: a child address BORROWS its path, so the
/// link has to outlive the `apply` it is handed to and a function cannot return the address itself.
#[cfg(feature = "sqlite")]
fn frame(column: &str) -> Frame<'_> {
  At::new(&ROW).frame(FieldName::new(column))
}

/// A comparison that reports a count and renders nothing.
///
/// [`ComplexComparison::is_empty`] is a DEFAULT body, so exercising it needs an implementor that
/// does not shadow it — every kind in the SQL family carries an inherent `is_empty` of its own,
/// which wins method resolution and would answer in the default's place.
#[cfg(feature = "sqlite")]
struct Counted(usize);

#[cfg(feature = "sqlite")]
impl ComplexComparison<sqlx::Sqlite> for Counted {
  fn conjuncts(&self) -> usize {
    self.0
  }

  // The PROJECTION, as the trait declares it. `SqlConjunction<'q, sqlx::Sqlite>` also compiles
  // while `&'q self` keeps `'q` late-bound — see `ComplexComparison::apply` for what unties it.
  fn apply<'q>(
    &'q self,
    _at: At<'_>,
    builder: <sqlx::Sqlite as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, SqlLoweringError> {
    Ok(builder)
  }
}

#[cfg(feature = "sqlite")]
#[test]
fn emptiness_follows_the_conjunct_count() {
  assert!(Counted(0).is_empty());
  assert!(!Counted(1).is_empty());
}

/// A comparison with no operators writes NOTHING into the accumulator it was handed, so the next
/// comparison's first conjunct still joins straight to the clause keyword rather than to a
/// separator nothing filled.
///
/// This is what `apply` opening conjuncts and never a clause buys: several comparisons share one
/// accumulator, the caller does not have to ask [`ComplexComparison::is_empty`] about any of them
/// first, and a caller that forgets does not render a broken statement.
#[cfg(feature = "sqlite")]
#[test]
fn an_empty_comparison_writes_nothing_and_leaves_nothing_dangling() {
  let empty =
    SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(ScalarFilter::<i64>::new()).unwrap();
  let set = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
    ScalarFilter::<i64>::new().with_eq(1i64),
  )
  .unwrap();

  let mut builder = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where();
  {
    let accumulator = SqlConjunction::new(builder.inner_mut());
    let accumulator = empty.apply(frame("n").at(), accumulator).unwrap();
    let accumulator = set.apply(frame("m").at(), accumulator).unwrap();
    assert_eq!(accumulator.written(), 1);
  }

  assert_eq!(
    builder.finalize().into_string(),
    "SELECT \"id\" FROM \"t\" WHERE \"m\" = ?"
  );
}

/// The CLAUSE keyword is the accumulator's too, pushed on the first conjunct and never before one —
/// so a statement whose every comparison is empty renders valid SQL with no ` WHERE ` in it.
///
/// "No filter given" is the ordinary query rather than a corner, and `SELECT … FROM "t" WHERE` is not
/// a statement. The keyword belongs where the SEPARATOR already does, and for the same reason: no
/// single writer knows whether it is the first. Making the caller ask
/// [`ComplexComparison::is_empty`] about every comparison first is exactly the footgun the
/// accumulator exists to remove.
#[cfg(feature = "sqlite")]
#[test]
fn a_statement_whose_comparisons_are_all_empty_opens_no_clause() {
  let empty =
    SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(ScalarFilter::<i64>::new()).unwrap();

  let mut builder = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where();
  {
    let accumulator = SqlConjunction::new(builder.inner_mut());
    let accumulator = empty.apply(frame("n").at(), accumulator).unwrap();
    let accumulator = empty.apply(frame("m").at(), accumulator).unwrap();
    assert_eq!(accumulator.written(), 0);
  }

  assert_eq!(builder.finalize().into_string(), "SELECT \"id\" FROM \"t\"");
}

/// A row keeps the names it was given, and the KEY WIDTH is the argument's rather than the type's —
/// the compile-time half of that is the doctest on [`RecordAddress::new`], and this is the positive
/// half it is paired with.
#[test]
fn a_row_keeps_the_table_and_the_key_columns_it_was_given() {
  const SEGMENT: RecordAddress = RecordAddress::new(
    FieldName::new("segment"),
    &[FieldName::new("media_id"), FieldName::new("segment_id")],
  );

  assert_eq!(SEGMENT.table(), FieldName::new("segment"));
  assert_eq!(
    SEGMENT.keys(),
    [FieldName::new("media_id"), FieldName::new("segment_id")]
  );
}

/// The TOP LEVEL is an address naming a row and no column, which is the whole of what a path buys:
/// under a single name every generated comparison had to be handed one, and there was no name that
/// made its columns render bare.
#[test]
fn the_top_level_names_a_row_and_no_column() {
  const SEGMENT: RecordAddress =
    RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);

  let at = At::new(&SEGMENT);

  assert!(at.path().is_none());
  assert_eq!(at.record(), &SEGMENT);
}

/// A frame extends the path by ONE segment and leaves the row alone, so a composite hands its parts
/// nothing but their own names and a generated comparison walks its entity's fields from a single
/// address.
///
/// The parent is unchanged, which is what lets one address serve every column of a row: pushing is
/// not a move.
#[test]
fn a_frame_extends_the_path_by_one_segment_and_keeps_the_row() {
  const SEGMENT: RecordAddress =
    RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);

  let at = At::new(&SEGMENT);
  let timebase = at.frame(FieldName::new("timebase"));
  let child = timebase.at();
  let path = child.path().expect("a frame names a column");

  assert_eq!(path.name(), FieldName::new("timebase"));
  assert!(path.parent().is_none());
  assert_eq!(child.record(), &SEGMENT);
  assert!(at.path().is_none());
}

/// The segments compose without any layer knowing the whole path: each pushes its own name onto
/// whatever it was handed, and only the walk back up the parents sees all three.
#[test]
fn the_segments_compose_and_no_layer_knows_the_whole_path() {
  const SEGMENT: RecordAddress =
    RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);

  let at = At::new(&SEGMENT);
  let a = at.frame(FieldName::new("a"));
  let num = a.at().frame(FieldName::new("num"));
  let den = num.at().frame(FieldName::new("den"));

  let mut segments = Vec::new();
  let mut cursor = den.at().path();
  while let Some(path) = cursor {
    segments.push(path.name());
    cursor = path.parent();
  }
  segments.reverse();

  assert_eq!(
    segments,
    [
      FieldName::new("a"),
      FieldName::new("num"),
      FieldName::new("den")
    ]
  );
}

/// A storage type that records the operand it BOUND, in bind order.
///
/// A composite's halves render `?` and `?`, so swapping them — the whole defect this design closes
/// — produces SQL that is byte-identical to the right answer. The operand is the only thing that
/// differs, and this is what sees it.
#[cfg(feature = "sqlite")]
struct Probe<'a> {
  value: i64,
  bound: &'a core::cell::RefCell<Vec<i64>>,
}

#[cfg(feature = "sqlite")]
impl Carrier<sqlx::Sqlite> for Probe<'_> {
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>) {
    self.bound.borrow_mut().push(self.value);
    qb.push_bind(self.value);
  }
}

/// ONE column — the default body, and the claim the bind above has to agree with: it pushes one
/// placeholder, so the lowering names one column. A downstream storage type writes exactly this
/// beside its carrier row.
#[cfg(feature = "sqlite")]
impl crate::ColumnKind for Probe<'_> {}

/// A two-column composite: one comparison per column, addressed by the part each occupies.
///
/// Generic over its halves rather than fixed to a leaf, which is what makes the three-level test
/// one type instead of two — `Ratio<Ratio<…, …>, …>` is this composite wrapping itself.
#[cfg(feature = "sqlite")]
struct Ratio<N, D> {
  num: N,
  den: D,
}

#[cfg(feature = "sqlite")]
impl<N, D> ComplexComparison<sqlx::Sqlite> for Ratio<N, D>
where
  N: ComplexComparison<sqlx::Sqlite>,
  D: ComplexComparison<sqlx::Sqlite>,
{
  fn conjuncts(&self) -> usize {
    self.num.conjuncts() + self.den.conjuncts()
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <sqlx::Sqlite as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, SqlLoweringError> {
    let num = at.frame(FieldName::new("num"));
    let builder = self.num.apply(num.at(), builder)?;
    let den = at.frame(FieldName::new("den"));
    self.den.apply(den.at(), builder)
  }
}

/// One column's comparison as a bare predicate FRAGMENT — no clause keyword, so what the assertions
/// below read is the conjuncts and their separators alone.
#[cfg(feature = "sqlite")]
fn rendered<C>(field: &str, comparison: &C) -> String
where
  C: ComplexComparison<sqlx::Sqlite>,
{
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let accumulator = SqlConjunction::with_lead(&mut qb, "");
    comparison.apply(frame(field).at(), accumulator).unwrap();
  }
  qb.sql().as_str().to_owned()
}

/// The same, applied at the TOP LEVEL — the address that names [`ROW`] and no column.
#[cfg(feature = "sqlite")]
fn rendered_at_top_level<C>(comparison: &C) -> String
where
  C: ComplexComparison<sqlx::Sqlite>,
{
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let accumulator = SqlConjunction::with_lead(&mut qb, "");
    comparison.apply(At::new(&ROW), accumulator).unwrap();
  }
  qb.sql().as_str().to_owned()
}

/// The `eq` operand alone, recording what it binds.
#[cfg(feature = "sqlite")]
fn eq(
  value: i64,
  bound: &core::cell::RefCell<Vec<i64>>,
) -> SqlScalarComparison<Probe<'_>, sqlx::Sqlite> {
  SqlScalarComparison::try_from_filter_with(
    ScalarFilter::<i64>::new().with_eq(value),
    |value: i64| Ok::<_, core::convert::Infallible>(Probe { value, bound }),
  )
  .unwrap()
}

/// ONE name goes down and each half extends it with its own part, so a composite occupying two
/// columns has no second name for a caller to pass — and therefore none to pass in the wrong order.
///
/// The bind log is the load-bearing half. Both halves render `?`, so a composite that handed the
/// numerator's comparison the denominator's name would produce this exact SQL and bind the two
/// operands the other way round.
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_addresses_its_parts_from_the_one_name_it_was_given() {
  let bound = core::cell::RefCell::new(Vec::new());
  let ratio = Ratio {
    num: eq(1, &bound),
    den: eq(90000, &bound),
  };

  assert_eq!(ratio.conjuncts(), 2);
  assert_eq!(
    rendered("timebase", &ratio),
    "\"timebase_num\" = ? AND \"timebase_den\" = ?"
  );
  assert_eq!(*bound.borrow(), [1, 90000]);
}

/// The same composite at the TOP LEVEL renders its parts BARE, because the top level is the empty
/// path and a part pushed onto nothing is the whole column name.
///
/// This is the case that had no answer under a single name. A composite was handed one and prefixed
/// every column with it, so the only way to render `num` was to pass a name that was not the row's
/// — and a predicate over a whole row would then disagree with the row's own address about which
/// column identifies it.
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_at_the_top_level_renders_its_parts_bare() {
  let bound = core::cell::RefCell::new(Vec::new());
  let ratio = Ratio {
    num: eq(1, &bound),
    den: eq(90000, &bound),
  };

  assert_eq!(rendered_at_top_level(&ratio), "\"num\" = ? AND \"den\" = ?");
  assert_eq!(*bound.borrow(), [1, 90000]);
}

/// Three levels deep, and no layer knows the whole path: the outer composite pushes `a`, which is
/// the only segment the middle one sees, and the middle one pushes onto THAT.
#[cfg(feature = "sqlite")]
#[test]
fn the_suffixes_compose_three_levels_deep() {
  let bound = core::cell::RefCell::new(Vec::new());
  let nested = Ratio {
    num: Ratio {
      num: eq(1, &bound),
      den: eq(2, &bound),
    },
    den: eq(3, &bound),
  };

  assert_eq!(nested.conjuncts(), 3);
  assert_eq!(
    rendered("a", &nested),
    "\"a_num_num\" = ? AND \"a_num_den\" = ? AND \"a_den\" = ?"
  );
  assert_eq!(*bound.borrow(), [1, 2, 3]);
}

/// The two kinds of composite compose with each other, and they extend the name differently for a
/// reason that is in the data rather than in the trait: [`SqlNullable`] wraps ANOTHER comparison of
/// the SAME column, so it passes its name down untouched, where a composite whose parts are SIBLING
/// columns extends it. Both are `ComplexComparison`, and the trait needs to know about neither.
#[cfg(feature = "sqlite")]
#[test]
fn a_same_column_wrapper_inside_a_composite_extends_nothing() {
  let bound = core::cell::RefCell::new(Vec::new());
  let ratio = Ratio {
    num: SqlNullable::<_, i64>::try_from_filter_with_inner(
      Nullable::new(ScalarFilter::<i64>::new().with_eq(1i64)).with_null(false),
      |inner| {
        SqlScalarComparison::try_from_filter_with(inner, |value: i64| {
          Ok::<_, core::convert::Infallible>(Probe {
            value,
            bound: &bound,
          })
        })
      },
    )
    .unwrap(),
    den: eq(2, &bound),
  };

  assert_eq!(ratio.conjuncts(), 3);
  assert_eq!(
    rendered("a", &ratio),
    "\"a_num\" = ? AND \"a_num\" IS NOT NULL AND \"a_den\" = ?"
  );
  assert_eq!(*bound.borrow(), [1, 2]);
}

/// The derived name reaches the column INTACT, however it is spelled: the suffix is appended to a
/// name and the leaf brackets what comes out, so a composite whose name needs quoting renders one
/// identifier per part rather than the syntax error a bracketed prefix would have produced.
///
/// The bracket character inside the name is the case that says the order is right: escaping it is
/// only possible once the whole name exists, which is after the suffix and not before it.
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_name_that_needs_quoting_reaches_its_columns() {
  let bound = core::cell::RefCell::new(Vec::new());
  let ratio = Ratio {
    num: eq(1, &bound),
    den: eq(2, &bound),
  };

  assert_eq!(
    rendered("time base", &ratio),
    "\"time base_num\" = ? AND \"time base_den\" = ?"
  );
  assert_eq!(
    rendered("time\"base", &ratio),
    "\"time\"\"base_num\" = ? AND \"time\"\"base_den\" = ?"
  );
}