2024-07-11 03:20:54 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-07-12 00:49:09 +00:00
|
|
|
"context"
|
2024-07-12 01:15:37 +00:00
|
|
|
"fmt"
|
2024-07-11 03:20:54 +00:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
2024-07-12 00:49:09 +00:00
|
|
|
func SetupDatabaseConnection(cmd *cobra.Command, args []string) {
|
|
|
|
dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT"))
|
|
|
|
|
|
|
|
db := NewDatabase(os.Getenv("DB_HOST"), dbPort)
|
2024-07-12 01:33:20 +00:00
|
|
|
err := db.Connect(os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"))
|
2024-07-12 00:49:09 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to connect to the database: %s", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd.SetContext(context.WithValue(cmd.Context(), "db", db))
|
|
|
|
}
|
|
|
|
|
2024-07-11 03:20:54 +00:00
|
|
|
var cli = &cobra.Command{
|
|
|
|
Use: "cobble",
|
|
|
|
Short: "Cobble is a simple SQL migration utility.",
|
|
|
|
}
|
|
|
|
|
|
|
|
var up = &cobra.Command{
|
2024-07-12 00:49:09 +00:00
|
|
|
Use: "up",
|
|
|
|
Short: "Applies migrations",
|
|
|
|
PreRun: SetupDatabaseConnection,
|
2024-07-11 03:20:54 +00:00
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
2024-07-12 00:49:09 +00:00
|
|
|
db := cmd.Context().Value("db").(DB)
|
2024-07-11 03:20:54 +00:00
|
|
|
migrationRoot := args[0]
|
2024-07-12 00:24:57 +00:00
|
|
|
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
|
|
|
|
migrationHistory, _ := migrationGraph.GetLinearHistory()
|
2024-07-11 03:20:54 +00:00
|
|
|
for _, migration := range migrationHistory {
|
|
|
|
log.Printf("%s", migration.Name)
|
2024-07-12 01:16:44 +00:00
|
|
|
if err := migration.Apply(db); err != nil {
|
2024-07-11 03:20:54 +00:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-07-12 01:15:37 +00:00
|
|
|
var inspect = &cobra.Command{
|
|
|
|
Use: "inspect",
|
|
|
|
Short: "Prints the nth migration in the history",
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
migrationRoot := args[0]
|
|
|
|
migrationIndex, _ := strconv.Atoi(args[1])
|
|
|
|
|
|
|
|
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
|
|
|
|
migrationHistory, _ := migrationGraph.GetLinearHistory()
|
|
|
|
migration := migrationHistory[migrationIndex]
|
|
|
|
sql, _ := migration.Sql()
|
|
|
|
fmt.Printf("%s:\n%s", migration.Name, sql)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-07-11 03:20:54 +00:00
|
|
|
func main() {
|
|
|
|
cli.AddCommand(up)
|
2024-07-12 01:15:37 +00:00
|
|
|
cli.AddCommand(inspect)
|
2024-07-11 03:20:54 +00:00
|
|
|
|
|
|
|
if err := cli.Execute(); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|