1 import { logger } from "@medusajs/framework/logger"
2 import { CustomDBMigrator } from "@medusajs/framework/utils"
3
4 import {
5 defineConfig,
6 MikroORM,
7 Options,
8 SqlEntityManager,
9 } from "@medusajs/framework/mikro-orm/postgresql"
10 import {
11 createDatabase,
12 createPostgresDatabaseTemplate,
13 dropDatabase,
14 dropPostgresDatabaseTemplate,
15 execOrTimeout,
16 formatError,
17 restorePostgresDatabaseFromTemplate,
18 } from "./medusa-test-runner-utils"
19 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
20
21 const DB_HOST = process.env.DB_HOST ?? "localhost"
22 const DB_USERNAME = process.env.DB_USERNAME ?? ""
23 const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
24 const DB_PORT = process.env.DB_PORT ?? "5432"
25
26 const databaseCredentials = {
27 user: DB_USERNAME,
28 password: DB_PASSWORD,
29 host: DB_HOST,
30 port: parseInt(DB_PORT),
31 }
32
33 export function getDatabaseURL(dbName?: string): string {
34 const DB_HOST = process.env.DB_HOST ?? "localhost"
35 const DB_USERNAME = process.env.DB_USERNAME ?? "postgres"
36 const DB_PASSWORD = process.env.DB_PASSWORD ?? ""
37 const DB_PORT = process.env.DB_PORT ?? "5432"
38 const DB_NAME = dbName ?? process.env.DB_TEMP_NAME
39
40 return `postgres://${encodeURIComponent(DB_USERNAME)}${
41 DB_PASSWORD ? `:${encodeURIComponent(DB_PASSWORD)}` : ""
42 }@${DB_HOST}:${DB_PORT}/${DB_NAME}`
43 }
44
45 export function getMikroOrmConfig({
46 mikroOrmEntities,
47 pathToMigrations,
48 clientUrl,
49 schema,
50 }: {
51 mikroOrmEntities: any[]
52 pathToMigrations?: string
53 clientUrl?: string
54 schema?: string
55 }): Options {
56 const DB_URL = clientUrl ?? getDatabaseURL()
57
58 return defineConfig({
59 clientUrl: DB_URL,
60 entities: Object.values(mikroOrmEntities),
61 schema: schema ?? process.env.MEDUSA_DB_SCHEMA,
62 debug: false,
63 pool: {
64 min: 2,
65 },
66 migrations: {
67 path: pathToMigrations,
68 pathTs: pathToMigrations,
69 silent: true,
70 // Snapshots only matter when generating migrations, and writing them
71 // leaves stray `.snapshot-<test db>.json` files in the source tree.
72 snapshot: false,
73 },
74 extensions: [CustomDBMigrator],
75 })
76 }
77
78 export interface TestDatabase {
79 mikroOrmEntities: any[]
80 pathToMigrations?: string | string[]
81 schema?: string
82 clientUrl?: string
83
84 orm: MikroORM | null
85 manager: SqlEntityManager | null
86
87 setupDatabase(): Promise<void>
88 clearDatabase(): Promise<void>
89 getManager(): SqlEntityManager
90 forkManager(): SqlEntityManager
91 getOrm(): MikroORM
92 }
93
94 /**
95 * Applies the migrations of a single directory. Used when a suite lists several
96 * migration sources (e.g. a module plus the provider under test), since a
97 * MikroORM instance only ever reads one migrations directory.
98 */
99 async function runMigrationsFromPath(
100 pathToMigrations: string,
101 clientUrl?: string,
102 schema?: string
103 ): Promise<void> {
104 const orm = await MikroORM.init({
105 ...getMikroOrmConfig({
106 mikroOrmEntities: [],
107 pathToMigrations,
108 clientUrl,
109 schema,
110 }),
111 discovery: { warnWhenNoEntities: false },
112 })
113
114 try {
115 await orm.getMigrator().up()
116 } finally {
117 await orm.close()
118 }
119 }
120
121 export function getMikroOrmWrapper({
122 mikroOrmEntities,
123 pathToMigrations,
124 clientUrl,
125 schema,
126 }: {
127 mikroOrmEntities: any[]
128 pathToMigrations?: string | string[]
129 clientUrl?: string
130 schema?: string
131 }): TestDatabase {
132 return {
133 mikroOrmEntities,
134 pathToMigrations,
135 clientUrl: clientUrl ?? getDatabaseURL(),
136 schema: schema ?? process.env.MEDUSA_DB_SCHEMA,
137
138 orm: null,
139 manager: null,
140
141 getManager() {
142 if (this.manager === null) {
143 throw new Error("manager entity not available")
144 }
145
146 return this.manager
147 },
148
149 forkManager() {
150 if (this.manager === null) {
151 throw new Error("manager entity not available")
152 }
153
154 return this.manager.fork()
155 },
156
157 getOrm() {
158 if (this.orm === null) {
159 throw new Error("orm entity not available")
160 }
161
162 return this.orm
163 },
164
165 async setupDatabase() {
166 const migrationPaths = Array.isArray(this.pathToMigrations)
167 ? this.pathToMigrations
168 : this.pathToMigrations
169 ? [this.pathToMigrations]
170 : []
171
172 const OrmConfig = getMikroOrmConfig({
173 mikroOrmEntities: this.mikroOrmEntities,
174 pathToMigrations: migrationPaths[0],
175 clientUrl: this.clientUrl,
176 schema: this.schema,
177 })
178
179 try {
180 this.orm = await MikroORM.init(OrmConfig)
181 this.manager = this.orm.em
182
183 try {
184 await this.orm.getSchemaGenerator().ensureDatabase()
185 } catch (err) {
186 logger.error("Error ensuring database:", err)
187 throw err
188 }
189
190 await this.manager?.execute(
191 `CREATE SCHEMA IF NOT EXISTS "${this.schema ?? "public"}";`
192 )
193
194 if (migrationPaths.length > 1) {
195 // Explicit sources own the schema, so the entity-derived schema is
196 // never generated on top of them.
197 for (const migrationPath of migrationPaths) {
198 await runMigrationsFromPath(
199 migrationPath,
200 this.clientUrl,
201 this.schema
202 )
203 }
204
205 return
206 }
207
208 const pendingMigrations = await this.orm
209 .getMigrator()
210 .getPendingMigrations()
211
212 if (pendingMigrations && pendingMigrations.length > 0) {
213 await this.orm
214 .getMigrator()
215 .up({ migrations: pendingMigrations.map((m) => m.name!) })
216 } else {
217 await this.orm.schema.refreshDatabase()
218 }
219 } catch (error) {
220 if (this.orm) {
221 try {
222 await this.orm.close()
223 } catch (closeError) {
224 logger.error("Error closing ORM:", closeError)
225 }
226 }
227 this.orm = null
228 this.manager = null
229 throw error
230 }
231 },
232
233 async clearDatabase() {
234 if (this.orm === null) {
235 throw new Error("ORM not configured")
236 }
237
238 try {
239 await this.manager?.execute(
240 `DROP SCHEMA IF EXISTS "${this.schema ?? "public"}" CASCADE;`
241 )
242
243 await this.manager?.execute(
244 `CREATE SCHEMA IF NOT EXISTS "${this.schema ?? "public"}";`
245 )
246
247 const closePromise = this.orm.close()
248
249 await execOrTimeout(closePromise)
250 } catch (error) {
251 logger.error("Error clearing database:", error)
252 try {
253 await this.orm?.close()
254 } catch (closeError) {
255 logger.error("Error during forced ORM close:", closeError)
256 }
257 throw error
258 } finally {
259 this.orm = null
260 this.manager = null
261 }
262 },
263 }
264 }
265
266 export const dbTestUtilFactory = (): any => ({
267 pgConnection_: null,
268
269 create: async function (dbName: string) {
270 try {
271 await createDatabase(
272 { databaseName: dbName, errorIfExist: false },
273 databaseCredentials
274 )
275 } catch (error) {
276 logger.error("Error creating database:", error)
277 throw error
278 }
279 },
280
281 snapshot: async function ({
282 databaseName,
283 templateName,
284 }: {
285 databaseName: string
286 templateName: string
287 }) {
288 try {
289 await createPostgresDatabaseTemplate({ databaseName, templateName })
290 } catch (error) {
291 logger.error(`Error creating database template:\n${formatError(error)}`)
292 throw error
293 }
294 },
295
296 restore: async function ({
297 databaseName,
298 templateName,
299 }: {
300 databaseName: string
301 templateName: string
302 }) {
303 try {
304 await restorePostgresDatabaseFromTemplate({ databaseName, templateName })
305 } catch (error) {
306 logger.error(
307 `Error restoring database from template:\n${formatError(error)}`
308 )
309 throw error
310 }
311 },
312
313 dropTemplate: async function (templateName: string) {
314 try {
315 await dropPostgresDatabaseTemplate(templateName)
316 } catch (error) {
317 logger.error(`Error dropping database template:\n${formatError(error)}`)
318 throw error
319 }
320 },
321
322 teardown: async function ({ schema }: { schema?: string } = {}) {
323 if (!this.pgConnection_) {
324 return
325 }
326
327 try {
328 const runRawQuery = this.pgConnection_.raw.bind(this.pgConnection_)
329 schema ??= "public"
330
331 const { rows: tableNames } = await runRawQuery(`SELECT table_name
332 FROM information_schema.tables
333 WHERE table_schema = '${schema}';`)
334
335 const skipIndexPartitionPrefix = "cat_"
336 const mainPartitionTables = ["index_data", "index_relation"]
337 let hasIndexTables = false
338
339 const tablesToTruncate: string[] = []
340 const allTablesToVerify: string[] = []
341
342 for (const { table_name } of tableNames) {
343 if (mainPartitionTables.includes(table_name)) {
344 hasIndexTables = true
345 }
346
347 if (
348 table_name.startsWith(skipIndexPartitionPrefix) ||
349 mainPartitionTables.includes(table_name)
350 ) {
351 allTablesToVerify.push(table_name)
352 continue
353 }
354
355 tablesToTruncate.push(`${schema}."${table_name}"`)
356 allTablesToVerify.push(table_name)
357 }
358
359 const allTablesToTruncase = [
360 ...tablesToTruncate,
361 ...(hasIndexTables ? mainPartitionTables : []),
362 ].join(", ")
363
364 if (allTablesToTruncase) {
365 await runRawQuery(`TRUNCATE ${allTablesToTruncase};`)
366 }
367
368 const verifyEmpty = async (maxRetries = 5) => {
369 for (let retry = 0; retry < maxRetries; retry++) {
370 const countQueries = allTablesToVerify.map(
371 (tableName) =>
372 `SELECT '${tableName}' as table_name, COUNT(*) as count FROM ${schema}."${tableName}"`
373 )
374
375 const { rows: counts } = await runRawQuery(
376 countQueries.join(" UNION ALL ")
377 )
378
379 const nonEmptyTables = counts.filter(
380 (row: { table_name: string; count: string }) =>
381 parseInt(row.count) > 0
382 )
383
384 if (nonEmptyTables.length === 0) {
385 return true
386 }
387
388 if (retry < maxRetries - 1) {
389 await new Promise((resolve) => setTimeout(resolve, 100))
390 } else {
391 const tableList = nonEmptyTables
392 .map(
393 (t: { table_name: string; count: string }) =>
394 `${t.table_name}(${t.count})`
395 )
396 .join(", ")
397 logger.warn(
398 `Some tables still contain data after truncate: ${tableList}`
399 )
400 }
401 }
402 return false
403 }
404
405 await verifyEmpty()
406 } catch (error) {
407 logger.error("Error during database teardown:", error)
408 throw error
409 }
410 },
411
412 shutdown: async function (dbName: string) {
413 try {
414 await closePgConnection(this.pgConnection_)
415 await unregisterFrameworkPgConnection(this.pgConnection_)
416
417 return await dropDatabase(
418 { databaseName: dbName, errorIfNonExist: false },
419 databaseCredentials
420 )
421 } catch (error) {
422 logger.error("Error during database shutdown:", error)
423 try {
424 await closePgConnection(this.pgConnection_)
425 await unregisterFrameworkPgConnection(this.pgConnection_)
426 } catch (cleanupError) {
427 logger.error("Error during forced cleanup:", cleanupError)
428 }
429 throw error
430 } finally {
431 this.pgConnection_ = null
432 }
433 },
434 })
435
436 async function closePgConnection(pgConnection: any) {
437 if (!pgConnection) {
438 return
439 }
440
441 const cleanupPromises: Promise<any>[] = []
442
443 if (pgConnection.context?.destroy) {
444 cleanupPromises.push(
445 execOrTimeout(pgConnection.context.destroy()).catch(() => void 0)
446 )
447 }
448
449 if (pgConnection.destroy) {
450 cleanupPromises.push(
451 execOrTimeout(pgConnection.destroy()).catch(() => void 0)
452 )
453 }
454
455 await Promise.all(cleanupPromises)
456 }
457
458 async function unregisterFrameworkPgConnection(pgConnection: any) {
459 if (!pgConnection) {
460 return
461 }
462
463 const { container } = await import("@medusajs/framework")
464
465 if (!container.hasRegistration(ContainerRegistrationKeys.PG_CONNECTION)) {
466 return
467 }
468
469 const registeredConnection = container.resolve(
470 ContainerRegistrationKeys.PG_CONNECTION
471 )
472
473 if (registeredConnection !== pgConnection) {
474 return
475 }
476
477 delete (container as { registrations?: Record<string, unknown> })
478 .registrations?.[ContainerRegistrationKeys.PG_CONNECTION]
479 }