Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use CHECK validation in Prisma models?

I have a table that can be created with this SQL code

CREATE TABLE IF NOT EXISTS "user" (
  id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name username NOT NULL,
  email email NOT NULL,
  password text NOT NULL,
  email_verified bool NOT NULL DEFAULT false,
  verify_email_code text,
  verify_email_code_exp_date TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CHECK (length(name) >= 3),
  CONSTRAINT unique_user_name UNIQUE (name),
  CHECK (length(email) >= 3),
  CONSTRAINT unique_user_email UNIQUE (email)
);

Here I'm checking length of name and email, and if length of either of them is less than 3 characters - the whole data will be rejected.

  1. How can I define this exact model with Prisma?
  2. If it isn't possible, what are workarounds?
like image 478
Sap Green Avatar asked Oct 19 '25 03:10

Sap Green


1 Answers

As of 2023, it's not possible:

Check constraints are currently not included in the generated Prisma schema - however, the underlying database still enforces the constraints. https://www.prisma.io/docs/guides/other/advanced-database-tasks/data-validation/postgresql#2-adding-a-table-with-a-single-check-constraint-on-a-single-column

You'll have to create a custom migration: https://www.prisma.io/docs/guides/migrate/developing-with-prisma-migrate/customizing-migrations

Open issue to support CHECK: https://github.com/prisma/prisma/issues/3388

like image 197
fafrd Avatar answered Oct 20 '25 16:10

fafrd