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
//! The clause machine's rendering.
//!
//! Asserting on the rendered text is right HERE and nowhere else in this family: the builder's
//! whole job is to produce that text, so the text is the observable. A comparison's tests assert on
//! the operand it holds, because two encodings of one operand render the same string.
//!
//! Gated on a dialect: a rendering is a thing a dialect does, and with the family root on and no
//! dialect there is nothing to render into. The clause WALK is asserted under ONE of them, because
//! the transition table is every dialect's; the BRACKET is not one rule, so the three tests that
//! read a rendered identifier take a dialect each.
#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]

use super::{QueryBuilder, SelectClause};
use crate::{
  FieldName,
  comparison::sql::{QuoteIdent, SqlConjunction},
};

/// The conjunct separator belongs to NEITHER conjunct — the first opens the clause and every later
/// one joins to it — and both are the same state. So the bit that tells them apart is a runtime
/// flag: the Nth visit to a state is not a new state.
///
/// It is the ACCUMULATOR's flag, and the keyword is its lead: `begin_where` runs before the first
/// predicate is asked for anything and so cannot know whether one follows.
#[cfg(feature = "sqlite")]
#[test]
fn the_where_clause_opens_once_and_joins_after() {
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where();
  {
    let mut conjunction = SqlConjunction::new(qb.inner_mut());
    conjunction.open().push("\"a\" = ").push_bind(1i64);
    conjunction.open().push("\"b\" = ").push_bind(2i64);
    conjunction.open().push("\"c\" = ").push_bind(3i64);
  }

  assert_eq!(
    qb.finalize().into_string(),
    "SELECT \"id\" FROM \"t\" WHERE \"a\" = ? AND \"b\" = ? AND \"c\" = ?"
  );
}

/// Entering the predicate list renders NOTHING, so a statement that turns out to have no predicate
/// carries no keyword — and the `WhereClause` self-loop is still an edge, walked here twice to no
/// effect.
#[cfg(feature = "sqlite")]
#[test]
fn entering_the_predicate_list_renders_nothing() {
  let sql = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where()
    .begin_where()
    .finalize()
    .into_string();

  assert_eq!(sql, "SELECT \"id\" FROM \"t\"");
}

/// The whole walk, in the one order the transition table admits — and the `SELECT` list's own
/// self-loop, which separates with a comma where the `WHERE` self-loop separates with a keyword.
#[cfg(feature = "sqlite")]
#[test]
fn the_clause_walk_renders_in_transition_order() {
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .push_field("\"n\"")
    .from("\"t\"")
    .begin_where();
  {
    SqlConjunction::new(qb.inner_mut())
      .open()
      .push("\"a\" = ")
      .push_bind(1i64);
  }

  let sql = qb
    .order_by(FieldName::new("n"), true)
    .limit(10)
    .offset(20)
    .finalize()
    .into_string();

  assert_eq!(
    sql,
    "SELECT \"id\", \"n\" FROM \"t\" WHERE \"a\" = ? ORDER BY \"n\" DESC LIMIT ? OFFSET ?"
  );
}

/// A keyset cursor is `(sort value, key)`, because a sort value REPEATS: a cursor that cannot break
/// the tie skips or repeats rows at the page boundary. So a second ordering term is not a
/// refinement, and `ORDER BY` needs the same self-loop `WHERE` has — with a comma where `WHERE`
/// joins with a keyword, and the same flag deciding which.
#[cfg(feature = "sqlite")]
#[test]
fn two_ordering_terms_join_with_a_comma() {
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where();
  {
    SqlConjunction::new(qb.inner_mut())
      .open()
      .push("\"a\" = ")
      .push_bind(1i64);
  }

  let sql = qb
    .order_by(FieldName::new("score"), true)
    .order_by(FieldName::new("id"), false)
    .finalize()
    .into_string();

  assert_eq!(
    sql,
    "SELECT \"id\" FROM \"t\" WHERE \"a\" = ? ORDER BY \"score\" DESC, \"id\" ASC"
  );
}

