sqlite

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

README

einherjar/db-sqlite

version license go health

Not every hall needs pillars that reach the sky. Sometimes what matters fits in a single room, carried wherever the warrior goes.

code.nochebuena.dev/einherjar/db-sqlite is the SQLite database component of the Einherjar framework. It uses the pure-Go modernc.org/sqlite driver (no CGO, cross-compilation works without a C toolchain), wraps database/sql behind a lifecycle-aware Component, and serializes writes through a mutex to prevent SQLITE_BUSY under concurrent goroutines. WAL mode is enabled by default.


Usage

Setup
import dbsqlite "code.nochebuena.dev/einherjar/db-sqlite"

db := dbsqlite.New(logger, dbsqlite.DefaultConfig())
launcher.Append(db)   // OnInit opens database; OnStop closes it
health.Register(db)   // BucketExists-style check; LevelDegraded
Querying
// GetExecutor returns the pool when called outside a UnitOfWork.
rows, err := db.GetExecutor(ctx).QueryContext(ctx, "SELECT id, name FROM users WHERE active = ?", true)
defer rows.Close()

var name string
err := db.GetExecutor(ctx).QueryRowContext(ctx, "SELECT name FROM users WHERE id = ?", id).Scan(&name)
Manual transaction
tx, err := db.Begin(ctx)
if err != nil {
    return err
}
defer tx.Rollback()

_, err = tx.ExecContext(ctx, "UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, fromID)
if err != nil {
    return err
}
return tx.Commit()

Note: Commit and Rollback do not accept a context — this is a database/sql limitation.

UnitOfWork wraps the transaction in context so every call to GetExecutor inside uow.Do automatically returns the active transaction. The internal write mutex prevents concurrent SQLITE_BUSY errors; only one goroutine can write at a time.

uow := dbsqlite.NewUnitOfWork(logger, db)

err := uow.Do(ctx, func(ctx context.Context) error {
    _, err := db.GetExecutor(ctx).ExecContext(ctx, "INSERT INTO orders (...) VALUES (...)", ...)
    return err
})

If the function returns an error, the transaction is rolled back. If it returns nil, the transaction is committed.

Error handling
if err := db.HandleError(someErr); err != nil {
    // SQLite error codes mapped to xerrors:
    // UNIQUE constraint failed → ErrAlreadyExists
    // FOREIGN KEY constraint   → ErrPreconditionFailed
    // NOT NULL constraint      → ErrInvalidInput
    // context.Canceled         → ErrCancelled
    // context.DeadlineExceeded → ErrDeadlineExceeded
}

HandleError is also available as a package-level function: dbsqlite.HandleError(err).


Environment variables

Variable Required Default Description
EINHERJAR_SQLITE_PATH Yes Path to the SQLite database file
EINHERJAR_SQLITE_MAX_OPEN_CONNS No 1 Maximum open connections (keep at 1 for writes)
EINHERJAR_SQLITE_MAX_IDLE_CONNS No 1 Maximum idle connections
EINHERJAR_SQLITE_PRAGMAS No ?_journal=WAL&_timeout=5000&_fk=true DSN pragma string

The default pragma string enables WAL mode (better concurrent reads), a 5-second busy timeout, and foreign key enforcement.


Dependency graph

contracts  (zero dependencies)
    ↑
  core
    ↑
db-sqlite  (contracts, core, modernc.org/sqlite)
    ↑
  your app

No CGO. Cross-compiles to any GOOS/GOARCH without a C toolchain.


Verification

cd db-sqlite/
go build ./...
go vet ./...
go test ./...
gofmt -l .

The hall is built before the warriors arrive. That is the only guarantee worth making.

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

func HandleError(err error) error

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

Component bundles the full sqlite capability: lifecycle management, health reporting, and the database Provider interface. Register with launcher and health before starting.

func New

func New(logger logging.Logger, cfg Config) Component

New returns a Component backed by the given configuration. The database is not opened until OnInit is called.

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.

func (Config) DSN

func (c Config) DSN() string

DSN constructs the SQLite connection string from the configuration.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL