migrate

package
v1.2.0 Latest Latest
Warning

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

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

Documentation

Overview

Package migrate applies SQL migrations to SQLite or PostgreSQL. Write migrations as files named <version>_<name>.sql, embed them, and apply them when the app starts:

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

app, err := ternApp(kit.WithPlugins(migrate.Plugin(db, migrations)))

`tern migrate new add users` creates a file with a timestamp version. A file may have an "-- +down" section that undoes it, for Down:

CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL);

-- +down
DROP TABLE users;

Each migration runs in a transaction and is recorded in the tern_migrations table with a checksum, so an applied migration that was edited afterwards is reported instead of silently ignored.

Index

Constants

This section is empty.

Variables

View Source
var ErrChanged = errors.New("migrate: an applied migration was changed")

ErrChanged is returned when an applied migration's file was edited.

Functions

func Plugin

func Plugin(db *sql.DB, fsys fs.FS) kit.Plugin

Plugin applies pending migrations when the server starts, before it accepts requests, and logs each one. A failed migration stops the server.

Types

type Migration

type Migration struct {
	Version   int64
	Name      string
	Applied   bool
	AppliedAt time.Time
	// contains filtered or unexported fields
}

Migration is one migration file and whether it was applied.

func Down

func Down(ctx context.Context, db *sql.DB, fsys fs.FS, steps int) ([]Migration, error)

Down undoes the last steps applied migrations with their "-- +down" sections, newest first, and returns them.

func Load

func Load(fsys fs.FS) ([]Migration, error)

Load reads the migrations in fsys: every <version>_<name>.sql file in its root, or in a migrations directory if the root has one.

func Status

func Status(ctx context.Context, db *sql.DB, fsys fs.FS) ([]Migration, error)

Status lists every migration and whether it was applied.

func Up

func Up(ctx context.Context, db *sql.DB, fsys fs.FS) ([]Migration, error)

Up applies every pending migration in version order and returns the ones it applied. It stops at the first error; migrations before it stay applied. Running instances may call it concurrently on Postgres, where an advisory lock serializes them.

Jump to

Keyboard shortcuts

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