Comprehensive Introduction and API Examples of Umzug for Seamless Database Migrations

Comprehensive Introduction and API Examples of Umzug for Seamless Database Migrations

Umzug is a versatile migration tool for Node.js that allows developers to manage their database schema changes effectively. In this article, we will provide a detailed introduction to Umzug, explore its powerful API, and showcase various code examples. By the end of this guide, you will be equipped with the knowledge to implement database migrations seamlessly using Umzug in your applications.

Getting Started with Umzug

First, let’s install Umzug:

npm install umzug --save

Basic Usage

Below is a basic example to demonstrate how to configure and run Umzug:

const { Umzug, SequelizeStorage } = require('umzug');
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize({/* Sequelize configuration */});

const umzug = new Umzug({
  migrations: { path: './migrations', pattern: /\.js$/ },
  storage: new SequelizeStorage({ sequelize }),
  context: sequelize.getQueryInterface(),
  logger: console,
});

(async () => {
  await umzug.up();
})();

Migration APIs

.up()

The .up() method executes all pending migrations:

await umzug.up();

.down()

The .down() method reverts the last batch of executed migrations:

await umzug.down();

.add()

The .add() method allows adding migrations dynamically:

umzug.add({
  name: 'migration-name',
  up: async () => {/* upgrade logic */},
  down: async () => {/* downgrade logic */}
});

.pending()

The .pending() method lists all pending migrations:

const pendingMigrations = await umzug.pending();

.executed()

The .executed() method lists all executed migrations:

const executedMigrations = await umzug.executed();

Example Application Integrating Umzug

Let’s create a sample application that integrates Umzug for managing database migrations:

1. Setting Up Sequelize

const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql',
});

2. Configuring Umzug

const { Umzug, SequelizeStorage } = require('umzug');

const umzug = new Umzug({
  migrations: { path: './migrations', pattern: /\.js$/ },
  storage: new SequelizeStorage({ sequelize }),
  context: sequelize.getQueryInterface(),
  logger: console,
});

module.exports = umzug;

3. Creating and Running Migrations

// create a migration file in ./migrations folder
// For example: 20211012-create-users-table.js

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      name: {
        allowNull: false,
        type: Sequelize.STRING,
      },
      email: {
        allowNull: false,
        type: Sequelize.STRING,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  },
};

4. Running Migrations on Application Start

Modify your application entry point to run migrations:

const umzug = require('./umzug');

(async () => {
  await umzug.up();
  console.log('All migrations performed successfully');
})();

With these steps, you have successfully integrated Umzug into your application to manage database migrations efficiently.

Conclusion

Umzug is a powerful tool for managing database migrations in your Node.js applications. It provides a simple yet flexible API to help you maintain and evolve your database schema over time. We hope this guide has provided you with valuable insights and practical examples to get started with Umzug.

Hash: 97e4de92eba367dbe2030d6e1dd152f1516e1c7209c4160b650160b690695493

Leave a Reply

Your email address will not be published. Required fields are marked *