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
//! The clause machine: a `SELECT` under construction whose current CLAUSE is a type parameter.
//!
//! [`ClauseTransition`] enumerates the legal edges, and the only bound a transition method carries
//! about the edge it walks is `S: ClauseTransition<Next>` — that bound IS "this edge is legal", so
//! an illegal edge is a MISSING IMPL and calling it is a compile error. `WHERE` cannot return to
//! `FROM`; `LIMIT` is reachable only from `ORDER BY`; `OFFSET` only from `LIMIT`. There is therefore
//! no runtime clause-order check anywhere below, and nothing to test for one — the compile-fail
//! fixtures in `tests/clause_order/` are where those refusals are pinned.
//!
//! # The typestate and the flags answer different questions
//!
//! Two `bool`s survive as runtime state, and that is correct rather than an unfinished typestate:
//! the type answers *may I enter `WHERE`*, the flag answers *is this the first term — emit the
//! clause keyword — or a later one — emit the separator*. **The Nth visit to a state is not a new
//! state**, so encoding the count in the type would say something false about the machine.
//!
//! Neither flag counts PREDICATES, and there is no third one that does: every conjunct in a
//! statement's `WHERE` — a comparison's, and the ` IN ( SELECT … )` a subquery opens — is opened
//! through one [`SqlConjunction`](super::SqlConjunction), which holds the clause keyword as its
//! lead and pushes it on the first conjunct anything writes. It is the only party that knows
//! whether any predicate rendered at all, so [`begin_where`](QueryBuilder::begin_where) renders
//! nothing.
//!
//! # The holder
//!
//! `QB` is the holder of the live [`sqlx::QueryBuilder`]: by default the builder itself, and — via
//! the std blanket `BorrowMut<T> for &mut T` — a `&mut sqlx::QueryBuilder<Db>` a caller already
//! owns, which [`QueryBuilder::select_into`] is the way into. It is also how a subquery nests: the
//! holder of a nested statement is the accumulator that opened its conjunct
//! (see [`SqlConjunction::sub_select`](super::SqlConjunction::sub_select)), moved in as an
//! [`OpenSubquery`](super::OpenSubquery), and [`finalize`](QueryBuilder::finalize) closes the
//! bracket and hands the accumulator back with its count untouched.
//!
//! # Which identifiers this module brackets, and which stay the caller's
//!
//! An ordering column and the field a subquery tests are plain NAMES: each arrives as a
//! [`FieldName`] and is bracketed here through [`quote_ident`](super::quote_ident), the convention
//! an identifier reaching [`ComplexComparison::apply`](crate::ComplexComparison::apply) already
//! follows. The bracketing DOUBLES the dialect's quote character, and that half is why it is a seam
//! rather than each caller's own business: a second implementation that omitted the doubling would
//! let a name close its own quoting, which is the whole of what the escaping closes. So a caller
//! assembling an ordering — a generated `*OrderBy` above all — has no escaping rule of its own to
//! get right.
//!
//! The other parameters are still the caller's, each for a reason of its own rather than by
//! omission:
//!
//! - [`push_field`](QueryBuilder::push_field) takes an EXPRESSION and not a name. `*` and
//!   `count(*)` are select fields, and bracketing either would name a column that. What separates
//!   the two is a projection type, and none exists.
//! - [`from`](QueryBuilder::from) takes a TABLE, and [`FieldName`] is the wrong noun for one. Which
//!   type a table's name should be is settled by DDL emission, where `CREATE TABLE` needs the same
//!   bracketing and the choice is between a `TableName` beside this type and a broader name for it.
//!   Answering it here would answer it from the one caller that does not need the answer.
//! - [`order_by_with`](QueryBuilder::order_by_with) takes an ordering term's SUBJECT and hands the
//!   caller the open buffer, because a subject that is a correlated subquery has no name to
//!   bracket. Whatever names it holds INSIDE are bracketed by whatever renders them — this same
//!   seam, one statement down. The two forms above render THROUGH it, so a term written as a name
//!   is bracketed here whichever of them a caller writes. A subject that is a whole SUB-SELECT has
//!   one thing more that is not a name — the statement's own pair of parentheses — and no line in
//!   this module writes it: [`order_by_sub_select`](QueryBuilder::order_by_sub_select) reaches the
//!   one place that does, a [`SubjectSlot`](super::SubjectSlot).
//!
//! Every VALUE — this module's and a comparison's alike — goes through `push_bind` and is never
//! interpolated.

