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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
//! The three lanes as a typestate, the statement each renders, and the connection every statement
//! of one call runs on.
//!
//! ```text
//! Find ─ filter ─┬─ fetch ──────────────────────────────────────────► Vec<R>   unordered, unlimited
//!                ├─ limit ─► Limited ─ fetch ──────────────────────► Vec<R>   unordered, any N
//!                └─ order ─► Ordered ─┬─ fetch ────────────────────► Vec<R>   ordered, whole set
//!                                     ├─ first ─► Paging<Forward>  ─┬ after ─┐
//!                                     ├─ last  ─► Paging<Backward> ─┼ before ┼► Paging<Positioned>
//!                                     └─ after / before / skip ─────┴ skip ──┘        │
//!                                                                                     ▼
//!                                                                          fetch ► Page<R, V>
//!                                                                          rows  ► Page<Row, V>
//! ```
//!
//! # A page has TWO legs, and they are one statement
//!
//! `fetch` crosses each row into its RECORD, which is what a Rust query answers with. `rows` hands
//! the rows themselves back, for the reader that mints something else from them — a wire face builds
//! its output object from the row, so a page that could only produce records would make that face
//! run the crossing and throw it away. Everything a page IS is written once and both legs run it;
//! the crossing is the only thing that differs, and it is a parameter. The same split is why
//! [`rows`] exists beside [`get`] on the id lane.
//!
//! # What each edge that is MISSING refuses
//!
//! - **A page without a written order.** `first`, `last`, `after`, `before` and `skip` exist on
//!   [`Ordered`] and nowhere else, so a cursor over an unordered set is a method that does not
//!   exist. This is the ruling's own enforcement: *in Rust this is UNSPELLABLE*.
//! - **A cursor position AND an offset.** Both `after`/`before` and `skip` consume into
//!   [`Positioned`], which offers neither, so the second one written is a method that does not
//!   exist. A position enum with two setters would keep the last one written and drop the other,
//!   silently — polarsync's exact wound, where a `skip` with no `first` beside it was ignored.
//! - **`after` on a backward walk, and `before` on a forward one.** The walk is chosen by the size
//!   method, and each walk's state carries only the position that runs with it. Relay permits the
//!   crossed pairs and nobody implements them honestly: `last` beside `after` is *the last N of
//!   everything after the cursor*, which cannot be answered without reaching the far end first.
//! - **An order after a ceiling.** A row ceiling and a page size are two names for one number, so a
//!   builder holding both would have to decide which wins. [`Limited`] ends its lane at `fetch`
//!   instead, which is what makes lane 2 *any N rows* and not a page with the cursors ignored.
//!
//! # One connection per call
//!
//! Every `fetch` acquires ONE connection and runs every statement of the call on it, which is
//! connection-level consistency for free. A call is several statements whenever the record has a
//! GATHERED collection — see [`hydrate`](super::hydrate), which is handed the connection rather
//! than an executor and therefore has none of its own to open.
//!
//! The framework never begins a transaction on its own; `find_<db>_snapshot` is the sugar that
//! does, and a caller wanting one on other terms passes a `&mut Transaction`, which satisfies
//! [`Acquire`](sqlx::Acquire) exactly as a `&Pool` does.
//!
//! # The WALK is measured against real engines, because its failure renders perfectly good SQL
//!
//! A page that skips or repeats a row is a statement that answers without an error, so the
//! rendering tests beside this module deliberately do not try to see it — the same split
//! [`SqlKeyset`](crate::comparison::sql::SqlKeyset) records one level down. What was put to the
//! engines instead is the whole thing: twelve rows carrying `NULL`s in the sort column, ties inside
//! a `slate` group, and a pair that only the key tail separates — paged TWO at a time, forwards and
//! backwards, every cursor round-tripped through its base64 STRING, against the full ordered scan.
//!
//! Exact on both, every row once and in the scan's own sequence, with the backward walk coming back
//! as the scan in display order: **SQLite 3.51.0 and PostgreSQL 17.10**. The other lanes ran on the
//! same rows — the unordered scan, the ceiling, the snapshot, `get` on a hit and on a miss, an
//! offset page whose edges then RESUMED by cursor, and a cursor minted under another order refused
//! as [`CursorError::Order`](crate::CursorError::Order) before any SQL rendered.
//!
//! Two mutations were put to the same walk, each leaving the rest of the page right. Both answered
//! without an error and lost rows:
//!
//! | mutation | what came back |
//! |---|---|
//! | the statement asks for the page size rather than one row more | the forward walk STOPS after its first page — 2 of 12 rows, and `hasNextPage` false with ten rows behind it |
//! | the backward page is not re-reversed | every page's rows arrive inverted, so the walk returns the scan with each page's pair swapped |
//!
//! The first row is why the extra row is fetched rather than inferred, and the second is why the
//! re-reversal is here rather than left to a caller: neither is visible in the statement's text.

use core::marker::PhantomData;

use super::{
  BeginRead, SqlDialect, SqlOrdering, SqlQuery, SqlQueryError,
  error::offset,
  hydrate::{absorb, aggregates, hydrate},
  snapshot::{close_read, open_read},
};
use crate::{
  Cursor, FieldName, Identifiable, OrderTerm, Record, Walk,
  comparison::{
    At, Backend, ComplexComparison,
    sql::{
      OrderSubjects, QueryBuilder, SelectClause, SqlConjunction, SqlKeyset, SqlOrder, SubjectShape,
      SubjectSlot, Utf8BytesMut, WhereClause, fold_columns, push_index, quote_ident,
    },
  },
  query::{DEFAULT_PAGE_SIZE, Edge, MAX_PAGE_SIZE, Page, partition},
};

/// The predicate a filter over `Row` crosses into at `Db`, read off the RECORD's own vocabulary
/// binding rather than off a slot of the engine's.
///
/// One name for a two-step projection, and the reason is that it is spent six times here in
/// signatures a reader has to scan. What it says is the whole of the migration: a comparison is a
/// fact about a record in a database — `<R as Record<Db>>::Comparison` — and the engine reads it
/// where it used to declare a copy, so the two can no longer disagree about which comparison a row
/// takes.
type RowComparison<Row, Db> = <<Row as SqlQuery<Db>>::Record as Record<Db>>::Comparison;

/// Where a page resumes: nowhere, at a cursor, or at an offset.
///
/// ONE enum with three states rather than two optional fields, so *both at once* is not a value
/// this type can hold. Which of them a builder may set is the typestate's — see the module note —
/// and this is what the engine reads once the choice has been made.
/// `Clone` and `Copy` are WRITTEN OUT rather than derived, for the reason every `Db`-parameterised
/// type in the comparison family writes its own: a derive would bound `V`, which this holds only
/// behind a shared reference — so a cursor value that is not `Copy` would make a position that is
/// not either, and the whole page would have to be threaded by move.
#[derive(Debug, PartialEq, Eq)]
enum Position<'a, V> {
  /// The first page of the walk.
  Start,
  /// After the row this cursor was minted at, running the walk's way.
  Cursor(&'a Cursor<V>),
  /// Past this many rows of the walk.
  Skip(u64),
}

