5

I have an Express application with Sequelize as ORM and PostgreSQL as database. Database is setup in such a manner where every tenants in my application will have different schemas.The migration files which exists in my application contains addColumn/removeColumn migrations. But when i am running npx sequelize-cli db:migrate command, i am getting the following error.

ERROR: relation "public.table_name" does not exist

The above error is throwing only for the migration files that contains either addColumn/removeColumn migrations. Also i am nowhere referring to public schema(even deleted the public schema from db). Is there a way to run the migrations against a particular schema(say test_schema) in Sequelize without hardcoding the schema name in the migration files?

Update #2

'use strict';

module.exports = {
  up: async(queryInterface, Sequelize) => {
    try {
      await queryInterface.addColumn('table_name', 'new_field_name', {
        type: Sequelize.INTEGER
      });
      return Promise.resolve();
    } catch (e) {
      return Promise.reject(e);
    }
  },

  down: async(queryInterface, Sequelize) => {
    try {
      await queryInterface.removeColumn('table_name','new_field_name');
      return Promise.resolve();
    } catch (e) {
      return Promise.reject(e);
    }
  }
};

Above is the code for addColumn migration .

1 Answers1

5

You can use an extended syntax of addColumn/removeColumn like this:

const { tableSchemas } = require('../config.json')
const tableName = 'table_name'
...
module.exports = {
  up: async(queryInterface, Sequelize) => {
    // adding transaction because we have several changes
    await queryInterface.sequelize.transaction(async transaction => {
      for (const tableSchema of tableSchemas) {
        const table = { schema: tableSchema, tableName: tableName }
        await queryInterface.addColumn(table, 'new_field_name', {
          type: Sequelize.INTEGER
        }, { transaction });
      }
    })
  },

  down: async(queryInterface, Sequelize) => {
    // adding transaction because we have several changes
    await queryInterface.sequelize.transaction(async transaction => {
      for (const tableSchema of tableSchemas) {
        const table = { schema: tableSchema, tableName: tableName }
        await queryInterface.removeColumn(table,'new_field_name', { transaction });
      }
    })
  }
};

Anatoly
  • 20,799
  • 3
  • 28
  • 42