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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! The keyset predicate: [`SqlKeyset`], the `WHERE` half of a page.
//!
//! # The general per-column expansion
//!
//! ```text
//! order   a ASC, b DESC, id ASC        cursor   (x, y, z)
//!
//! "a" > ? OR ("a" = ? AND ("b" < ? OR ("b" = ? AND "id" > ?)))
//! ```
//!
//! Each comparator follows ITS OWN column's direction — `>` under an ascending term and `<` under a
//! descending one — and each level's tie is broken by the level below it. The key tail at the end is
//! what makes the order total, so the innermost comparison is over a column no two rows share and
//! the boundary between two pages has exactly one place in it.
//!
//! # PG's row-value comparison is NOT this, and is deliberately not built
//!
//! `(a, b, id) > ($1, $2, $3)` is one predicate where this is `2n - 1`, and Postgres plans it
//! straight onto a composite index. It is legal ONLY under UNIFORM direction — a row value has one
//! comparison operator for the whole tuple, so a mixed order cannot be spelled that way at all — and
//! it says nothing about where `NULL` sits. Recorded as an optimization for the era that measures
//! it; the general form above is portable across all three dialects and is what v1 renders.
//!
//! # Nullable columns
//!
//! The framework pins `NULL` BELOW every value — see [`pinned_nulls`](super::pinned_nulls) — and
//! this expansion is the other half of that pin. What falls out is asymmetric and that is the
//! pinning working rather than a special case:
//!
//! | term runs | cursor value | rows strictly after it |
//! |---|---|---|
//! | ascending | a value | `"a" > ?` — and `NULL` is EXCLUDED for free, since `NULL > ?` is unknown, which is right because a `NULL` sorts before it |
//! | ascending | `NULL` | `"a" IS NOT NULL` — every value is above every `NULL` |
//! | descending | a value | `"a" < ? OR "a" IS NULL` — the `NULL`s trail a descending term, so they are after it |
//! | descending | `NULL` | NOTHING. The `NULL`s are the last group, so no row is after one |
//!
//! The last row is why a disjunct can be absent. `A OR false` IS `A`, so the arm contributes
//! nothing rather than a constant — and the tie group below it still renders, which is what keeps a
//! page resuming inside a run of `NULL`s.
//!
//! # It is MEASURED against real engines, because the failure renders perfectly well-formed SQL
//!
//! A keyset that skips or repeats a row is valid SQL that answers without an error, so a
//! differential over the rendered text cannot see it and the tests beside this file deliberately do
//! not try. What was put to the engines instead is the whole WALK: twelve rows carrying `NULL`s in
//! the sort column, ties inside an `a` group, ties inside a `(a, b)` pair so that only the key tail
//! separates two rows — paged two at a time, forwards and backwards, against the full ordered scan.
//!
//! Exact on all four, every row once and in the scan's own sequence: SQLite 3.51.0, PostgreSQL
//! 16.14 and 17.10, MySQL 8.4.11. The backward scan came back the exact reverse of the forward one,
//! which is the property [`Walk`] rests on.
//!
//! Three mutations were put to the same walk, each leaving the other half of the page right. Every
//! one of them answered without an error and lost rows:
//!
//! | mutation | forward | backward |
//! |---|---|---|
//! | one comparator ignores its column's direction | 8 of 12 rows | 9 of 12, two of them TWICE |
//! | the trailing-`NULL` arm dropped from a descending term | exact | 8 of 12 |
//! | the dialect's own `NULL` position instead of the pinned one | 8 of 12 | 4 of 12 |
//!
//! The second row is the one worth reading twice: the defect is INVISIBLE on the forward walk of
//! the same order and costs four rows on the backward one, which is what a test over one polarity
//! would have missed.
//!
//! # A COLLECTION boundary rides the same expansion, and was put to the same walk
//!
//! A page over an array-stored collection is one more term in the general form: `"tags" > $1` where
//! `$1` is the whole boundary list, bound as ONE array parameter through
//! [`Carrier`](super::Carrier)'s `Vec<E>` row. Nothing in this expansion is collection-shaped —
//! which is the property worth stating, since the alternative was a second lowering that could
//! disagree with the first.
//!
//! Measured on `PostgreSQL 14.23 (Homebrew) on aarch64-apple-darwin25.4.0`, `text[]` beside a
//! `bigint` key tail over eight rows carrying the empty array twice, an equal list twice and a
//! prefix pair, paged two at a time against the full ordered scan:
//!
//! | walk | result |
//! |---|---|
//! | `tags ASC, id ASC` forward and backward | EXACT — every row once, in the scan's own sequence |
//! | `tags DESC, id DESC` forward and backward | EXACT |
//! | a boundary at the EMPTY array | every row with any element follows it, and no other |
//! | two rows holding an equal list | separated by the key tail alone |
//!
//! …and run again against a database whose collation is `en_US.UTF-8`, where PostgreSQL's element
//! order is NOT byte order: exact on all four there too, because the ordering and the boundary
//! comparison are both the engine's and resolve one collation. The walk is in `query::order`'s own
//! note.
//!
//! Two mutations, run on the same live walk:
//!
//! | mutation | result |
//! |---|---|
//! | the comparator ignores its column's direction | 3 of 8 rows, one of them TWICE, on every polarity |
//! | the decoded boundary loses its last element — a strictly LESSER position under the pin | caught one step earlier, at the round trip: the decoded cursor is not the minted one |

use core::{fmt::Display, marker::PhantomData};

use super::{Carrier, NullOrder, SqlConjunction, SqlOrder, push_column};
use crate::{
  Cursor, CursorError, OrderDirection, OrderTerm, Walk,
  comparison::{At, Backend, ComplexComparison},
};

/// What SHAPE a term's subject takes — the one thing a position has to know BEFORE any of it is
/// written.
///
/// A unit enum rather than the `bool` that stood here: what *true* meant was two facts at once —
/// *this rides the SELECT list* and *this needs a pair of parentheses* — and a call site reading a
/// bare `true` said neither. Each variant names the shape it IS, and both facts follow from the
/// shape rather than being carried beside it.
///
/// # The two facts came APART, and [`Companion`](Self::Companion) is where
///
/// They coincided while every subject the row could not hold was an EXPRESSION. A `sortable`
/// collection's companion column is the case that separates them: `__ig_<field>_sort__` is a bare
/// column of the ordered table — nothing wraps a name — and it is none of the ROW's,
/// [`SqlQuery::COLUMNS`](crate::query::sql::SqlQuery::COLUMNS) being the record's own fields, so its
/// value has to ride the SELECT list exactly as a sub-select's does.
///
/// So the vocabulary is the two facts' PRODUCT and every inhabited combination has a name. The
/// fourth is not a shape anything can be: a subject the row already carries is one of the names the
/// `SELECT` list wrote, and a name needs no parentheses.
///
/// | | already on the row | rides the SELECT list |
/// |---|---|---|
/// | **wrapped in nothing** | [`Column`](Self::Column) | [`Companion`](Self::Companion) |
/// | **wrapped in parentheses** | — | [`SubSelect`](Self::SubSelect) |
///
/// # It is asked AHEAD of the write, and that is measured rather than stylistic
///
/// The SELECT-list projection decides whether to emit `<subject> AS "__ig_ord<n>__"` AT ALL, and it
/// has to decide before the first byte: a field opened and then abandoned is a comma and an alias
/// with no expression between them. So the shape cannot be a thing discovered while writing — it is a
/// question with an answer, asked first, and [`SubjectSlot`] is what the answer is then spent as.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubjectShape {
  /// The subject is a COLUMN of the row being ordered — its value is already on the returned row,
  /// under the name the `SELECT` list gave it, and nothing wraps it.
  Column,
  /// The subject is a COLUMN OF THE ORDERED TABLE THAT THE ROW DOES NOT CARRY — the `sortable`
  /// word's companion, which is [`TermSubject::Shadow`](crate::TermSubject::Shadow)'s own shape.
  ///
  /// A bare name, so nothing wraps it; not one of the row's fields, so the page projects it under a
  /// generated alias and reads the value back off the driver's row. That is what makes the boundary
  /// a page resumes at the very bytes this statement's `ORDER BY` sorted the row by.
  Companion,
  /// The subject is a whole SUB-SELECT — a correlated scalar statement, whose value has no column on
  /// the returned row and whose parentheses are part of what a subquery IS.
  SubSelect,
}

/// The single-shot channel one subject's BODY is written into, with the shape it was opened for
/// already decided.
///
/// # It is the ONE place the wrapping parentheses are spelled
///
/// A [`SubSelect`](SubjectShape::SubSelect) slot writes `(` before the body and `)` after it, and no
/// other line in this crate writes that pair for a subject. The reason is a measurement rather than
/// tidiness: a subject reaching the resume predicate with no pair is not an error but the START of a
/// scalar subquery, so the keyset's own outer bracket is absorbed and SQLite 3.51.0 and MySQL 8.4.11
/// answer the whole page with an EMPTY SET and no error at all — where PostgreSQL 17.10 refuses.
/// A pair each of the three positions wrote for itself was a pair any one of them could omit; a pair
/// written here is a pair none of them can, and a provider that wrote its own would have to be the
/// thing that stopped compiling.
///
/// # Spent exactly once, by construction
///
/// [`write`](Self::write) takes `self` BY VALUE and this type is neither [`Copy`] nor [`Clone`], so
/// a second write is a use of a moved value and a subject that renders twice is not a mistake anyone
/// can make. The buffer is borrowed for exactly as long as the slot, so nothing reaches past it
/// either.
pub struct SubjectSlot<'a, Db: sqlx::Database> {
  qb: &'a mut sqlx::QueryBuilder<Db>,
  shape: SubjectShape,
}

impl<'a, Db: sqlx::Database> SubjectSlot<'a, Db> {
  /// Open a slot over `qb` for a subject of `shape`.
  ///
  /// Crate-internal, because the three POSITIONS are the parties that ask
  /// [`OrderSubjects::shape`] and are therefore the only ones that can open a slot agreeing with
  /// the answer. A provider receives one; it never makes one.
  #[inline]
  pub(crate) const fn new(qb: &'a mut sqlx::QueryBuilder<Db>, shape: SubjectShape) -> Self {
    Self { qb, shape }
  }

  /// Write the subject's BODY, wrapped as this slot's shape requires.
  ///
  /// `body` receives the raw buffer, so the subject is several pushes and its BINDS are live — which
  /// is the whole reason this renders rather than returning a string, a placeholder being the one
  /// thing text cannot carry.
  ///
  /// # It is spent, and the compiler is where that is said
  ///
  /// A provider handed a slot writes once. Writing twice does not compile:
  ///
  /// ```compile_fail,E0382
  /// use ingraph::{
  ///   OrderTerm,
  ///   comparison::{At, sql::{OrderSubjects, SubjectSlot}},
  /// };
  ///
  /// struct Twice;
  ///
  /// impl<Db: sqlx::Database> OrderSubjects<Db> for Twice {
  ///   fn push_subject(
  ///     &self,
  ///     slot: SubjectSlot<'_, Db>,
  ///     _: At<'_>,
  ///     _: &[OrderTerm],
  ///     _: usize,
  ///   ) {
  ///     slot.write(|qb| { qb.push("1"); });
  ///     slot.write(|qb| { qb.push("2"); });
  ///   }
  /// }
  /// ```
  ///
  /// Its twin must COMPILE, and shares the imports and the call shape with it — stable rustdoc runs
  /// a `compile_fail` block just far enough to see it fail and never checks why, so a pair is what
  /// keeps the negative one honest. Neither names a dialect: a slot is spent once whichever database
  /// is under it, and the pair has to build on every lane that has this module.
  ///
  /// ```
  /// use ingraph::{
  ///   OrderTerm,
  ///   comparison::{At, sql::{OrderSubjects, SubjectSlot}},
  /// };
  ///
  /// struct Once;
  ///
  /// impl<Db: sqlx::Database> OrderSubjects<Db> for Once {
  ///   fn push_subject(
  ///     &self,
  ///     slot: SubjectSlot<'_, Db>,
  ///     _: At<'_>,
  ///     _: &[OrderTerm],
  ///     _: usize,
  ///   ) {
  ///     slot.write(|qb| { qb.push("1"); });
  ///   }
  /// }
  /// ```
  #[inline]
  pub fn write(self, body: impl FnOnce(&mut sqlx::QueryBuilder<Db>)) {
    match self.shape {
      // A COMPANION is a bare name too. What makes it a shape of its own is where its VALUE comes
      // back from, which is the projection's question and not this one — so the two share an arm
      // here and part at [`sorts`](crate::query::sql::find).
      SubjectShape::Column | SubjectShape::Companion => body(self.qb),
      SubjectShape::SubSelect => {
        self.qb.push("(");
        body(self.qb);
        self.qb.push(")");
      }
    }
  }
}

/// What each of an order's terms COMPARES — the left-hand side of every arm the expansion writes.
///
/// A term's subject is its COLUMN in every order this framework renders today, and [`TermColumns`]
/// is that answer; the seam is here because it is not the only one a term can have. An ordering
/// term over a to-one target lowers as a correlated scalar SUBQUERY, which is an expression rather
/// than a name — and it has to be the same expression in the `ORDER BY` and in every arm of this
/// predicate, or the page skips or repeats exactly the rows at a boundary, which is the property
/// [`SqlOrder`] exists to hold.
///
/// # It renders rather than returns, and what it renders is a BODY
///
/// The buffer arrives open, as it does at
/// [`QueryBuilder::order_by_with`](super::QueryBuilder::order_by_with), and for the same two
/// reasons: a subquery is several pushes, and it carries BINDS, which are the one thing a returned
/// string cannot carry. It arrives inside a [`SubjectSlot`], and the contract is one sentence: an
/// implementation writes the subject's BODY, never the brackets around it. A sub-select's
/// parentheses are the slot's, at every position that spends one — see [`SubjectSlot`] for the
/// measurement that put them there, and [`SqlKeyset::apply`](crate::ComplexComparison::apply) for
/// what this predicate's own brackets are and are not.
///
/// # The whole order arrives, not one term
///
/// The expansion walks the terms by index, and `level` is that index; `terms` is the order it
/// indexes, so an implementation that answers for some levels and defers the rest has both halves
/// in hand. `level` is always in range — the caller is the walk itself.
pub trait OrderSubjects<Db: sqlx::Database> {
  /// Write the BODY of `terms[level]`'s subject into `slot`, the row it constrains being `at`.
  ///
  /// The body and nothing else: whatever wraps it is decided by the shape this implementation
  /// already declared, and written by the slot.
  ///
  /// ONE expression, whatever the term's column spans. A term over a composite column compares its
  /// columns as a ROW VALUE — `("at_secs", "at_nanos")` — because a comparison against the cursor's
  /// value is one comparison: the operand is one value binding several placeholders, and only `eq`
  /// has a conjunctive spelling that means the same thing. What the `ORDER BY` needs instead is one
  /// entry per column, and that is [`push_entry`](Self::push_entry).
  fn push_subject(&self, slot: SubjectSlot<'_, Db>, at: At<'_>, terms: &[OrderTerm], level: usize);

  /// Write the body of the `leaf`-th ORDER BY entry of `terms[level]`'s subject.
  ///
  /// # It DEFAULTS to the whole subject, and that is the one-column answer
  ///
  /// A term names one column unless its type says otherwise — [`OrderTerm::width`] is the count —
  /// so for every subject that is not a composite column there is exactly one entry and it is the
  /// subject itself. That is why this defaults rather than being a second obligation: an
  /// implementation whose subjects are EXPRESSIONS states nothing here, and a correlated sub-select
  /// keeps arriving at exactly one `ORDER BY` position.
  ///
  /// # Why the ordering is per COLUMN where the predicate is per TERM
  ///
  /// `ORDER BY ("at_secs", "at_nanos") ASC` is not a spelling any of the three dialects has, and the
  /// order it would name is the one `ORDER BY "at_secs" ASC, "at_nanos" ASC` renders — the same
  /// lexicographic sequence the keyset's row value compares. So the two positions render one order
  /// in the two syntaxes each admits, and the direction and the `NULL` position are stated on every
  /// entry, which is what keeps a backward walk inverting the whole subject rather than half of it.
  fn push_entry(
    &self,
    slot: SubjectSlot<'_, Db>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
    leaf: usize,
  ) {
    let _ = leaf;
    self.push_subject(slot, at, terms, level);
  }

