【问题标题】:How to run a Knex migration conditionally如何有条件地运行 Knex 迁移
【发布时间】:2020-04-13 12:44:08
【问题描述】:

我错误地删除了将列添加到组表的迁移,然后不得不将其重新添加到我的本地数据库中。但是,在生产中,迁移并没有被错误地删除,所以现在它在运行添加的迁移时会抛出错误。

认识到可能有一个更优雅的解决方案,此时,我只想添加一个条件,仅当添加的列不存在时才运行此添加的迁移。

这是当前添加的迁移:

exports.up = function(knex, Promise) {
  return knex.schema.table('groups', function(t) {
    t.specificType('fulltext', 'tsvector');
    t.index('fulltext', null, 'gin');
  });
};

exports.down = function(knex, Promise) {
  return knex.schema.table('groups', function(t) {
    t.dropColumn('fulltext');
    t.dropIndex([ 'fulltext' ]);
  });
};

【问题讨论】:

    标签: database-migration knex.js


    【解决方案1】:

    您应该只重新创建/填充您的本地数据库...但无论如何,如果您真的想这样做,您需要使用 https://knexjs.org/#Schema-hasColumn

    exports.up = function(knex, Promise) {
      return knex.schema.hasColumn('tablename', 'columnname')
        .then(res => {
          if (res) {
            return; // skip
          }
          return knex.schema.table('groups', function(t) {
            t.specificType('fulltext', 'tsvector');
            t.index('fulltext', null, 'gin');
          });
        });
    };
    

    【讨论】:

    • 非常感谢!完美的答案。告诉我应该做什么,也告诉我能做什么!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 2016-11-02
    • 2017-12-21
    • 2021-05-11
    相关资源
    最近更新 更多