54 lines
1.9 KiB
JavaScript
54 lines
1.9 KiB
JavaScript
const mysql = require('mysql2/promise');
|
|
require('dotenv').config();
|
|
|
|
const SOURCE_DB = 'smart_asset_db';
|
|
const TARGET_DBS = ['sokuree_platform_dev', 'sokuree_platform_prod'];
|
|
|
|
async function migrate() {
|
|
const connection = await mysql.createConnection({
|
|
host: process.env.DB_HOST,
|
|
user: process.env.DB_USER,
|
|
password: process.env.DB_PASSWORD,
|
|
port: process.env.DB_PORT || 3306
|
|
});
|
|
|
|
try {
|
|
console.log(`Connected to MySQL at ${process.env.DB_HOST}`);
|
|
|
|
for (const targetDb of TARGET_DBS) {
|
|
console.log(`\nProcessing Target DB: ${targetDb}`);
|
|
|
|
// 1. Create Database
|
|
console.log(`Creating database ${targetDb} if not exists...`);
|
|
await connection.query(`CREATE DATABASE IF NOT EXISTS ${targetDb}`);
|
|
|
|
// 2. Get Tables from Source
|
|
const [tables] = await connection.query(`SHOW TABLES FROM ${SOURCE_DB}`);
|
|
const tableNames = tables.map(row => Object.values(row)[0]);
|
|
|
|
for (const table of tableNames) {
|
|
console.log(` Migrating table: ${table}...`);
|
|
|
|
// 3. Create Table (Structure)
|
|
// Drop if exists to ensure clean state or handle updates?
|
|
// Let's drop for now to ensure exact clone.
|
|
await connection.query(`DROP TABLE IF EXISTS ${targetDb}.${table}`);
|
|
await connection.query(`CREATE TABLE ${targetDb}.${table} LIKE ${SOURCE_DB}.${table}`);
|
|
|
|
// 4. Copy Data
|
|
await connection.query(`INSERT INTO ${targetDb}.${table} SELECT * FROM ${SOURCE_DB}.${table}`);
|
|
console.log(` -> Data copied.`);
|
|
}
|
|
}
|
|
|
|
console.log('\nMigration completed successfully!');
|
|
|
|
} catch (error) {
|
|
console.error('Migration failed:', error);
|
|
} finally {
|
|
await connection.end();
|
|
}
|
|
}
|
|
|
|
migrate();
|