  /// Write the body of the `leaf`-th VALUE column of `terms[level]`'s subject — the numbering
  /// [`OrderTerm::value_width`] counts, which is not [`OrderTerm::width`]'s.
  ///
  /// # It is the PRESENCE question, where [`push_entry`](Self::push_entry) is the ORDER's
  ///
  /// An `ORDER BY` entry names a column the rows are SORTED BY, and a derived index leaf is one of
  /// those. A null test asks whether the term's VALUE is at this row at all, and a derived leaf is
  /// not part of any value — `at_nanos IS NULL` is true for a stored instant with no representable
  /// position. So the two positions read one subject through two numberings, which is the law
  /// [`ColumnShape`](crate::ColumnShape) states: *a derived leaf serves the semantic order only;
  /// every structural judgment walks value leaves only*.
  ///
  /// # It DEFAULTS to the whole subject, exactly as its sibling does
  ///
  /// A subject that is an EXPRESSION — a correlated sub-select, a companion column — is one column
  /// and that column is its value, so the default is the one-column answer and a party whose
  /// subjects are all expressions states nothing here. Only a party rendering a composite's own
  /// COLUMNS has two numberings to tell apart, and [`TermColumns`] is that party.
  fn push_value_entry(
    &self,
    slot: SubjectSlot<'_, Db>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
    leaf: usize,
  ) {
    let _ = leaf;
    self.push_subject(slot, at, terms, level);
  }

  /// What shape `terms[level]`'s subject takes — read off the TERM's own
  /// [`subject`](OrderTerm::subject) unless an implementation says otherwise, which is why it
  /// defaults.
  ///
  /// It is answered HERE, beside the rendering, because the two are one fact: how a subject is
  /// WRITTEN and where its value COMES BACK FROM are decided together. Two parties answering them
  /// separately is a page whose cursor reads a column that was never selected.
  ///
  /// The two things that follow from the answer are the two a position needs. A
  /// [`SubSelect`](SubjectShape::SubSelect) has no column on the returned row, so the query layer
  /// projects it onto the page's own `SELECT` list under a generated alias and decodes it back off
  /// the driver's row — see [`SqlOrdering::value`](crate::query::sql::SqlOrdering::value), the other
  /// end of it — and it is wrapped in the parentheses a subquery IS. A
  /// [`Companion`](SubjectShape::Companion) is projected the same way and wrapped in nothing: it is
  /// a real column of the ordered TABLE and none of the ROW's. A
  /// [`Column`](SubjectShape::Column) needs neither.
  ///
  /// # The default READS THE TERM rather than answering [`Column`](SubjectShape::Column), and that
  /// is one authority
  ///
  /// Which storage form answered a collection is minted where the declaration is read and travels
  /// ON the term — [`TermSubject`](crate::TermSubject) — so a party re-deciding it here would be a
  /// second opinion, free to disagree with the `ORDER BY` already rendered from that same term. The
  /// default therefore projects the term's own answer: the ordinary order stays free of this
  /// ([`TermColumns`] states nothing, and neither does any party whose subjects are all names), and
  /// a companion term is projected wherever one is minted.
  ///
  /// An implementation that OVERRIDES this owns both halves, which is the nested order's case — it
  /// answers for the levels it mints and hands the rest back here rather than to a literal.
  fn shape(&self, terms: &[OrderTerm], level: usize) -> SubjectShape {
    match terms[level].subject() {
      crate::TermSubject::Shadow => SubjectShape::Companion,
      // An ABSENT subject is unreachable here rather than answered: an order carrying one is
      // refused whole at `SqlOrder::new`, so no keyset is ever built over it. It takes the column
      // answer with the others because a shape is a rendering fact and this term renders nothing.
      crate::TermSubject::Array
      | crate::TermSubject::Edge
      | crate::TermSubject::Value
      | crate::TermSubject::Absent(_) => SubjectShape::Column,
    }
  }
}

/// Every term's subject is its own COLUMN — the ordinary order, and [`SqlKeyset`]'s default.
///
/// It holds nothing: the terms arrive with the call, and what a column looks like is
/// [`Backend::write_column`](crate::Backend::write_column)'s, which is where the joining and the
/// bracketing live for every leaf in this family.
///
/// # A term whose column spans SEVERAL is still its own columns
///
/// The two readings differ only in how many names come out. The subject is the ROW VALUE of them —
/// which is what a comparison against one cursor slot needs, the slot being one value that binds
/// several placeholders — and each `ORDER BY` entry is one of them. Both walk the term's
/// [`segments`](OrderTerm::segments) under its own [`column`](OrderTerm::column), so a `SELECT` of
/// `at_secs`, a `WHERE` over it and an `ORDER BY` on it are one join rather than three that agree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TermColumns;

