Feat: Improvements to the migrations CLI and workflow (#8060)

This commit is contained in:
Harminder Virk
2024-07-11 16:52:34 +05:30
committed by GitHub
parent bb0303cd6a
commit 45c573b03a
10 changed files with 257 additions and 144 deletions
+2
View File
@@ -13,6 +13,7 @@ export const MedusaErrorTypes = {
NOT_ALLOWED: "not_allowed",
UNEXPECTED_STATE: "unexpected_state",
CONFLICT: "conflict",
UNKNOWN_MODULES: "unknown_modules",
PAYMENT_AUTHORIZATION_ERROR: "payment_authorization_error",
PAYMENT_REQUIRES_MORE_ERROR: "payment_requires_more_error",
}
@@ -20,6 +21,7 @@ export const MedusaErrorTypes = {
export const MedusaErrorCodes = {
INSUFFICIENT_INVENTORY: "insufficient_inventory",
CART_INCOMPATIBLE_STATE: "cart_incompatible_state",
UNKNOWN_MODULES: "unknown_modules",
}
/**
+12 -5
View File
@@ -5,6 +5,7 @@ import {
UmzugMigration,
} from "@mikro-orm/migrations"
import { MikroORM, MikroORMOptions } from "@mikro-orm/core"
import { PostgreSqlDriver } from "@mikro-orm/postgresql"
/**
* Events emitted by the migrations class
@@ -20,11 +21,13 @@ export type MigrationsEvents = {
* Exposes the API to programmatically manage Mikro ORM migrations
*/
export class Migrations extends EventEmitter<MigrationsEvents> {
#config: Partial<MikroORMOptions>
#configOrConnection: Partial<MikroORMOptions> | MikroORM<PostgreSqlDriver>
constructor(config: Partial<MikroORMOptions>) {
constructor(
configOrConnection: Partial<MikroORMOptions> | MikroORM<PostgreSqlDriver>
) {
super()
this.#config = config
this.#configOrConnection = configOrConnection
}
/**
@@ -32,10 +35,14 @@ export class Migrations extends EventEmitter<MigrationsEvents> {
* one
*/
async #getConnection() {
if ("connect" in this.#configOrConnection) {
return this.#configOrConnection as MikroORM<PostgreSqlDriver>
}
return await MikroORM.init({
...this.#config,
...this.#configOrConnection,
migrations: {
...this.#config.migrations,
...this.#configOrConnection.migrations,
silent: true,
},
})
@@ -1,23 +1,17 @@
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { EntitySchema } from "@mikro-orm/core"
import { upperCaseFirst } from "../../common"
import { mikroOrmCreateConnection } from "../../dal"
import { DmlEntity, toMikroORMEntity } from "../../dml"
import { loadDatabaseConfig } from "../load-module-database-config"
import { Migrations } from "../../migrations"
const TERMINAL_SIZE = process.stdout.columns
/**
* Utility function to build a migration script that will revert the migrations.
* Only used in mikro orm based modules.
* @param moduleName
* @param models
* @param pathToMigrations
*/
export function buildRevertMigrationScript({
moduleName,
models,
pathToMigrations,
}) {
export function buildRevertMigrationScript({ moduleName, pathToMigrations }) {
/**
* This script is only valid for mikro orm managers. If a user provide a custom manager
* he is in charge of reverting the migrations.
@@ -34,34 +28,30 @@ export function buildRevertMigrationScript({
> = {}) {
logger ??= console as unknown as Logger
console.log(new Array(TERMINAL_SIZE).join("-"))
console.log("")
logger.info(`MODULE: ${moduleName}`)
const dbData = loadDatabaseConfig(moduleName, options)!
const entities = Object.values(models).map((model) => {
if (DmlEntity.isDmlEntity(model)) {
return toMikroORMEntity(model)
}
const orm = await mikroOrmCreateConnection(dbData, [], pathToMigrations)
const migrations = new Migrations(orm)
return model
}) as unknown as EntitySchema[]
const orm = await mikroOrmCreateConnection(
dbData,
entities,
pathToMigrations
)
migrations.on("reverting", (migration) => {
logger.info(` ● Reverting ${migration.name}`)
})
migrations.on("reverted", (migration) => {
logger.info(` ✔ Reverted ${migration.name}`)
})
try {
const migrator = orm.getMigrator()
await migrator.down()
logger?.info(`${upperCaseFirst(moduleName)} module migration executed`)
const result = await migrations.revert()
if (result.length) {
logger.info("Reverted successfully")
} else {
logger.info("Skipped. Nothing to revert")
}
} catch (error) {
logger?.error(
`${upperCaseFirst(
moduleName
)} module migration failed to run - Error: ${error.errros ?? error}`
)
logger.error(`Failed with error ${error.message}`, error)
}
await orm.close()
}
}
@@ -1,18 +1,17 @@
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { EntitySchema } from "@mikro-orm/core"
import { upperCaseFirst } from "../../common"
import { mikroOrmCreateConnection } from "../../dal"
import { DmlEntity, toMikroORMEntity } from "../../dml"
import { loadDatabaseConfig } from "../load-module-database-config"
import { Migrations } from "../../migrations"
const TERMINAL_SIZE = process.stdout.columns
/**
* Utility function to build a migration script that will run the migrations.
* Only used in mikro orm based modules.
* @param moduleName
* @param models
* @param pathToMigrations
*/
export function buildMigrationScript({ moduleName, models, pathToMigrations }) {
export function buildMigrationScript({ moduleName, pathToMigrations }) {
/**
* This script is only valid for mikro orm managers. If a user provide a custom manager
* he is in charge of running the migrations.
@@ -29,48 +28,30 @@ export function buildMigrationScript({ moduleName, models, pathToMigrations }) {
> = {}) {
logger ??= console as unknown as Logger
console.log(new Array(TERMINAL_SIZE).join("-"))
console.log("")
logger.info(`MODULE: ${moduleName}`)
const dbData = loadDatabaseConfig(moduleName, options)!
const entities = Object.values(models).map((model) => {
if (DmlEntity.isDmlEntity(model)) {
return toMikroORMEntity(model)
}
const orm = await mikroOrmCreateConnection(dbData, [], pathToMigrations)
const migrations = new Migrations(orm)
return model
}) as unknown as EntitySchema[]
const orm = await mikroOrmCreateConnection(
dbData,
entities,
pathToMigrations
)
migrations.on("migrating", (migration) => {
logger.info(` ● Migrating ${migration.name}`)
})
migrations.on("migrated", (migration) => {
logger.info(` ✔ Migrated ${migration.name}`)
})
try {
const migrator = orm.getMigrator()
const pendingMigrations = await migrator.getPendingMigrations()
if (pendingMigrations.length) {
logger.info(
`Pending migrations: ${JSON.stringify(pendingMigrations, null, 2)}`
)
await migrator.up({
migrations: pendingMigrations.map((m) => m.name),
})
logger.info(
`${upperCaseFirst(moduleName)} module: ${
pendingMigrations.length
} migration files executed`
)
const result = await migrations.run()
if (result.length) {
logger.info("Completed successfully")
} else {
logger.info("Skipped. Database is upto-date")
}
} catch (error) {
logger.error(
`${upperCaseFirst(
moduleName
)} module migration failed to run - Error: ${error.errros ?? error}`
)
logger.error(`Failed with error ${error.message}`, error)
}
await orm.close()
}
}