【问题标题】:How to add constraint to existing table with knex如何使用 knex 向现有表添加约束
【发布时间】:2022-10-04 16:50:19
【问题描述】:

我正在尝试使用 Knex 迁移向现有表添加约束。
我使用的数据库是 Postgres。
我尝试了以下方法:

exports.up = function(knex) {
  return knex.schema.alterTable('users', table => {
    table.check(
      '?? <> \'deleted\' AND ?? IS NOT NULL',
      ['status', 'email'],
      'users_email_is_not_null'
    );
};

我不断收到以下错误:

error: alter table "users" add constraint users_email_is_not_null check($1$2 <> \'deleted\' AND $3$4 IS NOT NULL) - syntax error at or near "$2"

我尝试添加相同的约束创造一张桌子,它可以工作。 Knex 不支持此操作吗?

【问题讨论】:

    标签: knex.js


    【解决方案1】:

    我发现在 knex 中编写原始支票要容易得多

    export async function up(knex: Knex): Promise<void> {
       return knex.raw(`
           ALTER TABLE users 
           ADD CONSTRAINT "users_email_is_not_null" 
           CHECK (
               status != 'deleted'
               AND email IS NOT NULL
           )
       `)
    }
    
    export async function down(knex: Knex): Promise<void> {
       return  knex.raw(`
          ALTER TABLE "users" 
          DROP CONSTRAINT IF EXISTS "users_email_is_not_null"
       `)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2021-05-19
      • 2014-05-11
      • 2013-05-11
      相关资源
      最近更新 更多