Skip to content

Commit

Permalink
[109] Check if migration file exist before running migration
Browse files Browse the repository at this point in the history
  • Loading branch information
carryall committed Sep 29, 2023
1 parent ad4b942 commit 4a0fb79
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
8 changes: 6 additions & 2 deletions {{cookiecutter.app_name}}/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ env-teardown:

db/migrate:
make wait-for-postgres
goose -dir database/migrations -table "migration_versions" postgres "$(DATABASE_URL)" up
ifneq ("$(wildcard $(database/migrations/.keep))","")
goose -dir database/migrations -table "migration_versions" postgres "$(DATABASE_URL)" up
else
$(info NO migration files to run)
endif

db/rollback:
make wait-for-postgres
Expand All @@ -39,7 +43,7 @@ dev:

install-dependencies:
go install github.com/cosmtrek/[email protected]
go install github.com/pressly/goose/v3/cmd/goose@v3.9.0
go install github.com/pressly/goose/v3/cmd/goose@v3.15.0
go install github.com/ddollar/forego@latest
go mod tidy
npm install
Expand Down
21 changes: 18 additions & 3 deletions {{cookiecutter.app_name}}/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (

var database *gorm.DB

const databaseDir = "database/migrations"

func InitDatabase(databaseURL string) {
db, err := gorm.Open(postgres.Open(databaseURL), &gorm.Config{})
if err != nil {
Expand All @@ -38,12 +40,25 @@ func migrateDB(db *gorm.DB) {
log.Fatalf("Failed to convert gormDB to sqlDB: %v", err)
}

err = goose.Up(sqlDB, "database/migrations", goose.WithAllowMissing())
if migrationFileExist() {
err = goose.Up(sqlDB, databaseDir, goose.WithAllowMissing())
if err != nil {
log.Fatalf("Failed to migrate database: %v", err)
}

log.Println("Migrated database successfully.")
} else {
log.Println("NO migration files")
}
}

func migrationFileExist() bool {
files, err := os.ReadDir(databaseDir)
if err != nil {
log.Fatalf("Failed to migrate database: %v", err)
log.Fatalf("Missing migration directory: %v", err)
}

log.Println("Migrated database successfully.")
return len(files) > 0 && files[0].Name() != ".keep"
}

func GetDB() *gorm.DB {
Expand Down

0 comments on commit 4a0fb79

Please sign in to comment.