impl<V> Clone for Position<'_, V> {
  #[inline]
  fn clone(&self) -> Self {
    *self
  }
}

impl<V> Copy for Position<'_, V> {}

impl<'a, V> Position<'a, V> {
  /// Whether the request named a place to resume — which is what a forward page's
  /// `has_previous_page` reports, and a backward page's `has_next_page`.
  ///
  /// A `skip` of ZERO is not a position: it names the start of the walk, which is where a page with
  /// no position begins. Reporting *there is more behind you* for it would be the approximation
  /// drifting from relay's own rule, which permits a `true` that is wrong and not one that is
  /// meaningless.
  const fn is_set(self) -> bool {
    match self {
      Self::Start => false,
      Self::Cursor(_) => true,
      Self::Skip(skip) => skip > 0,
    }
  }

  /// The offset this position asks the statement for, checked against what the dialect can bind.
  fn offset(self) -> Result<Option<u64>, SqlQueryError> {
    match self {
      Self::Start | Self::Cursor(_) | Self::Skip(0) => Ok(None),
      Self::Skip(skip) => offset(skip).map(Some),
    }
  }

  /// The cursor this position resumes at, where it is one.
  const fn cursor(self) -> Option<&'a Cursor<V>> {
    match self {
      Self::Cursor(cursor) => Some(cursor),
      Self::Start | Self::Skip(_) => None,
    }
  }
}

/// A page running the order AS WRITTEN: `first` and `after`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Forward;

/// A page running the order INVERTED: `last` and `before`. The rows are re-reversed into display
/// order by the engine, so nothing downstream has to know which way the scan ran.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Backward;

/// A page whose position is fixed — by a cursor or by an offset — and which can no longer be given
/// the other kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Positioned;

/// A plural query with no order and no ceiling: the whole set, in whatever sequence the engine
/// answers in.
///
/// It renders NO `ORDER BY`, which is the ruling: a sort nobody asked for is work every row pays
/// for, and SQL's own unordered semantics is the honest answer to a query that named no order.
#[must_use = "a query builder renders nothing until it is fetched"]
pub struct Find<'a, Row, Db, A>
where
  Row: SqlQuery<Db>,
  Db: Backend + sqlx::Database,
{
  executor: A,
  filter: Option<&'a RowComparison<Row, Db>>,
  scope: Option<&'a RowComparison<Row, Db>>,
  snapshot: bool,
}

/// A plural query with a row ceiling and no order — lane 2, *any N rows*, asked for honestly.
///
/// No cursors and no connection: the rows it returns are arbitrary, which is what the caller asked
/// for and what a page would have had to lie about.
#[must_use = "a query builder renders nothing until it is fetched"]
pub struct Limited<'a, Row, Db, A>
where
  Row: SqlQuery<Db>,
  Db: Backend + sqlx::Database,
{
  find: Find<'a, Row, Db, A>,
  limit: u32,
}

/// A plural query with a WRITTEN order — the only state a page can be asked for from.
///
/// The order it holds is already COMPLETE: the client's terms followed by every address column none
/// of them named, which is what makes the order total and the page resumable. Completing it once,
/// here, is what keeps the `ORDER BY`, the keyset `WHERE` and the cursor three readings of one list.
#[must_use = "a query builder renders nothing until it is fetched"]
pub struct Ordered<'a, Row, Db, A>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  find: Find<'a, Row, Db, A>,
  order: Vec<Row::Order>,
  /// What each of that order's terms COMPARES, built once here and spent in every position that
  /// renders one: the SELECT list, the `ORDER BY` and the resume predicate. Built with the order
  /// rather than per statement, because a page renders three of them from it and two subjects that
  /// agree today is the drift this seam exists to close.
  subjects: Row::Subjects,
}

/// A page under construction: its size, the way it runs, and where it resumes.
///
/// `S` is which of those are still open — [`Forward`] and [`Backward`] each admit their own
/// position, [`Positioned`] admits none — and it is a marker rather than a field, so the state
/// costs nothing at runtime and the wrong call is a compile error.
#[must_use = "a query builder renders nothing until it is fetched"]
pub struct Paging<'a, Row, Db, A, S>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  ordered: Ordered<'a, Row, Db, A>,
  size: u32,
  walk: Walk,
  position: Position<'a, Row::Value>,
  // `fn() -> S` rather than a bare parameter, so the state marker contributes no auto-trait or
  // variance obligation — this crate's convention for every phantom state.
  state: PhantomData<fn() -> S>,
}

impl<'a, Row, Db, A> Find<'a, Row, Db, A>
where
  Row: SqlQuery<Db>,
  Db: Backend + sqlx::Database,
{
  /// A query over `executor`, unfiltered and unordered.
  ///
  /// `snapshot` is what `find_<db>_snapshot` sets: the call opens the dialect's read transaction
  /// around every statement it runs. It is a MODE rather than a state — nothing about which methods
  /// exist depends on it — so it is a parameter here and not a fourth type.
  #[inline]
  pub const fn new(executor: A, snapshot: bool) -> Self {
    Self {
      executor,
      filter: None,
      scope: None,
      snapshot,
    }
  }

  /// Constrain the query by `filter` — the CLIENT's predicate, the one a document wrote.
  ///
  /// Borrowed rather than owned, because a comparison is built from a client's filter and outlives
  /// the statement it renders into — the tie [`ComplexComparison::apply`] already spells.
  ///
  /// It REPLACES rather than accumulates, and the slot beside it is why that is safe to keep: a
  /// caller with two predicates to impose has [`scope`](Self::scope) for the second, so *call
  /// `filter` twice* is never the shape a conjunction has to take.
  #[inline]
  pub fn filter(mut self, filter: &'a RowComparison<Row, Db>) -> Self {
    self.filter = Some(filter);
    self
  }

  /// Constrain the query by `scope` — the SERVER's predicate, ANDed with the client's.
  ///
  /// # Two slots because there are two PARTIES, which is what caps this at two
  ///
  /// A read on this engine is narrowed from at most two places: the document a client wrote, and the
  /// scope the resolver attached because of where the field hangs. The emitted lineage leg is the
  /// first reader — its ancestry arguments mint a predicate the client never wrote, and its `where`
  /// argument is the client's beside it — so the pair is the domain's own shape rather than a
  /// ceiling picked for a call site.
  ///
  /// # It is a plain AND, and a contradiction is the EMPTY SET rather than a refusal
  ///
  /// Both reach [`predicates`] and are threaded through ONE accumulator, so the statement renders
  /// `<client> AND <scope>` in one `WHERE`. Nothing detects a conflict, and nothing should: a
  /// client scoping to one ancestry while naming another asks for the rows in both, which is a
  /// question with a well-defined answer of no rows. Refusing it would be this engine inventing a
  /// word for a set law SQL already obeys — and would make an intersection a client is allowed to
  /// take on any other pair of columns an error on this one.
  ///
  /// Borrowed for the same reason [`filter`](Self::filter) is.
  #[inline]
  pub fn scope(mut self, scope: &'a RowComparison<Row, Db>) -> Self {
    self.scope = Some(scope);
    self
  }

  /// Ceiling the query at `limit` rows — lane 2, and the end of it.
  #[inline]
  pub const fn limit(self, limit: u32) -> Limited<'a, Row, Db, A> {
    Limited { find: self, limit }
  }
}

impl<'a, Row, Db, A> Find<'a, Row, Db, A>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  /// Order the query by `written`, completed with the address columns that make it total.
  ///
  /// An order of NO terms needs no refusal here: it completes into that tail alone, which is a
  /// written order over the record's own address — the one order every record can always be paged
  /// in.
  #[inline]
  pub fn order(self, written: &[Row::Order]) -> Ordered<'a, Row, Db, A> {
    let order = Row::complete(written);
    Ordered {
      find: self,
      subjects: Row::subjects(&order),
      order,
    }
  }
}

impl<'a, Row, Db, A> Ordered<'a, Row, Db, A>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  /// The first `first` rows of the order as written.
  #[inline]
  pub fn first(self, first: u32) -> Paging<'a, Row, Db, A, Forward> {
    self.page(first, Walk::Forward)
  }

  /// The last `last` rows of the order as written — the same order read from the far end.
  #[inline]
  pub fn last(self, last: u32) -> Paging<'a, Row, Db, A, Backward> {
    self.page(last, Walk::Backward)
  }

  /// A default-sized page after `cursor`.
  #[inline]
  pub fn after(self, cursor: &'a Cursor<Row::Value>) -> Paging<'a, Row, Db, A, Positioned> {
    self.first(DEFAULT_PAGE_SIZE).after(cursor)
  }

  /// A default-sized page before `cursor`.
  #[inline]
  pub fn before(self, cursor: &'a Cursor<Row::Value>) -> Paging<'a, Row, Db, A, Positioned> {
    self.last(DEFAULT_PAGE_SIZE).before(cursor)
  }

  /// A default-sized page past `skip` rows of the order as written.
  #[inline]
  pub fn skip(self, skip: u64) -> Paging<'a, Row, Db, A, Positioned> {
    self.first(DEFAULT_PAGE_SIZE).skip(skip)
  }

  /// The page this state opens, with its size clamped to the framework's ceiling.
  ///
  /// Every way into a page goes through it, so a size past the cap is narrowed ONCE rather than at
  /// each entry point — and the entry points that supply the default go through the same call.
  fn page<S>(self, size: u32, walk: Walk) -> Paging<'a, Row, Db, A, S> {
    Paging {
      ordered: self,
      size: size.min(MAX_PAGE_SIZE),
      walk,
      position: Position::Start,
      state: PhantomData,
    }
  }
}

impl<'a, Row, Db, A> Paging<'a, Row, Db, A, Forward>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  /// Resume after the row `cursor` was minted at.
  #[inline]
  pub fn after(self, cursor: &'a Cursor<Row::Value>) -> Paging<'a, Row, Db, A, Positioned> {
    self.at(Position::Cursor(cursor))
  }

  /// Skip `skip` rows of the walk before the page begins.
  ///
  /// It applies INDEPENDENTLY of the page size, which is the bug polarsync shipped the other way
  /// round: there a `skip` with no `first` beside it was silently ignored.
  #[inline]
  pub fn skip(self, skip: u64) -> Paging<'a, Row, Db, A, Positioned> {
    self.at(Position::Skip(skip))
  }
}

impl<'a, Row, Db, A> Paging<'a, Row, Db, A, Backward>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  /// Resume before the row `cursor` was minted at — the backward walk's `after`.
  #[inline]
  pub fn before(self, cursor: &'a Cursor<Row::Value>) -> Paging<'a, Row, Db, A, Positioned> {
    self.at(Position::Cursor(cursor))
  }

  /// Skip `skip` rows of the backward walk before the page begins.
  #[inline]
  pub fn skip(self, skip: u64) -> Paging<'a, Row, Db, A, Positioned> {
    self.at(Position::Skip(skip))
  }
}

impl<'a, Row, Db, A, S> Paging<'a, Row, Db, A, S>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  /// How many rows this page holds — the ask, clamped to the framework's ceiling.
  ///
  /// Public because it is what a client actually gets: relay lets a server return fewer edges than
  /// were asked for, so a caller that wants to know the clamp happened can be told rather than
  /// having to count the rows that came back.
  #[inline]
  #[must_use]
  pub const fn size(&self) -> u32 {
    self.size
  }

  /// How many rows the STATEMENT asks for: the page, plus the one that answers *is there more*.
  ///
  /// `saturating_add` because the ceiling is a `u32`: a page clamped to the cap is nowhere near it,
  /// and a sum that wrapped would ask for no rows at all.
  #[inline]
  const fn window(&self) -> u32 {
    self.size.saturating_add(1)
  }

  /// The same page with its position fixed — the one move out of an open state, and the reason
  /// there is no way back into one.
  fn at(self, position: Position<'a, Row::Value>) -> Paging<'a, Row, Db, A, Positioned> {
    Paging {
      ordered: self.ordered,
      size: self.size,
      walk: self.walk,
      position,
      state: PhantomData,
    }
  }

  /// The terms this page's completed order renders as, in the sequence they run.
  ///
  /// The terms are the order AS WRITTEN whichever way the walk runs: a cursor is minted under the
  /// order rather than under the direction it was read in, which is what lets one set of cursors
  /// page a client forwards and backwards.
  ///
  /// One written word may render as SEVERAL terms — [`OrderTerm::levels`] expands a citizen that
  /// states a semantic sequence into one ordinary term per level — so this list is as long as the
  /// LEVELS and not as long as the client's order. Everything downstream is indexed by it: the
  /// `ORDER BY`'s entries, the keyset's arms, the projected sort aliases and the cursor's slots are
  /// four readings of THIS list, which is what keeps them from disagreeing about a boundary.
  fn terms(&self) -> Vec<OrderTerm> {
    self
      .ordered
      .order
      .iter()
      .flat_map(|term| Row::term(term.clone()).levels())
      .collect()
  }
}

/// The `SELECT … FROM … ` every lane opens with, up to the predicate list.
///
/// `begin_where` renders nothing, so a query with no predicate carries no keyword: entering the
/// list is a typestate move, and the clause keyword belongs to the accumulator that opens the first
/// conjunct. That is what lets all three lanes share one opening rather than branching on whether a
/// filter was given.
///
/// The row's own columns come first, the plan's aggregates after them, and whatever `sorts` adds
/// after those — so a statement's projection reads as *the row, then what was materialized onto it,
/// then what the ORDER produced* — and a lane that hydrates or that pages differs from one that does
/// neither by the TAIL of its SELECT list rather than by a second opening.
///
/// # Errors
///
/// A collection plan whose entry names no field, which is the one refusal deriving an edge table
/// has — see [`hydrate`](super::hydrate).
fn open<Row, Db>(
  sorts: impl FnOnce(QueryBuilder<SelectClause, Db>) -> QueryBuilder<SelectClause, Db>,
) -> Result<QueryBuilder<WhereClause, Db>, SqlQueryError>
where
  Row: SqlQuery<Db>,
  Db: SqlDialect,
{
  // Every COLUMN rather than every entry: a field whose type spans two contributes two names here,
  // and the walk is what joins each of them — `COLUMNS` holds no joined name to push.
  let builder = fold_columns::<Db, _>(
    Row::COLUMNS,
    QueryBuilder::<SelectClause, Db>::select(),
    &mut |builder, column| builder.push_field(column.as_str()),
  );
  Ok(
    sorts(aggregates::<Row, Db>(builder)?)
      .from(quote_ident::<Db>(Row::ADDRESS.table()).as_str())
      .begin_where(),
  )
}

/// The WORD a sort value's SELECT-list alias is built from — `__ig_ord0__` for the first term of
/// the completed order, `__ig_ord1__` for the second.
///
/// The plan's aggregate aliases are the precedent and the reason is the same one: several of these
/// ride ONE statement, so they have to be told apart, and the position in the order is what tells
/// them apart.
///
/// # It is the MongoDB family's spelling, to the byte, and that is the point of writing it twice
///
/// A sort value is one thing wherever it is stored, so a page that meant `__ig_ord0__` on one
/// deployment and something else on another would be two engines with two names for one position.
/// The two consts are held apart because the feature edge does not let one family see the other's;
/// `a_sort_alias_is_one_spelling_across_the_two_families` is what keeps them one string.
///
/// The LAW that decides the shape — why the digits fuse to the word instead of sitting behind a
/// `_` — is stated once, at the MongoDB mint, because that is the family in which a minted name is a
/// live document KEY beside the stored ones. Here it is a SELECT-list output alias, in a namespace
/// the statement opens and closes; the spelling is shared all the same.
///
/// [the MongoDB mint]: crate::query::mongo::sort_alias
const SORT_ALIAS: &str = "__ig_ord";

/// What closes a minted word — see [`SORT_ALIAS`].
const ALIAS_END: &str = "__";

/// The alias term `level` of a completed order is projected under.
///
/// Held rather than pushed, exactly as an aggregate's is: the two parties that need it are a
/// statement and a DECODE — [`sorts`] brackets it into the SELECT list and [`edges`] hands it to the
/// row as the column to read — so there is no one buffer for it to be written into.
fn sort_alias(level: usize) -> Utf8BytesMut {
  let mut alias = Utf8BytesMut::new();
  alias.push_str(SORT_ALIAS);
  push_index(level, &mut alias);
  alias.push_str(ALIAS_END);
  alias
}

/// Project every term of `order` whose value the returned ROW does not carry onto the SELECT list,
/// each under [`sort_alias`].
///
/// ```sql
/// SELECT …, (SELECT "keyframe"."title" FROM "keyframe"
///              WHERE "keyframe"."id" = "shot"."cover_id") AS "__ig_ord0__" FROM "shot"
/// SELECT …, "reel"."__ig_tags_sort__" AS "__ig_ord0__" FROM "reel"
/// ```
///
/// **Two shapes reach here, and the second is a bare NAME.** An EXPRESSION term has no column
/// anywhere to read. A COMPANION term has one — `__ig_<field>_sort__` is a real column of the
/// ordered table, and the `ORDER BY` beneath names it — but it is none of the ROW's,
/// [`SqlQuery::COLUMNS`] being the record's own fields, so its value would not come back either.
///
/// It is the SAME subject the `ORDER BY` and the keyset render, from the same value — which is what
/// makes the cursor's boundary the value the page actually sorted at rather than a second expression
/// that agrees today. For a COMPANION that identity is the whole of the frozen-boundary law at this
/// term: the bytes the cursor carries are the bytes this statement's own `ORDER BY` sorted this row
/// by, off that row in that statement. The alternative was to rebuild them from the collection —
/// [`collection_sort_key`](crate::collection_sort_key) over the list the row ends up holding — and
/// that list arrives from a SECOND statement, the gather, which is a second reading free to have
/// moved. A boundary read from anywhere but the ordered row is a boundary the ordering never
/// produced.
///
/// A term over a column of the ROW projects NOTHING: its value is already there, under a column the
/// `SELECT` list above named.
///
/// Which terms those are is [`SubjectShape`]'s answer, and it is asked BEFORE the field is opened:
/// a field opened and then abandoned is a comma and an alias with no expression between them. This
/// position writes no wrapping of its own — the [`SubjectSlot`] the shape opens is what brackets a
/// sub-select and leaves a companion bare, here as in the `ORDER BY` and in every arm of the resume
/// predicate.
fn sorts<'a, Db, S>(
  order: SqlOrder<'a, Db>,
  subjects: &'a S,
  at: At<'a>,
) -> impl FnOnce(QueryBuilder<SelectClause, Db>) -> QueryBuilder<SelectClause, Db> + 'a
where
  Db: SqlDialect,
  S: OrderSubjects<Db> + ?Sized,
{
  let terms = order.terms();
  move |mut builder| {
    for level in 0..terms.len() {
      let shape = subjects.shape(terms, level);
      match shape {
        SubjectShape::Column => continue,
        SubjectShape::Companion | SubjectShape::SubSelect => {}
      }
      let alias = sort_alias(level);
      builder = builder.push_field_with(|qb| {
        subjects.push_subject(SubjectSlot::new(qb, shape), at, terms, level);
        qb.push(" AS ");
        qb.push(quote_ident::<Db>(FieldName::new(alias.as_str())));
      });
    }
    builder
  }
}

