1
0
Code Issues Pull Requests Projects Releases Wiki Activity GitHub Gitee

dbPoolUtils添加事务支持

This commit is contained in:
程序员小墨 2022-10-25 20:19:03 +08:00
parent af677e3d0e
commit e79c70595b

View File

@ -65,6 +65,63 @@ async function query(sql, params) {
});
}
// sqlParamsEntities = { sql: "", params: [], callback: function(可选) }
async function transaction(sqlParamsEntities) {
let connection;
try {
connection = await new Promise((resolve, reject) => {
pool.getConnection(function (err, connection) {
if (err) {
reject(err);
}
resolve(connection);
});
});
} catch (err) {
console.error("获取事务connection失败", err);
return;
}
try {
return await new Promise((resolve, reject) => {
// 开启事务
connection.beginTransaction(function (err) {
if (err) {
reject(err);
}
// 开始执行SQL语句
console.log("开始执行transaction共执行" + sqlParamsEntities.length + "条数据");
sqlParamsEntities.forEach((entity) => {
connection.query(entity.sql, entity.param, function (tErr, data) {
if (tErr) {
reject(tErr);
}
if (typeof entity.callback === 'function')
return entity.callback(data);
})
});
// 执行完毕,提交事务
connection.commit(function (tErr, info) {
console.log("transaction info: " + JSON.stringify(info));
if (tErr) {
reject(tErr);
}
resolve(info);
})
});
});
} catch (err) {
console.error("事务执行失败,开始回滚");
connection.rollback(function () {
console.log("transaction error: " + err);
});
} finally {
connection.release();
}
}
async function close() {
await new Promise((resolve, reject) => {
if (!pool) return;
@ -76,7 +133,8 @@ async function close() {
}
module.exports = {
create: create,
query: query,
close: close,
create,
query,
transaction,
close,
}