|
1
|
export const metadata = { |
|
2
|
title: `${pageNumber} Migrations`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
In this chapter, you'll learn what a migration is and how to generate a migration or write it manually. |
|
8
|
|
|
9
|
## What is a Migration? |
|
10
|
|
|
11
|
A migration is a TypeScript or JavaScript file that defines database changes made by a module. Migrations are useful when you re-use a module or you're working in a team, so that when one member of a team makes a database change, everyone else can reflect it on their side by running the migrations. |
|
12
|
|
|
13
|
The migration's file has a class with two methods: |
|
14
|
|
|
15
|
- The `up` method reflects changes on the database. |
|
16
|
- The `down` method reverts the changes made in the `up` method. |
|
17
|
|
|
18
|
--- |
|
19
|
|
|
20
|
## Generate Migration |
|
21
|
|
|
22
|
Instead of you writing the migration manually, the Medusa CLI tool provides a [db:generate](!resources!/medusa-cli/commands/db#dbgenerate) command to generate a migration for a modules' data models. |
|
23
|
|
|
24
|
For example, assuming you have a `blog` Module, you can generate a migration for it by running the following command: |
|
25
|
|
|
26
|
```bash npx2yarn |
|
27
|
npx medusa db:generate blog |
|
28
|
``` |
|
29
|
|
|
30
|
This generates a migration file under the `migrations` directory of the Blog Module. You can then run it to reflect the changes in the database as mentioned in [this section](#run-the-migration). |
|
31
|
|
|
32
|
--- |
|
33
|
|
|
34
|
## Write a Migration Manually |
|
35
|
|
|
36
|
You can also write migrations manually. To do that, create a file in the `migrations` directory of the module and in it, a class that has an `up` and `down` method. The class's name should be of the format `Migration{YEAR}{MONTH}{DAY}{HOUR}{MINUTE}.ts` to ensure migrations are ran in the correct order. |
|
37
|
|
|
38
|
For example: |
|
39
|
|
|
40
|
<Note> |
|
41
|
|
|
42
|
As of [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0), MikroORM dependencies are included in the `@medusajs/framework` package. If you're using an older version of Medusa, change the import statement to `@mikro-orm/migrations`. |
|
43
|
|
|
44
|
</Note> |
|
45
|
|
|
46
|
```ts title="src/modules/blog/migrations/Migration202507021059_create_author.ts" |
|
47
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
48
|
|
|
49
|
export class Migration202507021059 extends Migration { |
|
50
|
|
|
51
|
async up(): Promise<void> { |
|
52
|
this.addSql("create table if not exists \"author\" (\"id\" text not null, \"name\" text not null, \"created_at\" timestamptz not null default now(), \"updated_at\" timestamptz not null default now(), \"deleted_at\" timestamptz null, constraint \"author_pkey\" primary key (\"id\"));") |
|
53
|
} |
|
54
|
|
|
55
|
async down(): Promise<void> { |
|
56
|
this.addSql("drop table if exists \"author\" cascade;") |
|
57
|
} |
|
58
|
|
|
59
|
} |
|
60
|
``` |
|
61
|
|
|
62
|
The migration class in the file extends the `Migration` class imported from `@medusajs/framework/mikro-orm/migrations`. In the `up` and `down` method of the migration class, you use the `addSql` method provided by MikroORM's `Migration` class to run PostgreSQL syntax. |
|
63
|
|
|
64
|
In the example above, the `up` method creates the table `author`, and the `down` method drops the table if the migration is reverted. |
|
65
|
|
|
66
|
<Note title="Important"> |
|
67
|
|
|
68
|
When you write a migration manually for a data model defined with [model.define](../page.mdx), make sure the created table includes the `created_at`, `updated_at`, and `deleted_at` columns. Medusa adds these [default properties](../properties/page.mdx#data-models-default-properties) to every data model, and the module's service relies on them in its queries. For example, the service filters out soft-deleted records using the `deleted_at` column, so queries fail at runtime if the column doesn't exist. |
|
69
|
|
|
70
|
</Note> |
|
71
|
|
|
72
|
<Note title="Tip"> |
|
73
|
|
|
74
|
Refer to [MikroORM's documentation](https://mikro-orm.io/docs/migrations#migration-class) for more details on writing migrations. |
|
75
|
|
|
76
|
</Note> |
|
77
|
|
|
78
|
### Migration File Naming |
|
79
|
|
|
80
|
Migrations are executed in the ascending order of their file names. So, it's recommended to prefix the migration file name with the timestamp of when the migration was created. This ensures that migrations are executed in the order they were created. |
|
81
|
|
|
82
|
For example, if you create a migration on July 2, 2025, at 10:59 AM, the file name should be `Migration202507021059_create_brand.ts`. This way, the migration will be executed after any previous migrations that were created before this date and time. |
|
83
|
|
|
84
|
--- |
|
85
|
|
|
86
|
## Run the Migration |
|
87
|
|
|
88
|
To run your migration, run the following command: |
|
89
|
|
|
90
|
<Note> |
|
91
|
|
|
92
|
This command also syncs module links. If you don't want that, use the `--skip-links` option. |
|
93
|
|
|
94
|
</Note> |
|
95
|
|
|
96
|
```bash npx2yarn |
|
97
|
npx medusa db:migrate |
|
98
|
``` |
|
99
|
|
|
100
|
This reflects the changes in the database as implemented in the migration's `up` method. |
|
101
|
|
|
102
|
--- |
|
103
|
|
|
104
|
## Rollback the Migration |
|
105
|
|
|
106
|
To rollback or revert the last migration you ran for a module, run the following command: |
|
107
|
|
|
108
|
```bash npx2yarn |
|
109
|
npx medusa db:rollback blog |
|
110
|
``` |
|
111
|
|
|
112
|
This rolls back the last ran migration on the Blog Module. |
|
113
|
|
|
114
|
### Caution: Rollback Migration before Deleting |
|
115
|
|
|
116
|
If you need to delete a migration file, make sure to rollback the migration first. Otherwise, you might encounter issues when generating and running new migrations. |
|
117
|
|
|
118
|
For example, if you delete the migration of the Blog Module, then try to create a new one, Medusa will create a brand new migration that re-creates the tables or indices. If those are still in the database, you might encounter errors. |
|
119
|
|
|
120
|
So, always rollback the migration before deleting it. |
|
121
|
|
|
122
|
--- |
|
123
|
|
|
124
|
## More Database Commands |
|
125
|
|
|
126
|
To learn more about the Medusa CLI's database commands, refer to [this CLI reference](!resources!/medusa-cli/commands/db). |
|
127
|
|
|
128
|
--- |
|
129
|
|
|
130
|
## Data Migration Scripts |
|
131
|
|
|
132
|
In some use cases, you may need to perform data migration after updates to the database. For example, after you added a `Site` data model to the Blog Module, you want to assign all existing posts and authors to a default site. Another example is updating data stored in a third-party system. |
|
133
|
|
|
134
|
In those scenarios, you can instead create a data migration script. They are asynchronous function that the Medusa application executes once when you run migrations. |
|
135
|
|
|
136
|
### How to Create a Data Migration Script |
|
137
|
|
|
138
|
You can create data migration scripts in a TypeScript or JavaScript file under the `src/migration-scripts` directory. The file must export an asynchronous function that will be executed when the `db:migrate` command is executed. |
|
139
|
|
|
140
|
For example, to create a data migration script for the Blog Module example, create the file `src/migration-scripts/migrate-blog-data.ts` with the following content: |
|
141
|
|
|
142
|
export const dataMigrationHighlights = [ |
|
143
|
["6", "migrateBlogData", "Function to execute when migrations are run"], |
|
144
|
["8", "isInstalled", "Confirm that the Blog Module is installed before running the workflow."], |
|
145
|
["12", "migrateBlogDataWorkflow", "Perform the data migration action."], |
|
146
|
] |
|
147
|
|
|
148
|
```ts title="src/migration-scripts/migrate-blog-data.ts" highlights={dataMigrationHighlights} |
|
149
|
import { MedusaModule } from "@medusajs/framework/modules-sdk" |
|
150
|
import { ExecArgs } from "@medusajs/framework/types" |
|
151
|
import { BLOG_MODULE } from "../modules/blog" |
|
152
|
import { createWorkflow } from "@medusajs/framework/workflows-sdk" |
|
153
|
|
|
154
|
export default async function migrateBlogData({ container }: ExecArgs) { |
|
155
|
// Check that the blog module exists |
|
156
|
if (!MedusaModule.isInstalled(BLOG_MODULE)) { |
|
157
|
return |
|
158
|
} |
|
159
|
|
|
160
|
await migrateBlogDataWorkflow(container).run({}) |
|
161
|
} |
|
162
|
|
|
163
|
const migrateBlogDataWorkflow = createWorkflow( |
|
164
|
"migrate-blog-data", |
|
165
|
() => { |
|
166
|
// Assuming you have these steps |
|
167
|
createDefaultSiteStep() |
|
168
|
|
|
169
|
assignBlogDataToSiteStep() |
|
170
|
} |
|
171
|
) |
|
172
|
``` |
|
173
|
|
|
174
|
In the above example, you default export an asynchronous function that receives an object parameter with the [Medusa Container](../../medusa-container/page.mdx) property. |
|
175
|
|
|
176
|
In the function, you first ensure that the Blog Module is installed to avoid errors otherwise. Then, you run a workflow that you've created in the same file that performs the necessary data migration. |
|
177
|
|
|
178
|
#### Test Data Migration Script |
|
179
|
|
|
180
|
To test out the data migration script, run the migration command: |
|
181
|
|
|
182
|
```bash npx2yarn |
|
183
|
npx medusa db:migrate |
|
184
|
``` |
|
185
|
|
|
186
|
Medusa will run any pending migrations and migration scripts, including your script. |
|
187
|
|
|
188
|
If the script runs successfully, Medusa won't run the script again. |
|
189
|
|
|
190
|
If there are errors in the script, you'll receive an error in the migration script logs. Medusa will keep running the script every time you run the migration command until it runs successfully. |
|
191
|
|
|
192
|
--- |
|
193
|
|
|
194
|
## Migration Examples |
|
195
|
|
|
196
|
The following section provides examples of writing migrations for common database changes. |
|
197
|
|
|
198
|
### Example: Migration with Relationship |
|
199
|
|
|
200
|
Consider you have a module with two data models: `Author` and `Post`. An author can have multiple posts, so there's a one-to-many relationship between the two models: |
|
201
|
|
|
202
|
```ts |
|
203
|
import { model } from "@medusajs/framework/utils" |
|
204
|
|
|
205
|
const Post = model.define("post", { |
|
206
|
id: model.id().primaryKey(), |
|
207
|
title: model.text(), |
|
208
|
author: model.belongsTo(() => Author, { |
|
209
|
mappedBy: "posts", |
|
210
|
}), |
|
211
|
}) |
|
212
|
|
|
213
|
const Author = model.define("author", { |
|
214
|
id: model.id().primaryKey(), |
|
215
|
name: model.text(), |
|
216
|
posts: model.hasMany(() => Post, { |
|
217
|
mappedBy: "author", |
|
218
|
}), |
|
219
|
}) |
|
220
|
``` |
|
221
|
|
|
222
|
To create a migration that reflects this relationship in the database, you can create a migration file as follows: |
|
223
|
|
|
224
|
```ts title="src/modules/blog/migrations/Migration202507021200_create_author_and_post.ts" |
|
225
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
226
|
|
|
227
|
export class Migration20251230112505 extends Migration { |
|
228
|
|
|
229
|
override async up(): Promise<void> { |
|
230
|
this.addSql(`create table if not exists "author" ("id" text not null, "name" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "author_pkey" primary key ("id"));`) |
|
231
|
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_author_deleted_at" ON "author" ("deleted_at") WHERE deleted_at IS NULL;`) |
|
232
|
|
|
233
|
this.addSql(`create table if not exists "post" ("id" text not null, "title" text not null, "author_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "post_pkey" primary key ("id"));`) |
|
234
|
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_post_author_id" ON "post" ("author_id") WHERE deleted_at IS NULL;`) |
|
235
|
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_post_deleted_at" ON "post" ("deleted_at") WHERE deleted_at IS NULL;`) |
|
236
|
|
|
237
|
this.addSql(`alter table if exists "post" add constraint "post_author_id_foreign" foreign key ("author_id") references "author" ("id") on update cascade;`) |
|
238
|
} |
|
239
|
|
|
240
|
override async down(): Promise<void> { |
|
241
|
this.addSql(`alter table if exists "post" drop constraint if exists "post_author_id_foreign";`) |
|
242
|
|
|
243
|
this.addSql(`drop table if exists "author" cascade;`) |
|
244
|
|
|
245
|
this.addSql(`drop table if exists "post" cascade;`) |
|
246
|
} |
|
247
|
|
|
248
|
} |
|
249
|
``` |
|
250
|
|
|
251
|
In this migration, the `up` method creates the `author` and `post` tables, including the foreign key constraint that establishes the relationship between them. The `down` method removes the foreign key constraint and drops both tables. |
|
252
|
|
|
253
|
### Example: Migration to Add a New Column |
|
254
|
|
|
255
|
Consider you have an existing `Post` data model, and you added a new `published_at` column to it. |
|
256
|
|
|
257
|
You can create a migration file to add this new column as follows: |
|
258
|
|
|
259
|
```ts title="src/modules/blog/migrations/Migration202507021300_add_published_at_to_post.ts" |
|
260
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
261
|
|
|
262
|
export class Migration20251230113025 extends Migration { |
|
263
|
|
|
264
|
override async up(): Promise<void> { |
|
265
|
this.addSql(`alter table if exists "post" add column if not exists "published_at" timestamptz null;`) |
|
266
|
} |
|
267
|
|
|
268
|
override async down(): Promise<void> { |
|
269
|
this.addSql(`alter table if exists "post" drop column if exists "published_at";`) |
|
270
|
} |
|
271
|
|
|
272
|
} |
|
273
|
``` |
|
274
|
|
|
275
|
In this migration, the `up` method adds the `published_at` column to the `post` table, while the `down` method removes it. |
|
276
|
|
|
277
|
### Example: Migration to Remove a Column |
|
278
|
|
|
279
|
Consider you have an existing `Post` data model, and you removed the `published_at` column from it. |
|
280
|
|
|
281
|
You can create a migration file to remove this column as follows: |
|
282
|
|
|
283
|
```ts title="src/modules/blog/migrations/Migration202507021400_remove_published_at_from_post.ts" |
|
284
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
285
|
|
|
286
|
export class Migration20251230113125 extends Migration { |
|
287
|
|
|
288
|
override async up(): Promise<void> { |
|
289
|
this.addSql(`alter table if exists "post" drop column if exists "published_at";`) |
|
290
|
} |
|
291
|
|
|
292
|
override async down(): Promise<void> { |
|
293
|
this.addSql(`alter table if exists "post" add column if not exists "published_at" timestamptz null;`) |
|
294
|
} |
|
295
|
|
|
296
|
} |
|
297
|
``` |
|
298
|
|
|
299
|
In this migration, the `up` method removes the `published_at` column from the `post` table, while the `down` method adds it back. |
|
300
|
|
|
301
|
### Example: Migration to Rename a Column |
|
302
|
|
|
303
|
Consider you have an existing `Post` data model with a `title` column, and you renamed it to `headline`. |
|
304
|
|
|
305
|
You can create a migration file to rename this column as follows: |
|
306
|
|
|
307
|
```ts title="src/modules/blog/migrations/Migration202507021500_rename_title_to_headline_in_post.ts" |
|
308
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
309
|
|
|
310
|
export class Migration20251230113214 extends Migration { |
|
311
|
|
|
312
|
override async up(): Promise<void> { |
|
313
|
this.addSql(`alter table if exists "post" rename column "title" to "headline";`) |
|
314
|
} |
|
315
|
|
|
316
|
override async down(): Promise<void> { |
|
317
|
this.addSql(`alter table if exists "post" rename column "headline" to "title";`) |
|
318
|
} |
|
319
|
|
|
320
|
} |
|
321
|
``` |
|
322
|
|
|
323
|
In this migration, the `up` method renames the `title` column to `headline` in the `post` table, while the `down` method renames it back to `title`. |
|
324
|
|
|
325
|
### Example: Migration to Create an Index |
|
326
|
|
|
327
|
Consider you have an existing `Post` data model, and add an index on the `headline` column to improve query performance: |
|
328
|
|
|
329
|
export const indexHighlights = [ |
|
330
|
["6", "index", "Define the index on the 'headline' column"], |
|
331
|
] |
|
332
|
|
|
333
|
```ts title="src/modules/blog/models/post.ts" highlights={indexHighlights} |
|
334
|
import { model } from "@medusajs/framework/utils" |
|
335
|
import { Author } from "./author" |
|
336
|
|
|
337
|
export const Post = model.define("post", { |
|
338
|
id: model.id().primaryKey(), |
|
339
|
headline: model.text().index(), |
|
340
|
author: model.belongsTo(() => Author, { |
|
341
|
mappedBy: "posts", |
|
342
|
}), |
|
343
|
}) |
|
344
|
``` |
|
345
|
|
|
346
|
You can create a migration file to create this index as follows: |
|
347
|
|
|
348
|
```ts title="src/modules/blog/migrations/Migration202507021600_create_index_on_headline_in_post.ts" |
|
349
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
350
|
|
|
351
|
export class Migration20251230113322 extends Migration { |
|
352
|
|
|
353
|
override async up(): Promise<void> { |
|
354
|
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_post_headline" ON "post" ("headline") WHERE deleted_at IS NULL;`) |
|
355
|
} |
|
356
|
|
|
357
|
override async down(): Promise<void> { |
|
358
|
this.addSql(`drop index if exists "IDX_post_headline";`) |
|
359
|
} |
|
360
|
|
|
361
|
} |
|
362
|
``` |
|
363
|
|
|
364
|
In this migration, the `up` method creates an index on the `headline` column of the `post` table, while the `down` method removes the index. |
|
365
|
|
|
366
|
### Example: Migration to Drop an Index |
|
367
|
|
|
368
|
Consider you have an existing `Post` data model with an index on the `headline` column, and you decide to remove this index. |
|
369
|
|
|
370
|
You can create a migration file to drop this index as follows: |
|
371
|
|
|
372
|
```ts title="src/modules/blog/migrations/Migration202507021700_drop_index_on_headline_in_post.ts" |
|
373
|
import { Migration } from "@medusajs/framework/mikro-orm/migrations" |
|
374
|
|
|
375
|
export class Migration20251230113350 extends Migration { |
|
376
|
|
|
377
|
override async up(): Promise<void> { |
|
378
|
this.addSql(`drop index if exists "IDX_post_headline";`) |
|
379
|
} |
|
380
|
|
|
381
|
override async down(): Promise<void> { |
|
382
|
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_post_headline" ON "post" ("headline") WHERE deleted_at IS NULL;`) |
|
383
|
} |
|
384
|
|
|
385
|
} |
|
386
|
``` |
|
387
|
|
|
388
|
In this migration, the `up` method drops the index on the `headline` column of the `post` table, while the `down` method recreates the index. |