我有一个对象数组,我希望sequelize中有一个原子事务。
updateCreatorDb(resultObj) {
return Promise.map(resultObj.rows, function (result: any) {
return sequelize.transaction({ autocommit: false }).then(function (t) {
return postgresService.updateByIdTrans(result.id, "user_transactions",
{ status: "sucess" }, t).then(function () {
return postgresService.updateByIdTrans(result.to_user, "user",
{ balance: sequelize.literal('balance+' + result.amount) }, t).then(function (data) {
t.commit();
}, function (error) {
t.rollback();
})
}, function (error) {
t.rollback();
});
});
});
}
updateByIdTrans(id: number, model: string, attributes, t: Transaction): Promise<void> {
let promise = new Promise<void>((resolve: Function, reject: Function) => {
logger.info("updating table " + model);
return models[model].update(attributes, { where: { id: id }, returning: true }, { transaction: t })
.then((results) => {
if (results.length > 0) {
logger.info(`Updated Object with id ${id}.`);
resolve(JSON.stringify(results[1][0]));
} else {
logger.info(`Object with id ${id} does not exist.`);
resolve(JSON.stringify(`Object with id ${id} does not exist.`));
}
}).catch((error: Error) => {
logger.error(error.message);
reject(error);
});
});
return promise;
}
如果第二个更新语句失败,那么我想回滚第一个更新语句,因为它们使用相同的事务对象,并且直到第二个更新语句成功才提交 。如果我在第二个更新语句中有错误,那么只有第二个更新语句被回滚并且第一个更新语句被提交。