this should do it

This commit is contained in:
2025-10-14 22:35:11 +03:00
parent 54daf46d06
commit 356df3fc46
4 changed files with 103 additions and 6 deletions

View File

@@ -5,16 +5,29 @@ import (
"fmt"
"os"
"path/filepath"
"syscall"
_ "modernc.org/sqlite"
)
func OpenDB(path string) (*sql.DB, error) {
type DBConfig struct {
JournalMode string
Synchronous string
BusyTimeout int
}
func OpenDB(path string, config *DBConfig) (*sql.DB, error) {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create database directory: %w", err)
}
// Check if database file exists and get file info for diagnostics
var fileInfo os.FileInfo
if info, err := os.Stat(path); err == nil {
fileInfo = info
}
db, err := sql.Open("sqlite", path)
if err != nil {
return nil, fmt.Errorf("failed to open database: %w", err)
@@ -22,14 +35,46 @@ func OpenDB(path string) (*sql.DB, error) {
if err := db.Ping(); err != nil {
db.Close()
return nil, fmt.Errorf("failed to ping database: %w", err)
// Enhanced error diagnostics
diag := fmt.Sprintf("database path: %s", path)
if fileInfo != nil {
diag += fmt.Sprintf(", file size: %d bytes, mode: %s", fileInfo.Size(), fileInfo.Mode())
}
// Check directory permissions
if dirInfo, err := os.Stat(dir); err == nil {
diag += fmt.Sprintf(", dir mode: %s", dirInfo.Mode())
}
// Check if it's a file system issue
if pathErr, ok := err.(*os.PathError); ok {
if pathErr.Err == syscall.ENOSPC {
diag += ", filesystem full"
} else if pathErr.Err == syscall.EACCES {
diag += ", permission denied"
}
}
return nil, fmt.Errorf("failed to ping database: %w (%s)", err, diag)
}
// Set default config if not provided
if config == nil {
config = &DBConfig{
JournalMode: "DELETE",
Synchronous: "FULL",
BusyTimeout: 10000,
}
}
pragmas := []string{
"PRAGMA journal_mode=WAL",
fmt.Sprintf("PRAGMA journal_mode=%s", config.JournalMode),
"PRAGMA foreign_keys=ON",
"PRAGMA synchronous=NORMAL",
"PRAGMA busy_timeout=5000",
fmt.Sprintf("PRAGMA synchronous=%s", config.Synchronous),
fmt.Sprintf("PRAGMA busy_timeout=%d", config.BusyTimeout),
"PRAGMA temp_store=MEMORY",
"PRAGMA mmap_size=268435456",
}
for _, pragma := range pragmas {