Search code examples
sql-serverazuresequelize.jsazure-sql-databaseazure-sql-server

sequelize azure sql database rollback


I am using sequelize with microsoft azure sql database. I am using following to connect to the database

let sequelize = new Sequelize(<DB_NAME>, <DB_USER>, <DB_PASS>, {
    dialect: 'mssql',
    host: 'xxxxxx.database.windows.net',
    operatorsAliases: false,
    encrypt: true,
    timestamps: true
  });

  sequelize.authenticate().then(() => {
    console.log('Connection established successfully.');
  }).catch(err => {
    console.error('Unable to connect to the database:', err);
  })

this establishes the connection. I want to use transaction with my sql queries. I use the following code to execute update operation on the data

const USERS= sequelize.define('USERS', <table details>);

await sequelize.transaction(async (t) => {
      await USERS.update(
          { status: 'USER REMOVED' },
          {
            where: { id: <ID>},
            returning: true,
          },
          {transaction : t}
        )
        throw "unsuccessful transaction"
  }).then(async function(){
    console.log("transaction successful")
  }
  ).catch(err => {
    console.error(err)
  })

after execution the logs show following

Executing (b9f23ee86231fc03255b): BEGIN TRANSACTION;
Executing (b9f23ee86231fc03255b): ROLLBACK TRANSACTION;

which translates to the transaction was rolled back. But when I check the data in the Azure SQL database is updated. Thus the transaction was not rolled back.

Is there something that I am missing or doing incorrectly ? does the azure SQL support transactions ?


Solution

  • The static model's update method has only two parameters: values and options so you should pass transaction inside options params:

    await USERS.update(
              { status: 'USER REMOVED' },
              {
                where: { id: <ID>},
                returning: true,
                transaction : t
              }
            )