/// Thread `filter`, `scope` and `extra` through ONE accumulator, so a page is *the client's filter
/// AND this* and no conjunct has to know what the others were.
///
/// `K` is a second comparison rather than a keyset by name, because the two callers pass different
/// ones: a page passes its keyset and `get` passes the address predicate. Both are conjuncts beside
/// the filter, which is the whole of what this needs to know about either.
///
/// `scope` is the SERVER's predicate — [`Find::scope`] carries what it is for. It is spelled as its
/// own parameter rather than folded into `filter` because the two comparisons are separate VALUES: a
/// column's operand slot holds one operand, so `id = 1` and `id = 2` cannot inhabit one comparison
/// struct however it is merged, and a conjunction that could not express its own contradiction would
/// answer the wrong rows rather than none. Two values applied to one accumulator is the shape that
/// can, and it is the shape this function already had.
fn predicates<Row, Db, K>(
  builder: &mut QueryBuilder<WhereClause, Db>,
  filter: Option<&RowComparison<Row, Db>>,
  scope: Option<&RowComparison<Row, Db>>,
  extra: Option<&K>,
) -> Result<(), SqlQueryError>
where
  Row: SqlQuery<Db>,
  Db: SqlDialect,
  K: ComplexComparison<Db>,
{
  let address = Row::ADDRESS;
  let mut conjunction = SqlConjunction::new(builder.inner_mut());
  if let Some(filter) = filter {
    conjunction = filter.apply(At::new(&address), conjunction)?;
  }
  if let Some(scope) = scope {
    conjunction = scope.apply(At::new(&address), conjunction)?;
  }
  if let Some(extra) = extra {
    conjunction = extra.apply(At::new(&address), conjunction)?;
  }
  // The accumulator holds the builder's `&mut`, and the clause transition that follows takes the
  // builder BY VALUE — so the borrow has to end here. It is a rebinding rather than a `drop`,
  // which clippy declines over a type with no destructor to run.
  let _ = conjunction;
  Ok(())
}

/// The statement that names ONE row, by its id.
///
/// No ceiling, and that is now PROVABLE rather than asserted: every table this engine addresses
/// declares its id `UNIQUE` — `PRIMARY KEY (id)` is what a framework-emitted one states, and a
/// user-declared physical layout owes the same constraint — so the predicate matches at most one
/// row by the schema's own law. A `LIMIT 1` would restate that law in the statement, and would hide
/// a duplicate id rather than letting the constraint report it.
fn address<Row, Db>(
  ids: &[<Row::Record as Identifiable>::Id],
) -> Result<sqlx::QueryBuilder<Db>, SqlQueryError>
where
  Row: SqlQuery<Db>,
  Db: SqlDialect,
{
  composed::<Row, Db>(ids, None)
}

/// The COMPOSED statement: the rows of `ids` that ALSO satisfy `filter`, in ONE `WHERE`.
///
/// It is [`address`] with the second conjunct filled in, and they share this body because they are
/// one statement asked with and without a predicate beside the keys. [`predicates`] already threads
/// both through one accumulator, so the composition is a parameter it was already taking.
///
/// This is the second leg of *search → keys → hydrate*: an index answers with keys, and the system
/// of record is asked for THOSE keys and the client's filter together. One round trip rather than
/// gather-then-prune — and it is what makes a page that came back short mean *the filter pruned*
/// rather than *the gather over-fetched*.
///
/// The keys ride [`SqlQuery::addresses`], which is the ROW-VALUE membership — `("id") IN ((?), (?))`
/// — and never a per-column `IN` list. Only `eq` decomposes conjunctively, so the per-column
/// spelling over a compound key asks for the CARTESIAN PRODUCT; see
/// [`SqlKeyIn`](crate::comparison::sql::SqlKeyIn), which exists as a type for that reason.
fn composed<Row, Db>(
  ids: &[<Row::Record as Identifiable>::Id],
  filter: Option<&RowComparison<Row, Db>>,
) -> Result<sqlx::QueryBuilder<Db>, SqlQueryError>
where
  Row: SqlQuery<Db>,
  Db: SqlDialect,
{
  let predicate = Row::addresses(ids)?;
  let mut builder = open::<Row, Db>(|builder| builder)?;
  // No SCOPE on the gather lane: this statement is addressed by keys a caller already holds, and
  // the party that narrowed those keys is the one that did the scoping.
  predicates::<Row, Db, Row::Address>(&mut builder, filter, None, Some(&predicate))?;
  Ok(builder.finalize())
}

/// Every ROW of `ids` that satisfies `filter`, in ONE composed statement, on a connection the
/// caller already holds.
///
/// # It takes a CONNECTION where [`rows`] takes an acquirable, and the retrieve loop is why
///
/// [`rows`] is a whole call: it acquires, brackets the dialect's read transaction and hands the
/// rows back. This one is a STEP — a retrieve's fill loop runs several of these against one page,
/// and a bracket per statement would put each batch in its own snapshot. The caller opens whatever
/// bracket the page wants, once, and spends this inside it.
///
/// # Rows rather than records, and the correlation is the caller's
///
/// The membership names a SET, so the plan answers in whatever sequence it chose — which is why
/// [`SqlQuery::id`] exists. The party that asked in an order reads each row's own id back and lines
/// the list up again; here that party is the retrieve seam, which has the ranked key list to line
/// it up against.
///
/// # Errors
///
/// A lowering refusal carried verbatim, a driver error, or an id that will not cross into this
/// database's stored type.
pub async fn gathered<Row, Db>(
  conn: &mut Db::Connection,
  ids: &[<Row::Record as Identifiable>::Id],
  filter: Option<&<Row::Record as Record<Db>>::Comparison>,
) -> Result<Vec<Row>, SqlQueryError>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  let mut statement = composed::<Row, Db>(ids, filter)?;
  Ok(decode::<Row, Db>(conn, &mut statement, usize::MAX).await?.0)
}

/// The unordered statement — lane 1 and lane 2, which differ only in whether a ceiling is bound.
pub(super) fn scan<Row, Db>(
  filter: Option<&RowComparison<Row, Db>>,
  scope: Option<&RowComparison<Row, Db>>,
  limit: Option<u32>,
) -> Result<sqlx::QueryBuilder<Db>, SqlQueryError>
where
  Row: SqlQuery<Db>,
  Db: SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
{
  let mut builder = open::<Row, Db>(|builder| builder)?;
  predicates::<Row, Db, RowComparison<Row, Db>>(&mut builder, filter, scope, None)?;
  Ok(match limit {
    Some(limit) => builder.limit(u64::from(limit)).finalize(),
    None => builder.finalize(),
  })
}

/// Whether a statement carries the SORT VALUES of the terms whose value its rows do not.
///
/// A unit enum rather than a `bool` beside three other optional fields, for the reason
/// `CollectionOrder` is one: what a bare flag says at a call site is nothing, and this one decides
/// whether a correlated subquery is evaluated a second time per row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SortValues {
  /// The page lane: every term the row does not carry also rides the SELECT list, because a cursor
  /// is minted from the row that comes back — an expression having no column there to read, and a
  /// companion column being none of the row's own.
  Projected,
  /// The ordered SCAN: no cursor is minted, so a projected value would be a correlated subquery
  /// evaluated once per row that nothing ever reads — and, for a companion, one more column read
  /// per row for a boundary nobody asked for.
  Unread,
}

