Sequelize is a popular Object-Relational Mapping (ORM) library for Node.js that supports multiple database systems, including PostgreSQL, MySQL, SQLite, and MSSQL. Implementing database transactions with Sequelize involves managing multiple database operations as a single unit of work, ensuring that either all operations are successful or none are applied.
Here's a step-by-step guide on how to implement transactions with Sequelize in a Node.js application:
Install Sequelize:
Make sure you have Sequelize installed in your Node.js project. You can install it using npm:
bashnpm install sequelize
Also, you'll need to install the database driver for the specific database you're using, for example:
bashnpm install pg # for PostgreSQL
Set Up Sequelize:
Set up Sequelize in your Node.js application by creating a Sequelize instance and defining your models.
javascript// sequelize.js
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql', // or 'postgres' | 'sqlite' | 'mssql'
host: 'localhost',
});
// Define your models here
// const User = sequelize.define('User', { /* ... */ });
// ...
module.exports = { sequelize };
Use Transactions:
Wrap your database operations in a transaction using sequelize.transaction()
method.
javascriptconst { sequelize } = require('./sequelize');
const performTransaction = async () => {
try {
await sequelize.transaction(async (t) => {
// Your database operations go here
// For example:
// await User.create({ /* ... */ }, { transaction: t });
// await Post.create({ /* ... */ }, { transaction: t });
});
console.log('Transaction committed successfully');
} catch (error) {
console.error('Transaction failed:', error);
}
};
performTransaction();
Rollback and Commit:
Inside the transaction callback, you can decide to commit or rollback the transaction based on your application logic.
javascriptconst { sequelize } = require('./sequelize');
const performTransaction = async () => {
const t = await sequelize.transaction();
try {
// Your database operations go here
// For example:
// await User.create({ /* ... */ }, { transaction: t });
// await Post.create({ /* ... */ }, { transaction: t });
// If everything is successful, commit the transaction
await t.commit();
console.log('Transaction committed successfully');
} catch (error) {
// If an error occurs, rollback the transaction
await t.rollback();
console.error('Transaction failed:', error);
}
};
performTransaction();
This ensures that if any of the operations within the transaction fail, the entire transaction will be rolled back, maintaining the consistency of your database.
Remember to customize the code according to your actual Sequelize models and database operations.