impl<Db> OrderSubjects<Db> for TermColumns
where
  Db: sqlx::Database + Backend<Buffer: Display>,
{
  /// # A LEVEL's subject is ONE COLUMN, and that is where an expanded citizen's row value goes
  ///
  /// A term carrying [`OrderTerm::leaf`] names that leaf and nothing else: its width is one, so the
  /// operand beside it binds one placeholder and the bracket a row value needed is not written. The
  /// row-value spelling below is still what a composite term that states no sequence compares, which
  /// is every one but the semantic citizens — so the statement a page renders over
  /// `at: Timestamp` is the same bytes it always was.
  #[inline]
  fn push_subject(&self, slot: SubjectSlot<'_, Db>, at: At<'_>, terms: &[OrderTerm], level: usize) {
    let term = &terms[level];
    let frame = at.frame(term.column());
    slot.write(|qb| match term.leaf() {
      Some(leaf) => push_term_leaf(qb, frame.at(), term, leaf),
      None if term.segments().is_empty() => push_column(qb, frame.at()),
      None => super::push_row_value(qb, frame.at(), term.segments()),
    });
  }

  #[inline]
  fn push_entry(
    &self,
    slot: SubjectSlot<'_, Db>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
    leaf: usize,
  ) {
    let term = &terms[level];
    let frame = at.frame(term.column());
    slot.write(|qb| match term.leaf() {
      // A LEVEL is one entry, and `leaf` is `0` at every call: the caller iterates
      // `OrderTerm::width`, which a level answers `1`. Which column it is, is the TERM's own.
      Some(own) => push_term_leaf(qb, frame.at(), term, own),
      None if term.segments().is_empty() => push_column(qb, frame.at()),
      None => {
        // The walk is called for its WRITE, and the answer is checked beside it: `leaf` is in range
        // by construction, since the caller iterates `OrderTerm::width` and that counts exactly
        // these leaves. A `false` would be an `ORDER BY` entry with nothing in it, which is a syntax
        // error rather than a wrong order — but the one authority for the count and for the names is
        // this walk, so the agreement is asserted rather than assumed.
        let written = super::push_leaf_column(qb, frame.at(), term.segments(), leaf);
        debug_assert!(written, "an ORDER BY entry names a leaf of its own term");
      }
    });
  }

  /// The same walk over the VALUE columns alone, which is a DIFFERENT INDEX into the same tree: a
  /// term over `MediaTimestamp` has four leaves and three value leaves, and its second value leaf is
  /// not its second leaf.
  ///
  /// A LEVEL has ONE column and it is both numberings' only member, so the two questions meet at the
  /// same name — which is what makes an expanded citizen's null arms be about the level's own column
  /// rather than about the whole instant's presence.
  #[inline]
  fn push_value_entry(
    &self,
    slot: SubjectSlot<'_, Db>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
    leaf: usize,
  ) {
    let term = &terms[level];
    let frame = at.frame(term.column());
    slot.write(|qb| match term.leaf() {
      Some(own) => push_term_leaf(qb, frame.at(), term, own),
      None if term.segments().is_empty() => push_column(qb, frame.at()),
      None => {
        let written = super::push_value_leaf_column(qb, frame.at(), term.segments(), leaf);
        debug_assert!(written, "a null test names a value leaf of its own term");
      }
    });
  }
}

/// The ONE column a LEVEL names — its own leaf of its own term's segment tree.
///
/// Written once and spent at all three of [`TermColumns`]' positions, which is the property that
/// matters: an `ORDER BY` entry, a keyset arm's left-hand side and that arm's null test are the same
/// column of the same level, joined by the same walk. Two of them spelling it separately is exactly
/// the drift [`Backend::write_column`](crate::Backend::write_column)'s single join exists to
/// prevent, one grain finer.
fn push_term_leaf<Db>(qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, term: &OrderTerm, leaf: usize)
where
  Db: sqlx::Database + Backend<Buffer: Display>,
{
  let written = super::push_leaf_column(qb, at, term.segments(), leaf);
  debug_assert!(written, "an order level names a leaf of its own term");
}

/// A borrowed party answers exactly as the party does, so ONE value can subject both renderings of
/// a page.
///
/// The `ORDER BY` and this predicate have to compare the same expression at every term or the page
/// skips or repeats exactly the rows at a boundary — and [`SqlKeyset`] holds its `S` BY VALUE, being
/// a value itself. Without this the engine would need two subjects: one moved in here and one kept
/// for the ordering, which is two things free to drift and the failure this seam exists to close.
/// With it, the engine builds one and hands `&S` to both.
impl<Db: sqlx::Database, S: OrderSubjects<Db> + ?Sized> OrderSubjects<Db> for &S {
  #[inline]
  fn push_subject(&self, slot: SubjectSlot<'_, Db>, at: At<'_>, terms: &[OrderTerm], level: usize) {
    S::push_subject(self, slot, at, terms, level);
  }

  /// Forwarded rather than left to the default, which would be the borrow's own `push_subject` and
  /// therefore the whole subject at every entry — a composite term's `ORDER BY` would name its row
  /// value once instead of its columns in sequence, and a borrowed party would not render what the
  /// party does.
  #[inline]
  fn push_entry(
    &self,
    slot: SubjectSlot<'_, Db>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
    leaf: usize,
  ) {
    S::push_entry(self, slot, at, terms, level, leaf);
  }

  /// Forwarded for [`push_entry`](Self::push_entry)'s reason, one numbering over: the default is the
  /// borrow's own `push_subject`, so a borrowed party would render a composite term's whole row
  /// value where the party renders one value leaf — and a null test would be the unportable
  /// `(a, b) IS NULL`.
  #[inline]
  fn push_value_entry(
    &self,
    slot: SubjectSlot<'_, Db>,
    at: At<'_>,
    terms: &[OrderTerm],
    level: usize,
    leaf: usize,
  ) {
    S::push_value_entry(self, slot, at, terms, level, leaf);
  }

  #[inline]
  fn shape(&self, terms: &[OrderTerm], level: usize) -> SubjectShape {
    S::shape(self, terms, level)
  }
}

/// One row's position in a written order, as the predicate that finds the rows after it.
///
/// # It is CONSTRUCTED from a checked order and a checked cursor, and there is no other way in
///
/// [`resume`](Self::resume) takes a [`SqlOrder`] — which has already been refused if the dialect
/// cannot place `NULL` — and a [`Cursor`], which is checked against that order's signature, width
/// and nullability there and then. So every refusal this page can make happens BEFORE the type
/// exists, and the lowering below cannot fail: a mismatched cursor is not a predicate that renders
/// wrongly, it is a value nobody is holding.
///
/// # One conjunct, whatever the order holds
///
/// The expansion is one parenthesised disjunction, so it joins a `WHERE` beside a filter's own
/// conjuncts through the accumulator every comparison threads — a page is *the client's filter AND
/// this*, and nothing here has to know what the filter was.
///
/// # `S` is what each term COMPARES, and its default is the ordinary answer
///
/// `SqlKeyset<'_, V, Db>` is the column keyset and names nothing extra to be one, because
/// [`TermColumns`] is the default. The parameter is where an order whose term is an EXPRESSION
/// enters — see [`OrderSubjects`] — and it is a type rather than a runtime branch so that the
/// column expansion is the same code and the same bytes it was before the seam existed.
pub struct SqlKeyset<'a, V, Db, S = TermColumns> {
  terms: &'a [OrderTerm],
  values: &'a [Option<V>],
  walk: Walk,
  subjects: S,
  // `fn() -> Db` rather than a bare parameter, so the dialect marker contributes no auto-trait or
  // variance obligation — this family's convention.
  db: PhantomData<fn() -> Db>,
}

