Sequelize addColumn 迁移始终引用公共模式

Nee*_*nan 5 postgresql node.js express sequelize.js sequelize-cli

我有一个 Express 应用程序,其中Sequelize作为 ORM,PostgreSQL作为数据库。数据库的设置方式使得我的应用程序中的每个租户都将具有不同的架构。我的应用程序中存在的迁移文件包含 addColumn/removeColumn 迁移。但是当我运行 npx Sequelize-cli db:migrate 命令时,出现以下错误。

错误:关系“public.table_name”不存在

上述错误仅针对包含 addColumn/removeColumn 迁移的迁移文件引发。另外,我没有提到公共模式(甚至从数据库中删除了公共模式)。有没有办法在 Sequelize 中针对特定模式(例如 test_schema)运行迁移,而无需在迁移文件中硬编码模式名称?

更新#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);
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

以上是addColumn迁移的代码。

Ana*_*oly 5

您可以使用 addColumn/removeColumn 的扩展语法,如下所示:

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 });
      }
    })
  }
};

Run Code Online (Sandbox Code Playgroud)