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
//! **THE THREE SQL STORES**: SQLite, PostgreSQL and MySQL, over one pointer table and one anchored
//! sweep.
//!
//! ```sql
//! CREATE TABLE IF NOT EXISTS "__ig_current_media" (
//!   "root"               BLOB    NOT NULL,   -- the root's own IdColumn word
//!   "scope"              TEXT    NOT NULL,   -- the closure this points for
//!   "run"                INTEGER NOT NULL,   -- RunId, as a signed integer
//!   "flipped_second"     INTEGER NOT NULL,   -- Timestamp's own two-column shape
//!   "flipped_nanosecond" INTEGER NOT NULL,
//!   PRIMARY KEY ("root", "scope")
//! )
//! ```
//!
//! # FOUR STATEMENTS ARE RENDERED ONCE, and the FIFTH deliberately is not
//!
//! `create`, `point`, `current` and `roll` are built when the store is opened and never again: what
//! the pointer table owes above everything is that the row it wrote is the row it reads back, and a
//! statement rebuilt per act is a statement that could differ per act.
//!
//! The SWEEP is the exception, and the reason is the knob. Retention is a THREE-TIER value whose
//! third tier turns the dial on a running deployment ([`GenerationsOverride`](super::GenerationsOverride)),
//! so a `DELETE` whose `LIMIT` was frozen at construction would be a `keep` that could be raised in a
//! request and never take effect. The depth is spliced as a DECIMAL INTEGER rather than bound, which
//! is safe for the reason it is not a name: it comes off a [`NonZeroUsize`] and is rendered by
//! `Display`, so the only characters it can contribute are digits.
//!
//! # THE SWEEP IS ANCHORED ON THE POINTER, and that is the whole safety argument
//!
//! ```sql
//! DELETE FROM "clip"
//!  WHERE "media" = ?
//!    AND "__ig_run__" < (SELECT MIN(r) FROM (SELECT DISTINCT "__ig_run__" AS r FROM "clip"
//!                                             WHERE "media" = ? AND "__ig_run__" <= ?
//!                                             ORDER BY r DESC LIMIT 1) AS kept)
//! ```
//!
//! The `<= ?` is the run the flip just made durable, and it is what keeps a CONCURRENT run safe:
//! rows of a re-analysis that has started writing and not yet flipped are above the ceiling, so they
//! are neither counted towards retention nor deleted by it. Without that bound, `keep = 1` would
//! count the half-written generation as the one to keep and delete the one every reader is on.
//!
//! The inner `FROM` is a DERIVED TABLE and not a bare correlated subquery, which is what makes the
//! statement legal on MySQL: a subquery naming the `DELETE`'s own target is error 1093 there, and a
//! derived table is materialised first, which is the standard shape all three dialects take the same
//! way.
//!
//! # THE ROOT'S COLUMN IS THE ROOT'S OWN
//!
//! The word is `<<Root as IdColumn<Db>>::Stored as StoredAs<Db>>::WORDS[0]`, which is exactly the
//! word a record's own key column takes in this dialect. That is not a convenience: it is what makes
//! a pointer row's key comparable with the record tables it points FOR, which the read filter's
//! anchored subquery depends on and which a hand-picked `TEXT` would have quietly forfeited.

use core::{marker::PhantomData, num::NonZeroUsize};

use smol_bytes::Utf8Bytes;

use crate::{IdColumn, StoredAs, Timestamp, drive::registry::RootKey};

use super::{
  Culled, CurrentRow, CurrentTable, Generational, GenerationsStore, GenerationsStoreError,
  RUN_COLUMN, RunId, Scope, Turning, UnnameableTable,
};

/// **THE DIALECT FACTS A GENERATIONS STORE NEEDS** — four words and three renderings, because five
/// statements over five columns is all there is.
///
/// It is a seam over `sqlx`'s own database marker types rather than a reuse of the query layer's
/// dialect trait, and the reason is what each is FOR: the query layer's dialect renders a filter tree
/// with operands, aliases, casts and a `LIMIT` grammar, and none of that has any bearing on five
/// statements over five columns. What this seat needs is how to quote a name, how to spell a
/// parameter, how to say *on conflict*, and the three words a scope, a run and a timestamp take.
pub trait GenerationsSql: sqlx::Database {
  /// The word the scope's text takes.
  const SCOPE: &'static str;
  /// The word a run takes — a signed 64-bit integer, [`RunId`]'s own crossing.
  const RUN: &'static str;
  /// The word a whole-seconds column takes.
  const SECOND: &'static str;
  /// The word a sub-second nanoseconds column takes.
  const NANOSECOND: &'static str;

  /// `identifier`, bracketed as this dialect brackets one.
  #[must_use]
  fn quote(identifier: &str) -> String;

  /// The `at`-th parameter marker, ONE-BASED — `?` where the dialect counts nothing, `$1` where it
  /// does.
  #[must_use]
  fn placeholder(at: usize) -> String;

  /// The clause that turns the `INSERT` into the flip, given the already-quoted key and value
  /// identifiers: it sets the run and both halves of the stamp, and touches nothing else.
  #[must_use]
  fn flip(root: &str, scope: &str, values: &[&str]) -> String;
}

/// **THE READ-PLAN'S OWN HALF**: the predicate that holds a generational table to its current
/// generation.
///
/// ```sql
/// "clip"."__ig_run__" = (SELECT "run" FROM "__ig_current_media"
///                         WHERE "root" = "clip"."media" AND "scope" = ?)
/// ```
///
/// # AN ANCHORED SUBQUERY, and the anchor is what makes it one PREDICATE rather than a join
///
/// The correlation is on the record's OWN root column, so the subquery is answered per row off the
/// pointer table's primary key, and the shape COMPOSES: a plan that is also holding retired roots out
/// ANDs the two predicates rather than negotiating between two joins. That is the machinery family
/// the retired filter belongs to as well, and it is why neither of them is a `JOIN` — a join changes
/// a plan's cardinality, and neither filter may.
///
/// # WHERE IT PLUGS IN, and what is not decided here
///
/// A read plan's own door for a predicate the client never wrote is
/// [`Find::scope`](crate::query::sql::Find::scope), which today admits exactly two parties — the
/// client's filter and the server's scope — and REPLACES rather than accumulating. Widening that cap
/// to a third party is a ruling about the query surface rather than about generations, so it is not
/// made here: this function renders the predicate, and the emitted query surface takes it up when
/// that cap moves. The retired filter is in the same position and will arrive through the same door.
///
/// `record` and `root_column` arrive UNQUOTED and leave quoted for this dialect; the scope is BOUND,
/// so the rendered string carries one parameter marker at `scope_at` and the caller binds
/// [`Scope::named`].
///
/// A root with NO pointer answers nothing: the subquery is `NULL`, the comparison is `NULL`, and the
/// row is not returned. That is the correct reading of a root mid-first-run — it has no current
/// generation, so it has no current rows — and it is stated because it is a consequence of the shape
/// rather than a case the shape handles.
#[must_use]
pub fn current_filter<Db: GenerationsSql>(
  record: &str,
  root_column: &str,
  pointers: &CurrentTable,
  scope_at: usize,
) -> String {
  let record = Db::quote(record);
  format!(
    "{record}.{run_column} = (SELECT {run} FROM {table} WHERE {root} = {record}.{root_column} AND \
     {scope} = {marker})",
    run_column = Db::quote(RUN_COLUMN),
    run = Db::quote(CurrentTable::RUN),
    table = Db::quote(pointers.name()),
    root = Db::quote(CurrentTable::ROOT),
    root_column = Db::quote(root_column),
    scope = Db::quote(CurrentTable::SCOPE),
    marker = Db::placeholder(scope_at),
  )
}

/// The four statements a store renders once — see the [module note](self) for why the sweep is not
/// among them.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Statements {
  /// `CREATE TABLE IF NOT EXISTS …`
  create: String,
  /// `INSERT INTO … ON CONFLICT … DO UPDATE SET run = …, flipped_second = …, flipped_nanosecond = …`
  point: String,
  /// `SELECT run FROM … WHERE root = … AND scope = …`
  current: String,
  /// `SELECT … FROM …`
  roll: String,
}

