feat: environment specific database handling

Changes have been made to support environment specific database file handling. By introducing a new environment variable "DB_FILE", the application's runtime now reads the database file path from the environment. In addition, subdirectories will now be automatically created if they don't exist and more detailed error messages will be printed in case of a failure. Environment variable setup and project building instructions were also updated in the README file.
This commit is contained in:
Florian Sylvain
2023-08-13 04:34:30 +02:00
parent 64ecbc6995
commit 245bf2fbf4
3 changed files with 35 additions and 10 deletions
+11 -3
View File
@@ -6,6 +6,8 @@ import (
"github.com/glebarez/sqlite"
"go.uber.org/dig"
"gorm.io/gorm"
"os"
"path/filepath"
)
type LocalContainer struct {
@@ -48,10 +50,16 @@ func InitContainer() {
digContainer := dig.New()
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic(err)
dbName := os.Getenv("DB_FILE")
if err := os.MkdirAll(filepath.Dir(dbName), os.ModePerm); err != nil {
panic("Unable to create necessary subdirectories: " + err.Error())
}
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{})
if err != nil {
panic("Unable to open the database: " + err.Error())
}
_ = db.AutoMigrate(&models.Article{}, &models.User{})
_ = digContainer.Provide(func() *gorm.DB { return db })