NodeJS 序列化种子以更改枚举

yduiuuwa  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(120)

我们有一个Postgres DB和一个枚举myApp_location,其中有两个值['east', 'west']。我们使用以下seeder创建了它

module.exports = {
  up: (queryInterface, Sequelize) => queryInterface.addColumn('myApp', 'location', {
    type: Sequelize.ENUM,
    values: ['east', 'west'],
    allowNull: true,
  }),
}

字符串
现在我们要给枚举添加一个值。我们可以用一个seeder来做一个查询:

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.sequelize.query("ALTER TYPE \"enum_myApp_location\" ADD VALUE 'north';");
  }
};


但是我们希望避免在seeder中使用query,如果可能的话,我们更喜欢使用queryInterface中内置的一些Sequelize
有没有办法不写sequelize.query呢?

wn9m85ua

wn9m85ua1#

以下是关于这个主题的完整讨论:github://sequelize/issues#7151
但在进一步寻找解决方案后,我想到了这个:

// example based on the Question:

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const pgEnumDropQuery = queryInterface.queryGenerator.pgEnumDrop('myApp', 'location')
    await queryInterface.changeColumn('myApp', 'location', { type: Sequelize.STRING })
    await queryInterface.sequelize.query(pgEnumDropQuery)
    await queryInterface.changeColumn('myApp', 'location', {
      type: Sequelize.ENUM,
      values: ['east', 'west', 'north'],
      allowNull: true
    })
  },
  down: async (queryInterface, Sequelize) => {
    const pgEnumDropQuery = queryInterface.queryGenerator.pgEnumDrop('myApp', 'location')
    await queryInterface.changeColumn('myApp', 'location', { type: Sequelize.STRING })
    await queryInterface.sequelize.query(pgEnumDropQuery)
    await queryInterface.changeColumn('myApp', 'location', {
      type: Sequelize.ENUM,
      values: ['east', 'west'],
      allowNull: true
    })
  }
}

字符串

w51jfk4q

w51jfk4q2#

可以使用queryInterface.changeColumn

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.transaction(async (transaction) => {
      await queryInterface.changeColumn('myApp', 'location', {
        type: Sequelize.ENUM('east', 'west', 'north'),
        allowNull: true,
        transaction,
      });
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.transaction(async (transaction) => {
      await queryInterface.changeColumn('myApp', 'location', {
        type: Sequelize.ENUM('east', 'west'),
        allowNull: true,
        transaction,
      });
    });
  },
};

字符串
down函数定义了如何撤消这些更改。在这种情况下,它将回滚up更改所做的更改。

相关问题