/// One order as a statement renders it — the whole of what an ordered lane knows about ordering.
///
/// The four fields are FOUR READINGS OF ONE LIST, which is why they travel as a value rather than as
/// four parameters: the terms, what each of them compares, where the page resumes among them, and
/// whether their values ride the SELECT list. Two of them are built from the third — the keyset
/// resumes `order` and both it and the ordering render `subjects` — so a call site that could pass
/// them independently is a call site that could pass a keyset over another order.
struct Ordering<'a, Row, Db>
where
  Row: SqlOrdering<Db>,
  Db: Backend + sqlx::Database,
{
  /// The completed terms, checked against this dialect.
  order: SqlOrder<'a, Db>,
  /// What each of those terms compares, borrowed so that the ordering and the keyset spend ONE
  /// value — see the borrow impl beside
  /// [`TermColumns`](crate::comparison::sql::TermColumns).
  subjects: &'a Row::Subjects,
  /// Where the page resumes, or [`None`] for the first page of a walk and for an ordered scan.
  keyset: Option<&'a SqlKeyset<'a, Row::Value, Db, &'a Row::Subjects>>,
  /// Whether the sort values ride the page's own SELECT list.
  values: SortValues,
}

/// The ordered statement, with or without a page.
///
/// ONE function for both, because a page IS an ordered query with a ceiling and a resume predicate:
/// splitting them would give the `ORDER BY` two renderings, which is the one thing [`SqlOrder`]
/// exists to prevent.
///
/// The ordering's subjects reach all three positions from here: the SELECT list through [`sorts`],
/// the `ORDER BY` through
/// [`push_order_by_with`](crate::comparison::sql::SqlOrder::push_order_by_with), and the resume
/// predicate through the keyset the caller already built from them.
fn ordered<Row, Db>(
  filter: Option<&RowComparison<Row, Db>>,
  scope: Option<&RowComparison<Row, Db>>,
  ordering: Ordering<'_, Row, Db>,
  walk: Walk,
  limit: Option<u32>,
  skip: Option<u64>,
) -> Result<sqlx::QueryBuilder<Db>, SqlQueryError>
where
  Row: SqlOrdering<Db>,
  Db: SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
{
  let address = Row::ADDRESS;
  let at = At::new(&address);
  let mut builder = match ordering.values {
    SortValues::Projected => open::<Row, Db>(sorts(ordering.order, ordering.subjects, at))?,
    SortValues::Unread => open::<Row, Db>(|builder| builder)?,
  };
  predicates::<Row, Db, SqlKeyset<'_, Row::Value, Db, &Row::Subjects>>(
    &mut builder,
    filter,
    scope,
    ordering.keyset,
  )?;
  let builder = ordering
    .order
    .push_order_by_with(builder, walk, at, ordering.subjects);
  Ok(match (limit, skip) {
    (Some(limit), Some(skip)) => builder.limit(u64::from(limit)).offset(skip).finalize(),
    (Some(limit), None) => builder.limit(u64::from(limit)).finalize(),
    // A skip with no ceiling has no way into `OFFSET`, and no caller can produce one: every page
    // carries a size, and the lane that carries a skip is a page.
    (None, _) => builder.finalize(),
  })
}

/// Open the dialect's read transaction where the call asked for one.
async fn begin<Db>(conn: &mut Db::Connection, snapshot: bool) -> Result<(), sqlx::Error>
where
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  if snapshot {
    sqlx::Executor::execute(&mut *conn, Db::BEGIN).await?;
  }
  Ok(())
}

/// Close it, whichever way the call went.
///
/// A failed close on the ERROR path is dropped rather than reported: the call already has something
/// to say, and a rollback that did not run leaves a connection the pool resets anyway. On the
/// success path it is reported, because a commit that did not run means the read was not the one
/// that was promised.
async fn end<Db>(conn: &mut Db::Connection, snapshot: bool, ok: bool) -> Result<(), sqlx::Error>
where
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  if !snapshot {
    return Ok(());
  }
  if ok {
    sqlx::Executor::execute(&mut *conn, Db::COMMIT).await?;
    return Ok(());
  }
  drop(sqlx::Executor::execute(&mut *conn, Db::ROLLBACK).await);
  Ok(())
}

/// Acquire ONE connection, run one statement on it, and give the records back.
async fn run<'c, Row, Db, A>(
  executor: A,
  snapshot: bool,
  mut statement: sqlx::QueryBuilder<Db>,
) -> Result<Vec<Row::Record>, SqlQueryError>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
  A: sqlx::Acquire<'c, Database = Db>,
{
  let mut held = executor.acquire().await?;
  let conn = &mut *held;
  begin::<Db>(conn, snapshot).await?;
  let records = raise::<Row, Db>(conn, &mut statement).await;
  end::<Db>(conn, snapshot, records.is_ok()).await?;
  records
}

/// Run `statement`, hydrate what it returned, and raise every row back into its record.
async fn raise<Row, Db>(
  conn: &mut Db::Connection,
  statement: &mut sqlx::QueryBuilder<Db>,
) -> Result<Vec<Row::Record>, SqlQueryError>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  let mut rows = decode::<Row, Db>(conn, statement, usize::MAX).await?.0;
  let mut records = Vec::with_capacity(rows.len());
  for row in rows.drain(..) {
    records.push(row.record()?);
  }
  Ok(records)
}

/// Run `statement`, take at most `ceiling` rows of what it returned, and give them their
/// collections — the one place a row becomes WHOLE, whichever lane asked for it.
///
/// The `bool` is whether the statement returned more rows than the ceiling took, which is what a
/// page's *is there another row this way* reads. Every other lane passes no ceiling and ignores it.
///
/// # The extra row is trimmed BEFORE the gather, and that is not only tidiness
///
/// A page asks for one row more than it holds, and that row is discarded. Hydrating it would bind
/// one key more into every gather of every page of a walk and then throw the elements away — the
/// cost is small and the wrongness is not: the batch a page gathers would be a row wider than the
/// page it is for.
async fn decode<Row, Db>(
  conn: &mut Db::Connection,
  statement: &mut sqlx::QueryBuilder<Db>,
  ceiling: usize,
) -> Result<(Vec<Row>, Vec<Db::Row>, bool), SqlQueryError>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  let mut raw = sqlx::Executor::fetch_all(&mut *conn, statement.build()).await?;
  let more = raw.len() > ceiling;
  // Trimmed HERE rather than at each reader, so the page's rows and the driver's rows are the same
  // list at the same length — which is what lets the two be walked in step below.
  raw.truncate(ceiling);
  let mut rows = Vec::with_capacity(raw.len());
  for row in &raw {
    let mut decoded = Row::from_row(row)?;
    // The aggregated collections rode this very row, under the aliases the SELECT list wrote — so
    // they are taken off it here, beside the decode, and never travel a statement of their own.
    absorb::<Row, Db>(&mut decoded, row)?;
    rows.push(decoded);
  }
  hydrate::<Row, Db>(conn, &mut rows).await?;
  Ok((rows, raw, more))
}

