Go Database Migrations with golang-migrate

Updated 9 min read
Go Database Migrations featured image: cards for up files, down files and version tracking

Go database migrations keep your database schema in step with your code, one small numbered change at a time. In this post, you will learn what a migration is and how the popular golang-migrate tool tracks them. Also, you will write safe “up” and “down” files. Then we will run migrations from the command line and from Go code at startup.

In the last lesson, Go PostgreSQL with pgx, we created the books table by hand in psql. Of course, that works on one laptop. However, it breaks down as soon as a team, a test server and production all need the same tables. You will also see embed and environment variables again, which we covered in Go environment variables for configuration.

What Are Go Database Migrations?

In short, a migration is a small SQL file that changes the database schema in one step. For example, one migration creates a table, and the next one adds a column. Each migration has a version number, so the tool always knows which changes a database already has.

For example, think of migrations as a recipe written as numbered steps. So a new cook simply follows the steps from the top. Meanwhile, a cook who already did steps 1 to 3 continues from step 4. Similarly, Go database migrations bring any database, old or new, to the latest schema.

Also, every migration usually comes in a pair. So the “up” file applies the change, and the “down” file undoes it.

Why Go Database Migrations Matter

Without migrations, however, schema changes live in someone’s head or in a chat message. As a result, environments drift apart and bugs appear only in production. Specifically, here is what migrations fix.

  • Same schema everywhere: laptops, CI, staging and production all run the same files.
  • History you can review: every schema change goes through a pull request, just like code.
  • Safe rollbacks: when a release goes wrong, a “down” file can undo the latest change.
  • Easy onboarding: a new developer runs one command, so the full schema appears in seconds.
  • Automatic deploys: the app or pipeline applies new migrations before new code runs.

In short, Go database migrations turn schema changes into normal, versioned code.

How Go Database Migrations Work

First, you write numbered files in a folder, such as 000001_create_books_table.up.sql. Then you run the tool against a database URL. Then the tool reads its own tracking table, schema_migrations, to find the current version. Finally, it applies every newer “up” file in order and saves the new version number.

Go Database Migrations diagram showing golang-migrate applying only pending files and updating schema_migrations
golang-migrate reads the current version from schema_migrations and applies only the newer up files, in order.

In particular, the tracking table has two columns. version holds the last applied number, and dirty is set to true while a migration runs. So if a migration fails halfway, the database stays marked as dirty until you fix it.

Key Parts of golang-migrate

In fact, golang-migrate works both as a command line tool and as a Go library. Also, it supports PostgreSQL, MySQL, SQLite and many more databases. So this table shows the commands you will use most.

CommandWhat it does
migrate create -ext sql -dir db/migrations -seq NAMECreates a new numbered up and down file
migrate -path db/migrations -database URL upApplies all pending migrations
migrate ... down 1Undoes only the latest migration
migrate ... versionPrints the current version
migrate ... force NSets the version after a manual fix

File Naming

Generally, each file name has a version, a description, a direction and the .sql extension. For instance, 000002_add_stock_to_books.up.sql. The -seq flag gives simple numbers like 000001, while the default uses a timestamp. Simple numbers are easier to read, so we use them here. However, busy teams often prefer timestamps, because two people rarely pick the same one.

Up and Down Files

An “up” file moves the schema forward, while its “down” file reverses exactly that change. So if up adds a column, down drops the same column.

The Database URL

For instance, a PostgreSQL URL looks like postgres://user:pass@localhost:5432/shop?sslmode=disable. Therefore, keep it in an environment variable instead of typing passwords into commands.

Migrations vs Manual Changes vs Auto-Migrate

Overall, there are three common ways to change a schema. So the table below compares them.

FeatureSQL migrationsManual SQL in psqlORM auto-migrate
Versioned historyYesNoPartly
Can roll backYes, with down filesOnly by handRarely
Reviewed in pull requestsYesNoOnly as Go structs
Handles data changesYes, any SQLYesNo
Same result everywhereYesNoMostly
Good forReal projectsQuick experimentsSmall demos
Go Database Migrations diagram showing up and down steps between schema versions
Each migration is a pair of files: up moves the schema forward one step, and down moves it back by exactly that step.

So when should you use which? Use SQL migrations for any project that has more than one database. On the other hand, manual SQL is fine for a quick local test you will throw away.

Hands-On: Go Database Migrations for a Book Store

Now let’s write Go database migrations for the book store from the pgx lesson. First we create a table, then add a column and finally add an index, each as its own migration.

Step 1: Install the CLI and Create Files

First, install the tool with Go. Here, the build tag adds PostgreSQL support.

go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
migrate create -ext sql -dir db/migrations -seq create_books_table
migrate create -ext sql -dir db/migrations -seq add_stock_to_books
migrate create -ext sql -dir db/migrations -seq add_author_index

Then each create command makes two empty files. As a result, the folder now holds six files numbered 000001 to 000003.

Step 2: Write the SQL

Now fill in each pair. For clarity, here are all six files, one after another.

-- 000001_create_books_table.up.sql
CREATE TABLE IF NOT EXISTS books (
    id     BIGSERIAL PRIMARY KEY,
    title  TEXT NOT NULL,
    author TEXT NOT NULL
);

-- 000001_create_books_table.down.sql
DROP TABLE IF EXISTS books;

-- 000002_add_stock_to_books.up.sql
ALTER TABLE books ADD COLUMN stock INTEGER NOT NULL DEFAULT 0;

-- 000002_add_stock_to_books.down.sql
ALTER TABLE books DROP COLUMN IF EXISTS stock;

-- 000003_add_author_index.up.sql
CREATE INDEX IF NOT EXISTS idx_books_author ON books (author);

-- 000003_add_author_index.down.sql
DROP INDEX IF EXISTS idx_books_author;

Notice the DEFAULT 0 in migration 2. Without it, adding a NOT NULL column would fail on a table that already has rows. Also, IF EXISTS and IF NOT EXISTS make each file safe to run again. We ran all three up files and then all three down files against PostgreSQL 16. As a result, the schema went forward and back cleanly.

Step 3: Run the Migrations

Next, apply all Go database migrations and check the version.

export DATABASE_URL="postgres://postgres:secret@localhost:5432/shop?sslmode=disable"
migrate -path db/migrations -database "$DATABASE_URL" up
migrate -path db/migrations -database "$DATABASE_URL" version
migrate -path db/migrations -database "$DATABASE_URL" down 1

The up command prints one line per applied migration, and version then prints 3. Then, after down 1, the index is gone and the version goes back to 2. The output looks like this, although your timings will differ.

1/u create_books_table (8.1ms)
2/u add_stock_to_books (12.4ms)
3/u add_author_index (16.9ms)
3
3/d add_author_index (5.2ms)

Step 4: Run Go Database Migrations at Startup

Many teams run Go database migrations from the app itself when it starts. So the files ship inside the binary with embed, and no extra tool is needed in production.

package main

import (
	"embed"
	"errors"
	"log"
	"os"

	"github.com/golang-migrate/migrate/v4"
	_ "github.com/golang-migrate/migrate/v4/database/postgres"
	"github.com/golang-migrate/migrate/v4/source/iofs"
)

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

func runMigrations(dbURL string) error {
	src, err := iofs.New(migrationsFS, "migrations")
	if err != nil {
		return err
	}
	m, err := migrate.NewWithSourceInstance("iofs", src, dbURL)
	if err != nil {
		return err
	}
	defer m.Close()
	if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
		return err
	}
	return nil
}

func main() {
	if err := runMigrations(os.Getenv("DATABASE_URL")); err != nil {
		log.Fatalf("migrate: %v", err)
	}
	log.Println("database is up to date")
}

Let’s walk through it, since this pattern appears in many Go services. First of all, the //go:embed line copies every .sql file into the binary at build time. Then iofs.New turns that embedded folder into a migration source. Finally, m.Up() applies pending files, and migrate.ErrNoChange simply means the database was already current, so we treat it as success.

Step 5: Fixing a Dirty Database

Sometimes a migration fails. For example, suppose migration 2 has a typo and fails halfway. Then every later command stops with error: Dirty database version 2. Fix and force version. To recover, first fix the database by hand so it matches version 1. Next, run migrate ... force 1 to clear the dirty flag. Finally, correct the SQL file and run up again.

Common Mistakes with Go Database Migrations

  • Editing a migration that already ran: other databases never see the change. Instead, always add a new migration.
  • Adding NOT NULL without a default: the migration fails on tables that have rows. So add a default or fill the column first.
  • Writing a down file that does not match: rollbacks then break the schema. Instead, make each down undo exactly its up.
  • Two developers using the same number: one file is skipped or conflicts. Use timestamps on busy teams, or check before merging.
  • Running migrations from many app copies at once: they may race. However, golang-migrate takes a database lock, so let it handle this, or run migrations in a separate deploy step.

Best Practices for Go Database Migrations

  • Keep each migration small, because small steps are easy to review and undo.
  • Test up, then down, then up again in CI, so broken down files are caught early.
  • Never put secrets in migration files, since they live in Git forever.
  • Separate schema and big data changes, because long data updates can lock tables.
  • Embed migrations in the binary, so the app and its schema always ship together.

Practice Task

To practise Go database migrations, add a migration that creates a sales table. Give it id, book_id and sold_at TIMESTAMPTZ NOT NULL DEFAULT now(). Then write the matching down file and run up, down 1 and up again.

Hint: add a foreign key with book_id BIGINT NOT NULL REFERENCES books(id).

Official Resources

These pages cover the tool, its CLI and Go’s embed feature, so check them for every option.

Quick Recap

  • Go database migrations are numbered SQL files that change the schema step by step.
  • Also, each migration has an up file and a matching down file.
  • golang-migrate tracks the current version in the schema_migrations table.
  • Then use up, down 1, version and force from the CLI.
  • Embed migrations and run m.Up() at startup, ignoring ErrNoChange.
  • Finally, never edit a migration that already ran; add a new one instead.

What’s Next?

Now our schema is versioned. Next, we will compare two popular ways to write the queries themselves. Specifically, we look at generating code with sqlc and using the GORM library.

Next lesson: Go sqlc vs GORM: Which Should You Use?