Add Data Model Check Constraints

In this chapter, you'll learn how to add check constraints to your data model.

What is a Check Constraint?#

A check constraint is a condition that must be satisfied by records inserted into a database table, otherwise an error is thrown.

For example, if you have a data model with a price property, you want to only allow positive number values. So, you add a check constraint that fails when inserting a record with a negative price value.


How to Set a Check Constraint?#

To set check constraints on a data model, use the checks method. This method accepts an array of check constraints to apply on the data model.

For example, to set a check constraint on a price property that ensures its value can only be a positive number:

Code
1import { model } from "@medusajs/framework/utils"2
3const CustomProduct = model.define("custom_product", {4  // ...5  price: model.bigNumber(),6})7.checks([8  (columns) => `${columns.price} >= 0`,9])

The item passed in the array parameter of checks can be a callback function that accepts as a parameter an object whose keys are the names of the properties in the data model schema, and values the respective column name in the database.

The function returns a string indicating the SQL check constraint expression. In the expression, use the columns parameter to access a property's column name.

You can also pass an object to the checks method:

Code
1import { model } from "@medusajs/framework/utils"2
3const CustomProduct = model.define("custom_product", {4  // ...5  price: model.bigNumber(),6})7.checks([8  {9    name: "custom_product_price_check",10    expression: (columns) => `${columns.price} >= 0`,11  },12])

The object accepts the following properties:

  • name: The check constraint's name.
  • expression: A function similar to the one that can be passed to the array. It accepts an object of columns and returns an SQL check constraint expression.

Apply in Migrations#

After adding the check constraint, make sure to generate and run migrations if you already have the table in the database. Otherwise, the check constraint won't be reflected.

To generate a migration for the data model's module then reflect it on the database, run the following command:

Terminal
npx medusa db:generate custom_modulenpx medusa db:migrate

The first command generates the migration under the migrations directory of your module's directory, and the second reflects it on the database.

Was this chapter helpful?
Edit this page
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break