Documentation
¶
Overview ¶
Package sql wraps github.com/jmoiron/sqlx with the lifecycle contract used across core: typed Config, functional Options, Shutdown / Healthcheck, and an opt-in OpenTelemetry instrumentation pipeline.
The package also exposes a transaction Manager (see manager.go) that threads transaction state through context.Context and a small set of generic squirrel-friendly executors (see executor.go).
Typical usage:
db, err := sql.New(ctx, sql.Config{
DriverName: pgCfg.Driver(),
DataSource: pgCfg.DSN(),
},
sql.WithOtel(),
sql.WithMaxOpenConns(25),
)
if err != nil { log.Fatal(err) }
a := app.New()
a.Add(db) // registers Shutdown + Healthcheck
Index ¶
- func Exec(ctx context.Context, q Querier, qb squirrel.Sqlizer) (int64, error)
- func Get[T any](ctx context.Context, q Querier, qb squirrel.Sqlizer) (T, error)
- func Select[T any](ctx context.Context, q Querier, qb squirrel.Sqlizer) ([]T, error)
- type Config
- type DB
- func (db *DB) BeginTx(ctx context.Context, opts *stdsql.TxOptions) (Tx, error)
- func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error)
- func (db *DB) GetContext(ctx context.Context, dest any, query string, args ...any) error
- func (db *DB) Healthcheck(ctx context.Context) error
- func (db *DB) SelectContext(ctx context.Context, dest any, query string, args ...any) error
- func (db *DB) Shutdown(_ context.Context) error
- func (db *DB) Unwrap() *sqlx.DB
- type DBManager
- type Manager
- type Option
- type Querier
- type Tx
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Config ¶ added in v1.3.0
type Config struct {
// DriverName is the database/sql driver name (e.g., "postgres", "mysql").
// Typically obtained from a postgres.Config via .Driver().
DriverName string
// DataSource is the driver-specific connection string. Typically
// obtained from a postgres.Config via .DSN().
DataSource string
}
Config describes a single SQL database to connect to. Plain fields, no struct tags — consumer apps map their viper keys to fields explicitly inside their own config.NewConfig().
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB wraps a *sqlx.DB and provides Querier semantics, transaction support, and lifecycle conformance. Implements lifecycle.Resource and lifecycle.Healthchecker.
Replaces the v1 DBConn type. The interface that was also called DB has been removed — use *sql.DB directly, or define your own narrow interface in consuming code if you need to mock at the database boundary.
func New ¶ added in v1.3.0
New connects to the database, applies pool tuning options, optionally installs OpenTelemetry instrumentation, and verifies the connection.
Replaces the v1 NewDB and NewDBWithOTel constructors — pass WithOtel() for the latter behavior.
Returns an error if the connection fails. Callers should treat this as fatal during startup.
func NewFromSqlx ¶ added in v1.3.0
NewFromSqlx wraps an existing *sqlx.DB. Useful in tests with sqlmock.
The wrapper does not change the underlying *sqlx.DB's pool settings — if pool tuning is needed, configure it on the *sqlx.DB before calling.
func (*DB) BeginTx ¶
BeginTx starts a transaction. The returned Tx implements Querier so it can be passed to the generic executors (Get, Select, Exec) in this package.
func (*DB) ExecContext ¶ added in v1.3.0
ExecContext executes a non-result query (INSERT/UPDATE/DELETE).
func (*DB) GetContext ¶ added in v1.3.0
GetContext executes the query and scans the single result row into dest. See sqlx.DB.GetContext for semantics.
func (*DB) Healthcheck ¶ added in v1.3.0
Healthcheck pings the database. Implements lifecycle.Healthchecker.
Cheap (single PING) and respects ctx via PingContext.
func (*DB) SelectContext ¶ added in v1.3.0
SelectContext executes the query and scans every result row into the dest slice. See sqlx.DB.SelectContext for semantics.
func (*DB) Shutdown ¶ added in v1.3.0
Shutdown closes the underlying *sqlx.DB, releasing the connection pool. Implements lifecycle.Resource.
Idempotent and concurrent-safe: the close runs exactly once; every subsequent call returns the same result.
The ctx parameter is currently ignored — sqlx/database/sql's Close is synchronous and not context-aware. The signature matches lifecycle.Resource for uniform integration with app.App.
type DBManager ¶
type DBManager struct {
// contains filtered or unexported fields
}
DBManager is the default Manager implementation backed by a *DB.
func NewManager ¶
NewManager wraps a *DB in a transaction Manager.
func (*DBManager) GetQuerier ¶ added in v1.2.0
GetQuerier — see Manager.GetQuerier.
type Manager ¶
type Manager interface {
// WithTx runs callback inside a single transaction. The callback's ctx
// carries the transaction; subsequent GetQuerier(ctx) calls return the
// transaction's Querier. On error, the transaction is rolled back and
// the callback's error is returned. On success, the transaction is
// committed.
WithTx(ctx context.Context, callback func(context.Context) error) error
// GetQuerier returns the active transaction's Querier if ctx was
// produced by WithTx; otherwise returns the manager's underlying *DB.
GetQuerier(ctx context.Context) Querier
// HasTx reports whether ctx already carries a WithTx-controlled
// transaction. Leaf primitives that MUST run inside a caller-owned
// transaction (e.g. a ledger writer that pairs a balance update with an
// audit insert) can use it to fail fast instead of silently auto-
// committing each statement.
HasTx(ctx context.Context) bool
}
Manager is the transaction orchestration interface used by repositories that want to participate in WithTx-controlled transactions without owning the transaction lifetime themselves.
Repositories should call manager.GetQuerier(ctx) on every query — the returned Querier is either the active transaction (if WithTx wrapped the call chain) or the underlying *DB.
type Option ¶ added in v1.3.0
type Option func(*options)
Option configures a new DB.
func WithConnMaxIdleTime ¶ added in v1.3.0
WithConnMaxIdleTime sets the maximum amount of time a connection may be idle before it is closed. Default: 0 (no idle limit). Use to recycle connections that haven't been used recently (e.g., 5 minutes).
func WithConnMaxLifetime ¶ added in v1.3.0
WithConnMaxLifetime sets the maximum amount of time a connection may be reused. Default: 0 (connections reused forever). Use a finite value (e.g., 30 minutes) to encourage healthy rotation behind load balancers.
func WithLogger ¶ added in v1.3.0
WithLogger attaches a *slog.Logger used for lifecycle events. Defaults to slog.Default() when omitted.
func WithMaxIdleConns ¶ added in v1.3.0
WithMaxIdleConns sets the maximum number of idle connections kept in the pool. Default: database/sql's default (2). Should be ≤ MaxOpenConns.
func WithMaxOpenConns ¶ added in v1.3.0
WithMaxOpenConns sets the maximum number of open connections to the database. Default: database/sql's default (0 = unlimited). Recommended to set explicitly in production (typical values: 10-50).
func WithOtel ¶ added in v1.3.0
func WithOtel() Option
WithOtel enables OpenTelemetry instrumentation by routing the connection through otelsqlx, which produces a span per query with attributes for the SQL statement, driver name, and result/error status.
Uses the global tracer/meter providers — call otel.Setup and register the provider with app.App before constructing the DB so the providers are non-noop.
type Querier ¶
type Querier interface {
GetContext(ctx context.Context, dest any, query string, args ...any) error
SelectContext(ctx context.Context, dest any, query string, args ...any) error
ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error)
}
Querier is the minimal query interface implemented by both *DB and Tx. Generic executors (Get, Select, Exec in executor.go) accept a Querier so they work uniformly inside or outside a transaction.