Versioned migrations with golang-migrate
Why schema changes live in numbered files, how golang-migrate tracks what ran, writing up and down files, and what to do when a migration fails halfway.
Learning outcomes
- Explain why schema changes go through migration files and never through a shell.
- Create, apply and roll back a migration with the migrate CLI.
- Read the schema_migrations table and recover from a dirty state.
- Write migrations that are safe to run against a table that already has data.
Why database migrations exist
A database schema is part of your application's source code, even though it lives inside a database rather than a Git repository.
As your application evolves, you'll add tables, change columns, introduce indexes, and modify relationships. These changes need to happen consistently across your local environment, CI, staging, and production.
Imagine you manually create the restaurants table in your local MySQL database. Your application works, so you move on to writing Go queries.
A teammate checks out your repository. Their database doesn't have that table. Your CI environment also starts with an empty database. Suddenly, the application works on your machine but fails everywhere else.
The problem is that the database schema was never recorded as part of the project.
A database migration solves this by representing every schema change as a versioned, reviewable file.
Instead of manually changing the database, you describe the change in SQL and let a migration tool apply it.
Why this matters
Reproducible environments
Anyone can start with an empty database and apply the same migrations to obtain the expected schema.
Code review
A schema change becomes part of a pull request. Reviewers can inspect new columns, constraints, indexes, and potential compatibility issues just like application code.
CI reliability
Your tests can create a fresh database, apply migrations, seed data, and execute integration tests against a known schema.
Production safety
The same migration files that were reviewed and tested can be applied to production. There is no undocumented sequence of manual SQL commands.
Introducing golang-migrate
For this project, you'll use golang-migrate, a database migration tool written in Go.
It manages a sequence of versioned migration files and tracks which versions have been applied to a database.
Its responsibility is deliberately narrow:
- Find migration files.
- Determine the current database version.
- Apply the appropriate SQL files in order.
- Record the resulting migration version.
- Prevent further migrations when the database is in a dirty state.
It does not design your schema, generate SQL queries, or decide whether a migration is safe for production. Those responsibilities belong to you.
Installing the CLI
On macOS, install it using Homebrew:
brew install golang-migrateVerify the installation:
migrate -versionThe CLI is the interface you'll use to create, apply, inspect, and roll back migrations.
Your project setup
Your repository stores migration files here:
backend/db/migrations/0001_restaurants.up.sql
backend/db/migrations/0001_restaurants.down.sql
backend/MakefileMySQL 8.4 runs through Docker Compose using the service named mysql.
Start the database:
docker compose up -d mysqlThe root password comes from MYSQL_ROOT_PASSWORD, whose local development default is dev.
For a local shell session, you can configure it with:
export MYSQL_ROOT_PASSWORD=devMake sure the database exists and is ready to accept connections before applying migrations.
Understanding migration files
A logical migration consists of two files:
- An
upmigration describes how to move the schema forward. - A
downmigration describes how to reverse that change.
For example:
db/migrations/0001_restaurants.up.sql
db/migrations/0001_restaurants.down.sqlThe number identifies the migration version. The title describes its purpose.
The .up.sql suffix tells the tool which file to execute when moving forward. The .down.sql suffix identifies the corresponding rollback.
The filename format is:
{version}_{title}.up.sql
{version}_{title}.down.sqlVersions determine execution order. Titles are descriptive and do not determine which migration runs first.
Creating a migration
The CLI provides a command for generating the two files:
migrate create -ext sql -dir db/migrations -seq restaurantsThis creates:
000001_restaurants.up.sql
000001_restaurants.down.sqlNotice the six-digit numbering.
Your repository uses four-digit names such as 0001_restaurants.up.sql. Both conventions work because golang-migrate parses the leading numeric portion as the migration version.
To generate four-digit sequential filenames explicitly, you can use:
migrate create -ext sql -dir db/migrations -seq -digits 4 restaurantsFor this course, follow the existing four-digit naming convention.
Never assign the same version to two different migrations. The version is the identity of the migration, not simply part of its display name.
What goes inside each file?
The up file creates or modifies database objects.
For example, a simple migration might contain:
CREATE TABLE restaurants (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL
) ENGINE=InnoDB;The corresponding down file reverses that change:
DROP TABLE restaurants;The two files should describe opposite directions of the same schema change.
For your actual exercise, the migration will create six related tables, so the rollback must account for their foreign-key dependencies.
How golang-migrate tracks database state
The most important piece of the migration system is a table named schema_migrations.
You don't create this table yourself. The migration tool manages it.
It stores two important pieces of information:
| Column | Meaning |
|---|---|
version | The latest migration version recorded |
dirty | Whether a migration is currently considered incomplete or failed |
On a fresh database the table is empty: no version is recorded yet, which golang-migrate calls the nil version and shows as -1 in commands such as force.
After successfully applying migration 1:
| version | dirty |
|---|---|
| 1 | false |
After successfully applying migration 2:
| version | dirty |
|---|---|
| 2 | false |
The important detail is that version is not a count of tables or SQL statements. It identifies the migration version that the database has reached.
The dirty flag is equally important.
Before executing a migration, golang-migrate marks the target version as dirty. If execution succeeds, it records the completed version and clears the dirty state.
If execution fails, the database remains marked dirty.
This prevents the tool from blindly executing additional migrations against a potentially inconsistent schema.
Running migrations locally
Your project already provides a Makefile target for applying migrations.
migrate:
migrate -database "mysql://root:$$MYSQL_ROOT_PASSWORD@tcp(127.0.0.1:3306)/zomato" -path db/migrations upRun it from the backend directory:
make migrateLet's break down the command.
-database
Specifies the MySQL connection string.
mysql://root:PASSWORD@tcp(127.0.0.1:3306)/zomatoIt identifies:
- Database user:
root - Password:
MYSQL_ROOT_PASSWORD - Host:
127.0.0.1 - Port:
3306 - Database:
zomato
-path db/migrations
Specifies the directory containing your migration files.
up
Instructs the tool to apply every unapplied migration in ascending version order.
The double dollar sign in the Makefile is intentional. Make interprets $$ as a literal $, allowing the shell to expand MYSQL_ROOT_PASSWORD when the recipe executes.
One file, many statements
Your migration file contains several statements:
CREATE TABLE restaurants (...);
CREATE TABLE items (...);
CREATE TABLE item_sizes (...);The Go MySQL driver refuses to send more than one statement in a single call unless the connection is opened with multiStatements=true. You don't need to add it to the URL: golang-migrate's MySQL driver turns it on for every connection it opens from a mysql:// URL, which is why the Makefile works as written.
It only matters if you ever run migrations from Go code with your own *sql.DB (the WithInstance API). Then you must open that connection with multiStatements=true yourself, or the first file with two statements fails.
Essential CLI commands
You should understand the following commands before working on your migration.
| Command | Purpose |
|---|---|
migrate create | Generate migration files |
migrate up | Apply all pending migrations |
migrate up N | Apply the next N migrations |
migrate down 1 | Roll back one migration |
migrate version | Display the current migration version and dirty state |
migrate goto N | Move to a specified migration version |
migrate force N | Set the recorded version without executing SQL |
The commands use the same connection and migration directory options as your Makefile.
Applying migrations incrementally
Suppose your directory contains:
0001_restaurants.up.sql
0002_seed_data.up.sql
0003_add_indexes.up.sqlYou can apply everything:
migrate -database "$DATABASE_URL" -path db/migrations upOr apply only the first two migrations:
migrate -database "$DATABASE_URL" -path db/migrations up 2The latter is useful when you want to test migration behaviour one step at a time.
Rolling back
To reverse only the latest applied migration:
migrate -database "$DATABASE_URL" -path db/migrations down 1This executes the corresponding .down.sql file and moves the recorded version backwards.
For example, if the database is at version 2, the command executes version 2's down migration and returns to version 1.
Do not confuse this with deleting the migration file. The file remains in the repository so that the schema can be recreated later.
Inspecting the current version
Run:
migrate -database "$DATABASE_URL" -path db/migrations versionThis is particularly useful before and after applying or rolling back migrations.
You should know whether the database is clean and which version it currently records before troubleshooting anything.
Moving to a specific version
The goto command moves the database to a specified migration version:
migrate -database "$DATABASE_URL" -path db/migrations goto 2It applies forward migrations when the target is ahead and down migrations when the target is behind.
Use it when you intentionally want to move to a particular version, not as a substitute for understanding the effects of a rollback.
Dirty migrations and recovery
This is particularly important with MySQL.
MySQL 8.4 supports atomic DDL for individual supported operations, but that does not mean an entire multi-statement migration runs as one transaction.
Statements such as CREATE TABLE, ALTER TABLE, and DROP TABLE cause implicit commits.
Consequently, you cannot assume that wrapping all your schema changes in BEGIN and COMMIT will make the entire migration reversible.
Consider a migration containing:
CREATE TABLE restaurants (...);
CREATE TABLE items (...);
CREATE TABLE item_sizes (
...
FOREIGN KEY (item_id) REFERENCES nonexistent_table(id)
);Suppose the first two statements succeed but the third fails.
The first two tables may already exist. MySQL does not automatically remove them just because the migration file failed.
golang-migrate marks the migration version dirty because it cannot safely assume the intended schema change completed.
The migration state machine


What does force actually do?
The force command is often misunderstood.
For example:
migrate -database "$DATABASE_URL" -path db/migrations force -1This sets the recorded version to -1, meaning "no migration applied", and clears the dirty flag. Any other number must be a version that has a migration file: force 0 would leave you at a version with no file, and the next up fails with no migration found for version 0.
It does not execute any SQL.
It does not remove partially created tables, repair indexes, or restore missing data.
It only changes the migration tool's recorded state.
A safe recovery procedure
Suppose migration 1 failed after creating restaurants and items, but before creating item_sizes.
Follow this process:
- Inspect the error message and identify the statement that failed.
- Check the actual database state using
SHOW TABLES,SHOW CREATE TABLE, and other relevant inspection queries. - Determine whether the existing objects are safe to remove or whether the migration needs to be completed manually.
- Correct the migration SQL.
- Make the actual schema match the state you intend to record.
- Force the appropriate previous version.
- Run the migration again.
- Verify the resulting schema and migration version.
For this specific example, if you remove the two partially created tables and restore the database to its original empty state, reset the version to "nothing applied":
migrate -database "$DATABASE_URL" -path db/migrations force -1Then:
make migrateHowever, if you manually complete every operation in migration 1 instead, forcing version 1 may be appropriate. You must first establish that the actual database fully matches the intended end state of that migration.
Writing reversible migrations
Your .down.sql file should reverse the .up.sql changes.
For tables connected by foreign keys, deletion must happen in dependency order.
Consider the restaurant and menu relationships:


You cannot safely drop a parent table while child tables still reference it.
Therefore, the rollback must reverse the dependency order:
DROP TABLE option_prices;
DROP TABLE options;
DROP TABLE option_groups;
DROP TABLE item_sizes;
DROP TABLE items;
DROP TABLE restaurants;The child tables are removed first, followed by their parents.
This is the reverse of the logical order in which the relationships were established.
For more complicated schemas, draw the foreign-key dependency graph before writing the rollback.
Also remember that a down migration is not automatically safe just because it is syntactically valid. Dropping a table containing production data is destructive.
A rollback should be treated as a deliberate operational decision, not a routine way to undo application behaviour.
Production migration practices
Local development is forgiving. Production databases contain real data, serve active requests, and may be too large for expensive schema changes to run without planning.
Follow these rules.
Never edit an applied migration
Once a migration has been applied in a shared environment, consider it immutable.
Suppose migration 1 created restaurants, but you now realise it is missing an index.
Do not modify migration 1 and expect production databases to notice.
Create migration 2 that adds the index.
The existing migration history must remain reproducible.
Use expand and contract for breaking changes
Consider renaming a column from name to restaurant_name.
Dropping the old column and adding the new one in a single deployment can break the currently running application.
Instead, use an expand-and-contract approach:
- Expand: Add the new column without removing the old one.
- Deploy: Update application code to support the new schema. Depending on the transition, both columns may need to be written.
- Backfill: Copy existing values into the new column.
- Switch: Make the application use the new column.
- Contract: After old application instances are gone and compatibility is no longer required, remove the old column in a later migration.
This makes schema changes compatible with rolling deployments.
Be careful with large-table indexes
Adding an index to a large production table can be expensive.
InnoDB supports online DDL operations, which can allow concurrent reads and writes while certain schema changes execute.
For a supported operation, you may explicitly request:
ALTER TABLE restaurants
ADD INDEX idx_rest_name (name),
ALGORITHM=INPLACE,
LOCK=NONE;Here:
ALGORITHM=INPLACErequests an in-place operation rather than a table-copy operation.LOCK=NONErequests concurrent reads and writes during the operation.
These options are not universally supported for every operation or table configuration. MySQL will reject the request if the requested combination is unsupported.
Even an online operation consumes resources and can affect performance. Test it with representative data and plan large production changes carefully.
Where migrations run
Migrations are not just a local development command. They are part of the application's deployment lifecycle.
There are three important places where they should run.
1. Locally
When developing a feature, apply migrations through:
make migrateYour local MySQL database then matches the schema expected by your Go code.
2. In CI
Before running integration tests, CI should:
- Start a clean MySQL 8.4 instance.
- Apply all migrations.
- Seed the required data.
- Execute tests against the migrated database.
This ensures migrations work from a fresh environment rather than only on a developer's existing database.
3. During deployment
Run migrations as a separate deployment step before deploying application code that depends on the new schema.
The deployment process should ensure that migration failures prevent incompatible application changes from being rolled out.
For changes using expand-and-contract, the older application version must remain compatible with the expanded schema until the transition is complete.
Knowledge assessment
Why should a production database schema change be represented by a versioned migration file rather than executed manually?
Practical applications
Exercise 2.3: Write the restaurant and menu migrations
You'll create:
db/migrations/0001_restaurants.up.sql
db/migrations/0001_restaurants.down.sqlYour up migration will create the six tables from Lesson 2.1:
restaurantsitemsitem_sizesoption_groupsoptionsoption_prices
You'll define their column types, primary keys, composite keys, foreign keys, and indexes.
Your down migration will remove those tables in reverse dependency order.
You'll then apply the migration locally using make migrate, inspect the resulting schema and migration version, roll it back using down 1, and apply it again.
The objective is to demonstrate that you can take a database schema from an empty state to the required structure and safely reverse that change.
By the end, you should be comfortable treating database schema changes as versioned application code rather than a collection of manual SQL operations.
References
Everything above is explained on this page; these are where it comes from (golang-migrate v4, MySQL 8.4).