impl Statements {
  /// The four, for `table`, with `root_word` as the root column's own dialect word.
  fn render<Db: GenerationsSql>(table: &CurrentTable, root_word: &str) -> Self {
    let name = Db::quote(table.name());
    let root = Db::quote(CurrentTable::ROOT);
    let scope = Db::quote(CurrentTable::SCOPE);
    let run = Db::quote(CurrentTable::RUN);
    let second = Db::quote(CurrentTable::FLIPPED_SECOND);
    let nanosecond = Db::quote(CurrentTable::FLIPPED_NANOSECOND);
    let columns = format!("{root}, {scope}, {run}, {second}, {nanosecond}");
    let binds = (1..=5).map(Db::placeholder).collect::<Vec<_>>().join(", ");
    Self {
      create: format!(
        "CREATE TABLE IF NOT EXISTS {name} ({root} {root_word} NOT NULL, {scope} {scope_word} NOT \
         NULL, {run} {run_word} NOT NULL, {second} {second_word} NOT NULL, {nanosecond} \
         {nanosecond_word} NOT NULL, PRIMARY KEY ({root}, {scope}))",
        scope_word = Db::SCOPE,
        run_word = Db::RUN,
        second_word = Db::SECOND,
        nanosecond_word = Db::NANOSECOND,
      ),
      point: format!(
        "INSERT INTO {name} ({columns}) VALUES ({binds}) {flip}",
        flip = Db::flip(&root, &scope, &[&run, &second, &nanosecond]),
      ),
      current: format!(
        "SELECT {run} FROM {name} WHERE {root} = {one} AND {scope} = {two}",
        one = Db::placeholder(1),
        two = Db::placeholder(2),
      ),
      roll: format!("SELECT {columns} FROM {name}"),
    }
  }
}

/// **ONE `DELETE`**, for one table of the closure — rendered per act, for the reason the
/// [module note](self) gives.
///
/// Three binds in one order for every dialect — the root twice and the ceiling once — rather than
/// one dialect reusing a marker and the others not. PostgreSQL could name `$1` twice and spend two
/// binds instead of three; spelling the same sequence everywhere is what lets one body do the
/// binding for all of them.
fn sweep_statement<Db: GenerationsSql>(table: &Generational, keep: NonZeroUsize) -> String {
  let name = Db::quote(table.table());
  let root = Db::quote(table.root());
  let run = Db::quote(RUN_COLUMN);
  format!(
    "DELETE FROM {name} WHERE {root} = {one} AND {run} < (SELECT MIN(r) FROM (SELECT DISTINCT {run} \
     AS r FROM {name} WHERE {root} = {two} AND {run} <= {three} ORDER BY r DESC LIMIT {keep}) AS \
     kept)",
    one = Db::placeholder(1),
    two = Db::placeholder(2),
    three = Db::placeholder(3),
  )
}

/// **ONE CLOSURE'S POINTERS, ON ONE SQL DATABASE** — and the tables its retention duty reaches.
///
/// It holds a POOL rather than opening one, which is the framework's own posture at every other
/// storage seam: a deployment whose records already live in this database hands over the pool it has,
/// and one that wants the pointers elsewhere opens a second and hands that over. Nothing here reads a
/// DSN — see [`GenerationsOptions`](super::GenerationsOptions), which is the document a deployment
/// reads one OFF.
///
/// # THE ROSTER IS A CONSTRUCTION ARGUMENT, and it is what a closure IS
///
/// A pointer table knows its own name; it cannot know which record tables the closure it points for
/// is made of, families being opened rather than declared. So the roster is stated — by an emitted
/// launch that read the declaration, or by a deployment wiring its own store — and an EMPTY roster is
/// a legitimate state rather than a misconfiguration: it is a closure whose pointer is kept and whose
/// generations nothing collects, which is what a deployment auditing before it sweeps wants.
pub struct SqlGenerations<Db: sqlx::Database, Root> {
  /// Where the rows go.
  pool: sqlx::Pool<Db>,
  /// Which table the pointers go in.
  table: CurrentTable,
  /// The tables the retention duty reaches — see the type note.
  roster: Vec<Generational>,
  /// The four, rendered once.
  statements: Statements,
  /// The family's key type. `fn() -> Root` rather than `Root`, so the store is `Send + Sync`
  /// whatever the key is — the store never holds one.
  root: PhantomData<fn() -> Root>,
}

impl<Db: sqlx::Database, Root> core::fmt::Debug for SqlGenerations<Db, Root> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlGenerations")
      .field("table", &self.table.name())
      .field("roster", &self.roster.len())
      .finish_non_exhaustive()
  }
}

impl<Db: sqlx::Database, Root> Clone for SqlGenerations<Db, Root> {
  fn clone(&self) -> Self {
    Self {
      pool: self.pool.clone(),
      table: self.table.clone(),
      roster: self.roster.clone(),
      statements: self.statements.clone(),
      root: PhantomData,
    }
  }
}

