Skip to content

Commit

Permalink
auto create db if not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
cubny committed Feb 18, 2024
1 parent 9a45214 commit 814ac8f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
31 changes: 31 additions & 0 deletions internal/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"time"

Expand Down Expand Up @@ -55,6 +57,7 @@ func Init(ctx context.Context, runMigration bool) (*App, error) {
a := &App{ctx: ctx}

a.initConfig()
a.initDBFile()
a.initSQLClient()
if runMigration {
a.migrate()
Expand All @@ -73,6 +76,34 @@ func (a *App) ifNoError(fn func() *App) *App {
}
return fn()
}

func (a *App) initDBFile() *App {
return a.ifNoError(func() *App {
if _, err := os.Stat(a.cfg.DB.Path); os.IsNotExist(err) {
_, b, _, _ := runtime.Caller(0)
basePath := filepath.Dir(filepath.Dir(b))
log.Infof("base path: %s", basePath)
dbPath := filepath.Join(basePath, a.cfg.DB.Path)
log.Infof("db path: %s", dbPath)
dirName := filepath.Dir(dbPath)
log.Infof("dir name: %s", dirName)
if _, statErr := os.Stat(dirName); os.IsNotExist(statErr) {
mkdirErr := os.MkdirAll(dirName, os.ModePerm)
if mkdirErr != nil {
a.err = fmt.Errorf("failed to create db directory: %w", mkdirErr)
return a
}
}
_, createErr := os.Create(a.cfg.DB.Path)
if createErr != nil {
a.err = fmt.Errorf("failed to create db file: %w", createErr)
return a
}
}
return a
})
}

func (a *App) initSQLClient() *App {
return a.ifNoError(func() *App {
var sqlClient *sql.DB
Expand Down
1 change: 1 addition & 0 deletions internal/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func TestApp_StopOnError(t *testing.T) {

t.Run("initConfig", testFn(app.initConfig))
t.Run("initAPIServer", testFn(app.initAPIServer))
t.Run("initDBFile", testFn(app.initDBFile))
t.Run("initSQLClient", testFn(app.initSQLClient))
t.Run("migrate", testFn(app.migrate))
t.Run("initRepo", testFn(app.initRepo))
Expand Down

0 comments on commit 814ac8f

Please sign in to comment.