feat: move migrations commands to the new db namespace (#8810)

This commit is contained in:
Harminder Virk
2024-08-27 16:40:00 +05:30
committed by GitHub
parent 6470168526
commit 2a5ee970e6
6 changed files with 334 additions and 79 deletions
+58
View File
@@ -142,6 +142,64 @@ function buildLocalCommands(cli, isLocalProject) {
}) })
), ),
}) })
.command({
command: "db:migrate",
desc: "Migrate the database by executing pending migrations",
builder: (builder) => {
builder.option("skip-links", {
type: "boolean",
describe: "Do not sync links",
})
builder.option("execute-all-links", {
type: "boolean",
describe:
"Skip prompts and execute all (including unsafe) actions from sync links",
})
builder.option("execute-safe-links", {
type: "boolean",
describe:
"Skip prompts and execute only safe actions from sync links",
})
},
handler: handlerP(
getCommandHandler("db/migrate", (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
return cmd(args)
})
),
})
.command({
command: "db:rollback [modules...]",
desc: "Rollback last batch of executed migrations for a given module",
builder: {
modules: {
description: "Modules for which to rollback migrations",
demand: true,
},
},
handler: handlerP(
getCommandHandler("db/rollback", (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
return cmd(args)
})
),
})
.command({
command: "db:generate [modules...]",
desc: "Generate migrations for a given module",
builder: {
modules: {
description: "Modules for which to generate migration files",
demand: true,
},
},
handler: handlerP(
getCommandHandler("db/generate", (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
return cmd(args)
})
),
})
.command({ .command({
command: "db:sync-links", command: "db:sync-links",
desc: "Sync database schema with the links defined by your application and Medusa core", desc: "Sync database schema with the links defined by your application and Medusa core",
@@ -0,0 +1,59 @@
import { join } from "path"
import { ContainerRegistrationKeys, MedusaError } from "@medusajs/utils"
import { LinkLoader, logger, MedusaAppLoader } from "@medusajs/framework"
import { ensureDbExists } from "../utils"
import { initializeContainer } from "../../loaders"
import { getResolvedPlugins } from "../../loaders/helpers/resolve-plugins"
const TERMINAL_SIZE = process.stdout.columns
const main = async function ({ directory, modules }) {
try {
/**
* Setup
*/
const container = await initializeContainer(directory)
await ensureDbExists(container)
const medusaAppLoader = new MedusaAppLoader()
const configModule = container.resolve(
ContainerRegistrationKeys.CONFIG_MODULE
)
const plugins = getResolvedPlugins(directory, configModule, true) || []
const linksSourcePaths = plugins.map((plugin) =>
join(plugin.resolve, "links")
)
await new LinkLoader(linksSourcePaths).load()
/**
* Generating migrations
*/
logger.info("Generating migrations...")
await medusaAppLoader.runModulesMigrations({
moduleNames: modules,
action: "generate",
})
console.log(new Array(TERMINAL_SIZE).join("-"))
logger.info("Migrations generated")
process.exit()
} catch (error) {
console.log(new Array(TERMINAL_SIZE).join("-"))
if (error.code && error.code === MedusaError.Codes.UNKNOWN_MODULES) {
logger.error(error.message)
const modulesList = error.allModules.map(
(name: string) => ` - ${name}`
)
logger.error(`Available modules:\n${modulesList.join("\n")}`)
} else {
logger.error(error.message, error)
}
process.exit(1)
}
}
export default main
@@ -0,0 +1,64 @@
import { join } from "path"
import { ContainerRegistrationKeys } from "@medusajs/utils"
import { LinkLoader, logger, MedusaAppLoader } from "@medusajs/framework"
import { syncLinks } from "./sync-links"
import { ensureDbExists } from "../utils"
import { initializeContainer } from "../../loaders"
import { getResolvedPlugins } from "../../loaders/helpers/resolve-plugins"
const TERMINAL_SIZE = process.stdout.columns
const main = async function ({
directory,
skipLinks,
executeAllLinks,
executeSafeLinks,
}) {
try {
/**
* Setup
*/
const container = await initializeContainer(directory)
await ensureDbExists(container)
const medusaAppLoader = new MedusaAppLoader()
const configModule = container.resolve(
ContainerRegistrationKeys.CONFIG_MODULE
)
const plugins = getResolvedPlugins(directory, configModule, true) || []
const linksSourcePaths = plugins.map((plugin) =>
join(plugin.resolve, "links")
)
await new LinkLoader(linksSourcePaths).load()
/**
* Run migrations
*/
logger.info("Running migrations...")
await medusaAppLoader.runModulesMigrations({
action: "run",
})
console.log(new Array(TERMINAL_SIZE).join("-"))
logger.info("Migrations completed")
/**
* Sync links
*/
if (!skipLinks) {
console.log(new Array(TERMINAL_SIZE).join("-"))
await syncLinks(medusaAppLoader, {
executeAll: executeAllLinks,
executeSafe: executeSafeLinks,
})
}
process.exit()
} catch (error) {
logger.error(error)
process.exit(1)
}
}
export default main
@@ -0,0 +1,57 @@
import { join } from "path"
import { ContainerRegistrationKeys, MedusaError } from "@medusajs/utils"
import { LinkLoader, logger, MedusaAppLoader } from "@medusajs/framework"
import { ensureDbExists } from "../utils"
import { initializeContainer } from "../../loaders"
import { getResolvedPlugins } from "../../loaders/helpers/resolve-plugins"
const TERMINAL_SIZE = process.stdout.columns
const main = async function ({ directory, modules }) {
try {
/**
* Setup
*/
const container = await initializeContainer(directory)
await ensureDbExists(container)
const medusaAppLoader = new MedusaAppLoader()
const configModule = container.resolve(
ContainerRegistrationKeys.CONFIG_MODULE
)
const plugins = getResolvedPlugins(directory, configModule, true) || []
const linksSourcePaths = plugins.map((plugin) =>
join(plugin.resolve, "links")
)
await new LinkLoader(linksSourcePaths).load()
/**
* Reverting migrations
*/
logger.info("Reverting migrations...")
await medusaAppLoader.runModulesMigrations({
moduleNames: modules,
action: "revert",
})
console.log(new Array(TERMINAL_SIZE).join("-"))
logger.info("Migrations reverted")
process.exit()
} catch (error) {
console.log(new Array(TERMINAL_SIZE).join("-"))
if (error.code && error.code === MedusaError.Codes.UNKNOWN_MODULES) {
logger.error(error.message)
const modulesList = error.allModules.map(
(name: string) => ` - ${name}`
)
logger.error(`Available modules:\n${modulesList.join("\n")}`)
} else {
logger.error(error.message, error)
}
process.exit(1)
}
}
export default main
+34 -17
View File
@@ -81,23 +81,20 @@ async function askForLinkActionsToPerform(
}) })
} }
const main = async function ({ directory, executeSafe, executeAll }) { /**
try { * Low-level utility to sync links. This utility is used
const container = await initializeContainer(directory) * by the migrate command as-well.
await ensureDbExists(container) */
export async function syncLinks(
const configModule = container.resolve( medusaAppLoader: MedusaAppLoader,
ContainerRegistrationKeys.CONFIG_MODULE {
) executeAll,
executeSafe,
const medusaAppLoader = new MedusaAppLoader() }: {
executeSafe: boolean
const plugins = getResolvedPlugins(directory, configModule, true) || [] executeAll: boolean
const linksSourcePaths = plugins.map((plugin) => }
join(plugin.resolve, "links") ) {
)
await new LinkLoader(linksSourcePaths).load()
const planner = await medusaAppLoader.getLinksExecutionPlanner() const planner = await medusaAppLoader.getLinksExecutionPlanner()
logger.info("Syncing links...") logger.info("Syncing links...")
@@ -175,6 +172,26 @@ const main = async function ({ directory, executeSafe, executeAll }) {
} else { } else {
logger.info("Database already up-to-date") logger.info("Database already up-to-date")
} }
}
const main = async function ({ directory, executeSafe, executeAll }) {
try {
const container = await initializeContainer(directory)
await ensureDbExists(container)
const configModule = container.resolve(
ContainerRegistrationKeys.CONFIG_MODULE
)
const medusaAppLoader = new MedusaAppLoader()
const plugins = getResolvedPlugins(directory, configModule, true) || []
const linksSourcePaths = plugins.map((plugin) =>
join(plugin.resolve, "links")
)
await new LinkLoader(linksSourcePaths).load()
await syncLinks(medusaAppLoader, { executeAll, executeSafe })
process.exit() process.exit()
} catch (e) { } catch (e) {
logger.error(e) logger.error(e)
+2 -2
View File
@@ -1,10 +1,10 @@
import syncLinks from "./db/sync-links" import syncLinksCmd from "./db/sync-links"
const main = async function (argv) { const main = async function (argv) {
if (argv.action !== "sync") { if (argv.action !== "sync") {
return process.exit() return process.exit()
} }
await syncLinks(argv) await syncLinksCmd(argv)
} }
export default main export default main