diff options
author | EuAndreh <eu@euandre.org> | 2024-02-23 11:11:38 -0300 |
---|---|---|
committer | EuAndreh <eu@euandre.org> | 2024-02-23 11:21:21 -0300 |
commit | cd50a23dab8623f232da7d6b1b9511f4590e9788 (patch) | |
tree | 349e111763eac7853d9f1dd7a61e9bce117f3993 /src/accretion.mjs | |
parent | Big cleanup (diff) | |
download | papod-cd50a23dab8623f232da7d6b1b9511f4590e9788.tar.gz papod-cd50a23dab8623f232da7d6b1b9511f4590e9788.tar.xz |
Implement accretion.runMigrations() and wrappings of node-sqlite3
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;") + } +}; |