Skip to main content

capsule_library/db/
migrate.rs

1//! Forward-only stepwise migrator for the client SQLite catalog.
2//!
3//! The catalog (`index/library.sqlite` in the [client library layout]) **is** the user's
4//! library as they experience it, so it carries the same "backward-compatible reads forever"
5//! obligation as the server schema and is given the same mechanism: a forward-only stepwise
6//! migrator keyed on `PRAGMA user_version`, the client-side analogue of the server's
7//! forward-only sea-orm migrations. Opening a catalog stamped below [`SCHEMA_VERSION`] walks
8//! it up, one step per version, to the current one. There is no downgrade step, for the same
9//! reason the server has none — "rollback then continue" is what corrupts data, on a laptop
10//! as much as on a server.
11//!
12//! SSoT: design/versioning § Client Catalog Migration.
13//!
14//! # Why not drop and rebuild
15//!
16//! `rebuild_index` is the **repair** path ([Maintenance § Repair]), reached when the index is
17//! already known-inconsistent. It is not a release ritual: spending it on every shipped column
18//! would re-derive the whole library on each upgrade and re-lose whatever the sidecars do not
19//! yet carry (importer-formed stack placement). The migrator is the durability
20//! mechanism; rebuild stays the recovery path it was.
21//!
22//! # A shipped step is immutable
23//!
24//! **Once a step appears in [`STEPS`], it is never edited — only followed by another step.**
25//! Some user's catalog has already been walked through the old text; changing it now means the
26//! same `user_version` describes two different schemas, and every later step is then reasoning
27//! about a shape that may or may not exist. If a shipped step was wrong, add the *next* step
28//! that repairs it and bump [`SCHEMA_VERSION`].
29//!
30//! This is enforced, not merely asserted: `shipped_steps_are_immutable` in this module's tests
31//! locks each step's canonical rendering behind a SHA-256 fingerprint checked into
32//! `STEP_FINGERPRINTS`. Editing a shipped step fails that test with an explanation. Adding a
33//! new step appends a fingerprint and leaves the existing ones untouched.
34//!
35//! # What the shipped history actually was
36//!
37//! Reconstructed from `git log --follow -p capsule-core/src/db/schema.rs` rather than from the
38//! version doc comment, which does not match what shipped on the mainline:
39//!
40//! | stamp | mainline shape |
41//! |-------|----------------|
42//! | v1    | base tables, `assets.hash_blake3` |
43//! | v1    | *still* v1 after `assets.hash_blake3` was renamed to `hash_sha256` — the rename shipped **without a version bump** (`1776c04`) |
44//! | v2    | + `cached_representations` + `idx_cache_evict` (`6c74679`, merged `8b3e06b`) |
45//! | v2    | *still* v2 after `albums`, `idx_albums_created`, `idx_assets_type` arrived from a branch that had independently bumped 1 → 2 for its own change (`3e19de0`, merged `3ebb16d`) |
46//! | v3    | + `embeddings` + its two indexes (`09ae1d1`) |
47//! | v4    | + `assets.is_hidden`, `idx_assets_hidden`, widened `idx_assets_timeline` (`5d3ef26`) |
48//! | v5    | + `assets.caption`, `assets.latitude`, `assets.longitude` |
49//! | v6    | + `idx_assets_album_recency` |
50//! | v7    | + `upload_guards` |
51//!
52//! Two consequences the original plan did not anticipate, both handled below:
53//!
54//! 1. **v1 is ambiguous**: a v1-stamped catalog may carry either `hash_blake3` or `hash_sha256`,
55//!    so the 1 → 2 step renames *conditionally* rather than unconditionally.
56//! 2. **v2 is ambiguous**: two branches stamped 2 for different additions, so a v2-stamped
57//!    catalog may be missing `albums` **or** `cached_representations` depending on which build
58//!    created it. The 2 → 3 step therefore re-asserts the whole v2 shape before adding its own
59//!    tables. Every statement involved is `IF NOT EXISTS`, so this costs nothing on a catalog
60//!    that already has them.
61//!
62//! [client library layout]: https://docs/design/filesystem/client/#desktop-library-layout
63//! [Maintenance § Repair]: https://docs/design/filesystem/maintenance/#repair
64
65use rusqlite::Connection;
66
67use crate::db::schema::{DDL, SCHEMA_VERSION};
68
69/// The oldest schema version this migrator can walk from.
70///
71/// Also the version an *unstamped* catalog (one that already has tables but reports
72/// `user_version = 0`) is adopted at — v1 predates nothing, so there is no older shape to
73/// mistake it for.
74pub(crate) const BASELINE_VERSION: u32 = 1;
75
76/// A single DDL statement (or batch) in a migration step, plus the condition under which it
77/// runs.
78///
79/// Conditions are declarative rather than closures so that a step's entire behaviour is
80/// visible in its data, and therefore fingerprintable — see the immutability rule in the
81/// module docs.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub(crate) enum Ddl {
84    /// Run unconditionally. Must be idempotent (`IF NOT EXISTS` / `DROP … IF EXISTS`).
85    Always(&'static str),
86    /// Run only when `table` **has** `column` — used for renames of a column that an
87    /// ambiguous historical stamp may or may not still carry.
88    IfColumnPresent {
89        table: &'static str,
90        column: &'static str,
91        sql: &'static str,
92    },
93    /// Run only when `table` **lacks** `column` — used for `ALTER TABLE … ADD COLUMN`, which
94    /// is not idempotent on its own.
95    IfColumnMissing {
96        table: &'static str,
97        column: &'static str,
98        sql: &'static str,
99    },
100}
101
102impl Ddl {
103    /// Canonical single-line rendering, hashed into the step fingerprint. Whitespace inside
104    /// `sql` is preserved deliberately: reformatting a shipped statement is an edit like any
105    /// other, and the point of the lock is that shipped text does not move.
106    #[cfg(test)]
107    fn fingerprint_line(&self) -> String {
108        match self {
109            Self::Always(sql) => format!("A|{sql}"),
110            Self::IfColumnPresent { table, column, sql } => format!("P|{table}.{column}|{sql}"),
111            Self::IfColumnMissing { table, column, sql } => format!("M|{table}.{column}|{sql}"),
112        }
113    }
114}
115
116/// One version-to-version migration step. `to` is always `from + 1`: the walk is stepwise, so
117/// a catalog four versions behind is brought forward by four separate, separately committed
118/// steps rather than one jump.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub(crate) struct Step {
121    pub from: u32,
122    pub to: u32,
123    /// Stable identifier used in logs and in the immutability fingerprint.
124    pub name: &'static str,
125    pub ddl: &'static [Ddl],
126}
127
128impl Step {
129    #[cfg(test)]
130    fn fingerprint_input(&self) -> String {
131        let mut out = format!("{}->{} {}\n", self.from, self.to, self.name);
132        for ddl in self.ddl {
133            out.push_str(&ddl.fingerprint_line());
134            out.push('\n');
135        }
136        out
137    }
138}
139
140// ── The shipped steps ───────────────────────────────────────────────────────
141//
142// APPEND ONLY. See the module docs: a step that has shipped is never edited.
143
144/// v1 → v2. Canonicalises the hash column and creates the two tables that the two colliding
145/// v2 branches introduced between them (`albums` from the iOS branch, `cached_representations`
146/// from the lifecycle-index branch).
147///
148/// The rename is conditional because it shipped inside v1 without a bump: a v1-stamped catalog
149/// created before `1776c04` has `hash_blake3`, one created after has `hash_sha256`.
150const STEP_1_TO_2: Step = Step {
151    from: 1,
152    to: 2,
153    name: "v1_to_v2_sha256_albums_and_cache",
154    ddl: &[
155        Ddl::IfColumnPresent {
156            table: "assets",
157            column: "hash_blake3",
158            sql: "ALTER TABLE assets RENAME COLUMN hash_blake3 TO hash_sha256;",
159        },
160        // SQLite rewrites dependent index definitions on RENAME COLUMN, but the index is
161        // recreated explicitly so the resulting shape does not depend on that behaviour.
162        Ddl::Always(
163            "DROP INDEX IF EXISTS idx_assets_hash;
164             CREATE INDEX IF NOT EXISTS idx_assets_hash ON assets(hash_sha256);",
165        ),
166        Ddl::Always(
167            "CREATE TABLE IF NOT EXISTS albums (
168                 id              TEXT    PRIMARY KEY,
169                 name            TEXT    NOT NULL,
170                 created_at      INTEGER NOT NULL,
171                 modified_at     INTEGER NOT NULL,
172                 cover_asset_id  TEXT
173             );
174             CREATE INDEX IF NOT EXISTS idx_albums_created ON albums(created_at);
175             CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(asset_type);",
176        ),
177        Ddl::Always(
178            "CREATE TABLE IF NOT EXISTS cached_representations (
179                 uuid              TEXT    NOT NULL,
180                 tier              TEXT    NOT NULL,
181                 format            TEXT,
182                 bytes             INTEGER NOT NULL,
183                 path              TEXT    NOT NULL,
184                 last_accessed_at  INTEGER NOT NULL,
185                 pinned            INTEGER NOT NULL DEFAULT 0,
186                 is_owned_original INTEGER NOT NULL DEFAULT 0,
187                 PRIMARY KEY (uuid, tier)
188             );
189             CREATE INDEX IF NOT EXISTS idx_cache_evict
190                 ON cached_representations(pinned, is_owned_original, last_accessed_at);",
191        ),
192    ],
193};
194
195/// v2 → v3. Adds the `embeddings` provenance companion table.
196///
197/// The `vec0` partition tables are *not* created here: their vector dimension is declared by
198/// the model registry, so they are created at runtime by their writer (see
199/// [`crate::db::VectorTableSpec`]).
200///
201/// The first two statements re-assert the v2 shape. That is not redundancy: two branches
202/// stamped 2 for different additions, so a v2-stamped catalog is missing one of the two tables
203/// depending on which build created it, and the stamp cannot tell us which.
204const STEP_2_TO_3: Step = Step {
205    from: 2,
206    to: 3,
207    name: "v2_to_v3_embeddings",
208    ddl: &[
209        Ddl::Always(
210            "CREATE TABLE IF NOT EXISTS albums (
211                 id              TEXT    PRIMARY KEY,
212                 name            TEXT    NOT NULL,
213                 created_at      INTEGER NOT NULL,
214                 modified_at     INTEGER NOT NULL,
215                 cover_asset_id  TEXT
216             );
217             CREATE INDEX IF NOT EXISTS idx_albums_created ON albums(created_at);
218             CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(asset_type);",
219        ),
220        Ddl::Always(
221            "CREATE TABLE IF NOT EXISTS cached_representations (
222                 uuid              TEXT    NOT NULL,
223                 tier              TEXT    NOT NULL,
224                 format            TEXT,
225                 bytes             INTEGER NOT NULL,
226                 path              TEXT    NOT NULL,
227                 last_accessed_at  INTEGER NOT NULL,
228                 pinned            INTEGER NOT NULL DEFAULT 0,
229                 is_owned_original INTEGER NOT NULL DEFAULT 0,
230                 PRIMARY KEY (uuid, tier)
231             );
232             CREATE INDEX IF NOT EXISTS idx_cache_evict
233                 ON cached_representations(pinned, is_owned_original, last_accessed_at);",
234        ),
235        Ddl::Always(
236            "CREATE TABLE IF NOT EXISTS embeddings (
237                 asset_id      TEXT    NOT NULL,
238                 task          TEXT    NOT NULL,
239                 platform      TEXT    NOT NULL,
240                 model_id      TEXT    NOT NULL,
241                 model_version TEXT    NOT NULL,
242                 vec_rowid     INTEGER NOT NULL,
243                 created_at    INTEGER NOT NULL,
244                 PRIMARY KEY (asset_id, task, platform)
245             );
246             CREATE INDEX IF NOT EXISTS idx_embeddings_asset ON embeddings(asset_id);
247             CREATE INDEX IF NOT EXISTS idx_embeddings_task  ON embeddings(task, platform, model_version);",
248        ),
249    ],
250};
251
252/// v3 → v4. Adds `assets.is_hidden`, the index projection of the sidecar `hidden` LWW register.
253///
254/// Existing rows default to `0` — not hidden — which is the correct reading of a catalog whose
255/// sidecars predate the register. The gated Hidden view is empty until the sidecars are
256/// re-projected, rather than a random subset of the library disappearing from the timeline.
257///
258/// `idx_assets_timeline` is dropped and recreated rather than left alone: v4 widened it to
259/// include `is_hidden`, and `CREATE INDEX IF NOT EXISTS` would silently keep the narrow one.
260const STEP_3_TO_4: Step = Step {
261    from: 3,
262    to: 4,
263    name: "v3_to_v4_hidden_assets",
264    ddl: &[
265        Ddl::IfColumnMissing {
266            table: "assets",
267            column: "is_hidden",
268            sql: "ALTER TABLE assets ADD COLUMN is_hidden INTEGER NOT NULL DEFAULT 0;",
269        },
270        Ddl::Always(
271            "CREATE INDEX IF NOT EXISTS idx_assets_hidden ON assets(is_hidden);
272             DROP INDEX IF EXISTS idx_assets_timeline;
273             CREATE INDEX IF NOT EXISTS idx_assets_timeline
274                 ON assets(is_deleted, is_stack_hidden, is_hidden, capture_utc, capture_timestamp);",
275        ),
276    ],
277};
278
279/// v4 → v5. Adds `assets.caption`, `assets.latitude` and `assets.longitude`, the index
280/// projections of the sidecar `caption` LWW register and of its effective location.
281///
282/// Existing rows read `NULL` — no caption, no location — until their sidecars are re-projected
283/// (the next signed write to the asset, or `rebuild_index`). SQL cannot read a sealed sidecar,
284/// so the step cannot backfill them; the sidecar stays the only copy of record either way, so
285/// nothing is lost while the projection trails it.
286const STEP_4_TO_5: Step = Step {
287    from: 4,
288    to: 5,
289    name: "v4_to_v5_caption_and_location",
290    ddl: &[
291        Ddl::IfColumnMissing {
292            table: "assets",
293            column: "caption",
294            sql: "ALTER TABLE assets ADD COLUMN caption TEXT;",
295        },
296        Ddl::IfColumnMissing {
297            table: "assets",
298            column: "latitude",
299            sql: "ALTER TABLE assets ADD COLUMN latitude REAL;",
300        },
301        Ddl::IfColumnMissing {
302            table: "assets",
303            column: "longitude",
304            sql: "ALTER TABLE assets ADD COLUMN longitude REAL;",
305        },
306    ],
307};
308
309/// v5 → v6. Adds `idx_assets_album_recency`, the covering index the album order reads: the
310/// latest effective capture among each album's assets that are neither hidden nor trashed.
311///
312/// Index-only: no column is added and no row is touched, so the step cannot lose or reorder
313/// anything a v5 catalog holds. Recency is derived from columns every v5 row already carries.
314const STEP_5_TO_6: Step = Step {
315    from: 5,
316    to: 6,
317    name: "v5_to_v6_album_recency_index",
318    ddl: &[Ddl::Always(
319        "CREATE INDEX IF NOT EXISTS idx_assets_album_recency
320             ON assets(album_id, is_deleted, is_hidden, capture_utc, capture_timestamp);",
321    )],
322};
323
324/// v6 → v7. Adds the `upload_guards` table: an original's source guard — its identity and
325/// every STREAM chunk's authentication tag — recorded when its upload bundle is built.
326///
327/// Additive: a new table, no row of an existing one touched. A v6 catalog holds no guard, and
328/// none is needed for it: every bundle re-records its guard in the hashing pass that builds it.
329const STEP_6_TO_7: Step = Step {
330    from: 6,
331    to: 7,
332    name: "v6_to_v7_upload_guards",
333    ddl: &[Ddl::Always(
334        "CREATE TABLE IF NOT EXISTS upload_guards (
335             asset_id        TEXT    PRIMARY KEY,
336             nonce_prefix    BLOB    NOT NULL,
337             plaintext_size  INTEGER NOT NULL,
338             source_len      INTEGER NOT NULL,
339             modified_ns     INTEGER,
340             file_dev        INTEGER,
341             file_ino        INTEGER,
342             ctime_secs      INTEGER,
343             ctime_nanos     INTEGER,
344             chunk_tags      BLOB    NOT NULL,
345             recorded_at     INTEGER NOT NULL
346         );",
347    )],
348};
349
350/// Every shipped step, in ascending order. Append only.
351pub(crate) const STEPS: &[Step] = &[
352    STEP_1_TO_2,
353    STEP_2_TO_3,
354    STEP_3_TO_4,
355    STEP_4_TO_5,
356    STEP_5_TO_6,
357    STEP_6_TO_7,
358];
359
360/// SHA-256 (hex) of each shipped step's canonical rendering, parallel to [`STEPS`].
361///
362/// This is the immutability lock described in the module docs. Appending a step appends a
363/// fingerprint; editing a shipped step changes an existing one, which fails
364/// `shipped_steps_are_immutable`.
365#[cfg(test)]
366const STEP_FINGERPRINTS: &[&str] = &[
367    // v1 -> v2  v1_to_v2_sha256_albums_and_cache
368    "320b317864ff7cdd1a46cc65ec1b864a7b8ae675411521dcb449593bfabd93a4",
369    // v2 -> v3  v2_to_v3_embeddings
370    "15ff0fc10221e1d01deebaafd9b8855b8a9f59491285379a11bf90ba7756f2f6",
371    // v3 -> v4  v3_to_v4_hidden_assets
372    "420ac7077cf5dd3d5888ce07594263e8ace4558adc79f8972096d80ef9a6fe14",
373    // v4 -> v5  v4_to_v5_caption_and_location
374    "a11341c354995462fad47c5f15f02450d4a90d8d0ab3e69fa5cba55da5982004",
375    // v5 -> v6  v5_to_v6_album_recency_index
376    "249e75f76146b3efea9bb2b371937f45132872edade608b72272cd415f4ab747",
377    // v6 -> v7  v6_to_v7_upload_guards
378    "def046c476a8ce231351c0f2feb2dbba3bb3cf547675e11b01a576d317f28caf",
379];
380
381// ── Errors ──────────────────────────────────────────────────────────────────
382
383/// Why a catalog could not be brought to `SCHEMA_VERSION`.
384#[derive(Debug, thiserror::Error)]
385pub enum MigrationError {
386    /// The catalog was written by a newer build than this one.
387    ///
388    /// **This is a refusal, not a downgrade.** Forward-only settles the direction of
389    /// migration; this settles what happens in the other direction. The catalog is left
390    /// byte-for-byte untouched — no stamp rewrite, no DDL, no drop — because an older binary
391    /// cannot know what invariants the newer schema added, and writing to it would corrupt a
392    /// library the user's *current* build can still open perfectly. The recovery is to update
393    /// the app, which is always available; there is no recovery from silent divergent writes.
394    #[error(
395        "catalog schema v{found} is newer than this build supports (v{supported}); \
396         update Capsule to open this library"
397    )]
398    CatalogTooNew { found: u32, supported: u32 },
399
400    /// No step is registered out of `from`. Structurally impossible while
401    /// `steps_form_a_contiguous_chain` passes; kept so a gap fails loudly rather than looping.
402    #[error("no migration step is registered from catalog schema v{from} (target v{to})")]
403    MissingStep { from: u32, to: u32 },
404
405    /// A step failed. The catalog is still stamped `from`: each step commits atomically, so a
406    /// failure rolls the whole step back and the next open retries it.
407    #[error("catalog migration step v{from} -> v{to} ({name}) failed: {source}")]
408    Step {
409        from: u32,
410        to: u32,
411        name: &'static str,
412        #[source]
413        source: rusqlite::Error,
414    },
415
416    #[error(transparent)]
417    Sqlite(#[from] rusqlite::Error),
418}
419
420impl From<MigrationError> for rusqlite::Error {
421    /// Flatten into the error type the catalog's callers already handle.
422    ///
423    /// [`crate::db::DatabaseDriver::open`] is consumed by `capsule-core-ffi` and
424    /// `library::open` through `rusqlite::Error`, so the migrator's typed error is flattened
425    /// at that boundary rather than rippling a new error type through them. Callers that want
426    /// the typed error call [`DatabaseDriver::migrate`](crate::db::DatabaseDriver::migrate).
427    fn from(err: MigrationError) -> Self {
428        match err {
429            MigrationError::Sqlite(inner) => inner,
430            // `SqliteFailure` with a message is the only rusqlite variant that renders an
431            // arbitrary string verbatim through `Display`, so the migrator's explanation
432            // survives the flattening intact.
433            other => Self::SqliteFailure(
434                rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_ERROR),
435                Some(other.to_string()),
436            ),
437        }
438    }
439}
440
441// ── Outcome ─────────────────────────────────────────────────────────────────
442
443/// One applied step, as reported by `migrate`.
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445pub struct Applied {
446    pub from: u32,
447    pub to: u32,
448    pub name: &'static str,
449}
450
451/// What `migrate` did. Recorded so the CLI, the FFI host, and a support bundle can all say
452/// exactly what ran against a user's library.
453#[derive(Debug, Clone, PartialEq, Eq)]
454pub struct Outcome {
455    /// The version the catalog reported on open (`0` for a catalog this call created).
456    pub from: u32,
457    /// The version it is stamped at now — always `SCHEMA_VERSION` on success.
458    pub to: u32,
459    /// True when the catalog was empty and the current schema was created outright.
460    pub created: bool,
461    /// The steps applied, in order. Empty for a fresh create and for an already-current open.
462    pub applied: Vec<Applied>,
463}
464
465// ── The migrator ────────────────────────────────────────────────────────────
466
467/// Bring `conn` to [`SCHEMA_VERSION`], creating the schema outright if the catalog is empty.
468///
469/// Fresh catalog → the current [`DDL`] is applied in one shot and stamped. Existing catalog →
470/// the registered [`STEPS`] are walked upward from its `user_version`, each in its own
471/// transaction. Catalog already current → nothing runs. Catalog newer than this build →
472/// [`MigrationError::CatalogTooNew`], with nothing written.
473#[tracing::instrument(level = "debug", skip_all, fields(target_version = SCHEMA_VERSION))]
474pub(crate) fn migrate(conn: &Connection) -> Result<Outcome, MigrationError> {
475    let stamped = read_user_version(conn)?;
476
477    if stamped > SCHEMA_VERSION {
478        tracing::error!(
479            found = stamped,
480            supported = SCHEMA_VERSION,
481            "catalog migration: refusing to open a catalog newer than this build; \
482             nothing was written"
483        );
484        return Err(MigrationError::CatalogTooNew {
485            found: stamped,
486            supported: SCHEMA_VERSION,
487        });
488    }
489
490    let from = if stamped == 0 {
491        if is_empty(conn)? {
492            tracing::info!(
493                version = SCHEMA_VERSION,
494                "catalog migration: empty catalog, creating the current schema"
495            );
496            create_fresh(conn)?;
497            return Ok(Outcome {
498                from: 0,
499                to: SCHEMA_VERSION,
500                created: true,
501                applied: Vec::new(),
502            });
503        }
504        // Tables but no stamp: a catalog written before the stamp existed, or one whose header
505        // was lost. v1 is the oldest shape that ever shipped, so adopt it and walk up; the
506        // 1 -> 2 step's conditions tolerate either v1 dialect.
507        tracing::warn!(
508            baseline = BASELINE_VERSION,
509            "catalog migration: catalog has tables but no user_version stamp; \
510             adopting the baseline version and migrating forward"
511        );
512        BASELINE_VERSION
513    } else {
514        stamped
515    };
516
517    if from == SCHEMA_VERSION {
518        tracing::debug!(
519            version = SCHEMA_VERSION,
520            "catalog migration: already at the current schema version, no steps to apply"
521        );
522        return Ok(Outcome {
523            from,
524            to: SCHEMA_VERSION,
525            created: false,
526            applied: Vec::new(),
527        });
528    }
529
530    tracing::info!(
531        from,
532        to = SCHEMA_VERSION,
533        "catalog migration: upgrading the catalog schema"
534    );
535
536    let mut cursor = from;
537    let mut applied = Vec::new();
538    while cursor < SCHEMA_VERSION {
539        let step = STEPS
540            .iter()
541            .find(|s| s.from == cursor)
542            .ok_or(MigrationError::MissingStep {
543                from: cursor,
544                to: SCHEMA_VERSION,
545            })?;
546        apply_step(conn, step)?;
547        applied.push(Applied {
548            from: step.from,
549            to: step.to,
550            name: step.name,
551        });
552        cursor = step.to;
553    }
554
555    tracing::info!(
556        from,
557        to = cursor,
558        steps = applied.len(),
559        "catalog migration: complete"
560    );
561
562    Ok(Outcome {
563        from,
564        to: cursor,
565        created: false,
566        applied,
567    })
568}
569
570/// Apply one step atomically: every statement plus the stamp bump commit together, so a
571/// failure leaves the catalog at `step.from` and the next open retries the same step.
572fn apply_step(conn: &Connection, step: &Step) -> Result<(), MigrationError> {
573    tracing::info!(
574        from = step.from,
575        to = step.to,
576        name = step.name,
577        statements = step.ddl.len(),
578        "catalog migration: applying step"
579    );
580
581    let run = |tx: &rusqlite::Transaction<'_>| -> Result<(), rusqlite::Error> {
582        for (idx, ddl) in step.ddl.iter().enumerate() {
583            match ddl {
584                Ddl::Always(sql) => {
585                    tracing::trace!(step = step.name, idx, "catalog migration: exec");
586                    tx.execute_batch(sql)?;
587                }
588                Ddl::IfColumnPresent { table, column, sql } => {
589                    let present = has_column(tx, table, column)?;
590                    tracing::trace!(
591                        step = step.name,
592                        idx,
593                        table,
594                        column,
595                        present,
596                        "catalog migration: guarded exec (if column present)"
597                    );
598                    if present {
599                        tx.execute_batch(sql)?;
600                    }
601                }
602                Ddl::IfColumnMissing { table, column, sql } => {
603                    let present = has_column(tx, table, column)?;
604                    tracing::trace!(
605                        step = step.name,
606                        idx,
607                        table,
608                        column,
609                        present,
610                        "catalog migration: guarded exec (if column missing)"
611                    );
612                    if !present {
613                        tx.execute_batch(sql)?;
614                    }
615                }
616            }
617        }
618        tx.execute_batch(&format!("PRAGMA user_version = {};", step.to))
619    };
620
621    let tx = conn.unchecked_transaction()?;
622    match run(&tx) {
623        Ok(()) => {
624            tx.commit()?;
625            tracing::info!(
626                from = step.from,
627                to = step.to,
628                name = step.name,
629                "catalog migration: step committed"
630            );
631            Ok(())
632        }
633        Err(source) => {
634            // Explicit rollback so the failure is logged next to the reason; the guard would
635            // roll back on drop regardless.
636            let rollback = tx.rollback();
637            tracing::error!(
638                from = step.from,
639                to = step.to,
640                name = step.name,
641                error = %source,
642                rollback_ok = rollback.is_ok(),
643                "catalog migration: step failed and was rolled back; \
644                 the catalog is unchanged at its previous version"
645            );
646            Err(MigrationError::Step {
647                from: step.from,
648                to: step.to,
649                name: step.name,
650                source,
651            })
652        }
653    }
654}
655
656/// Create the current schema on an empty catalog and stamp it.
657///
658/// The DDL runs outside a transaction because it opens with `PRAGMA journal_mode = WAL`, which
659/// SQLite refuses to change inside one. That is safe here and only here: the catalog is empty,
660/// so a partial failure leaves nothing worth preserving and the next open starts over.
661fn create_fresh(conn: &Connection) -> Result<(), rusqlite::Error> {
662    conn.execute_batch(DDL)?;
663    conn.execute_batch(&format!("PRAGMA user_version = {SCHEMA_VERSION};"))
664}
665
666fn read_user_version(conn: &Connection) -> Result<u32, rusqlite::Error> {
667    conn.query_row("PRAGMA user_version", [], |row| row.get(0))
668}
669
670/// True when the catalog holds no user tables — the fresh-install signal, distinct from a
671/// populated catalog whose stamp was lost.
672fn is_empty(conn: &Connection) -> Result<bool, rusqlite::Error> {
673    let count: i64 = conn.query_row(
674        "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
675        [],
676        |row| row.get(0),
677    )?;
678    Ok(count == 0)
679}
680
681/// Whether `table` has `column`. `table` is always a step-local `&'static str`, never caller
682/// input, so the interpolation cannot carry anything but our own identifiers.
683fn has_column(conn: &Connection, table: &str, column: &str) -> Result<bool, rusqlite::Error> {
684    let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
685    let mut rows = stmt.query([])?;
686    while let Some(row) = rows.next()? {
687        let name: String = row.get(1)?;
688        if name == column {
689            return Ok(true);
690        }
691    }
692    Ok(false)
693}
694
695#[cfg(test)]
696#[allow(clippy::unwrap_used)]
697mod tests;