彻底重构-1

This commit is contained in:
yml
2026-04-09 09:06:08 +08:00
parent b509394b09
commit df2eb34478
92 changed files with 2226 additions and 1261 deletions
+24 -16
View File
@@ -1,33 +1,28 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import process from 'node:process'
import { fileURLToPath } from 'node:url'
import { getDb } from './client.js'
import { closeDb, query, withTransaction } 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()
export async function runDatabaseMigrations() {
const files = fs.readdirSync(MIGRATIONS_DIR)
.filter((name) => name.endsWith('.sql'))
.sort()
db.exec(`
await query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
id BIGSERIAL PRIMARY KEY,
filename TEXT NOT NULL UNIQUE,
applied_at TEXT NOT NULL
);
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)
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 (?, ?)
`)
const appliedRows = await query('SELECT filename FROM schema_migrations')
const applied = new Set(appliedRows.rows.map((row) => String(row.filename)))
for (const filename of files) {
if (applied.has(filename)) {
@@ -35,8 +30,13 @@ export function runDatabaseMigrations() {
}
const sql = fs.readFileSync(path.join(MIGRATIONS_DIR, filename), 'utf8')
db.exec(sql)
insertApplied.run(filename, new Date().toISOString())
await withTransaction(async (client) => {
await client.query(sql)
await client.query(
'INSERT INTO schema_migrations (filename, applied_at) VALUES ($1, NOW())',
[filename],
)
})
}
}
@@ -44,4 +44,12 @@ const currentFilePath = fileURLToPath(import.meta.url)
if (process.argv[1] && path.resolve(process.argv[1]) === currentFilePath) {
runDatabaseMigrations()
.then(async () => {
await closeDb()
})
.catch(async (error) => {
console.error(error)
await closeDb()
process.exit(1)
})
}