diff options
Diffstat (limited to 'src/db.mjs')
-rw-r--r-- | src/db.mjs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/db.mjs b/src/db.mjs new file mode 100644 index 0000000..59d6a0e --- /dev/null +++ b/src/db.mjs @@ -0,0 +1,49 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import url from "node:url"; + +import { difference, log } from "./utils.mjs"; + + +const DIRNAME = path.dirname(url.fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = DIRNAME + "/sql/migrations/"; +const MIGRATION_FILENAMES = fs.readdirSync(MIGRATIONS_DIR, "UTF-8"); + +let db = null; +export const init = async (dbName = process.env.PAPO_DB_PATH || ":memory:") => { + assert(dbName); + + db = await sqlite.open(dbName); + await db.exec(` + BEGIN TRANSACTION; + CREATE TABLE IF NOT EXISTS migrations ( + filename TEXT PRIMARY KEY + ); + COMMIT TRANSACTION; + `); + + const done = await db.all(` + SELECT filename FROM migrations; + `).map(row => row.filename); + const pending = difference( + new Set(MIGRATION_FILENAMES), + new Set(done) + ); + const sortedPending = [...pending].sort((a, b) => a.localeCompare(b)); + + await db.exec("BEGIN TRANSACTION;"); + for (const filename of sortedPending) { + log({ + log: "exec-migration", + filename, + }); + const sql = fs.readFileSync(MIGRATIONS_DIR + filename, "UTF-8"); + await db.exec(sql); + await db.run( + `INSERT INTO migrations (filename) VALUES ($filename);`, + { filename }, + ); + } + await db.exec("COMMIT TRANSACTION;"); +}; |