fix(): Proper schema usage when running migrations (#14036)

* fix(): Proper schema usage when running migrations

* Create thick-pugs-dance.md
This commit is contained in:
Adrien de Peretti
2025-11-12 15:56:50 +01:00
committed by GitHub
parent da4c0110ba
commit e59cdae336
3 changed files with 57 additions and 13 deletions
+6
View File
@@ -0,0 +1,6 @@
---
"@medusajs/link-modules": patch
"@medusajs/utils": patch
---
fix(): Proper schema usage when running migrations
@@ -32,7 +32,25 @@ export class CustomDBMigrator extends BaseMigrator {
const MigrationClass = Object.values( const MigrationClass = Object.values(
migration migration
)[0] as Constructor<Migration> )[0] as Constructor<Migration>
const instance = new MigrationClass($this.driver, $this.config) const instance = new MigrationClass(
$this.driver,
$this.config
) as Migration
const customSchema = $this.config.options.schema
if (customSchema) {
const up = instance.up
const down = instance.down
instance.up = async function (...args) {
this.driver.execute(`SET LOCAL search_path TO ${customSchema}`)
return up.bind(this)(...args)
}
instance.down = async function (...args) {
this.driver.execute(`SET LOCAL search_path TO ${customSchema}`)
return down.bind(this)(...args)
}
}
await $this.runner.run(instance, method) await $this.runner.run(instance, method)
} }
@@ -31,6 +31,8 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
*/ */
#dbConfig: ReturnType<typeof ModulesSdkUtils.loadDatabaseConfig> #dbConfig: ReturnType<typeof ModulesSdkUtils.loadDatabaseConfig>
#schema: string = "public"
/** /**
* The set of commands that are unsafe to execute automatically when * The set of commands that are unsafe to execute automatically when
* performing "alter table" * performing "alter table"
@@ -56,6 +58,7 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
options?: ModuleServiceInitializeOptions options?: ModuleServiceInitializeOptions
) { ) {
this.#dbConfig = ModulesSdkUtils.loadDatabaseConfig("link_modules", options) this.#dbConfig = ModulesSdkUtils.loadDatabaseConfig("link_modules", options)
this.#schema = options?.database?.schema ?? "public"
this.#linksEntities = joinerConfig this.#linksEntities = joinerConfig
.map((config) => { .map((config) => {
if (config.isReadOnlyLink) { if (config.isReadOnlyLink) {
@@ -96,7 +99,7 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
orm: MikroORM<PostgreSqlDriver> orm: MikroORM<PostgreSqlDriver>
): Promise<void> { ): Promise<void> {
await orm.em.getDriver().getConnection().execute(` await orm.em.getDriver().getConnection().execute(`
CREATE TABLE IF NOT EXISTS "${this.tableName}" ( CREATE TABLE IF NOT EXISTS "${this.#schema}"."${this.tableName}" (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
table_name VARCHAR(255) NOT NULL UNIQUE, table_name VARCHAR(255) NOT NULL UNIQUE,
link_descriptor JSONB NOT NULL DEFAULT '{}'::jsonb, link_descriptor JSONB NOT NULL DEFAULT '{}'::jsonb,
@@ -125,7 +128,8 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
>( >(
` `
SELECT table_name SELECT table_name
FROM information_schema.tables; FROM information_schema.tables
WHERE table_schema = '${this.#schema}';
` `
) )
) )
@@ -155,7 +159,9 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
.getConnection() .getConnection()
.execute( .execute(
` `
INSERT INTO ${this.tableName} (table_name, link_descriptor) VALUES ${positionalArgs} ON CONFLICT DO NOTHING; INSERT INTO "${this.#schema}"."${
this.tableName
}" (table_name, link_descriptor) VALUES ${positionalArgs} ON CONFLICT DO NOTHING;
`, `,
existingTables.flatMap((tableName, index) => [ existingTables.flatMap((tableName, index) => [
tableName, tableName,
@@ -185,7 +191,12 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
.getConnection() .getConnection()
.execute( .execute(
` `
INSERT INTO "${this.tableName}" (table_name, link_descriptor) VALUES (?, ?); SET LOCAL search_path TO "${this.#schema}";
INSERT INTO "${
this.tableName
}" (table_name, link_descriptor) VALUES (?, ?);
${sql} ${sql}
`, `,
[tableName, linkDescriptor] [tableName, linkDescriptor]
@@ -201,8 +212,10 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
tableName: string tableName: string
) { ) {
await orm.em.getDriver().getConnection().execute(` await orm.em.getDriver().getConnection().execute(`
DROP TABLE IF EXISTS "${tableName}"; DROP TABLE IF EXISTS "${this.#schema}"."${tableName}";
DELETE FROM "${this.tableName}" WHERE table_name = '${tableName}'; DELETE FROM "${this.#schema}"."${
this.tableName
}" WHERE table_name = '${tableName}';
`) `)
} }
@@ -227,7 +240,9 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
link_descriptor: PlannerActionLinkDescriptor link_descriptor: PlannerActionLinkDescriptor
}[] }[]
>(` >(`
SELECT table_name, link_descriptor from "${this.tableName}" SELECT table_name, link_descriptor from "${this.#schema}"."${
this.tableName
}"
`) `)
return results.map((tuple) => ({ return results.map((tuple) => ({
@@ -410,10 +425,12 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
descriptor: PlannerActionLinkDescriptor descriptor: PlannerActionLinkDescriptor
) { ) {
await orm.em.getDriver().getConnection().execute(` await orm.em.getDriver().getConnection().execute(`
ALTER TABLE "${oldName}" RENAME TO "${newName}"; ALTER TABLE "${this.#schema}"."${oldName}" RENAME TO "${
UPDATE "${ this.#schema
this.tableName }"."${newName}";
}" SET table_name = '${newName}', link_descriptor = '${JSON.stringify( UPDATE "${this.#schema}"."${
this.tableName
}" SET table_name = '${newName}', link_descriptor = '${JSON.stringify(
descriptor descriptor
)}' WHERE table_name = '${oldName}'; )}' WHERE table_name = '${oldName}';
`) `)
@@ -504,7 +521,10 @@ export class MigrationsExecutionPlanner implements ILinkMigrationsPlanner {
case "create": case "create":
return await this.createLinkTable(orm, action) return await this.createLinkTable(orm, action)
case "update": case "update":
return await orm.em.getDriver().getConnection().execute(action.sql) const sql = `SET LOCAL search_path TO "${this.#schema}"; \n\n${
action.sql
}`
return await orm.em.getDriver().getConnection().execute(sql)
default: default:
return return
} }