|
1
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations"; |
|
2
|
|
|
3
|
export class Migration20241122120331 extends Migration { |
|
4
|
|
|
5
|
async up(): Promise<void> { |
|
6
|
this.addSql('alter table if exists "image" add column if not exists "rank" integer not null default 0, add column if not exists "product_id" text null;'); |
|
7
|
|
|
8
|
// Migrate existing relationships |
|
9
|
this.addSql(` |
|
10
|
update "image" i |
|
11
|
set product_id = pi.product_id, |
|
12
|
rank = ( |
|
13
|
select count(*) |
|
14
|
from product_images pi2 |
|
15
|
where pi2.product_id = pi.product_id |
|
16
|
and pi2.image_id <= pi.image_id |
|
17
|
) - 1 |
|
18
|
from "product_images" pi |
|
19
|
where pi.image_id = i.id; |
|
20
|
`); |
|
21
|
|
|
22
|
// Delete orphaned images |
|
23
|
this.addSql(` |
|
24
|
delete from "image" |
|
25
|
where product_id is null; |
|
26
|
`); |
|
27
|
|
|
28
|
this.addSql('alter table if exists "image" alter column "product_id" set not null;'); |
|
29
|
this.addSql('alter table if exists "image" add constraint "image_product_id_foreign" foreign key ("product_id") references "product" ("id") on update cascade on delete cascade;'); |
|
30
|
this.addSql('drop table if exists "product_images" cascade;'); |
|
31
|
} |
|
32
|
|
|
33
|
async down(): Promise<void> { |
|
34
|
this.addSql('create table if not exists "product_images" ("product_id" text not null, "image_id" text not null, constraint "product_images_pkey" primary key ("product_id", "image_id"));'); |
|
35
|
|
|
36
|
// Migrate relationships back to join table |
|
37
|
this.addSql(` |
|
38
|
insert into "product_images" (product_id, image_id) |
|
39
|
select product_id, id |
|
40
|
from "image" |
|
41
|
where product_id is not null; |
|
42
|
`); |
|
43
|
|
|
44
|
this.addSql('alter table if exists "product_images" add constraint "product_images_product_id_foreign" foreign key ("product_id") references "product" ("id") on update cascade on delete cascade;'); |
|
45
|
this.addSql('alter table if exists "product_images" add constraint "product_images_image_id_foreign" foreign key ("image_id") references "image" ("id") on update cascade on delete cascade;'); |
|
46
|
|
|
47
|
this.addSql('alter table if exists "image" drop constraint if exists "image_product_id_foreign";'); |
|
48
|
this.addSql('alter table if exists "image" drop column if exists "rank";'); |
|
49
|
this.addSql('alter table if exists "image" drop column if exists "product_id";'); |
|
50
|
} |
|
51
|
|
|
52
|
} |