Skip to Content
Sequelize v6

Sequelize v6

Docs: https://sequelize.org/docs/v6/getting-started/

Transactions

https://sequelize.org/docs/v6/other-topics/transactions/

Sequelize does not use transactions by default. However, for production-ready usage of Sequelize, you should definitely configure Sequelize to use transactions. Sequelize supports two ways of using transactions: 1. Unmanaged transactions: Committing and rolling back the transaction should be done manually by the user (by calling the appropriate Sequelize methods). 2. Managed transactions: Sequelize will automatically rollback the transaction if any error is thrown, or commit the transaction otherwise. Also, if CLS (Continuation Local Storage) is enabled, all queries within the transaction callback will automatically receive the transaction object.

Unmanaged transactions

// First, we start a transaction from your connection and save it into a variable const t = await sequelize.transaction(); try { // Then, we do some calls passing this transaction as an option: const user = await User.create( { firstName: 'Bart', lastName: 'Simpson', }, { transaction: t }, ); await user.addSibling( { firstName: 'Lisa', lastName: 'Simpson', }, { transaction: t }, ); // If the execution reaches this line, no errors were thrown. // We commit the transaction. await t.commit(); } catch (error) { // If the execution reaches this line, an error was thrown. // We rollback the transaction. await t.rollback(); }

Managed transactions

const { Transaction } = require('sequelize'); await sequelize.transaction( { isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE, }, async t => { // Your code }, );
Last updated on