migrate

package
v0.16.1 Latest Latest
Warning

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

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

Documentation

Overview

Package migrate applies SQL schema migrations from an embedded filesystem.

It wraps github.com/pressly/goose using goose's Provider API, so callers never touch goose's process-global state (SetBaseFS/SetDialect) and several migrators can coexist in one process (e.g. app vs tests). Migrations are read from an fs.FS — typically an embed.FS of `*.sql` files — so they ship inside the binary.

Usage

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

// db is a *dbx.DB; db.DB.DB is its *sql.DB.
m, err := migrate.New(db.DB.DB, migrationsFS)
if err != nil {
    return err
}
defer m.Close()
if err := m.Up(ctx); err != nil {
    return err
}

New takes a *sql.DB opened with a driver matching the dialect (Postgres by default, e.g. a pgx connection; another one via WithDialect). It does not take ownership of db: Close never closes the handle. Use fs.Sub if the migrations live in a subdirectory of the embedded FS.

Operations

  • Up applies every pending migration in version order (a no-op when current).
  • Down rolls back the most recently applied migration.
  • Version returns the current applied schema version (0 before any migration).
  • Status returns the applied state of every known migration, ordered by version, as []MigrationStatus.

Dialects

The supported dialects are re-exported so callers need not import goose: Postgres (the default), MySQL, SQLite3; New takes another one via WithDialect. Dialect is an alias for goose.Dialect.

Example

Up applies the pending migrations in version order; a second Up has nothing to do.

package main

import (
	"context"
	"errors"
	"fmt"
	"testing/fstest"

	"github.com/assanoff/skit/dbx"
	"github.com/assanoff/skit/dbx/sqlite"
	"github.com/assanoff/skit/migrate"
	_ "modernc.org/sqlite"
)

// migrations stands in for the embed.FS of a service's *.sql files.
var migrations = fstest.MapFS{
	"00001_widgets.sql": {Data: []byte(`-- +goose Up
CREATE TABLE widgets (id INTEGER PRIMARY KEY, name TEXT NOT NULL);

-- +goose Down
DROP TABLE widgets;
`)},
	"00002_widget_price.sql": {Data: []byte(`-- +goose Up
ALTER TABLE widgets ADD COLUMN price INTEGER NOT NULL DEFAULT 0;

-- +goose Down
ALTER TABLE widgets DROP COLUMN price;
`)},
}

// open opens an in-memory SQLite database and a Migrator over it.
func open() (*dbx.DB, *migrate.Migrator, error) {
	db, err := sqlite.Open(sqlite.Config{Path: ":memory:"})
	if err != nil {
		return nil, nil, err
	}

	m, err := migrate.New(db.DB.DB, migrations, migrate.WithDialect(migrate.SQLite3))
	if err != nil {
		return nil, nil, errors.Join(err, db.Close())
	}
	return db, m, nil
}

func main() {
	ctx := context.Background()
	db, m, err := open()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = db.Close() }()

	for range 2 {
		if err := m.Up(ctx); err != nil {
			fmt.Println(err)
			return
		}
		v, err := m.Version(ctx)
		fmt.Println("version:", v, err)
	}
}
Output:
version: 2 <nil>
version: 2 <nil>

Index

Examples

Constants

View Source
const (
	Postgres = goose.DialectPostgres
	MySQL    = goose.DialectMySQL
	SQLite3  = goose.DialectSQLite3
)

Supported dialects, re-exported so callers need not import goose directly.

Variables

This section is empty.

Functions

This section is empty.

Types

type Dialect

type Dialect = goose.Dialect

Dialect identifies the database dialect for migrations.

type MigrationStatus

type MigrationStatus struct {
	Version int64
	Source  string
	Applied bool
}

MigrationStatus is the applied state of a single migration.

type Migrator

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

Migrator applies goose migrations against a database/sql handle. Construct it with New and release it with Close. It is safe to reuse across calls.

func New

func New(db *sql.DB, fsys fs.FS, opts ...Option) (*Migrator, error)

New builds a Migrator for the database handle db and the migration filesystem fsys. fsys is usually an embed.FS rooted at the `*.sql` files; pass the embedded FS directly (use fs.Sub if the migrations live in a subdirectory).

The handle must be opened with a driver matching the dialect — e.g. a pgx/lib-pq connection for Postgres, the default. New does not take ownership of db; Close releases only the provider.

func (*Migrator) Close

func (m *Migrator) Close() error

Close releases the Migrator. It deliberately does NOT close the underlying database handle passed to New: New does not take ownership, so the caller owns the handle's lifecycle. (goose's provider.Close would close the *sql.DB, which silently breaks callers that keep using their handle after migrating — e.g. dbtest.NewPostgres hands back a live pool. goose holds no other resources that require release once Up/Down/Status have returned.)

func (*Migrator) Down

func (m *Migrator) Down(ctx context.Context) error

Down rolls back the most recently applied migration.

Example

Down rolls back the last applied migration; Status lists every migration with its state.

package main

import (
	"context"
	"errors"
	"fmt"
	"testing/fstest"

	"github.com/assanoff/skit/dbx"
	"github.com/assanoff/skit/dbx/sqlite"
	"github.com/assanoff/skit/migrate"
	_ "modernc.org/sqlite"
)

// migrations stands in for the embed.FS of a service's *.sql files.
var migrations = fstest.MapFS{
	"00001_widgets.sql": {Data: []byte(`-- +goose Up
CREATE TABLE widgets (id INTEGER PRIMARY KEY, name TEXT NOT NULL);

-- +goose Down
DROP TABLE widgets;
`)},
	"00002_widget_price.sql": {Data: []byte(`-- +goose Up
ALTER TABLE widgets ADD COLUMN price INTEGER NOT NULL DEFAULT 0;

-- +goose Down
ALTER TABLE widgets DROP COLUMN price;
`)},
}

// open opens an in-memory SQLite database and a Migrator over it.
func open() (*dbx.DB, *migrate.Migrator, error) {
	db, err := sqlite.Open(sqlite.Config{Path: ":memory:"})
	if err != nil {
		return nil, nil, err
	}

	m, err := migrate.New(db.DB.DB, migrations, migrate.WithDialect(migrate.SQLite3))
	if err != nil {
		return nil, nil, errors.Join(err, db.Close())
	}
	return db, m, nil
}

func main() {
	ctx := context.Background()
	db, m, err := open()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = db.Close() }()

	if err := m.Up(ctx); err != nil {
		fmt.Println(err)
		return
	}
	if err := m.Down(ctx); err != nil {
		fmt.Println(err)
		return
	}
	v, err := m.Version(ctx)
	fmt.Println("version:", v, err)

	st, err := m.Status(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, s := range st {
		fmt.Println(s.Version, s.Source, s.Applied)
	}
}
Output:
version: 1 <nil>
1 00001_widgets.sql true
2 00002_widget_price.sql false

func (*Migrator) Status

func (m *Migrator) Status(ctx context.Context) ([]MigrationStatus, error)

Status returns the applied state of every known migration, ordered by version.

func (*Migrator) Up

func (m *Migrator) Up(ctx context.Context) error

Up applies every pending migration in version order. It is a no-op when the schema is already current.

func (*Migrator) Version

func (m *Migrator) Version(ctx context.Context) (int64, error)

Version returns the current applied schema version (0 before any migration).

type Option added in v0.14.0

type Option func(*options)

Option customizes a Migrator.

func WithDialect added in v0.14.0

func WithDialect(d Dialect) Option

WithDialect sets the database dialect (default Postgres).

Jump to

Keyboard shortcuts

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