Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CHECK constraints in Seqeulize PostgreSQL ORM (Node.js)

I'm using Sequelize as ORM with a PostgreSQL engine. When using raw queries I can create a table and have columns with 'CHECK' constraints such as

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);

In the docs I cannot find a way to do this in Sequelize when defining models. Is there any way of doing this? I don't want to reinvent the wheel ;)

Thanks!!

like image 293
Loek Janssen Avatar asked Nov 06 '16 00:11

Loek Janssen


People also ask

What is check constraint in PostgreSQL?

In PostgreSQL, the Check constraint can be defined by a separate name. It is used to control the value of columns being inserted. It allows us to verify a condition that the value being stored into a record. If the statement is false, then the data disrupts the constraint which is not saved in the table.

What are constraints in Sequelize?

"Constraints" are rules for more in-depth checks performed at SQL level vs. at the Sequelize level. A typical example is checking that the email submitted is a unique email address. A user submits an entry, and their email gets checked against other emails in the database to ensure that it's unique.

How do you validate Sequelize?

To do that in Sequelize we can use validations and constraints. Validations are done by the Sequelize framework on the JavaScript level. We can provide custom validator functions or use predefined validators for this. If our data fails this validation then no SQL query will be made.

Can you use Sequelize with Postgres?

For this application, we'll use Sequelize as ORM, as it supports multiple dialects, one of which is PostgreSQL. Sequelize provides a comfortable API to work with PostgreSQL databases from setup to execution, but there are many ORMs (e.g. TypeORM, Objection. js) to choose from for a Node.


1 Answers

module.exports = {

    up: (queryInterface, Sequelize) => {

        return queryInterface.createTable('Products', {
            product_no: {
                type: Sequelize.INTEGER
            },
            price: {
                type: Sequelize.NUMERIC
            },
            name: {
                type: Sequelize.TEXT
            }
        }).

        then(() => queryInterface.addConstraint('Products', ['price'], {
            type: 'check',
            where: {
                price: {
                    [Sequelize.Op.gt]: 0
                }
            }
        }));
    },

    down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('Products');
    }
};
like image 153
mcmlxxxiii Avatar answered Oct 11 '22 12:10

mcmlxxxiii