Skip to content

Commit

Permalink
refactor automigration file
Browse files Browse the repository at this point in the history
  • Loading branch information
vinit717 committed May 22, 2024
1 parent 3712611 commit 255b5f7
Showing 1 changed file with 63 additions and 26 deletions.
89 changes: 63 additions & 26 deletions cmd/bun/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package migration

import (
"context"
"fmt"
"log"
"os"
Expand All @@ -14,36 +15,72 @@ import (
)

func RunMigrations() {
currentDir, err := os.Getwd()
if err != nil {
panic(err)
}

envFilePath := filepath.Join(currentDir, ".env")
utils.LoadEnv(envFilePath)
dsn := os.Getenv("DB_URL")

db, err := utils.SetupDBConnection(dsn)
if err != nil {
log.Fatalf("failed to connect to the database: %v", err)
os.Exit(1)
}
defer db.Close()

migrator := migrate.NewMigrator(db, migrations.Migrations)

err = migrator.Init(context.Background())
if err != nil {
log.Fatalf("failed to initialize migration tables: %v", err)
}

err = runMigrate(migrator)
if err != nil {
log.Fatalf("failed to run migrations: %v", err)
}
}

currentDir, err := os.Getwd()
if err != nil {
panic(err)
}

envFilePath := filepath.Join(currentDir, ".env")

utils.LoadEnv(envFilePath)
func runMigrate(migrator *migrate.Migrator) error {
ctx := context.Background()
if err := migrator.Lock(ctx); err != nil {
return err
}
defer migrator.Unlock(ctx) // nolint: errcheck

group, err := migrator.Migrate(ctx)
if err != nil {
return err
}
if group.IsZero() {
fmt.Println("there are no new migrations to run (database is up to date)")
return nil
}
fmt.Printf("migrated to %s\n", group)
return nil
}

dsn := os.Getenv("DB_URL")
func RegisterCLICommands() *cli.App {
dsn := os.Getenv("DB_URL")
db, err := utils.SetupDBConnection(dsn)
if err != nil {
log.Fatalf("failed to connect to the database: %v", err)
}
defer db.Close()

db, err := utils.SetupDBConnection(dsn)
if err != nil {
log.Fatalf("failed to connect to the database: %v", err)
os.Exit(1)
}
migrator := migrate.NewMigrator(db, migrations.Migrations)

app := &cli.App{
Name: "bun",
app := &cli.App{
Name: "bun",
Commands: []*cli.Command{
newDBCommand(migrator),
},
}

Commands: []*cli.Command{
newDBCommand(migrate.NewMigrator(db, migrations.Migrations)),
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}

defer db.Close()
return app
}

func newDBCommand(migrator *migrate.Migrator) *cli.Command {
Expand Down Expand Up @@ -193,4 +230,4 @@ func newDBCommand(migrator *migrate.Migrator) *cli.Command {
},
},
}
}
}

0 comments on commit 255b5f7

Please sign in to comment.