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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! What an order renders as, per dialect and per walk, and what it refuses first.
//!
//! Asserting on the rendered text is right here for the reason the clause machine's own tests give:
//! the deliverable IS the text. What the text has to show is the pinned position of `NULL`, and it
//! shows up in exactly one of the three dialects — which is the measurement, not an omission.

#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]

use super::{SqlOrder, SqlOrderError};
use crate::{
  FieldName, OrderDirection, OrderTerm, RecordAddress, TermName, Walk,
  comparison::{
    At,
    sql::{
      NullOrder, NullOrdering, OrderSubjects, QueryBuilder, QuoteIdent, SelectClause, SubjectShape,
      SubjectSlot, TermColumns, quote_ident,
    },
  },
  query::{
    CollectionBoundary, CollectionOrdering, NullPlacement, OrderCapability, ShadowBoundary,
    ShadowOrdering, TermRepetition,
  },
};

/// The identities the orders below are written over.
const CREATED: &TermName = TermName::new("created_at");
const TITLE: &TermName = TermName::new("title");
const ID: &TermName = TermName::new("id");
const TAGS: &TermName = TermName::new("tags");

/// `created_at DESC, id ASC` over `NOT NULL` columns — the ordinary written order with its key
/// tail.
fn required() -> [OrderTerm; 2] {
  [
    OrderTerm::new(CREATED, FieldName::new("created_at"), OrderDirection::Desc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ]
}

/// The same order with a NULLABLE sort column in front of it.
fn optional() -> [OrderTerm; 3] {
  [
    OrderTerm::nullable(TITLE, FieldName::new("title"), OrderDirection::Asc),
    OrderTerm::new(CREATED, FieldName::new("created_at"), OrderDirection::Desc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ]
}

/// `SELECT * FROM t ORDER BY …` for one dialect, as `terms` renders it running `walk`'s way.
///
/// The table is pushed UNQUOTED — the clause machine takes a table as the caller's already-bracketed
/// text — so the only bracketing in these assertions is the ordering column's, which is what they
/// are about.
fn ordered<Db>(terms: &[OrderTerm], walk: Walk) -> String
where
  Db: sqlx::Database + QuoteIdent + NullOrder + OrderCapability,
{
  let order = SqlOrder::<Db>::new(terms).expect("this order is renderable for this dialect");
  order
    .push_order_by(
      QueryBuilder::<SelectClause, Db>::select()
        .push_field("*")
        .from("t"),
      walk,
    )
    .finalize()
    .into_string()
}

/// The row every subject below is written against — a table and the column that identifies one of
/// its rows.
const ROW: RecordAddress = RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]);

/// The same statement with each term's left-hand side written by `subjects`.
///
/// What a subject binds is not asserted here and is not missing: the keyset's own tests render this
/// same shape and count the operands at every occurrence, which is the polarity where a subject
/// written once and reused would still produce the right text.
fn ordered_over<Db, S>(terms: &[OrderTerm], walk: Walk, subjects: &S) -> String
where
  Db: sqlx::Database + NullOrder + OrderCapability,
  S: OrderSubjects<Db>,
{
  let order = SqlOrder::<Db>::new(terms).expect("this order is renderable for this dialect");
  order
    .push_order_by_with(
      QueryBuilder::<SelectClause, Db>::select()
        .push_field("*")
        .from("t"),
      walk,
      At::new(&ROW),
      subjects,
    )
    .finalize()
    .into_string()
}

/// Term 0's subject is a correlated scalar SUBQUERY and every other term's is its column — the
/// mixed order a nested ordering term produces, and the same party the keyset's own tests render
/// through.
struct CoverTitle;

