kanban-persistence-sqlite 0.8.0

SQLite storage backend for the kanban project management tool
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
use std::path::PathBuf;

use chrono::Utc;
use kanban_domain::{KanbanError, KanbanResult};
use sqlx::{Pool, Sqlite};
use uuid::Uuid;

use super::helpers::{db_err, p_uuid};
use super::{SqliteStore, SUPPORTED_SCHEMA_VERSION};

impl SqliteStore {
    pub(crate) async fn load_or_create_instance_id(pool: &Pool<Sqlite>) -> KanbanResult<Uuid> {
        let row: Option<String> =
            sqlx::query_scalar("SELECT instance_id FROM metadata WHERE id = 1")
                .fetch_optional(pool)
                .await
                .map_err(db_err)?;
        match row {
            Some(s) => p_uuid(&s),
            None => {
                let id = Uuid::new_v4();
                let now = Utc::now().to_rfc3339();
                sqlx::query(
                    "INSERT INTO metadata (id, instance_id, saved_at, schema_version) VALUES (1, ?, ?, ?)",
                )
                .bind(id.to_string())
                .bind(&now)
                .bind(SUPPORTED_SCHEMA_VERSION)
                .execute(pool)
                .await
                .map_err(db_err)?;
                Ok(id)
            }
        }
    }

    /// Drops the legacy command_log table if it exists and lacks the new
    /// `batch_index` column. Called before SCHEMA so the new table can be
    /// created cleanly via `CREATE TABLE IF NOT EXISTS`.
    pub(crate) async fn drop_legacy_command_log_if_present(
        pool: &Pool<Sqlite>,
    ) -> KanbanResult<()> {
        let has_command_log: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='command_log'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if !has_command_log {
            return Ok(());
        }
        let has_batch_index_col: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('command_log') WHERE name = 'batch_index'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if !has_batch_index_col {
            tracing::info!(
                "dropping legacy command_log table (pre-KAN-405 schema) so the KAN-191 schema can be applied"
            );
            sqlx::raw_sql("DROP TABLE IF EXISTS command_log")
                .execute(pool)
                .await
                .map_err(db_err)?;
        }
        Ok(())
    }

    pub(crate) async fn migrate(pool: &Pool<Sqlite>) -> KanbanResult<()> {
        // KAN-191 reintroduces command_log persistence (KAN-405 had dropped it).
        // The dense batch_index → JSON mapping is created by SCHEMA at open
        // time; no migration of the legacy column-set is needed because the
        // schema is owned by this crate.
        //
        // KAN-845: this function's steps are idempotent presence-checks, not
        // gated by SUPPORTED_SCHEMA_VERSION themselves. Any step added here
        // that performs an irreversible/structural change must be paired
        // with bumping SUPPORTED_SCHEMA_VERSION (mod.rs) so
        // write_pre_migration_backup fires for it - see that constant's doc
        // comment.

        let has_undo_state: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='undo_state'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;

        if has_undo_state {
            tracing::info!(
                "dropping legacy undo_state table: undo cursor stays in-session, only command_log persists"
            );
            sqlx::raw_sql("DROP TABLE IF EXISTS undo_state")
                .execute(pool)
                .await
                .map_err(db_err)?;
        }

        let has_position_col: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('boards') WHERE name = 'position'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;

        if !has_position_col {
            sqlx::raw_sql("ALTER TABLE boards ADD COLUMN position INTEGER NOT NULL DEFAULT 0")
                .execute(pool)
                .await
                .map_err(db_err)?;
        }

        let has_card_counter_col: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('boards') WHERE name = 'card_counter'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;

        if !has_card_counter_col {
            sqlx::raw_sql("ALTER TABLE boards ADD COLUMN card_counter INTEGER NOT NULL DEFAULT 1")
                .execute(pool)
                .await
                .map_err(db_err)?;
        }

        Self::drop_legacy_card_edges_if_present(pool).await?;

        // KAN-522: ALTER in writer-stamp columns on pre-v2 metadata tables.
        for col in ["writer_version", "writer_commit"] {
            let has_col: bool = sqlx::query_scalar(&format!(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('metadata') WHERE name = '{col}'"
            ))
            .fetch_one(pool)
            .await
            .map_err(db_err)?;
            if !has_col {
                sqlx::raw_sql(&format!("ALTER TABLE metadata ADD COLUMN {col} TEXT"))
                    .execute(pool)
                    .await
                    .map_err(db_err)?;
            }
        }
        // Once the ALTERs above have caught the schema up, normalise
        // schema_version. Doing it unconditionally is idempotent and
        // also self-heals any DBs where the field drifted.
        sqlx::query("UPDATE metadata SET schema_version = ? WHERE id = 1 AND schema_version < ?")
            .bind(SUPPORTED_SCHEMA_VERSION)
            .bind(SUPPORTED_SCHEMA_VERSION)
            .execute(pool)
            .await
            .map_err(db_err)?;

        Ok(())
    }

