Devpill #4 - Database migrations with Migrate

Published: (December 6, 2025 at 07:47 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Cover image for Devpill #4 - Database migrations with Migrate

Install

# download it
curl -L https://github.com/golang-migrate/migrate/releases/download/v4.17.0/migrate.linux-amd64.tar.gz | tar xvz

# copy it to Go path bin
cp -r migrate $GOPATH/bin/migrate

# if migrate command does not work, add the following lines to ~/.bashrc
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

Create base files

This command creates two files:

  • init.up.sql – contains the SQL commands that apply the migration.
  • init.down.sql – contains the SQL commands that revert the migration.
# creating the init up and down files
migrate create -ext=sql -dir=db/migrations -seq init

Execute Migration

# apply the up migration
migrate -path=db/migrate -database "postgres://myuser:mypassword@localhost:5432/databaseName?sslmode=disable" -verbose up

# revert the migration (run the down file)
migrate -path=db/migrate -database "postgres://myuser:mypassword@localhost:5432/devices-api?sslmode=disable" -verbose down
Back to Blog

Related posts

Read more »