impl<Db: sqlx::Database + crate::Backend<Buffer: core::fmt::Display> + QuoteIdent> OrderSubjects<Db>
  for CoverTitle
{
  fn push_subject(&self, slot: SubjectSlot<'_, Db>, at: At<'_>, terms: &[OrderTerm], level: usize) {
    if level > 0 {
      TermColumns.push_subject(slot, at, terms, level);
      return;
    }
    // The BODY and no brackets, which is every provider's contract: the pair a sub-select needs is
    // the slot's, and dropping it is a syntax error on all three engines rather than an untidiness.
    slot.write(|qb| {
      qb.push("SELECT ");
      qb.push(quote_ident::<Db>(FieldName::new("title")));
      qb.push(" FROM ");
      qb.push(quote_ident::<Db>(FieldName::new("keyframe")));
      qb.push(" WHERE ");
      qb.push(quote_ident::<Db>(FieldName::new("id")));
      qb.push(" = ");
      qb.push(quote_ident::<Db>(FieldName::new("cover_id")));
    });
  }

  /// Level 0 is the subquery and every other level is its own column — stated rather than delegated
  /// to [`TermColumns`], whose answer is the trait's default and names no `Db` for inference to find.
  fn shape(&self, _: &[OrderTerm], level: usize) -> SubjectShape {
    if level > 0 {
      return SubjectShape::Column;
    }
    SubjectShape::SubSelect
  }
}

/// **The seam at its default.** A column ordering is [`TermColumns`] written out, so the text every
/// assertion above renders is reached by both ways in and is ONE text — which is what keeps the
/// named form from drifting from the form the keyset compares against, the drift that skips or
/// repeats exactly the rows at a page boundary.
///
/// All three dialects and both polarities, because the two renderings differ in exactly the two
/// things a dialect decides: how an identifier is bracketed and whether the `NULL` position is
/// stated.
#[test]
fn the_named_ordering_is_the_subject_seam_at_its_default() {
  #[cfg(feature = "sqlite")]
  for walk in [Walk::Forward, Walk::Backward] {
    for terms in [&required()[..], &optional()[..]] {
      assert_eq!(
        ordered_over::<sqlx::Sqlite, _>(terms, walk, &TermColumns),
        ordered::<sqlx::Sqlite>(terms, walk)
      );
    }
  }
  #[cfg(feature = "postgres")]
  for walk in [Walk::Forward, Walk::Backward] {
    for terms in [&required()[..], &optional()[..]] {
      assert_eq!(
        ordered_over::<sqlx::Postgres, _>(terms, walk, &TermColumns),
        ordered::<sqlx::Postgres>(terms, walk)
      );
    }
  }
  #[cfg(feature = "mysql")]
  for walk in [Walk::Forward, Walk::Backward] {
    for terms in [&required()[..], &optional()[..]] {
      assert_eq!(
        ordered_over::<sqlx::MySql, _>(terms, walk, &TermColumns),
        ordered::<sqlx::MySql>(terms, walk)
      );
    }
  }
}

/// **The expression in ordering position.** The provider writes the subquery's BODY, the slot its
/// shape opened brackets it, and the direction is pushed after the pair — so a nested term reaches
/// the `ORDER BY` as a term like any other.
#[cfg(feature = "sqlite")]
#[test]
fn a_correlated_subquery_is_an_ordering_term_like_any_other() {
  assert_eq!(
    ordered_over::<sqlx::Sqlite, _>(&required(), Walk::Forward, &CoverTitle),
    "SELECT * FROM t ORDER BY \
     (SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = \"cover_id\") DESC, \"id\" ASC"
  );
}

/// The `NULL` position is stated on the term whose subject is an EXPRESSION exactly as it is on a
/// column's, which is the pin holding: what the position is about is the term's VALUE, and a
/// missing to-one target is SQL `NULL` in that position as surely as an absent column value is.
#[cfg(feature = "postgres")]
#[test]
fn a_nested_term_takes_the_pinned_null_position_too() {
  assert_eq!(
    ordered_over::<sqlx::Postgres, _>(&optional(), Walk::Forward, &CoverTitle),
    "SELECT * FROM t ORDER BY \
     (SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = \"cover_id\") ASC NULLS FIRST, \
     \"created_at\" DESC, \"id\" ASC"
  );
  assert_eq!(
    ordered_over::<sqlx::Postgres, _>(&optional(), Walk::Backward, &CoverTitle),
    "SELECT * FROM t ORDER BY \
     (SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = \"cover_id\") DESC NULLS LAST, \
     \"created_at\" ASC, \"id\" DESC"
  );
}

