Skip to content

Commit 1d803ea

Browse files
committed
check file & db state for healthcheck
1 parent bd0f312 commit 1d803ea

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

core/utils.go

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212
"time"
1313

1414
"github.com/skip2/go-qrcode"
15+
"gorm.io/driver/sqlite"
16+
"gorm.io/gorm"
1517
)
1618

1719
// Make unique titles
@@ -114,15 +116,33 @@ func HealthCheck(w http.ResponseWriter, r *http.Request) {
114116
statusCode := http.StatusOK
115117
status, dbStatus := "ok", "ok"
116118

117-
sqlDB, err := db.DB.DB()
118-
if err != nil {
119-
statusCode = http.StatusInternalServerError
120-
status = "error"
121-
dbStatus = "connection_error"
122-
} else if err := sqlDB.Ping(); err != nil {
119+
if db.DB == nil {
120+
// DB not initialized
123121
statusCode = http.StatusInternalServerError
124122
status = "error"
125-
dbStatus = "unreachable"
123+
dbStatus = "missing_file"
124+
} else {
125+
// Check DB file exists
126+
if _, err := os.Stat(db.DBPath); os.IsNotExist(err) {
127+
statusCode = http.StatusInternalServerError
128+
status = "error"
129+
dbStatus = "missing_file"
130+
} else {
131+
// Open a new connection to check integrity
132+
tmpDB, err := gorm.Open(sqlite.Open(db.DBPath), &gorm.Config{})
133+
if err != nil {
134+
statusCode = http.StatusInternalServerError
135+
status = "error"
136+
dbStatus = "corrupted"
137+
} else {
138+
var result string
139+
if err := tmpDB.Raw("PRAGMA quick_check").Scan(&result).Error; err != nil || result != "ok" {
140+
statusCode = http.StatusInternalServerError
141+
status = "error"
142+
dbStatus = "corrupted"
143+
}
144+
}
145+
}
126146
}
127147

128148
w.Header().Set("Content-Type", "application/json")

db/init.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
)
1313

1414
var DB *gorm.DB
15+
var DBPath string
1516

1617
func Init() {
1718
var err error
@@ -60,4 +61,7 @@ func Init() {
6061

6162
// Silence verbose GORM logs
6263
DB.Logger = logger.Default.LogMode(logger.Silent)
64+
65+
// Check file for health checks
66+
DBPath = dbPath
6367
}

0 commit comments

Comments
 (0)