- scripts/db-deploy.js:建库(有权限时) → 基线表 sql/schema.sql → 全部未执行的 database/migrations, 幂等可重复执行;--check 只列出待执行迁移(有 pending 时退出码 1),便于上线前/CI 卡一道 - 保留仓库内所有迁移脚本:sql/migrations 历史补丁、database/migrations、一次性数据脚本都不删不改, 顺序与用途写进 README「部署 / 升级(库结构)」 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
172 lines
6.1 KiB
JavaScript
172 lines
6.1 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 部署 / 升级时**一次执行**的库结构脚本(幂等,可反复跑)
|
||
*
|
||
* npm run db:deploy # 建库(缺则建) + 基线表 + 全部未执行的迁移
|
||
* npm run db:deploy -- --check # 只检查:列出还没执行的迁移,不改库
|
||
* npm run db:deploy -- --dry-run # 同上(别名)
|
||
*
|
||
* 执行顺序(**所有迁移脚本都保留在仓库里**,这里只是按固定顺序跑一遍):
|
||
* 1. `sql/schema.sql` 基线表(CREATE TABLE IF NOT EXISTS,可重复执行)
|
||
* 2. `database/migrations/*.js` Sequelize 迁移(靠 SequelizeMeta 记账,只跑没跑过的)
|
||
*
|
||
* `sql/migrations/*.sql` 是**历史一次性补丁**(重建 users、加列、删旧 devices 表),
|
||
* 只为老库保留:新库的 schema.sql 已经包含最终结构,重复执行会报 Duplicate column。
|
||
* 需要给很老的库补跑时手动执行,见 README「快速开始」。
|
||
*
|
||
* 连接信息与运行时同源:环境变量 > config/config.local.js > 默认值(scripts/db-config.js)。
|
||
*/
|
||
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const { spawnSync } = require('child_process');
|
||
const mysql = require('mysql2/promise');
|
||
|
||
const resolveDbConfig = require('./db-config');
|
||
|
||
const ROOT = path.join(__dirname, '..');
|
||
const SCHEMA_FILE = path.join(ROOT, 'sql', 'schema.sql');
|
||
const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations');
|
||
const META_TABLE = 'SequelizeMeta';
|
||
|
||
const args = process.argv.slice(2);
|
||
const checkOnly = args.includes('--check') || args.includes('--dry-run');
|
||
|
||
/** 去掉 -- 行注释,再按分号切分成可逐条执行的语句(与 init-db.js 同一套规则) */
|
||
function splitStatements(sql) {
|
||
return sql
|
||
.split(/\r?\n/)
|
||
.filter((line) => !line.trim().startsWith('--'))
|
||
.join('\n')
|
||
.split(';')
|
||
.map((stmt) => stmt.trim())
|
||
.filter(Boolean);
|
||
}
|
||
|
||
/** 仓库里的全部迁移文件名(按文件名升序 = 执行顺序) */
|
||
function migrationFiles() {
|
||
if (!fs.existsSync(MIGRATIONS_DIR)) return [];
|
||
return fs.readdirSync(MIGRATIONS_DIR)
|
||
.filter((name) => name.endsWith('.js'))
|
||
.sort();
|
||
}
|
||
|
||
/** 已执行的迁移名(元数据表不存在 = 一条都没跑过) */
|
||
async function appliedMigrations(conn) {
|
||
try {
|
||
const [rows] = await conn.query(`SELECT name FROM \`${META_TABLE}\` ORDER BY name`);
|
||
return rows.map((row) => row.name);
|
||
} catch (err) {
|
||
if (err.code === 'ER_NO_SUCH_TABLE') return [];
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
async function connect(config, database) {
|
||
const options = { host: config.host, port: config.port, user: config.user, password: config.password };
|
||
if (database) options.database = database;
|
||
return mysql.createConnection(options);
|
||
}
|
||
|
||
/** 库不存在就建(账号没有建库权限时只告警,交给 DBA 预先建好) */
|
||
async function ensureDatabase(config) {
|
||
const conn = await connect(config);
|
||
try {
|
||
await conn.query(
|
||
`CREATE DATABASE IF NOT EXISTS \`${config.database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci`,
|
||
);
|
||
console.log(`[db:deploy] 数据库就绪:${config.database}`);
|
||
} catch (err) {
|
||
console.warn(`[db:deploy] 跳过建库(${err.code || err.message}),请确认库 ${config.database} 已由 DBA 建好`);
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
}
|
||
|
||
/** 基线表:schema.sql 全部是 CREATE TABLE IF NOT EXISTS,重复执行安全 */
|
||
async function applyBaseSchema(conn) {
|
||
const statements = splitStatements(fs.readFileSync(SCHEMA_FILE, 'utf8'));
|
||
console.log(`[db:deploy] 应用基线表:sql/schema.sql(${statements.length} 条语句)`);
|
||
for (const stmt of statements) {
|
||
await conn.query(stmt);
|
||
}
|
||
}
|
||
|
||
/** 执行 sequelize-cli(走本地依赖,不联网) */
|
||
function runSequelizeMigrate() {
|
||
const cli = require.resolve('sequelize-cli/lib/sequelize');
|
||
const result = spawnSync(process.execPath, [ cli, 'db:migrate' ], {
|
||
cwd: ROOT,
|
||
stdio: 'inherit',
|
||
env: process.env,
|
||
});
|
||
if (result.status !== 0) {
|
||
throw new Error(`sequelize-cli db:migrate 退出码 ${result.status}`);
|
||
}
|
||
}
|
||
|
||
async function main() {
|
||
const config = resolveDbConfig();
|
||
console.log(`[db:deploy] 目标:${config.host}:${config.port}/${config.database} as ${config.user}`);
|
||
|
||
if (checkOnly) {
|
||
const conn = await connect(config, config.database);
|
||
try {
|
||
const applied = new Set(await appliedMigrations(conn));
|
||
const pending = migrationFiles().filter((name) => !applied.has(name));
|
||
console.log(`[db:deploy] 已执行 ${applied.size} 条,待执行 ${pending.length} 条`);
|
||
for (const name of pending) console.log(` pending ${name}`);
|
||
if (pending.length) process.exitCode = 1;
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
return;
|
||
}
|
||
|
||
await ensureDatabase(config);
|
||
|
||
const conn = await connect(config, config.database);
|
||
try {
|
||
await applyBaseSchema(conn);
|
||
} finally {
|
||
await conn.end();
|
||
}
|
||
|
||
const before = new Set();
|
||
const conn2 = await connect(config, config.database);
|
||
try {
|
||
for (const name of await appliedMigrations(conn2)) before.add(name);
|
||
} finally {
|
||
await conn2.end();
|
||
}
|
||
|
||
console.log(`[db:deploy] 执行 SQL 迁移:database/migrations(${migrationFiles().length} 条,已执行 ${before.size} 条)`);
|
||
runSequelizeMigrate();
|
||
|
||
const conn3 = await connect(config, config.database);
|
||
try {
|
||
const applied = await appliedMigrations(conn3);
|
||
const pending = migrationFiles().filter((name) => !applied.includes(name));
|
||
const done = migrationFiles().filter((name) => !before.has(name));
|
||
|
||
for (const name of done) console.log(` applied ${name}`);
|
||
if (pending.length) {
|
||
console.warn(`[db:deploy] ⚠️ 仍有 ${pending.length} 条未执行:${pending.join(', ')}`);
|
||
process.exitCode = 1;
|
||
return;
|
||
}
|
||
|
||
const [tables] = await conn3.query('SHOW TABLES');
|
||
const names = tables.map((row) => Object.values(row)[0]);
|
||
console.log(`[db:deploy] 完成:本次执行 ${done.length} 条迁移,库内 ${names.length} 张表`);
|
||
} finally {
|
||
await conn3.end();
|
||
}
|
||
}
|
||
|
||
main().catch((err) => {
|
||
console.error(`[db:deploy] 失败:${err.code || ''} ${err.message}`);
|
||
process.exit(1);
|
||
});
|