61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
import { sql } from 'drizzle-orm';
|
|
import { execSync } from 'child_process';
|
|
import { config } from '../modules/config.ts';
|
|
|
|
const VERSION_TABLE = '__db_version';
|
|
const CURRENT_VERSION = '0.1.0';
|
|
|
|
function getDb() {
|
|
return drizzle(config.DATABASE_URL || '');
|
|
}
|
|
|
|
export async function syncDatabase() {
|
|
const database = getDb();
|
|
|
|
try {
|
|
// 1. 确保版本表存在
|
|
await database.execute(sql`
|
|
CREATE TABLE IF NOT EXISTS ${VERSION_TABLE} (
|
|
id SERIAL PRIMARY KEY,
|
|
version VARCHAR(255) NOT NULL,
|
|
applied_at TIMESTAMP DEFAULT NOW()
|
|
)
|
|
`);
|
|
|
|
// 2. 获取当前数据库版本
|
|
const result = await database.execute(sql`
|
|
SELECT version FROM ${VERSION_TABLE} ORDER BY id DESC LIMIT 1
|
|
`);
|
|
const dbVersion = result.rows[0]?.version;
|
|
|
|
// 3. 版本对比
|
|
if (dbVersion === CURRENT_VERSION) {
|
|
console.log('[DB Sync] Version up to date:', CURRENT_VERSION);
|
|
return;
|
|
}
|
|
|
|
console.log(`[DB Sync] Version mismatch: DB=${dbVersion}, Code=${CURRENT_VERSION}`);
|
|
console.log('[DB Sync] Running drizzle-kit push...');
|
|
|
|
// 4. 执行 drizzle-kit push
|
|
execSync('npx drizzle-kit push --force', {
|
|
cwd: process.cwd(),
|
|
stdio: 'inherit',
|
|
env: { ...process.env, DATABASE_URL: config.DATABASE_URL },
|
|
});
|
|
|
|
// 5. 更新版本记录
|
|
await database.execute(sql`
|
|
INSERT INTO ${VERSION_TABLE} (version) VALUES (${CURRENT_VERSION})
|
|
`);
|
|
|
|
console.log('[DB Sync] Migration completed, version updated to:', CURRENT_VERSION);
|
|
} catch (error) {
|
|
console.error('[DB Sync] Migration failed:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export const sync = syncDatabase;
|