如何有条件地运行Knex迁移

问题描述 投票:0回答:1

我错误地删除了将列添加到组表的迁移,然后不得不将其重新添加到我的本地数据库中。但是,在生产环境中,迁移没有被误删除,因此现在在运行添加的迁移时会引发错误。

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

这是当前添加的迁移:

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个回答
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');
      });
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.