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 ;
use ;
use crate::;
/// 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.
/// 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.
/// 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.
/// 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.
;
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.