const assert = require("node:assert/strict"); const fs = require("node:fs"); const sqlite = require("./napi-sqlite.node"); const { difference, log } = require("./utils"); const MIGRATIONS_DIR = __dirname + "/sql/migrations/"; const MIGRATION_FILENAMES = fs.readdirSync(MIGRATIONS_DIR, "UTF-8"); let db = null; const init = async (dbName = process.env.PAPO_DB_PATH) => { 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;"); }; module.exports = { init, };