diff --git a/{{cookiecutter.app_name}}/Makefile b/{{cookiecutter.app_name}}/Makefile index d5ccfe0..727bb47 100644 --- a/{{cookiecutter.app_name}}/Makefile +++ b/{{cookiecutter.app_name}}/Makefile @@ -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 @@ -39,7 +43,7 @@ dev: install-dependencies: go install github.com/cosmtrek/air@v1.43.0 - 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 diff --git a/{{cookiecutter.app_name}}/database/database.go b/{{cookiecutter.app_name}}/database/database.go index 6fc606f..a1cbcd6 100644 --- a/{{cookiecutter.app_name}}/database/database.go +++ b/{{cookiecutter.app_name}}/database/database.go @@ -2,6 +2,7 @@ package database import ( "fmt" + "os" {% if cookiecutter.use_logrus == "no" %}"log" {% endif %} @@ -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 { @@ -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 {