hatch-surf/internal/store/db.go
Riley Zhang ceaf7f9fb5 test: add unit tests for handler and store packages
- Added TestSearchRequests for store package (0% → 100% coverage)
- Added TestOpenInMemory for store package Open function
- Added TestNewSQLiteRepoNilDB for error handling
- Added TestV1ReplayRequest for handler package (0% → 100% coverage)
- Added TestPrettyJSON and TestFormatTime for inspect helpers
- Added TestJoinPath for path joining utility
- Added TestHandleMockReturnsErrorOnInvalidJSON
- Added TestInspectReturnsHTMLErrorOnRepoFailure
- Added TestCaptureMissingEndpointID, TestV1CaptureRequestMissingEndpoint, TestV1ListRequestsMissingEndpoint

Coverage improvements:
- Handler: 77.1% → 82.2%
- Store: 61.1% → 82.2%

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-24 05:07:50 +02:00

42 lines
882 B
Go

package store
import (
"database/sql"
_ "embed"
"fmt"
_ "modernc.org/sqlite"
"os"
"path/filepath"
)
//go:embed schema.sql
var schemaSQL string
func Open(dbPath string) (Repository, error) {
if dbPath == "" {
dbPath = filepath.Join("data", "hatch.db")
}
dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, fmt.Errorf("store: create db dir %s: %w", dir, err)
}
conn, err := sql.Open("sqlite", dbPath+"?_journal_mode=WAL&_busy_timeout=5000")
if err != nil {
return nil, fmt.Errorf("store: open %s: %w", dbPath, err)
}
conn.SetMaxOpenConns(1)
if err := migrate(conn); err != nil {
conn.Close()
return nil, fmt.Errorf("store: migrate: %w", err)
}
return NewSQLiteRepo(conn)
}
func migrate(db *sql.DB) error {
_, err := db.Exec(schemaSQL)
if err != nil {
return fmt.Errorf("store/migrate: %w", err)
}
return nil
}