out-of-your-element/db/migrate.js

44 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-09-30 12:24:05 +00:00
// @ts-check
const fs = require("fs")
const {join} = require("path")
async function migrate(db) {
let files = fs.readdirSync(join(__dirname, "migrations"))
files = files.sort()
db.prepare("CREATE TABLE IF NOT EXISTS migration (filename TEXT NOT NULL)").run()
let progress = db.prepare("SELECT * FROM migration").pluck().get()
if (!progress) {
progress = ""
db.prepare("INSERT INTO migration VALUES ('')").run()
}
let migrationRan = false
for (const filename of files) {
2024-01-19 03:42:00 +00:00
/* c8 ignore next - we can't unit test this, but it's run on every real world bridge startup */
2023-09-30 12:24:05 +00:00
if (progress >= filename) continue
console.log(`Applying database migration ${filename}`)
if (filename.endsWith(".sql")) {
const sql = fs.readFileSync(join(__dirname, "migrations", filename), "utf8")
db.exec(sql)
} else if (filename.endsWith(".js")) {
await require("./" + join("migrations", filename))(db)
} else {
continue
}
migrationRan = true
db.transaction(() => {
db.prepare("DELETE FROM migration").run()
db.prepare("INSERT INTO migration VALUES (?)").run(filename)
})()
}
if (migrationRan) {
console.log("Database migrations all done.")
}
}
module.exports.migrate = migrate