impl<Db, Root> SqlGenerations<Db, Root>
where
  Db: GenerationsSql,
  Root: IdColumn<Db>,
  <Root as IdColumn<Db>>::Stored: StoredAs<Db>,
{
  /// `family`'s pointers, on `pool`, sweeping `roster`.
  ///
  /// The table name is minted from the family and is not a knob: `__ig_current_<family>`. See
  /// [`CurrentTable::new`], which is also where the name is REFUSED if it could not be spliced
  /// safely — the four statements are rendered here, once, so that is the last moment a caller's
  /// string can be stopped.
  ///
  /// # Errors
  ///
  /// [`UnnameableTable`], where `family` is not a bare identifier.
  ///
  /// # Panics
  ///
  /// Where the root's stored form declares NO column word for this dialect — a `WORDS` of length
  /// zero. That is not reachable through the id vocabulary, whose every member spans exactly one
  /// column, and it is spelled rather than defaulted so that a downstream `IdColumn` row which got it
  /// wrong is loud here rather than silent in a `CREATE TABLE` with a missing type.
  pub fn new(
    pool: sqlx::Pool<Db>,
    family: impl Into<Utf8Bytes>,
    roster: Vec<Generational>,
  ) -> Result<Self, UnnameableTable> {
    let table = CurrentTable::new(family)?;
    let root_word = <<Root as IdColumn<Db>>::Stored as StoredAs<Db>>::WORDS
      .first()
      .expect("an id spans exactly one column, so its stored form has exactly one word");
    let statements = Statements::render::<Db>(&table, root_word);
    Ok(Self {
      pool,
      table,
      roster,
      statements,
      root: PhantomData,
    })
  }

  /// The pointer table this store writes.
  #[inline]
  #[must_use]
  pub const fn table(&self) -> &CurrentTable {
    &self.table
  }

  /// The tables its retention duty reaches.
  #[inline]
  #[must_use]
  pub fn roster(&self) -> &[Generational] {
    &self.roster
  }

  /// The `CREATE TABLE IF NOT EXISTS` this store runs — what a schema review reads.
  #[inline]
  #[must_use]
  pub fn create_statement(&self) -> &str {
    &self.statements.create
  }

  /// The flipping `INSERT` this store runs.
  #[inline]
  #[must_use]
  pub fn point_statement(&self) -> &str {
    &self.statements.point
  }

  /// The one-pointer `SELECT` this store runs.
  #[inline]
  #[must_use]
  pub fn current_statement(&self) -> &str {
    &self.statements.current
  }

  /// The whole-table `SELECT` this store runs.
  #[inline]
  #[must_use]
  pub fn roll_statement(&self) -> &str {
    &self.statements.roll
  }

  /// The `DELETE` this store would run over `table` at `keep` — what a schema review reads, and what
  /// a test asserts the anchoring of.
  #[inline]
  #[must_use]
  pub fn sweep_statement(&self, table: &Generational, keep: NonZeroUsize) -> String {
    sweep_statement::<Db>(table, keep)
  }
}

