connsql

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: MIT Imports: 16 Imported by: 0

README

conn-sql

Postgres SQL resource for omcrgnt apps: DSN-only config, vinovest/sqlx, XSAM/otelsql, ctx-first API.

Driver import (application)

import _ "github.com/jackc/pgx/v5/stdlib"

Catalog

type catalog struct {
    DB *connsql.DB `ecfg:"DB"`
    Tx port.Transactor // wire: same *connsql.DB implements port.Transactor
}

Environment

Variable Description
CONN_SQL_DSN postgres://user:pass@host:5432/db?sslmode=disable
CONN_SQL_LABEL Resource label (otel / metrics)
CONN_SQL_POOL_MAX_OPEN Max open conns (default 10)
CONN_SQL_POOL_MAX_IDLE Max idle conns (default 5)
CONN_SQL_POOL_MAX_LIFETIME Conn max lifetime (default 30m)
CONN_SQL_POOL_MAX_IDLE_TIME Conn max idle time (default 5m)

API

Method Rows / affected On mismatch
GetOne exactly 1 read ErrNoRows / ErrMultipleRows
GetList 0..N read always ok
Exec any no check
ExecOne exactly 1 write ErrNoRows / ErrMultipleRows + rollback (implicit tx)

All methods take context.Context as the first argument (no Context suffix in names).

Query
var qUserByEmail = connsql.Q("user_by_email", `SELECT id, email FROM users WHERE email = $1`)
err := db.GetOne(ctx, qUserByEmail, &row, email)

Query.Name() labels Prometheus metrics; Query.String() is SQL (also in otel spans).

Transactions

err := db.WithTransaction(ctx, func(ctx context.Context) error {
    return db.Exec(ctx, qInsertUser, args...)
})

db implements port.Transactor via WithinTransaction.

Nested WithTransaction reuses the outer transaction.

Adapter error mapping

Map in repository adapters, not in conn-sql:

conn-sql typical domain
ErrNoRows ErrNotFound
ErrMultipleRows ErrConflict
if connsql.IsNotFound(err) {
    return domain.ErrNotFound
}

Probe

ProbeReady(ctx) pings the database (ops readiness pattern).

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoRows is returned when exactly one row was expected but none were found.
	ErrNoRows = sql.ErrNoRows

	// ErrMultipleRows is returned when exactly one row was expected but more were found.
	ErrMultipleRows = errors.New("connsql: expected exactly one row")
)

Functions

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is ErrNoRows.

Types

type Config

type Config struct {
	Label common.Label
	DSN   DSN
	Pool  PoolConfig
}

Config is the conn-sql spec; ecfg fills before Build.

func (*Config) Build

func (cfg *Config) Build() (any, error)

type ConnMaxIdleTime

type ConnMaxIdleTime time.Duration

ConnMaxIdleTime is the maximum idle time before a connection is closed.

func (ConnMaxIdleTime) Usage

func (ConnMaxIdleTime) Usage() string

func (ConnMaxIdleTime) Validate

func (c ConnMaxIdleTime) Validate() error

type ConnMaxLifetime

type ConnMaxLifetime time.Duration

ConnMaxLifetime is the maximum lifetime of a connection.

func (ConnMaxLifetime) Usage

func (ConnMaxLifetime) Usage() string

func (ConnMaxLifetime) Validate

func (c ConnMaxLifetime) Validate() error

type DB

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

DB is the Postgres SQL resource. Catalog field: *DB (Configurable).

func NewTestDB

func NewTestDB(sqlxDB *sqlx.DB) *DB

NewTestDB constructs a DB from an existing sqlx handle (tests only).

func (*DB) BuildConfig

func (*DB) BuildConfig() (app.Materializer, error)

BuildConfig returns the config spec for materialize.

func (*DB) Close

func (db *DB) Close(_ context.Context) error

Close closes the connection pool.

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, q Query, args ...any) error

Exec runs a write without checking rows affected.

func (*DB) ExecOne

func (db *DB) ExecOne(ctx context.Context, q Query, args ...any) error

ExecOne runs a write and requires exactly one affected row. Always runs inside a transaction when not already in [WithTransaction]; rolls back on != 1.

func (*DB) GetList

func (db *DB) GetList(ctx context.Context, q Query, dest any, args ...any) error

GetList loads zero or more rows into dest (*[]T).

func (*DB) GetOne

func (db *DB) GetOne(ctx context.Context, q Query, dest any, args ...any) error

GetOne loads exactly one row into dest (*T). Returns ErrNoRows or ErrMultipleRows when row count is not one.

func (*DB) Label

func (db *DB) Label() string

Label returns the configured resource label.

func (*DB) ProbeReady

func (db *DB) ProbeReady(ctx context.Context) error

ProbeReady reports database traffic readiness via Ping.

func (*DB) WithTransaction

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

WithTransaction runs fn inside a SQL transaction. Nested calls reuse the outer transaction.

func (*DB) WithinTransaction

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

WithinTransaction implements port.Transactor.

type DSN

type DSN string

DSN is a Postgres connection URL.

func (DSN) String

func (d DSN) String() string

func (DSN) Usage

func (DSN) Usage() string

func (DSN) Validate

func (d DSN) Validate() error

type MaxIdleConns

type MaxIdleConns int

MaxIdleConns is the maximum number of idle connections.

func (MaxIdleConns) Usage

func (MaxIdleConns) Usage() string

func (MaxIdleConns) Validate

func (n MaxIdleConns) Validate() error

type MaxOpenConns

type MaxOpenConns int

MaxOpenConns is the maximum number of open connections.

func (MaxOpenConns) Usage

func (MaxOpenConns) Usage() string

func (MaxOpenConns) Validate

func (n MaxOpenConns) Validate() error

type Meta

type Meta struct {
	Driver  string // sql driver name registered by pgx stdlib
	Dialect string // sqlx dialect
}

Meta describes how to open a parsed Postgres DSN.

func ParseDSN

func ParseDSN(dsn string) (Meta, error)

ParseDSN validates a Postgres DSN and returns driver metadata.

type PoolConfig

type PoolConfig struct {
	MaxOpen     MaxOpenConns
	MaxIdle     MaxIdleConns
	MaxLifetime ConnMaxLifetime
	MaxIdleTime ConnMaxIdleTime
}

PoolConfig tunes the Go sql.DB pool.

type Query

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

Query binds a stable metric label to SQL text.

func Q

func Q(name, sql string) Query

Q creates a query with a low-cardinality metric name and SQL body.

func (Query) Name

func (q Query) Name() string

Name returns the metric label for this query.

func (Query) String

func (q Query) String() string

String returns the SQL text.

Directories

Path Synopsis
example
app command

Jump to

Keyboard shortcuts

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