Add SQL table CHECK using sequelize?

元气小坏坏 提交于 2020-04-30 07:13:26

问题


I want to add this CHECK in one of my tables. I am using Sequelize in a node.js api running on Postgres DB.

CHECK (
    (
        CASE WHEN UserID         IS NULL THEN 0 ELSE 1 END
        + CASE WHEN TableID      IS NULL THEN 0 ELSE 1 END
        + CASE WHEN FoodID       IS NULL THEN 0 ELSE 1 END
        + CASE WHEN RestaurantID IS NULL THEN 0 ELSE 1 END
        + CASE WHEN CategoryID   IS NULL THEN 0 ELSE 1 END
        + CASE WHEN ShipID       IS NULL THEN 0 ELSE 1 END
    )
    = 1
)

So, I need the database to enforce the check on the table where one of those columns must be not null, and only one, the others must be null.

Is there a way to do that in Sequelize?

I tried doing this:

let sql = `ALTER TABLE TestTable
ADD CONSTRAINT check_test CHECK testBool=false;`
await sequelize.query(sql, { type: sequelize.QueryTypes.RAW });

I just created TestTable with a testBool column just to test things out to see if they would run at all.

When that runs I get this ERROR:

relation "testtable" does not exist

I don't understand why the name is all lowercase. In the model definition I even have the:

freezeTableName: true

I can see the Table in the DB, I can save rows to it etc... so, it's there.


回答1:


From the feedback I got in the comments:

  1. use the sequelize.QueryTypes.RAW

  2. follow proper naming conventions Postgres naming rules

  3. run this query worked:

    let sql = ALTER TABLE test_table ADD CONSTRAINT check_test CHECK testBool=false;

    await sequelize.query(sql, { type: sequelize.QueryTypes.RAW });



来源:https://stackoverflow.com/questions/61214694/add-sql-table-check-using-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!