use core::{
  borrow::{Borrow, BorrowMut},
  marker::PhantomData,
};

use super::{OpenSubquery, QuoteIdent, SqlConjunction, quote_ident};
use crate::FieldName;

/// A legal clause-order edge `Self → Next`.
///
/// The complete set of impls in this module is the grammar of a well-formed statement, written as a
/// list rather than as a check: adding an edge is one line, and removing one turns every call site
/// that walked it into `E0277`.
pub trait ClauseTransition<Next> {}

/// The `SELECT` list. Accepts another field, or the table that closes it.
pub struct SelectClause;
/// The table is named. The statement may take predicates, be ordered, or end here.
pub struct FromClause;
/// The predicate list. Each conjunct is one visit, and the visit COUNT is a runtime flag rather
/// than a state — held by the [`SqlConjunction`](super::SqlConjunction) every predicate is rendered
/// through, this type holding none of its own.
pub struct WhereClause;
/// The ordering terms. Like [`WhereClause`], each term is one visit and the count is a flag.
pub struct OrderByClause;
/// The row ceiling.
pub struct LimitClause;
/// The row skip.
pub struct OffsetClause;
/// The terminal. Only a statement that could be executed has an edge to it, so a half-formed one
/// cannot be handed back.
pub struct Finalize;

impl ClauseTransition<SelectClause> for SelectClause {}
impl ClauseTransition<FromClause> for SelectClause {}
impl ClauseTransition<WhereClause> for FromClause {}
impl ClauseTransition<WhereClause> for WhereClause {}
// A statement with no predicate is an ordinary one, so ordering does not go through `WHERE`; and a
// keyset cursor is `(sort value, key)`, so a second ordering term is required rather than a
// refinement — the sort value repeats, and a cursor that cannot break the tie skips or repeats rows
// at the page boundary.
impl ClauseTransition<OrderByClause> for FromClause {}
impl ClauseTransition<OrderByClause> for WhereClause {}
impl ClauseTransition<OrderByClause> for OrderByClause {}
// A row ceiling over an UNORDERED result is reachable, and that is a ruling rather than a relaxation.
// The edge was absent while the only consumer of `LIMIT` was a page, where a ceiling without an
// order really does name arbitrary rows; the query layer's second lane is *any N rows* asked for
// honestly — `SELECT … LIMIT ?` with no `ORDER BY`, no cursor and no connection — and refusing it
// here would have left a caller wanting one to fetch the whole table and truncate in memory. What
// still cannot be spelled is a page: a cursor over an unordered set compares values against nothing,
// and the party that refuses that is the query builder's typestate, where the order is written.
impl ClauseTransition<LimitClause> for FromClause {}
impl ClauseTransition<LimitClause> for WhereClause {}
impl ClauseTransition<LimitClause> for OrderByClause {}
impl ClauseTransition<OffsetClause> for LimitClause {}
impl ClauseTransition<Finalize> for FromClause {}
impl ClauseTransition<Finalize> for WhereClause {}
impl ClauseTransition<Finalize> for OrderByClause {}
impl ClauseTransition<Finalize> for LimitClause {}
impl ClauseTransition<Finalize> for OffsetClause {}

/// One allocation for a statement of ordinary size, so the clause walk does not grow the buffer
/// clause by clause.
const STATEMENT_CAPACITY: usize = 1024;

/// A `SELECT` under construction: its current clause is `Op`, its dialect is `Db`, and `QB` holds
/// the live [`sqlx::QueryBuilder`] the text lands in.
///
/// The builder is a VALUE that passes through each layer rather than a `&mut` written into. That is
/// what makes nesting unbounded — a nested statement's holder is its parent — and it carries the
/// exclusivity the borrow used to: two accumulators over one buffer would interleave placeholders
/// and arguments, and you cannot hold two of these because you moved the one you had.
///
/// # No lifetime
///
/// sqlx 0.9's own `QueryBuilder` has none — it dropped the `'args` parameter that a builder written
/// against an earlier sqlx had to carry — so nothing here forces one, and a parameter nothing
/// forces is a wart every later signature would have to spell. The lifetime slot a borrowing
/// backend needs survives one level up, on the backend's builder associated type; this type stops
/// claiming one it does not use.
#[must_use]
pub struct QueryBuilder<Op, Db, QB = sqlx::QueryBuilder<Db>> {
  inner: QB,
  pushed_select_field: bool,
  pushed_order_by: bool,
  // `fn() -> Op` / `fn() -> Db` rather than bare parameters, so neither marker contributes an
  // auto-trait or variance obligation — the same phantom `comparison_kind!` writes for its own
  // shape and dialect markers.
  //
  // `Db` needs a marker of its own even though it names the default holder: a parameter that
  // appears only in another parameter's DEFAULT is unused (`E0392`).
  state: PhantomData<fn() -> Op>,
  db: PhantomData<fn() -> Db>,
}