    /// The durable pre-migration backup path for a given DB file and source
    /// schema version: `<db_path>.v<from_version>.backup`. The JSON
    /// backend's analogous `.v{N}.backup` convention
    /// (`kanban-persistence-json::migration::backup::pre_latest_backup_path_for`)
    /// uses `Path::with_extension`, which REPLACES an existing extension
    /// (`board.json` -> `board.v2.backup`); this uses `OsString::push`,
    /// which APPENDS after it (`kanban.db` -> `kanban.db.v2.backup`), so the
    /// two backends' artifacts share a suffix format but not identical
    /// naming mechanics. Exposed `pub(crate)` so the test module computes
    /// the same path instead of duplicating the formula.
    pub(crate) fn backup_path_for(db_path: &std::path::Path, from_version: u32) -> PathBuf {
        let mut backup = db_path.as_os_str().to_owned();
        backup.push(format!(".v{from_version}.backup"));
        PathBuf::from(backup)
    }

    /// Durable, transactionally-consistent copy of the DB written to
    /// [`Self::backup_path_for`] before an IRREVERSIBLE schema upgrade, so a
    /// user can roll back after downgrading the binary. Kept on success
    /// (unlike the migration's own transaction, which only guards a
    /// mid-migration crash) — a deliberate divergence from the JSON
    /// backend's `.v{N}.backup`, which is removed once its migration step
    /// succeeds: JSON's backup exists only to survive a crash mid-*step*,
    /// while this one is the rollback artifact for the whole
    /// binary-downgrade window, so it must outlive a successful process
    /// exit. No-op if a backup already exists (a prior run's snapshot is
    /// still a valid pre-upgrade copy - never clobber it).
    ///
    /// Written atomically and genuinely no-clobber: `VACUUM INTO` targets a
    /// fresh [`tempfile::NamedTempFile`] scratch path (cryptographically
    /// unique per call, not derived from the PID - two concurrent callers,
    /// even within the same process, can never collide on it), then
    /// [`std::fs::hard_link`] installs it at `backup`. Unlike `rename(2)`,
    /// which on POSIX silently REPLACES an existing destination and returns
    /// `Ok`, `hard_link` atomically fails with `AlreadyExists` if `backup`
    /// already exists - so a genuine concurrent-writer race is resolved by
    /// dropping our copy, never by silently overwriting a valid backup. A
    /// crash or ENOSPC mid-copy never leaves a truncated file at the final
    /// `backup` path for the `backup.exists()` check above to mistake for a
    /// good backup - worst case it leaves an orphaned scratch file in the
    /// same directory. Because its name is single-use-random rather than
    /// derived from `backup`'s path, nothing in this codebase can recognize
    /// and clean it up after a hard crash (no `Drop` runs); this is a
    /// bounded, rare disk-space leak, not a correctness issue - the design
    /// deliberately trades "guessable stale-tmp cleanup" (which the
    /// PID-based scheme this replaces only pretended to provide - it could
    /// only ever clean up its own process's leftovers) for "no
    /// same-path collision risk", which matters more here.
    ///
    /// Uses `VACUUM INTO`: a single consistent file (no `-wal`/`-shm`
    /// sidecars, no manual checkpoint). NOTE: `VACUUM INTO` takes a string
    /// LITERAL, not a bind parameter, so the path is interpolated with
    /// single quotes escaped; a scratch path containing non-UTF8 bytes is
    /// rejected outright with a clear error rather than silently mangled
    /// via a lossy conversion, since a mangled literal would make `VACUUM
    /// INTO` write somewhere other than where this function expects to find
    /// its own output. It also cannot run inside a transaction and fails if
    /// the target file already exists, both satisfied here: `open()` has no
    /// transaction open at this point, and the scratch file is a brand-new
    /// [`tempfile::NamedTempFile`] whose placeholder is removed immediately
    /// before `VACUUM INTO` claims the now-free name.
    ///
    /// Does not implement `kanban_persistence::MigrationStrategy` — that
    /// trait models a file-to-file transform (`detect_version` + `migrate`
    /// returning a new path) built for the JSON backend's
    /// rewrite-the-whole-file chain. SQLite's migrations are in-place
    /// ALTER/CREATE statements against a live connection pool, not file
    /// transforms, so this backend intentionally uses its own mechanism
    /// rather than force-fitting that trait's shape; unifying the two is a
    /// larger cross-crate design change, deferred rather than attempted here.
    ///
    /// No rotation/cleanup policy today: only one migration boundary (2->3)
    /// exists, so at most one backup file accumulates per database. Add a
    /// retention policy when a second irreversible migration is introduced.
    ///
    /// Runs synchronously on the `open()` call path: for a large database
    /// this blocks startup for the duration of the full-file copy and
    /// requires roughly 2x the database's disk space with no upfront
    /// space check. Acceptable for now (this only fires on the rare
    /// irreversible-migration boundary, not on every startup) but a known,
    /// deliberately deferred limitation - a progress indicator and
    /// disk-space precheck belong at the CLI/TUI/MCP call sites that have a
    /// UI to show one, not in this persistence-layer function.
    pub(crate) async fn write_pre_migration_backup(
        pool: &Pool<Sqlite>,
        db_path: &std::path::Path,
        from_version: u32,
    ) -> KanbanResult<()> {
        let backup = Self::backup_path_for(db_path, from_version);

        if backup.exists() {
            tracing::info!(
                path = %backup.display(),
                "pre-migration SQLite backup already present; keeping it"
            );
            return Ok(());
        }

        let parent = db_path
            .parent()
            .map(std::path::Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));
        let tmp = tokio::task::spawn_blocking(move || -> KanbanResult<PathBuf> {
            let named = tempfile::NamedTempFile::new_in(&parent).map_err(KanbanError::Io)?;
            let tmp_path = named.path().to_path_buf();
            // VACUUM INTO refuses to write into a file that already exists,
            // so free the just-reserved unique name for it to claim. The
            // window between this and VACUUM INTO writing to `tmp_path` is
            // not exploitable in practice: the name carries enough entropy
            // that another process guessing it is astronomically unlikely,
            // and even a collision here only fails this attempt's `VACUUM
            // INTO`, never corrupts `backup` itself.
            drop(named);
            Ok(tmp_path)
        })
        .await
        .map_err(|e| KanbanError::Database(e.to_string()))??;

