import { drizzle } from 'drizzle-orm/mysql2' import { migrate } from 'drizzle-orm/mysql2/migrator' import { createConnection } from 'mysql2/promise' import path from 'node:path' import { fileURLToPath } from 'node:url' /** * 考虑做成一个脚本,不是在这里执行,暂时无法保证一定在其它插件前最先运行 */ /** * 自动执行 MySQL 数据库迁移 * 等同于命令:drizzle-kit migrate */ export async function runMigrations() { const databaseUrl = process.env.DATABASE_URL if (!databaseUrl) { throw new Error('DATABASE_URL 未设置') } const connection = await createConnection({ uri: databaseUrl, }) const db = drizzle(connection) try { console.log('🚀 开始执行 MySQL 迁移...') const migrationsFolder = path.resolve(process.cwd(), 'migrations') await migrate(db, { migrationsFolder, }) console.log('✅ MySQL 迁移完成!') } catch (err) { console.log('❌ 迁移失败:', err) throw err } finally { await connection.end() } } const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) if (isMain) { runMigrations().catch((err) => { console.error(err) process.exit(1) }) }