/// An ordering term may be an EXPRESSION, and a whole nested statement is one: the subject is
/// written into the buffer this method hands out, so a correlated subquery is assembled where it
/// lands rather than joined into a `String` first.
///
/// Two things the text alone cannot say are asserted beside it. The subquery's BINDS join the outer
/// statement's list in render order — the predicate's first, the ordering term's second, the
/// ceiling's last — because the nested statement writes into the same buffer and the same list; and
/// the count says all three arrived, where three `?` read the same whatever went into them.
///
/// The `NULL` position is stated here too, because this method renders what it is told — it is the
/// base the two named forms go through rather than a third spelling beside them.
#[cfg(feature = "sqlite")]
#[test]
fn an_ordering_term_can_be_a_correlated_subquery() {
  use sqlx::Execute;

  use crate::{
    Carrier,
    comparison::sql::{NullPosition, tests::Probe},
  };

  let bound = core::cell::RefCell::new(Vec::new());
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"media\"")
    .begin_where();
  {
    let mut accumulator = SqlConjunction::new(qb.inner_mut());
    let slot = accumulator.open();
    slot.push("\"kind\" = ");
    Probe {
      value: 1,
      bound: &bound,
    }
    .push_bind(slot);
  }

  let mut statement = qb
    .order_by_with(
      |qb| {
        // The RAW channel, so the brackets are this caller's — which is what makes this a scalar
        // subquery rather than a syntax error — and the nested statement is opened over the very
        // buffer handed in.
        qb.push("(");
        let mut nested = QueryBuilder::<SelectClause, sqlx::Sqlite, _>::select_into(&mut *qb)
          .push_field("\"title\"")
          .from("\"keyframe\"")
          .begin_where();
        {
          let mut correlation = SqlConjunction::new(nested.inner_mut());
          let slot = correlation.open();
          slot.push("\"id\" = ");
          Probe {
            value: 2,
            bound: &bound,
          }
          .push_bind(slot);
        }
        qb.push(")");
      },
      true,
      Some(NullPosition::Last),
    )
    .order_by(FieldName::new("id"), false)
    .limit(10)
    .finalize();

  let mut built = statement.build();
  let binds = match built.take_arguments() {
    Ok(Some(arguments)) => sqlx::Arguments::len(&arguments),
    Ok(None) | Err(_) => 0,
  };

  assert_eq!(
    built.sql().as_str(),
    "SELECT \"id\" FROM \"media\" WHERE \"kind\" = ? \
     ORDER BY (SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) DESC NULLS LAST, \"id\" ASC \
     LIMIT ?"
  );
  assert_eq!(*bound.borrow(), [1, 2]);
  assert_eq!(binds, 3);
}

/// Two expression terms join with the comma a column term joins with, because the separator is the
/// clause machine's whichever form wrote the term — a subject that had to know whether it was the
/// first would be a subject deciding a thing it cannot see.
#[cfg(feature = "sqlite")]
#[test]
fn two_expression_terms_join_with_a_comma() {
  let sql = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("*")
    .from("t")
    .order_by_with(
      |qb| {
        qb.push("(SELECT 1)");
      },
      false,
      None,
    )
    .order_by_with(
      |qb| {
        qb.push("(SELECT 2)");
      },
      true,
      None,
    )
    .finalize()
    .into_string();

  assert_eq!(
    sql,
    "SELECT * FROM t ORDER BY (SELECT 1) ASC, (SELECT 2) DESC"
  );
}

/// The sub-select form renders what the expression form renders when the caller remembers the
/// pair — and this asserts the two texts are ONE, which is the whole claim of moving the pair.
///
/// The direction and the `NULL` position land OUTSIDE the brackets, where the expression form puts
/// them, so a term written either way sorts the same. The body has BINDS, which is the other half of
/// the callback contract carrying over: they join the outer statement's list in render order.
#[cfg(feature = "sqlite")]
#[test]
fn a_sub_select_term_pairs_the_brackets_the_expression_form_leaves_to_its_caller() {
  use sqlx::Execute;

  use crate::{
    Carrier,
    comparison::sql::{NullPosition, tests::Probe},
  };

  let bound = core::cell::RefCell::new(Vec::new());
  let mut statement = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("*")
    .from("t")
    .order_by_sub_select(
      |qb| {
        qb.push("SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ");
        Probe {
          value: 4,
          bound: &bound,
        }
        .push_bind(qb);
      },
      true,
      Some(NullPosition::Last),
    )
    .order_by(FieldName::new("id"), false)
    .finalize();

  let built = statement.build();

  assert_eq!(
    built.sql().as_str(),
    "SELECT * FROM t \
     ORDER BY (SELECT \"title\" FROM \"keyframe\" WHERE \"id\" = ?) DESC NULLS LAST, \"id\" ASC"
  );
  assert_eq!(*bound.borrow(), [4]);
}

