// 执行 schema.sql 到远程数据库 // 用法:node run_schema.js const mysql = require('mysql2/promise') const fs = require('fs') const path = require('path') require('dotenv').config({ path: path.join(__dirname, '.env') }) const CONFIG = { host: '110.42.255.239', port: 3306, user: 'root', password: 'Wentian9588.', database: 'miniprogram', multipleStatements: true, charset: 'utf8mb4' } const SCHEMA_PATH = path.join(__dirname, 'config', 'schema.sql') function splitSql(sql) { // 去掉 -- 注释行 const lines = sql.split('\n').map(l => l.replace(/--.*$/, '')).join('\n') // 按 ; 切分(保留完整语句) const stmts = [] let buf = '' let inString = false let stringChar = '' for (let i = 0; i < lines.length; i++) { const ch = lines[i] if (inString) { buf += ch if (ch === stringChar && lines[i - 1] !== '\\') { inString = false } continue } if (ch === "'" || ch === '"') { inString = true stringChar = ch buf += ch continue } if (ch === ';') { const s = buf.trim() if (s) stmts.push(s) buf = '' continue } buf += ch } const tail = buf.trim() if (tail) stmts.push(tail) return stmts } async function main() { const sql = fs.readFileSync(SCHEMA_PATH, 'utf8') const statements = splitSql(sql) console.log(`解析到 ${statements.length} 条语句`) const connection = await mysql.createConnection(CONFIG) console.log(`已连接 ${CONFIG.host}:${CONFIG.port}/${CONFIG.database}`) let ok = 0 let fail = 0 for (let i = 0; i < statements.length; i++) { const stmt = statements[i] const preview = stmt.replace(/\s+/g, ' ').slice(0, 80) try { await connection.query(stmt) ok++ console.log(`[${i + 1}/${statements.length}] OK ${preview}`) } catch (err) { fail++ console.error(`[${i + 1}/${statements.length}] FAIL ${preview}`) console.error(` ${err.code || ''} ${err.sqlMessage || err.message}`) } } console.log(`\n完成 ✅ 成功 ${ok} / 失败 ${fail}`) await connection.end() } main().catch(err => { console.error('连接失败:', err.message) process.exit(1) })