dbx

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 12 Imported by: 7

Documentation

Overview

Package dbx provides SQL helpers on top of jmoiron/sqlx and database/sql: a pool and a transaction behind one Querier, query and exec helpers, transactions that open on a pool and join on a transaction, and bulk insert. It imports no driver: the presets dbx/pg (Postgres through pgx) and dbx/sqlite open a pool with a Classifier of their engine's errors, and New binds a pool of any other driver.

The query helpers return their result and classify a failure into the package sentinels (ErrDBNotFound, ErrDBDuplicatedEntry, ErrDBRetryable), so callers match them with errors.Is instead of inspecting driver codes. The sentinel wraps the driver error: errors.As still reaches it with its details. They log nothing: the caller handles the error once, and a preset records the query on a span.

Usage

db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "app"})
if err != nil {
    return err
}
if err := dbx.StatusCheck(ctx, db); err != nil {
    return err
}

// One row by key: no rows is ErrDBNotFound.
const get = `SELECT id, name FROM widgets WHERE id = :id`
w, err := dbx.NamedQueryOne[Widget](ctx, db, get, map[string]any{"id": id})
if errors.Is(err, dbx.ErrDBNotFound) {
    // the store returns its domain not-found error
}

// A list: no rows is an empty result, not an error.
const q = `SELECT id, name FROM widgets WHERE name = :name`
widgets, err := dbx.NamedQueryList[Widget](ctx, db, q, map[string]any{"name": "gadget"})

// A scalar.
n, err := dbx.QueryOne[int](ctx, db, `SELECT count(*) FROM widgets`)

// Postgres only: pass a slice as a single array parameter; pgx binds it
// as a Postgres array, so ANY(:ids) filters without expanding
// placeholders. On other databases use NamedQueryListUsingIn.
out, err := dbx.NamedQueryList[Widget](ctx, db,
    `SELECT * FROM widgets WHERE id = ANY(:ids)`,
    map[string]any{"ids": []int64{235, 401, 512}}, // slice -> one $1 -> int8[]
)

// Write inside a transaction.
err = dbx.WithinTran(ctx, log, db, func(tx *dbx.Tx) error {
    const ins = `INSERT INTO widgets (id, name) VALUES (:id, :name)`
    return dbx.NamedExec(ctx, tx, ins, w)
})
if errors.Is(err, dbx.ErrDBDuplicatedEntry) {
    // unique violation
}

Pool and transaction

A *DB is a pool, a *Tx a transaction; both are a Querier, which every helper takes. Only this package implements Querier. A *Tx has no Begin, Commit or Rollback: what is built over it — a store, a Core over that store — can only join it. So a store holds a Querier and has one constructor for both:

widgetdb.NewStore(log, db) // WithinTran opens a transaction
widgetdb.NewStore(log, tx) // WithinTran joins tx

Nothing goes through ctx: whether WithinTran opens or joins is decided by the type of the value passed in.

Errors

A Classifier maps the errors of one engine onto the sentinels; the presets ship one each, and a pool of another driver passes its own to New. Without a Classifier only ErrDBNotFound is recognized. ErrDBRetryable marks an error after which the whole transaction may run again; on Postgres a deadlock victim (40P01) and a serialization failure (40001).

Querying

Two families; the name tells the mode. Without a prefix a query takes no parameters and runs as written: it is not parsed for :name, so DDL, casts (::) and colons in literals pass through. The Named variants bind :name from a struct via its `db` tags or from a map[string]any; inside them write a cast as CAST(… AS …), since :: breaks the :name parsing.

  • Exec / NamedExec run a statement; ExecRowsAffected / NamedExecRowsAffected return the number of rows it changed.
  • QueryOne / NamedQueryOne scan the first row into a struct or a scalar T; no rows is ErrDBNotFound, and an error later in the result is returned.
  • QueryList / NamedQueryList scan every row into a []T; no rows is a nil slice and no error.
  • NamedQueryListUsingIn handles a query with an IN (:ids) clause: it expands the slice parameter (sqlx.In) and rebinds before running. An empty slice is an error.

What no rows means is decided where the meaning is known. A row by key is ErrDBNotFound, which the store turns into its domain not-found error. A list may be empty. The affected-row count means changed, not matched — MySQL without clientFoundRows counts an UPDATE to the same values as 0, a Postgres BEFORE trigger may skip a row — so the store that updates or deletes by key turns 0 into its not-found error, and other callers read the count as they need.

For an IN-style filter on Postgres, bind the slice as a single array parameter and match with ANY(:ids) (see Usage): pgx encodes []int64/[]string as a Postgres array, so the query text stays constant regardless of list length. ANY works on Postgres only; NamedQueryListUsingIn expands IN (:ids) on any database.

Transactions

WithinTran on a *DB opens a transaction: it commits when the function returns nil and rolls back on an error or a panic. An error the Classifier marks ErrDBRetryable rolls the transaction back in full, so WithinTran re-runs the function in a fresh transaction with a short exponential backoff (3 attempts) and only then returns the error. The function must therefore be safe to run more than once — keep side effects inside the transaction and do not mutate captured state between runs.

WithinTran on a *Tx joins it: the function runs in that transaction, and the WithinTran that opened it commits, rolls back or retries. A joined call is not a savepoint: if it wrote and failed, return its error, or half of its work commits.

Tran is a transaction over a set the domain declares — repositories, publishers, the Cores of other domains — built by a function from the transaction on every attempt:

tran := dbx.NewTran(log, db, func(tx *dbx.Tx) widget.Unit {
    return widget.Unit{Repo: widgetdb.NewStore(log, tx), Users: users(tx)}
})
err := tran.WithinTran(ctx, func(u widget.Unit) error { ... })

It satisfies the domain's interface with the same WithinTran method without an adapter. Over a *Tx it joins, so Trans nest.

UUID columns

database/sql scans and binds the standard uuid.UUID, and pgx and modernc.org/sqlite take it as is. A driver that converts arguments on its own, such as go-sql-driver/mysql, rejects it: a store that must run there holds UUID instead (sql.Null[UUID] for a nullable column) and converts at the core/db boundary:

type dbWidget struct {
    ID dbx.UUID `db:"id"`
}
row := dbWidget{ID: dbx.UUID(w.ID)} // core -> db
w.ID = uuid.UUID(row.ID)            // db -> core

Bind a lone UUID argument the same way: dbx.UUID(id). UUID binds through its string form, so on Postgres-only paths prefer uuid.UUID: a []UUID in ANY encodes about ten times slower.

Bulk writes

BulkInsert writes len(values)/len(columns) rows, splitting into batches that stay under Postgres's bind-parameter cap, with values laid out row-major. An optional conflictAction (e.g. "ON CONFLICT DO NOTHING") is appended verbatim.

Index

Constants

View Source
const DefaultStatusCheckTimeout = 30 * time.Second

DefaultStatusCheckTimeout bounds StatusCheck when it is called with a context that carries no deadline of its own (e.g. context.Background()). Without it a non-transient failure — wrong port, missing database, bad credentials, TLS mismatch — would retry forever and hang the caller silently. Pass a context.WithTimeout to choose a different bound.

Variables

View Source
var (
	ErrDBNotFound        = sql.ErrNoRows
	ErrDBDuplicatedEntry = errors.New("duplicated entry")
	ErrDBRetryable       = errors.New("retryable")
)

Sentinel errors returned by this package; match them with errors.Is. A Classifier wraps the driver error with ErrDBDuplicatedEntry or ErrDBRetryable, so errors.As still reaches it.

Functions

func BulkInsert

func BulkInsert(ctx context.Context, q Querier, table string, columns []string, values []any, conflictAction string) error

BulkInsert inserts len(values)/len(columns) rows into table in batches, each batch a single multi-row INSERT. conflictAction, if non-empty, is appended verbatim (e.g. "ON CONFLICT DO NOTHING"). values are laid out row-major: [r0c0, r0c1, r1c0, r1c1, ...].

The query is built with "?" markers and rebound to the driver's bind style via q.Rebind (sqlx), so it is engine-portable: Postgres gets "$1,$2,…", SQLite/ MySQL keep "?". No per-dialect placeholder handling is needed.

func Exec added in v0.14.0

func Exec(ctx context.Context, q Querier, query string) error

Exec runs a statement as written: it takes no parameters and is not parsed for :name, so DDL, casts (::) and colons in literals pass through.

func ExecRowsAffected added in v0.14.0

func ExecRowsAffected(ctx context.Context, q Querier, query string) (int64, error)

ExecRowsAffected is Exec that returns the number of rows the statement changed. The count means changed, not matched (MySQL without clientFoundRows counts an UPDATE to the same values as 0), so what 0 means is the caller's decision.

func NamedExec added in v0.14.0

func NamedExec(ctx context.Context, q Querier, query string, arg any) error

NamedExec runs a statement with :name parameters bound from arg, a struct with `db` tags or a map[string]any.

func NamedExecRowsAffected added in v0.14.0

func NamedExecRowsAffected(ctx context.Context, q Querier, query string, arg any) (int64, error)

NamedExecRowsAffected is NamedExec that returns the number of rows the statement changed; see ExecRowsAffected. A store that updates or deletes by key turns 0 into its own not-found error.

func NamedQueryList added in v0.14.0

func NamedQueryList[T any](ctx context.Context, q Querier, query string, arg any) ([]T, error)

NamedQueryList is QueryList for a query with :name parameters bound from arg.

func NamedQueryListUsingIn added in v0.14.0

func NamedQueryListUsingIn[T any](ctx context.Context, q Querier, query string, arg any) ([]T, error)

NamedQueryListUsingIn is NamedQueryList for a query with an IN (:ids) clause: it expands the slice parameters (sqlx.In) and rebinds the query for the driver. It is the portable form of ANY, which works on Postgres only. An empty slice is an error: guard it before the call.

func NamedQueryOne added in v0.14.0

func NamedQueryOne[T any](ctx context.Context, q Querier, query string, arg any) (T, error)

NamedQueryOne is QueryOne for a query with :name parameters bound from arg.

func QueryList added in v0.14.0

func QueryList[T any](ctx context.Context, q Querier, query string) ([]T, error)

QueryList runs a query as written (see Exec) and scans every row into a T, a struct with `db` tags or a scalar. No rows is a nil slice and no error.

func QueryOne added in v0.14.0

func QueryOne[T any](ctx context.Context, q Querier, query string) (T, error)

QueryOne runs a query as written (see Exec) and scans its first row into T, a struct with `db` tags or a scalar. No rows is ErrDBNotFound; an error later in the result is returned, not lost.

func StatusCheck

func StatusCheck(ctx context.Context, db *DB) error

StatusCheck pings the database, retrying until it is reachable or ctx is done.

On timeout it returns errors.Join(ctx.Err(), lastPingErr) rather than a bare "context deadline exceeded", so the real cause — connection refused, TLS failure, password authentication failed — is visible at the call site instead of being masked by the deadline.

If ctx has no deadline, DefaultStatusCheckTimeout is applied as a backstop so a persistent failure surfaces its error instead of hanging forever.

func WithinTran

func WithinTran(ctx context.Context, log *slog.Logger, q Querier, fn func(tx *Tx) error) error

WithinTran runs fn so that its statements commit or roll back together.

On a *DB it opens a transaction, commits it when fn returns nil and rolls it back on an error or a panic. An error the Classifier of the pool marks ErrDBRetryable rolls the transaction back in full, so WithinTran re-runs fn in a new one a few times (see retryBackoff) before returning the error: fn may run more than once, keep its side effects inside the transaction and no state between runs. log gets the retries and a failed rollback.

On a *Tx it joins: fn runs in that transaction, and nothing is committed, rolled back or retried here — the WithinTran that opened it does that. A joined call is not a savepoint: return its error.

Types

type Classifier added in v0.14.0

type Classifier interface {
	Classify(err error) error
}

Classifier wraps a driver error with the dbx sentinel it recognizes — fmt.Errorf("%w: %w", ErrDBDuplicatedEntry, err) — or returns err unchanged. The presets dbx/pg and dbx/sqlite ship one each; a pool of another driver implements it itself.

type DB added in v0.14.0

type DB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

DB is a pool bound to the Classifier of its engine.

func New added in v0.14.0

func New(db *sql.DB, driverName string, c Classifier) *DB

New binds a database/sql pool. driverName selects the sqlx bind style ("pgx", "sqlite3", "mysql"), not the registered driver. With a nil c only ErrDBNotFound is recognized.

type JSONSlice added in v0.6.0

type JSONSlice[T any] []T

JSONSlice adapts a Go slice to a Postgres JSONB column. skit runs pgx v5 in database/sql mode (via sqlx), where database/sql cannot scan a Postgres array (text[], int8[]) back into a Go slice — there is no sql.Scanner for a bare slice, so an array-valued column fails StructScan. Storing the slice as JSONB and (un)marshaling it here sidesteps that: a JSONSlice[T] field StructScans cleanly and binds as a named parameter, so the store still uses one row struct.

Use it as the db-model field type for any slice-valued column:

type dbAdvert struct {
    Photos dbx.JSONSlice[string] `db:"photos"`
}

backed by a column declared `photos JSONB NOT NULL DEFAULT '[]'::jsonb`.

func (*JSONSlice[T]) Scan added in v0.6.0

func (s *JSONSlice[T]) Scan(src any) error

Scan implements sql.Scanner: unmarshal the JSONB payload back into the slice. A SQL NULL and an empty payload both yield a nil slice.

func (JSONSlice[T]) Value added in v0.6.0

