happenstance-postgres 0.8.0

PostgreSQL event store and projection store adapters for happenstance.
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
//! The schema, and the one way it is applied.
//!
//! # Why a file rather than a `sqlx::migrate!`
//!
//! The manifest carries the argument in full. The short form: a migrator's
//! `_sqlx_migrations` table is *per schema*, one per fixture instance, about a
//! history this crate makes moot: every migration is `IF NOT EXISTS`, so `apply`
//! runs them all against any schema, fresh or migrated by an older build. Since
//! #483 the log has three, `MIGRATION_1`, `_3` and `_4` (named: `event-store`).
//!
//! # Why the SQL is `include_str!`d rather than written inline
//!
//! `happenstance-sqlite` keeps its `MIGRATION_1` as a `&str` constant in Rust
//! and mirrors it into a doc comment, then has a test compare the mirror against
//! `sqlite_master` object by object — because the two copies drift otherwise. A
//! `.sql` file has no second copy to drift from, gets SQL syntax highlighting in
//! every editor, and is the artefact a DBA asks for when they want to know what
//! this crate will do to their database. `include_str!` means it is still
//! compiled in, so a published crate carries its own schema and a consumer needs
//! nothing from this repository to apply it.

use sqlx::PgExecutor;

#[cfg(feature = "event-store")]
use crate::error::PostgresEventStoreError;

/// The event log's first migration, as SQL; [`MIGRATION_3`] follows it.
///
/// Exposed rather than private because a consumer running their own migration
/// tooling needs the text, and the alternative is that they copy it out of the
/// repository and it drifts. Applying both is [`apply`].
///
/// Idempotent: every object is created `IF NOT EXISTS`, so applying it to a
/// schema that has it is a no-op. Frozen since first publish: a change is a new one.
#[cfg(feature = "event-store")]
pub const MIGRATION_1: &str = include_str!("../migrations/0001_event_log.sql");

/// The event log's second migration, as SQL: the write-group columns and
/// their index (#420).
///
/// `write_group`, on every row, the lowest position the write that put the row
/// in gave out, and `group_guard`, on that first row only, the guard an
/// ingested group arrived under. A runner and a store peer read the log back
/// in whole writes through them (SY-39). Both nullable with no default, so
/// adding them rewrites no row; a row from before this migration reads as a
/// group of its own.
///
/// **Apply it before deploying this build**: every `INSERT` this build sends
/// names `write_group`, and fails against a table without it. Idempotent, as
/// [`MIGRATION_1`] is. The index is built in the migration's transaction; the
/// file says how to build it `CONCURRENTLY` first on a large table.
///
/// Numbered 3 because that is the directory's sequence:
/// `migrations/0002_projection_checkpoint.sql` belongs to the other role.
#[cfg(feature = "event-store")]
pub const MIGRATION_3: &str = include_str!("../migrations/0003_write_group.sql");

/// The event log's third migration, as SQL: the removal record (#483, #484,
/// ADR-0110).
///
/// The `event_removed` table, keyed by the origin pair, and a `BEFORE DELETE`
/// row trigger on `event` that records the identity of every row deleted from
/// it, by any client, through the table's own schema whatever the deleting
/// session's `search_path`. An ingest treats a recorded identity as one the
/// store holds (SY-40), so a pruned replica that re-pulls, or is re-pushed, its
/// removed events skips them instead of appending them again or refusing them
/// as an unheld own identity.
///
/// **Apply it before deploying this build**: every ingest this build sends
/// locks `event_removed` first, and fails against a schema without it. Append
/// and the reads do not touch it. Idempotent, as [`MIGRATION_1`] is.
///
/// **Grant an ingesting role `SELECT, UPDATE` on `event_removed`**: its
/// `LOCK ... IN SHARE MODE` needs one of `UPDATE`, `DELETE`, `TRUNCATE` or,
/// from Postgres 17, `MAINTAIN`. A deleting role needs nothing more, as the
/// trigger's function is `SECURITY DEFINER`; the file says why that is safe.
///
/// A `TRUNCATE` fires no row trigger and records nothing, and a removal made
/// before this migration ran is not recorded either; the file shows the
/// `INSERT` an operator runs to record one by hand. The record grows by one
/// row per removal and is kept for ever: deleting a row from it lets that
/// identity be ingested again.
#[cfg(feature = "event-store")]
pub const MIGRATION_4: &str = include_str!("../migrations/0004_removal_record.sql");

