forked from cadence/out-of-your-element
Add database migrations
This commit is contained in:
parent
7a218f1254
commit
1d99b91ef7
11 changed files with 263 additions and 33 deletions
42
db/migrate.js
Normal file
42
db/migrate.js
Normal file
|
@ -0,0 +1,42 @@
|
|||
// @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) {
|
||||
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
|
Loading…
Add table
Add a link
Reference in a new issue