最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set default notNullable reference column in Knex migration only for existing rows - Stack Overflow

programmeradmin2浏览0评论

I have a postgresql database, and I am trying the following migration to add a non-nullable reference column to an existing table, using Knex:

exports.up = function (knex) {
  return knex.schema.table('Donation', (table) => {
    table.integer('causeId').notNullable();
    table.foreign('causeId').references('Cause.id');
  });
};

When I run this migration, I get the following error due to existing rows:

error: alter table "Donation" add column "causeId" integer not null - column "causeId" contains null values

I want to seed the column with a default value only for existing rows. For subsequent insertions, I would rather the insert fail if a value is not provided, so .notNullable().defaultTo(...) won't work.

I was thinking of maybe using defaultTo() only for the initial migration and then removing the constraint after, but I'm drawing a blank on how to acplish this.

Any help would be appreciated!

I have a postgresql database, and I am trying the following migration to add a non-nullable reference column to an existing table, using Knex:

exports.up = function (knex) {
  return knex.schema.table('Donation', (table) => {
    table.integer('causeId').notNullable();
    table.foreign('causeId').references('Cause.id');
  });
};

When I run this migration, I get the following error due to existing rows:

error: alter table "Donation" add column "causeId" integer not null - column "causeId" contains null values

I want to seed the column with a default value only for existing rows. For subsequent insertions, I would rather the insert fail if a value is not provided, so .notNullable().defaultTo(...) won't work.

I was thinking of maybe using defaultTo() only for the initial migration and then removing the constraint after, but I'm drawing a blank on how to acplish this.

Any help would be appreciated!

Share Improve this question edited May 20, 2020 at 18:44 Corey Larson asked May 20, 2020 at 15:53 Corey LarsonCorey Larson 1,16410 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

My solution ended up being to use defaultTo(...) on creation of this column and then alter it afterwards using alterTable(...).

Not sure of a better way, but this works.

exports.up = function (knex) {
  function relateCauseToDonation() {
    return knex.schema.table('Donation', (table) => {
      table.integer('causeId').notNullable().defaultTo(1);
      table.foreign('causeId').references('Cause.id');
    });
  }

  function removeDefaultToFromCauseId() {
    return knex.schema.alterTable('Donation', (table) => {
      table.integer('causeId').notNullable().alter();
    });
  }

  return relateCauseToDonation().then(removeDefaultToFromCauseId);
};
发布评论

评论列表(0)

  1. 暂无评论