bunmigrate

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: MIT Imports: 9 Imported by: 0

README

bunmigrate

A migration runner for bun, and a ready-made migrate command for CLIs built on urfave/cli v3.

bun ships a migrator but no command around it, so every project grows its own. This is that command, extracted: init, up, rollback, new, status, lock and unlock, over a migration set the consumer keeps.

The difference from bun's own behaviour is how migrations are grouped. bun applies everything pending as one group, so one rollback undoes all of it. Here each migration is applied in a group of its own, so rollback undoes the last migration and up --count 2 applies two. --group on either command asks for bun's whole-group behaviour back.

$ myapp migrate up
Applied 20240301120000_create_users
Applied 20240302093000_add_email_index
$ myapp migrate status
 NAME                             GROUP  APPLIED AT
 20240301120000_create_users      #1     2026-07-31T18:20:11Z
 20240302093000_add_email_index   #2     2026-07-31T18:20:11Z

Installation

go get oaklab.hu/go/bunmigrate

Usage

The migration set stays in the consuming module - the //go:embed directive only resolves against the module it is written in - and so does everything about opening the database.

// migrations/main.go
package migrations

import (
 "embed"

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

var Migrations = migrate.NewMigrations()

//go:embed *.sql
var sqlMigrations embed.FS

func init() {
 if err := Migrations.Discover(sqlMigrations); err != nil {
  panic(err)
 }
}

clicmd.New takes that set and a function that opens the database, and returns an ordinary *cli.Command:

import (
 "oaklab.hu/go/bunmigrate/clicmd"

 "example.com/myapp/migrations"
)

cmd := &cli.Command{
 Name: "myapp",
 Commands: []*cli.Command{
  clicmd.New(migrations.Migrations, func(ctx context.Context) (*bun.DB, error) {
   cfg, err := config.Load()
   if err != nil {
    return nil, err
   }

   return database.Open(ctx, cfg.DatabaseURL)
  }),
 },
}

The open function runs when a subcommand runs, not when the command is built, so a missing database or a broken configuration file does not stop the rest of the CLI from working. The handle is closed again after the subcommand finishes.

Any migrate.MigratorOption may follow, for a migration table under a different name and the rest of bun's knobs:

clicmd.New(migrations.Migrations, open, migrate.WithTableName("schema_migrations"))
Without urfave/cli

clicmd is a thin layer over bunmigrate.Runner, which is what actually talks to bun. Use it directly to drive migrations from somewhere else - a startup hook, a test fixture, a different CLI framework:

runner := bunmigrate.New(db, migrations.Migrations)

if err := runner.Init(ctx); err != nil {
 return err
}

applied, err := runner.Migrate(ctx, bunmigrate.MigrateOptions{})
if err != nil {
 return err
}

for _, m := range applied {
 log.Printf("applied %s", m)
}

Migrate and Rollback return what they did even when they return an error, so a run that failed halfway can still be reported.

Importing oaklab.hu/go/bunmigrate brings in bun and nothing else; urfave/cli and the table renderer come with clicmd.

SQLite

EnsureSQLiteFile creates the database file named by a file: DSN, and the directories leading to it. SQLite creates a missing database file itself but not the directory it sits in, so the first run of an application that keeps its database under file:instance/app.sqlite fails until something creates instance:

if err := bunmigrate.EnsureSQLiteFile(cfg.DatabaseURL); err != nil {
 return nil, err
}

DSNs that do not name a file on disk - anything without the file: prefix, :memory:, mode=memory - are left alone.

Stability

Tagged v0.x while the API settles. The surface is deliberately small; adding a method later is easy, removing one is not.

License

MIT

Documentation

Overview

Package bunmigrate runs schema migrations for github.com/uptrace/bun.

Runner wraps bun's github.com/uptrace/bun/migrate.Migrator with the workflow a command-line migration tool needs: applying pending migrations one at a time, stamping them without running them, rolling back the last one, and listing their status. Subpackage clicmd turns a Runner into a urfave/cli command; this package itself depends on bun and the standard library only.

The migration set stays with the caller. Keeping github.com/uptrace/bun/migrate.Migrations, its //go:embed directive and its Discover call in the consuming module is what makes the embedded migration files resolve against that module rather than this one.

Index

Constants

This section is empty.

Variables

View Source
var ErrCountWithGroup = errors.New("cannot limit the count of a grouped migration")

ErrCountWithGroup is returned by Runner.Migrate when MigrateOptions asks for a limited run and a single group at the same time. The two are mutually exclusive: a group is applied by bun in one step, with no place to stop.

Functions

func EnsureSQLiteFile

func EnsureSQLiteFile(dsn string) error

EnsureSQLiteFile creates the database file named by a SQLite "file:" DSN, along with the directories leading to it.

SQLite creates a missing database file on its own, but not the directory it sits in, so the first run of an application that keeps its database under, say, "file:instance/app.sqlite" fails with "unable to open database file" until something creates "instance". This is that something, meant to be called from the function that opens the database, before migrations run.

Anything that does not name a file on disk is left alone: DSNs without the "file:" prefix, ":memory:" and "mode=memory". The file is created with mode 0600 and its directories with 0700, since a database rarely wants to be world-readable; an existing file keeps its own permissions.

Types

type MigrateOptions

type MigrateOptions struct {
	// Group applies all pending migrations as a single group, the way bun does
	// it, instead of one group per migration. A later rollback then undoes the
	// whole group at once.
	Group bool
	// Stamp records the migrations as applied without running them. Use it to
	// adopt a database whose schema already matches.
	Stamp bool
	// Count applies at most this many migrations, oldest first. Zero applies
	// all of them. It cannot be combined with Group.
	Count int
}

MigrateOptions configures Runner.Migrate.

type RollbackOptions

type RollbackOptions struct {
	// Group rolls back the whole last migration group instead of the single
	// last applied migration.
	Group bool
	// Stamp records the migrations as unapplied without running their down
	// migrations.
	Stamp bool
}

RollbackOptions configures Runner.Rollback.

type Runner

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

Runner applies, rolls back and inspects a set of migrations.

Where bun's migrate.Migrator applies every pending migration as one group, a Runner applies them one at a time, each in a group of its own, so that a rollback undoes a single migration and a run can stop after a given number of them. Setting Group in MigrateOptions or RollbackOptions asks for bun's whole-group behaviour instead.

A Runner is a thin wrapper: it holds no state of its own beyond the migrator, and it is safe for concurrent use to the same extent bun's migrator is.

func New

func New(db *bun.DB, migrations *migrate.Migrations, opts ...migrate.MigratorOption) *Runner

New returns a Runner that migrates db with the given migration set.

migrate.WithMarkAppliedOnSuccess is enabled ahead of opts, so a migration that fails partway through is not left recorded as applied. Pass migrate.WithMarkAppliedOnSuccess(false) in opts to restore bun's default.

func (*Runner) CreateGo

func (r *Runner) CreateGo(ctx context.Context, name string) (*migrate.MigrationFile, error)

CreateGo writes a Go migration file into the migrations directory. The generated file registers itself with the migration set of the package it lands in, so it compiles only once that package declares one.

func (*Runner) CreateSQL

func (r *Runner) CreateSQL(ctx context.Context, name string) ([]*migrate.MigrationFile, error)

CreateSQL writes an up and a down SQL migration file into the migrations directory and returns both.

func (*Runner) Init

func (r *Runner) Init(ctx context.Context) error

Init creates the migration bookkeeping tables. It is safe to call against a database that already has them.

func (*Runner) Lock

func (r *Runner) Lock(ctx context.Context) error

Lock takes the migration lock, so that a second process cannot migrate the same database at the same time. Runner.Migrate and Runner.Rollback do this themselves; call it directly only to hold the lock across processes, which is what a "lock" subcommand is for.

The lock is a row in the locks table, not a database session lock: it outlives the process that took it and is released only by Runner.Unlock.

func (*Runner) Migrate

func (r *Runner) Migrate(ctx context.Context, opts MigrateOptions) (migrate.MigrationSlice, error)

Migrate applies pending migrations, oldest first, and returns those it applied.

Each migration lands in a group of its own unless MigrateOptions.Group is set. The database is locked for the duration.

The returned slice holds the migrations that were applied even when the error is non-nil, so a partial run can still be reported.

func (*Runner) Migrator

func (r *Runner) Migrator() *migrate.Migrator

Migrator returns the migrator underneath, for the operations this package does not wrap: migrate.Migrator.Reset, migrate.Migrator.MissingMigrations and the rest of bun's API.

func (*Runner) Rollback

func (r *Runner) Rollback(ctx context.Context, opts RollbackOptions) (migrate.MigrationSlice, error)

Rollback undoes the last applied migration and returns it, or nothing when the database is already at its initial state.

With RollbackOptions.Group the whole last group is undone, newest migration first. The database is locked for the duration.

The returned slice holds the migrations that were rolled back even when the error is non-nil.

func (*Runner) Status

func (r *Runner) Status(ctx context.Context) (migrate.MigrationSlice, error)

Status returns every known migration, applied or not, oldest first.

func (*Runner) Unlock

func (r *Runner) Unlock(ctx context.Context) error

Unlock releases the migration lock. It reports no error when the lock is not held.

Source Files

  • doc.go
  • runner.go
  • sqlite.go

Directories

Path Synopsis
Package clicmd exposes a bunmigrate.Runner as a urfave/cli v3 command.
Package clicmd exposes a bunmigrate.Runner as a urfave/cli v3 command.

Jump to

Keyboard shortcuts

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