Documentation
¶
Overview ¶
Package sqlite provides a pure-Go SQLite client with lifecycle management, health checks, and unit-of-work transaction support for Einherjar applications.
Overview ¶
New returns a Component that manages a database/sql connection pool, satisfies the lifecycle.Component lifecycle hooks (OnInit, OnStart, OnStop), and implements observability.Checkable with critical priority.
NewUnitOfWork wraps multiple repository operations in a single serialized transaction via context injection — no transaction object is passed between functions. Write transactions are serialized through an internal mutex to prevent SQLITE_BUSY errors under concurrent goroutines.
Lifecycle Registration ¶
db := sqlite.New(logger, cfg) launcher.Register(db) health.Register(db)
Querying ¶
Repository code receives a Provider or Executor and calls Provider.GetExecutor to obtain the active transaction (if inside a UnitOfWork) or the connection pool:
exec := db.GetExecutor(ctx)
row := exec.QueryRowContext(ctx, "SELECT id FROM users WHERE email = ?", email)
if err := row.Scan(&id); err != nil {
return db.HandleError(err) // maps sql.ErrNoRows → ErrNotFound, etc.
}
Unit of Work ¶
NewUnitOfWork wraps operations in a single serialized write transaction. The transaction is injected into the context; Provider.GetExecutor returns it automatically.
uow := sqlite.NewUnitOfWork(logger, db)
err := uow.Do(ctx, func(ctx context.Context) error {
exec := db.GetExecutor(ctx) // returns active Tx
_, err := exec.ExecContext(ctx, "INSERT INTO orders ...")
return err
})
Error Handling ¶
HandleError translates database/sql and SQLite error codes into typed xerrors values. Call it at every point where a database error is first observed:
if err := row.Scan(&out); err != nil {
return db.HandleError(err)
}
Mapped codes:
- sql.ErrNoRows → ErrNotFound
- SQLITE_CONSTRAINT_UNIQUE (2067) → ErrAlreadyExists
- SQLITE_CONSTRAINT_PRIMARYKEY (1555) → ErrAlreadyExists
- SQLITE_CONSTRAINT_FOREIGNKEY (787) → ErrInvalidInput
- all others → ErrInternal
Configuration ¶
All fields are read from environment variables with the EINHERJAR_SQLITE_* prefix:
- EINHERJAR_SQLITE_PATH (required) — file path or ":memory:"
- EINHERJAR_SQLITE_MAX_OPEN_CONNS — default: 1
- EINHERJAR_SQLITE_MAX_IDLE_CONNS — default: 1
- EINHERJAR_SQLITE_PRAGMAS — default: "?_journal=WAL&_timeout=5000&_fk=true"
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HandleError ¶
HandleError maps database/sql and SQLite errors to typed xerrors values. Returns nil when err is nil. Also available as Provider.HandleError.
Mapped codes:
- sql.ErrNoRows → ErrNotFound
- SQLITE_CONSTRAINT_UNIQUE (2067) → ErrAlreadyExists
- SQLITE_CONSTRAINT_PRIMARYKEY (1555)→ ErrAlreadyExists
- SQLITE_CONSTRAINT_FOREIGNKEY (787) → ErrInvalidInput
- all others → ErrInternal
Types ¶
type Component ¶
type Component interface {
lifecycle.Component
observability.Checkable
observability.Identifiable
Provider
}
Component bundles the full sqlite capability: lifecycle management, health reporting, and the database Provider interface. Register with launcher and health before starting.
type Config ¶
type Config struct {
// Path is the SQLite file path. Use ":memory:" for in-memory databases.
Path string `env:"EINHERJAR_SQLITE_PATH,required"`
MaxOpenConns int `env:"EINHERJAR_SQLITE_MAX_OPEN_CONNS" envDefault:"1"`
MaxIdleConns int `env:"EINHERJAR_SQLITE_MAX_IDLE_CONNS" envDefault:"1"`
// Pragmas are appended to the DSN as query parameters.
// Default enables WAL journal mode, 5-second busy timeout, and FK enforcement.
Pragmas string `env:"EINHERJAR_SQLITE_PRAGMAS" envDefault:"?_journal=WAL&_timeout=5000&_fk=true"`
}
Config holds SQLite connection settings. Path is required; all other fields have production-safe defaults via DefaultConfig.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with all optional fields set to production-safe defaults. Callers must supply Path.
type Executor ¶
type Executor interface {
// ExecContext executes a query that returns no rows.
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
// QueryContext executes a query that returns rows.
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// QueryRowContext executes a query that returns at most one row.
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
Executor is the shared query interface for both the connection pool and an active transaction. Repository code accepts Executor so it works identically inside and outside a UnitOfWork.
type Provider ¶
type Provider interface {
// GetExecutor returns the active transaction injected by [UnitOfWork] if one
// is present in ctx, otherwise returns the connection pool.
GetExecutor(ctx context.Context) Executor
// Begin starts a new transaction.
Begin(ctx context.Context) (Tx, error)
// Ping verifies that the database connection is alive.
Ping(ctx context.Context) error
// HandleError maps a database/sql or SQLite error to a typed [xerrors] value.
// Call this at every point where a database error is first observed.
HandleError(err error) error
}
Provider is the database access interface consumed by repositories and services. All methods are safe for concurrent use.
type Tx ¶
type Tx interface {
Executor
// Commit commits the transaction.
Commit() error
// Rollback rolls back the transaction. Safe to call after Commit.
Rollback() error
}
Tx extends Executor with commit and rollback. Obtained via Provider.Begin when manual transaction control is needed. Prefer UnitOfWork for the common case of a single transactional unit.
Note: Commit and Rollback accept no context argument — this matches the database/sql limitation. The underlying *sql.Tx does not support context cancellation on Commit or Rollback.
type UnitOfWork ¶
type UnitOfWork interface {
// Do begins a transaction, calls fn with the enriched context, and commits
// on success or rolls back on error. The original fn error is always returned
// when fn fails, regardless of the rollback outcome.
Do(ctx context.Context, fn func(ctx context.Context) error) error
}
UnitOfWork wraps a set of repository operations in a single serialized database transaction. The transaction is injected into the context; Provider.GetExecutor returns it automatically so repository code requires no changes to participate.
Write transactions are serialized through a mutex to prevent SQLITE_BUSY errors. Pass the result of New to NewUnitOfWork to enable serialization.
func NewUnitOfWork ¶
func NewUnitOfWork(logger logging.Logger, client Provider) UnitOfWork
NewUnitOfWork returns a UnitOfWork backed by the given client. When client is the result of New, write transactions are serialized through an internal mutex to prevent SQLITE_BUSY errors.