67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
// Package sqlite owns the SQLite implementation of application persistence.
|
|
package sqlite
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
_ "embed"
|
|
"fmt"
|
|
"strings"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
const driverName = "sqlite"
|
|
|
|
//go:embed schema.sql
|
|
var schema string
|
|
|
|
// Open opens a SQLite database and initializes a new database with the current schema.
|
|
func Open(ctx context.Context, path string) (*sql.DB, error) {
|
|
dsn := path
|
|
if path != ":memory:" && !strings.HasPrefix(path, "file:") {
|
|
dsn = "file:" + path
|
|
}
|
|
db, err := sql.Open(driverName, dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open sqlite: %w", err)
|
|
}
|
|
db.SetMaxOpenConns(1)
|
|
if err := configure(ctx, db); err != nil {
|
|
_ = db.Close()
|
|
return nil, err
|
|
}
|
|
if err := initialize(ctx, db); err != nil {
|
|
_ = db.Close()
|
|
return nil, err
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
func configure(ctx context.Context, db *sql.DB) error {
|
|
for _, statement := range []string{
|
|
"PRAGMA foreign_keys = ON",
|
|
"PRAGMA journal_mode = WAL",
|
|
"PRAGMA busy_timeout = 5000",
|
|
} {
|
|
if _, err := db.ExecContext(ctx, statement); err != nil {
|
|
return fmt.Errorf("configure sqlite: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func initialize(ctx context.Context, db *sql.DB) error {
|
|
var existing int
|
|
if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='system_state'").Scan(&existing); err != nil {
|
|
return fmt.Errorf("inspect sqlite schema: %w", err)
|
|
}
|
|
if existing == 1 {
|
|
return nil
|
|
}
|
|
if _, err := db.ExecContext(ctx, schema); err != nil {
|
|
return fmt.Errorf("initialize sqlite schema: %w", err)
|
|
}
|
|
return nil
|
|
}
|