1 import { Migration } from "@medusajs/framework/mikro-orm/migrations"
2 import { ulid } from "ulid"
3
4 export class Migration20250505092459 extends Migration {
5 override async up(): Promise<void> {
6 this.addSql(
7 `alter table if exists "workflow_execution" drop constraint if exists "workflow_execution_workflow_id_transaction_id_run_id_unique";`
8 )
9 this.addSql(
10 `drop index if exists "IDX_workflow_execution_workflow_id_transaction_id_unique";`
11 )
12 this.addSql(
13 `alter table if exists "workflow_execution" drop constraint if exists "PK_workflow_execution_workflow_id_transaction_id";`
14 )
15
16 this.addSql(
17 `alter table if exists "workflow_execution" add column if not exists "run_id" text not null default '${ulid()}';`
18 )
19 this.addSql(
20 `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_workflow_execution_workflow_id_transaction_id_run_id_unique" ON "workflow_execution" (workflow_id, transaction_id, run_id) WHERE deleted_at IS NULL;`
21 )
22 /*
23 * We mistakenly named this migration differently in the workflow engines; this has caused issues with the migrations. Switching between engines will fail because the primary key is attempted to be set twice.
24 * The issue happens in the following scenario:
25 * 1. In memory engine is used
26 * 2. Migration is run
27 * 3. Primary is key added
28 * 3. Redis engine is used
29 * 4. Migration is run
30 * 5. Same primary key is attempted to be set again
31 * 6. Migration fails
32 *
33 * The same scenario can happen if you go from Redis to In memory.
34 *
35 * With this fix, we ensure the primary key is only ever set once.
36 */
37 this.addSql(
38 `alter table if exists "workflow_execution" drop constraint if exists "workflow_execution_pkey";`
39 )
40 this.addSql(
41 `alter table if exists "workflow_execution" add constraint "workflow_execution_pkey" primary key ("workflow_id", "transaction_id", "run_id");`
42 )
43 }
44
45 override async down(): Promise<void> {
46 this.addSql(
47 `drop index if exists "IDX_workflow_execution_workflow_id_transaction_id_run_id_unique";`
48 )
49 this.addSql(
50 `alter table if exists "workflow_execution" drop constraint if exists "workflow_execution_pkey";`
51 )
52 this.addSql(
53 `alter table if exists "workflow_execution" drop column if exists "run_id";`
54 )
55
56 this.addSql(
57 `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_workflow_execution_workflow_id_transaction_id_unique" ON "workflow_execution" (workflow_id, transaction_id) WHERE deleted_at IS NULL;`
58 )
59 this.addSql(
60 `alter table if exists "workflow_execution" add constraint "workflow_execution_pkey" primary key ("workflow_id", "transaction_id");`
61 )
62 }
63 }