Member-only story
How Golang DB migration tool work?
2 min readJan 28, 2022
migrate
Database migrations tool is written in Go. Use as CLI or import as a library.
The migration tool uses a schema_migrations table. One table exists for one DB.
mysql> select * from schema_migrations;
+---------+-------+
| version | dirty |
+---------+-------+
| 33 | 0 |
+---------+-------+
1 row in set (0.00 sec)
The command to apply all migrations to a DB would check-in schema_migrations
table and pick migrations after the version (for the current case – 34 and onwards).
migration upmigration down 33
The down
migration executes the down file for version 33 and updates the schema_migrations table.
Code
Migration files are read from 1..N if no version is specified.
migrate/migrate.go
// read reads either up or down migrations from source `from` to `to`.// Each migration is then written to the ret channel.// If an error occurs during reading, that error is written to the ret channel, too.// Once read is done reading…