Skip to content

Commit 295465e

Browse files
committed
docs: add data migration scripts section
1 parent 1797f02 commit 295465e

File tree

1 file changed

+44
-0
lines changed
  • www/apps/book/app/learn/fundamentals/data-models/write-migration

1 file changed

+44
-0
lines changed

www/apps/book/app/learn/fundamentals/data-models/write-migration/page.mdx

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,50 @@ So, always rollback the migration before deleting it.
103103

104104
---
105105

106+
## Data Migration Scripts
107+
108+
Some features might require data migrations to ensure new functionality works as expected after an upgrade. Typically, these migrations can be dealt with by database migrations within a module. However, this is not the case when the changes affect the data models in several modules or if the data is stored in a third-party system. In those scenarios, the data needs to be brought to the desired state.
109+
110+
To do so, you can use data migration scripts. They are very similar to regular scripts, in the sense that you have access to the dependency container, i.e. all modules. However, instead of running manually, data migration scripts are run automatically as part of running `medusa db:migrate`.
111+
112+
### How they work
113+
114+
The Medusa project, its plugins, and the core are scoured for files in the `src/migration-scripts` folder, which are then executed. The files should export a default function. These scripts are only run once, provided they succeed.
115+
116+
The flow is as follows:
117+
118+
- Find files
119+
- Ensure the `script_migrations` table exists. If not, create it
120+
- Identify pending migration scripts (scripts that have not been ran previously)
121+
- Acquire a lock on the table
122+
- Begin loop, for each script
123+
- Insert migration script in the database
124+
- Execute script
125+
- Mark script as finished
126+
- Release lock
127+
128+
### Example
129+
130+
```ts title="src/migration-scripts/example.tsx"
131+
import { MedusaModule } from "@medusajs/framework/modules-sdk"
132+
import { ExecArgs } from "@medusajs/framework/types"
133+
import { Modules } from "@medusajs/framework/utils"
134+
135+
export default async function migrationScript({
136+
container,
137+
}: ExecArgs) {
138+
// Check if the required modules are present
139+
if (!MedusaModule.isInstalled(Modules.PRODUCT))
140+
return
141+
142+
// Migrate data
143+
await migrateDataWorkflow(container).run(...)
144+
145+
}
146+
```
147+
148+
---
149+
106150
## More Database Commands
107151

108152
To learn more about the Medusa CLI's database commands, refer to [this CLI reference](!resources!/medusa-cli/commands/db).

0 commit comments

Comments
 (0)