This package allow run migrations on PostgreSQL database using Golang.
The package is compatible with library sqlx and driver pgx
The package require a Go version with modules support
go get github.com/maxchagin/pgmigrate
To run the migration in your project, you need to follow the steps:
- define a list migration files
- init migration in your application
- run migration
The ordering and direction of the migration files is determined by the filenames used for them. The package expects the filenames of migrations to have the format:
{version}_{title}.{action}.sql
Versioning with incrementing integers
1_create_table.up.sql - up migration
1_create_table.down.sql - down migration
Or timestamps resolution:
1627628025_create_table.up.sql - up migration
1627628025_create_table.down.sql - down migration
See more example
The following methods are supported:
Up()
- run all available migrations;
Down()
- down all migration;
Goto(version int)
- go to the specified migration;
Skip(steps []int)
- skip specified migrations;
Version()
- get the current version of the migration;
Clone project
cd work_dir
git clone https://github.com/maxchagin/pgmigrate
cd pgmigrate
Run PostgreSQL in docker
docker compose -f ./example/docker-compose.yml up
With sql
Go to example
cd ./example/sql
go run main.go
package main
import (
"log"
"github.com/maxchagin/pgmigrate"
)
func main() {
m, err := pgmigrate.New("./migrations", "localhost", "5432", "root", "test", "root", "disable", map[string]string{
"search_path": "test",
"application_name": "test",
})
if err != nil {
log.Fatalln(err)
}
// migrate up
err = m.Up()
if err != nil {
log.Fatalln(err)
}
}
Compatible with sqlx
Go to example
cd ./example/sqlx
go run main.go
package main
import (
"fmt"
"log"
"github.com/maxchagin/pgmigrate"
"github.com/jmoiron/sqlx"
)
func main() {
connStr := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s search_path=%s application_name=%s", "localhost", "5432", "root", "test", "root", "disable", "test", "test")
connSqlx, err := sqlx.Connect("postgres", connStr)
if err != nil {
log.Fatalln(err)
}
m := pgmigrate.CompatibleWithSqlx(
"./migrations",
&pgmigrate.Sqlx{
DB: connSqlx,
})
// migrate up
err = m.Up()
if err != nil {
log.Fatalln(err)
}
}
Compatible with pgx
Go to example
cd ./example/pgx
go run main.go
package main
import (
"context"
"fmt"
"log"
"github.com/maxchagin/pgmigrate"
"github.com/jackc/pgx/v4"
)
func main() {
connURL := fmt.Sprintf("postgres://%s:%s@%s:%s/%s", "root", "root", "localhost", "5432", "test")
config, err := pgx.ParseConfig(connURL)
if err != nil {
log.Fatalln(err)
}
config.RuntimeParams = map[string]string{
"search_path": "test",
"application_name": "test",
}
connPgx, err := pgx.ConnectConfig(context.Background(), config)
if err != nil {
log.Fatalln(err)
}
m := pgmigrate.CompatibleWithPgx(
"./migrations",
&pgmigrate.Pgx{
DB: connPgx,
})
// migrate up
err = m.Up()
if err != nil {
log.Fatalln(err)
}
}