49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
// InitDB opens a SQLite connection and configures PRAGMAs per review-resolutions #28 and #45.
|
|
//
|
|
// modernc.org/sqlite is a pure-Go driver (CGO_ENABLED=0) — acceptable write-performance
|
|
// tradeoff for a personal tool. To switch to mattn/go-sqlite3 (CGO), just change the
|
|
// import and driver name; the interface stays the same.
|
|
func InitDB(path string) (*sqlx.DB, error) {
|
|
dir := filepath.Dir(path)
|
|
if dir != "" && dir != "." {
|
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
return nil, fmt.Errorf("create db directory: %w", err)
|
|
}
|
|
}
|
|
|
|
dsn := fmt.Sprintf("file:%s?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)", path)
|
|
db, err := sqlx.Connect("sqlite", dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open sqlite: %w", err)
|
|
}
|
|
|
|
// Single connection avoids "database is locked" under concurrent writes.
|
|
// WAL mode allows readers to proceed while a write is in progress.
|
|
db.SetMaxOpenConns(1)
|
|
|
|
for _, pragma := range []string{
|
|
"PRAGMA journal_mode = WAL",
|
|
"PRAGMA busy_timeout = 5000",
|
|
"PRAGMA foreign_keys = ON",
|
|
"PRAGMA synchronous = NORMAL",
|
|
} {
|
|
if _, err := db.Exec(pragma); err != nil {
|
|
db.Close()
|
|
return nil, fmt.Errorf("exec %s: %w", pragma, err)
|
|
}
|
|
}
|
|
|
|
return db, nil
|
|
}
|