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