Sample Header Ad - 728x90

Drizzle migrations don't seem to be repeatable

0 votes
0 answers
24 views
In our node.js backend we are using drizzle ORM with postgres, but our migrations are failing for some of our customers db's but not for all of them. Also, when I create a new empty database and do the migrations, it first does so successfully, but afterwards it starts failing too.. error: company_function_id referenced in foreign key constraint does not exist This is a part of our first migration file: 0000_nosy_mastermind.sql
...

--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "employees" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"user_id" uuid,
	"first_name" varchar(255) NOT NULL,
	"last_name" varchar(255) NOT NULL,
	"company_email" text,
	"telephone" varchar(255),
	"bank_account_number" varchar(255),
	"extra_info" text,
	"date_employment_start" timestamp,
	"date_employment_end" timestamp,
	"company_id" uuid NOT NULL,
	"company_function_id" uuid,
               ....
    CONSTRAINT "employees_id_unique" UNIQUE("id")
);
--> statement-breakpoint
...
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "company_functions" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"name" varchar(255) NOT NULL,
	"description" text,
	"department_id" uuid,
	"created_at" timestamp DEFAULT now(),
	"updated_at" timestamp DEFAULT now(),
	"company_id" uuid NOT NULL,
	CONSTRAINT "company_functions_id_unique" UNIQUE("id"),
	CONSTRAINT "unique_company_function_name" UNIQUE("company_id","name","department_id")
);
--> statement-breakpoint
...
--> statement-breakpoint
DO $$ BEGIN
 ALTER TABLE "employees" ADD CONSTRAINT "employees_company_function_id_company_functions_id_fk" FOREIGN KEY ("company_function_id") REFERENCES "public"."company_functions"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
 WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
...
The second part is where the migration fails: docker postgres output showing the error and the cause Now, I'm guessing this failure is due to this part from 0078_concerned_micromacro.sql
DO $$
BEGIN
  ALTER TABLE "employees" DROP COLUMN IF EXISTS "company_function_id";
EXCEPTION
  WHEN undefined_column THEN NULL;
END $$;
But what I find strange is that these sql statements should not be able to run twice. Because the first time it makes sense. But the second time it will not recreate the table (due to the if not exists part). So company_function_id will be gone. but it does tries to add a foreign key constraint on that field that does not exist anymore. How should this be compatible?
Asked by michielQaro (1 rep)
Aug 4, 2025, 02:01 PM