/// One page's rows, trimmed, hydrated, and whether the row after them was there — each row crossed
/// by `mint` into whatever the calling lane's edges carry.
///
/// # The crossing is a parameter because a page has TWO readers, not because it might
///
/// A Rust caller pages RECORDS, which is what a query answers with. A wire face pages ROWS, because
/// the output object it mints is minted from the row — the same reason [`rows`] hands rows back —
/// and a page that could only produce records would make that lane run a conversion to discard it.
/// So the one thing that differs between the two is passed in, and everything a page IS — the extra
/// row, the trim, the hydration, the per-term sort values, the cursor mint — is written once.
async fn edges<Row, Db, T>(
  conn: &mut Db::Connection,
  statement: &mut sqlx::QueryBuilder<Db>,
  order: &[Row::Order],
  terms: &[OrderTerm],
  size: usize,
  mut mint: impl FnMut(Row) -> Result<T, SqlQueryError>,
) -> Result<(Vec<Edge<T, Row::Value>>, bool), SqlQueryError>
where
  Row: SqlOrdering<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  // The row PAST the page is the whole of what the extra row is for, and the decode reports it
  // rather than carrying it: `fetch_all` returned what the statement asked for, which was one more
  // than the page holds.
  let (mut rows, raw, more) = decode::<Row, Db>(conn, statement, size).await?;
  // WHICH LEAF each rendered term is, in the sequence `terms` runs — the map back from a statement's
  // levels to the written words that produced them. It is computed once per page rather than per
  // row, and from the same `Row::term` the terms were built with, so a level's slot and the entry
  // the `ORDER BY` rendered for it are the same level by construction rather than by counting twice.
  let mut levels: Vec<(&Row::Order, usize)> = Vec::with_capacity(terms.len());
  for term in order {
    for level in Row::term(term.clone()).levels() {
      levels.push((term, level.leaf().unwrap_or(0)));
    }
  }
  debug_assert_eq!(
    levels.len(),
    terms.len(),
    "a page's cursor holds one slot per rendered term"
  );
  let mut edges = Vec::with_capacity(rows.len());
  for (row, from) in rows.drain(..).zip(&raw) {
    let mut values: Vec<Option<Row::Value>> = Vec::with_capacity(levels.len());
    for (at, (term, leaf)) in levels.iter().enumerate() {
      // The ALIAS is the ENGINE's, handed over rather than recomputed — the same discipline an
      // aggregated collection's crossing is given its own under. A term over a column ignores both
      // it and the raw row and reads the decoded one.
      values.push(row.value((*term).clone(), *leaf, from, sort_alias(at).as_str())?);
    }
    // `Cursor::at` is the framework's own UNCHECKED mint, and this is the position it is for: both
    // halves are in hand, read from one row under one order. What is CHECKED is the other end —
    // `Cursor::resume`, where the string came back from a client.
    let cursor = Cursor::at(terms, values);
    edges.push(Edge::new(mint(row)?, cursor));
  }
  Ok((edges, more))
}

impl<'a, Row, Db, A> Find<'a, Row, Db, A>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  /// Every row the filter admits, in no order — lane 1.
  ///
  /// # Errors
  ///
  /// A lowering refusal carried verbatim, a driver error, or a row that will not cross back into
  /// its record.
  pub async fn fetch<'c>(self) -> Result<Vec<Row::Record>, SqlQueryError>
  where
    A: sqlx::Acquire<'c, Database = Db>,
  {
    let statement = scan::<Row, Db>(self.filter, self.scope, None)?;
    run::<Row, Db, A>(self.executor, self.snapshot, statement).await
  }
}

impl<'a, Row, Db, A> Limited<'a, Row, Db, A>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  /// Any `limit` rows the filter admits — lane 2.
  ///
  /// # Errors
  ///
  /// As [`Find::fetch`].
  pub async fn fetch<'c>(self) -> Result<Vec<Row::Record>, SqlQueryError>
  where
    A: sqlx::Acquire<'c, Database = Db>,
  {
    let statement = scan::<Row, Db>(self.find.filter, self.find.scope, Some(self.limit))?;
    run::<Row, Db, A>(self.find.executor, self.find.snapshot, statement).await
  }
}

impl<'a, Row, Db, A> Ordered<'a, Row, Db, A>
where
  Row: SqlOrdering<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  /// Every row the filter admits, in the written order completed with the key — an ordered scan,
  /// with no ceiling and no cursors.
  ///
  /// It renders the SAME order a page of this query does, which is what makes it the reference a
  /// page walk is checked against.
  ///
  /// # Errors
  ///
  /// As [`Find::fetch`], plus an order this dialect cannot render.
  pub async fn fetch<'c>(self) -> Result<Vec<Row::Record>, SqlQueryError>
  where
    A: sqlx::Acquire<'c, Database = Db>,
  {
    let terms: Vec<OrderTerm> = self
      .order
      .iter()
      .flat_map(|term| Row::term(term.clone()).levels())
      .collect();
    let order = SqlOrder::<Db>::new(&terms)?;
    let statement = ordered::<Row, Db>(
      self.find.filter,
      self.find.scope,
      Ordering {
        order,
        subjects: &self.subjects,
        keyset: None,
        // No cursor is minted here, so a sort value projected onto this statement would be a
        // correlated subquery evaluated once per row that nothing ever reads.
        values: SortValues::Unread,
      },
      Walk::Forward,
      None,
      None,
    )?;
    run::<Row, Db, A>(self.find.executor, self.find.snapshot, statement).await
  }
}

