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!!
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.
"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.
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.
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.
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');
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With