使用Sequelize迁移Postgres数据时遇ConnectionManager报错求助
解决Sequelize跨Postgres数据库迁移时的ConnectionManager关闭错误
运行数据迁移脚本时出现错误:
Error: ConnectionManager.getConnection was called after the connection manager was closed!
错误原因分析
- 未等待模型同步完成:
dbA.sync()和dbB.sync()是异步操作,直接执行后续的findAll、bulkCreate时,数据库连接可能还没准备就绪,导致后续操作出现连接异常。 - 多余的跨数据库关联定义:
ModelA.hasOne(ModelB)和ModelB.belongsTo(ModelA)是跨数据库的模型关联,当前场景只是数据迁移,不需要该关联,而且该操作会触发额外的连接请求,和迁移逻辑冲突。 - 连接关闭时机过早:
dbA.close()和dbB.close()没有等待bulkCreate等异步操作完全完成就执行,导致未完成的数据库请求试图从已关闭的连接管理器获取连接,抛出错误。
修复后的代码
// Import Sequelize const { Sequelize, DataTypes } = require('sequelize'); async function migrateData() { let dbA, dbB; try { // Define the connection to Database A dbA = new Sequelize('postgres', 'newuser', 'pass', { host: 'localhost', dialect: 'postgres' }); // Define the connection to Database B dbB = new Sequelize('postgres2', 'newuser', 'pass', { host: 'localhost', dialect: 'postgres' }); // Define the models for Database A and B const ModelA = dbA.define('modelA', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.STRING, allowNull: false }, age: { type: DataTypes.INTEGER, allowNull: false } }); const ModelB = dbB.define('modelB', { student_id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, student_name: { type: DataTypes.STRING, allowNull: false }, student_age: { type: DataTypes.INTEGER, allowNull: false } }); // 等待模型同步完成 await dbA.sync(); await dbB.sync(); // 从数据库A查询数据 const dataFromA = await ModelA.findAll(); // 映射数据格式 const mappedData = dataFromA.map(item => ({ student_name: item.name, student_age: item.age })); // 批量插入到数据库B await ModelB.bulkCreate(mappedData); console.log('数据迁移完成'); } catch (error) { console.error('迁移过程出错:', error); } finally { // 确保所有操作完成后关闭连接,即使出错也能关闭 if (dbA) await dbA.close(); if (dbB) await dbB.close(); } } migrateData();
关键修复点
- 给
dbA.sync()、dbB.sync()添加await,保证模型同步完成后再执行数据操作。 - 移除了不必要的跨数据库关联定义,避免触发额外的连接请求。
- 使用
try/catch/finally结构,确保无论迁移成功还是失败,都会关闭数据库连接,同时保证所有异步操作完成后才执行关闭动作。 - 给
dbA.close()和dbB.close()添加await,等待连接关闭完成。
内容的提问来源于stack exchange,提问作者Anmol Bajpai
相关产品推荐
相关产品推荐

