【发布时间】:2016-01-23 16:15:00
【问题描述】:
我们一直在尝试在 Loopback 中实现 ACID 事务,但没有成功。文档中的唯一示例使用“创建”方法。我们已经尝试完全覆盖事件以及操作挂钩的多种变体。我们只能让 create 示例工作。
核心需求:我们需要能够在特定模型的 create 和 update 方法中启动一个事务,然后在事务中更新多个表(使用 Loopback 的 ORM 函数或直接使用 SQL ) 具有基于业务规则提交或回滚的能力。 例如,我们需要端点能够接受带有抬头和明细交易的发票,对其进行验证,更新各种表(例如库存和客户),然后保存(或回滚)一个 ACID 事务中的所有更改。
使用数据库事务: https://docs.strongloop.com/display/public/LB/Using+database+transactions)
这是文档中的示例:
Post.create({title: 't1', content: 'c1'}, {transaction: tx}, function(err, post) {
post.updateAttributes({content: 'c2', {transaction: tx}, function(err, newPost) {
//
newPost.reviews.create({content: 'r1'}, {transaction: tx}, function(err, newPost) {
});
}
});
操作钩子: https://docs.strongloop.com/display/public/LB/Operation+hooks
我们只能成功覆盖几个核心方法:
Item.create = function(id, cb){
console.log('create'); // Success!
}
//
Item.find = function(id, cb){
console.log('find'); // Success!
}
Item.findById = function(id, cb){
console.log('findById'); // Success!
}
Item.getById = function(id, cb){
console.log('updateAttributes'); // Did not work!
}
Item.all = function(id, cb){
console.log('all'); // Did not work!
};
Item.findOrCreate = function(id, test, cb){
console.log('findOrCreate'); // Did not work!
}
Item.replicate = function(id, test, cb){
console.log('replicate'); // Did not work!
}
Item.save = function(id, test, cb){
console.log('save'); // Did not work!
}
Item.updateAll = function(id, test, cb){
console.log('updateAll'); // Did not work!
}
Item.upsert = function(id, test, cb){
console.log('upsert'); // Did not work!
}
Item.updateAttribute = function(id, cb){
console.log('updateAttribute'); // Did not work!
};
Item.updateById = function(id, test, cb){
console.log('updateById'); // Did not work!
}
在操作挂钩中实现保存、更新等也不起作用:
Item.observe('before save', function(ctx, next) {
console.log('before save');
ctx.Model.beginTransaction({isolationLevel: ctx.Model.Transaction.READ_COMMITTED}, function(err, tx) {
// Now we have a transaction (tx)
console.log('begin transaction', err);
//tx.commit(function(err) {
// console.log('commit', err);
//})
//tx.rollback(function(err) {
// console.log('rollback', err);
//})
next();
});
})
【问题讨论】:
-
到目前为止,我们无法找到任何完整的文档(包括 Loopback 文档)或任何使用 Loopback 的完整 ACID 事务的完整示例。这个功能真的完全发布了吗?
-
经过一番挫折后,我们决定不使用 Loopback 中的数据库事务功能,并实现了 Knex SQL Query Builder。 Knex 有一个非常好的、独立于数据库的接口,支持多表事务。
-
嗨,我评论只是为了添加环回 2 文档的新链接:loopback.io/doc/en/lb2/Using-database-transactions.html 和 loopback.io/doc/en/lb2/Operation-hooks.html
标签: javascript transactions loopbackjs strongloop acid