| 32 | } |
| 33 | |
| 34 | function applyMigrations(db: Database.Database): void { |
| 35 | db.exec(` |
| 36 | CREATE TABLE IF NOT EXISTS _migrations ( |
| 37 | name TEXT PRIMARY KEY, |
| 38 | applied_at TEXT NOT NULL |
| 39 | ); |
| 40 | `); |
| 41 | |
| 42 | const applied = new Set( |
| 43 | (db.prepare("SELECT name FROM _migrations").all() as { name: string }[]).map( |
| 44 | (row) => row.name, |
| 45 | ), |
| 46 | ); |
| 47 | |
| 48 | for (const migration of MIGRATIONS) { |
| 49 | if (applied.has(migration.name)) continue; |
| 50 | const tx = db.transaction(() => { |
| 51 | db.exec(migration.sql); |
| 52 | db.prepare("INSERT INTO _migrations (name, applied_at) VALUES (?, ?)").run( |
| 53 | migration.name, |
| 54 | new Date().toISOString(), |
| 55 | ); |
| 56 | }); |
| 57 | tx(); |
| 58 | } |
| 59 | } |