drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
21.47k stars 486 forks source link

[BUG]: null value in column "XXX" of relation "YYY" violates not-null constraint #2487

Closed trompx closed 1 week ago

trompx commented 3 weeks ago

What version of drizzle-orm are you using?

0.31.2 (also not working on 0.30.10)

What version of drizzle-kit are you using?

0.22.7 (also not working on 0.21.1)

Describe the Bug

I'm trying to create a userId column, fk to users.id but optional (so I don't set the notNull property):

userId: char("user_id", {
  length: 12,
}).references(() => users.id),

But when I try to insert a value with NULL user_id, I get the error:

null value in column "user_id" of relation "notifications" violates not-null constraint

I've read that we're supposed to be able set null as fk if notNull is not present. I also tried with every combination of onDelete/onUpdate (set null, cascade etc.) but nothing works.

Also, in snapshot.json:

"user_id": {
  "name": "user_id",
  "type": "char(12)",
  "primaryKey": false,
  "notNull": false <------ GOOD
},

In generated sql:

CREATE TABLE IF NOT EXISTS "notifications" (
    "id" serial PRIMARY KEY NOT NULL,
    "user_id" char(12),
    ...
);

Expected behavior

I should be able to set a NULL value

Environment & setup

No response

trompx commented 3 weeks ago

I checked in drizzle-kit, the generated schema has a notNull() while I have clearly not set any notNull in my table declaration. This is a major bug.

In drizzle-kit schema explorer, I have : userId: char("to_user_id", { length: 12 }).notNull(),

trompx commented 1 week ago

It seems after creating a new project, it is not adding notNull() when not specified, so may be due to a node_modules cache issue. Will reopen if happens again.