/// A column term IS the expression form with its name bracketed on the way in, and this renders both
/// spellings of one order to say so.
///
/// It is the assertion the delegation is worth having: `order_by` and `order_by_nulls` push nothing
/// of their own beyond [`quote_ident`], so there is no second rendering of a direction or of a
/// separator that could drift from this one.
#[cfg(feature = "sqlite")]
#[test]
fn a_column_term_is_the_expression_form_with_its_name_bracketed() {
  use crate::comparison::sql::quote_ident;

  let named = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("*")
    .from("t")
    .order_by(FieldName::new("title"), true)
    .order_by(FieldName::new("id"), false)
    .finalize()
    .into_string();

  let written = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("*")
    .from("t")
    .order_by_with(
      |qb| {
        qb.push(quote_ident::<sqlx::Sqlite>(FieldName::new("title")));
      },
      true,
      None,
    )
    .order_by_with(
      |qb| {
        qb.push(quote_ident::<sqlx::Sqlite>(FieldName::new("id")));
      },
      false,
      None,
    )
    .finalize()
    .into_string();

  assert_eq!(named, "SELECT * FROM t ORDER BY \"title\" DESC, \"id\" ASC");
  assert_eq!(named, written);
}

/// Ordering does not require a predicate to have been pushed first: `FROM → ORDER BY` is an
/// ordinary statement, and without that edge every ordered query would have to invent a `WHERE`.
#[cfg(feature = "sqlite")]
#[test]
fn a_statement_with_no_predicate_can_still_be_ordered() {
  let sql = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .order_by(FieldName::new("id"), false)
    .limit(10)
    .finalize()
    .into_string();

  assert_eq!(sql, "SELECT \"id\" FROM \"t\" ORDER BY \"id\" ASC LIMIT ?");
}

/// A row ceiling does not require an order either, and both ways in are walked here: straight from
/// the table, and from a predicate list.
///
/// It is the query layer's UNORDERED lane — *any N rows*, asked for honestly, with no `ORDER BY`, no
/// cursor and no connection. The edge was once absent on the ground that such a ceiling names
/// arbitrary rows, which is true and is what the caller asked for; what remains unspellable is a
/// PAGE without an order, and that is refused by the query builder's typestate rather than by this
/// table.
#[cfg(feature = "sqlite")]
#[test]
fn an_unordered_statement_can_still_be_limited() {
  let bare = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .limit(10)
    .finalize()
    .into_string();

  assert_eq!(bare, "SELECT \"id\" FROM \"t\" LIMIT ?");

  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"t\"")
    .begin_where();
  {
    SqlConjunction::new(qb.inner_mut())
      .open()
      .push("\"a\" = ")
      .push_bind(1i64);
  }

  assert_eq!(
    qb.limit(10).finalize().into_string(),
    "SELECT \"id\" FROM \"t\" WHERE \"a\" = ? LIMIT ?"
  );
}

/// A subquery is the same walk one level down, and the accumulator that opened it comes back with
/// its count intact: it had already opened a conjunct to hold the subquery, so the conjunct after
/// the subquery joins with ` AND ` rather than pushing the lead a second time.
///
/// The SECOND `sub_select` is what pins that — a `finalize` that handed back a fresh accumulator
/// would render ` WHERE ` here — and `written()` reads the same count directly, so the guard does
/// not rest on the text alone.
///
/// The nested `WHERE` is the inner statement's own, which is why the rendering holds two of them
/// and neither is a repeat of the other.
#[cfg(feature = "sqlite")]
#[test]
fn a_sub_select_nests_a_walk_and_gives_the_accumulator_back() {
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"parent\"")
    .begin_where();
  {
    let mut inner = SqlConjunction::new(qb.inner_mut())
      .sub_select(FieldName::new("child_id"))
      .push_field("\"id\"")
      .from("\"child\"")
      .begin_where();
    {
      SqlConjunction::new(inner.inner_mut())
        .open()
        .push("\"kind\" = ")
        .push_bind(7i64);
    }

    let accumulator = inner.finalize();
    assert_eq!(accumulator.written(), 1);

    let accumulator = accumulator
      .sub_select(FieldName::new("tag_id"))
      .push_field("\"id\"")
      .from("\"tag\"")
      .finalize();
    assert_eq!(accumulator.written(), 2);
  }

  let sql = qb.finalize().into_string();
  assert_eq!(
    sql,
    "SELECT \"id\" FROM \"parent\" WHERE \"child_id\" IN ( SELECT \"id\" FROM \"child\" \
     WHERE \"kind\" = ? ) AND \"tag_id\" IN ( SELECT \"id\" FROM \"tag\" )"
  );
  assert_eq!(sql.matches("WHERE").count(), 2);
}

