Skip to content

Migrations

Vugar Safarzada edited this page Apr 25, 2024 · 2 revisions

Sequelize is a popular ORM (Object-Relational Mapping) tool for Node.js, and it has the ability to automatically update database schemas. When making changes to your tables, such as adding a new column, you can use a system called "migrations" with Sequelize. This system allows you to track and manage changes made to your database. Using Sequelize migrations, you can update your database without needing to drop and recreate tables each time.

Here’s how you can handle migrations in Sequelize:

  1. Create a Migration File: Use the Sequelize CLI to create a new migration file. For example, if you want to add a new column to a table, you can use the following command:

    sequelize migration:create --name add-new-column
    
  2. Edit the Migration File: Open the created file and edit the up and down functions. The up function applies the change, and the down function reverts it. For example, to add a column:

    'use strict';
    
    module.exports = {
      up: async (queryInterface, Sequelize) => {
        await queryInterface.addColumn('TableName', 'newColumnName', {
          type: Sequelize.STRING,
          allowNull: true
        });
      },
    
      down: async (queryInterface, Sequelize) => {
        await queryInterface.removeColumn('TableName', 'newColumnName');
      }
    };
  3. Run the Migration: To apply the changes to your database, use the following command:

    sequelize db:migrate
    

These steps help you maintain control over changes to your database and make updates without any data loss.

Regarding Other SQL Dialects: Using other SQL systems like PostgreSQL involves similar processes with migrations. Switching to a different SQL management system won't directly solve this issue; what’s important is to properly utilize systems like migrations regardless of the SQL dialect.

Clone this wiki locally