refactor: setup database connection via prerun
This commit is contained in:
parent
40e9ccc61c
commit
e5e96c3de7
1 changed files with 20 additions and 13 deletions
33
cobble.go
33
cobble.go
|
@ -1,37 +1,44 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func SetupDatabaseConnection(cmd *cobra.Command, args []string) {
|
||||||
|
dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT"))
|
||||||
|
|
||||||
|
db := NewDatabase(os.Getenv("DB_HOST"), dbPort)
|
||||||
|
err := db.Connect(os.Getenv("DB_APP_USER"), os.Getenv("DB_APP_PASSWORD"), os.Getenv("DB_NAME"))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to connect to the database: %s", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd.SetContext(context.WithValue(cmd.Context(), "db", db))
|
||||||
|
}
|
||||||
|
|
||||||
var cli = &cobra.Command{
|
var cli = &cobra.Command{
|
||||||
Use: "cobble",
|
Use: "cobble",
|
||||||
Short: "Cobble is a simple SQL migration utility.",
|
Short: "Cobble is a simple SQL migration utility.",
|
||||||
}
|
}
|
||||||
|
|
||||||
var up = &cobra.Command{
|
var up = &cobra.Command{
|
||||||
Use: "up",
|
Use: "up",
|
||||||
Short: "Applies migrations",
|
Short: "Applies migrations",
|
||||||
|
PreRun: SetupDatabaseConnection,
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT"))
|
db := cmd.Context().Value("db").(DB)
|
||||||
|
|
||||||
db := NewDatabase(os.Getenv("DB_HOST"), dbPort)
|
|
||||||
err := db.Connect(os.Getenv("DB_APP_USER"), os.Getenv("DB_APP_PASSWORD"), os.Getenv("DB_NAME"))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Failed to connect to the database: %s", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
migrationRoot := args[0]
|
migrationRoot := args[0]
|
||||||
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
|
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
|
||||||
migrationHistory, _ := migrationGraph.GetLinearHistory()
|
migrationHistory, _ := migrationGraph.GetLinearHistory()
|
||||||
for _, migration := range migrationHistory {
|
for _, migration := range migrationHistory {
|
||||||
log.Printf("%s", migration.Name)
|
log.Printf("%s", migration.Name)
|
||||||
if err = migration.ApplyMigration(db); err != nil {
|
if err := migration.ApplyMigration(db); err != nil {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue