migrate

package module
v1.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 29 Imported by: 0

README

Melody Bun ORM migration commands

This package exposes Bun migrations as Melody CLI commands (clicontract.Command in cli/contract/command.go).

It intentionally contains only:

  • command construction and flag wiring (see RegisterCommands)
  • Bun migrate execution per command

Your application is responsible for:

  • registering a *bunorm.ManagerRegistry service and choosing the default manager (see integrations/bunorm/manager_registry.go)
  • providing a *migrate.Migrations collection (your app-owned migrations package)
  • choosing the migrations directory layout

Install

In your application module:

go get github.com/precision-soft/melody/integrations/bunorm/migrate@latest

Usage

1) Define your migrations collection

Create a migrations package in your app and expose a *migrate.Migrations collection:

package main

import "github.com/uptrace/bun/migrate"

var Migrations = migrate.NewMigrations()
2) Register commands via a CliModule

Register the commands from a module that implements application/contract.CliModule:

package main

import (
    "your/module/database"
    "your/module/database/migrations"

    applicationcontract "github.com/precision-soft/melody/application/contract"
    clicontract "github.com/precision-soft/melody/cli/contract"
    bunormmigrate "github.com/precision-soft/melody/integrations/bunorm/migrate"
    kernelcontract "github.com/precision-soft/melody/kernel/contract"
)

func (instance *YourModule) RegisterCliCommands(kernelInstance kernelcontract.Kernel) []clicontract.Command {
    commands := make([]clicontract.Command, 0)

    commands = append(
        commands,
        bunormmigrate.RegisterCommands(
            migrations.Migrations,
            bunormmigrate.Options{
                CommandPrefix:            "db",
                ManagerFlagName:          "manager",
                ManagerRegistryServiceId: database.ServiceManagerRegistryId,
            },
        )...,
    )

    return commands
}

var _ applicationcontract.CliModule = (*YourModule)(nil)

Or bundle it as a self-registering application module, so a single RegisterModule call contributes the commands instead of hand-writing RegisterCliCommands:

app.RegisterModule(bunormmigrate.NewModule(bunormmigrate.ModuleConfig{
    Migrations: migrations.Migrations,
    Options:    bunormmigrate.Options{CommandPrefix: "db"},
}))

Multiple database contexts

A binary with several databases declares one context per database and registers the module once; each context gets its own command family pinned to its manager in the shared registry:

app.RegisterModule(bunormmigrate.NewModule(bunormmigrate.ModuleConfig{
    Contexts: []bunormmigrate.ContextConfig{
        {Name: "platform", Migrations: platformmigrations.Migrations},
        {Name: "payment", Migrations: paymentmigrations.Migrations},
    },
}))

This generates db:platform:init|migrate|rollback|status|unlock|create and the same family under db:payment:*. By convention a context's pinned manager name equals the context name (override with Options.ManagerName) and its prefix derives from the base prefix (db:<name>, override with Options.CommandPrefix); every context resolves against the one shared *bunorm.ManagerRegistry. The pin only replaces the registry-default fallback — an explicit --manager flag still wins. Contexts composes with the legacy single-set Migrations field, which keeps its unprefixed commands. For hand-wired setups, RegisterContextCommands(contexts, baseOptions) returns the same commands without the module wrapper.

If you deliberately keep separate registries per context, set each context's ManagerRegistryServiceId.

Options

RegisterCommands accepts an Options value.

  • CommandPrefix (default: db) controls the command namespace (db:init, db:migrate, etc.).
  • ManagerFlagName (default: manager) controls the flag used to select a manager (--manager by default).
  • ManagerRegistryServiceId (default: service.database.manager.registry) is the container service id for the *bunorm.ManagerRegistry. It selects which registry instance these commands resolve, not which implementation: the commands resolve the concrete *bunorm.ManagerRegistry, because bunorm publishes no registry contract for them to depend on instead. Point it at a second registry to give a context its own set of managers; there is no door here for substituting a registry of your own.
  • ManagerName (default: empty) pins the manager used when the --manager flag is absent; empty falls back to the registry default.

Empty values are replaced with the defaults in RegisterCommands, and DefaultOptions answers with that same set as a value — the way to read what a field falls back to, or to start from it and change one field.

Commands

All commands accept the standard Melody output flags. Under --format=json a command accumulates its output and renders one machine-readable json envelope on a single line — a failure included — instead of the plain-text output; --format=json-pretty renders the same document indented for reading by hand, and --verbose and --no-color affect the plain-text output alone. The per-query lines a migration prints through RunQueries follow the same flags: the command hands its posture to the migrations through the context the migrator passes them, so a migration passes that context on to RunQueries itself: the skeleton db:create writes is bun's default template, since the command passes no WithGoTemplate option, and it runs no query and prints its own line to standard output. A migration that drops the context falls back to the process-wide default, which the command installs only for the length of its run; a host that runs migrations on its own sets it through SetDefaultRunnerOption.

The json document therefore carries every block the command produces at any verbosity: --verbose never shapes it. Its keys are stable — data.details, data.migrations.applied, data.migrations.pending, data.migrations.rolledBack, data.migrations.ranNotRecorded, data.database, data.files, data.messages — and are not the headings the text blocks print. data.database.database is json null when the connection reports no current database, where the text block renders <null>. One consequence is worth knowing: a json run performs the database-identity query a text run only performs under --verbose.

The manager can be selected with --<managerFlagName>. Without the flag the ManagerName pin from the registration options is used, and only an empty pin falls back to the registry default — which is the point of pinning one manager per command set, so a multi-context binary cannot migrate the wrong database by omitting the flag.

With the default prefix (db), the commands are:

  • db:init – initializes the migrations tables.
  • db:migrate – applies pending migrations.
  • db:rollback – rolls back the last migration group.
  • db:status – shows applied and pending migrations.
  • db:unlock – unlocks the migrations table. It clears the lock whatever holds it, so it is run only once no migration is running against the database: a lock a live run holds, cleared, lets a second run apply the same set beside it. The failure of a run that could not release its lock names the table and this command.
  • db:create <migration-name> – creates a go migrations file. No database is opened for it; on the third major a --manager the registry does not know is refused before the file is written, while the first two majors accept it, naming it only in the report's detail line, and refuse a wrong --manager only in the command it is passed to.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Down

func Down(ctx context.Context, db *bun.DB, migrationName string, queries []Query) error

func DownWithOption

func DownWithOption(ctx context.Context, db *bun.DB, migrationName string, queries []Query, option RunnerOption) error

func RegisterCommands

func RegisterCommands(
	migrations *migrate.Migrations,
	options Options,
) []contract.Command

RegisterCommands builds the migration command family for one migration set. A nil set is refused rather than answered with no commands: the caller believes it registered the family and finds out at invocation time, as "unknown command", far from the wiring that caused it. The module gates its own optional set before calling here, so a binary that registers only migration contexts never reaches this refusal.

func RegisterContextCommands added in v1.2.0

func RegisterContextCommands(
	contexts []ContextConfig,
	baseOptions Options,
) []contract.Command

RegisterContextCommands builds one command family per migration context — db:<name>:migrate, db:<name>:rollback, ... — each pinned to its context's registry manager, so a binary with several databases registers the module once instead of once per context. Zero-value fields of baseOptions and of each context's Options resolve as documented on ContextConfig.

func RunQueries

func RunQueries(ctx context.Context, db *bun.DB, direction string, migrationName string, queries []Query) error

func RunQueriesWithOption

func RunQueriesWithOption(ctx context.Context, db *bun.DB, direction string, migrationName string, queries []Query, option RunnerOption) error

func SetDefaultRunnerOption added in v1.3.0

func SetDefaultRunnerOption(option RunnerOption)

SetDefaultRunnerOption installs the process-wide fallback RunQueries uses when the context carries no option. It is the door of a host process that runs migrations on its own; the migrate commands do not leave anything behind in it — each installs its posture for the length of its run and puts back what was there, and a posture the host installs through this door while a command runs is left where the host put it.

func Up

func Up(ctx context.Context, db *bun.DB, migrationName string, queries []Query) error

func UpWithOption

func UpWithOption(ctx context.Context, db *bun.DB, migrationName string, queries []Query, option RunnerOption) error

Types

type ContextConfig added in v1.2.0

type ContextConfig struct {
	Name       string
	Migrations *migrate.Migrations
	Options    Options
}

ContextConfig declares one migration context of a multi-database binary: its own migration set and its own command family (db:<name>:migrate, db:<name>:rollback, ...) pinned to one registry manager, so omitting the --manager flag can never migrate the wrong database. Zero-value ManagerRegistryServiceId, ManagerFlagName and CommandPrefix inherit from the base options handed to RegisterContextCommands, then from DefaultOptions(); the command prefix derives as <basePrefix>:<name>. ManagerName is intentionally per-context: a context targets the manager named after it (its own name) unless it pins its own Options.ManagerName, and it never inherits the base pin, because a migration context must target its own database.

type CreateCommand

type CreateCommand struct {
	// contains filtered or unexported fields
}

func NewCreateGoCommand

func NewCreateGoCommand(migrations *migrate.Migrations, options Options) *CreateCommand

func (*CreateCommand) Description

func (instance *CreateCommand) Description() string

func (*CreateCommand) Flags

func (instance *CreateCommand) Flags() []clicontract.Flag

func (*CreateCommand) Name

func (instance *CreateCommand) Name() string

func (*CreateCommand) Run

func (instance *CreateCommand) Run(runtimeInstance runtimecontract.Runtime, commandContext *clicontract.CommandContext) (runErr error)

type InitCommand

type InitCommand struct {
	// contains filtered or unexported fields
}

func NewInitCommand

func NewInitCommand(migrations *migrate.Migrations, options Options) *InitCommand

func (*InitCommand) Description

func (instance *InitCommand) Description() string

func (*InitCommand) Flags

func (instance *InitCommand) Flags() []clicontract.Flag

func (*InitCommand) Name

func (instance *InitCommand) Name() string

func (*InitCommand) Run

func (instance *InitCommand) Run(runtimeInstance runtimecontract.Runtime, commandContext *clicontract.CommandContext) (runErr error)

type MigrateCommand

type MigrateCommand struct {
	// contains filtered or unexported fields
}

func NewMigrateCommand

func NewMigrateCommand(migrations *migrate.Migrations, options Options) *MigrateCommand

func (*MigrateCommand) Description

func (instance *MigrateCommand) Description() string

func (*MigrateCommand) Flags

func (instance *MigrateCommand) Flags() []clicontract.Flag

func (*MigrateCommand) Name

func (instance *MigrateCommand) Name() string

func (*MigrateCommand) Run

func (instance *MigrateCommand) Run(runtimeInstance runtimecontract.Runtime, commandContext *clicontract.CommandContext) (runErr error)

type Module added in v1.1.0

type Module struct {
	// contains filtered or unexported fields
}

func NewModule added in v1.1.0

func NewModule(config ModuleConfig) *Module

func (*Module) Description added in v1.1.0

func (instance *Module) Description() string

func (*Module) Name added in v1.1.0

func (instance *Module) Name() string

func (*Module) RegisterCliCommands added in v1.1.0

func (instance *Module) RegisterCliCommands(kernelInstance kernelcontract.Kernel) []clicontract.Command

type ModuleConfig added in v1.1.0

type ModuleConfig struct {
	Migrations *migrate.Migrations
	Options    Options

	/* Contexts declares additional per-database command families (db:<name>:migrate, ...) for multi-context binaries; it composes with the single-set form above, which keeps its unprefixed commands. */
	Contexts []ContextConfig
}

type Options

type Options struct {
	ManagerRegistryServiceId string
	ManagerFlagName          string
	CommandPrefix            string

	/* ManagerName pins the registry manager these commands use when the --manager flag is absent; empty falls back to the registry default. Pin one manager per command set so a multi-context binary can never migrate the wrong database by omitting the flag. */
	ManagerName string
}

func DefaultOptions

func DefaultOptions() Options

type Query

type Query struct {
	Name string
	SQL  string
}

type RollbackCommand

type RollbackCommand struct {
	// contains filtered or unexported fields
}

func NewRollbackCommand

func NewRollbackCommand(migrations *migrate.Migrations, options Options) *RollbackCommand

func (*RollbackCommand) Description

func (instance *RollbackCommand) Description() string

func (*RollbackCommand) Flags

func (instance *RollbackCommand) Flags() []clicontract.Flag

func (*RollbackCommand) Name

func (instance *RollbackCommand) Name() string

func (*RollbackCommand) Run

func (instance *RollbackCommand) Run(runtimeInstance runtimecontract.Runtime, commandContext *clicontract.CommandContext) (runErr error)

type RunnerOption

type RunnerOption struct {
	Writer  io.Writer
	NoColor bool
}

func DefaultRunnerOption

func DefaultRunnerOption() RunnerOption

type StatusCommand

type StatusCommand struct {
	// contains filtered or unexported fields
}

func NewStatusCommand

func NewStatusCommand(migrations *migrate.Migrations, options Options) *StatusCommand

func (*StatusCommand) Description

func (instance *StatusCommand) Description() string

func (*StatusCommand) Flags

func (instance *StatusCommand) Flags() []clicontract.Flag

func (*StatusCommand) Name

func (instance *StatusCommand) Name() string

func (*StatusCommand) Run

func (instance *StatusCommand) Run(runtimeInstance runtimecontract.Runtime, commandContext *clicontract.CommandContext) (runErr error)

type UnlockCommand

type UnlockCommand struct {
	// contains filtered or unexported fields
}

func NewUnlockCommand

func NewUnlockCommand(migrations *migrate.Migrations, options Options) *UnlockCommand

func (*UnlockCommand) Description

func (instance *UnlockCommand) Description() string

func (*UnlockCommand) Flags

func (instance *UnlockCommand) Flags() []clicontract.Flag

func (*UnlockCommand) Name

func (instance *UnlockCommand) Name() string

func (*UnlockCommand) Run

func (instance *UnlockCommand) Run(runtimeInstance runtimecontract.Runtime, commandContext *clicontract.CommandContext) (runErr error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址