drizzle-team / drizzle-kit-mirror

Docs and issues repository for drizzle-kit
289 stars 17 forks source link

`.primaryKey()` isn't picked up when updating an existing table. #175

Open andreterron opened 1 year ago

andreterron commented 1 year ago

Creating a new table on our schema:

export const testTable = pgTable("test", {
  id: uuid("id")
    .default(sql`extensions.uuid_generate_v4()`)
    .notNull()
    .primaryKey(),
  name: text("name"),
});

Correctly generates the sql migration (With PRIMARY KEY):

CREATE TABLE IF NOT EXISTS "test" (
    "id" uuid PRIMARY KEY DEFAULT extensions.uuid_generate_v4() NOT NULL,
    "name" text
);

But if I start with the following schema

export const testTable = pgTable("test", {
  name: text("name"),
});

And then add the id property, I get the following migration (Nothing about the primary key):

ALTER TABLE "test" ADD COLUMN "id" uuid DEFAULT extensions.uuid_generate_v4() NOT NULL;

I would expect the sql migration to also set id as the primary key, but I had to manually add the following SQL statement to our migration:

ALTER TABLE "test" ADD PRIMARY KEY ("id");

Sharing it here so that others can be aware of it, and hopefully be fixed!

Environment:

lirbank commented 4 months ago

I am using "drizzle-kit": "0.22.6".

I just ran into this as well. I am adding a primary key to some existing tables that don't have one. I workaround for the migration issue is to do it in two passes:

  1. First add the "id" field to the schema, but skip the primary key:
export const testTable = pgTable("test", {
  id: uuid("id").defaultRandom().notNull(), // <- Don't add the primary key
  createdAt: timestamp("created_at").notNull().defaultNow(),
});
  1. Generate a migration.

Output (first migration)

ALTER TABLE "test" ADD COLUMN "id" uuid DEFAULT gen_random_uuid() NOT NULL;--> statement-breakpoint
  1. Add the primary key to the schema
export const testTable = pgTable("test", {
  id: uuid("id").defaultRandom().notNull().primaryKey(), 
  createdAt: timestamp("created_at").notNull().defaultNow(),
});
  1. Generate a migration.

Output (second migration)

ALTER TABLE "test" ADD PRIMARY KEY ("id");
  1. Run migrations