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.
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.
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`;
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With