libdbexec

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package libdbexec provides driver-agnostic interfaces (DBManager, Exec, QueryRower) for SQL access, implemented for PostgreSQL (lib/pq) and SQLite. WithTransaction pairs a CommitTx with a ReleaseTx meant for defer, and low-level driver errors are translated to package-level sentinels (ErrNotFound, ErrUniqueViolation, ErrDeadlockDetected, ...).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned by Scan when sql.ErrNoRows is encountered.
	ErrNotFound = errors.New("libdb: not found")

	// ErrTxFailed indicates a failure during transaction finalization (Commit or Rollback).
	ErrTxFailed = errors.New("libdb: transaction failed")

	// ErrMaxRowsReached indicates a table's configured maximum row count would be exceeded.
	ErrMaxRowsReached = errors.New("max row count reached")

	// ErrUniqueViolation corresponds to unique key constraint errors (e.g., PostgreSQL code 23505).
	ErrUniqueViolation = errors.New("libdb: unique constraint violation")
	// ErrForeignKeyViolation corresponds to foreign key constraint errors (e.g., PostgreSQL code 23503).
	ErrForeignKeyViolation = errors.New("libdb: foreign key violation")
	// ErrNotNullViolation corresponds to not-null constraint errors (e.g., PostgreSQL code 23502).
	ErrNotNullViolation = errors.New("libdb: not null constraint violation")
	// ErrCheckViolation corresponds to check constraint errors (e.g., PostgreSQL code 23514).
	ErrCheckViolation = errors.New("libdb: check constraint violation")
	// ErrConstraintViolation is a generic error for constraint violations not specifically mapped.
	ErrConstraintViolation = errors.New("libdb: constraint violation")

	// ErrDeadlockDetected corresponds to deadlock errors (e.g., PostgreSQL code 40P01).
	ErrDeadlockDetected = errors.New("libdb: deadlock detected")
	// ErrSerializationFailure corresponds to serialization failures (e.g., PostgreSQL code 40001).
	ErrSerializationFailure = errors.New("libdb: serialization failure")
	// ErrLockNotAvailable corresponds to lock acquisition failures (e.g., PostgreSQL code 55P03).
	ErrLockNotAvailable = errors.New("libdb: lock not available")
	// ErrQueryCanceled corresponds to query cancellation (e.g., PostgreSQL code 57014 or context cancellation).
	ErrQueryCanceled = errors.New("libdb: query canceled")

	// ErrDataTruncation corresponds to data truncation errors (e.g., PostgreSQL code 22001).
	ErrDataTruncation = errors.New("libdb: data truncation error")
	// ErrNumericOutOfRange corresponds to numeric overflow errors (e.g., PostgreSQL code 22003).
	ErrNumericOutOfRange = errors.New("libdb: numeric value out of range")
	// ErrInvalidInputSyntax corresponds to syntax errors in data representation (e.g., PostgreSQL code 22P02).
	ErrInvalidInputSyntax = errors.New("libdb: invalid input syntax")

	// ErrUndefinedColumn corresponds to referencing an unknown column (e.g., PostgreSQL code 42703).
	ErrUndefinedColumn = errors.New("libdb: undefined column")
	// ErrUndefinedTable corresponds to referencing an unknown table (e.g., PostgreSQL code 42P01).
	ErrUndefinedTable = errors.New("libdb: undefined table")
)

Predefined errors, checkable with errors.Is.

View Source
var ErrInvalidSQLiteOptions = errors.New("libdb: invalid sqlite options")

ErrInvalidSQLiteOptions reports a SQLiteOptions value that is rejected at construction.

Functions

func SQLiteBusyTimeout added in v0.38.0

func SQLiteBusyTimeout(d time.Duration) *time.Duration

SQLiteBusyTimeout returns a pointer to d for SQLiteOptions.BusyTimeout.

func SQLiteCacheKiB added in v0.38.0

func SQLiteCacheKiB(kib int) *int

SQLiteCacheKiB returns a CacheSize requesting approximately kib kibibytes of page cache. The argument is a magnitude; its sign is normalised away.

func SQLiteCachePages added in v0.38.0

func SQLiteCachePages(pages int) *int

SQLiteCachePages returns a CacheSize requesting that many cache pages. The argument is a magnitude; its sign is normalised away.

func SQLiteConns added in v0.38.0

func SQLiteConns(n int) *int

SQLiteConns returns a pointer to n for the pool limit fields.

func SetupLocalInstance

func SetupLocalInstance(ctx context.Context, dbName, dbUser, dbPassword string) (string, *postgres.PostgresContainer, func(), error)

SetupLocalInstance starts an ephemeral PostgreSQL container for tests. It returns a connection string, the container, and a cleanup func.

Types

type CommitTx

type CommitTx func(ctx context.Context) error

CommitTx commits a transaction; call only on the success path. Returns nil, a wrapped ErrTxFailed, or a context error if ctx is done before the attempt.

type DBManager

type DBManager interface {
	// WithoutTransaction returns an executor operating directly on the connection
	// group, outside any transaction; each operation may run on a different connection.
	WithoutTransaction() Exec

	// WithTransaction starts a transaction and returns an Exec bound to it, a
	// CommitTx, and a ReleaseTx (idempotent, safe for defer, rolls back if not
	// committed). onRollback handlers run only after a successful rollback and
	// must not touch the transaction.
	WithTransaction(ctx context.Context, onRollback ...func()) (Exec, CommitTx, ReleaseTx, error)

	// Close terminates the underlying database connection group.
	Close() error
}

DBManager is the main entry point for database interactions: obtaining executors and managing the connection lifecycle.

func NewPostgresDBManager

func NewPostgresDBManager(ctx context.Context, dsn string, schema string) (DBManager, error)

NewPostgresDBManager creates a DBManager for PostgreSQL, opening a connection group for dsn, pinging it, and optionally applying schema.

func NewSQLiteDBManager

func NewSQLiteDBManager(ctx context.Context, path string, schema string) (DBManager, error)

NewSQLiteDBManager creates a DBManager for the SQLite database at path, creating the parent directory if missing and applying schema on open.

func NewSQLiteDBManagerWithOptions added in v0.38.0

func NewSQLiteDBManagerWithOptions(ctx context.Context, path string, schema string, opts SQLiteOptions) (DBManager, error)

NewSQLiteDBManagerWithOptions creates a DBManager for SQLite tuned by opts, which is validated before anything is opened. A zero opts is equivalent to NewSQLiteDBManager.

type Exec

type Exec interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

	// QueryContext executes a query returning rows. Callers must check rows.Err() after iterating.
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

	// QueryRowContext always returns a non-nil QueryRower; errors surface from its Scan.
	QueryRowContext(ctx context.Context, query string, args ...any) QueryRower

	// DriverName returns the database driver name ("postgres", "sqlite").
	DriverName() string
}

Exec is the common interface for executing database operations, whether within a transaction or directly on the connection group. Implementations must translate driver errors into the package's Err* sentinels.

type QueryRower

type QueryRower interface {
	// Scan returns ErrNotFound if no row matched; other errors are translated too.
	Scan(dest ...any) error
}

QueryRower wraps *sql.Row so Scan errors (like sql.ErrNoRows) are translated consistently.

type ReleaseTx

type ReleaseTx func() error

ReleaseTx rolls back a transaction if it wasn't committed and is a no-op otherwise; idempotent and meant for defer.

type SQLiteJournalMode added in v0.38.0

type SQLiteJournalMode string

SQLiteJournalMode selects PRAGMA journal_mode. The zero value selects WAL.

const (
	SQLiteJournalDefault  SQLiteJournalMode = ""
	SQLiteJournalWAL      SQLiteJournalMode = "WAL"
	SQLiteJournalDelete   SQLiteJournalMode = "DELETE"
	SQLiteJournalTruncate SQLiteJournalMode = "TRUNCATE"
	SQLiteJournalPersist  SQLiteJournalMode = "PERSIST"
	SQLiteJournalMemory   SQLiteJournalMode = "MEMORY"
	SQLiteJournalOff      SQLiteJournalMode = "OFF"
)

SQLite journal modes. SQLiteJournalDefault resolves to SQLiteJournalWAL.

type SQLiteOptions added in v0.38.0

type SQLiteOptions struct {
	// JournalMode selects PRAGMA journal_mode. The zero value selects WAL.
	JournalMode SQLiteJournalMode

	// Synchronous selects PRAGMA synchronous. The zero value emits no pragma
	// and leaves SQLite's FULL default.
	Synchronous SQLiteSynchronous

	// BusyTimeout sets PRAGMA busy_timeout. Nil means the 5000ms default; a
	// pointer to zero fails contended writes immediately.
	BusyTimeout *time.Duration

	// DisableForeignKeys turns off PRAGMA foreign_keys. The zero value keeps
	// foreign keys enforced.
	DisableForeignKeys bool

	// CacheSize sets PRAGMA cache_size. Nil emits no pragma. Negative is a size
	// in KiB and positive a page count, so prefer SQLiteCacheKiB or
	// SQLiteCachePages over a bare literal.
	CacheSize *int

	// MaxOpenConns caps total open connections via sql.DB.SetMaxOpenConns. Nil
	// leaves the pool unbounded.
	MaxOpenConns *int

	// MaxIdleConns caps retained idle connections via sql.DB.SetMaxIdleConns.
	// Nil leaves Go's default of 2.
	MaxIdleConns *int

	// ConnMaxLifetime bounds how long a connection may be reused via
	// sql.DB.SetConnMaxLifetime. The zero value means unlimited.
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime bounds how long a connection may sit idle via
	// sql.DB.SetConnMaxIdleTime. The zero value means unlimited.
	ConnMaxIdleTime time.Duration
}

SQLiteOptions tunes a SQLite DBManager. The zero value is WAL journal mode, a 5000ms busy timeout, foreign keys enforced, no synchronous or cache_size pragma, and Go's default connection pool. Pointer fields distinguish unset (nil) from an explicit zero.

type SQLiteSynchronous added in v0.38.0

type SQLiteSynchronous string

SQLiteSynchronous selects PRAGMA synchronous. The zero value emits no pragma at all, leaving the driver default (FULL) in place.

const (
	SQLiteSynchronousDefault SQLiteSynchronous = ""
	SQLiteSynchronousOff     SQLiteSynchronous = "OFF"
	SQLiteSynchronousNormal  SQLiteSynchronous = "NORMAL"
	SQLiteSynchronousFull    SQLiteSynchronous = "FULL"
	SQLiteSynchronousExtra   SQLiteSynchronous = "EXTRA"
)

SQLite synchronous levels. SQLiteSynchronousDefault emits no pragma; SQLiteSynchronousNormal and SQLiteSynchronousOff require WAL journal mode.

Jump to

Keyboard shortcuts

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