dbPoolUtils添加事务支持
This commit is contained in:
@@ -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() {
|
async function close() {
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
if (!pool) return;
|
if (!pool) return;
|
||||||
@@ -76,7 +133,8 @@ async function close() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
create: create,
|
create,
|
||||||
query: query,
|
query,
|
||||||
close: close,
|
transaction,
|
||||||
|
close,
|
||||||
}
|
}
|
Reference in New Issue
Block a user