impl<'a, Row, Db, A, S> Paging<'a, Row, Db, A, S>
where
  Row: SqlOrdering<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
{
  /// The page, in DISPLAY order, with what is known about either side of it.
  ///
  /// # How the row after the page is used
  ///
  /// The statement asks for one row MORE than the page holds. Its presence is *there is another row
  /// this way*, exactly, and it is trimmed before the page is built — so `has_next_page` on a
  /// forward walk and `has_previous_page` on a backward one are measurements rather than guesses.
  /// The other side of each is *a position was given*, which relay permits and which never claims
  /// *no more* when there is more.
  ///
  /// A backward page is scanned from the far end and RE-REVERSED here, so what comes out is the
  /// order as written whichever way the walk ran.
  ///
  /// # Errors
  ///
  /// As [`Ordered::fetch`], plus a cursor that is not this order's and a `skip` past what the
  /// dialect's `OFFSET` can hold.
  pub async fn fetch<'c>(self) -> Result<Page<Row::Record, Row::Value>, SqlQueryError>
  where
    A: sqlx::Acquire<'c, Database = Db>,
  {
    self.page(|row| Ok(row.record()?)).await
  }

  /// The same page, its edges carrying ROWS — lane 乙.
  ///
  /// # Why the engine grows the lane rather than the caller converting
  ///
  /// A wire face is minted from the row: the output object an emitted resolver returns reads the
  /// row's own members, and the crossing into the record is a conversion that face would run to
  /// discard. [`rows`] already says exactly this for the id-gather; a page is the other lane that
  /// needs it, and one statement serves both — paging and face-minting share a source, so a caller
  /// that had to convert would be paying for a record nothing reads.
  ///
  /// Everything else about the page is [`fetch`](Self::fetch)'s: one statement, the extra row, the
  /// cursor minted from the row under the page's own order, and the re-reversal of a backward walk.
  ///
  /// # Errors
  ///
  /// As [`fetch`](Self::fetch), minus the one thing this lane cannot hit — a row that will not cross
  /// into its record, since it never crosses.
  pub async fn rows<'c>(self) -> Result<Page<Row, Row::Value>, SqlQueryError>
  where
    A: sqlx::Acquire<'c, Database = Db>,
  {
    self.page(Ok).await
  }

  /// The page both legs are: one statement in one bracket, its rows crossed by `mint`.
  ///
  /// Written once rather than twice because everything here is delicate and none of it differs
  /// between the legs — the degrade-law check before the statement is built, the keyset resumed from
  /// the client's cursor, the read transaction opened and closed around exactly one statement, and
  /// the walk-dependent reading of the extra row. A second copy would be two places for those to
  /// drift apart.
  async fn page<'c, T>(
    self,
    mint: impl FnMut(Row) -> Result<T, SqlQueryError>,
  ) -> Result<Page<T, Row::Value>, SqlQueryError>
  where
    A: sqlx::Acquire<'c, Database = Db>,
  {
    let terms = self.terms();
    // The degrade law's SECOND row, read before the statement is built: a page's order lives
    // entirely in the statement, and a boundary it could not be resumed at is refused by name
    // rather than served as a sequence the next page cannot continue. The ordered scan beside this
    // one does not ask, which is the whole of the split — it mints no cursor.
    let terms = partition::<Db>(&terms).paging::<Db>()?;
    let order = SqlOrder::<Db>::new(terms)?;
    let subjects = &self.ordered.subjects;
    let keyset = self
      .position
      .cursor()
      .map(|cursor| SqlKeyset::resume_with(order, cursor, self.walk, subjects))
      .transpose()?;
    let mut statement = ordered::<Row, Db>(
      self.ordered.find.filter,
      self.ordered.find.scope,
      Ordering {
        order,
        subjects,
        keyset: keyset.as_ref(),
        values: SortValues::Projected,
      },
      self.walk,
      Some(self.window()),
      self.position.offset()?,
    )?;

    let mut held = self.ordered.find.executor.acquire().await?;
    let conn = &mut *held;
    let snapshot = self.ordered.find.snapshot;
    begin::<Db>(conn, snapshot).await?;
    let fetched = edges::<Row, Db, T>(
      conn,
      &mut statement,
      &self.ordered.order,
      terms,
      self.size as usize,
      mint,
    )
    .await;
    end::<Db>(conn, snapshot, fetched.is_ok()).await?;

    let (mut edges, more) = fetched?;
    let resumed = self.position.is_set();
    if matches!(self.walk, Walk::Backward) {
      edges.reverse();
    }
    Ok(match self.walk {
      Walk::Forward => Page::new(edges, more, resumed),
      Walk::Backward => Page::new(edges, resumed, more),
    })
  }
}

/// One row by its ID, or [`None`] where no row lives there.
///
/// # The ID is the whole parameter, and the record's `*Key` is not narrowed by that
///
/// A caller hands over one value, because one column is what names a row: the id is `UNIQUE`. The
/// lineage the record's `*Key` also carries is stored beside it and is reachable from every other
/// lane — a filter, an order, a page — so the key kept its columns and stopped being the address.
///
/// # The miss is UNIFORM
///
/// An absent row is `Ok(None)` on every path, always. polarsync answers null on one path, an error
/// on another and a logged error on a third, so a caller's handling of *not found* depends on which
/// resolver it came through — which is a fact about that codebase rather than about the data.
///
/// # Errors
///
/// A lowering refusal carried verbatim, a driver error, an id that will not cross into this
/// database's stored type, or a row that will not cross back into its record.
pub async fn get<'c, Row, Db, A>(
  executor: A,
  id: &<Row::Record as Identifiable>::Id,
  snapshot: bool,
) -> Result<Option<Row::Record>, SqlQueryError>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
  A: sqlx::Acquire<'c, Database = Db>,
{
  let statement = address::<Row, Db>(core::slice::from_ref(id))?;
  let records = run::<Row, Db, A>(executor, snapshot, statement).await?;
  Ok(records.into_iter().next())
}

/// Every ROW of `ids`, in ONE statement, hydrated — the id-gather lane.
///
/// # Rows rather than records, because the caller of this is a WIRE crossing
///
/// Every other lane here hands back records, because a record is what a query answers with. This one
/// exists for an interface's hydration, whose next hop is the member's own output object — and that
/// crossing is minted from the ROW, not from the record. Handing back a record would be a conversion
/// run to be discarded.
///
/// # The order is the ENGINE's, and [`SqlQuery::id`] is what lines it up again
///
/// A membership names a set, so the rows come back in whatever sequence the plan chose. A caller
/// that asked in an order reads each row's own id back and reorders — which is what the emitted
/// hydration does, into the union statement's own sequence.
///
/// # The bracket is the same one every interface lane takes
///
/// It opens the dialect's read transaction, or passes through where the surface already holds one —
/// see [`BeginRead`]. Handed the same `&mut Transaction` a page ran on, this gather sees exactly the
/// rows that page answered with.
///
/// # Errors
///
/// A lowering refusal carried verbatim, a driver error, or an id that will not cross into this
/// database's stored type.
pub async fn rows<'c, Row, Db, A>(
  executor: A,
  ids: &[<Row::Record as Identifiable>::Id],
) -> Result<Vec<Row>, SqlQueryError>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row>,
  Db: SqlDialect,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  Db::Arguments: sqlx::IntoArguments<Db>,
  A: sqlx::Acquire<'c, Database = Db> + BeginRead,
{
  let mut statement = address::<Row, Db>(ids)?;
  let mut held = executor.acquire().await?;
  let conn = &mut *held;
  let opened = open_read::<Db, A>(conn).await?;
  let decoded = decode::<Row, Db>(conn, &mut statement, usize::MAX).await;
  close_read::<Db>(conn, opened, decoded.is_ok()).await?;
  Ok(decoded?.0)
}

/// A PAGE over a `sortable` collection — the statement each dialect renders for one, and the walk
/// a live engine returns. Beside [`tests`], which is the three lanes' own rendering harness.
#[cfg(test)]
mod shadow_tests;
#[cfg(test)]
mod tests;