/// A BORROWED subjects party answers exactly as the party does, which is what lets one value reach
/// the ordering and the keyset both — two renderings of one order, from one subject.
#[cfg(feature = "sqlite")]
#[test]
fn one_subjects_value_serves_both_renderings() {
  let subjects = CoverTitle;
  assert_eq!(
    ordered_over::<sqlx::Sqlite, _>(&required(), Walk::Forward, &&subjects),
    ordered_over::<sqlx::Sqlite, _>(&required(), Walk::Forward, &subjects)
  );
}

/// The dialects whose own default already puts `NULL` where the framework pins it state NOTHING —
/// so the ordering term is the bare column and an index over it still serves the order.
///
/// Measured: SQLite 3.51.0 and MySQL 8.4.11 both lead an ascending term with `NULL` and trail a
/// descending one, which IS the pinned position.
#[test]
fn the_dialects_that_already_agree_state_nothing() {
  #[cfg(feature = "sqlite")]
  {
    assert_eq!(<sqlx::Sqlite as NullOrder>::NULLS, NullOrdering::Implicit);
    assert_eq!(
      ordered::<sqlx::Sqlite>(&optional(), Walk::Forward),
      "SELECT * FROM t ORDER BY \"title\" ASC, \"created_at\" DESC, \"id\" ASC"
    );
  }
  #[cfg(feature = "mysql")]
  {
    assert_eq!(<sqlx::MySql as NullOrder>::NULLS, NullOrdering::Implicit);
    assert_eq!(
      ordered::<sqlx::MySql>(&optional(), Walk::Forward),
      "SELECT * FROM t ORDER BY `title` ASC, `created_at` DESC, `id` ASC"
    );
  }
}

/// The one dialect whose own default DISAGREES states the position on the term.
///
/// Measured: PostgreSQL 16.14 and 17.10 trail an ascending term with `NULL` and lead a descending
/// one — the opposite of the pin — and both have the clause, so the term carries it.
#[cfg(feature = "postgres")]
#[test]
fn postgres_states_the_position_on_the_term() {
  assert_eq!(<sqlx::Postgres as NullOrder>::NULLS, NullOrdering::Explicit);
  assert_eq!(
    ordered::<sqlx::Postgres>(&optional(), Walk::Forward),
    "SELECT * FROM t ORDER BY \"title\" ASC NULLS FIRST, \"created_at\" DESC, \"id\" ASC"
  );
}

/// A `NOT NULL` term states nothing on ANY dialect, Postgres included: the column holds no `NULL`,
/// so every position is the same position and the clause would cost an index match for a row that
/// cannot exist.
#[cfg(feature = "postgres")]
#[test]
fn a_not_null_term_states_nothing_even_where_the_dialect_disagrees() {
  assert_eq!(
    ordered::<sqlx::Postgres>(&required(), Walk::Forward),
    "SELECT * FROM t ORDER BY \"created_at\" DESC, \"id\" ASC"
  );
}

/// A backward walk inverts every term — which, with the rows re-reversed after they come back, is
/// the same order read from the far end.
#[cfg(feature = "sqlite")]
#[test]
fn a_backward_walk_inverts_every_term() {
  assert_eq!(
    ordered::<sqlx::Sqlite>(&required(), Walk::Backward),
    "SELECT * FROM t ORDER BY \"created_at\" ASC, \"id\" DESC"
  );
}

/// **The property the pin was chosen for.** The framework's `NULL` position is a total order on the
/// domain, so inverting a term inverts the position with it — `ASC NULLS FIRST` reverses into
/// `DESC NULLS LAST`, which is the same rule and not a second one.
///
/// A position pinned as a per-direction convention would not do this: `NULLS LAST` whichever way the
/// term runs reverses into `NULLS FIRST`, so the two directions of one relay connection would order
/// the nulls differently and a client walking back across a null boundary would skip or repeat
/// exactly the rows on it.
#[cfg(feature = "postgres")]
#[test]
fn the_pinned_position_inverts_with_the_walk() {
  assert_eq!(
    ordered::<sqlx::Postgres>(&optional(), Walk::Forward),
    "SELECT * FROM t ORDER BY \"title\" ASC NULLS FIRST, \"created_at\" DESC, \"id\" ASC"
  );
  assert_eq!(
    ordered::<sqlx::Postgres>(&optional(), Walk::Backward),
    "SELECT * FROM t ORDER BY \"title\" DESC NULLS LAST, \"created_at\" ASC, \"id\" DESC"
  );
}

