From 60bb492e56c8b2093ed71b30e871082abce57ce7 Mon Sep 17 00:00:00 2001 From: Pulkit Kathuria Date: Mon, 16 Dec 2024 13:23:16 +0900 Subject: [PATCH] fix: db singleton --- main.go | 2 +- pkg/database.go | 23 ++++++++++++++++------- pkg/log.go | 1 + pkg/watcher.go | 3 ++- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index 2365bfb..47f00d1 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,7 @@ var filePathsMutex sync.Mutex func main() { flags() - pkg.SetupLoggingStdout(f.LogLevel, f.Log) + pkg.SetupLoggingStdout(f.LogLevel, f.Log) // nolint: errcheck flag.VisitAll(func(f *flag.Flag) { slog.Info(f.Name, slog.String("value", f.Value.String())) }) diff --git a/pkg/database.go b/pkg/database.go index 627d3b2..f31934a 100644 --- a/pkg/database.go +++ b/pkg/database.go @@ -9,12 +9,21 @@ import ( _ "github.com/glebarez/go-sqlite" // nolint: revive ) +var ( + db *sql.DB +) + func InitDB(dbName string) (*sql.DB, error) { - slog.Info("Initializing database", "dbName", dbName) - db, err := sql.Open("sqlite", dbName) - if err != nil { - slog.Error("Error opening database", "error", err.Error()) - return nil, err + var err error + if db == nil { + slog.Info("Initializing database", "dbName", dbName) + db, err = sql.Open("sqlite", dbName) + if err != nil { + slog.Error("Error opening database", "error", err.Error()) + return nil, err + } + } else { + slog.Info("Database already initialized") } _, err = db.Exec(` @@ -38,8 +47,8 @@ func InitDB(dbName string) (*sql.DB, error) { slog.Error("Error creating plot table", "error", err.Error()) return nil, err } - db.SetMaxOpenConns(5) - db.SetMaxIdleConns(5) + db.SetMaxOpenConns(10) + db.SetMaxIdleConns(10) db.SetConnMaxLifetime(time.Hour) return db, nil diff --git a/pkg/log.go b/pkg/log.go index cf1c162..e531199 100644 --- a/pkg/log.go +++ b/pkg/log.go @@ -19,6 +19,7 @@ func SetupLoggingStdout(logLevel int, logFile string) error { } if logFile == "" { slog.SetDefault(slog.New(slogcolor.NewHandler(os.Stderr, opts))) + return nil } slog.SetDefault(slog.New(slogcolor.NewHandler(&lumberjack.Logger{ Filename: logFile, diff --git a/pkg/watcher.go b/pkg/watcher.go index adb26ee..96363cd 100644 --- a/pkg/watcher.go +++ b/pkg/watcher.go @@ -197,5 +197,6 @@ func (w *Watcher) saveState() error { } func (w *Watcher) Close() error { - return w.db.Close() + // return w.db.Close() + return nil }