|
1
|
import { MikroORM, MikroORMOptions } from "@medusajs/deps/mikro-orm/core" |
|
2
|
import { |
|
3
|
MigrateOptions, |
|
4
|
MigrationResult, |
|
5
|
UmzugMigration, |
|
6
|
} from "@medusajs/deps/mikro-orm/migrations" |
|
7
|
import { |
|
8
|
defineConfig, |
|
9
|
PostgreSqlDriver, |
|
10
|
} from "@medusajs/deps/mikro-orm/postgresql" |
|
11
|
import { EventEmitter } from "events" |
|
12
|
import { access, mkdir, rename, writeFile } from "fs/promises" |
|
13
|
import { basename, dirname, join } from "path" |
|
14
|
import { readDir } from "../common" |
|
15
|
import { CustomDBMigrator } from "../dal/mikro-orm/custom-db-migrator" |
|
16
|
|
|
17
|
// Define the replacement mappings |
|
18
|
const replacements = [ |
|
19
|
// MikroORM imports - replace mikro-orm/{subpath} with @medusajs/framework/mikro-orm/{subpath} |
|
20
|
{ |
|
21
|
pattern: /from\s+['"]@?mikro-orm\/([^'"]+)['"]/g, |
|
22
|
// eslint-disable-next-line quotes |
|
23
|
replacement: 'from "@medusajs/framework/mikro-orm/$1"', |
|
24
|
}, |
|
25
|
// PG imports - replace pg with @medusajs/framework/pg |
|
26
|
{ |
|
27
|
pattern: /from\s+['"]pg['"]/g, |
|
28
|
// eslint-disable-next-line quotes |
|
29
|
replacement: 'from "@medusajs/framework/pg"', |
|
30
|
}, |
|
31
|
] |
|
32
|
|
|
33
|
/** |
|
34
|
* Events emitted by the migrations class |
|
35
|
*/ |
|
36
|
export type MigrationsEvents = { |
|
37
|
migrating: [UmzugMigration] |
|
38
|
migrated: [UmzugMigration] |
|
39
|
reverting: [UmzugMigration] |
|
40
|
reverted: [UmzugMigration] |
|
41
|
"revert:skipped": [UmzugMigration & { reason: string }] |
|
42
|
} |
|
43
|
|
|
44
|
/** |
|
45
|
* Exposes the API to programmatically manage Mikro ORM migrations |
|
46
|
*/ |
|
47
|
export class Migrations extends EventEmitter<MigrationsEvents> { |
|
48
|
#configOrConnection: Partial<MikroORMOptions> | MikroORM<PostgreSqlDriver> |
|
49
|
|
|
50
|
constructor( |
|
51
|
configOrConnection: Partial<MikroORMOptions> | MikroORM<PostgreSqlDriver> |
|
52
|
) { |
|
53
|
super() |
|
54
|
this.#configOrConnection = configOrConnection |
|
55
|
} |
|
56
|
|
|
57
|
/** |
|
58
|
* Returns an existing connection or instantiates a new |
|
59
|
* one |
|
60
|
*/ |
|
61
|
async #getConnection() { |
|
62
|
if ("connect" in this.#configOrConnection) { |
|
63
|
return this.#configOrConnection as MikroORM<PostgreSqlDriver> |
|
64
|
} |
|
65
|
|
|
66
|
return await MikroORM.init( |
|
67
|
defineConfig({ |
|
68
|
...(this.#configOrConnection as any), |
|
69
|
migrations: { |
|
70
|
...this.#configOrConnection.migrations, |
|
71
|
silent: true, |
|
72
|
}, |
|
73
|
extensions: [CustomDBMigrator], |
|
74
|
}) |
|
75
|
) |
|
76
|
} |
|
77
|
|
|
78
|
/** |
|
79
|
* Generates migrations for a collection of entities defined |
|
80
|
* in the config |
|
81
|
*/ |
|
82
|
async generate(): Promise<MigrationResult> { |
|
83
|
const connection = await this.#getConnection() |
|
84
|
const migrator = connection.getMigrator() |
|
85
|
|
|
86
|
try { |
|
87
|
await this.migrateSnapshotFile(migrator["snapshotPath"]) |
|
88
|
await this.ensureSnapshot(migrator["snapshotPath"]) |
|
89
|
const migrationResult = await migrator.createMigration() |
|
90
|
const code = migrationResult.code |
|
91
|
if (code) { |
|
92
|
let modifiedContent = code |
|
93
|
let wasModified = false |
|
94
|
|
|
95
|
replacements.forEach(({ pattern, replacement }) => { |
|
96
|
const newContent = modifiedContent.replace(pattern, replacement) |
|
97
|
if (newContent !== modifiedContent) { |
|
98
|
wasModified = true |
|
99
|
modifiedContent = newContent |
|
100
|
} |
|
101
|
}) |
|
102
|
|
|
103
|
if (wasModified) { |
|
104
|
await writeFile( |
|
105
|
join( |
|
106
|
connection.config.getDriver().config.get("migrations").path ?? "", |
|
107
|
migrationResult.fileName |
|
108
|
), |
|
109
|
modifiedContent, |
|
110
|
"utf-8" |
|
111
|
) |
|
112
|
} |
|
113
|
migrationResult.code = modifiedContent |
|
114
|
} |
|
115
|
return migrationResult |
|
116
|
} finally { |
|
117
|
await connection.close(true) |
|
118
|
} |
|
119
|
} |
|
120
|
|
|
121
|
/** |
|
122
|
* Run migrations for the provided entities |
|
123
|
*/ |
|
124
|
async run( |
|
125
|
options?: string | string[] | MigrateOptions |
|
126
|
): Promise<UmzugMigration[]> { |
|
127
|
const connection = await this.#getConnection() |
|
128
|
const migrator = connection.getMigrator() |
|
129
|
|
|
130
|
migrator["umzug"].on("migrating", (event: UmzugMigration) => |
|
131
|
this.emit("migrating", event) |
|
132
|
) |
|
133
|
migrator["umzug"].on("migrated", (event: UmzugMigration) => { |
|
134
|
this.emit("migrated", event) |
|
135
|
}) |
|
136
|
|
|
137
|
try { |
|
138
|
const res = await migrator.up(options) |
|
139
|
return res |
|
140
|
} finally { |
|
141
|
migrator["umzug"].clearListeners() |
|
142
|
await connection.close(true) |
|
143
|
} |
|
144
|
} |
|
145
|
|
|
146
|
/** |
|
147
|
* Run migrations for the provided entities |
|
148
|
*/ |
|
149
|
async revert( |
|
150
|
options?: string | string[] | MigrateOptions |
|
151
|
): Promise<UmzugMigration[]> { |
|
152
|
const connection = await this.#getConnection() |
|
153
|
const migrator = connection.getMigrator() |
|
154
|
|
|
155
|
migrator["umzug"].on("reverting", (event: UmzugMigration) => |
|
156
|
this.emit("reverting", event) |
|
157
|
) |
|
158
|
migrator["umzug"].on("reverted", (event: UmzugMigration) => { |
|
159
|
this.emit("reverted", event) |
|
160
|
}) |
|
161
|
|
|
162
|
try { |
|
163
|
return await migrator.down(options) |
|
164
|
} catch (error) { |
|
165
|
/** |
|
166
|
* This is a very ugly hack to recover from an exception thrown by |
|
167
|
* MikrORM when the `down` method is not implemented by the |
|
168
|
* migration. |
|
169
|
* |
|
170
|
* We cannot check if "down" method exists on the migration, because it |
|
171
|
* always exists (as inherited from the parent class). Also, throwing |
|
172
|
* an exception is important, so that Mikro ORM does not consider the |
|
173
|
* given migration as reverted. |
|
174
|
*/ |
|
175
|
if ( |
|
176
|
error?.migration && |
|
177
|
error?.cause?.message === "This migration cannot be reverted" |
|
178
|
) { |
|
179
|
this.emit("revert:skipped", { |
|
180
|
...error.migration, |
|
181
|
reason: "Missing down method", |
|
182
|
}) |
|
183
|
return [] |
|
184
|
} |
|
185
|
|
|
186
|
throw error |
|
187
|
} finally { |
|
188
|
migrator["umzug"].clearListeners() |
|
189
|
await connection.close(true) |
|
190
|
} |
|
191
|
} |
|
192
|
|
|
193
|
/** |
|
194
|
* Migrates the existing snapshot file of a module to follow to be |
|
195
|
* named after the current snapshot file. |
|
196
|
* |
|
197
|
* If there are multiple snapshot files inside the directory, then |
|
198
|
* the first one will be used. |
|
199
|
*/ |
|
200
|
protected async migrateSnapshotFile(snapshotPath: string): Promise<void> { |
|
201
|
// If the expected snapshot already exists, no rename needed — running the |
|
202
|
// rename would incorrectly overwrite it with an incorrect snapshot file, |
|
203
|
// leading to side effects when generating migrations |
|
204
|
const alreadyExists = await access(snapshotPath) |
|
205
|
.then(() => true) |
|
206
|
.catch(() => false) |
|
207
|
if (alreadyExists) { |
|
208
|
return |
|
209
|
} |
|
210
|
|
|
211
|
const entries = await readDir(dirname(snapshotPath), { |
|
212
|
ignoreMissing: true, |
|
213
|
}) |
|
214
|
|
|
215
|
// Only rename the exact known legacy filename (`.snapshot-<module>.json` |
|
216
|
// renamed to `.snapshot-medusa-<module>.json` for plugin:db:generate users). |
|
217
|
// Matching any `.json` file risks picking up full-DB snapshots. |
|
218
|
const expectedName = basename(snapshotPath) |
|
219
|
const legacyName = expectedName.replace(/^\.snapshot-medusa-/, ".snapshot-") |
|
220
|
const snapshotFile = entries.find( |
|
221
|
(entry) => entry.isFile() && entry.name === legacyName |
|
222
|
) |
|
223
|
|
|
224
|
if (snapshotFile) { |
|
225
|
const absoluteName = join( |
|
226
|
snapshotFile.parentPath || snapshotFile.path, |
|
227
|
snapshotFile.name |
|
228
|
) |
|
229
|
|
|
230
|
if (absoluteName !== snapshotPath) { |
|
231
|
await rename(absoluteName, snapshotPath) |
|
232
|
} |
|
233
|
} |
|
234
|
} |
|
235
|
|
|
236
|
/** |
|
237
|
* Generate a default snapshot file if it does not already exists. This |
|
238
|
* prevent from creating a database to manage the migrations and instead |
|
239
|
* rely on the snapshot. |
|
240
|
* |
|
241
|
* @param snapshotPath |
|
242
|
* @protected |
|
243
|
*/ |
|
244
|
protected async ensureSnapshot(snapshotPath: string): Promise<void> { |
|
245
|
await mkdir(dirname(snapshotPath), { recursive: true }) |
|
246
|
|
|
247
|
const doesFileExists = await access(snapshotPath) |
|
248
|
.then(() => true) |
|
249
|
.catch(() => false) |
|
250
|
|
|
251
|
if (doesFileExists) { |
|
252
|
return |
|
253
|
} |
|
254
|
|
|
255
|
const emptySnapshotContent = JSON.stringify( |
|
256
|
{ |
|
257
|
tables: [], |
|
258
|
namespaces: [], |
|
259
|
}, |
|
260
|
null, |
|
261
|
2 |
|
262
|
) |
|
263
|
|
|
264
|
await writeFile(snapshotPath, emptySnapshotContent, "utf-8") |
|
265
|
} |
|
266
|
} |