187 lines
6.4 KiB
JavaScript
187 lines
6.4 KiB
JavaScript
/**
|
|
* 快递公司数据迁移脚本 - Node.js
|
|
* Feature: database-migration, Property 2: 数据记录数一致性
|
|
* Validates: Requirements 9.2
|
|
*
|
|
* 源表: MySQL delivery (11 条记录)
|
|
* 目标表: SQL Server deliveries
|
|
*
|
|
* 字段映射:
|
|
* - id -> id (SMALLINT)
|
|
* - name -> name (NVARCHAR(50))
|
|
* - code -> code (NVARCHAR(30))
|
|
*/
|
|
|
|
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, "''") + "'";
|
|
}
|
|
|
|
// 获取已迁移的快递公司ID列表
|
|
async function getMigratedIds(pool) {
|
|
const result = await pool.request().query('SELECT id FROM deliveries');
|
|
return new Set(result.recordset.map(r => r.id));
|
|
}
|
|
|
|
// 批量插入快递公司数据
|
|
async function insertDeliveriesBatch(pool, deliveries) {
|
|
if (deliveries.length === 0) return 0;
|
|
|
|
let insertedCount = 0;
|
|
|
|
// 构建批量插入SQL
|
|
let sqlBatch = 'SET IDENTITY_INSERT deliveries ON;\n';
|
|
|
|
for (const delivery of deliveries) {
|
|
sqlBatch += `
|
|
INSERT INTO deliveries (id, name, code)
|
|
VALUES (${delivery.id}, ${escapeString(delivery.name)}, ${escapeString(delivery.code)});
|
|
`;
|
|
}
|
|
|
|
sqlBatch += 'SET IDENTITY_INSERT deliveries OFF;';
|
|
|
|
try {
|
|
await pool.request().batch(sqlBatch);
|
|
insertedCount = deliveries.length;
|
|
console.log(`批量插入成功: ${insertedCount} 条记录`);
|
|
} catch (err) {
|
|
console.error('批量插入失败:', err.message);
|
|
// 如果批量失败,尝试逐条插入
|
|
for (const delivery of deliveries) {
|
|
try {
|
|
const singleSql = `
|
|
SET IDENTITY_INSERT deliveries ON;
|
|
INSERT INTO deliveries (id, name, code)
|
|
VALUES (${delivery.id}, ${escapeString(delivery.name)}, ${escapeString(delivery.code)});
|
|
SET IDENTITY_INSERT deliveries OFF;`;
|
|
|
|
await pool.request().batch(singleSql);
|
|
insertedCount++;
|
|
console.log(` ✓ 插入快递公司 ${delivery.id}: ${delivery.name} (${delivery.code})`);
|
|
} catch (singleErr) {
|
|
console.error(` ✗ 插入快递公司 ${delivery.id} (${delivery.name}) 失败:`, 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, code
|
|
FROM delivery
|
|
ORDER BY id
|
|
`);
|
|
console.log(`MySQL 快递公司总数: ${rows.length}\n`);
|
|
|
|
// 显示快递公司列表
|
|
console.log('快递公司列表:');
|
|
for (const row of rows) {
|
|
const status = migratedIds.has(row.id) ? '已迁移' : '待迁移';
|
|
console.log(` ${row.id}. ${row.name} (${row.code}) [${status}]`);
|
|
}
|
|
console.log('');
|
|
|
|
// 过滤出未迁移的快递公司
|
|
const deliveriesToMigrate = rows.filter(delivery => !migratedIds.has(delivery.id));
|
|
console.log(`待迁移快递公司数: ${deliveriesToMigrate.length}\n`);
|
|
|
|
if (deliveriesToMigrate.length === 0) {
|
|
console.log('所有快递公司数据已迁移完成!');
|
|
} else {
|
|
// 批量迁移
|
|
console.log('开始迁移快递公司数据...');
|
|
const inserted = await insertDeliveriesBatch(sqlPool, deliveriesToMigrate);
|
|
console.log(`\n迁移完成!共插入 ${inserted} 条记录`);
|
|
}
|
|
|
|
// 验证迁移结果
|
|
console.log('\n========================================');
|
|
console.log('迁移结果验证');
|
|
console.log('========================================');
|
|
|
|
const [mysqlCount] = await mysqlConn.execute('SELECT COUNT(*) as count FROM delivery');
|
|
const sqlResult = await sqlPool.request().query('SELECT COUNT(*) as count FROM deliveries');
|
|
|
|
console.log(`MySQL delivery 表记录数: ${mysqlCount[0].count}`);
|
|
console.log(`SQL Server deliveries 表记录数: ${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迁移后的快递公司列表:');
|
|
const migratedDeliveries = await sqlPool.request().query('SELECT id, name, code FROM deliveries ORDER BY id');
|
|
for (const delivery of migratedDeliveries.recordset) {
|
|
console.log(` ${delivery.id}. ${delivery.name} (${delivery.code})`);
|
|
}
|
|
|
|
} catch (err) {
|
|
console.error('迁移过程中发生错误:', err);
|
|
process.exit(1);
|
|
} finally {
|
|
// 关闭连接
|
|
if (mysqlConn) await mysqlConn.end();
|
|
if (sqlPool) await sqlPool.close();
|
|
}
|
|
}
|
|
|
|
main();
|