Last active
January 27, 2016 23:29
-
-
Save bdittmer/573940d1e4d2842a68d1 to your computer and use it in GitHub Desktop.
Simple db miguration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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