/// A column name is bracketed by the clause machine's own seam, so an order carries no escaping rule
/// of its own — and a name holding the bracket character is doubled rather than closing its quoting.
#[cfg(feature = "sqlite")]
#[test]
fn a_column_is_bracketed_by_the_seam_that_already_brackets_one() {
  let terms = [OrderTerm::new(
    ID,
    FieldName::new("a\"b"),
    OrderDirection::Asc,
  )];

  assert_eq!(
    ordered::<sqlx::Sqlite>(&terms, Walk::Forward),
    "SELECT * FROM t ORDER BY \"a\"\"b\" ASC"
  );
}

/// There is no default order, so an order over NO terms has no spelling — refused before a
/// `QueryBuilder` is touched.
#[cfg(feature = "sqlite")]
#[test]
fn an_order_over_no_terms_is_refused() {
  assert_eq!(
    SqlOrder::<sqlx::Sqlite>::new(&[]).map(|order| order.terms().len()),
    Err(SqlOrderError::Empty)
  );
}

/// A dialect that can place `NULL` NEITHER way — its own default disagrees and it has no clause.
///
/// None of the three shipped dialects is one, so the third [`NullOrdering`] member is reachable only
/// from a dialect written downstream. That is exactly what it is for: the trait is a per-dialect
/// capability, and a fourth engine has to be able to say honestly that it has not got this one.
struct Placeless;

impl NullOrder for Placeless {
  const NULLS: NullOrdering = NullOrdering::Inexpressible;
}

