|
1
|
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types" |
|
2
|
import { setTimeout } from "timers/promises" |
|
3
|
import { mikroOrmCreateConnection } from "../../dal" |
|
4
|
import { loadDatabaseConfig } from "../load-module-database-config" |
|
5
|
import { Migrations } from "../../migrations" |
|
6
|
import { toMikroOrmEntities } from "../../dml" |
|
7
|
import { kebabCase } from "../../common/to-kebab-case" |
|
8
|
|
|
9
|
const TERMINAL_SIZE = process.stdout.columns |
|
10
|
|
|
11
|
/** |
|
12
|
* Utility function to build a migration generation script that will generate the migrations. |
|
13
|
* Only used in mikro orm based modules. |
|
14
|
* @param moduleName |
|
15
|
* @param models |
|
16
|
* @param pathToMigrations |
|
17
|
*/ |
|
18
|
export function buildGenerateMigrationScript({ |
|
19
|
moduleName, |
|
20
|
models, |
|
21
|
pathToMigrations, |
|
22
|
}) { |
|
23
|
/** |
|
24
|
* This script is only valid for mikro orm managers. If a user provide a custom manager |
|
25
|
* he is in charge of running the migrations. |
|
26
|
* @param options |
|
27
|
* @param logger |
|
28
|
* @param moduleDeclaration |
|
29
|
*/ |
|
30
|
return async function ( |
|
31
|
{ options, logger } = {} as Pick< |
|
32
|
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>, |
|
33
|
"options" | "logger" |
|
34
|
> |
|
35
|
) { |
|
36
|
logger ??= console as unknown as Logger |
|
37
|
|
|
38
|
logger.info(new Array(TERMINAL_SIZE).join("-")) |
|
39
|
logger.info("") |
|
40
|
logger.info(`MODULE: ${moduleName}`) |
|
41
|
|
|
42
|
const dbData = loadDatabaseConfig(moduleName, options)! |
|
43
|
|
|
44
|
const normalizedModels = toMikroOrmEntities(models) |
|
45
|
const orm = await mikroOrmCreateConnection( |
|
46
|
{ |
|
47
|
...dbData, |
|
48
|
snapshotName: `.snapshot-${kebabCase( |
|
49
|
moduleName.replace("Service", "") |
|
50
|
)}`, |
|
51
|
}, |
|
52
|
normalizedModels, |
|
53
|
pathToMigrations |
|
54
|
) |
|
55
|
|
|
56
|
const migrations = new Migrations(orm) |
|
57
|
|
|
58
|
try { |
|
59
|
const { fileName } = await migrations.generate() |
|
60
|
if (fileName) { |
|
61
|
logger.info(`Generated successfully (${fileName}).`) |
|
62
|
|
|
63
|
// Add a 1-second delay after creating a migration file to ensure unique |
|
64
|
// timestamps across modules. MikroORM uses second-precision timestamps |
|
65
|
// (YYYYMMDDHHmmss format), so without this delay, multiple modules |
|
66
|
// processed within the same second would get identical migration filenames. |
|
67
|
// The delay is only added when a migration is actually created, not when |
|
68
|
// skipped due to no schema changes. |
|
69
|
// See: https://github.com/medusajs/medusa/issues/14410 |
|
70
|
await setTimeout(1000) |
|
71
|
} else { |
|
72
|
logger.info(`Skipped. No changes detected in your models.`) |
|
73
|
} |
|
74
|
} catch (error) { |
|
75
|
logger.error(`Failed with error ${error.message}`, error) |
|
76
|
} |
|
77
|
} |
|
78
|
} |