[英]Transaction rollback issue with knex
I am trying to do mysql transactions using knex in node js. 我正在尝试在节点js中使用knex进行mysql事务。 My SQL transactions look like this 我的SQL事务看起来像这样
1- Check if company name exists, if yes then prompt error and rollback transaction. 1-检查公司名称是否存在,如果存在,则提示错误并回滚事务。
2- Check if email address exists, if yes then prompt error and rollback transaction. 2-检查电子邮件地址是否存在,如果存在,则提示错误并回滚事务。
3- Insert into user, company and userroles tables and if error encountered rollback transaction. 3-插入用户表,公司表和用户角色表,如果遇到错误则回滚事务。
Now I observe that if error occurs inside nested then especially the lastone then transaction doesn't rollback instead it commits previous transactions. 现在,我观察到,如果嵌套内发生错误,则尤其是最后一个错误,则事务不会回滚,而是提交先前的事务。
Here is my function code 这是我的功能代码
return knex.transaction(function(t){
return knex('company').where({ companyname: companyname }).select('companyid')
.then(function(rows){
if(rows.length >= 1)
return Promise.reject('company already exist');
return knex('Users').where({email: emailaddress}).select('userid')
})
.then(function(rows){
if(rows.length >=1 )
return Promise.reject('user already exist');
return knex('Users').insert({username:username,email:emailaddress,passsword:password,creationtime:'2008-11-11 13:23:44',updationtime:'2008-11-11 13:23:44'},'userid')
})
.then(function(useridreturned){
userid=useridreturned;
return knex('company').insert({companyname:companyname,companytokens:100})
})
.then(function(companyidreturn){
companyid=companyidreturn;
return knex('userroles').insert({userid:userid[0],roleid:1,companyid:companyid[0]},'userrolesid')
})
.then(function(result){
return Promise.resolve('Account Created');
})
.then(t.commit)
.catch(t.rollback)
})
Am I doing something wrong here ? 我在这里做错什么了吗?
When using transactions with knex, you need to tell to every query that it should go to given transaction. 当使用带有knex的事务时,您需要告诉每个查询它应该进入给定的事务。
So instead of doing knex('table').insert({...}})
(which allocated new connection from pool) you should write t('table').insert({...}})
which will send query to the connection where transaction is going on. 因此,而不是做knex('table').insert({...}})
(它从池中分配了新的连接),您应该编写t('table').insert({...}})
来发送查询到正在进行事务的连接。
Also if you are returning promise from 另外,如果您从
knex.transaction(trx => {
return trx('table').insert({...});
})
You must not call explicit trx.commit()
/ trx.rollback()
those are called by knex implicitly with result / reject value of the returned promise. 您不能调用显式的trx.commit()
/ trx.rollback()
它们被knex隐式调用,并带有返回的promise的result /拒绝值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.