How to create timestamped migration files with migrate tool – Golang

Golang has one of the strong libraries for Database migrations. Visit /migrate for more information for how to use migrate tool for migration execution in golang.

One of the many challenges that developers are facing is to create migration files – database migration scripts with the timestamped name of the file for up and down migrations. Well, migrate tool has an option to do it for you so no worries. Use below command to create timestamped up and down migration files.

migrate create

Below are options available:

create [-ext E] [-dir D] [-seq] [-digits N] [-format] NAME
Create a set of timestamped up/down migrations titled NAME, in directory D with extension E.
Use -seq option to generate sequential up/down migrations with N digits.
Use -format option to specify a Go time format string.

One thing to take note is -dir option has relative directory path, If it doesn’t exist, it would be created.

Example:

chintan@hw-61:~/go/src/project/setup/db$ migrate create -dir migrations -ext sql Initial_migrations

above command would create migrations up and down files under ~/go/src/project/setup/db/migrations folder with timestamp_Initial_migrations.up.sql and timestamp_Initial_migrations.down.sql

 

Leave a Reply