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
24.77k stars 656 forks source link

[BUG]: `pgEnum` generates faulty migrations #3514

Open rnkp755 opened 3 weeks ago

rnkp755 commented 3 weeks ago

Report hasn't been filed before.

What version of drizzle-orm are you using?

0.36.1

What version of drizzle-kit are you using?

0.28.0

Other packages

@neondatabase/serverless

Describe the Bug

Created a User Schema with role.

import { pgTable, varchar, timestamp, pgEnum } from "drizzle-orm/pg-core";
import { randomUUID } from "crypto";

// Define the roles enum
export const rolesEnum = pgEnum("roles", ["user", "admin"]);

// Define the 'users' table
export const usersTable = pgTable("users", {
  id: varchar({ length: 36 })
    .$default(() => randomUUID()) // Use Node's randomUUID to generate unique string ID
    .primaryKey(),
  name: varchar({ length: 255 }).notNull(),
  email: varchar({ length: 255 }).notNull().unique(),
  role: rolesEnum().default("user"),
  created_at: timestamp().defaultNow().notNull(),
});

Generated Migration:

CREATE TYPE "public"."roles" AS ENUM('user', 'admin');
CREATE TABLE IF NOT EXISTS "users" (
    "id" varchar(36) PRIMARY KEY NOT NULL,
    "name" varchar(255) NOT NULL,
    "email" varchar(255) NOT NULL,
    "role" "roles" DEFAULT 'user',
    "created_at" timestamp DEFAULT now() NOT NULL,
    CONSTRAINT "users_email_unique" UNIQUE("email")
);

While migrating this an error came as: applying migrations...error: type "roles" does not exist

I needed to change the sql file a bit to make it work perfectly. I added few line of code which should've been added automatically.

New sql file:

CREATE TYPE "public"."roles" AS ENUM('user', 'admin');
CREATE TABLE IF NOT EXISTS "users" (
    "id" varchar(36) PRIMARY KEY NOT NULL,
    "name" varchar(255) NOT NULL,
    "email" varchar(255) NOT NULL,
    "role" "roles" DEFAULT 'user',
    "created_at" timestamp DEFAULT now() NOT NULL,
    CONSTRAINT "users_email_unique" UNIQUE("email")
);
// Extra lines
DO $$ BEGIN
 CREATE TYPE "roles" AS ENUM('admin', 'user');
EXCEPTION
 WHEN duplicate_object THEN null;
END $$;