18

I am using sequalize transaction in Nodejs,but my problem is that it don't take my users table in Transaction and update my table

return sequelize.transaction(function (t) {
    var Users = objAllTables.users.users();
    return Users.update(updateUser, {
        where: {
            uid: sessionUser.uid,
            status: 'ACTIVE'
        }
    },{ transaction: t }).then(function (result) {

       return Utils.sendVerificationEmail(sessionUser.uid, sessionUser.user_email)
            .then(function(data){
                 data = false;  
                if(data == false){
                        throw new Error('Failed Email');
                }

            });


    }).then(function (result) {
        console.log(result);
        // Transaction has been committed
        // result is whatever the result of the promise chain returned to the transaction callback
    })

}).catch(function(err){
    res.send({message:err.message})
})

CONSOLE:

Executing (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): START TRANSACTION;
Executing (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): SET autocommit = 1;
Executing (default): UPDATE `users` SET `username`='edited' WHERE `uid` = 20 AND `status` = 'ACTIVE'
Executing (ad5247bd-18b8-4c6f-bb30-92744c7a5ac8): ROLLBACK;

As you can see in the console update query run out of the transaction

Shaharyar
  • 12,254
  • 4
  • 46
  • 66
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29
  • I want to print the same Excution in my console. Hoe to do that? – shumana chowdhury Oct 17 '17 at 18:22
  • @shumanachowdhury you need to enable logging in sequelize options while connecting to database. see [this](https://stackoverflow.com/questions/21427501/how-can-i-see-the-sql-generated-by-sequelize-js) – Shaharyar Nov 07 '17 at 07:31

1 Answers1

53

transaction key must be in options:

return Users.update(updateUser, {
        where: {
            uid: sessionUser.uid,
            status: 'ACTIVE'
        },
        transaction: t     //second parameter is "options", so transaction must be in it
    })
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • what if we use destroy method of sequelize ? i-e users.destroy() – Ahmer Saeed Oct 05 '17 at 14:05
  • 5
    @AhmerSaeed `destroy` takes only 1 parameter, you have to pass all options in it. *i.e.* `users.destroy({ where: { id: 57 }, transaction: t })` – Shaharyar Oct 07 '17 at 13:06
  • 2
    For anyone searching for this (since I occassionally do), the sequelize doc for the update function can be found here (since Google doesn't always find it too well in my opinion): https://sequelize.org/master/class/lib/model.js~Model.html#static-method-update – DesperateEi Nov 20 '20 at 06:39