func (s JSONSlice[T]) Value() (driver.Value, error)

Value implements driver.Valuer: marshal the slice to JSON for the JSONB column. A nil slice is written as an empty JSON array, not SQL NULL, so a NOT NULL column with a '[]' default round-trips.

type Querier added in v0.14.0

type Querier interface {
	sqlx.ExtContext
	// contains filtered or unexported methods
}

Querier runs statements: a *DB on the pool, a *Tx in a transaction. Only this package implements it, so no other type decides whether WithinTran opens a transaction or joins one.

type Tran added in v0.14.0

type Tran[U any] struct {
	// contains filtered or unexported fields
}

Tran runs a function in one transaction over U, a set of repositories, publishers and Cores of other domains bound to that transaction. The domain declares

type Tran interface {
    WithinTran(ctx context.Context, fn func(u Unit) error) error
}

and the wiring passes NewTran(log, db, bind), which satisfies it without an adapter. A Tran over a *Tx joins that transaction, so Trans nest.

func NewTran added in v0.14.0

func NewTran[U any](log *slog.Logger, q Querier, bind func(tx *Tx) U) *Tran[U]

NewTran returns a Tran over q, a pool or a transaction. bind builds U from the transaction and nothing else: it runs on every attempt, so a re-run gets a fresh U over the new transaction.

func (*Tran[U]) WithinTran added in v0.14.0

func (t *Tran[U]) WithinTran(ctx context.Context, fn func(u U) error) error

WithinTran runs fn on bind(tx) as the package WithinTran does: over a *DB it opens the transaction, over a *Tx it joins it. fn may run more than once.

type Tx added in v0.14.0

type Tx struct {
	// contains filtered or unexported fields
}

Tx is a transaction opened by WithinTran. It has no Begin, Commit or Rollback: what is built over it can only join it, and the WithinTran that opened it ends it.

func (*Tx) BindNamed added in v0.14.0

func (t *Tx) BindNamed(query string, arg any) (string, []any, error)

BindNamed expands the :name parameters of query from arg.

func (*Tx) DriverName added in v0.14.0

func (t *Tx) DriverName() string

DriverName returns the sqlx driver name.

func (*Tx) ExecContext added in v0.14.0

func (t *Tx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext runs a statement that returns no rows.

func (*Tx) QueryContext added in v0.14.0

func (t *Tx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext runs a query that returns rows.

func (*Tx) QueryRowxContext added in v0.14.0

func (t *Tx) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row

QueryRowxContext runs a query that returns at most one row.

func (*Tx) QueryxContext added in v0.14.0

func (t *Tx) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)

QueryxContext runs a query that returns sqlx rows.

func (*Tx) Rebind added in v0.14.0

func (t *Tx) Rebind(query string) string

Rebind converts '?' placeholders to the bind style of the driver.

type UUID added in v0.12.0

type UUID uuid.UUID

UUID is a uuid.UUID that binds on any driver. database/sql scans and binds the standard uuid.UUID itself, and pgx and modernc.org/sqlite take it as is; a driver that converts arguments on its own, such as go-sql-driver/mysql, rejects it. UUID binds as the canonical string through driver.Valuer (a CHAR(36) column on MySQL) and scans the driver's text or 16-byte form, so a store that must run on such a driver keeps one row struct:

type dbAdvert struct {
    ID      dbx.UUID              `db:"id"`
    OwnerID sql.Null[dbx.UUID]    `db:"owner_id"` // nullable column
}

Convert at the core/db boundary with plain conversions: dbx.UUID(a.ID) and uuid.UUID(row.ID). A SQL NULL is a scan error; use sql.Null[dbx.UUID] for a nullable column.

func (*UUID) Scan added in v0.12.0

func (u *UUID) Scan(src any) error

Scan implements sql.Scanner: accept the textual form or the raw 16 bytes.

func (UUID) Value added in v0.12.0

func (u UUID) Value() (driver.Value, error)

Value implements driver.Valuer: bind the UUID as its canonical string.

Directories

Path Synopsis
Package pg opens a Postgres pool for dbx through the pgx driver, with query tracing, pool metrics and a Classifier of Postgres error codes.
Package pg opens a Postgres pool for dbx through the pgx driver, with query tracing, pool metrics and a Classifier of Postgres error codes.
Package sqlite opens a SQLite pool for dbx through a driver the caller registers, modernc.org/sqlite by default, with a Classifier of SQLite result codes.
Package sqlite opens a SQLite pool for dbx through a driver the caller registers, modernc.org/sqlite by default, with a Classifier of SQLite result codes.

Jump to

Keyboard shortcuts

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