Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

fix(db): correct modernc DSN (busy_timeout+WAL) + add DB error mapping

Cawlummcf21aa2de6c6
diff --git a/backend/db/sqlite.go b/backend/db/sqlite.go
index 2c0a390..06def90 100644
--- a/backend/db/sqlite.go
+++ b/backend/db/sqlite.go
@@ -21,7 +21,15 @@ func Connect() {
}
var err error
- DB, err = sql.Open("sqlite", dbPath+"?_journal_mode=DELETE&_foreign_keys=on&_busy_timeout=5000")
+ // modernc.org/sqlite uses _pragma=NAME(VALUE) DSN syntax. The old mattn-style
+ // params (_journal_mode=…&_busy_timeout=…) were silently ignored, leaving
+ // busy_timeout at 0 — so any contended lock failed instantly (a write racing
+ // other requests would 500). Fix:
+ // busy_timeout(5000): wait up to 5s for a lock instead of erroring.
+ // journal_mode(WAL): readers don't block the writer; fewer locks.
+ // synchronous(NORMAL): the safe, faster durability setting under WAL.
+ // foreign_keys(on): keep cascade deletes working (DeleteAccount relies on it).
+ DB, err = sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(on)")
if err != nil {
log.Fatalf("failed to open database: %v", err)
}
diff --git a/backend/utils/dberr.go b/backend/utils/dberr.go
new file mode 100644
index 0000000..ba270eb
--- /dev/null
+++ b/backend/utils/dberr.go
@@ -0,0 +1,72 @@
+package utils
+
+import (
+ "database/sql"
+ "errors"
+ "log"
+
+ "github.com/gin-gonic/gin"
+ sqlite "modernc.org/sqlite"
+ sqlitelib "modernc.org/sqlite/lib"
+)
+
+// sqliteCode returns the SQLite result code for err, or 0 if err is not a
+// modernc SQLite error.
+func sqliteCode(err error) int {
+ var se *sqlite.Error
+ if errors.As(err, &se) {
+ return se.Code()
+ }
+ return 0
+}
+
+// IsLocked reports whether err is a transient SQLite lock (SQLITE_BUSY /
+// SQLITE_LOCKED), the kind of failure that is worth retrying rather than
+// surfacing as a domain error.
+func IsLocked(err error) bool {
+ switch sqliteCode(err) {
+ case sqlitelib.SQLITE_BUSY, sqlitelib.SQLITE_LOCKED:
+ return true
+ default:
+ return false
+ }
+}
+
+// IsUniqueViolation reports whether err is a UNIQUE/PRIMARY KEY constraint
+// violation, so callers can distinguish a genuine duplicate from any other
+// write failure.
+func IsUniqueViolation(err error) bool {
+ switch sqliteCode(err) {
+ case sqlitelib.SQLITE_CONSTRAINT_UNIQUE, sqlitelib.SQLITE_CONSTRAINT_PRIMARYKEY:
+ return true
+ default:
+ return false
+ }
+}
+
+// DBError maps a database error to an HTTP response and reports whether it wrote
+// one. It deliberately ignores nil and sql.ErrNoRows: "no rows" means something
+// different per endpoint (401, 404, an empty 200), so each caller handles that
+// itself before delegating the rest here:
+//
+// err := db.DB.QueryRow(...).Scan(...)
+// if err == sql.ErrNoRows { utils.NotFound(c, "..."); return }
+// if utils.DBError(c, err) { return }
+//
+// A locked database becomes a 503 the client can retry; anything else is a
+// logged 500. Both lock and unexpected errors are logged so a "database is
+// locked" incident is visible in the server logs instead of masquerading as a
+// bad login or a duplicate email.
+func DBError(c *gin.Context, err error) bool {
+ if err == nil || errors.Is(err, sql.ErrNoRows) {
+ return false
+ }
+ if IsLocked(err) {
+ log.Printf("db locked on %s %s: %v", c.Request.Method, c.Request.URL.Path, err)
+ ServiceUnavailable(c, "the database is busy, please try again in a moment")
+ return true
+ }
+ log.Printf("db error on %s %s: %v", c.Request.Method, c.Request.URL.Path, err)
+ InternalError(c)
+ return true
+}
diff --git a/backend/utils/dberr_test.go b/backend/utils/dberr_test.go
new file mode 100644
index 0000000..dd74f09
--- /dev/null
+++ b/backend/utils/dberr_test.go
@@ -0,0 +1,121 @@
+package utils
+
+import (
+ "database/sql"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ _ "modernc.org/sqlite"
+)
+
+func testCtx() (*gin.Context, *httptest.ResponseRecorder) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodGet, "/x", nil)
+ return c, w
+}
+
+// uniqueErr returns a real modernc UNIQUE-constraint error.
+func uniqueErr(t *testing.T) error {
+ t.Helper()
+ d, err := sql.Open("sqlite", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ if _, err := d.Exec(`CREATE TABLE t (x TEXT UNIQUE)`); err != nil {
+ t.Fatal(err)
+ }
+ d.Exec(`INSERT INTO t VALUES ('a')`)
+ _, err = d.Exec(`INSERT INTO t VALUES ('a')`)
+ if err == nil {
+ t.Fatal("expected unique violation")
+ }
+ return err
+}
+
+// busyErr returns a real modernc SQLITE_BUSY error by writing from a second
+// connection while a write lock is held on the first.
+func busyErr(t *testing.T) error {
+ t.Helper()
+ path := t.TempDir() + "/busy.db"
+ a, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(0)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer a.Close()
+ if _, err := a.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY)`); err != nil {
+ t.Fatal(err)
+ }
+ tx, err := a.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tx.Exec(`INSERT INTO t (id) VALUES (1)`); err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+
+ b, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(0)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+ _, err = b.Exec(`INSERT INTO t (id) VALUES (2)`)
+ if err == nil {
+ t.Fatal("expected busy error")
+ }
+ return err
+}
+
+func TestClassifiers(t *testing.T) {
+ uniq := uniqueErr(t)
+ busy := busyErr(t)
+
+ if !IsUniqueViolation(uniq) {
+ t.Errorf("IsUniqueViolation(unique) = false, want true")
+ }
+ if IsLocked(uniq) {
+ t.Errorf("IsLocked(unique) = true, want false")
+ }
+ if !IsLocked(busy) {
+ t.Errorf("IsLocked(busy) = false, want true")
+ }
+ if IsUniqueViolation(busy) {
+ t.Errorf("IsUniqueViolation(busy) = true, want false")
+ }
+ if IsLocked(errors.New("plain")) || IsUniqueViolation(errors.New("plain")) {
+ t.Errorf("plain error should classify as neither")
+ }
+}
+
+func TestDBError(t *testing.T) {
+ busy := busyErr(t)
+
+ cases := []struct {
+ name string
+ err error
+ handled bool
+ wantCode int
+ }{
+ {"nil", nil, false, http.StatusOK}, // 200 = recorder default, nothing written
+ {"no rows", sql.ErrNoRows, false, http.StatusOK}, // caller's responsibility
+ {"locked", busy, true, http.StatusServiceUnavailable}, // retryable 503
+ {"generic", errors.New("boom"), true, http.StatusInternalServerError},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ c, w := testCtx()
+ if got := DBError(c, tc.err); got != tc.handled {
+ t.Fatalf("DBError handled = %v, want %v", got, tc.handled)
+ }
+ if w.Code != tc.wantCode {
+ t.Fatalf("status = %d, want %d", w.Code, tc.wantCode)
+ }
+ })
+ }
+}
diff --git a/backend/utils/response.go b/backend/utils/response.go
index 547163f..7e950dc 100644
--- a/backend/utils/response.go
+++ b/backend/utils/response.go
@@ -33,3 +33,14 @@ func InternalError(c *gin.Context) {
func ValidationError(c *gin.Context, err error) {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
}
+
+func Conflict(c *gin.Context, msg string) {
+ c.JSON(http.StatusConflict, gin.H{"error": msg})
+}
+
+// ServiceUnavailable signals a transient failure the client may retry, such as
+// a busy/locked database.
+func ServiceUnavailable(c *gin.Context, msg string) {
+ c.Header("Retry-After", "2")
+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": msg})
+}