241 lines
8.7 KiB
JavaScript
241 lines
8.7 KiB
JavaScript
/**
|
||
* 钻石商品数据迁移脚本 - Node.js
|
||
* Feature: database-migration, Property 2: 数据记录数一致性
|
||
* Feature: database-migration, Property 7: 数据迁移往返一致性
|
||
* Validates: Requirements 6.3
|
||
*
|
||
* 源表: MySQL diamond_products (5 条记录)
|
||
* 目标表: SQL Server diamond_products
|
||
*/
|
||
|
||
const mysql = require('mysql2/promise');
|
||
const sql = require('mssql');
|
||
|
||
// MySQL 配置
|
||
const mysqlConfig = {
|
||
host: '192.168.195.16',
|
||
port: 1887,
|
||
user: 'root',
|
||
password: 'Dbt@com@123',
|
||
database: 'youdas',
|
||
charset: 'utf8mb4'
|
||
};
|
||
|
||
// SQL Server 配置
|
||
const sqlServerConfig = {
|
||
server: '192.168.195.15',
|
||
port: 1433,
|
||
user: 'sa',
|
||
password: 'Dbt@com@123',
|
||
database: 'honey_box',
|
||
options: {
|
||
encrypt: false,
|
||
trustServerCertificate: true
|
||
}
|
||
};
|
||
|
||
// 转义SQL字符串
|
||
function escapeString(str) {
|
||
if (str === null || str === undefined) return 'NULL';
|
||
return "N'" + String(str).replace(/'/g, "''") + "'";
|
||
}
|
||
|
||
// 格式化日期时间 (MySQL datetime -> SQL Server datetime2)
|
||
function formatDatetime(dt) {
|
||
if (!dt) return 'NULL';
|
||
if (dt instanceof Date) {
|
||
return "'" + dt.toISOString().slice(0, 23).replace('T', ' ') + "'";
|
||
}
|
||
return "'" + String(dt).slice(0, 23).replace('T', ' ') + "'";
|
||
}
|
||
|
||
// 获取已迁移的钻石商品ID列表
|
||
async function getMigratedIds(pool) {
|
||
const result = await pool.request().query('SELECT id FROM diamond_products');
|
||
return new Set(result.recordset.map(r => r.id));
|
||
}
|
||
|
||
// 批量插入钻石商品数据
|
||
async function insertDiamondProductsBatch(pool, products) {
|
||
if (products.length === 0) return 0;
|
||
|
||
let insertedCount = 0;
|
||
|
||
// 构建批量插入SQL
|
||
let sqlBatch = 'SET IDENTITY_INSERT diamond_products ON;\n';
|
||
|
||
for (const product of products) {
|
||
sqlBatch += `
|
||
INSERT INTO diamond_products (
|
||
id, name, products_id, products_type, base_reward, price,
|
||
is_first, first_bonus_reward, first_charge_image, first_select_charge_image,
|
||
normal_image, normal_select_image, sort_order, status, created_at, updated_at
|
||
) VALUES (
|
||
${product.id},
|
||
${escapeString(product.name)},
|
||
${escapeString(product.products_id)},
|
||
${escapeString(product.products_type)},
|
||
${escapeString(product.base_reward)},
|
||
${parseFloat(product.price) || 0},
|
||
${product.is_first || 0},
|
||
${escapeString(product.first_bonus_reward)},
|
||
${escapeString(product.first_charge_image)},
|
||
${escapeString(product.first_select_charge_image)},
|
||
${escapeString(product.normal_image)},
|
||
${escapeString(product.normal_select_image)},
|
||
${product.sort_order || 0},
|
||
${product.status !== undefined ? product.status : 1},
|
||
${formatDatetime(product.created_at)},
|
||
${formatDatetime(product.updated_at)}
|
||
);
|
||
`;
|
||
}
|
||
|
||
sqlBatch += 'SET IDENTITY_INSERT diamond_products OFF;';
|
||
|
||
try {
|
||
await pool.request().batch(sqlBatch);
|
||
insertedCount = products.length;
|
||
} catch (err) {
|
||
console.error('批量插入失败:', err.message);
|
||
// 如果批量失败,尝试逐条插入
|
||
for (const product of products) {
|
||
try {
|
||
const singleSql = `
|
||
SET IDENTITY_INSERT diamond_products ON;
|
||
INSERT INTO diamond_products (
|
||
id, name, products_id, products_type, base_reward, price,
|
||
is_first, first_bonus_reward, first_charge_image, first_select_charge_image,
|
||
normal_image, normal_select_image, sort_order, status, created_at, updated_at
|
||
) VALUES (
|
||
${product.id},
|
||
${escapeString(product.name)},
|
||
${escapeString(product.products_id)},
|
||
${escapeString(product.products_type)},
|
||
${escapeString(product.base_reward)},
|
||
${parseFloat(product.price) || 0},
|
||
${product.is_first || 0},
|
||
${escapeString(product.first_bonus_reward)},
|
||
${escapeString(product.first_charge_image)},
|
||
${escapeString(product.first_select_charge_image)},
|
||
${escapeString(product.normal_image)},
|
||
${escapeString(product.normal_select_image)},
|
||
${product.sort_order || 0},
|
||
${product.status !== undefined ? product.status : 1},
|
||
${formatDatetime(product.created_at)},
|
||
${formatDatetime(product.updated_at)}
|
||
);
|
||
SET IDENTITY_INSERT diamond_products OFF;`;
|
||
|
||
await pool.request().batch(singleSql);
|
||
insertedCount++;
|
||
} catch (singleErr) {
|
||
console.error(`插入钻石商品 ${product.id} 失败:`, singleErr.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
return insertedCount;
|
||
}
|
||
|
||
async function main() {
|
||
console.log('========================================');
|
||
console.log('钻石商品数据迁移脚本 - Node.js');
|
||
console.log('========================================\n');
|
||
|
||
let mysqlConn = null;
|
||
let sqlPool = null;
|
||
|
||
try {
|
||
// 连接 MySQL
|
||
console.log('正在连接 MySQL...');
|
||
mysqlConn = await mysql.createConnection(mysqlConfig);
|
||
console.log('MySQL 连接成功\n');
|
||
|
||
// 连接 SQL Server
|
||
console.log('正在连接 SQL Server...');
|
||
sqlPool = await sql.connect(sqlServerConfig);
|
||
console.log('SQL Server 连接成功\n');
|
||
|
||
// 获取已迁移的ID
|
||
console.log('正在获取已迁移的钻石商品ID...');
|
||
const migratedIds = await getMigratedIds(sqlPool);
|
||
console.log(`已迁移钻石商品数: ${migratedIds.size}\n`);
|
||
|
||
// 从 MySQL 获取所有钻石商品数据
|
||
console.log('正在从 MySQL 读取钻石商品数据...');
|
||
const [rows] = await mysqlConn.execute(`
|
||
SELECT id, name, products_id, products_type, base_reward, price,
|
||
is_first, first_bonus_reward, first_charge_image, first_select_charge_image,
|
||
normal_image, normal_select_image, sort_order, status, created_at, updated_at
|
||
FROM diamond_products
|
||
ORDER BY id
|
||
`);
|
||
console.log(`MySQL 钻石商品总数: ${rows.length}\n`);
|
||
|
||
// 过滤出未迁移的钻石商品
|
||
const productsToMigrate = rows.filter(product => !migratedIds.has(product.id));
|
||
console.log(`待迁移钻石商品数: ${productsToMigrate.length}\n`);
|
||
|
||
if (productsToMigrate.length === 0) {
|
||
console.log('所有钻石商品数据已迁移完成!');
|
||
} else {
|
||
// 批量迁移(每批50条)
|
||
const batchSize = 50;
|
||
let totalInserted = 0;
|
||
|
||
for (let i = 0; i < productsToMigrate.length; i += batchSize) {
|
||
const batch = productsToMigrate.slice(i, i + batchSize);
|
||
const inserted = await insertDiamondProductsBatch(sqlPool, batch);
|
||
totalInserted += inserted;
|
||
console.log(`进度: ${Math.min(i + batchSize, productsToMigrate.length)}/${productsToMigrate.length} (本批插入: ${inserted})`);
|
||
}
|
||
|
||
console.log(`\n迁移完成!共插入 ${totalInserted} 条记录`);
|
||
}
|
||
|
||
// 验证迁移结果
|
||
console.log('\n========================================');
|
||
console.log('迁移结果验证');
|
||
console.log('========================================');
|
||
|
||
const [mysqlCount] = await mysqlConn.execute('SELECT COUNT(*) as count FROM diamond_products');
|
||
const sqlResult = await sqlPool.request().query('SELECT COUNT(*) as count FROM diamond_products');
|
||
|
||
console.log(`MySQL diamond_products 表记录数: ${mysqlCount[0].count}`);
|
||
console.log(`SQL Server diamond_products 表记录数: ${sqlResult.recordset[0].count}`);
|
||
|
||
if (mysqlCount[0].count === sqlResult.recordset[0].count) {
|
||
console.log('\n✅ 数据迁移完成,记录数一致!');
|
||
} else {
|
||
console.log(`\n⚠️ 记录数不一致,差异: ${mysqlCount[0].count - sqlResult.recordset[0].count}`);
|
||
}
|
||
|
||
// 显示迁移后的数据样本
|
||
console.log('\n========================================');
|
||
console.log('迁移后数据样本');
|
||
console.log('========================================');
|
||
|
||
const sampleResult = await sqlPool.request().query(`
|
||
SELECT TOP 5 id, name, price, status, created_at
|
||
FROM diamond_products
|
||
ORDER BY id
|
||
`);
|
||
|
||
console.log('\nSQL Server diamond_products 表数据:');
|
||
sampleResult.recordset.forEach(row => {
|
||
console.log(` ID: ${row.id}, 名称: ${row.name}, 价格: ${row.price}, 状态: ${row.status}`);
|
||
});
|
||
|
||
} catch (err) {
|
||
console.error('迁移过程中发生错误:', err);
|
||
process.exit(1);
|
||
} finally {
|
||
// 关闭连接
|
||
if (mysqlConn) await mysqlConn.end();
|
||
if (sqlPool) await sqlPool.close();
|
||
}
|
||
}
|
||
|
||
main();
|