impl<Db: sqlx::Database> QueryBuilder<SelectClause, Db> {
  /// Open a statement in a buffer of its own: `SELECT `, ready for its first field.
  pub fn select() -> Self {
    Self::select_into(sqlx::QueryBuilder::new(String::with_capacity(
      STATEMENT_CAPACITY,
    )))
  }
}

impl<Db, QB> QueryBuilder<SelectClause, Db, QB>
where
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  /// Open a statement inside a builder someone else owns: push `SELECT ` into `holder` and walk the
  /// clauses from there.
  ///
  /// [`select`](QueryBuilder::select) allocates its own holder; this is the same constructor over
  /// any other. Two holders matter: `&mut sqlx::QueryBuilder<Db>` — admitted by the std blanket
  /// `BorrowMut<T> for &mut T` — for a statement rendering into a buffer the caller already has,
  /// and [`OpenSubquery`](super::OpenSubquery) for the nested statement
  /// [`SqlConjunction::sub_select`](super::SqlConjunction::sub_select) opens, which is this same
  /// call one line down.
  ///
  /// Whatever brackets a nested statement is the OPENER's. `sub_select` pairs its ` IN ( ` with the
  /// [`finalize`](QueryBuilder::finalize) that closes it; a caller opening a bracket around a
  /// `&mut` holder closes that one itself, because nothing is holding this statement for a
  /// `finalize` to hand back.
  pub fn select_into(mut holder: QB) -> Self {
    holder.borrow_mut().push("SELECT ");
    Self {
      inner: holder,
      pushed_select_field: false,
      pushed_order_by: false,
      state: PhantomData,
      db: PhantomData,
    }
  }
}

impl<Op, Db, QB> Borrow<sqlx::QueryBuilder<Db>> for QueryBuilder<Op, Db, QB>
where
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  #[inline]
  fn borrow(&self) -> &sqlx::QueryBuilder<Db> {
    self.inner.borrow()
  }
}