        tracing::info!(
            path = %backup.display(),
            from_version,
            "writing durable pre-migration SQLite backup before irreversible schema upgrade \
             (full copy of the database; may take a while for large databases)"
        );

        let target = match tmp.to_str() {
            Some(s) => s.replace('\'', "''"),
            None => {
                return Err(KanbanError::Database(format!(
                    "pre-migration SQLite backup scratch path is not valid UTF-8: {}",
                    tmp.display()
                )));
            }
        };
        if let Err(e) = sqlx::query(&format!("VACUUM INTO '{target}'"))
            .execute(pool)
            .await
        {
            let _ = tokio::fs::remove_file(&tmp).await;
            return Err(db_err(e));
        }

        match tokio::fs::hard_link(&tmp, &backup).await {
            Ok(()) => {
                let _ = tokio::fs::remove_file(&tmp).await;
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                // Lost a race with a concurrent writer: `backup` was
                // created between our check above and this hard_link.
                // Their copy is equally valid; drop ours.
                let _ = tokio::fs::remove_file(&tmp).await;
            }
            Err(e) => {
                let _ = tokio::fs::remove_file(&tmp).await;
                return Err(KanbanError::Io(e));
            }
        }

        tracing::warn!(
            path = %backup.display(),
            from_version,
            to_version = SUPPORTED_SCHEMA_VERSION,
            "wrote durable pre-migration SQLite backup before irreversible schema upgrade \
             (full copy of the database file)"
        );
        Ok(())
    }

    /// schema 2 -> 3 (KAN-832). Idempotent, additive-in-place (no `.backup`
    /// of its own - see [`Self::write_pre_migration_backup`], which the
    /// `open()` call site invokes before this runs). Two structural changes:
    ///   1. `archived_cards` gains `board_id`, backfilled from the archived
    ///      card's `original_column_id -> columns.board_id`. A row whose
    ///      original column no longer exists gets `Uuid::nil()` + a warning.
    ///   2. `cards` is table-swapped to DROP the `column_id -> columns` FK, so
    ///      deleting a column no longer cascade-deletes an archived card's row.
    ///
    /// Must run BEFORE SCHEMA (SCHEMA's `idx_archived_cards_board_id` fails
    /// against the pre-3 `board_id`-less table).
    ///
    /// FK note (spike-validated): `DROP TABLE cards` with `foreign_keys` ON
    /// fires `ON DELETE CASCADE` on `sprint_logs`/`archived_cards` and WIPES
    /// them. `PRAGMA defer_foreign_keys` defers CHECKING, not cascade ACTIONS,
    /// so it does NOT help. We disable enforcement with `PRAGMA foreign_keys =
    /// OFF` on a dedicated connection OUTSIDE any transaction (the pragma is a
    /// no-op inside a tx), then restore it.
    pub(crate) async fn migrate_v2_to_v3_archived_cards(pool: &Pool<Sqlite>) -> KanbanResult<()> {
        // Fresh DB: archived_cards does not exist yet (SCHEMA creates it in the
        // correct v3 shape). Nothing to migrate.
        let has_archived_cards: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='archived_cards'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if !has_archived_cards {
            return Ok(());
        }
        // Idempotent: already migrated if board_id is present.
        let has_board_id: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('archived_cards') WHERE name = 'board_id'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if has_board_id {
            return Ok(());
        }

        tracing::info!(
            "migrating SQLite schema 2 -> 3: archived_cards.board_id + cards FK decouple"
        );

        // Count the rows whose `original_column_id` no longer resolves to a
        // column (the backfill subquery would yield NULL) so we can warn. This
        // is computed up front against the pre-migration table; the count is
        // identical to the post-backfill `board_id IS NULL` count.
        let unresolved: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM archived_cards
              WHERE (SELECT c.board_id FROM columns c
                       WHERE c.id = archived_cards.original_column_id) IS NULL",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if unresolved > 0 {
            tracing::warn!(
                count = unresolved,
                "archived_cards board_id backfill: unresolvable original_column_id; \
                 setting board_id = nil"
            );
        }

        // Run the whole migration as one `raw_sql` batch on the pool executor.
        // `&Pool` acquires a SINGLE connection for the entire multi-statement
        // string and runs it in one await, so:
        //   * `PRAGMA foreign_keys = OFF` applies to the same connection that
        //     performs the `cards` table swap (a table-swap under FK ON fires
        //     ON DELETE CASCADE on sprint_logs/archived_cards and wipes them);
        //     the pragma is issued OUTSIDE the transaction (before BEGIN), where
        //     it is not a no-op, and restored afterwards.
        //   * the future stays `Send`-provable for the `tokio::spawn`ed
        //     store-open path. Holding an acquired `&mut SqliteConnection`
        //     executor across multiple awaits instead leaves the higher-ranked
        //     `for<'c> &'c mut SqliteConnection: Executor<'c>` / `Send` bound
        //     unresolved, and `tokio::spawn` fails with "implementation of
        //     `Executor`/`Send` is not general enough".
        // The unresolvable rows are set to `Uuid::nil()` via a SQL literal so
        // the batch needs no dynamic binds.
        sqlx::raw_sql(
            "PRAGMA foreign_keys = OFF;
            BEGIN;
            ALTER TABLE archived_cards ADD COLUMN board_id TEXT;
            UPDATE archived_cards
               SET board_id = (SELECT c.board_id FROM columns c
                                 WHERE c.id = archived_cards.original_column_id);
            UPDATE archived_cards
               SET board_id = '00000000-0000-0000-0000-000000000000'
             WHERE board_id IS NULL;
            CREATE TABLE cards_new (
                id TEXT PRIMARY KEY,
                column_id TEXT NOT NULL,
                title TEXT NOT NULL,
                description TEXT,
                priority TEXT NOT NULL DEFAULT 'Medium',
                status TEXT NOT NULL DEFAULT 'Todo',
                position INTEGER NOT NULL,
                due_date TEXT,
                points INTEGER CHECK (points >= 0 AND points <= 255),
                card_number INTEGER NOT NULL DEFAULT 0,
                sprint_id TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                completed_at TEXT,
                FOREIGN KEY (sprint_id) REFERENCES sprints(id) ON DELETE SET NULL
            );
            INSERT INTO cards_new SELECT
                id, column_id, title, description, priority, status, position,
                due_date, points, card_number, sprint_id, created_at, updated_at,
                completed_at
              FROM cards;
            DROP TABLE cards;
            ALTER TABLE cards_new RENAME TO cards;
            COMMIT;
            PRAGMA foreign_keys = ON;",
        )
        .execute(pool)
        .await
        .map_err(db_err)?;
        Ok(())
    }

    /// Schema 4 -> 5 (KAN-963): add `cards.board_id`, a durable board reference
    /// independent of `column_id` (same rationale as `archived_cards.board_id`
    /// above — a card's column can be legitimately deleted once the card is
    /// archived, and board resolution must survive that). Unlike the 2->3
    /// migration, `cards` needs no table rebuild here: `column_id` already
    /// carries no FK, so a plain `ALTER TABLE ADD COLUMN` + backfill suffices.
    pub(crate) async fn migrate_v4_to_v5_cards_board_id(pool: &Pool<Sqlite>) -> KanbanResult<()> {
        // Fresh DB: SCHEMA creates `cards` in the correct v5 shape. Nothing to
        // migrate.
        let has_cards: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='cards'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if !has_cards {
            return Ok(());
        }
        // Idempotent: already migrated if board_id is present.
        let has_board_id: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('cards') WHERE name = 'board_id'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if has_board_id {
            return Ok(());
        }

        tracing::info!("migrating SQLite schema 4 -> 5: cards.board_id + backfill");

        let unresolved: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM cards
              WHERE (SELECT c.board_id FROM columns c
                       WHERE c.id = cards.column_id) IS NULL",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if unresolved > 0 {
            tracing::warn!(
                count = unresolved,
                "cards board_id backfill: unresolvable column_id; setting board_id = nil"
            );
        }

        sqlx::raw_sql(
            "BEGIN;
            ALTER TABLE cards ADD COLUMN board_id TEXT;
            UPDATE cards
               SET board_id = (SELECT c.board_id FROM columns c
                                 WHERE c.id = cards.column_id);
            UPDATE cards
               SET board_id = '00000000-0000-0000-0000-000000000000'
             WHERE board_id IS NULL;
            COMMIT;",
        )
        .execute(pool)
        .await
        .map_err(db_err)?;
        Ok(())
    }

    /// Drop the pre-KAN-504 `card_edges` table (single table with an
    /// `edge_type` column) if present. The per-kind `spawns_edges` /
    /// `blocks_edges` / `relates_edges` tables created by SCHEMA
    /// replace it; nothing of KAN-504's graph work is live so we
    /// don't need to copy data forward — any rows in the legacy
    /// table belong to a development-only database.
    pub(crate) async fn drop_legacy_card_edges_if_present(pool: &Pool<Sqlite>) -> KanbanResult<()> {
        let has_card_edges: bool = sqlx::query_scalar(
            "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='card_edges'",
        )
        .fetch_one(pool)
        .await
        .map_err(db_err)?;
        if !has_card_edges {
            return Ok(());
        }
        tracing::info!(
            "dropping legacy card_edges table (pre per-kind schema); per-kind tables take over"
        );
        sqlx::raw_sql(
            "DROP INDEX IF EXISTS idx_card_edges_source;
             DROP INDEX IF EXISTS idx_card_edges_target;
             DROP TABLE IF EXISTS card_edges;",
        )
        .execute(pool)
        .await
        .map_err(db_err)?;
        Ok(())
    }
}