#!/usr/bin/env node // ===================================================== // 資料庫遷移腳本 // ===================================================== const mysql = require('mysql2/promise'); const fs = require('fs'); const path = require('path'); // 資料庫配置 const dbConfig = { host: process.env.DB_HOST || 'mysql.theaken.com', port: parseInt(process.env.DB_PORT || '33306'), user: process.env.DB_USER || 'AI_Platform', password: process.env.DB_PASSWORD || 'Aa123456', database: process.env.DB_NAME || 'db_AI_Platform', charset: 'utf8mb4', timezone: '+08:00', acquireTimeout: 60000, timeout: 60000, reconnect: true, connectionLimit: 10, queueLimit: 0, }; async function runMigration() { let connection; try { console.log('🚀 開始資料庫遷移...'); // 創建連接 connection = await mysql.createConnection({ ...dbConfig, multipleStatements: true }); console.log('✅ 資料庫連接成功'); // 讀取 SQL 文件 const sqlFile = path.join(__dirname, '..', 'database-schema-simple.sql'); const sqlContent = fs.readFileSync(sqlFile, 'utf8'); console.log('📖 讀取 SQL 文件成功'); // 分割 SQL 語句並逐個執行 console.log('⚡ 執行 SQL 語句...'); const statements = sqlContent .split(';') .map(stmt => stmt.trim()) .filter(stmt => stmt.length > 0 && !stmt.startsWith('--')); for (let i = 0; i < statements.length; i++) { const statement = statements[i]; if (statement.trim()) { try { // 特殊處理 USE 語句 if (statement.toUpperCase().startsWith('USE')) { await connection.query(statement + ';'); } else { await connection.execute(statement + ';'); } console.log(`✅ 執行語句 ${i + 1}/${statements.length}`); } catch (error) { console.error(`❌ 語句 ${i + 1} 執行失敗:`, error.message); console.error(`語句內容: ${statement.substring(0, 100)}...`); throw error; } } } console.log('✅ 資料庫結構創建成功!'); // 驗證表是否創建成功 console.log('🔍 驗證表結構...'); const [tables] = await connection.execute('SHOW TABLES'); console.log(`📊 共創建了 ${tables.length} 個表:`); tables.forEach((table, index) => { const tableName = Object.values(table)[0]; console.log(` ${index + 1}. ${tableName}`); }); // 檢查視圖 console.log('🔍 驗證視圖...'); const [views] = await connection.execute('SHOW FULL TABLES WHERE Table_type = "VIEW"'); console.log(`📈 共創建了 ${views.length} 個視圖:`); views.forEach((view, index) => { const viewName = Object.values(view)[0]; console.log(` ${index + 1}. ${viewName}`); }); // 檢查觸發器 console.log('🔍 驗證觸發器...'); const [triggers] = await connection.execute('SHOW TRIGGERS'); console.log(`⚙️ 共創建了 ${triggers.length} 個觸發器:`); triggers.forEach((trigger, index) => { console.log(` ${index + 1}. ${trigger.Trigger}`); }); console.log('🎉 資料庫遷移完成!'); } catch (error) { console.error('❌ 遷移失敗:', error.message); console.error('詳細錯誤:', error); process.exit(1); } finally { if (connection) { await connection.end(); console.log('🔌 資料庫連接已關閉'); } } } // 執行遷移 if (require.main === module) { runMigration().catch(console.error); } module.exports = { runMigration };