【问题标题】:Sequelize addColumn migration always referring public schemaSequelize addColumn 迁移始终引用公共架构
【发布时间】:2020-08-12 03:11:06
【问题描述】:

我有一个 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);
    }
  }
};

以上是addColumn迁移的代码。

【问题讨论】:

  • 请展示一个使用 addColumn/removeColumn 进行迁移的示例
  • @Anatoly 我已经用示例迁移更新了问题。请参阅。

标签: node.js postgresql express sequelize.js sequelize-cli


【解决方案1】:

您可以像这样使用 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 });
      }
    })
  }
};

【讨论】:

  • 我正在寻找一种无需在迁移文件中硬编码架构名称的方法
  • 您可以在迁移文件中导入配置文件并使用其中的架构名称。
  • 我认为这在我的情况下是不可能的,因为我需要针对 5 个模式运行迁移。请分享您的想法
  • 5 个模式名称的来源在哪里?
  • 现在我在 config.json 文件中硬编码模式
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 2017-06-26
  • 2019-05-20
  • 1970-01-01
  • 2020-12-17
  • 2013-10-06
  • 2017-08-29
  • 1970-01-01
相关资源
最近更新 更多