Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelizejs: how to use transactions along with raw queries

Tags:

sequelize.js

I'm using sequelize orm. I cannot find in their documentation how to use transactions when using raw queries. All I see there is for model defined query methods. But for raw queries, there is no specification on where to put the transaction object to use for that specific query.

like image 924
user3631341 Avatar asked Oct 06 '15 09:10

user3631341


2 Answers

query method docs

You can pass the transaction in as such:

const t = await sequelize.transaction();

sequelize.query('SELECT * FROM table;', { transaction: t })

See transactions docs for different ways to define transactions.

like image 101
Jan Aagaard Meier Avatar answered Jan 03 '23 16:01

Jan Aagaard Meier


The link above does not help me, but have figure out the solution: (If you rollback in the catch block, the transaction will be reverted.)

  sequelize.transaction(async transaction => {
    try {
      await sequelize.query(
        `
        UPDATE Balances
        SET amount = @amount := amount - ${10}
        WHERE userId=${1}`,
        {
          type: Sequelize.QueryTypes.UPDATE,
          transaction,
          raw: true
        },
      )

      await sequelize.query(
        `
        UPDATE Balances
        SET amount = @amount := amount - ${10}
        WHERE userId=${2}`,
        {
          type: Sequelize.QueryTypes.UPDATE,
          transaction,
          raw: true
        },
      )

    } catch (error) {
      transaction.rollback();
      throw `TRANSACTION_ERROR`;
    }
  })
like image 37
Peter Avatar answered Jan 03 '23 15:01

Peter