panel/cmd/migrate.go

67 lines
1.4 KiB
Go
Raw Normal View History

2024-11-06 21:18:14 +01:00
/*
Package cmd
Copyright © 2024 Shane C. <shane@scaffoe.com>
*/
package cmd
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/spf13/cobra"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/migrate"
"log"
"omnibill.net/omnibill/migrations"
"omnibill.net/omnibill/shared"
)
// migrateCmd represents the migrate command
var migrateCmd = &cobra.Command{
Use: "migrate",
Short: "Migrate the db to the most recent version available",
Run: func(cmd *cobra.Command, args []string) {
dsn := shared.GetPostgresURI()
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
log.Fatalln(err)
}
pool, err := pgxpool.NewWithConfig(context.Background(), config)
if err != nil {
log.Fatalln(err)
}
sqldb := stdlib.OpenDBFromPool(pool)
db := bun.NewDB(sqldb, pgdialect.New())
migrator := migrate.NewMigrator(db, migrations.Migrations)
ctx := context.Background()
if err := migrator.Init(ctx); err != nil {
log.Fatalln(err)
}
if err := migrator.Lock(ctx); err != nil {
log.Fatalln(err)
}
defer migrator.Unlock(ctx)
group, err := migrator.Migrate(ctx)
if err != nil {
log.Fatalln(err)
}
if group.IsZero() {
fmt.Printf("there are no new migrations to run (database is up to date)\n")
return
}
fmt.Printf("migrated to %s\n", group)
},
}
func init() {
rootCmd.AddCommand(migrateCmd)
}