Sequelize Transactions
Sequelize Transactions

Sequelize Transactions

Spread the love
MySQL transactions in sequelize with Node.js
Sequelize transactions

Atomic transactions are the backbone of relational databases. ACID-compliant databases like MySQL or Postgres provide some very important properties of data integrity with the help of transactions. This essentially means all statements executed within the scope of a single transaction are either all successfully executed or the entire block is rolled back. In my previous two articles, we have learned about the basics of Sequelize & Sequelize associations. We will learn about MySQL transactions in sequelize with Node.js in this last post. 


Sequelize supports two ways of using transactions:

  1. Unmanaged transactions
  2. Managed transactions

Unmanaged transactions: 
Committing and rolling back the transaction should be done manually by the user by calling the Sequelize transaction.commit() & transaction.rollback() methods.

const transaction = await models.sequelize.transaction();  
try {    
 const user = await models.User.create({
     firstName: 'Bart',
     lastName: 'Simpson'
   }, {
    transaction
   });
 const account = await models.Account.create({
  uId: user.uId,
  accountType: 'Free'
 }, {
   transaction
 })
 await transaction.commit();  
} catch (error) {    
  await transaction.rollback();
}

In an unmanaged transaction, we first create a User entity followed by an Account entity. User manually needs to commit the transaction by calling commit() & if any error occurs roll back the transaction using rollback().

Managed transactions
 Sequelize will automatically roll back the transaction for us in case of an error, or commit the transaction otherwise.

// Example of managed transaction code
try {    
 const result = await models.sequelize.transaction(async (t) => {
   const user = await models.User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
   }, { 
     transaction: t 
   });
  const account = await models.Account.create({
    uId: user.uId,
    accountType: 'Free'
   }, {
    transaction: t
  });
  return user
 })
} catch (error) { 
   console.log(error)   
}

In the above, the transaction is started by passing a callback to sequelize.transaction which generated transaction object “t”. Sequelize executes the callback, passing t into it. If the callback throws an error, Sequelize will automatically roll back the transaction & If the callback succeeds, Sequelize will automatically commit the transaction. 

Using this 2 types of Sequelize transaction, you can achieve database integrity. We have covered almost all the topics to start with sequelize in three articles. Feel free to connect if you need any help in sequelize.

Thanks for reading.

2 Comments

  1. Pingback: Four Sequelize associations you should know | Noob2Geek

  2. Pingback: Learn Sequelize in 7 mins: Part 1 | Noob2Geek

Leave a Reply

Your email address will not be published.