Enha: db use same connection to avoid db locking
This commit is contained in:
@ -2,6 +2,7 @@ package repos
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gralias/config"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
@ -20,6 +21,7 @@ type AllRepos interface {
|
||||
SettingsRepo
|
||||
CardMarksRepo
|
||||
InitTx(ctx context.Context) (context.Context, *sqlx.Tx, error)
|
||||
Close()
|
||||
}
|
||||
|
||||
type RepoProvider struct {
|
||||
@ -28,16 +30,31 @@ type RepoProvider struct {
|
||||
pathToDB string
|
||||
}
|
||||
|
||||
var RP AllRepos
|
||||
|
||||
func init() {
|
||||
cfg := config.LoadConfigOrDefault("")
|
||||
// sqlite3 has lock on write, so we need to have only one connection per whole app
|
||||
// https://github.com/mattn/go-sqlite3/issues/274#issuecomment-232942571
|
||||
RP = NewRepoProvider(cfg.DBPath)
|
||||
}
|
||||
|
||||
func NewRepoProvider(pathToDB string) *RepoProvider {
|
||||
db, err := sqlx.Connect("sqlite3", pathToDB)
|
||||
if err != nil {
|
||||
slog.Error("Unable to connect to database", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
_, err = db.Exec("PRAGMA foreign_keys = ON;")
|
||||
if err != nil {
|
||||
slog.Error("Unable to enable foreign keys", "error", err)
|
||||
os.Exit(1)
|
||||
stmts := []string{
|
||||
"PRAGMA foreign_keys = ON;",
|
||||
"PRAGMA busy_timeout=200;",
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
_, err = db.Exec(stmt)
|
||||
if err != nil {
|
||||
slog.Error("Unable to enable foreign keys", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
slog.Info("Successfully connected to database")
|
||||
// db.SetMaxOpenConns(2)
|
||||
@ -45,9 +62,7 @@ func NewRepoProvider(pathToDB string) *RepoProvider {
|
||||
DB: db,
|
||||
pathToDB: pathToDB,
|
||||
}
|
||||
|
||||
go rp.pingLoop()
|
||||
|
||||
return rp
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user