Skip to content

Instantly share code, notes, and snippets.

@bdittmer
Last active January 27, 2016 23:29
Show Gist options
  • Save bdittmer/573940d1e4d2842a68d1 to your computer and use it in GitHub Desktop.
Save bdittmer/573940d1e4d2842a68d1 to your computer and use it in GitHub Desktop.
Simple db miguration
package main
import (
"database/sql"
"fmt"
"github.com/DavidHuie/gomigrate"
_ "github.com/lib/pq"
"os"
)
var builtAt string
var hash string
func main() {
migrationsDir := os.Getenv("MIGRATIONS_DIR")
dbUrl := os.Getenv("POSTGRES_URL")
if dbUrl == "" {
dbUrl = "postgres://localhost:5432/dbname"
}
if migrationsDir == "" {
migrationsDir = "./migrations"
}
if len(os.Args) == 1 {
fmt.Print("Expecting up or down\n")
return
}
direction := os.Args[1]
db, err := sql.Open("postgres", dbUrl)
defer db.Close()
if err != nil {
fmt.Errorf("Error opening postgres connection: %v", err)
return
}
m, err := gomigrate.NewMigrator(db, gomigrate.Postgres{}, migrationsDir)
if err != nil {
fmt.Errorf("Error creating migrator: %v", err)
return
}
if direction == "up" {
if err := m.Migrate(); err != nil {
fmt.Errorf("Error with up migration: %v", err)
return
}
} else if direction == "down" {
if err := m.Rollback(); err != nil {
fmt.Errorf("Error with down migration: %v", err)
return
}
} else {
fmt.Printf("Unknown command %s", direction)
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment