drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[BUG]: Postgres | applying migrations...error: relation "public.users" does not exist

Open PhiboGit opened this issue 1 year ago • 4 comments

Report hasn't been filed before.

  • [x] I have verified that the bug I'm about to report hasn't been filed before.

What version of drizzle-orm are you using?

0.41.0

What version of drizzle-kit are you using?

0.30.6

Other packages

No response

Describe the Bug

I am running into the same error as stated in this issue: #2891

Setup

Drizzle Table Definitions

export const usersTable = pgTable(
  'users',
  {
    id: integer().primaryKey().generatedAlwaysAsIdentity(),
  },
);

export const charactersTable = pgTable(
  'characters',
  {
    id: integer().primaryKey().generatedAlwaysAsIdentity(),
    userId: integer()
      .notNull()
      .references(() => usersTable.id, {
        onDelete: 'cascade',
      }),
  },
);

Drizzle Config

import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  out: './drizzle',
  schema: [
    './src/db/app/schemas/users.ts',
  ],
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.POSTGRES_URL!,
  },
});

Steps to reproduce

  1. drizzle-kit generate
CREATE TABLE "characters" (
	"id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "characters_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1),
	"userId" integer NOT NULL
);
--> statement-breakpoint
CREATE TABLE "users" (
	"id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "users_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1)
);
--> statement-breakpoint
ALTER TABLE "characters" ADD CONSTRAINT "characters_userId_users_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
  1. drizzle-kit migrate
applying migrations...error: relation "public.users" does not exist
    at /node_modules/pg/lib/client.js:545:17
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async <anonymous> (/node_modules/src/pg-core/dialect.ts:102:7)
    at async NodePgSession.transaction (/node_modules/src/node-postgres/session.ts:233:19)
    at async PgDialect.migrate (/node_modules/src/pg-core/dialect.ts:95:3)
    at async migrate (/node_modules/src/node-postgres/migrator.ts:10:2) {
  length: 110,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'namespace.c',
  line: '429',
  routine: 'RangeVarGetRelidExtended'
}

Workarounds

  • With psql execute the creation of the tables first and then alter the table.
  • Or remove "public". from references in the sql file and run drizzle-kit migrate again.

The order of operations (CREATE TABLE -> ALTER TABLE) is valid in PostgreSQL and is a valid workaround for this error.

This suggests the issue lies within the execution context of npx drizzle-kit migrate. It's likely wrapping the entire migration script in a single transaction, and within that transaction, the ALTER TABLE statements are executed before the CREATE TABLE "characters" statement.

PhiboGit avatar Apr 05 '25 22:04 PhiboGit

I'm encountering this same issue, the ADD CONSTRAINT ... FOREIGN KEY statement seems to insert the "public" schema name in the REFERENCES argument, which causes issues when not using the public schema. A workaround I've been using is to use an older version of drizzle-kit and drizzle orm.

Here's the version that I use and the SQL file that I get with npx drizzle-kit generate:pg

"drizzle-kit": "^0.20.1",
"drizzle-orm": "^0.29.0"
CREATE TABLE IF NOT EXISTS "characters" (
	"id" serial PRIMARY KEY NOT NULL,
	"user_id" integer NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "users" (
	"id" serial PRIMARY KEY NOT NULL
);
--> statement-breakpoint
DO $$ BEGIN
 ALTER TABLE "characters" ADD CONSTRAINT "characters_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE cascade ON UPDATE no action;  -- "users"("id"), not "public"."users"("id")
EXCEPTION
 WHEN duplicate_object THEN null;
END $$;

It would be really useful if you could bring back not specifying the schema as public, as otherwise trying to run migrations in a dynamically in a multi-tenant database is really difficult. Without the "public" it just requires setting the search path before running migrations.

Kuki145 avatar May 22 '25 10:05 Kuki145

I ran into something similar when attempting to create a multi-tenant backend, but always run into an issue when generating the migration. It seems to insistent on adding the public schema to the references for god knows what reason. I had to manually remove the public references from the sql every time i generate another migration.

The actual applying of the migrations is no big deal because you can just create a pool of connections, one for each tenant schema, and set the search_path to the tenant schema name and loop through them, but the generation of the sql is still an absolute headache.

Drizzle is great in so many ways but unfortunately they don't seem to care about multi-tenant schema use cases, which is key for enterprise adoption due to data isolation regulations

TensorsWillFlow avatar Jul 04 '25 00:07 TensorsWillFlow

Hey everyone!

I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.

I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!

We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.


First branch is drizzle-kit rewrite

All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439

As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.

What's left here:

  • We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the srid issue here as well).
  • We are finishing commutative migrations for all dialects.
  • We are finishing up the command, so the migration flow will be as simple as drizzle-kit up for you.

Where it brings us:

  • We are getting drizzle-kit into a new good shape where we can call it [email protected]!

Timeline:

  • We need ~2 weeks to finish all of the above and send this branch to beta for testing.

Second big branch is a complex one with several HUGE updates

  • Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)

TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k

You can read more about it here.

What's left here:

Where it brings us:

  • We are getting drizzle-orm into a new good shape where we can call it [email protected]!

Breaking changes:

  • We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.

Third branch is adding support for CockroachDB and MSSQL dialects

Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.

Summary

All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.

We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).

We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.

Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!

Timelines

We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!

AndriiSherman avatar Aug 30 '25 19:08 AndriiSherman

This issue has been fixed in the beta tag, which serves as the release candidate for Drizzle v1 It's available under drizzle-orm@beta and drizzle-kit@beta version.

For more info please check: https://orm.drizzle.team/docs/upgrade-v1

AndriiSherman avatar Jan 03 '26 19:01 AndriiSherman