Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[109] Fix: Cannot run a project if it does not have any DB migration #114

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion {{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
ifeq ("$(wildcard $(database/migrations/.keep))","")
$(info NO migration files to run)
else
goose -dir database/migrations -table "migration_versions" postgres "$(DATABASE_URL)" up
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
23 changes: 20 additions & 3 deletions {{cookiecutter.app_name}}/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package database

import (
"fmt"
"os"
{% if cookiecutter.use_logrus == "no" %}"log"
{% endif %}

Expand All @@ -13,12 +14,15 @@ import (
"github.com/pressly/goose/v3"
"github.com/spf13/viper"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

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 +42,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 the database: %v", err)
}

log.Println("Database migrated 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
Loading