/// What [`apply`] sends: [`MIGRATION_1`], [`MIGRATION_3`], then
/// [`MIGRATION_4`], as one batch.
///
/// `concat!` over the three `include_str!`s, so the batch is one constant
/// compiled in and not a string assembled per call. It begins with
/// the test-only `WRITE_GROUP_LOG`, byte for byte.
#[cfg(feature = "event-store")]
const EVENT_LOG: &str = concat!(
    include_str!("../migrations/0001_event_log.sql"),
    "\n",
    include_str!("../migrations/0003_write_group.sql"),
    "\n",
    include_str!("../migrations/0004_removal_record.sql"),
);

/// What a version-2 build's [`apply`] sent: [`MIGRATION_1`], then
/// [`MIGRATION_3`]. Kept for the tests that stand a version-2 schema up, as
/// an older build left it, and check this build's batch begins with it.
#[cfg(all(test, feature = "event-store"))]
pub(crate) const WRITE_GROUP_LOG: &str = concat!(
    include_str!("../migrations/0001_event_log.sql"),
    "\n",
    include_str!("../migrations/0003_write_group.sql"),
);

/// The version a schema is at once [`MIGRATION_1`] and [`MIGRATION_3`] are
/// on it: what the write-group build's [`apply`] left, and what
/// [`SCHEMA_VERSION`] read until migration 4.
#[cfg(feature = "event-store")]
const WRITE_GROUP_SCHEMA_VERSION: u32 = 2;

/// The **event log's** schema version.
///
/// Three: [`MIGRATION_1`], [`MIGRATION_3`] and [`MIGRATION_4`]. It was one
/// through first publish, while the slice that wired ADR-0024's mechanism could
/// still add its column to [`MIGRATION_1`] in place, because no deployed table
/// existed to alter. That licence ended at this crate's first publish, so write
/// groups, the first change to the log after it, are a migration of their own
/// and a version of their own (two), and so is the removal record (three).
///
/// Nothing stores this number in the database: a schema carries no marker, and
/// [`apply`] is idempotent, so bringing a schema up to this version is running
/// [`apply`] against it.
///
/// `migrations/0002_projection_checkpoint.sql` is not part of it. It adds
/// no object to the event log and belongs to the other role's lineage, which
/// carries its own `PROJECTION_SCHEMA_VERSION` — named in code rather than
/// linked, because that constant is behind the `projection-store` feature and
/// this one is not. The number in that filename is the directory's sequence, so
/// that a DBA applying the files in order gets a working database for whichever
/// roles they use.
#[cfg(feature = "event-store")]
pub const SCHEMA_VERSION: u32 = WRITE_GROUP_SCHEMA_VERSION + 1;

/// Applies [`MIGRATION_1`], [`MIGRATION_3`] and then [`MIGRATION_4`] to
/// whatever schema `executor` resolves against.
///
/// Which schema that is depends on the connection's `search_path`, and this
/// function deliberately does not set it: a caller pointing a pool at one schema
/// and a caller using the default `public` are both legitimate, and a library
/// that silently rewrites `search_path` breaks the first one. The test fixture
/// creates a schema per instance and sets the path on the pool; a consumer does
/// whatever their deployment does.
///
/// # Upgrading a schema an older build migrated
///
/// Run this against it, then deploy. Every migration is idempotent, so on
/// such a schema only the ones it lacks do anything. [`MIGRATION_3`]'s `ALTER
/// TABLE`s take a brief exclusive lock on `event`, and its index build blocks
/// writes while it runs; `migrations/0003_write_group.sql` says how to build
/// the index beforehand without blocking them. [`MIGRATION_4`] creates a small
/// table and a trigger, whose creation briefly blocks writes to `event`; on a
/// schema that has the trigger it takes no lock on `event` at all.
///
/// # Errors
///
/// [`PostgresEventStoreError::Driver`] if the server rejects the statements —
/// most plausibly because the role cannot create objects in the target schema.
#[cfg(feature = "event-store")]
pub async fn apply<'e, E>(executor: E) -> Result<(), PostgresEventStoreError>
where
    E: PgExecutor<'e>,
{
    // `execute` rather than a prepared query: this is multiple statements, and
    // the extended protocol admits exactly one. Postgres runs a multi-statement
    // simple-protocol batch in an implicit transaction, so a failure part-way
    // leaves no half-built table behind, and a schema it reaches has both
    // migrations or neither.
    sqlx::raw_sql(EVENT_LOG).execute(executor).await?;
    Ok(())
}

