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.57k stars 490 forks source link

[BUG]: drizzle-kit does not respect the order of columns configured in primaryKey() #2326

Open yodhcn opened 1 month ago

yodhcn commented 1 month ago

What version of drizzle-orm are you using?

0.30.10

What version of drizzle-kit are you using?

0.21.1

Describe the Bug

export const worksToCreators = sqliteTable(
  'works_to_creators',
  {
    workId: integer('work_id')
      .notNull()
      .references(() => works.id),
    creatorId: integer('creator_id')
      .notNull()
      .references(() => creators.id),
    classification: text('classification', {
      enum: [
        'voice_by',
        'music_by',
        'other_by',
      ],
    }).notNull(),
  },
  (t) => ({
    pk: primaryKey({
      columns: [t.workId, t.creatorId, t.classification],
    }),
  })
)

desired column order: [t.workId, t.creatorId, t.classification] actual column order: [t.classification, t.creator_id, t.work_id]

CREATE TABLE `works_to_creators` (
    `work_id` integer NOT NULL,
    `creator_id` integer NOT NULL,
    `classification` text NOT NULL,
    PRIMARY KEY(`classification`, `creator_id`, `work_id`), # wrong order
    FOREIGN KEY (`work_id`) REFERENCES `works`(`id`) ON UPDATE no action ON DELETE no action,
    FOREIGN KEY (`creator_id`) REFERENCES `creators`(`id`) ON UPDATE no action ON DELETE no action
);

Expected behavior

export const worksToCreators = sqliteTable(
  'works_to_creators',
  {
    workId: integer('work_id')
      .notNull()
      .references(() => works.id),
    creatorId: integer('creator_id')
      .notNull()
      .references(() => creators.id),
    classification: text('classification', {
      enum: [
        'voice_by',
        'music_by',
        'other_by',
      ],
    }).notNull(),
  },
  (t) => ({
    pk: primaryKey({
      columns: [t.workId, t.creatorId, t.classification],
    }),
  })
)
CREATE TABLE `works_to_creators` (
    `work_id` integer NOT NULL,
    `creator_id` integer NOT NULL,
    `classification` text NOT NULL,
    PRIMARY KEY(`work_id`, `creator_id`, `classification`), # correct order
    FOREIGN KEY (`work_id`) REFERENCES `works`(`id`) ON UPDATE no action ON DELETE no action,
    FOREIGN KEY (`creator_id`) REFERENCES `creators`(`id`) ON UPDATE no action ON DELETE no action
);

Environment & setup

import type { Config } from 'drizzle-kit'

export default {
  schema: './src/db/schema/index.ts',
  out: './drizzle',
  dialect: 'sqlite',
  driver: 'd1',
} satisfies Config
bunx drizzle-kit generate