diff --git a/{{cookiecutter.app_name}}/Makefile b/{{cookiecutter.app_name}}/Makefile index d5ccfe0..3027f94 100644 --- a/{{cookiecutter.app_name}}/Makefile +++ b/{{cookiecutter.app_name}}/Makefile @@ -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 @@ -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..200882c 100644 --- a/{{cookiecutter.app_name}}/database/database.go +++ b/{{cookiecutter.app_name}}/database/database.go @@ -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 { @@ -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 {