/// A subquery is an ORDINARY conjunct, so it may sit anywhere in a predicate list: the plain
/// conjunct here opens the clause and the subquery after it joins with ` AND `.
///
/// This is the order that the count deciding the separator makes expressible. A subquery opened
/// from the clause machine kept a count of its own that no accumulator could read, so whichever of
/// the two wrote second had to be told what to lead with — and only the accumulator can be told.
#[cfg(feature = "sqlite")]
#[test]
fn a_sub_select_joins_a_clause_a_plain_conjunct_opened() {
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"parent\"")
    .begin_where();
  {
    let mut accumulator = SqlConjunction::new(qb.inner_mut());
    accumulator.open().push("\"z\" = ").push_bind(1i64);

    accumulator
      .sub_select(FieldName::new("child_id"))
      .push_field("\"id\"")
      .from("\"child\"")
      .finalize();
  }

  assert_eq!(
    qb.finalize().into_string(),
    "SELECT \"id\" FROM \"parent\" WHERE \"z\" = ? AND \"child_id\" IN \
     ( SELECT \"id\" FROM \"child\" )"
  );
}

/// The subject may be a COLUMN rather than a name, and the two spellings agree where a column is
/// one segment — which is what makes the named form the twin's own rendering rather than a second
/// one beside it.
///
/// A composite's foreign key is where they part: a path of two segments is ONE identifier with the
/// segments run together, and no [`FieldName`] spells it. That is the whole reason a relation's
/// left-hand side is written rather than named.
#[cfg(feature = "sqlite")]
#[test]
fn a_sub_select_takes_a_written_subject_where_a_name_cannot_reach() {
  use crate::{At, RecordAddress, comparison::sql::push_column};

  const PARENT: RecordAddress =
    RecordAddress::new(FieldName::new("parent"), &[FieldName::new("id")]);

  fn rendered(at: At<'_>) -> String {
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
    SqlConjunction::with_lead(&mut qb, "")
      .sub_select_with(|qb| push_column(qb, at))
      .push_field("\"id\"")
      .from("\"child\"")
      .finalize();
    qb.into_string()
  }

  let shallow = At::new(&PARENT).frame(FieldName::new("child_id"));
  let cover = At::new(&PARENT).frame(FieldName::new("cover"));
  let deep = cover.at().frame(FieldName::new("child_id"));

  assert_eq!(
    rendered(shallow.at()),
    "\"child_id\" IN ( SELECT \"id\" FROM \"child\" )"
  );
  assert_eq!(
    rendered(deep.at()),
    "\"cover_child_id\" IN ( SELECT \"id\" FROM \"child\" )"
  );

  // The named form renders THROUGH the twin, so the one-segment column above and this are the same
  // bytes rather than two spellings that happen to agree.
  let mut named = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  SqlConjunction::with_lead(&mut named, "")
    .sub_select(FieldName::new("child_id"))
    .push_field("\"id\"")
    .from("\"child\"")
    .finalize();
  assert_eq!(named.into_string(), rendered(shallow.at()));
}

