diff options
Diffstat (limited to 'src/db.js')
-rw-r--r-- | src/db.js | 58 |
1 files changed, 32 insertions, 26 deletions
@@ -1,43 +1,49 @@ -const fs = require("node:fs"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); + const sqlite = require("./napi-sqlite.node"); +const { difference, log } = require("./utils"); -// const value = 8; -// console.log(`${value} time 2 =`, sqlite.my_function(value)); -const CONFIG_FILE = __dirname + "/sql/config.sql"; const MIGRATIONS_DIR = __dirname + "/sql/migrations/"; +const MIGRATION_FILENAMES = fs.readdirSync(MIGRATIONS_DIR, "UTF-8"); let db = null; -const init = async () => { - console.log({ - sqlite, - }); - console.log(`sqlite.myfn(2): ${sqlite.myfn(2)}`); - console.log(`sqlite.open(2): ${sqlite.open(2)}`); - /* - const config = fs.readFileSync(CONFIG_FILE, "UTF-8"); - const migrations = fs.readdirSync(MIGRATIONS_DIR, "UTF-8"); +const init = async (dbName = process.env.PAPO_DB_PATH) => { + assert(dbName); - await exec(config); - await exec(` + db = await sqlite.open(dbName); + await db.exec(` + BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS migrations ( filename TEXT PRIMARY KEY ); - `); - const done = await run(` - SELECT filename FROM migrations; + COMMIT TRANSACTION; `); - // FIXME: sort - const pending = new Set(migrations).difference(new Set(done)); + 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 exec("BEGIN TRANSACTION;"); - for (const p of pending) { - await exec(fs.readFileSync(MIGRATIONS_DIR + p, "UTF-8")); - await exec(`INSERT INTO migrations (filename) VALUES (?)`, p); + 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 exec("COMMIT TRANSACTION;"); - */ + await db.exec("COMMIT TRANSACTION;"); }; module.exports = { |