你好我正在尝试创建一个队列,以便当有人在我的postgres数据库上使用sequelize.js进行api路径时,会发生更新。我的主要目标是防止并发修改一行数据。
addFile(req, res) {
// repoPath = directory being watched
// localPath = full local path change was made on
const { repoPath, localPath, data, className, lessonName, lessonId, classCode } = req.body;
const { pathToRepoStorage, subPath, fileDirectory } = this.pathMaker(repoPath, localPath, className, lessonName);
let repo = null;
return sequelize.transaction((t) => {
// chain all your queries here. make sure you return them.
return Lesson.findById(lessonId,
{
transaction: t,
})
.then((lesson) => {
repo = lesson.get('repo');
this.addNodeToTree(repo, fileDirectory, subPath);
return Lesson.update({ repo },
{
where: {
id: lessonId,
},
transaction: t,
});
});
}).then((updated) => {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
if (updated) {
fs.outputFile(pathToRepoStorage, data, (err) => {
if (err) {
res.sendStatus(500);
} else {
// send repo object
this.io.to(classCode).emit('updated-directory', repo);
res.sendStatus(200);
}
});
} else {
throw new Error();
}
}).catch((err) => {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
res.sendStatus(500);
});
}
我回来的信息是:
1执行(默认):更新"课程"组 " fileWatched" =' /用户/约书亚/桌面/项目/ test_watching'" updatedAt" =' 2017年2月21日 03:51:23.132 +00:00'在哪里" id" =' 5'
1执行(7d3b44c1-022d-45b5-a873-d09be8726963):开始 TRANSACTION;
1执行(2acc13f0-f351-4c73-b2ee-db1a63c7c460):START TRANSACTION;
1执行(7d3b44c1-022d-45b5-a873-d09be8726963):SET SESSION 交易隔离级别可重复阅读;
1执行(2acc13f0-f351-4c73-b2ee-db1a63c7c460):SET SESSION 交易隔离级别可重复阅读;
1执行(7d3b44c1-022d-45b5-a873-d09be8726963):SELECT" id", " name","讲座","链接"," repo"," fileWatched"," createdAt& #34 ;, " updatedAt"," classId"来自"课程" AS"课程"在哪里"课程"。" id" =' 5';
1执行(2acc13f0-f351-4c73-b2ee-db1a63c7c460):SELECT" id", " name","讲座","链接"," repo"," fileWatched"," createdAt& #34 ;, " updatedAt"," classId"来自"课程" AS"课程"在哪里"课程"。" id" =' 5';
1执行(7d3b44c1-022d-45b5-a873-d09be8726963):更新"课程" 组 "回购" =' [{"标题":"哈哈哈""路径":"哈哈哈" }]'" updatedAt" =' 2017年2月21日 03:51:23.189 +00:00'在哪里" id" =' 5'
1执行(2acc13f0-f351-4c73-b2ee-db1a63c7c460):更新"课程" 组 "回购" =' [{"标题":"你好""路径":"你好" }]'" updatedAt" =' 2017年2月21日 03:51:23.189 +00:00'在哪里" id" =' 5'
1执行(7d3b44c1-022d-45b5-a873-d09be8726963):COMMIT;
1执行(2acc13f0-f351-4c73-b2ee-db1a63c7c460):ROLLBACK;
虽然这确实阻止了我的第二次呼叫覆盖我的第一个呼叫,但我的第二个呼叫被完全忽略了,我需要在第一次呼叫完成后立即运行。
这是我第一次搞乱交易,我似乎无法找到非常好的文档,最能帮助我的是 transaction documentation
答案 0 :(得分:0)
答案 1 :(得分:0)
请阅读链接http://docs.sequelizejs.com/class/lib/transaction.js~Transaction.html,您将解决问题
return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
// your transactions
}).then(result => {
// transaction has been committed. Do something after the commit if required.
}).catch(err => {
// do something with the err.
});