#!/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 migrateTables() { 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 語句,只保留 CREATE TABLE 語句 const statements = sqlContent .split(';') .map(stmt => stmt.trim()) .filter(stmt => { return stmt.length > 0 && !stmt.startsWith('--') && !stmt.toUpperCase().includes('DELIMITER') && !stmt.toUpperCase().includes('TRIGGER') && !stmt.toUpperCase().includes('CREATE VIEW') && !stmt.toUpperCase().includes('INSERT INTO') && !stmt.toUpperCase().includes('SELECT') && (stmt.toUpperCase().includes('CREATE TABLE') || stmt.toUpperCase().includes('CREATE DATABASE') || stmt.toUpperCase().includes('USE')); }); console.log(`📊 找到 ${statements.length} 個表創建語句`); // 逐個執行語句 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('🎉 資料表遷移完成!'); } catch (error) { console.error('❌ 遷移失敗:', error.message); console.error('詳細錯誤:', error); process.exit(1); } finally { if (connection) { await connection.end(); console.log('🔌 資料庫連接已關閉'); } } } // 執行遷移 if (require.main === module) { migrateTables().catch(console.error); } module.exports = { migrateTables };