| 18 | let cached: CachedHandle | null = null; |
| 19 | |
| 20 | export function getDb(opts: { dbPath?: string } = {}): StageDb { |
| 21 | const dbPath = opts.dbPath ?? getDbPath(); |
| 22 | if (cached && cached.path === dbPath) return cached.drizzle; |
| 23 | if (cached) closeDb(); |
| 24 | |
| 25 | const sqlite = new Database(dbPath); |
| 26 | sqlite.pragma("journal_mode = WAL"); |
| 27 | sqlite.pragma("foreign_keys = ON"); |
| 28 | |
| 29 | const db = drizzle(sqlite, { schema }); |
| 30 | migrate(db, { migrationsFolder: findMigrationsFolder() }); |
| 31 | |
| 32 | cached = { sqlite, drizzle: db, path: dbPath }; |
| 33 | return db; |
| 34 | } |
| 35 | |
| 36 | export function closeDb(): void { |
| 37 | if (!cached) return; |