/// Its capability row, which the two SQL answers project through rather than restate: the null
/// placement IS the `NullOrder` answer above, and the list reading is the SQL family's. What it says
/// about collections is what every dialect but PostgreSQL says.
impl OrderCapability for Placeless {
  const NULLS: NullPlacement = NullPlacement::of(<Self as NullOrder>::NULLS);
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Divergent;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// **Refusing is what makes the pin mean anything.** A dialect that cannot place `NULL` gets a
/// typed refusal naming the offending term — not the dialect's own ordering, which would serve a
/// page ordered one way against a cursor comparing the other and report nothing.
#[test]
fn a_dialect_that_cannot_place_null_refuses_a_nullable_term() {
  assert_eq!(
    SqlOrder::<Placeless>::new(&optional()).map(|order| order.terms().len()),
    Err(SqlOrderError::NullPosition(TITLE))
  );
}

/// …and keeps working for every order that has no `NULL` to place, which is the honest granularity:
/// what the dialect cannot express is a POSITION, and an order over `NOT NULL` columns needs none.
#[test]
fn a_dialect_that_cannot_place_null_still_orders_columns_that_hold_none() {
  assert_eq!(
    SqlOrder::<Placeless>::new(&required()).map(|order| order.terms().len()),
    Ok(2)
  );
}

/// The signature an order carries is the one a cursor minted under it holds, and it is the terms'
/// rather than the dialect's — see [`OrderSignature`](crate::OrderSignature).
#[cfg(all(feature = "sqlite", feature = "postgres"))]
#[test]
fn one_written_order_signs_alike_on_two_dialects() {
  let terms = required();
  let sqlite = SqlOrder::<sqlx::Sqlite>::new(&terms).expect("a renderable order");
  let postgres = SqlOrder::<sqlx::Postgres>::new(&terms).expect("a renderable order");

  assert_eq!(sqlite.signature(), postgres.signature());
}

/// Each refusal says what it says in one sentence.
#[test]
fn the_refusals_say_which_one_they_are() {
  assert_eq!(
    SqlOrderError::Empty.to_string(),
    "an order over no terms has no spelling"
  );
  assert_eq!(
    SqlOrderError::NullPosition(TITLE).to_string(),
    "`title` is nullable and this dialect cannot put NULL below every value"
  );
}

/// **THE ONE PUSHABLE ROW RENDERS, AND IT RENDERS NOTHING SPECIAL.**
///
/// PostgreSQL's array ordering IS the framework's, so an order over a collection column is one
/// bracketed name like any other — which is the whole of what *pushable* buys. The text is the
/// deliverable here for the reason this module's note gives.
#[cfg(feature = "postgres")]
#[test]
fn postgres_orders_a_column_stored_collection_as_a_plain_term() {
  let terms = [
    OrderTerm::array(TAGS, FieldName::new("tags"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ];

  assert_eq!(
    ordered::<sqlx::Postgres>(&terms, Walk::Forward),
    r#"SELECT * FROM t ORDER BY "tags" ASC, "id" ASC"#
  );
}

/// …and the two dialects that mean something else by it refuse the same order, by name.
///
/// A column-stored collection is JSON on both, and JSON's ordering compares the stored text or ranks
/// by element type before value — so `ORDER BY tags` there answers a different question under the
/// client's own term. It is the same fact `ListCrossingError::JsonOrdering` refuses the four
/// ordering OPERATORS for, one clause over.
#[cfg(all(feature = "sqlite", feature = "mysql"))]
#[test]
fn the_json_dialects_refuse_a_column_stored_collection() {
  let terms = [
    OrderTerm::array(TAGS, FieldName::new("tags"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ];

  assert_eq!(
    SqlOrder::<sqlx::Sqlite>::new(&terms).map(|order| order.terms().len()),
    Err(SqlOrderError::CollectionSemantics(TAGS))
  );
  assert_eq!(
    SqlOrder::<sqlx::MySql>::new(&terms).map(|order| order.terms().len()),
    Err(SqlOrderError::CollectionSemantics(TAGS))
  );
}

/// A collection kept in a TABLE OF ITS OWN is refused by every dialect, PostgreSQL included — the
/// verdict is the TERM's, so the pushable row above is about the storage form rather than about the
/// dialect.
///
/// Mutation: giving `TermSubject::Edge` the array's verdict makes PostgreSQL render
/// `ORDER BY "tags"` against a row that has no such column — valid SQL, a query error one lifecycle
/// later.
#[cfg(all(feature = "sqlite", feature = "postgres", feature = "mysql"))]
#[test]
fn every_dialect_refuses_an_edge_stored_collection() {
  let terms = [
    OrderTerm::edge(TAGS, FieldName::new("tags"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ];

  for refusal in [
    SqlOrder::<sqlx::Postgres>::new(&terms).map(|order| order.terms().len()),
    SqlOrder::<sqlx::Sqlite>::new(&terms).map(|order| order.terms().len()),
    SqlOrder::<sqlx::MySql>::new(&terms).map(|order| order.terms().len()),
  ] {
    assert_eq!(refusal, Err(SqlOrderError::CollectionTable(TAGS)));
  }
}

/// The refusals are the FRAME's, which is what makes a capability row load-bearing rather than
/// decorative: this constructor reads `partition`, so a row that lied would redden here instead of
/// rendering a statement ordered by something the client did not write.
///
/// `Placeless` answers `Divergent` about collections and cannot place a `NULL`, and each of its two
/// answers arrives as its own sentence.
#[test]
fn the_constructor_reports_whichever_capability_row_refused() {
  let collection = [
    OrderTerm::array(TAGS, FieldName::new("tags"), OrderDirection::Asc),
    OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
  ];

  assert_eq!(
    SqlOrder::<Placeless>::new(&collection).map(|order| order.terms().len()),
    Err(SqlOrderError::CollectionSemantics(TAGS))
  );
  assert_eq!(
    SqlOrder::<Placeless>::new(&optional()).map(|order| order.terms().len()),
    Err(SqlOrderError::NullPosition(TITLE)),
    "the nullability verdict is the same one the hand-written check used to give"
  );
}

/// **The ORDER BY over a term whose column spans SEVERAL** — the framework's own instant, at
/// `at_secs` and `at_nanos` beneath one field.
///
/// One term, one identity, one cursor slot; two `ORDER BY` entries. The direction and the `NULL`
/// position are stated on BOTH, because they are one subject read left to right rather than two
/// terms a client wrote — and a backward walk therefore inverts the whole pair, which is what makes
/// the reversed page the same order read from the far end.
mod spanning {
  use super::{ID, ROW, SqlOrder};
  use crate::{
    FieldName, OrderDirection, OrderTerm, TermName, Walk,
    comparison::{
      At,
      sql::{NullOrder, QueryBuilder, SelectClause, TermColumns},
    },
    query::OrderCapability,
  };

  /// The identity of the instant's own field.
  const AT: &TermName = TermName::new("at");

  /// `at ASC, id ASC` where `at` is the framework's instant: TWO columns beneath the first term.
  fn instant(direction: OrderDirection) -> [OrderTerm; 2] {
    [
      OrderTerm::spanning(
        AT,
        FieldName::new("at"),
        <crate::Timestamp as crate::ColumnKind>::SEGMENTS,
        <crate::Timestamp as crate::ColumnKind>::ORDER,
        direction,
      ),
      OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
    ]
  }

  fn ordered<Db>(terms: &[OrderTerm], walk: Walk) -> String
  where
    Db: sqlx::Database + NullOrder + OrderCapability + crate::Backend<Buffer: core::fmt::Display>,
  {
    SqlOrder::<Db>::new(terms)
      .expect("this order is renderable for this dialect")
      .push_order_by_with(
        QueryBuilder::<SelectClause, Db>::select()
          .push_field("*")
          .from("t"),
        walk,
        At::new(&ROW),
        &TermColumns,
      )
      .finalize()
      .into_string()
  }

  /// The width is the TYPE's, so the entry count is too: two for the instant and one for the tail.
  #[test]
  fn a_composite_term_is_two_columns_wide() {
    assert_eq!(instant(OrderDirection::Asc)[0].width(), 2);
    assert_eq!(instant(OrderDirection::Asc)[1].width(), 1);
  }

  #[cfg(feature = "sqlite")]
  #[test]
  fn an_instant_orders_by_both_of_its_columns() {
    assert_eq!(
      ordered::<sqlx::Sqlite>(&instant(OrderDirection::Asc), Walk::Forward),
      "SELECT * FROM t ORDER BY \"at_secs\" ASC, \"at_nanos\" ASC, \"id\" ASC"
    );
    assert_eq!(
      ordered::<sqlx::Sqlite>(&instant(OrderDirection::Desc), Walk::Forward),
      "SELECT * FROM t ORDER BY \"at_secs\" DESC, \"at_nanos\" DESC, \"id\" ASC"
    );
  }

  /// A backward walk inverts EVERY entry of the subject. Inverting one half and not the other is
  /// not the reverse of any order — it is a sequence no forward walk produces — so the pair moving
  /// together is the property the re-reversed page rests on.
  #[cfg(feature = "sqlite")]
  #[test]
  fn a_backward_walk_inverts_the_whole_subject() {
    assert_eq!(
      ordered::<sqlx::Sqlite>(&instant(OrderDirection::Asc), Walk::Backward),
      "SELECT * FROM t ORDER BY \"at_secs\" DESC, \"at_nanos\" DESC, \"id\" DESC"
    );
  }

  /// Postgres states the `NULL` position on every entry it renders, and a `NOT NULL` term states
  /// none — so a composite of `NOT NULL` columns is the same two entries there as anywhere.
  #[cfg(feature = "postgres")]
  #[test]
  fn the_postgres_entries_are_the_same_two() {
    assert_eq!(
      ordered::<sqlx::Postgres>(&instant(OrderDirection::Asc), Walk::Forward),
      "SELECT * FROM t ORDER BY \"at_secs\" ASC, \"at_nanos\" ASC, \"id\" ASC"
    );
  }

  #[cfg(feature = "mysql")]
  #[test]
  fn the_mysql_entries_bracket_with_backticks() {
    assert_eq!(
      ordered::<sqlx::MySql>(&instant(OrderDirection::Desc), Walk::Forward),
      "SELECT * FROM t ORDER BY `at_secs` DESC, `at_nanos` DESC, `id` ASC"
    );
  }
}