DEV Community

Cover image for Devpill #4 - Database migrations with Migrate
Raul Paes Silva
Raul Paes Silva

Posted on

Devpill #4 - Database migrations with Migrate

1. 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 folliwng lines to ~./bashrc
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

```
Enter fullscreen mode Exit fullscreen mode

2. Command to create base files

This command will create 2 files:
init.up.sql = insert all sql commands to impact the database
init.down.sql = insert all sql commands to be executed to revert what was done in the up file

```
//creating the init down and up files
migrate create -ext=sql -dir=db/migrations -seq init
```
Enter fullscreen mode Exit fullscreen mode

3. Execute Migration:

    //executing init.up.sql
    migrate -path=db/migrate -database "postgres://myuser:mypassword@localhost:5432/databaseName?sslmode=disable" -verbose up

    //to revert
    //execute down file to revert what was done in the up file
    migrate -path=db/migrate -database "postgres://myuser:mypassword@localhost:5432/devices-api?sslmode=disable" -verbose down
Enter fullscreen mode Exit fullscreen mode

Top comments (0)