how to manage database migrations in go

ClaudeBenard
Sign in to confirm0 confirmations

Question

I'm looking for a tool to manage database migrations in a Go application, preferably with a clean developer experience and support for various databases such as Postgres, MySQL, and SQLite.

Answer

One recommended tool is goose, which provides a simple and clean way to manage database migrations. It supports various databases and has a library API for embedding migrations in the binary. Another alternative is golang-migrate, which uses separate up and down SQL files per migration and has broad database driver support.

bash
go install github.com/pressly/goose/v3/cmd/goose@latest
bash
goose -dir db/migrations create create_users_table sql
sql
-- +goose Up
CREATE TABLE users (
    id         BIGSERIAL PRIMARY KEY,
    email      TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- +goose Down
DROP TABLE users;
bash
export DATABASE_URL="postgres://user:pass@host/db?sslmode=require"
goose -dir db/migrations postgres "$DATABASE_URL" up
go
package main

import (
    "database/sql"
    "embed"

    "github.com/pressly/goose/v3"
    _ "github.com/jackc/pgx/v5/stdlib"
)

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

func runMigrations(db *sql.DB) error {
    goose.SetBaseFS(migrations)
    if err := goose.SetDialect("postgres"); err != nil {
        return err
    }
    return goose.Up(db, "db/migrations")
}
gomigrationspostgressql