/// The impl that lets a builder be another builder's holder, and so lets a subquery nest.
impl<Op, Db, QB> BorrowMut<sqlx::QueryBuilder<Db>> for QueryBuilder<Op, Db, QB>
where
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  #[inline]
  fn borrow_mut(&mut self) -> &mut sqlx::QueryBuilder<Db> {
    self.inner.borrow_mut()
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB> {
  /// Move along a legal edge without rendering anything.
  ///
  /// Every transition method below ends in this call, which is where the one bound that makes the
  /// edge legal is discharged — so a method renders its clause and then asks the table whether it
  /// was allowed to.
  #[inline]
  fn advance<Next>(self) -> QueryBuilder<Next, Db, QB>
  where
    S: ClauseTransition<Next>,
  {
    QueryBuilder {
      inner: self.inner,
      pushed_select_field: self.pushed_select_field,
      pushed_order_by: self.pushed_order_by,
      state: PhantomData,
      db: PhantomData,
    }
  }
}

impl<Op, Db, QB> QueryBuilder<Op, Db, QB>
where
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  /// The underlying builder, for rendering a predicate between clause transitions — bind operands
  /// with `push_bind`, push identifiers the caller has already validated.
  #[inline]
  pub fn inner_mut(&mut self) -> &mut sqlx::QueryBuilder<Db> {
    self.inner.borrow_mut()
  }

  fn push_select_field(&mut self) {
    if self.pushed_select_field {
      self.inner.borrow_mut().push(", ");
    }
    self.pushed_select_field = true;
  }

  fn push_order_by(&mut self) {
    if self.pushed_order_by {
      self.inner.borrow_mut().push(", ");
    } else {
      self.inner.borrow_mut().push(" ORDER BY ");
    }
    self.pushed_order_by = true;
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB>
where
  S: ClauseTransition<SelectClause>,
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  /// Append one comma-separated `SELECT` field. `name` is the caller's rendered column expression
  /// (`"col"`, `*`, `count(*)`) and is pushed verbatim.
  pub fn push_field(self, name: &str) -> QueryBuilder<SelectClause, Db, QB> {
    self.push_field_with(|qb| {
      qb.push(name);
    })
  }

  /// Open the next `SELECT` field — its separator already pushed — and write it in PIECES.
  ///
  /// [`push_field`](Self::push_field)'s counterpart for a field that is an EXPRESSION assembled out
  /// of several rendered names: a correlated aggregate and an `<expression> AS <alias>` projection
  /// are several pushes each, and joining them into a `String` first is an allocation whose only
  /// cause is that this seam was missing. It is
  /// [`SqlConjunction::open`](super::SqlConjunction::open) one clause up — that hands back the
  /// buffer with a conjunct opened, this one with a field opened — and the SEPARATOR stays this
  /// type's either way, which is what a caller assembling a field cannot then get wrong.
  pub fn push_field_with(
    mut self,
    field: impl FnOnce(&mut sqlx::QueryBuilder<Db>),
  ) -> QueryBuilder<SelectClause, Db, QB> {
    self.push_select_field();
    field(self.inner.borrow_mut());
    self.advance()
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB>
where
  S: ClauseTransition<FromClause>,
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  /// Push ` FROM <table>`, `table` being the caller's already-quoted identifier.
  ///
  /// A table is not a field, so this does not take the [`FieldName`] an ordering term does. Which
  /// type it should take is DDL emission's to settle — see the module note.
  pub fn from(mut self, table: &str) -> QueryBuilder<FromClause, Db, QB> {
    {
      let qb = self.inner.borrow_mut();
      qb.push(" FROM ");
      qb.push(table);
    }
    self.advance()
  }
}

impl<S: ClauseTransition<WhereClause>, Db, QB> QueryBuilder<S, Db, QB> {
  /// Enter the predicate list, rendering NOTHING.
  ///
  /// It is a pure typestate move, and the empty body is the point rather than an omission: the
  /// clause keyword belongs to the [`SqlConjunction`](super::SqlConjunction) the predicates are
  /// threaded, which pushes it on its first conjunct. This method runs before the first comparison
  /// is asked for anything, so a keyword pushed here is a keyword pushed whether or not a predicate
  /// follows — and `SELECT … FROM "t" WHERE` is what "no filter given" would render.
  ///
  /// The bounds say so too: a method that renders nothing needs neither a dialect nor a way to
  /// reach the buffer. What it still needs is the edge, and that is the whole of what it asks for.
  ///
  /// The way in is [`inner_mut`](Self::inner_mut) — build a `SqlConjunction` over it, thread every
  /// comparison through that one accumulator, and drop it before the next clause transition.
  #[inline]
  pub fn begin_where(self) -> QueryBuilder<WhereClause, Db, QB> {
    self.advance()
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB>
where
  S: ClauseTransition<OrderByClause>,
  Db: sqlx::Database + QuoteIdent,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  /// Push one ordering term — ` ORDER BY <column> ASC|DESC` the first time, `, <column> …` after —
  /// `column` being a plain name this method brackets for the dialect through
  /// [`quote_ident`](super::quote_ident).
  ///
  /// The second term is what a keyset cursor needs rather than a refinement of the first: a cursor
  /// is `(sort value, key)`, because the sort value repeats and a cursor that cannot break the tie
  /// skips or repeats rows at the page boundary.
  ///
  /// Which separator to push is a runtime flag for the same reason
  /// [`begin_where`](Self::begin_where)'s is: the Nth visit to a state is not a new state.
  ///
  /// A term over a NULLABLE column has one thing more to say, and
  /// [`order_by_nulls`](Self::order_by_nulls) is where it says it — this one states no position,
  /// which is exactly right for a `NOT NULL` column and not a default for the other kind.
  pub fn order_by(self, column: &FieldName, desc: bool) -> QueryBuilder<OrderByClause, Db, QB> {
    self.order_by_nulls(column, desc, None)
  }

  /// [`order_by`](Self::order_by) with the position of SQL `NULL` stated —
  /// ` ORDER BY <column> ASC NULLS FIRST` and its three siblings.
  ///
  /// # `None` is "state nothing", and it is not a default
  ///
  /// It is the right answer twice, and both times because there is nothing to say rather than
  /// because a position was omitted. A `NOT NULL` column holds no `NULL`, so every dialect's own
  /// default and the framework's pinned position agree vacuously — and stating a clause there is
  /// noise that costs an index match on the one dialect that reads it. A dialect whose own default
  /// already IS the pinned position has nothing to add either; see
  /// [`NullOrdering`](super::NullOrdering), where that is two of the three.
  ///
  /// So the caller that knows both facts decides, and this method renders what it is told. That
  /// caller is [`SqlOrder`](super::SqlOrder), which holds the order's nullability and the dialect's
  /// answer together and is therefore the one party that can be asked whether the position is
  /// expressible at all.
  pub fn order_by_nulls(
    self,
    column: &FieldName,
    desc: bool,
    nulls: Option<super::NullPosition>,
  ) -> QueryBuilder<OrderByClause, Db, QB> {
    self.order_by_with(
      |qb| {
        qb.push(quote_ident::<Db>(column));
      },
      desc,
      nulls,
    )
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB>
where
  S: ClauseTransition<OrderByClause>,
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  /// Open the next ordering term — its separator already pushed — and write the term's SUBJECT in
  /// PIECES, this method contributing the ` ASC`/` DESC` and the `NULL` position after it.
  ///
  /// It is [`push_field_with`](Self::push_field_with) one clause down, and it is the base
  /// [`order_by`](Self::order_by) and [`order_by_nulls`](Self::order_by_nulls) render their column
  /// through. A subject that is a correlated scalar subquery is a nested STATEMENT — several
  /// pushes, and binds of its own — so rendering it into a `String` first would allocate and then
  /// have nowhere to put the binds, a placeholder being the one thing text cannot carry. The buffer
  /// arrives open, and [`select_into`](Self::select_into) wraps it as it wraps any other holder.
  ///
  /// What stays this type's is what a caller writing one term cannot see: the leading ` ORDER BY `
  /// or the `, ` before this term, and the direction and `NULL` position after it.
  ///
  /// The bounds are the pair's less one, and the missing one is the point: nothing here pushes an
  /// identifier, so nothing here asks for [`QuoteIdent`](super::QuoteIdent).
  ///
  /// # This is the RAW channel: the caller owns every bracket in it
  ///
  /// Whatever brackets a nested statement is the opener's, exactly as
  /// [`SqlConjunction::sub_select`](super::SqlConjunction::sub_select) pairs its own — so this
  /// method pushes none. A subject that omits them is not a tidiness question:
  /// `ORDER BY SELECT … DESC` is a syntax error on SQLite 3.51.0, PostgreSQL 17.10 and MySQL
  /// 8.4.11 alike, measured.
  ///
  /// A caller writing a whole sub-select therefore wants the twin —
  /// [`order_by_sub_select`](Self::order_by_sub_select) — which takes the BODY and reaches the one
  /// place that pairs the parentheses. An order rendered through the
  /// [`OrderSubjects`](super::OrderSubjects) seam reaches it too, so neither route is where a
  /// remembered bracket lives.
  ///
  /// # There is no `_with` twin of [`order_by`](Self::order_by), and the pair above is why
  ///
  /// `order_by` exists to spare a `NOT NULL` term's call site the word `None`. A caller already
  /// writing its subject as a closure is spared nothing by a fourth method, so the three are one
  /// chain rather than four siblings.
  pub fn order_by_with(
    mut self,
    subject: impl FnOnce(&mut sqlx::QueryBuilder<Db>),
    desc: bool,
    nulls: Option<super::NullPosition>,
  ) -> QueryBuilder<OrderByClause, Db, QB> {
    self.push_order_by();
    {
      let qb = self.inner.borrow_mut();
      subject(qb);
      qb.push(if desc { " DESC" } else { " ASC" });
      if let Some(nulls) = nulls {
        qb.push(nulls.as_str());
      }
    }
    self.advance()
  }

  /// [`order_by_with`](Self::order_by_with) for a term whose subject is a whole SUB-SELECT: the
  /// callback writes the statement's BODY and this method pairs the brackets around it.
  ///
  /// The contract is the other one's otherwise — the raw buffer arrives open, so the body is
  /// several pushes and its binds are live, and [`select_into`](Self::select_into) re-enters the
  /// clause machine over the same buffer exactly as it does there.
  ///
  /// # The pair is not this method's own, and that is what makes it ONE pair
  ///
  /// It renders through a [`SubSelect`](super::SubjectShape::SubSelect)
  /// [`SubjectSlot`](super::SubjectSlot), which is the single line in this crate that spells the
  /// wrapping parentheses. An ORDER written by the [`OrderSubjects`](super::OrderSubjects) seam
  /// reaches that same line through its own slot, so a subject rendered by hand here and the same
  /// subject rendered by a provider cannot be bracketed differently.
  ///
  /// What the measurement bought is stated there in full: a subject that drops its brackets is a
  /// syntax error in this clause on all three engines, which is loud, and the same subject in the
  /// keyset that PAGES this order is absorbed as the start of a scalar subquery — an empty page with
  /// no error at all on two of them.
  pub fn order_by_sub_select(
    self,
    body: impl FnOnce(&mut sqlx::QueryBuilder<Db>),
    desc: bool,
    nulls: Option<super::NullPosition>,
  ) -> QueryBuilder<OrderByClause, Db, QB> {
    self.order_by_with(
      |qb| super::SubjectSlot::new(qb, super::SubjectShape::SubSelect).write(body),
      desc,
      nulls,
    )
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB>
where
  S: ClauseTransition<LimitClause>,
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  i64: sqlx::Type<Db>,
{
  /// Push ` LIMIT ?` and bind the value, clamped to [`i64::MAX`] — SQL's `LIMIT` binds a signed
  /// integer, so a `u64` past the ceiling saturates rather than overflowing.
  pub fn limit(mut self, limit: u64) -> QueryBuilder<LimitClause, Db, QB> {
    {
      let qb = self.inner.borrow_mut();
      qb.push(" LIMIT ");
      qb.push_bind(clamp_to_i64(limit));
    }
    self.advance()
  }
}

impl<S, Db, QB> QueryBuilder<S, Db, QB>
where
  S: ClauseTransition<OffsetClause>,
  Db: sqlx::Database,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  i64: sqlx::Type<Db>,
{
  /// Push ` OFFSET ?` and bind the value, clamped like [`limit`](Self::limit)'s.
  pub fn offset(mut self, offset: u64) -> QueryBuilder<OffsetClause, Db, QB> {
    {
      let qb = self.inner.borrow_mut();
      qb.push(" OFFSET ");
      qb.push_bind(clamp_to_i64(offset));
    }
    self.advance()
  }
}

impl<S, Db> QueryBuilder<S, Db>
where
  S: ClauseTransition<Finalize>,
  Db: sqlx::Database,
{
  /// Hand back the finished statement's builder.
  ///
  /// Reachable only from a state with a `Finalize` edge, so a `SELECT` with no table — or a
  /// statement whose subquery is still open — cannot be executed.
  #[inline]
  pub fn finalize(self) -> sqlx::QueryBuilder<Db> {
    self.inner
  }
}

impl<'q, S, Db> QueryBuilder<S, Db, OpenSubquery<'q, Db>>
where
  S: ClauseTransition<Finalize>,
  Db: sqlx::Database,
{
  /// Close this subquery's ` )` and return the accumulator that opened it, its conjunct count
  /// intact — so the conjunct AFTER the subquery joins with ` AND ` rather than pushing the lead a
  /// second time.
  ///
  /// That count is the whole reason the accumulator is moved in rather than borrowed, and it is
  /// ONE count: [`SqlConjunction::sub_select`](super::SqlConjunction::sub_select) opened this
  /// subquery's conjunct through the same counter every other conjunct goes through, so a subquery
  /// can sit anywhere in a predicate list.
  ///
  /// This is the same name as the outer [`finalize`](QueryBuilder::finalize) and a different
  /// method: the two impls are disjoint in the holder, so which one a call resolves to is decided
  /// by what is holding this builder.
  #[inline]
  pub fn finalize(mut self) -> SqlConjunction<'q, Db> {
    self.inner_mut().push(" )");
    self.inner.0
  }
}

/// `LIMIT` and `OFFSET` bind a SIGNED integer, so a count past the ceiling saturates: a wrap would
/// silently ask for a different page, and a panic would refuse a query the caller can still answer.
#[inline]
fn clamp_to_i64(value: u64) -> i64 {
  i64::try_from(value).unwrap_or(i64::MAX)
}

#[cfg(test)]
mod tests;