1 import {
2 ILinkMigrationsPlanner,
3 LinkMigrationsPlannerAction,
4 ModuleJoinerConfig,
5 ModuleServiceInitializeOptions,
6 PlannerActionLinkDescriptor,
7 } from "@medusajs/framework/types"
8
9 import { EntitySchema, MikroORM } from "@medusajs/framework/mikro-orm/core"
10 import {
11 DatabaseSchema,
12 PostgreSqlDriver,
13 } from "@medusajs/framework/mikro-orm/postgresql"
14 import {
15 arrayDifference,
16 DALUtils,
17 executeWithConcurrency,
18 ModulesSdkUtils,
19 normalizeMigrationSQL,
20 } from "@medusajs/framework/utils"
21 import { generateEntity } from "../utils"
22
23 /**
24 * The migrations execution planner creates a plan of SQL queries
25 * to be executed to keep link modules database state in sync
26 * with the links defined inside the user application.
27 */
28 export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
29 /**
30 * Database options for the module service
31 */
32 #dbConfig: ReturnType<typeof ModulesSdkUtils.loadDatabaseConfig>
33
34 #schema: string = "public"
35
36 /**
37 * The set of commands that are unsafe to execute automatically when
38 * performing "alter table"
39 */
40 #unsafeSQLCommands = ["alter column", "drop column"]
41
42 /**
43 * On-the-fly computed set of entities for the user provided joinerConfig and the link it is coming from
44 */
45 #linksEntities: {
46 linkDescriptor: PlannerActionLinkDescriptor
47 entity: EntitySchema
48 }[]
49
50 /**
51 * The table that keeps a track of tables generated by the link
52 * module.
53 */
54 protected tableName = "link_module_migrations"
55
56 constructor(
57 joinerConfig: ModuleJoinerConfig[],
58 options?: ModuleServiceInitializeOptions
59 ) {
60 this.#dbConfig = ModulesSdkUtils.loadDatabaseConfig("link_modules", options)
61 this.#schema = options?.database?.schema ?? "public"
62 this.#linksEntities = joinerConfig
63 .map((config) => {
64 if (config.isReadOnlyLink) {
65 return
66 }
67
68 const [primary, foreign] = config.relationships ?? []
69 const linkDescriptor: PlannerActionLinkDescriptor = {
70 fromModule: primary.serviceName,
71 toModule: foreign.serviceName,
72 fromModel: primary.alias,
73 toModel: foreign.alias,
74 }
75
76 return {
77 entity: generateEntity(config, primary, foreign),
78 linkDescriptor,
79 }
80 })
81 .filter((item) => !!item)
82 }
83
84 /**
85 * Initializes the ORM using the normalized dbConfig and set
86 * of provided entities
87 */
88 protected async createORM(entities: EntitySchema[] = []) {
89 return await DALUtils.mikroOrmCreateConnection(this.#dbConfig, entities, "")
90 }
91
92 /**
93 * Ensure the table to track link modules migrations
94 * exists.
95 *
96 * @param orm MikroORM
97 */
98 protected async ensureMigrationsTable(
99 orm: MikroORM<PostgreSqlDriver>
100 ): Promise<void> {
101 await orm.em.getDriver().getConnection().execute(`
102 CREATE TABLE IF NOT EXISTS "${this.#schema}"."${this.tableName}" (
103 id SERIAL PRIMARY KEY,
104 table_name VARCHAR(255) NOT NULL UNIQUE,
105 link_descriptor JSONB NOT NULL DEFAULT '{}'::jsonb,
106 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
107 )
108 `)
109 }
110
111 /**
112 * Ensure the migrations table is in sync
113 *
114 * @param orm
115 * @protected
116 */
117 protected async ensureMigrationsTableUpToDate(
118 orm: MikroORM<PostgreSqlDriver>
119 ) {
120 const existingTables: string[] = (
121 await orm.em
122 .getDriver()
123 .getConnection()
124 .execute<
125 {
126 table_name: string
127 }[]
128 >(
129 `
130 SELECT table_name
131 FROM information_schema.tables
132 WHERE table_schema = '${this.#schema}';
133 `
134 )
135 )
136 .map(({ table_name }) => table_name)
137 .filter((tableName) =>
138 this.#linksEntities.some(
139 ({ entity }) => entity.meta.collection === tableName
140 )
141 )
142
143 if (!existingTables.length) {
144 return
145 }
146
147 const orderedDescriptors = existingTables.map((tableName) => {
148 return this.#linksEntities.find(
149 ({ entity }) => entity.meta.collection === tableName
150 )!.linkDescriptor
151 })
152
153 const positionalArgs = new Array(existingTables.length)
154 .fill("(?, ?)")
155 .join(", ")
156
157 await orm.em
158 .getDriver()
159 .getConnection()
160 .execute(
161 `
162 INSERT INTO "${this.#schema}"."${
163 this.tableName
164 }" (table_name, link_descriptor) VALUES ${positionalArgs} ON CONFLICT DO NOTHING;
165 `,
166 existingTables.flatMap((tableName, index) => [
167 tableName,
168 JSON.stringify(orderedDescriptors[index]),
169 ])
170 )
171 }
172
173 /**
174 * Insert tuple to the migrations table and create the link table
175 *
176 * @param orm
177 * @param action
178 * @protected
179 */
180 protected async createLinkTable(
181 orm: MikroORM<PostgreSqlDriver>,
182 action: LinkMigrationsPlannerAction & {
183 linkDescriptor: PlannerActionLinkDescriptor
184 sql: string
185 }
186 ) {
187 const { tableName, linkDescriptor, sql } = action
188
189 await orm.em
190 .getDriver()
191 .getConnection()
192 .execute(
193 `
194 SET LOCAL search_path TO "${this.#schema}";
195
196 INSERT INTO "${
197 this.tableName
198 }" (table_name, link_descriptor) VALUES (?, ?) ON CONFLICT DO NOTHING;
199
200 ${sql}
201 `,
202 [tableName, linkDescriptor]
203 )
204 }
205
206 /**
207 * Drops the link table and untracks it from the "link_modules_migrations"
208 * table.
209 */
210 protected async dropLinkTable(
211 orm: MikroORM<PostgreSqlDriver>,
212 tableName: string
213 ) {
214 await orm.em.getDriver().getConnection().execute(`
215 DROP TABLE IF EXISTS "${this.#schema}"."${tableName}";
216 DELETE FROM "${this.#schema}"."${
217 this.tableName
218 }" WHERE table_name = '${tableName}';
219 `)
220 }
221
222 /**
223 * Returns an array of table names that have been tracked during
224 * the last run. In short, these tables were created by the
225 * link modules migrations runner.
226 *
227 * @param orm MikroORM
228 */
229 protected async getTrackedLinksTables(
230 orm: MikroORM<PostgreSqlDriver>
231 ): Promise<
232 {
233 table_name: string
234 link_descriptor: PlannerActionLinkDescriptor
235 }[]
236 > {
237 const results = await orm.em.getDriver().getConnection().execute<
238 {
239 table_name: string
240 link_descriptor: PlannerActionLinkDescriptor
241 }[]
242 >(`
243 SELECT table_name, link_descriptor from "${this.#schema}"."${
244 this.tableName
245 }"
246 `)
247
248 return results.map((tuple) => ({
249 table_name: tuple.table_name,
250 link_descriptor: tuple.link_descriptor,
251 }))
252 }
253
254 private pickTableRelatedCommands(tableName: string, sqlCommand: string) {
255 const ignoreColumns = ["created_at", "updated_at", "deleted_at"]
256 const commands = sqlCommand.split(";")
257 const returnedCommands = commands
258 .filter((command) => {
259 const cmd = command.trim()
260 return (
261 cmd.length &&
262 cmd !== "set names 'utf8'" &&
263 cmd.includes(`"${tableName}"`) &&
264 !ignoreColumns.some((column) => cmd.includes(`column "${column}"`))
265 )
266 })
267 .map((cmd) => cmd.trim())
268
269 if (returnedCommands.length > 0) {
270 // adds ; at the end of each command
271 returnedCommands.push("")
272 }
273
274 return returnedCommands.join(";")
275 }
276 /**
277 * Returns the migration plan for a specific link entity.
278 */
279 protected async getEntityMigrationPlan(
280 linkDescriptor: PlannerActionLinkDescriptor,
281 entity: EntitySchema,
282 trackedLinksTables: string[]
283 ): Promise<LinkMigrationsPlannerAction> {
284 const tableName = entity.meta.collection
285 const orm = await this.createORM([entity])
286
287 try {
288 const generator = orm.getSchemaGenerator()
289 const platform = orm.em.getPlatform()
290 const connection = orm.em.getConnection()
291 const schemaName = this.#dbConfig.schema || "public"
292
293 /**
294 * If the table name for the entity has not been
295 * managed by us earlier, then we should create
296 * it.
297 */
298 if (!trackedLinksTables.includes(tableName)) {
299 return {
300 action: "create",
301 linkDescriptor,
302 tableName,
303 sql: normalizeMigrationSQL(await generator.getCreateSchemaSQL()),
304 }
305 }
306
307 /**
308 * Pre-fetching information schema from the database and using that
309 * as the way to compute the update diff.
310 *
311 * @note
312 * The "loadInformationSchema" mutates the "dbSchema" argument provided
313 * to it as the first argument.
314 */
315 const dbSchema = new DatabaseSchema(platform, schemaName)
316 await platform
317 .getSchemaHelper?.()
318 ?.loadInformationSchema(dbSchema, connection, [
319 {
320 table_name: tableName,
321 schema_name: schemaName,
322 },
323 ])
324
325 let updateSQL = normalizeMigrationSQL(
326 await generator.getUpdateSchemaSQL({
327 fromSchema: dbSchema,
328 })
329 )
330
331 updateSQL = this.pickTableRelatedCommands(tableName, updateSQL)
332
333 /**
334 * Entity is upto-date and hence we do not have to perform
335 * any updates on it.
336 */
337 if (!updateSQL.length) {
338 return {
339 action: "noop",
340 linkDescriptor,
341 tableName,
342 }
343 }
344
345 const usesUnsafeCommands = this.#unsafeSQLCommands.some((fragment) => {
346 return updateSQL.match(new RegExp(`${fragment}`, "ig"))
347 })
348
349 return {
350 action: usesUnsafeCommands ? "notify" : "update",
351 linkDescriptor,
352 tableName,
353 sql: updateSQL,
354 }
355 } finally {
356 await orm.close(true)
357 }
358 }
359
360 /**
361 * This method loops over the tables we have fetched from the
362 * "link_module_migrations" tables and checks if their new
363 * name is different from the tracked name and in that
364 * case it will rename the actual table and also the
365 * tracked entry.
366 */
367 protected async migrateOldTables(
368 orm: MikroORM<PostgreSqlDriver>,
369 trackedTables: {
370 table_name: string
371 link_descriptor: PlannerActionLinkDescriptor
372 }[]
373 ) {
374 const migratedTables: {
375 table_name: string
376 link_descriptor: PlannerActionLinkDescriptor
377 }[] = []
378
379 for (let trackedTable of trackedTables) {
380 const linkEntity = this.#linksEntities.find((entity) => {
381 return (
382 entity.linkDescriptor.fromModel ===
383 trackedTable.link_descriptor.fromModel &&
384 entity.linkDescriptor.toModel ===
385 trackedTable.link_descriptor.toModel &&
386 entity.linkDescriptor.fromModule.toLowerCase() ===
387 trackedTable.link_descriptor.fromModule.toLowerCase() &&
388 entity.linkDescriptor.toModule.toLowerCase() ===
389 trackedTable.link_descriptor.toModule.toLowerCase()
390 )
391 })
392 const newTableName = linkEntity?.entity.meta.collection
393
394 /**
395 * Perform rename
396 */
397 if (newTableName && trackedTable.table_name !== newTableName) {
398 await this.renameOldTable(
399 orm,
400 trackedTable.table_name,
401 newTableName,
402 linkEntity.linkDescriptor
403 )
404 migratedTables.push({
405 ...trackedTable,
406 table_name: newTableName,
407 })
408 } else {
409 migratedTables.push({
410 ...trackedTable,
411 })
412 }
413 }
414
415 return migratedTables
416 }
417
418 /**
419 * Renames existing table and also its tracked entry
420 */
421 protected async renameOldTable(
422 orm: MikroORM<PostgreSqlDriver>,
423 oldName: string,
424 newName: string,
425 descriptor: PlannerActionLinkDescriptor
426 ) {
427 await orm.em.getDriver().getConnection().execute(`
428 ALTER TABLE "${this.#schema}"."${oldName}" RENAME TO "${newName}";
429 UPDATE "${this.#schema}"."${
430 this.tableName
431 }" SET table_name = '${newName}', link_descriptor = '${JSON.stringify(
432 descriptor
433 )}' WHERE table_name = '${oldName}';
434 `)
435 }
436
437 /**
438 * Creates a plan to executed in order to keep the database state in
439 * sync with the user-defined links.
440 *
441 * This method only creates a plan and does not change the database
442 * state. You must call the "executePlan" method for that.
443 */
444 async createPlan() {
445 const orm = await this.createORM()
446
447 try {
448 await this.ensureMigrationsTable(orm)
449
450 const executionActions: LinkMigrationsPlannerAction[] = []
451
452 await this.ensureMigrationsTableUpToDate(orm)
453
454 const trackedTables = await this.migrateOldTables(
455 orm,
456 await this.getTrackedLinksTables(orm)
457 )
458 const trackedTablesNames = trackedTables.map(
459 ({ table_name }) => table_name
460 )
461
462 /**
463 * Looping through the new set of entities and generating
464 * execution plan for them
465 */
466 for (let { entity, linkDescriptor } of this.#linksEntities) {
467 executionActions.push(
468 await this.getEntityMigrationPlan(
469 linkDescriptor,
470 entity,
471 trackedTablesNames
472 )
473 )
474 }
475
476 const linksTableNames = this.#linksEntities.map(
477 ({ entity }) => entity.meta.collection
478 )
479
480 /**
481 * Finding the tables to be removed
482 */
483 const tablesToRemove = arrayDifference(
484 trackedTablesNames,
485 linksTableNames
486 )
487 tablesToRemove.forEach((tableToRemove) => {
488 executionActions.push({
489 action: "delete",
490 tableName: tableToRemove,
491 linkDescriptor: trackedTables.find(
492 ({ table_name }) => tableToRemove === table_name
493 )!.link_descriptor,
494 })
495 })
496
497 return executionActions
498 } finally {
499 await orm.close(true)
500 }
501 }
502
503 /**
504 * Executes the actionsPlan actions where the action is one of 'create' | 'update' | 'delete'.
505 * 'noop' and 'notify' actions are implicitly ignored. If a notify action needs to be
506 * executed, you can mutate its action to 'update', in that scenario it means that an unsafe
507 * update sql (from our point of view) will be executed and some data could be lost.
508 *
509 * @param actionPlan
510 */
511 async executePlan(actionPlan: LinkMigrationsPlannerAction[]): Promise<void> {
512 const orm = await this.createORM()
513
514 // Separate single-connection ORM used exclusively to hold advisory locks.
515 const lockOrm = await DALUtils.mikroOrmCreateConnection(
516 { ...this.#dbConfig, pool: { min: 1, max: 1 } },
517 [],
518 ""
519 )
520 const lockConn = lockOrm.em.getDriver().getConnection()
521
522 try {
523 const concurrency = parseInt(process.env.DB_MIGRATION_CONCURRENCY ?? "1")
524 await executeWithConcurrency(
525 actionPlan.map((action) => {
526 return async () => {
527 const lockKey = `db-link-migration:${action.tableName}`
528
529 await lockConn.execute("BEGIN")
530 await lockConn.execute(
531 `SELECT pg_advisory_xact_lock(hashtext('${lockKey}'))`
532 )
533
534 try {
535 switch (action.action) {
536 case "delete":
537 await this.dropLinkTable(orm, action.tableName)
538 break
539 case "create":
540 await this.createLinkTable(orm, action)
541 break
542 case "update":
543 const sql = `SET LOCAL search_path TO "${
544 this.#schema
545 }"; \n\n${action.sql}`
546 await orm.em.getDriver().getConnection().execute(sql)
547 break
548 default:
549 break
550 }
551 } finally {
552 await lockConn.execute("COMMIT")
553 }
554 }
555 }),
556 concurrency
557 )
558 } finally {
559 await orm.close(true)
560 await lockOrm.close(true)
561 }
562 }
563 }