/// The bind list is the half the rendered text cannot show: three `?` read the same whatever went
/// into them, so a nest that rendered its text in the right place while binding out of order would
/// satisfy every assertion above.
///
/// The operands are recorded as they are bound, and the order is the render order — the outer
/// conjunct before the subquery, the subquery's own, then the outer conjunct after it — because
/// the nested statement writes into the same buffer and the same bind list.
#[cfg(feature = "sqlite")]
#[test]
fn a_nested_statement_binds_in_render_order() {
  use crate::{Carrier, comparison::sql::tests::Probe};

  let bound = core::cell::RefCell::new(Vec::new());
  let mut qb = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
    .push_field("\"id\"")
    .from("\"parent\"")
    .begin_where();
  {
    let mut accumulator = SqlConjunction::new(qb.inner_mut());
    {
      let slot = accumulator.open();
      slot.push("\"z\" = ");
      Probe {
        value: 1,
        bound: &bound,
      }
      .push_bind(slot);
    }

    let mut inner = accumulator
      .sub_select(FieldName::new("child_id"))
      .push_field("\"id\"")
      .from("\"child\"")
      .begin_where();
    {
      let mut nested = SqlConjunction::new(inner.inner_mut());
      let slot = nested.open();
      slot.push("\"kind\" = ");
      Probe {
        value: 2,
        bound: &bound,
      }
      .push_bind(slot);
    }

    let mut accumulator = inner.finalize();
    {
      let slot = accumulator.open();
      slot.push("\"y\" = ");
      Probe {
        value: 3,
        bound: &bound,
      }
      .push_bind(slot);
    }
  }

  assert_eq!(
    qb.finalize().into_string(),
    "SELECT \"id\" FROM \"parent\" WHERE \"z\" = ? AND \"child_id\" IN \
     ( SELECT \"id\" FROM \"child\" WHERE \"kind\" = ? ) AND \"y\" = ?"
  );
  assert_eq!(*bound.borrow(), [1, 2, 3]);
}

/// A caller may still bracket a nest by hand — [`QueryBuilder::select_into`] takes the `&mut` an
/// accumulator's [`open`](SqlConjunction::open) yields, as it takes any other holder — and this is
/// what [`SqlConjunction::sub_select`] is the paired spelling of.
///
/// What the hand-rolled route gives up is exactly the pairing: the ` )` here is pushed by the same
/// code that pushed the ` IN ( ` because the test wrote both, where `sub_select`'s close is the
/// only method that can reach the holder it hands out.
#[cfg(feature = "sqlite")]
#[test]
fn a_conjunct_can_host_a_hand_bracketed_nested_statement() {
  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  {
    let mut accumulator = SqlConjunction::with_lead(&mut qb, "");
    {
      let slot = accumulator.open();
      slot.push("\"child_id\" IN ( ");
      let mut nested = QueryBuilder::<SelectClause, sqlx::Sqlite, _>::select_into(&mut *slot)
        .push_field("\"id\"")
        .from("\"child\"")
        .begin_where();
      {
        // The nested statement's own accumulator, over the same buffer: its ` WHERE ` is its own
        // and the outer accumulator's separators are unaffected, because the two count separately
        // and each opens the clause of the statement it belongs to.
        SqlConjunction::new(nested.inner_mut())
          .open()
          .push("\"kind\" = ")
          .push_bind(7i64);
      }
      slot.push(" )");
    }
    accumulator.open().push("\"z\" = ").push_bind(1i64);
  }

  assert_eq!(
    qb.into_string(),
    "\"child_id\" IN ( SELECT \"id\" FROM \"child\" WHERE \"kind\" = ? ) AND \"z\" = ?"
  );
}

/// Render a statement whose ordering term and whose subquery's left-hand side are the SAME name, so
/// one string holds both of the identifiers this module brackets.
///
/// The select field and the table are pushed as given, and neither is a name — `*` is an expression
/// and `t` is a table — so nothing in the rendering is this seam's output except the two copies of
/// `column`.
///
/// `column` is a `&str` and the [`FieldName`] wrap is made HERE, once, for the reason the family
/// harness makes its own: the parameter is a name by construction, being the only thing this
/// function takes, so the type has nothing left to distinguish at the call sites.
fn ordered_and_nested<Db: sqlx::Database + QuoteIdent>(column: &str) -> String {
  let mut qb = QueryBuilder::<SelectClause, Db>::select()
    .push_field("*")
    .from("t")
    .begin_where();
  {
    SqlConjunction::new(qb.inner_mut())
      .sub_select(FieldName::new(column))
      .push_field("*")
      .from("u")
      .finalize();
  }

  qb.order_by(FieldName::new(column), true)
    .finalize()
    .into_string()
}

