fix(state-store): handle FK constraints in v4→v5 migration

The table recreation migration failed on machines with existing
transaction_bills/cassette_bills rows due to FK constraints on
transactions(txid). Also clean up leftover transactions_new table
from any previous failed migration attempt.

Closes #38

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Patrick Mulligan 2026-03-26 15:05:03 -04:00
commit bebe987b60

View file

@ -158,8 +158,12 @@ export function initDatabase(dbPath?: string): void {
if (existing && existing.value === '4') {
// Migration v4 → v5: add manual_dispense type and remediated_by column
// SQLite cannot ALTER CHECK constraints, so recreate the table
// SQLite cannot ALTER CHECK constraints, so recreate the table.
// Disable FK constraints during migration to avoid errors from
// transaction_bills/cassette_bills referencing transactions(txid).
db.pragma('foreign_keys = OFF')
db.exec(`
DROP TABLE IF EXISTS transactions_new;
CREATE TABLE transactions_new (
txid TEXT PRIMARY KEY,
type TEXT NOT NULL CHECK (type IN ('cash_in', 'cash_out', 'manual_dispense')),
@ -179,6 +183,7 @@ export function initDatabase(dbPath?: string): void {
DROP TABLE transactions;
ALTER TABLE transactions_new RENAME TO transactions;
`)
db.pragma('foreign_keys = ON')
db.exec(`
CREATE TABLE IF NOT EXISTS operator_commands (
id INTEGER PRIMARY KEY AUTOINCREMENT,