/// **ONE DIALECT'S WHOLE PARTICIPATION**: its four words, its three renderings and its
/// [`GenerationsStore`] row.
///
/// A macro rather than one generic impl, and the reason is `sqlx`'s own shape: `Executor` is
/// implemented for `&Pool<Db>` per concrete database, and a body written over an abstract `Db` would
/// have to carry that as a `for<'c>` bound at every call. Three expansions of one body cost nothing a
/// reader has to keep in step — the body is written ONCE, here — and buy a signature per dialect that
/// says exactly what it needs.
macro_rules! sql_generations {
  (
    $db:ty, $feature:literal, {
      scope: $scope:literal,
      run: $run:literal,
      second: $second:literal,
      nanosecond: $nanosecond:literal,
      quote: $quote:expr,
      placeholder: $placeholder:expr,
      flip: $flip:expr,
    }
  ) => {
    #[cfg(feature = $feature)]
    #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
    impl GenerationsSql for $db {
      const SCOPE: &'static str = $scope;
      const RUN: &'static str = $run;
      const SECOND: &'static str = $second;
      const NANOSECOND: &'static str = $nanosecond;

      fn quote(identifier: &str) -> String {
        #[allow(clippy::redundant_closure_call)]
        ($quote)(identifier)
      }

      fn placeholder(at: usize) -> String {
        #[allow(clippy::redundant_closure_call)]
        ($placeholder)(at)
      }

      fn flip(root: &str, scope: &str, values: &[&str]) -> String {
        #[allow(clippy::redundant_closure_call)]
        ($flip)(root, scope, values)
      }
    }

    #[cfg(feature = $feature)]
    #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
    impl<Root> GenerationsStore<Root> for SqlGenerations<$db, Root>
    where
      Root: RootKey + IdColumn<$db>,
      <Root as IdColumn<$db>>::Stored: StoredAs<$db>
        + sqlx::Type<$db>
        + for<'q> sqlx::Encode<'q, $db>
        + for<'r> sqlx::Decode<'r, $db>
        + Send
        + Unpin
        + 'static,
    {
      // AUDIT (`AssertSqlSafe`, sqlx 0.9's dynamic-SQL gate) for all five verbs below: every
      // statement is rendered out of four kinds of part and no others — this dialect's own `const`
      // words, five column names that are `const`s on `CurrentTable` plus the framework's own
      // `RUN_COLUMN`, IDENTIFIERS that `CurrentTable::new`/`Generational::new` refuse unless
      // `slot::is_identifier` accepts them, and — in the sweep alone — a retention depth rendered
      // from a `NonZeroUsize` by `Display`, which can contribute only digits. That identifier
      // charset is ASCII alphanumerics and `_`, not digit-leading, so no accepted name can carry a
      // quote, a comment, a semicolon or whitespace. Every VALUE — the key, the scope, the run, both
      // halves of the stamp — is BOUND.
      fn ready(&self) -> Turning<'_, ()> {
        Box::pin(async move {
          sqlx::query(sqlx::AssertSqlSafe(self.statements.create.clone()))
            .execute(&self.pool)
            .await
            .map(|_created| ())
            .map_err(|source| GenerationsStoreError::new("ready", self.table.named(), source))
        })
      }

      fn point<'a>(&'a self, row: &'a CurrentRow<Root>) -> Turning<'a, ()> {
        Box::pin(async move {
          sqlx::query(sqlx::AssertSqlSafe(self.statements.point.clone()))
            .bind(row.key().to_stored())
            .bind(row.scope().as_str().to_owned())
            .bind(row.run().as_i64())
            .bind(row.at().as_second())
            .bind(row.at().subsec_nanosecond())
            .execute(&self.pool)
            .await
            .map(|_flipped| ())
            .map_err(|source| GenerationsStoreError::new("point", self.table.named(), source))
        })
      }

      fn current<'a>(&'a self, key: &'a Root, scope: &'a Scope) -> Turning<'a, Option<RunId>> {
        Box::pin(async move {
          use sqlx::Row as _;

          let row = sqlx::query(sqlx::AssertSqlSafe(self.statements.current.clone()))
            .bind(key.to_stored())
            .bind(scope.as_str().to_owned())
            .fetch_optional(&self.pool)
            .await
            .map_err(|source| GenerationsStoreError::new("current", self.table.named(), source))?;
          row
            .map(|row| {
              row
                .try_get::<i64, _>(CurrentTable::RUN)
                .map(RunId::from_i64)
                .map_err(|source| GenerationsStoreError::new("current", self.table.named(), source))
            })
            .transpose()
        })
      }

      fn roll(&self) -> Turning<'_, Vec<CurrentRow<Root>>> {
        Box::pin(async move {
          let rows = sqlx::query(sqlx::AssertSqlSafe(self.statements.roll.clone()))
            .fetch_all(&self.pool)
            .await
            .map_err(|source| GenerationsStoreError::new("roll", self.table.named(), source))?;
          rows.into_iter().map(|row| self.read_row(&row)).collect()
        })
      }

      fn sweep<'a>(
        &'a self,
        key: &'a Root,
        current: RunId,
        keep: NonZeroUsize,
      ) -> Turning<'a, Culled> {
        Box::pin(async move {
          let mut swept = Culled::default();
          for table in &self.roster {
            let statement = sweep_statement::<$db>(table, keep);
            let done = sqlx::query(sqlx::AssertSqlSafe(statement))
              .bind(key.to_stored())
              .bind(key.to_stored())
              .bind(current.as_i64())
              .execute(&self.pool)
              .await
              .map_err(|source| {
                // The TABLE named in the refusal is the one the `DELETE` was refused on rather than
                // the pointer table, because that is the one a reader has to go and look at.
                GenerationsStoreError::new("sweep", table.table().to_owned(), source)
              })?;
            swept.tables += 1;
            swept.rows += done.rows_affected();
          }
          Ok(swept)
        })
      }
    }

    /// ONE POINTER ROW, READ BACK — the inverse of the five binds, at THIS dialect.
    ///
    /// It lives inside the expansion rather than beside it because `sqlx::Row::try_get` asks for
    /// `Type<Db>` and `Decode<'_, Db>` at the CONCRETE database: `i64`, `i32` and `String` have
    /// those rows per driver, and a body written over an abstract `Db` would have to re-state every
    /// one of them as a bound its callers could not discharge.
    #[cfg(feature = $feature)]
    impl<Root> SqlGenerations<$db, Root>
    where
      Root: RootKey + IdColumn<$db>,
      <Root as IdColumn<$db>>::Stored:
        sqlx::Type<$db> + for<'r> sqlx::Decode<'r, $db> + Send + Unpin + 'static,
    {
      /// The row, or the refusal that stopped it.
      fn read_row(
        &self,
        row: &<$db as sqlx::Database>::Row,
      ) -> Result<CurrentRow<Root>, GenerationsStoreError> {
        use sqlx::Row as _;

        let refuse =
          |source: sqlx::Error| GenerationsStoreError::new("roll", self.table.named(), source);
        let stored: <Root as IdColumn<$db>>::Stored =
          row.try_get(CurrentTable::ROOT).map_err(refuse)?;
        // A row this store did not write — a hand-edited key, a column repurposed — is a DECODE
        // refusal and is reported as one, carrying the id vocabulary's own sentence about what it
        // would not admit.
        let key = Root::from_stored(stored)
          .map_err(|refusal| refuse(sqlx::Error::Decode(Box::new(refusal))))?;
        let scope: String = row.try_get(CurrentTable::SCOPE).map_err(refuse)?;
        let scope =
          Scope::new(scope).map_err(|refusal| refuse(sqlx::Error::Decode(Box::new(refusal))))?;
        let run: i64 = row.try_get(CurrentTable::RUN).map_err(refuse)?;
        let second: i64 = row.try_get(CurrentTable::FLIPPED_SECOND).map_err(refuse)?;
        let nanosecond: i32 = row
          .try_get(CurrentTable::FLIPPED_NANOSECOND)
          .map_err(refuse)?;
        let at = Timestamp::from_parts(second, nanosecond)
          .map_err(|refusal| refuse(sqlx::Error::Decode(Box::new(refusal))))?;
        Ok(CurrentRow::new(key, scope, RunId::from_i64(run), at))
      }
    }
  };
}