/// Both names reach the statement BRACKETED, and it is this module that brackets them rather than
/// the caller — the ordering term and the field a subquery tests are the two identifiers here that
/// are names.
///
/// Reading the rendered characters is the instrument that fits this and nothing else: quoting IS
/// text, and a name that closes its own identifier is visible in nothing but the text.
///
/// The escape is the half that matters. Unescaped, `n" = 1 OR "x` would end the identifier and
/// leave ` = 1 OR ` standing as SQL — in an `ORDER BY` and in a membership test at once. Escaped,
/// each is one identifier: a column that does not exist, which the engine refuses.
#[cfg(feature = "sqlite")]
#[test]
fn sqlite_brackets_an_ordering_term_and_a_subquery_field() {
  assert_eq!(
    ordered_and_nested::<sqlx::Sqlite>("n"),
    "SELECT * FROM t WHERE \"n\" IN ( SELECT * FROM u ) ORDER BY \"n\" DESC"
  );
  assert_eq!(
    ordered_and_nested::<sqlx::Sqlite>("n\" = 1 OR \"x"),
    "SELECT * FROM t WHERE \"n\"\" = 1 OR \"\"x\" IN ( SELECT * FROM u ) \
     ORDER BY \"n\"\" = 1 OR \"\"x\" DESC"
  );
}

#[cfg(feature = "postgres")]
#[test]
fn postgres_brackets_an_ordering_term_and_a_subquery_field() {
  assert_eq!(
    ordered_and_nested::<sqlx::Postgres>("a\"b"),
    "SELECT * FROM t WHERE \"a\"\"b\" IN ( SELECT * FROM u ) ORDER BY \"a\"\"b\" DESC"
  );
}

/// The bracket belongs to the DIALECT, and this is the lane that says so: MySQL reads `"n"` as a
/// string literal unless `ANSI_QUOTES` is set, so another dialect's bracket here would order by a
/// constant and test a constant's membership — a wrong answer rather than an error.
#[cfg(feature = "mysql")]
#[test]
fn mysql_brackets_an_ordering_term_and_a_subquery_field() {
  assert_eq!(
    ordered_and_nested::<sqlx::MySql>("a`b"),
    "SELECT * FROM t WHERE `a``b` IN ( SELECT * FROM u ) ORDER BY `a``b` DESC"
  );
  // A double quote is an ordinary character in a MySQL name, so doubling it here would rename the
  // column.
  assert_eq!(
    ordered_and_nested::<sqlx::MySql>("a\"b"),
    "SELECT * FROM t WHERE `a\"b` IN ( SELECT * FROM u ) ORDER BY `a\"b` DESC"
  );
}

/// The whole shape a GENERATED order takes: the requested term, then the key columns that end every
/// order — `(sort values…, key)`, which is what a keyset cursor pages without skipping or repeating
/// a row.
///
/// Assembled by hand for the reason `graphql::tests::wire` mirrors the emitted order-by's shape:
/// the emitter cannot reach this crate. Which column names an ordering CHOOSES is that lowering's
/// answer and is asserted against a real expansion in `ingraph-derive`'s fixtures; how each one is
/// BRACKETED is this family's, and it is the half that differs per dialect — so the shape is
/// rendered here once per dialect the builder supports.
fn generated_order<Db: sqlx::Database + QuoteIdent>() -> String {
  QueryBuilder::<SelectClause, Db>::select()
    .push_field("*")
    .from("t")
    .order_by(FieldName::new("title"), true)
    .order_by(FieldName::new("reel_id"), false)
    .order_by(FieldName::new("id"), false)
    .finalize()
    .into_string()
}

/// The term's direction is the client's and the tail's is not: the key runs ASCENDING behind a
/// `DESC` term, because it is the cursor's spine rather than a preference.
#[cfg(feature = "sqlite")]
#[test]
fn sqlite_renders_a_term_and_then_the_key() {
  assert_eq!(
    generated_order::<sqlx::Sqlite>(),
    "SELECT * FROM t ORDER BY \"title\" DESC, \"reel_id\" ASC, \"id\" ASC"
  );
}

#[cfg(feature = "postgres")]
#[test]
fn postgres_renders_a_term_and_then_the_key() {
  assert_eq!(
    generated_order::<sqlx::Postgres>(),
    "SELECT * FROM t ORDER BY \"title\" DESC, \"reel_id\" ASC, \"id\" ASC"
  );
}

/// MySQL brackets with a backtick, so the same order is a different statement — and a double quote
/// there is a string literal, which would order the whole table by a constant.
#[cfg(feature = "mysql")]
#[test]
fn mysql_renders_a_term_and_then_the_key() {
  assert_eq!(
    generated_order::<sqlx::MySql>(),
    "SELECT * FROM t ORDER BY `title` DESC, `reel_id` ASC, `id` ASC"
  );
}