Sling Academy
Home/Node.js/How to Safely Use Migrations in Sequelize.js

How to Safely Use Migrations in Sequelize.js

Last updated: December 29, 2023

Introduction

Migrations are a vital part of any database-heavy application development process, allowing developers to define and track changes to the database schema over time. Sequelize.js, a popular Node.js ORM for relational databases such as PostgreSQL, MySQL, SQLite, and MSSQL, offers a comprehensive migration system. In this guide, we’ll explore how to use Sequelize migrations safely and effectively to evolve your database schema without losing data or causing downtime.

Understanding Migrations

Before diving into the nitty-gritty of Sequelize migrations, it’s important to understand the concept of migration itself. A migration is a set of database operations that can modify the database schema, add new data, or modify existing data. Migrations are typically versioned and allow for both forward (up) and backward (down) changes, facilitating easy database versioning and rollback capabilities.

Setting Up Sequelize Migrations

// Install the Sequelize CLI
$ npm install --save sequelize-cli

// Initialize migrations
$ npx sequelize-cli init

This will create a new ‘migrations’ folder in your project where you can place your migration files.

Creating Your First Migration

// Generate a new migration file for creating a 'Users' table
$ npx sequelize-cli migration:generate --name create-users

This command will create a new file in the ‘migrations’ folder that you can then populate with up and down methods.

Implementing Safe Migration Practices

To ensure safety during migrations, follow these practices:

  • Always back up your database before performing migrations.
  • Test your migrations in a development or staging environment before applying them to production.
  • Use transactions to make sure that migrations can be rolled back in case of failure.
  • Keep your migrations idempotent, meaning they can be run multiple times without causing errors or unexpected results.
  • Sequentially number and time-stamp migrations to avoid conflicts within your team.

Example: A Safe Migration Script

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.sequelize.transaction(async transaction => {
      await queryInterface.createTable('Users', {
        id: {
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
          type: Sequelize.INTEGER
        },
        // More fields here
      }, { transaction });
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  }
};

In this example, we wrap the createTable operation within a transaction to ensure that it can be rolled back safely if necessary.

Advanced Migration Concepts

As your application grows, you may need to deal with more complex migration scenarios, such as:

  • Data migrations and transformation
  • Splitting or merging tables
  • Handling foreign keys and associations

Let’s take a look at an example involving a data migration:

// An example migration to split 'name' into 'first_name' and 'last_name'
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.sequelize.transaction(async transaction => {
      await queryInterface.addColumn('Users', 'first_name', Sequelize.STRING, { transaction });
      await queryInterface.addColumn('Users', 'last_name', Sequelize.STRING, { transaction });
      // Imagine a query here to update the new columns based on the existing 'name' column.
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeColumn('Users', 'first_name');
    await queryInterface.removeColumn('Users', 'last_name');
    // Any necessary cleanup steps.
  }
};

Conclusion

In this guide, we’ve covered the basics of creating and running safe migrations using Sequelize.js. Remember to always follow best practices, such as testing your migrations and using transactions, to keep your database schema changes smooth and safe. As your application scales and evolves, sequelize migrations will be an essential tool in ensuring that your database schema keeps up with the changes in a controlled and reliable manner.

Next Article: Sequelize.js: How to Safely Change Model Schema in Production

Previous Article: How to Perform Bulk Update in Sequelize.js

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates