init
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import process from 'node:process'
|
||||
|
||||
import { getDb } from './client.js'
|
||||
|
||||
const CURRENT_DIR = path.dirname(fileURLToPath(import.meta.url))
|
||||
const MIGRATIONS_DIR = path.join(CURRENT_DIR, 'migrations')
|
||||
|
||||
export function runDatabaseMigrations() {
|
||||
const db = getDb()
|
||||
const files = fs.readdirSync(MIGRATIONS_DIR)
|
||||
.filter((name) => name.endsWith('.sql'))
|
||||
.sort()
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
filename TEXT NOT NULL UNIQUE,
|
||||
applied_at TEXT NOT NULL
|
||||
);
|
||||
`)
|
||||
|
||||
const appliedRows = db.prepare('SELECT filename FROM schema_migrations').all()
|
||||
const applied = new Set(appliedRows.map((row) => row.filename))
|
||||
const insertApplied = db.prepare(`
|
||||
INSERT INTO schema_migrations (filename, applied_at)
|
||||
VALUES (?, ?)
|
||||
`)
|
||||
|
||||
for (const filename of files) {
|
||||
if (applied.has(filename)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const sql = fs.readFileSync(path.join(MIGRATIONS_DIR, filename), 'utf8')
|
||||
db.exec(sql)
|
||||
insertApplied.run(filename, new Date().toISOString())
|
||||
}
|
||||
}
|
||||
|
||||
const currentFilePath = fileURLToPath(import.meta.url)
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === currentFilePath) {
|
||||
runDatabaseMigrations()
|
||||
}
|
||||
Reference in New Issue
Block a user