Skip to content

How to properly use sequelize with transactions #10503

Closed

Description

@AmbroiseVuaridel

What are you doing?

// the following code shows what the problem is, even though it may not run
//with sequelize and a pool like:

pool:{
max: 10, //Never have more than x open connections
min: 3, //At a minimum, have x open connections/maintain no minimum number of connections
idle: 1000*3600 //Remove a connection from the pool after the connection has been idle (not been used) for x milli seconds
},

// repeat the following 2 line 3 (=minimum connection in pool) times with newName = "Foo", "Bar", then "Foo Bar"

module.exports.index = async function (req,res){
let user = await db.user.findOne({where:{id:1}}); 
try{
let transaction = await db.sequelize.transaction({autocommit:false});
    await user.update({name:req.body.newName},{transaction:transaction});
await transaction.commit();
}
catch(e){
await transaction.rollback();
}
}

// finally execute this many times

module.exports.index2 = async function (req,res){
let user = await db.user.findOne({where:{id:1}}); 
res.send("the name of the user is : "+user.name);
}

What do you expect to happen?

I wanted :
"the name of the user is : Foo Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo Bar"

What is actually happening?

But the output was :
"the name of the user is : Foo"
"the name of the user is : Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo"
"the name of the user is : Bar"
"the name of the user is : Foo Bar"
"the name of the user is : Foo"
"the name of the user is : Bar"

The problem was solved by encapsulating all the findOne in a transaction like so:

module.exports.index = async function (req,res){
try{
let transaction = await db.sequelize.transaction({autocommit:false});
let user = await db.user.findOne({where:{id:1},transaction:transaction});
    await user.update({name:req.body.newName},{transaction:transaction});
await transaction.commit();
}
catch(e){
await transaction.rollback();
}
}
module.exports.index2 = async function (req,res){
try{
    let transaction = await db.sequelize.transaction({autocommit:false});
    let user = await db.user.findOne({where:{id:1},transaction:transaction}); 
    res.send("the name of the user is : "+user.name);
    await transaction.commit();
}
catch(e){
   await transaction.rollback();
}
}

findOne (and I guess other functions) are not autocommit:true (they have a hidden running transaction), this means that when a pool has more than one connection, and you run a findOne with one of them, they will have uncommited transactions that will soon induce the returning wrong values of the attributes you have changed in the meantime (only true for strict isolation levels). The output value will be dependent on which connection it was from. When new findOne will be used, it will be on a random connection of the pool, if some update where made on other connections they won't be taken into account if a previous findOne was made on the current connection.

example:
connexion A: findOne => "Foo"
connexion B: update => "Bar"
connextion A : findOne=>"Foo"
with transactions (what it sould be by default):
connexion A: findOne => "Foo"
connexion B: update => "Bar"
connextion A: findOne=>"Bar"

for people having similar issues, printing transaction.connection.connectionId was helpfull to understand the link between the connection pool, transaction, and the values change...

I am not looking for an answer except if someone has some constructive criticism on my code or my comprehension, I only hope that it may help someone one day. I have lost a lot of time figuring this out and wish to avoid it to someone else.

I hope that I successfully re transcribed the necessary code and comments so that the problem is understandable and reproducible.

Dialect: mysql
Dialect version: latest
Database version: latest
Sequelize version: 4.43.0

Some keywords to help people find it:
sequelize mysql postgresql ACID transaction isolation level wrong value model update save findone findall commit rollback database connection pool different disable cache previous DataValues values status aftercommit asynchronous promise await previousDataValues

Activity

  1. sushantdhiman commented on Mar 4, 2019

    @sushantdhiman
    Contributor

    Hey @AmbroiseVuaridel , I think this was fixed by #9921 Can you please try sequelize@next (will install v5-beta) and see if that works for you.

  2. AmbroiseVuaridel commented on Mar 4, 2019

    @AmbroiseVuaridel
    Author

    Hey @sushantdhiman , thank you, glad to hear you are working on it! For now my project depends on https://www.npmjs.com/package/sequelize-hierarchy which has a problem with version 5, when I have some time I will retry to make it reproducible in v5

  3. AmbroiseVuaridel commented on Mar 4, 2019

    @AmbroiseVuaridel
    Author

    I have found also that the line where the transaction is created impact the result, if you call let transaction = await db.sequelize.transaction({autocommit:false}); before the findOne, it works as expected, not if you call it afterward, even if you don't pass the transaction in options of findOne...

  4. qqaimh commented on May 8, 2019

    @qqaimh

    I find another bugger.
    `
    try{
    let transaction = await dbseq.sequelize.transaction({autocommit:false});

            let user = await userDao.findOne({where:{nickname:nickname},transaction:transaction});
    
            await user.update({teihanhan:data1.tiehanhan-data2.vipprice},{transaction:transaction});
    
            await user.update({costmoney:data1.costmoney+data2.vipprice},{transaction:transaction});
    
             asyncclient.sadd(body.vipid,nickname);
    
             ctx.body= {
                            code:0,
                            message:"购买成功",
                            tiehanhan: data1.tiehanhan-data2.vipprice,
                            costmoney: data1.costmoney+data2.vipprice
                        };   
    
          await transaction.commit();
        }catch(e){
    
       ctx.body= {
                            code:499,
                            message:"系统错误,请稍后再试"
                        };
    
        await transaction.rollback();
      }`
    

    The log
    `Executing (9469eb2d-0453-42d6-b76a-f044d7db81f6): START TRANSACTION;

    Executing (9469eb2d-0453-42d6-b76a-f044d7db81f6): SELECT email, password, salt, tiehanhan, costmoney, nickname, phonenumber, createAt, updateAt, version, status FROM Users AS Users WHERE Users.nickname = '123';

    Executing (9469eb2d-0453-42d6-b76a-f044d7db81f6): UPDATE Users SET costmoney=? WHERE email = ?

    Executing (9469eb2d-0453-42d6-b76a-f044d7db81f6): COMMIT;`

  5. papb commented on Aug 1, 2019

    @papb
    Member

    Closing this since I believe the documentation on transactions has improved.

  6. papb commented on Aug 1, 2019

    @papb
    Member

    @qqaimh If you are having issues, please open a new issue following our bug report template.

  7. ccemeraldeyes commented on Sep 6, 2019

    @ccemeraldeyes

    @papb I disagree that documentation on transactions is sufficient now. I was still assuming that single operations would have their own transactions by default. I would strongly suggest adding disclaimers in multiple places saying that without some kind of manual intervention, sequelize uses ZERO TRANSACTIONS.

  8. papb commented on Sep 6, 2019

    @papb
    Member

    @ccemeraldeyes Ok. I will do this very soon. Thanks!

  9. reopened this on Sep 6, 2019
  10. added
    docs
    on Sep 6, 2019
  11. self-assigned this
    on Sep 6, 2019
  12. added
    status: wip
    on Sep 6, 2019
  13. AmbroiseVuaridel commented on Sep 8, 2019

    @AmbroiseVuaridel
    Author

    @papb Thanks !

  14. removed
    status: wip
    on Jan 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

docs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions