init-current-schema.js
1.34 KB
#!/usr/bin/env node
/**
* 只对确认为空的新库执行:按当前结构建表、建余额视图,并把现有 migration 记为已执行。
*/
import { recreateBillingViews } from '@drama/billing'
import { applyCurrentSchema, createDb } from '@drama/db'
import { databaseUrlFromArgs } from './env-file.js'
import { migrationTableName, vokoMigrationConfig } from './migration-config.js'
import { vokoTargetTables } from './schema.js'
const db = createDb({ url: databaseUrlFromArgs(process.argv.slice(2)), pool: { min: 1, max: 1 } })
try {
const [rows] = await db.raw('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() LIMIT 1')
if (rows.length > 0) throw new Error(`voko database is not empty: ${rows[0].TABLE_NAME}`)
const createdTables = await applyCurrentSchema(db, vokoTargetTables)
await recreateBillingViews(db)
const [, pending] = await db.migrate.list(vokoMigrationConfig)
const baselined = pending.map((migration) => migration.file)
if (baselined.length > 0) {
const now = new Date()
await db(migrationTableName).insert(baselined.map((name) => ({ name, batch: 1, migration_time: now })))
}
console.log(JSON.stringify({ ok: true, target: '@voko/server', mode: 'init-current-schema', created_tables: createdTables, baselined_migrations: baselined }, null, 2))
} finally {
await db.destroy()
}