impl<'a, V, Db: NullOrder> SqlKeyset<'a, V, Db> {
  /// The predicate that resumes `order` at `cursor`, running `walk`'s way, every term comparing its
  /// own column.
  ///
  /// `walk` is an INPUT rather than something read off the cursor: one cursor pages both ways, which
  /// is the whole of what relay's `after` and `before` are, and which way this call runs is the
  /// request's rather than the cursor's. Re-reversing the rows a backward walk returns is the
  /// engine's — this layer inverts the comparators and the ordering, and stops there.
  ///
  /// # Errors
  ///
  /// Whatever [`Cursor::resume`] refuses: a cursor minted under another order, a tuple that is not
  /// as wide as the order, or a `NULL` at a `NOT NULL` term.
  pub fn resume(
    order: SqlOrder<'a, Db>,
    cursor: &'a Cursor<V>,
    walk: Walk,
  ) -> Result<Self, CursorError> {
    Self::resume_with(order, cursor, walk, TermColumns)
  }
}

impl<'a, V, Db: NullOrder, S> SqlKeyset<'a, V, Db, S> {
  /// [`resume`](SqlKeyset::resume) with what each term compares written by `subjects`.
  ///
  /// # Errors
  ///
  /// [`resume`](SqlKeyset::resume)'s, which are the cursor's and are raised before `subjects` is
  /// asked for anything.
  pub fn resume_with(
    order: SqlOrder<'a, Db>,
    cursor: &'a Cursor<V>,
    walk: Walk,
    subjects: S,
  ) -> Result<Self, CursorError> {
    Ok(Self {
      terms: order.terms(),
      values: cursor.resume(order.terms())?,
      walk,
      subjects,
      db: PhantomData,
    })
  }

  /// The order this predicate resumes.
  #[inline]
  #[must_use]
  pub const fn terms(&self) -> &'a [OrderTerm] {
    self.terms
  }

  /// The boundary row's ordering tuple.
  #[inline]
  #[must_use]
  pub const fn values(&self) -> &'a [Option<V>] {
    self.values
  }

  /// Which way this page runs.
  #[inline]
  #[must_use]
  pub const fn walk(&self) -> Walk {
    self.walk
  }

  /// Which way term `at` RUNS on this walk.
  #[inline]
  fn direction(&self, at: usize) -> OrderDirection {
    self.walk.direction(self.terms[at].direction())
  }

  /// Whether any row can sort strictly after term `at`'s cursor value.
  ///
  /// False in exactly one case: a `NULL` under a descending term. The framework pins `NULL` below
  /// every value, so a descending term's `NULL`s are its last group and no row is after one.
  #[inline]
  fn has_arm(&self, at: usize) -> bool {
    self.values[at].is_some() || !self.direction(at).is_descending()
  }

  /// The LAST term whose arm can admit a row, or [`None`] where none can.
  ///
  /// Terms past it contribute nothing: their own arm is empty and there is no level below to break
  /// a tie into, so `eq AND false` is false. Finding the index up front is what lets the render
  /// walk forwards and still know where to stop, without building a fragment it might discard.
  ///
  /// [`None`] is unreachable through the framework's own orders — the key tail's columns are
  /// `NOT NULL`, so the innermost arm always admits — and it is answered rather than asserted,
  /// because the terms are a caller's slice.
  #[inline]
  fn last_arm(&self) -> Option<usize> {
    (0..self.terms.len()).rfind(|at| self.has_arm(*at))
  }
}

