Sling Academy
Home/Node.js/Sequelize.js: How to Rename a Table

Sequelize.js: How to Rename a Table

Last updated: December 29, 2023

Introduction

Sequelize is a powerful, promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features robust transaction support, relations, eager and lazy loading, read replication and more. Renaming tables in Sequelize is a straightforward process, but it requires a good understanding of migrations and the query interface. This article will guide you through the process of renaming tables in Sequelize with code examples ranging from basic to advanced.

Prerequisites

Before proceeding, ensure that you have Sequelize installed and configured in your Node.js project. You should be familiar with the basics of Sequelize models, migrations, and how to run them.

Using Migrations to Rename a Table

The primary method for renaming a table in Sequelize is through migrations, which allow changes to the database schema to be tracked, reverted, and shared across different environments.

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.renameTable('OldTableName', 'NewTableName');
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.renameTable('NewTableName', 'OldTableName');
  }
};

The above migration script renames the table from ‘OldTableName’ to ‘NewTableName’. The down function defines how to revert the change if necessary.

Advanced Table Renaming

If you have complex scenarios such as renaming a table and also updating its associations, you may need to perform multiple operations within the same migration.

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.renameTable('OldTableName', 'NewTableName');
    await queryInterface.sequelize.query('UPDATE associations SET tableName = NewTableName WHERE tableName = 'OldTableName');
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.renameTable('NewTableName', 'OldTableName');
    await queryInterface.sequelize.query('UPDATE associations SET tableName = 'OldTableName' WHERE tableName = NewTableName');
  }
};

This migration script not only renames the table but also updates any association references to the new table name within a single migration.

Handling Constraints and Indexes

When renaming a table that has associated indexes or foreign key constraints, you will need to update or recreate these as well.

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.renameTable('OldTableName', 'NewTableName');
    // Handle renaming of foreign key constraints and indexes here
  },

  down: async (queryInterface, Sequelize) => {
    // Handle reverting of foreign key constraints and indexes changes here
    await queryInterface.renameTable('NewTableName', 'OldTableName');
  }
};

The migration above should be modified to include additional logic for renaming constraints and indexes to match the new table name.

Using Raw SQL

Finally, if you need to circumvent the Sequelize abstraction or work with features not yet supported by the ORM, you can perform raw SQL queries within your migrations.

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.sequelize.query('ALTER TABLE 'OldTableName' RENAME TO 'NewTableName';');
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.sequelize.query('ALTER TABLE 'NewTableName' RENAME TO 'OldTableName';');
  }
};

Using raw SQL allows more control and should be used cautiously as it bypasses the abstraction layer provided by Sequelize, making the code database-specific.

Conclusion

Renaming tables in Sequelize through migrations is a safe and recommended approach to evolve your database schema. Always ensure that you update subsequent references to the new table name, and consider the effects on indexes and foreign keys. Proper use of the up and down functions in migrations ensures that the changes are reversible, maintaining the integrity of your development process. With the steps given in this tutorial, you should be able to confidently rename tables in your Sequelize-managed database.

Next Article: Sequelize.js: How to Connect to Multiple Databases

Previous Article: Sequelize.js: How to Alter/Change a Table

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