This commit is contained in:
yml
2026-04-08 16:30:42 +08:00
commit 313c036845
131 changed files with 22393 additions and 0 deletions
+47
View File
@@ -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()
}