user3631341
user3631341

Reputation: 525

Sequelizejs: how to use transactions along with raw queries

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.

Upvotes: 9

Views: 19352

Answers (4)

Amit Srivastav
Amit Srivastav

Reputation: 1

let t = db.transaction();
await db.sequelize.query(query, {
    type: QueryTypes.INSERT,
    // Use transaction in the object just after query 
    transaction: t,
    replacements: {},
});

Upvotes: 0

Sharky
Sharky

Reputation: 489

Those who are still checking it out, use this: We need to commit the transaction in the end.

const t = await sequelize.transaction();

try{
  await sequelize.query('SELECT * FROM table;', { transaction: t })
  await t.commit();
}
catch (e) {
 await t.rollback();
}

Please check the documentation here: https://sequelize.org/master/manual/transactions.html

Upvotes: 1

Peter
Peter

Reputation: 1249

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`;
    }
  })

Upvotes: 5

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28788

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.

Upvotes: 28

Related Questions