/// ONE impl for every dialect, and both of the ways a lowering can differ are uniform here.
///
/// - **The SQL is identical.** `>`, `<`, `=`, `IS NULL`, `IS NOT NULL`, `AND`, `OR` and brackets are
///   ANSI and spelled alike in SQLite, Postgres and MySQL. Everything per-dialect about a page is in
///   the `ORDER BY`, which is [`SqlOrder`]'s.
/// - **The bounds are identical.** `V: Carrier<Db>` is what the OPERANDS cost, exactly as it is for
///   [`SqlScalarComparison`](super::SqlScalarComparison) and [`SqlKeyIn`](super::SqlKeyIn), and
///   `S: OrderSubjects<Db>` is what the left-hand sides cost. Neither names a dialect.
///
/// What a rendered COLUMN costs — [`Backend<Buffer: Display>`](crate::Backend::Buffer) — is named by
/// neither, and that is [`OrderSubjects`] rather than a relaxation: whoever writes the subjects asks
/// for what writing them costs, so [`TermColumns`] carries that bound and a subject rendered some
/// other way is not made to. The default instantiation therefore requires exactly what it required
/// before.
///
/// It refuses nothing, so [`Backend::Error`](crate::Backend::Error) goes unnamed in the bounds: what
/// this predicate could have refused was refused at [`SqlKeyset::resume`], where no statement had
/// been touched.
impl<V, Db, S> ComplexComparison<Db> for SqlKeyset<'_, V, Db, S>
where
  Db: sqlx::Database + NullOrder + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>>,
  V: Carrier<Db>,
  S: OrderSubjects<Db>,
{
  /// One, whatever the order holds: the expansion is a single parenthesised disjunction, and a
  /// cursor no row can be after renders `1 = 0`, which is also one.
  #[inline]
  fn conjuncts(&self) -> usize {
    1
  }

  /// # The brackets
  ///
  /// Each level opens two — one around the whole tie group and one around the level nested inside
  /// it — because `AND` binds tighter than `OR`: without the inner pair,
  /// `a = ? AND b > ? OR (…)` reads as `(a = ? AND b > ?) OR (…)`, which admits rows whose `a` is
  /// not the cursor's at all. The innermost arm is bracketed too, and that is not redundant: a
  /// descending nullable arm IS a disjunction, so the pair is load-bearing exactly where it looks
  /// least so, and rendering it always is what keeps that from being a case someone has to spot.
  ///
  /// # …and one OUTER pair, which is the same argument one level further out
  ///
  /// The expansion is a DISJUNCTION at its top level, and this comparison is one conjunct of a
  /// `WHERE` that may hold others. Unbracketed, `title = ? AND a > ? OR (…)` reads as
  /// `(title = ? AND a > ?) OR (…)` — so a page beside a filter returns rows the FILTER excluded,
  /// which is a wrong answer with no error anywhere and is invisible on a page with no filter.
  ///
  /// It was invisible here too until a filter and a page were rendered into one statement for the
  /// first time: every test over this kind rendered the predicate alone, where the missing pair
  /// changes nothing. The pair is now always rendered — a single-term order gets `("id" > ?)` and
  /// the degenerate `1 = 0` needs none, being one atom — because a bracket that is only emitted
  /// when something else is present is a bracket decided by a caller this comparison cannot see.
  ///
  /// # None of them is a SUBJECT's
  ///
  /// Every pair above brackets a disjunction or a tie group, and none of them wraps a subject. A
  /// subject that needs one of its own — a scalar subquery, whose parentheses are part of what a
  /// subquery IS — gets it from the [`SubjectSlot`] this predicate opens at
  /// [`push_subject`](Self::push_subject), which is the one place in the crate that spells the pair.
  /// Measured on the three engines: a subject reaching this predicate with no pair at all is a
  /// SYNTAX ERROR on PostgreSQL 17.10 and, on SQLite 3.51.0 and MySQL 8.4.11, an empty answer with
  /// no error at all — the outer pair above turns into the start of a scalar subquery and the whole
  /// page silently comes back empty. That measurement is why the pair sits behind a type rather than
  /// in three positions' worth of code that could disagree.
  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    let qb = builder.open();
    let Some(last) = self.last_arm() else {
      // No row is after this cursor under this walk, which is an ANSWER — the page is empty — and
      // the same degeneration `push_in` gives an empty list. One atom, so no pair.
      qb.push("1 = 0");
      return Ok(builder);
    };
    qb.push("(");
    for level in 0..last {
      if self.has_arm(level) {
        self.push_arm(qb, at, level);
        qb.push(" OR ");
      }
      qb.push("(");
      self.push_eq(qb, at, level);
      qb.push(" AND (");
    }
    self.push_arm(qb, at, last);
    for _ in 0..last {
      qb.push("))");
    }
    qb.push(")");
    Ok(builder)
  }
}

impl<V, Db, S> SqlKeyset<'_, V, Db, S>
where
  Db: sqlx::Database + NullOrder,
  V: Carrier<Db>,
  S: OrderSubjects<Db>,
{
  /// What term `level` compares, as this order's subjects spell it.
  ///
  /// A descending nullable arm names it twice and the tie group below once more, so one term's
  /// subject can reach the statement three times — all of them through this call, which is what
  /// keeps a subject carrying operands binding them at every occurrence rather than at the first.
  ///
  /// This position writes no wrapping of its own. It asks the subjects for the term's
  /// [`shape`](super::OrderSubjects::shape), opens a [`SubjectSlot`] for it and hands that over —
  /// and the slot is what writes a sub-select's parentheses, here as at the other two positions.
  /// This is the position that made the arrangement worth having: a missing pair here is not an
  /// error but the start of a scalar subquery, and the page comes back empty.
  fn push_subject(&self, qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, level: usize) {
    let slot = SubjectSlot::new(qb, self.subjects.shape(self.terms, level));
    self.subjects.push_subject(slot, at, self.terms, level);
  }

  /// The cursor's value at `level`, bracketed where the term names several columns.
  ///
  /// A slot is ONE value and binds as many placeholders as its type spans — the comma inside a
  /// composite's binds being [`Carrier`]'s — so what this adds is the pair that makes the right-hand
  /// side a row value beside a left-hand side that already is one. The width comes from the TERM,
  /// which is the same claim the subject was rendered from; a term and a value disagreeing about it
  /// is the two-traits-must-agree failure [`Carrier::push_bind`] states, and it renders SQL the
  /// engine refuses rather than a wrong page.
  fn push_operand(&self, qb: &mut sqlx::QueryBuilder<Db>, level: usize, value: &V) {
    if self.terms[level].width() == 1 {
      value.push_bind(qb);
      return;
    }
    qb.push("(");
    value.push_bind(qb);
    qb.push(")");
  }

  /// `<subject> IS [NOT] NULL` for an ordinary term, and the CONJUNCTION of that over the leaves of
  /// a composite one.
  ///
  /// The row-value spelling is not portable: measured on SQLite 3.51.0, `(a, b) IS NULL` is
  /// *row value misused*. The conjunctive one is what PostgreSQL's own row-value null test MEANS —
  /// true where every field is null — and it is the only reading a carrier can produce anyway, since
  /// a composite binds all of its columns or none.
  ///
  /// A nullable composite IS a state a declaration reaches now, an optional composite having gained
  /// its read face — so this is exercised rather than defensive.
  ///
  /// **THE WALK IS THE VALUE LEAVES (ingraph #454).** It was `0..width`, which includes a DERIVED
  /// leaf where the type has one: `MediaTimestamp`'s `at_nanos` is `NULL` for an instant that is
  /// stored and unplaceable, so this test called such a row absent while the decode and the presence
  /// FILTER both called it present — and a page therefore could not reach it in either direction, it
  /// being neither in the `NULL` group nor after it. The three readers now read one bit,
  /// `ColumnShape::holds_value`, so BOTH derived words are dropped and neither reader is deciding on
  /// nullability: the filter skips them, the decode's `None` test skips them, and this walks
  /// [`OrderTerm::value_width`] through
  /// [`push_value_entry`](super::OrderSubjects::push_value_entry), which is the second numbering
  /// [`SubjectShape`]'s own position-indexing needed. `cursor::order`'s `spanning_nullable` carries
  /// the other half of this.
  ///
  /// The COMPARISON is deliberately not narrowed with it. A row value compared with `<` or `=` here
  /// has to name exactly what the `ORDER BY` sorted by, which is the term's whole width — the two
  /// renderings of one order being what this type exists to keep identical. So one subject is read
  /// through two numberings: the order's, and the value's.
  fn push_null_test(&self, qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, level: usize, not: bool) {
    let test = if not { " IS NOT NULL" } else { " IS NULL" };
    let width = self.terms[level].value_width();
    if width == 0 {
      // A composite with NO value column has nothing that could be absent, which is the answer
      // `Assemble`'s own row gives for one: always present, never `None`. The constants say so
      // rather than the conjunct being dropped, which would have made `IS NULL` mean *every row* —
      // the same standing the presence filter's own walk takes. No shipped type reaches it.
      qb.push(if not { "TRUE" } else { "FALSE" });
      return;
    }
    if width == 1 {
      let slot = SubjectSlot::new(qb, self.subjects.shape(self.terms, level));
      self
        .subjects
        .push_value_entry(slot, at, self.terms, level, 0);
      qb.push(test);
      return;
    }
    qb.push("(");
    for leaf in 0..width {
      if leaf > 0 {
        qb.push(" AND ");
      }
      let slot = SubjectSlot::new(qb, self.subjects.shape(self.terms, level));
      self
        .subjects
        .push_value_entry(slot, at, self.terms, level, leaf);
      qb.push(test);
    }
    qb.push(")");
  }

  /// The rows whose term `level` sorts strictly AFTER the cursor's — the module note's table.
  ///
  /// Only called where [`has_arm`](Self::has_arm) is true, so the fourth row of that table — a
  /// `NULL` under a descending term, which no row is after — cannot arrive.
  fn push_arm(&self, qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, level: usize) {
    let descending = self.direction(level).is_descending();
    let Some(value) = &self.values[level] else {
      // A `NULL` under an ASCENDING term: every value is above every `NULL`, and there is nothing
      // to bind.
      self.push_null_test(qb, at, level, true);
      return;
    };
    self.push_subject(qb, at, level);
    qb.push(if descending { " < " } else { " > " });
    self.push_operand(qb, level, value);
    if descending && self.terms[level].is_nullable() {
      // A descending term trails its `NULL`s, so they are after every value — and `NULL < ?` is
      // unknown rather than true, so they have to be named.
      qb.push(" OR ");
      self.push_null_test(qb, at, level, false);
    }
  }

  /// The rows whose term `level` is EQUAL to the cursor's — the tie the level below breaks.
  ///
  /// `IS NULL` rather than `= NULL` where the value is absent, because SQL's `=` is unknown against
  /// `NULL` and would drop the whole run of `NULL`s the page is resuming inside.
  fn push_eq(&self, qb: &mut sqlx::QueryBuilder<Db>, at: At<'_>, level: usize) {
    match &self.values[level] {
      Some(value) => {
        self.push_subject(qb, at, level);
        qb.push(" = ");
        self.push_operand(qb, level, value);
      }
      None => {
        self.push_null_test(qb, at, level, false);
      }
    }
  }
}

/// The subjects go unprinted and unbounded, as the dialect marker does: what a `Debug` here is read
/// for is which order is being resumed at which values, and requiring the party that renders them to
/// be printable would be a bound on every keyset for the sake of one line of output.
impl<V: core::fmt::Debug, Db, S> core::fmt::Debug for SqlKeyset<'_, V, Db, S> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlKeyset")
      .field("terms", &self.terms)
      .field("values", &self.values)
      .field("walk", &self.walk)
      .finish()
  }
}

/// Written out rather than derived, for the reason every `Db`-parameterised type in this family
/// writes its own: a derive would bound `Db`, which is a marker held as `PhantomData<fn() -> Db>`.
///
/// It asks `S: Clone` where [`Copy`] below asks `S: Copy`, so a subject that is one and not the
/// other still travels. [`TermColumns`] is both, so the column keyset is exactly as `Copy` as it was
/// while its three fields were the whole of it.
impl<V, Db, S: Clone> Clone for SqlKeyset<'_, V, Db, S> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      terms: self.terms,
      values: self.values,
      walk: self.walk,
      subjects: self.subjects.clone(),
      db: PhantomData,
    }
  }
}

impl<V, Db, S: Copy> Copy for SqlKeyset<'_, V, Db, S> {}

/// The subjects are compared, and that is not bookkeeping: two keysets over one order and one cursor
/// that compare different EXPRESSIONS are two different predicates, so leaving them out would be an
/// equality that says the opposite.
impl<V: PartialEq, Db, S: PartialEq> PartialEq for SqlKeyset<'_, V, Db, S> {
  fn eq(&self, other: &Self) -> bool {
    self.terms == other.terms
      && self.values == other.values
      && self.walk == other.walk
      && self.subjects == other.subjects
  }
}

/// The COMPANION shape's own suite — the third member of the subject vocabulary, and the two
/// facts that came apart in it. Beside [`tests`], which is the expansion's per-polarity half.
#[cfg(test)]
mod shadow_tests;
#[cfg(test)]
mod tests;