chore(utils): patch unique index migration (#11136)

This commit is contained in:
Carlos R. L. Rodrigues
2025-01-24 13:48:37 -03:00
committed by GitHub
parent cdfde0dfac
commit a76208ed02
3 changed files with 42 additions and 1 deletions

View File

@@ -0,0 +1,5 @@
---
"@medusajs/utils": patch
---
chore(utils): patch unique index migration

View File

@@ -1,7 +1,7 @@
import { CustomTsMigrationGenerator } from "../mikro-orm-create-connection"
function unwrapSql(sql: string) {
return sql.toString().match(/this.addSql\(`(.*?)`\)/)?.[1]
return sql.toString().match(/this.addSql\(`([\s\S]*?)`\)/m)?.[1]
}
describe("CustomTsMigrationGenerator", () => {

View File

@@ -7,6 +7,42 @@ import { normalizeMigrationSQL } from "../utils"
type FilterDef = Parameters<typeof MikroORMFilter>[0]
export class CustomTsMigrationGenerator extends TSMigrationGenerator {
// TODO: temporary fix to drop unique constraint before creating unique index
private dropUniqueConstraintBeforeUniqueIndex(
sqlPatches: string[],
sql: string
) {
// DML unique index
const uniqueIndexName = sql.match(/"IDX_(.+?)_unique"/)?.[1]
if (!uniqueIndexName) {
return
}
// Add drop unique constraint if it exists, using the same name as index without IDX_ prefix
const tableName = sql.match(/ON "(.+?)"/)?.[1]
if (tableName) {
sqlPatches.push(
`alter table if exists "${tableName}" drop constraint if exists "${uniqueIndexName}_unique";`
)
}
}
generateMigrationFile(
className: string,
diff: { up: string[]; down: string[] }
): string {
const sqlPatches: string[] = []
for (const sql of diff.up) {
this.dropUniqueConstraintBeforeUniqueIndex(sqlPatches, sql)
}
for (const sql of sqlPatches) {
diff.up.unshift(sql)
}
return super.generateMigrationFile(className, diff)
}
createStatement(sql: string, padLeft: number): string {
if (isString(sql)) {
sql = normalizeMigrationSQL(sql)