sql_generations!(sqlx::Sqlite, "sqlite", {
  scope: "TEXT",
  run: "INTEGER",
  second: "INTEGER",
  nanosecond: "INTEGER",
  quote: |identifier: &str| format!("\"{identifier}\""),
  placeholder: |_at: usize| "?".to_owned(),
  flip: |root: &str, scope: &str, values: &[&str]| {
    let sets = values
      .iter()
      .map(|value| format!("{value} = excluded.{value}"))
      .collect::<Vec<_>>()
      .join(", ");
    format!("ON CONFLICT ({root}, {scope}) DO UPDATE SET {sets}")
  },
});

sql_generations!(sqlx::Postgres, "postgres", {
  scope: "text",
  run: "bigint",
  second: "bigint",
  nanosecond: "integer",
  quote: |identifier: &str| format!("\"{identifier}\""),
  // THE ONE DIALECT THAT COUNTS ITS PARAMETERS, which is the whole reason `placeholder` takes an
  // ordinal at all.
  placeholder: |at: usize| format!("${at}"),
  flip: |root: &str, scope: &str, values: &[&str]| {
    let sets = values
      .iter()
      .map(|value| format!("{value} = EXCLUDED.{value}"))
      .collect::<Vec<_>>()
      .join(", ");
    format!("ON CONFLICT ({root}, {scope}) DO UPDATE SET {sets}")
  },
});

sql_generations!(sqlx::MySql, "mysql", {
  // `varchar(255)`, which is the house's own text word one module over — a ceiling inherited rather
  // than chosen. A scope is a bare identifier, so nothing this seat writes approaches it.
  scope: "varchar(255)",
  run: "bigint",
  second: "bigint",
  nanosecond: "int",
  quote: |identifier: &str| format!("`{identifier}`"),
  placeholder: |_at: usize| "?".to_owned(),
  // MySQL names no conflict TARGET: the clause fires on whichever unique key collided, and this
  // table has exactly one. `VALUES(col)` is the row that was refused, which is what `excluded` is
  // called on the other two.
  flip: |_root: &str, _scope: &str, values: &[&str]| {
    let sets = values
      .iter()
      .map(|value| format!("{value} = VALUES({value})"))
      .collect::<Vec<_>>()
      .join(", ");
    format!("ON DUPLICATE KEY UPDATE {sets}")
  },
});