/// The projection store's schema, as SQL.
///
/// Exposed for the same reason `MIGRATION_1` is: a consumer running their own
/// migration tooling needs the text, and the alternative is that they copy it out
/// of the repository and it drifts. Applying it is [`apply_projection`].
///
/// It is idempotent, and it does **not** include the conformance suite's probe
/// read model — that table is the suite's, lives behind the `conformance`
/// feature, and has no business in an application's database.
#[cfg(feature = "projection-store")]
pub const MIGRATION_2: &str = include_str!("../migrations/0002_projection_checkpoint.sql");

/// The projection schema version this crate's code is written against.
///
/// One, and separate from [`SCHEMA_VERSION`] on purpose. The two roles share a
/// crate and a driver; they do not share a schema lineage. A consumer taking
/// `event-store` alone applies migration 1 and never this one, so a single
/// counter spanning both would report a version they are not at.
///
/// The file is named `0002_…` because that is the directory's sequence and a DBA
/// applying the files in order should get a working database for both roles. The
/// number in the filename and the number here answer different questions.
#[cfg(feature = "projection-store")]
pub const PROJECTION_SCHEMA_VERSION: u32 = 1;

/// Applies [`MIGRATION_2`] to whatever schema `executor` resolves against.
///
/// Separate from [`apply`] rather than folded into it, and the separation is the
/// point: an application using only the event store gets no
/// `projection_checkpoint` table, and one using only the projection store gets no
/// event log. A single `apply` would decide for both.
///
/// It does not set `search_path`, for the reason [`apply`] does not.
///
/// # Errors
///
/// [`Driver`](crate::error::PostgresProjectionStoreError::Driver) if the server
/// rejects the statements
/// — most plausibly because the role cannot create objects in the target schema.
#[cfg(feature = "projection-store")]
pub async fn apply_projection<'e, E>(
    executor: E,
) -> Result<(), crate::error::PostgresProjectionStoreError>
where
    E: PgExecutor<'e>,
{
    // `raw_sql` for the reason `apply` uses it: the extended protocol admits one
    // statement, and a simple-protocol batch runs in an implicit transaction, so
    // a failure part-way leaves no half-built table behind.
    sqlx::raw_sql(MIGRATION_2).execute(executor).await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "event-store")]
    use super::{MIGRATION_1, MIGRATION_4, SCHEMA_VERSION, WRITE_GROUP_SCHEMA_VERSION};

    #[cfg(feature = "event-store")]
    /// [`MIGRATION_1`] with its `--` line comments removed.
    ///
    /// The two guards below scan for words that must not appear in the schema —
    /// and the schema's comments are largely *about* those words, explaining why
    /// each is absent. Scanning the raw text therefore fails on a correct file,
    /// which is what the first run of these tests did: `bigserial` and `xid8`
    /// were both found, both in prose saying they were deliberately not used.
    ///
    /// A test that cannot tell a statement from a comment about a statement is
    /// not checking what it claims to. This is not a workaround for the failure;
    /// it is the fix for it.
    fn statements() -> String {
        MIGRATION_1
            .lines()
            .map(|line| line.split_once("--").map_or(line, |(code, _)| code))
            .collect::<Vec<_>>()
            .join(
                "
",
            )
    }

    #[cfg(feature = "event-store")]
    /// The stripper is itself load-bearing, so it gets a test.
    ///
    /// If it silently stopped stripping, both guards below would go green on a
    /// file that had genuinely acquired a `bigserial` — the failure mode is a
    /// pair of tests that pass because they can no longer see anything.
    #[test]
    fn the_comment_stripper_removes_prose_and_keeps_sql() {
        let stripped = statements();
        assert!(
            !stripped.contains("ADR-0024"),
            "prose survived the strip, so the guards below are scanning comments"
        );
        assert!(
            stripped.contains("CREATE TABLE IF NOT EXISTS event"),
            "the strip ate SQL, so the guards below are scanning nothing"
        );
    }

    #[cfg(feature = "event-store")]
    /// The mechanism's column is present, and this test changed hands.
    ///
    /// It was written by `postgres-schema-and-live-fixture` asserting the
    /// **absence** of an `xid8` column, so that a schema story could not settle
    /// the position-visibility question in passing. That guard did its job and
    /// is now spent: the story that owns the mechanism has chosen it, on
    /// ADR-0013's phase-2 measurement, and the column is deliberate.
    ///
    /// Inverted rather than deleted. A removed test leaves no trace that the
    /// schema ever had something to prove; an inverted one records that the
    /// column arrived through the story entitled to add it, and fails if some
    /// later edit removes the mechanism while leaving the reads that depend on
    /// it in place.
    #[test]
    fn migration_1_carries_the_visibility_mechanism_column() {
        let statements = statements();
        assert!(
            statements.contains("xact_id"),
            "the frontier mechanism's column is gone, but `head` and every read still              filter on it"
        );
        assert!(
            statements.contains("event_xact_idx"),
            "the frontier predicate has lost its index, which turns every read into a              sequential scan and charges the mechanism for the absence of an index rather              than for what it costs"
        );
    }

    #[cfg(feature = "event-store")]
    /// `position` must not be a sequence default, and the reason is one sentence
    /// long: a `serial` column is `nextval()`, and `nextval()` allocating outside
    /// the transaction is where ES-10's invariant is lost.
    ///
    /// This is a text assertion because it is cheap and runs with no server. The
    /// live half — `column_default IS NULL` and `is_identity = 'NO'` read back
    /// out of `information_schema` — is in the gated conformance target, where a
    /// real server can disagree with the text.
    #[test]
    fn position_is_not_a_serial_column() {
        let statements = statements();
        for forbidden in ["bigserial", "serial", "AS IDENTITY"] {
            assert!(
                !statements.contains(forbidden),
                "migration 1 contains `{forbidden}`: a sequence default on `position` \
                 is exactly the construction ES-10 forbids"
            );
        }
    }

    #[cfg(feature = "event-store")]
    /// The event log's lineage is at two once migration 3 is on it (#420).
    ///
    /// This read `the_schema_version_is_one_until_first_publish` and asserted
    /// one, under the licence to edit [`MIGRATION_1`] in place that ended at
    /// this crate's first publish. Write groups are the first change to the
    /// log after it, so they are a second migration and a second version,
    /// which is what the expectation now pins.
    ///
    /// Since migration 4 (#483, #484) the version-2 state is the one an
    /// older build's `apply` leaves, named [`WRITE_GROUP_SCHEMA_VERSION`], and
    /// this asserts its number there. The public value, [`SCHEMA_VERSION`],
    /// is no longer asserted here: `the_schema_version_counts_the_removal_record`
    /// pins it, at 3.
    #[test]
    fn the_schema_version_counts_the_write_group_migration() {
        assert_eq!(WRITE_GROUP_SCHEMA_VERSION, 2);
    }

    #[cfg(feature = "event-store")]
    /// The event log's lineage is at three once migration 4, the removal
    /// record, is on it (#483, #484, ADR-0110): one past the write-group
    /// version.
    #[test]
    fn the_schema_version_counts_the_removal_record() {
        assert_eq!(SCHEMA_VERSION, 3);
        assert_eq!(SCHEMA_VERSION, WRITE_GROUP_SCHEMA_VERSION + 1);
    }

    #[cfg(feature = "event-store")]
    /// [`MIGRATION_4`] with its `--` line comments removed, as [`statements`]
    /// strips migration 1.
    fn migration_4_statements() -> String {
        MIGRATION_4
            .lines()
            .map(|line| line.split_once("--").map_or(line, |(code, _)| code))
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[cfg(feature = "event-store")]
    /// Migration 4 creates the record keyed by the origin pair, the function
    /// that writes it through the firing table's own schema, and a `BEFORE
    /// DELETE` row trigger guarded by the origin index's predicate. Every
    /// object is created so that applying it twice is a no-op: the table `IF
    /// NOT EXISTS`, the function `OR REPLACE`, and the trigger only when the
    /// table carries none of that name.
    ///
    /// Rejects an `AFTER` trigger, which deadlocks a removal against an ingest
    /// holding the record's lock; a static `INSERT`, which resolves the record
    /// through the deleting session's `search_path`; and an unguarded or
    /// conflict-intolerant insert, which fails a `DELETE` of an unstamped row or
    /// of an identity recorded once already. And rejects a function that runs
    /// as the deleting role, which fails a retention role's `DELETE` for want
    /// of `INSERT` on the record, or one that resolves `format` through a
    /// caller's `search_path` or that any role may attach to its own table;
    /// `ingest::tests::privileges` shows the first live.
    #[test]
    fn migration_4_creates_the_record_and_its_trigger_idempotently() {
        let statements = migration_4_statements();
        assert!(
            !statements.contains("ADR-0110"),
            "prose survived the strip, so the assertions below are scanning comments"
        );
        for expected in [
            "CREATE TABLE IF NOT EXISTS event_removed (",
            "origin_store    bytea   NOT NULL,",
            "origin_position bigint  NOT NULL,",
            "PRIMARY KEY (origin_store, origin_position)",
            "CREATE OR REPLACE FUNCTION event_record_removal() RETURNS trigger",
            "LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp",
            "REVOKE EXECUTE ON FUNCTION event_record_removal() FROM PUBLIC;",
            "'INSERT INTO %I.event_removed (origin_store, origin_position) '",
            "'VALUES ($1, $2) ON CONFLICT DO NOTHING',",
            "TG_TABLE_SCHEMA",
            "USING OLD.origin_store, OLD.origin_position;",
            "RETURN OLD;",
            "WHERE tgrelid = 'event'::regclass AND tgname = 'event_record_removal'",
            "BEFORE DELETE ON event",
            "FOR EACH ROW",
            "WHEN (OLD.origin_store IS NOT NULL AND OLD.origin_position IS NOT NULL)",
            "EXECUTE FUNCTION event_record_removal();",
        ] {
            assert!(
                statements.contains(expected),
                "migration 4 has lost `{expected}`"
            );
        }
        for forbidden in ["AFTER DELETE", "DROP TRIGGER", "TRUNCATE", "bigserial"] {
            assert!(
                !statements.contains(forbidden),
                "migration 4 contains `{forbidden}`"
            );
        }
    }

    #[cfg(feature = "event-store")]
    /// `apply` sends migrations 1, 3 and 4, in one batch, so one implicit
    /// transaction: a schema it reaches has all three or none. The first two
    /// are exactly what an older build's `apply` sent.
    #[test]
    fn apply_sends_migrations_1_and_3_then_migration_4() {
        let batch = super::EVENT_LOG;
        assert!(
            batch.starts_with(super::WRITE_GROUP_LOG),
            "migrations 1 and 3 go first, as a version-2 build sent them"
        );
        assert!(batch.ends_with(MIGRATION_4), "migration 4 goes last");
        assert_eq!(
            batch.len(),
            super::WRITE_GROUP_LOG.len() + 1 + MIGRATION_4.len(),
            "the batch is the three migrations and the lines between them, nothing else"
        );
    }

    #[cfg(feature = "event-store")]
    /// [`MIGRATION_3`](super::MIGRATION_3) with its `--` line comments
    /// removed, as [`statements`] strips migration 1.
    fn migration_3_statements() -> String {
        super::MIGRATION_3
            .lines()
            .map(|line| line.split_once("--").map_or(line, |(code, _)| code))
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[cfg(feature = "event-store")]
    /// Migration 3 adds both write-group columns and the partial index the
    /// group read looks rows up through, each `IF NOT EXISTS`, so applying it
    /// twice is a no-op as applying migration 1 twice is.
    #[test]
    fn migration_3_adds_the_write_group_columns_and_their_index() {
        let statements = migration_3_statements();
        assert!(
            !statements.contains("#420"),
            "prose survived the strip, so the assertions below are scanning comments"
        );
        for expected in [
            "ALTER TABLE event ADD COLUMN IF NOT EXISTS write_group bigint",
            "ALTER TABLE event ADD COLUMN IF NOT EXISTS group_guard bytea",
            "CREATE INDEX IF NOT EXISTS event_write_group_idx",
            "WHERE write_group IS NOT NULL",
        ] {
            assert!(
                statements.contains(expected),
                "migration 3 has lost `{expected}`"
            );
        }
        assert!(
            !statements.contains("DEFAULT")
                && !statements.contains("bigint NOT NULL")
                && !statements.contains("bytea NOT NULL"),
            "a default or a NOT NULL on a write-group column rewrites every row of an \
             existing table, and the legacy rule needs NULL"
        );
    }

    #[cfg(feature = "event-store")]
    /// The guards that scan migration 1 for a sequence default hold for
    /// migration 3 too: it never touches `position`.
    #[test]
    fn migration_3_puts_no_sequence_default_on_position() {
        let statements = migration_3_statements();
        for forbidden in ["bigserial", "serial", "AS IDENTITY", "position"] {
            assert!(
                !statements.contains(forbidden),
                "migration 3 mentions `{forbidden}`; it adds two columns and an index, \
                 and touches nothing migration 1 owns"
            );
        }
    }

    #[cfg(feature = "event-store")]
    /// `apply` sends migration 1 and then migration 3, in one batch, so one
    /// implicit transaction: a schema it reaches has both or neither.
    ///
    /// Since migration 4 this holds of the version-2 batch an older build's
    /// `apply` sent, [`WRITE_GROUP_LOG`](super::WRITE_GROUP_LOG), which this
    /// build's batch begins with
    /// (`apply_sends_migrations_1_and_3_then_migration_4`).
    #[test]
    fn apply_sends_migration_1_then_migration_3() {
        let batch = super::WRITE_GROUP_LOG;
        assert!(batch.starts_with(MIGRATION_1), "migration 1 goes first");
        assert!(batch.ends_with(super::MIGRATION_3), "migration 3 goes last");
        assert_eq!(
            batch.len(),
            MIGRATION_1.len() + 1 + super::MIGRATION_3.len(),
            "the batch is the two migrations and the line between them, nothing else"
        );
    }

    /// Migration 2 stores the authority rather than inferring it, and constrains
    /// it to the two `Authority` variants.
    ///
    /// The cheap half of a guard whose live half — the CHECK actually refusing a
    /// third value — is in the gated conformance target, where a real server can
    /// disagree with the text.
    #[cfg(feature = "projection-store")]
    #[test]
    fn migration_2_stores_a_constrained_authority() {
        let sql = super::MIGRATION_2;
        assert!(
            sql.contains(
                "authority     text   NOT NULL CHECK (authority IN ('live', 'rebuilding'))"
            ),
            "the authority column has lost its CHECK, so a row can record a state              `Checkpoint` cannot represent and `checkpoint` will fail on read              instead of the write failing where it happened"
        );
    }

    /// The suite's probe table is not in the migrations directory.
    ///
    /// A `.sql` file there is, by construction, something a DBA applies. This is
    /// the assertion that keeps the test read model out of an application's
    /// database — the failure `happenstance-sqlite`'s own comment names and that
    /// no test in this repository could otherwise catch, because every test
    /// enables the feature that creates it.
    #[cfg(feature = "projection-store")]
    #[test]
    fn no_migration_file_creates_the_probe_table() {
        for sql in [
            #[cfg(feature = "event-store")]
            MIGRATION_1,
            super::MIGRATION_2,
            #[cfg(feature = "event-store")]
            MIGRATION_4,
        ] {
            assert!(
                !sql.contains("projection_probe"),
                "a migration file creates the conformance probe table, so applying                  this crate's schema would put the suite's read model in a                  consumer's database"
            );
        }
    }
}