'use strict'; const fs = require('fs'); const path = require('path'); const db = require('../src/infra/db'); const TABLES = ['performance_assessments', 'fault_disposals', 'incident_events']; async function main() { const schema = fs.readFileSync( path.resolve(__dirname, '../../../deploy/mysql/init/01-schema.sql'), 'utf8', ); for (const table of TABLES) { const start = schema.indexOf(`CREATE TABLE ${table} (`); const marker = ') ENGINE=InnoDB;'; const end = schema.indexOf(marker, start); if (start < 0 || end < 0) throw new Error(`未找到 ${table} DDL`); const statement = schema.slice(start, end + marker.length); await db.execute(statement.replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS')); await db.execute( `INSERT INTO sync_table_versions (table_name, version) VALUES (?, 0) ON DUPLICATE KEY UPDATE table_name = VALUES(table_name)`, [table], ); await db.execute( `INSERT INTO modules (\`key\`, status, notes) VALUES (?, 'active', ?) ON DUPLICATE KEY UPDATE status = 'active', notes = VALUES(notes)`, [table, { performance_assessments: '绩效考核', fault_disposals: '故障处置', incident_events: '事故事件' }[table]], ); } await db.execute('ALTER TABLE fault_disposals MODIFY final_result TEXT NULL'); for (const module of ['performance', 'faults', 'incidents', 'audit']) { await db.execute( `INSERT INTO role_permissions (role_id, module, actions) SELECT id, ?, 1 FROM roles ON DUPLICATE KEY UPDATE actions = actions | 1`, [module], ); } await db.execute( `INSERT INTO role_permissions (role_id, module, actions) SELECT id, 'exports', 16 FROM roles ON DUPLICATE KEY UPDATE actions = actions | 16`, ); console.log('monthly materials schema migrated'); } main() .then(() => db.close()) .catch(async (error) => { console.error(error); await db.close(); process.exit(1); });