diff options
author | EuAndreh <eu@euandre.org> | 2024-02-23 06:05:19 -0300 |
---|---|---|
committer | EuAndreh <eu@euandre.org> | 2024-02-23 06:05:21 -0300 |
commit | c36bf8e3577da31cf6d575879c7e92d3e9c7e4f1 (patch) | |
tree | 4fd5414e76490e297c4c770ff35e09149ef3658f /src/db.mjs | |
parent | Remove C code and cleanup repository (diff) | |
download | papod-c36bf8e3577da31cf6d575879c7e92d3e9c7e4f1.tar.gz papod-c36bf8e3577da31cf6d575879c7e92d3e9c7e4f1.tar.xz |
Big cleanup
- delete all SQLite Node-API code: we'll use the C++ one instead;
- implement hero.mjs, with tests!
- use ESM all over.
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;"); +}; |