Documentation
¶
Overview ¶
Package sqldb wraps *bun.DB with lifecycle management, query builder proxies, error mapping, and transaction support.
A *DB is a component: bound with app.ProvideValue(db), its Start pings the database under Config.PingTimeout (zero means DefaultPingTimeout) before the components that depend on it start, its Ready reports it in /ready (named *sqldb.DB, or by credo.ComponentName), and the App shuts it down after its consumers. A failed ping fails the start and closes the database; with WithOptionalStart it is logged at Warn instead and the start goes on, while Ready keeps pinging, so the database gates readiness until it answers unless it is bound with credo.OptionalReadiness().
This is a separate Go submodule (github.com/credo-go/credo/store/sqldb) so that applications not using SQL databases do not pull in the Bun dependency.
Creating a Connection ¶
db, err := sqldb.Open(&sqldb.Config{
Driver: "postgres",
Host: "localhost",
Port: 5432,
Name: "myapp",
User: "postgres",
Password: "secret",
MaxOpen: 25,
MaxIdle: new(10),
MaxIdleTime: 5 * time.Minute,
MaxLifetime: 30 * time.Minute,
})
Driver-family detection uses an exact, case-insensitive allowlist: postgres/pgx, mysql, and sqlite/sqlite3/sqliteshim. A differently named registered driver uses its native Config.DSN plus WithDialect; a connector uses WithConnector plus WithDialect. Credo does not infer a family from a substring or a connector's concrete type, and rejects known driver/dialect family mismatches. When Credo builds a PostgreSQL or MySQL DSN, Port must be between 1 and 65535 and IPv6 hosts are bracketed correctly. Use Config.DSN or WithConnector for driver-native default-port or socket behavior.
Positive PostgreSQL ConnectTimeout values are rounded up to whole seconds so a sub-second value cannot silently disable the timeout. Config.Options cannot override reserved endpoint/credential fields or a simultaneously configured SSLMode/ConnectTimeout; conflicting sources fail without including option values in the error. Explicit nil WithDialect/WithConnector values also fail. SSLMode is driver-specific (PostgreSQL sslmode, MySQL tls), and Credo imposes no universal TLS default; production configuration must choose the driver's verified mode explicitly.
Connection Pool ¶
Credo does not choose a workload-independent finite pool size. MaxOpen=0 preserves database/sql's unlimited-open behavior. If the pool is still unlimited when Start's ping succeeds, Start logs one structured warning, credo: store configuration warning with code sqldb.pool.max_open_unlimited and module=sqldb, to WithLogger's logger or the App's. A program that runs the database without an App calls Start itself or reads Stats().MaxOpenConnections.
MaxIdle uses a pointer to distinguish absence from an explicit zero: nil makes Credo leave the idle limit unset (the effective database/sql default remains subject to MaxOpen), new(0) retains no idle connections, and a positive value is applied exactly. With MaxOpen > 0, MaxIdle must not exceed MaxOpen; Open rejects the configuration instead of relying on database/sql's silent clamp. MaxIdleTime=0 disables idle-age expiry and MaxLifetime=0 disables lifetime expiry. Positive values are applied unchanged.
DB.Stats returns the complete sql.DBStats snapshot. Health details include current open/in-use/idle counts and cumulative wait/closure counters, but readiness does not serialize adapter details. Credo does not derive StatusDegraded from pool saturation: that policy remains gated on production metrics, an explicit SLO, windowed deltas, hysteresis, and opt-in thresholds. A database gates readiness unless it is bound with credo.OptionalReadiness(), so a DEGRADED that removed readiness on a noisy universal threshold could cascade across replicas.
Resource Identity ¶
DB is a credo.ResourceIdentifier: ResourceIdentity returns the *DB pointer. A wrapper type that embeds *DB inherits it, so the App treats the *DB and its wrappers as holders of one database and closes it once, after the last holder retires. Only a wrapper without state of its own to release may share the identity; one that releases state of its own holds the *DB in a named field and does not forward ResourceIdentity.
Query Builder Proxies ¶
The DB type exposes Select, Insert, Update, and Delete methods that return proxy query builders. These proxies inject transactions from context, map errors to store.Err* sentinels, and provide escape hatches (Apply, Unwrap) for advanced usage. Each builder accepts at most one optional model. Supplying more causes the builder to record an error that its terminal returns without executing. SelectQuery's curated Limit and Offset forward every value; zero and negative values keep Bun's semantics and omit the clause.
var user User
err := db.Select(&user).Where("id = ?", id).Scan(ctx)
// err is already mapped: sql.ErrNoRows → store.ErrNotFound
ApplyFilter runs a func(*Filter) on the query's WHERE clause, so a single predicate (tenant scoping, soft-delete filters, ownership checks) scopes Select, Update, and Delete alike instead of being duplicated per query type. Filter is Credo's type with the predicate methods only (Where, WhereOr, WhereGroup, WherePK, WhereDeleted, WhereAllWithDeleted), so a select scoped through it keeps its automatic total in Count and Page.
func tenantScope(id int64) func(*sqldb.Filter) {
return func(f *sqldb.Filter) { f.Where("tenant_id = ?", id) }
}
Bun Visibility Policy ¶
Credo does not hide Bun — it integrates it. The proxy layer exists to attach two guarantees to query execution, not to abstract Bun away:
- Transaction injection: terminal methods (Scan, Count, Exists, Exec) resolve the connection from the context at execution time, so code inside InTx transparently runs on the transaction. Only a connection set with the wrapper's Conn is kept; one set inside an Apply callback is overridden by the injection. Select terminals run on an execution snapshot taken with Bun's own Clone, so the builder may be reused across executions and TX boundaries.
- Error mapping: the same terminals pass driver errors through the store.Err* mapping before returning.
Bun types therefore appear in proxy signatures (bun.IConn, Apply callbacks) by design. The wrapper reads and writes no Bun private state: it builds on Bun's public API only, and the count conformance tests pin the Bun behaviour Count and Page rely on. When the curated proxy surface lacks something:
- Missing builder method: use Apply (per query type) or ApplyFilter (shared WHERE predicates). Both keep the terminal guarantees intact; a select built with Apply pages with PageWithCount.
- Missing terminal method: request an addition to the curated set — the guarantees live in the terminals, so they must be on the proxy.
- Conn is the transaction-aware native Bun escape hatch. It returns the active transaction or the base DB, but native executions still bypass Credo error mapping.
- Unwrap and Client are deliberate opt-outs: executions through the raw Bun objects they return get neither automatic TX injection nor error mapping.
SelectQuery.Clone is the public, top-level builder-fork API. It forwards to Bun's Clone and is not a recursive object-graph copy: a bound destination and nested CTE/relation query values may remain shared. Do not mutate or scan shared values concurrently through source and clone.
Transactions ¶
Use InTx to execute a function within a transaction. The adapter stores the TX in a private per-DB scope so repositories using sqldb proxies pick it up automatically without cross-DB collisions:
err := db.InTx(ctx, func(ctx context.Context) error {
// repos pick up the scoped TX automatically
return nil
})
InTxWith accepts sql.TxOptions for configuring isolation level and read-only mode on the outer transaction. Nested calls use a Bun savepoint; because a savepoint cannot apply new transaction options, a nested call with non-default options returns ErrNestedTxOptions instead of silently ignoring them. From a handler, pass the request context: db.InTx(c.Context(), fn). Nested savepoint creation and cleanup are cancellation-safe and bounded: callback queries retain their original context, while savepoint operations use an internal context controlled by Credo. An uncertain begin/release/ rollback marks the shared transaction rollback-only before a fail-safe ambient abort, so an outer callback cannot swallow the error and commit; that outer InTx returns ErrTxRollbackOnly. Savepoint operations and ambient abort each use a five-second default budget; WithTxCleanupTimeout overrides it without limiting callback execution time.
A callback error is returned unchanged after rollback; only begin, rollback, and commit driver errors are mapped. Panic rollback preserves the original panic value. A nil callback returns ErrNilTxCallback before BEGIN. A commit error can leave the database outcome unknown, so it must not be treated as proof that no changes were applied or as an unconditional retry signal.
For a native Bun operation that must participate in the transaction, use Conn with the callback context. The returned bun.IDB is borrowed and must not escape the callback:
err := db.InTx(ctx, func(txCtx context.Context) error {
return db.Conn(txCtx).NewSelect().Model(&users).Scan(txCtx)
})
Pagination ¶
SelectQuery.Page is the typed pagination terminal: it runs a count and a LIMIT/OFFSET SELECT and returns a ready *pagination.Page[T]. Like One and All it is a Form-A terminal, so T drives the table and destination and the query is built model-less:
req := &pagination.PageRequest{Page: 2, PerPage: 20} // normalized by BindQuery
page, err := db.Select().
Where("active = ?", true).
OrderExpr("created_at DESC, id DESC").
Page[User](ctx, req)
One, All, and Page require T to be the actual table model and reject a model bound through Select, Model, or Apply with ErrTypedTerminalModel before executing. TableExpr does not turn a typed terminal into a projection API; use TableExpr(...).Scan(ctx, &dest) for projections. For relations, bind the destination and use Scan instead:
var users []User
err := db.Select(&users).Relation("Orders").Scan(ctx)
BindQuery applies PageRequest.Validate, whose input policy defaults/clamps the request. Page does not repeat that policy. Instead it copies req and strictly validates the snapshot before touching the database: nil, non-positive Page or PerPage, and native-int offset overflow return pagination.ErrInvalidPageRequest before the count. The caller's request is never mutated; a valid PerPage above the package default cap (for example a custom normalized value of 100) remains valid and is not clamped by the terminal. When the count reports zero rows, the data query is skipped and the page keeps the snapshot's page/per-page with a non-nil empty slice.
Total is the number of rows the data query returns without its LIMIT and OFFSET, or an error, never another number. Count and Page run Bun's native count, which drops ORDER BY, LIMIT, OFFSET and FOR, counts groups or distinct tuples for a query with GroupExpr or Distinct, and runs no model hook. They run it only on a query the wrapper can prove: built without Apply, Unwrap or a Relation callback; whose model's type does not implement bun.BeforeSelectHook; and that either carries GroupExpr or Distinct or has no raw ColumnExpr and no Having. Every other query returns an error matching ErrUnsupportedCountQuery before I/O, naming the rule and its culprit, and the caller pages it with PageWithCount and a count of its own; another query's Count passes as it is:
page, err := db.Select().
Apply(withReportColumns).
OrderExpr("created_at DESC, id DESC").
PageWithCount[Report](ctx, req, db.Select((*Report)(nil)).ApplyFilter(scope).Count)
PageWithCount validates the request as Page does, runs the count and the data query with the page's window, and builds the page with NewPage; the count's sort and lock clauses are the caller's. A model whose type implements only bun.BeforeAppendModelHook keeps its automatic total: on a SELECT Bun runs that hook only for values already in the destination, Page scans into an empty slice of its own, and the count runs no hook.
MySQL validates the output names of the count's derived source when it executes. If it returns ER_DUP_FIELDNAME (1060), Count and Page wrap ErrUnsupportedCountQuery after I/O while preserving the driver cause; unique aliases resolve collisions. Non-count MySQL 1060 errors remain unchanged. Driver causes are diagnostic and must not be rendered directly to HTTP. CursorPage is the accepted working shape for forward keyset pagination; Slice is only a working name for a future total-free offset result. Neither API is exported yet. Use a stable ORDER BY with a unique tie-breaker for deterministic offset pages.
The count and the data query use internal execution snapshots and join the ambient transaction, but remain separate database statements. Page never starts an implicit transaction. PostgreSQL Read Committed can observe statement-level drift; PostgreSQL/InnoDB callers that require one snapshot establish a read-only Repeatable Read outer transaction and pass its txCtx to Page. SQLite keeps the first-read snapshot of a plain explicit InTx; WAL permits a concurrent writer while rollback-journal mode may serialize it. The pinned modernc SQLite driver does not reliably enforce TxOptions Isolation/ReadOnly, so those options are not a SQLite guarantee.
Page responds with the queried type directly. For a model→DTO response, run Page[Model] and reshape it with pagination's Page.Map, which carries the metadata over unchanged:
modelPage, err := db.Select().Where("active = ?", true).Page[Model](ctx, req)
if err != nil {
return nil, err
}
dtoPage := modelPage.Map(func(m Model) DTO { return toDTO(m) })
When the conversion itself can fail, fetch the model page, map its records with ordinary error handling, and build the DTO page with NewPage:
modelPage, err := q.Page[Model](ctx, req)
// ...map modelPage.Records to dtos, returning any conversion error...
page := pagination.NewPage(
dtos, modelPage.Total, modelPage.Page, modelPage.PerPage,
)
NewPage computes TotalPages with overflow-safe quotient-and-remainder ceiling division, including totals near math.MaxInt64.
Migrations ¶
The DB wraps Bun's migration engine (bun/migrate — part of the already pinned Bun module) behind two methods: RegisterMigrations stores a *migrate.Migrations set at wiring time, and Migrate runs the pending ones. Multi-replica production should run the same Migrate method in one deadline-bounded pre-deploy job. Migrate also matches credo's App.OnStart hook; this is an opt-in convenience for development and deliberate single-replica deployments:
//go:embed migrations/*.sql
var sqlMigrations embed.FS
migrations := migrate.NewMigrations()
if err := migrations.Discover(sqlMigrations); err != nil {
return err
}
db.RegisterMigrations(migrations)
app.OnStart(db.Migrate) // dev/single-replica convenience
Seeding is a plain migration file (for example 2_seed_plans.up.sql) — there is no separate seed mechanism. Mark-on-success gives at-least-once retry, not atomic rollback: migrations must be transactional where supported or idempotent/reconcilable. Bun's table lock is fail-fast. Unlock is detached from parent cancellation and caller-bounded to five seconds; timeout leaves its outcome uncertain and is not automatically retried. Direct Bun migrators used for rollback/status/generation do not inherit Credo's options. Status/generation repeat only relevant options; DB-mutating apply/rollback callers additionally own Init, Lock, and bounded Unlock.
Error Mapping ¶
Terminal methods on the proxy types (Scan, Count, Exists, Exec) pass driver errors through mapError before returning. Common mappings:
- sql.ErrNoRows → store.ErrNotFound
- unique violation → store.ErrAlreadyExists
- foreign-key violation → store.ErrConstraint
- serialization failure → store.ErrSerialization
- deadlock → store.ErrDeadlock
- lock/busy contention → store.ErrContention
- bad connection → store.ErrUnavailable
- read-only / replica → store.ErrReadOnly
- context deadline → store.ErrTimeout
The classifier is context- and driver-family-aware. Structured SQLSTATE, MySQL number envelopes, and SQLite numeric codes produce a *store.Error that preserves the original cause and driver code. Loose message matching is not used. Callers can branch with errors.Is or inspect store.KindOf; store.IsTransient describes a condition, not permission to retry an operation. Update.Exec and Delete.Exec do not convert "no rows affected" into ErrNotFound — inspect sql.Result for that.
Escape Hatch ¶
Client() returns the underlying *bun.DB for model registration, advanced migration operations, and calls intentionally tied to the base DB. Queries executed via Client() bypass the proxy interceptors: there is no automatic TX injection from context and no error mapping to store.Err* sentinels. For native Bun work that must join an ambient transaction use Conn(ctx); for normal repository code use the proxy layer. Conn selects the right connection but still does not add Credo error mapping.
Stability ¶
Beta (see the project README's "Maturity by Area" table): the module is released in lockstep with the root module, and its beta label keeps it outside the v1 compatibility promise. Breaking changes are possible before v1.
Maturity: beta
Index ¶
- Constants
- Variables
- type Config
- type DB
- func (db *DB) Client() *bun.DB
- func (db *DB) Conn(ctx context.Context) bun.IDB
- func (db *DB) Delete(model ...any) *DeleteQuery
- func (db *DB) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (db *DB) Health(ctx context.Context) store.Health
- func (db *DB) InTx(ctx context.Context, fn func(ctx context.Context) error) error
- func (db *DB) InTxWith(ctx context.Context, opts *sql.TxOptions, fn func(ctx context.Context) error) error
- func (db *DB) Insert(model ...any) *InsertQuery
- func (db *DB) Migrate(ctx context.Context) (err error)
- func (db *DB) Ping(ctx context.Context) error
- func (db *DB) Query(ctx context.Context, dest any, query string, args ...any) error
- func (db *DB) QueryRow(ctx context.Context, dest any, query string, args ...any) error
- func (db *DB) Ready(ctx context.Context) error
- func (db *DB) RegisterMigrations(m *migrate.Migrations, opts ...migrate.MigratorOption)
- func (db *DB) RequireTx(ctx context.Context) (bun.IDB, error)
- func (db *DB) ResourceIdentity() any
- func (db *DB) Select(model ...any) *SelectQuery
- func (db *DB) Shutdown(_ context.Context) error
- func (db *DB) Start(ctx context.Context) error
- func (db *DB) Stats() sql.DBStats
- func (db *DB) Update(model ...any) *UpdateQuery
- type DeleteQuery
- func (q *DeleteQuery) Apply(fns ...func(*bun.DeleteQuery) *bun.DeleteQuery) *DeleteQuery
- func (q *DeleteQuery) ApplyFilter(fn func(*Filter)) *DeleteQuery
- func (q *DeleteQuery) Conn(db bun.IConn) *DeleteQuery
- func (q *DeleteQuery) Exec(ctx context.Context, dest ...any) (sql.Result, error)
- func (q *DeleteQuery) Model(model any) *DeleteQuery
- func (q *DeleteQuery) Returning(query string, args ...any) *DeleteQuery
- func (q *DeleteQuery) Unwrap() *bun.DeleteQuery
- func (q *DeleteQuery) Where(query string, args ...any) *DeleteQuery
- func (q *DeleteQuery) WherePK(cols ...string) *DeleteQuery
- type Filter
- func (f *Filter) Where(query string, args ...any) *Filter
- func (f *Filter) WhereAllWithDeleted() *Filter
- func (f *Filter) WhereDeleted() *Filter
- func (f *Filter) WhereGroup(sep string, fn func(*Filter)) *Filter
- func (f *Filter) WhereOr(query string, args ...any) *Filter
- func (f *Filter) WherePK(cols ...string) *Filter
- type InsertQuery
- func (q *InsertQuery) Apply(fns ...func(*bun.InsertQuery) *bun.InsertQuery) *InsertQuery
- func (q *InsertQuery) Column(columns ...string) *InsertQuery
- func (q *InsertQuery) Conn(db bun.IConn) *InsertQuery
- func (q *InsertQuery) Exec(ctx context.Context, dest ...any) (sql.Result, error)
- func (q *InsertQuery) Model(model any) *InsertQuery
- func (q *InsertQuery) On(query string, args ...any) *InsertQuery
- func (q *InsertQuery) Returning(query string, args ...any) *InsertQuery
- func (q *InsertQuery) Set(query string, args ...any) *InsertQuery
- func (q *InsertQuery) Unwrap() *bun.InsertQuery
- func (q *InsertQuery) Value(column string, expr string, args ...any) *InsertQuery
- type Option
- type SelectQuery
- func (q *SelectQuery) All[T any](ctx context.Context) ([]T, error)
- func (q *SelectQuery) Apply(fns ...func(*bun.SelectQuery) *bun.SelectQuery) *SelectQuery
- func (q *SelectQuery) ApplyFilter(fn func(*Filter)) *SelectQuery
- func (q *SelectQuery) Clone() *SelectQuery
- func (q *SelectQuery) Column(columns ...string) *SelectQuery
- func (q *SelectQuery) ColumnExpr(query string, args ...any) *SelectQuery
- func (q *SelectQuery) Conn(db bun.IConn) *SelectQuery
- func (q *SelectQuery) Count(ctx context.Context) (int, error)
- func (q *SelectQuery) Distinct() *SelectQuery
- func (q *SelectQuery) ExcludeColumn(columns ...string) *SelectQuery
- func (q *SelectQuery) Exists(ctx context.Context) (bool, error)
- func (q *SelectQuery) GroupExpr(query string, args ...any) *SelectQuery
- func (q *SelectQuery) Having(query string, args ...any) *SelectQuery
- func (q *SelectQuery) Join(join string, args ...any) *SelectQuery
- func (q *SelectQuery) JoinOn(cond string, args ...any) *SelectQuery
- func (q *SelectQuery) JoinOnOr(cond string, args ...any) *SelectQuery
- func (q *SelectQuery) Limit(n int) *SelectQuery
- func (q *SelectQuery) Model(model any) *SelectQuery
- func (q *SelectQuery) Offset(n int) *SelectQuery
- func (q *SelectQuery) One[T any](ctx context.Context) (T, error)
- func (q *SelectQuery) OrderExpr(query string, args ...any) *SelectQuery
- func (q *SelectQuery) Page[T any](ctx context.Context, req *pagination.PageRequest) (*pagination.Page[T], error)
- func (q *SelectQuery) PageWithCount[T any](ctx context.Context, req *pagination.PageRequest, ...) (*pagination.Page[T], error)
- func (q *SelectQuery) Relation(name string, apply ...func(*bun.SelectQuery) *bun.SelectQuery) *SelectQuery
- func (q *SelectQuery) Scan(ctx context.Context, dest ...any) error
- func (q *SelectQuery) TableExpr(query string, args ...any) *SelectQuery
- func (q *SelectQuery) Unwrap() *bun.SelectQuery
- func (q *SelectQuery) Where(query string, args ...any) *SelectQuery
- func (q *SelectQuery) WhereOr(query string, args ...any) *SelectQuery
- func (q *SelectQuery) WherePK(cols ...string) *SelectQuery
- type UpdateQuery
- func (q *UpdateQuery) Apply(fns ...func(*bun.UpdateQuery) *bun.UpdateQuery) *UpdateQuery
- func (q *UpdateQuery) ApplyFilter(fn func(*Filter)) *UpdateQuery
- func (q *UpdateQuery) Column(columns ...string) *UpdateQuery
- func (q *UpdateQuery) Conn(db bun.IConn) *UpdateQuery
- func (q *UpdateQuery) Exec(ctx context.Context, dest ...any) (sql.Result, error)
- func (q *UpdateQuery) Model(model any) *UpdateQuery
- func (q *UpdateQuery) OmitZero() *UpdateQuery
- func (q *UpdateQuery) Returning(query string, args ...any) *UpdateQuery
- func (q *UpdateQuery) Set(query string, args ...any) *UpdateQuery
- func (q *UpdateQuery) Unwrap() *bun.UpdateQuery
- func (q *UpdateQuery) Where(query string, args ...any) *UpdateQuery
- func (q *UpdateQuery) WherePK(cols ...string) *UpdateQuery
Constants ¶
const DefaultPingTimeout = 5 * time.Second
DefaultPingTimeout is the deadline of the ping DB.Start sends when Config.PingTimeout is zero.
Variables ¶
var ( // ErrNilTxCallback indicates that a transaction was requested without a // callback. The transaction is not started when this error is returned. ErrNilTxCallback = errors.New("sqldb: transaction callback must not be nil") // ErrNestedTxOptions indicates that non-default sql.TxOptions were supplied // to a nested transaction. Bun implements nested transactions with a // savepoint, where isolation and read-only options cannot be applied. ErrNestedTxOptions = errors.New("sqldb: nested transaction options are not supported") // ErrTxRollbackOnly indicates that a nested savepoint operation had an // uncertain outcome and poisoned the ambient transaction. The outer // transaction is aborted instead of being allowed to commit. ErrTxRollbackOnly = errors.New("sqldb: transaction is rollback-only") )
var ErrTypedTerminalModel = errors.New("sqldb: typed terminal requires a model-less query")
ErrTypedTerminalModel reports that One, All, Page, or PageWithCount was called on a SelectQuery that already has a model bound to it. Typed terminals own their destination model, so overriding a pre-bound model would discard relation and model state silently.
var ErrUnsupportedCountQuery = errors.New("sqldb: unsupported Count/Page query")
ErrUnsupportedCountQuery reports a query whose total Count and Page cannot prove. They run Bun's native count only on a query built without Apply, Unwrap or a Relation callback, whose model's type does not implement bun.BeforeSelectHook, and that either carries GroupExpr or Distinct or has no raw ColumnExpr and no Having. Every other query fails with this sentinel before I/O; the message names the rule, its culprit, and the remedy: page the query with SelectQuery.PageWithCount and a count of your own.
MySQL validates the output names of the count's derived source at execution. When the count returns ER_DUP_FIELDNAME (1060), Count and Page wrap this sentinel while preserving the original driver cause. That mapping is local to the count; the same MySQL error from any other operation passes through unchanged.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Driver is the SQL driver name (e.g., "postgres", "pgx", "mysql", "sqlite3").
// This must match the driver registered via a blank import in the application.
Driver string
// Host is the database server hostname or IP address.
Host string
// Port is the database server port number. It must be between 1 and 65535
// when Credo builds a PostgreSQL or MySQL DSN. Use DSN or WithConnector for
// driver-specific default-port behavior.
Port int
// Name is the database name.
Name string
// User is the database user.
User string
// Password is the database password.
Password string
// DSN is an optional raw DSN string. When set, it is used as-is and Credo
// does not merge Host, credentials, SSLMode, ConnectTimeout, or Options into
// it.
DSN string
// ConnectTimeout is the maximum time to wait for a connection to be
// established. Zero means no timeout. PostgreSQL DSNs represent this value
// in whole seconds, so positive fractional seconds are rounded up.
ConnectTimeout time.Duration
// PingTimeout is the deadline of the ping [DB.Start] sends. Zero means
// [DefaultPingTimeout] (5s), not "no deadline" as for ConnectTimeout:
// an unbounded ping would hang the App's start. A negative value fails
// Open.
PingTimeout time.Duration
// MaxOpen is the maximum number of open connections. Zero keeps the
// database/sql default, which is unlimited.
MaxOpen int
// MaxIdle is the maximum number of idle connections. Nil makes Credo leave
// the idle limit unset; the effective database/sql default remains subject
// to MaxOpen. A non-nil zero disables idle connections.
MaxIdle *int
// MaxLifetime is the maximum lifetime of a connection. Zero disables the
// lifetime limit.
MaxLifetime time.Duration
// MaxIdleTime is the maximum amount of time a connection may remain idle.
// Zero disables the idle-time limit.
MaxIdleTime time.Duration
// SSLMode sets the driver-specific SSL/TLS mode. PostgreSQL receives it as
// sslmode (for example, "require" or "verify-full"); MySQL receives it as
// tls (for example, "true" or a registered TLS config name). Credo does not
// impose a cross-driver TLS default.
SSLMode string
// Options holds additional driver-specific connection parameters. Core
// PostgreSQL endpoint and credential keys are reserved, and an option may not
// duplicate SSLMode or ConnectTimeout when the corresponding field is set.
// MySQL parseTime is always true and cannot be overridden. Ambiguous sources
// fail when Credo builds the DSN; use DSN for full driver-native control.
Options map[string]string
}
Config holds connection parameters for SQL databases.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB wraps *bun.DB with lifecycle management, query builder proxies, error mapping, and transaction support. It is a component: bound with app.ProvideValue, it is pinged by DB.Start before its dependants start, reported in /ready through DB.Ready, and shut down after its consumers.
func Open ¶
Open creates a DB from Config.
Steps:
- Build or use the provided DSN
- Open sql.DB (or use the provided Connector)
- Detect or use the provided dialect
- Create bun.DB
- Apply connection pool settings
func (*DB) Client ¶
Client returns the underlying *bun.DB for raw SQL, model registration, advanced migration operations, and any Bun feature not covered by the proxy layer.
Warning: queries executed via the returned *bun.DB bypass the proxy interceptors. There is no automatic TX injection from context (see DB.InTx / DB.Conn) and no error mapping to store.Err* sentinels. Use the proxy layer (DB.Select, DB.Insert, DB.Update, DB.Delete) for normal repository code. For an advanced Bun operation that must join an ambient transaction, build it through db.Conn(ctx). Reserve Client() for model registration and operations intentionally tied to the base DB, such as migration operations beyond DB.Migrate. A directly constructed Bun migrator does not inherit RegisterMigrations options. Status/generation callers repeat the options they need; DB-mutating apply/rollback callers must also own Init, Lock, and bounded cancellation-detached Unlock.
func (*DB) Conn ¶
Conn returns the active transaction for this DB from ctx, or the underlying Bun DB when no transaction is active. It is the transaction-aware escape hatch for advanced Bun operations that are not covered by Credo's proxies:
err := db.InTx(ctx, func(txCtx context.Context) error {
return db.Conn(txCtx).NewSelect().Model(&users).Scan(txCtx)
})
Conn does not lease a dedicated sql.Conn. The returned value is borrowed and must not escape the InTx callback when it represents a transaction. Queries executed through it use Bun directly and therefore bypass Credo error mapping. A nil context selects the underlying DB.
func (*DB) Delete ¶
func (db *DB) Delete(model ...any) *DeleteQuery
Delete creates a new DeleteQuery proxy. It accepts zero or one model; more than one records a builder error that Exec returns.
func (*DB) Health ¶
Health returns structured health information including status, round-trip latency, and connection pool statistics.
func (*DB) InTx ¶
InTx starts a transaction, stores it in this DB's typed context scope, executes fn with that context, and commits on nil / rolls back on error. Nested calls use a Bun savepoint. If fn panics, rollback is attempted and the original panic value is re-raised. A nil fn returns ErrNilTxCallback without starting a transaction.
In a handler, call it with the request context:
err := db.InTx(c.Context(), func(ctx context.Context) error {
// repos called with this ctx pick up the TX automatically
return svc.Transfer(ctx, from, to, amount)
})
A callback error is an application value: after a successful rollback it is returned unchanged and is never passed through the SQL driver error mapper. Begin, rollback, and commit errors are mapped separately. A commit error can leave the database outcome unknown; callers must not blindly retry solely because Commit returned an error.
Nested savepoint creation and cleanup are bounded and cancellation-aware. If their outcome becomes uncertain, the shared transaction state is marked rollback-only before the ambient SQL abort starts; an outer callback cannot swallow the nested error and commit. If a callback returns nil after its context was canceled, the savepoint is rolled back and the context error is returned.
The callback is the transaction lifetime boundary. It must not retain txCtx or start transaction work (including nested InTx calls) that outlives its return.
func (*DB) InTxWith ¶
func (db *DB) InTxWith(ctx context.Context, opts *sql.TxOptions, fn func(ctx context.Context) error) error
InTxWith is like DB.InTx but accepts sql.TxOptions for configuring the outer transaction's isolation level and read-only mode. Bun implements a nested transaction as a savepoint, which cannot apply new transaction options; a nested call with non-default options returns ErrNestedTxOptions before creating the savepoint or invoking fn, instead of silently ignoring them. Option support and enforcement remain driver- specific: Credo does not emulate an unsupported isolation level, and an unsupported level must not be assumed to have taken effect merely because Begin succeeded. The pinned modernc SQLite driver does not reliably enforce Isolation or ReadOnly, so use ordinary InTx for SQLite snapshot reads.
func (*DB) Insert ¶
func (db *DB) Insert(model ...any) *InsertQuery
Insert creates a new InsertQuery proxy. It accepts zero or one model; more than one records a builder error that Exec returns.
func (*DB) Migrate ¶
Migrate runs all pending registered migrations. In multi-replica production, call it from one deadline-bounded pre-deploy job before rolling out the application. Its signature also matches credo's App.OnStart hook; this opt-in form is convenient for development, tests, and deliberate single-replica deployments:
db.RegisterMigrations(migrations) app.OnStart(db.Migrate)
Migrate creates the Bun migration bookkeeping tables if needed, takes Bun's table-based advisory lock, applies unapplied migrations in order, and releases the lock. If another instance holds the lock, Migrate fails immediately rather than waiting; it does not retry. Running with no pending migrations executes no Up body, although Init, Lock, and Unlock still run.
Unlock ignores parent cancellation but gets a fresh five-second budget. Caller wait remains bounded even if a driver ignores context. A timeout means the unlock outcome is uncertain: the driver goroutine or connection may remain active and the lock row may remain or be deleted later. Do not retry or delete a stale row until the old runner is known to have stopped.
Returns an error if no migration set was registered, or if an operation surfaced by Bun fails; errors are mapped to store.Err* sentinels where applicable. A transactional SQL migration (.tx.up.sql) reports the error of its COMMIT or ROLLBACK, so a commit that fails leaves the migration unapplied; a database that cannot roll back DDL still applies what it ran before the failure. Direct Bun migrators do not inherit RegisterMigrations options. Callers must repeat the options relevant to status or generation; DB-mutating apply/rollback paths must additionally own Init, Lock, and bounded cancellation-detached Unlock themselves.
func (*DB) Query ¶
Query executes a raw SQL query that returns multiple rows, with TX injection and error mapping. dest should be a pointer to a slice.
func (*DB) QueryRow ¶
QueryRow executes a raw SQL query that returns a single row, with TX injection and error mapping. dest is scanned into.
func (*DB) Ready ¶ added in v0.25.0
Ready reports whether the database answers: nil when DB.Health is up, else an error naming the status that wraps Health's cause, so errors.Is and errors.As reach it.
func (*DB) RegisterMigrations ¶
func (db *DB) RegisterMigrations(m *migrate.Migrations, opts ...migrate.MigratorOption)
RegisterMigrations registers the migration set that DB.Migrate runs. The set is a plain migrate.Migrations from Bun: populate it with (*migrate.Migrations).Discover for SQL files (works with embed.FS) or MustRegister for Go migrations, then hand it to the DB once at wiring time. Optional opts are passed through to the underlying migrate.NewMigrator (table names, hooks, template data, ...).
By default the wrapper applies migrate.WithMarkAppliedOnSuccess(true), so a migration is recorded only after its Up function returns nil. This is an at-least-once bookkeeping policy, not an atomicity guarantee: partial non-transactional effects or a marker-write failure can make a later DB.Migrate repeat work. Migrations must therefore be transactional where the database supports it or explicitly idempotent/reconcilable. Pass WithMarkAppliedOnSuccess(false) to restore Bun's record-before-running policy when its different recovery tradeoff is intentional.
Panics if m is nil or if migrations were already registered — both are wiring-time programming errors, never runtime conditions.
func (*DB) RequireTx ¶
RequireTx returns the active transaction for this DB or store.ErrTxMissing when ctx is outside its transaction scope. Unlike DB.Conn, it never falls back to the underlying DB. The returned transaction is borrowed and must not escape the InTx callback.
func (*DB) ResourceIdentity ¶
ResourceIdentity names the physical database the DB holds. Wrapper types that embed *DB inherit it, so the App treats a *DB and the wrappers around it as holders of one resource and closes that resource once, after its last holder retires. Only a wrapper without state of its own to release may share the identity; one that releases state of its own holds the *DB in a named field and does not forward it.
func (*DB) Select ¶
func (db *DB) Select(model ...any) *SelectQuery
Select creates a new SelectQuery proxy. It accepts zero or one model; more than one records a builder error that the terminal method returns.
func (*DB) Shutdown ¶
Shutdown closes the database connection pool. The pool is always closed — even when ctx is already canceled or past its deadline — because leaving it open leaks connections; sql.DB.Close is a fast local operation that takes no context. ctx is accepted only to satisfy the credo.Component interface.
func (*DB) Start ¶ added in v0.25.0
Start pings the database under Config.PingTimeout, so the App's start walk reaches it before the components that depend on it start. On success it logs each pool warning once at Warn — today the code sqldb.pool.max_open_unlimited, read from the effective pool, so a SetMaxOpenConns on its client before the start counts. A failed ping closes the database before Start returns the error, since Open opened the pool and the App does not shut down a component whose Start failed; with WithOptionalStart it is logged instead, and Start returns nil.
The records go to WithLogger's logger, else to the logger of the App's call (credo.InfraFrom), scoped to the database's component, and carry module=sqldb.
func (*DB) Stats ¶
Stats returns a point-in-time snapshot of the underlying database/sql connection pool. OpenConnections, InUse, and Idle are instantaneous gauges; WaitCount, WaitDuration, and the closed-connection fields are cumulative for the lifetime of the pool. MaxOpenConnections equal to zero means the pool is unlimited. Cumulative values reset when a new DB and pool are opened. Stats does not ping the database.
func (*DB) Update ¶
func (db *DB) Update(model ...any) *UpdateQuery
Update creates a new UpdateQuery proxy. It accepts zero or one model; more than one records a builder error that Exec returns.
type DeleteQuery ¶
type DeleteQuery struct {
// contains filtered or unexported fields
}
DeleteQuery proxies bun.DeleteQuery with TX injection and error mapping.
func (*DeleteQuery) Apply ¶
func (q *DeleteQuery) Apply(fns ...func(*bun.DeleteQuery) *bun.DeleteQuery) *DeleteQuery
Apply delegates to Bun's native Apply for advanced builder methods. Nil functions are filtered out. A connection set inside fn is overridden by TX injection at the terminal; use Conn for an explicit connection.
func (*DeleteQuery) ApplyFilter ¶ added in v0.26.0
func (q *DeleteQuery) ApplyFilter(fn func(*Filter)) *DeleteQuery
ApplyFilter runs fn on a Filter over this query's WHERE clause, so a single predicate — tenant scoping, soft-delete filters, ownership checks — scopes a select, an update, and a delete alike. A nil fn is a no-op.
func (*DeleteQuery) Conn ¶
func (q *DeleteQuery) Conn(db bun.IConn) *DeleteQuery
Conn sets an explicit connection, bypassing context TX injection.
func (*DeleteQuery) Exec ¶
Exec executes the delete query.
Before TX injection the builder is shallow-copied so injecting the connection does not mutate the caller's builder. bun exposes Clone only on SelectQuery, so a deep copy is unavailable here; the shallow copy suffices because bun reads — never mutates — the builder while generating SQL.
Driver errors are mapped to store.Err* sentinels. Callers should inspect the returned sql.Result to detect zero-row deletes; the proxy does not convert "no rows affected" into store.ErrNotFound.
func (*DeleteQuery) Model ¶
func (q *DeleteQuery) Model(model any) *DeleteQuery
Model sets the model for the delete.
func (*DeleteQuery) Returning ¶
func (q *DeleteQuery) Returning(query string, args ...any) *DeleteQuery
Returning adds a RETURNING clause.
func (*DeleteQuery) Unwrap ¶
func (q *DeleteQuery) Unwrap() *bun.DeleteQuery
Unwrap returns the underlying *bun.DeleteQuery for builder-only use.
func (*DeleteQuery) Where ¶
func (q *DeleteQuery) Where(query string, args ...any) *DeleteQuery
Where adds a WHERE condition.
func (*DeleteQuery) WherePK ¶
func (q *DeleteQuery) WherePK(cols ...string) *DeleteQuery
WherePK adds a WHERE clause for the primary key columns.
type Filter ¶ added in v0.26.0
type Filter struct {
// contains filtered or unexported fields
}
Filter adds predicates to the WHERE clause of the select, update or delete query that SelectQuery.ApplyFilter, UpdateQuery.ApplyFilter or DeleteQuery.ApplyFilter runs it on, so one function scopes all three:
func tenantScope(id int64) func(*sqldb.Filter) {
return func(f *sqldb.Filter) { f.Where("tenant_id = ?", id) }
}
page, err := db.Select().ApplyFilter(tenantScope(id)).Page[Order](ctx, req)
_, err = db.Update((*Order)(nil)).Set("status = ?", s).ApplyFilter(tenantScope(id)).Exec(ctx)
_, err = db.Delete((*Order)(nil)).ApplyFilter(tenantScope(id)).Exec(ctx)
Filter has the predicate methods and nothing else, so a callback cannot change a select's projection, sort or window: a query scoped through it keeps its automatic total in Count and Page. A callback that needs more than predicates uses the query's Apply. A Filter is valid only during the callback it is passed to.
func (*Filter) WhereAllWithDeleted ¶ added in v0.26.0
WhereAllWithDeleted includes a soft-delete model's soft-deleted rows.
func (*Filter) WhereDeleted ¶ added in v0.26.0
WhereDeleted limits a soft-delete model's query to the soft-deleted rows.
func (*Filter) WhereGroup ¶ added in v0.26.0
WhereGroup adds the conditions fn adds to its Filter as one parenthesized group, joined to the preceding conditions with sep (" AND " or " OR ").
type InsertQuery ¶
type InsertQuery struct {
// contains filtered or unexported fields
}
InsertQuery proxies bun.InsertQuery with TX injection and error mapping.
func (*InsertQuery) Apply ¶
func (q *InsertQuery) Apply(fns ...func(*bun.InsertQuery) *bun.InsertQuery) *InsertQuery
Apply delegates to Bun's native Apply for advanced builder methods. Nil functions are filtered out.
func (*InsertQuery) Column ¶
func (q *InsertQuery) Column(columns ...string) *InsertQuery
Column specifies columns to insert.
func (*InsertQuery) Conn ¶
func (q *InsertQuery) Conn(db bun.IConn) *InsertQuery
Conn sets an explicit connection, bypassing context TX injection.
func (*InsertQuery) Exec ¶
Exec executes the insert query.
Before TX injection the builder is shallow-copied so injecting the connection does not mutate the caller's builder. bun exposes Clone only on SelectQuery, so a deep copy is unavailable here; the shallow copy suffices because bun reads — never mutates — the builder while generating SQL.
Driver errors are mapped to semantic store errors. Unique-constraint violations become store.ErrAlreadyExists; foreign-key violations become store.ErrConstraint.
func (*InsertQuery) Model ¶
func (q *InsertQuery) Model(model any) *InsertQuery
Model sets the model for the insert.
func (*InsertQuery) On ¶
func (q *InsertQuery) On(query string, args ...any) *InsertQuery
On adds an ON CONFLICT clause.
func (*InsertQuery) Returning ¶
func (q *InsertQuery) Returning(query string, args ...any) *InsertQuery
Returning adds a RETURNING clause.
func (*InsertQuery) Set ¶
func (q *InsertQuery) Set(query string, args ...any) *InsertQuery
Set adds a SET clause for ON CONFLICT DO UPDATE.
func (*InsertQuery) Unwrap ¶
func (q *InsertQuery) Unwrap() *bun.InsertQuery
Unwrap returns the underlying *bun.InsertQuery for builder-only use.
func (*InsertQuery) Value ¶
func (q *InsertQuery) Value(column string, expr string, args ...any) *InsertQuery
Value sets a custom value expression for a column.
type Option ¶
type Option func(*options)
Option configures an Open call.
func WithConnector ¶
WithConnector provides a custom driver.Connector, bypassing DSN-based connection creation. When set, Config.DSN and the DSN built from Config fields are ignored for sql.Open. Open rejects nil and typed-nil connectors.
func WithDialect ¶
WithDialect overrides the auto-detected dialect. Use this when the driver name does not match an exact known driver alias. Open rejects an explicitly nil dialect and a known dialect that conflicts with the configured known driver family.
func WithLogger ¶ added in v0.25.0
WithLogger gives the DB a logger of its own for what DB.Start logs: the pool warnings and, with WithOptionalStart, a failed ping. Without it the DB logs through the logger of the App that starts it, scoped to the database's component. Either way the records carry module=sqldb. A nil logger is ignored.
func WithOptionalStart ¶ added in v0.25.0
func WithOptionalStart() Option
WithOptionalStart makes a failed ping in DB.Start non-fatal: Start logs it at Warn, with the deadline and the error, logs the pool warnings as after a successful ping, and returns nil, leaving the pool open, since database/sql opens connections on demand once the server is back. DB.Ready keeps pinging, so the database gates readiness until it answers unless it is bound with credo.OptionalReadiness().
func WithTxCleanupTimeout ¶
WithTxCleanupTimeout sets how long Credo waits for each nested savepoint creation, release, or rollback and for the fail-safe ambient transaction abort. The default is 5 seconds. A driver operation that ignores context may continue in its goroutine, but the transaction is marked rollback-only and the caller stops waiting. d must be greater than zero; Open returns an error for invalid values.
type SelectQuery ¶
type SelectQuery struct {
// contains filtered or unexported fields
}
SelectQuery proxies bun.SelectQuery with TX injection and error mapping.
func (*SelectQuery) All ¶
func (q *SelectQuery) All[T any](ctx context.Context) ([]T, error)
All executes the query and returns every matching row as a []T. T drives both the table and the scan destination, so the query is built model-less and All owns the destination:
users, err := db.Select().Where("active = ?", true).OrderExpr("id").All[User](ctx)
No matching rows yield an empty, non-nil slice and a nil error — unlike One, an empty result is not store.ErrNotFound. Driver errors map to the store.Err* sentinels. The query must be model-less; a model bound through Select, Model, or Apply returns ErrTypedTerminalModel before execution. The receiver is not mutated: an internal execution snapshot receives the destination and ambient transaction from ctx, exactly as for SelectQuery.Scan.
func (*SelectQuery) Apply ¶
func (q *SelectQuery) Apply(fns ...func(*bun.SelectQuery) *bun.SelectQuery) *SelectQuery
Apply delegates to Bun's native Apply for advanced builder methods not in the curated proxy set. Nil functions are filtered out. Interceptors (TX injection, error mapping) are preserved on terminal methods; a connection set inside fn is overridden by TX injection, so use SelectQuery.Conn for an explicit connection.
The wrapper cannot see what fn changes, so Count and Page cannot prove the total of a query built with Apply; page it with SelectQuery.PageWithCount.
func (*SelectQuery) ApplyFilter ¶ added in v0.26.0
func (q *SelectQuery) ApplyFilter(fn func(*Filter)) *SelectQuery
ApplyFilter runs fn on a Filter over this query's WHERE clause, so a single predicate — tenant scoping, soft-delete filters, ownership checks — scopes a select, an update, and a delete alike. fn adds predicates only, so a query built with it keeps its automatic total in Count and Page. A nil fn is a no-op.
func (*SelectQuery) Clone ¶
func (q *SelectQuery) Clone() *SelectQuery
Clone returns a top-level query-builder fork through Bun's own Clone. It follows Bun's sharing semantics for nested values, including a bound destination and CTE or relation subqueries; do not mutate or scan source and clone concurrently when they share such values.
func (*SelectQuery) Column ¶
func (q *SelectQuery) Column(columns ...string) *SelectQuery
Column adds columns to select.
func (*SelectQuery) ColumnExpr ¶
func (q *SelectQuery) ColumnExpr(query string, args ...any) *SelectQuery
ColumnExpr adds a raw expression to the SELECT clause. Use for computed columns and aggregates that the model layer cannot express.
Bun's count replaces the projection, so Count and Page cannot prove the total of a query with a raw ColumnExpr unless it also carries GroupExpr or Distinct; page such a query with SelectQuery.PageWithCount.
func (*SelectQuery) Conn ¶
func (q *SelectQuery) Conn(db bun.IConn) *SelectQuery
Conn sets an explicit connection, bypassing context TX injection. Only a connection set here is kept: one set inside an Apply callback is overridden by transaction injection at the terminal.
func (*SelectQuery) Count ¶
func (q *SelectQuery) Count(ctx context.Context) (int, error)
Count runs Bun's native count and returns the number of rows the query returns without its LIMIT and OFFSET. Bun's count drops ORDER BY, LIMIT, OFFSET and FOR, wraps a query with GroupExpr or Distinct so that it counts groups or distinct tuples, and runs no model hook.
Count runs only on a query the wrapper can prove: one built without Apply, Unwrap or a Relation callback; whose model's type does not implement bun.BeforeSelectHook; and that either carries GroupExpr or Distinct or has no raw ColumnExpr and no Having. Every other query returns an error matching ErrUnsupportedCountQuery before I/O, naming the rule and its culprit.
The count runs on the query's own connection: the one set with Conn, else the ambient transaction from ctx, else the pool. Driver errors are mapped to store.Err* sentinels; on MySQL, ER_DUP_FIELDNAME (1060) from the count is wrapped with ErrUnsupportedCountQuery while retaining the driver cause.
func (*SelectQuery) Distinct ¶
func (q *SelectQuery) Distinct() *SelectQuery
Distinct adds a DISTINCT clause.
func (*SelectQuery) ExcludeColumn ¶
func (q *SelectQuery) ExcludeColumn(columns ...string) *SelectQuery
ExcludeColumn removes columns that the model would otherwise select. Use "*" to start from an empty set and add columns explicitly.
func (*SelectQuery) Exists ¶
func (q *SelectQuery) Exists(ctx context.Context) (bool, error)
Exists executes the query and returns true if at least one row matches. Driver errors are mapped to store.Err* sentinels.
func (*SelectQuery) GroupExpr ¶
func (q *SelectQuery) GroupExpr(query string, args ...any) *SelectQuery
GroupExpr adds a GROUP BY expression.
func (*SelectQuery) Having ¶
func (q *SelectQuery) Having(query string, args ...any) *SelectQuery
Having adds a HAVING clause. Count and Page cannot prove the total of a query with Having unless it also carries GroupExpr or Distinct.
func (*SelectQuery) Join ¶
func (q *SelectQuery) Join(join string, args ...any) *SelectQuery
Join adds a JOIN clause. The join string is the full join expression including the join type and ON condition, e.g. "LEFT JOIN orders AS o ON o.user_id = u.id". For composing the ON clause separately, follow with JoinOn.
func (*SelectQuery) JoinOn ¶
func (q *SelectQuery) JoinOn(cond string, args ...any) *SelectQuery
JoinOn appends an additional ON condition to the most recent Join, joined with AND.
func (*SelectQuery) JoinOnOr ¶
func (q *SelectQuery) JoinOnOr(cond string, args ...any) *SelectQuery
JoinOnOr appends an additional ON condition to the most recent Join, joined with OR.
func (*SelectQuery) Limit ¶
func (q *SelectQuery) Limit(n int) *SelectQuery
Limit sets the LIMIT clause. Zero and negative values keep Bun's semantics: the clause is omitted.
func (*SelectQuery) Model ¶
func (q *SelectQuery) Model(model any) *SelectQuery
Model sets the model for the query.
func (*SelectQuery) Offset ¶
func (q *SelectQuery) Offset(n int) *SelectQuery
Offset sets the OFFSET clause. Zero and negative values keep Bun's semantics: the clause is omitted.
func (*SelectQuery) One ¶
func (q *SelectQuery) One[T any](ctx context.Context) (T, error)
One executes the query and returns its first matching row as a value of T. T drives both the table and the scan destination, so the query is built model-less and One owns the destination. T may be a struct or a pointer to one (User or *User); both forms work:
user, err := db.Select().Where("id = ?", id).One[User](ctx)
One applies LIMIT 1, so multiple matches are not an error — it returns the first row; add an OrderExpr for a deterministic choice. A missing row returns store.ErrNotFound (wrapping sql.ErrNoRows), so callers branch with errors.Is(err, store.ErrNotFound); other driver errors map to the store.Err* sentinels. The query must be model-less; a model bound through Select, Model, or Apply returns ErrTypedTerminalModel before execution. The receiver is not mutated: an internal execution snapshot receives the destination and the ambient transaction from ctx, exactly as for SelectQuery.Scan.
func (*SelectQuery) OrderExpr ¶
func (q *SelectQuery) OrderExpr(query string, args ...any) *SelectQuery
OrderExpr adds an ORDER BY expression.
func (*SelectQuery) Page ¶
func (q *SelectQuery) Page[T any](ctx context.Context, req *pagination.PageRequest) (*pagination.Page[T], error)
Page runs Bun's native count and the data query with LIMIT/OFFSET and assembles the result as a *pagination.Page[T]. Like SelectQuery.One and SelectQuery.All it is a typed terminal: T drives both the table and the scan destination, so the query is built model-less and Page owns the result:
page, err := db.Select().
ApplyFilter(tenantScope(tenantID)).
OrderExpr("created_at DESC").
Page[User](ctx, req) // (*pagination.Page[User], error)
req is copied once and never modified. BindQuery applies defaults through pagination.PageRequest.Validate; manually constructed requests may call pagination.PageRequest.Normalize (or NormalizeWithMax) first. Page itself never defaults or clamps: it strictly requires positive Page and PerPage values and an offset that fits in int. Nil, invalid, or overflowing requests return an error matching pagination.ErrInvalidPageRequest before any I/O. Valid custom PerPage values above pagination.MaxPerPage remain unchanged.
The query must be model-less; a model bound through Select, Model, or Apply returns ErrTypedTerminalModel before any I/O. Use a bound model with SelectQuery.Scan when relations or a custom destination are required.
Total is the number of rows the data query returns without its LIMIT and OFFSET, or an error, never another number. Page counts under the rule of SelectQuery.Count, with T as the model: a query the wrapper cannot prove, including one whose T implements bun.BeforeSelectHook, returns an error matching ErrUnsupportedCountQuery before any I/O; page it with SelectQuery.PageWithCount. A query scoped through SelectQuery.ApplyFilter keeps its automatic total.
The count runs first; when it reports zero rows the data query is skipped and the returned Page carries a non-nil empty Records slice with the requested page and per-page preserved. The count and the data query are separate statements, so under concurrent writes the total and the page can drift. A normal Read Committed transaction does not make the two statements share a snapshot; use an isolation level with that guarantee when consistency is required. Both statements run on the query's own connection and join the ambient transaction from ctx exactly like SelectQuery.Scan, so the receiver is never mutated. Credo does not start an implicit transaction: PostgreSQL and MySQL/InnoDB callers normally select Repeatable Read on an outer DB.InTxWith call, while SQLite callers use an explicit DB.InTx read transaction. Always pass the callback's txCtx to Page; isolation support remains driver-specific.
Page is the all-in-one terminal for flows that respond with the queried type directly. When records need a model→DTO mapping, run Page[Model] and map it with pagination's Page.Map, which carries the metadata over:
modelPage, err := q.Page[Model](ctx, req)
if err != nil {
return nil, err
}
dtoPage := modelPage.Map(func(m Model) DTO { return toDTO(m) })
For a conversion that can fail, iterate modelPage.Records with ordinary error handling and build the DTO page with pagination.NewPage, carrying modelPage's Total, Page, and PerPage over.
func (*SelectQuery) PageWithCount ¶ added in v0.26.0
func (q *SelectQuery) PageWithCount[T any]( ctx context.Context, req *pagination.PageRequest, count func(context.Context) (int, error), ) (*pagination.Page[T], error)
PageWithCount pages the query with the caller's count, for a query whose total Page cannot prove: one built with Apply, Unwrap or a Relation callback, with a raw ColumnExpr or Having and neither GroupExpr nor Distinct, or whose T implements bun.BeforeSelectHook. Another query's Count passes as it is:
page, err := db.Select().
Apply(withReportColumns).
OrderExpr("created_at DESC").
PageWithCount[Report](ctx, req, db.Select((*Report)(nil)).ApplyFilter(scope).Count)
PageWithCount validates req as SelectQuery.Page does, and requires a model-less query, both before any I/O. It then runs count, and the data query with the page's window, and builds the page with pagination.NewPage: Total is the count's result, unchanged. An error from count is returned as it is. The count's sort and lock clauses, its connection and its consistency with the data query are the caller's.
func (*SelectQuery) Relation ¶
func (q *SelectQuery) Relation(name string, apply ...func(*bun.SelectQuery) *bun.SelectQuery) *SelectQuery
Relation loads a named relation for a bound model. Use the model-bound Scan form for eager loading, for example:
var users []User
err := db.Select(&users).Relation("Orders").Scan(ctx)
A relation cannot be deferred to One, All, or Page: typed terminals require a model-less query and return ErrTypedTerminalModel when a model is already bound. A non-nil apply callback is an escape hatch: Count cannot prove the total of a query built with one.
func (*SelectQuery) Scan ¶
func (q *SelectQuery) Scan(ctx context.Context, dest ...any) error
Scan executes the query and scans results into dest.
Driver errors are mapped to store.Err* sentinels. In particular, sql.ErrNoRows is returned as store.ErrNotFound, so callers can use errors.Is(err, store.ErrNotFound) without importing database/sql.
func (*SelectQuery) TableExpr ¶
func (q *SelectQuery) TableExpr(query string, args ...any) *SelectQuery
TableExpr sets the FROM clause from a raw expression. Use for model-less queries (reporting, ad-hoc projections) where Model is not appropriate.
func (*SelectQuery) Unwrap ¶
func (q *SelectQuery) Unwrap() *bun.SelectQuery
Unwrap returns the underlying *bun.SelectQuery for builder-only use. Terminal methods on the unwrapped query bypass Credo interceptors (TX injection, error mapping). Use Apply for the recommended escape hatch that preserves interceptors. The wrapper cannot see what is done to the unwrapped query, so Count and Page cannot prove its total afterwards.
func (*SelectQuery) Where ¶
func (q *SelectQuery) Where(query string, args ...any) *SelectQuery
Where adds a WHERE condition.
func (*SelectQuery) WhereOr ¶
func (q *SelectQuery) WhereOr(query string, args ...any) *SelectQuery
WhereOr adds an OR WHERE condition.
func (*SelectQuery) WherePK ¶
func (q *SelectQuery) WherePK(cols ...string) *SelectQuery
WherePK adds a WHERE clause for the primary key columns.
type UpdateQuery ¶
type UpdateQuery struct {
// contains filtered or unexported fields
}
UpdateQuery proxies bun.UpdateQuery with TX injection and error mapping.
func (*UpdateQuery) Apply ¶
func (q *UpdateQuery) Apply(fns ...func(*bun.UpdateQuery) *bun.UpdateQuery) *UpdateQuery
Apply delegates to Bun's native Apply for advanced builder methods. Nil functions are filtered out. A connection set inside fn is overridden by TX injection at the terminal; use Conn for an explicit connection.
func (*UpdateQuery) ApplyFilter ¶ added in v0.26.0
func (q *UpdateQuery) ApplyFilter(fn func(*Filter)) *UpdateQuery
ApplyFilter runs fn on a Filter over this query's WHERE clause, so a single predicate — tenant scoping, soft-delete filters, ownership checks — scopes a select, an update, and a delete alike. A nil fn is a no-op.
func (*UpdateQuery) Column ¶
func (q *UpdateQuery) Column(columns ...string) *UpdateQuery
Column specifies columns to update.
func (*UpdateQuery) Conn ¶
func (q *UpdateQuery) Conn(db bun.IConn) *UpdateQuery
Conn sets an explicit connection, bypassing context TX injection.
func (*UpdateQuery) Exec ¶
Exec executes the update query.
Before TX injection the builder is shallow-copied so injecting the connection does not mutate the caller's builder. bun exposes Clone only on SelectQuery, so a deep copy is unavailable here; the shallow copy suffices because bun reads — never mutates — the builder while generating SQL.
Driver errors are mapped to store.Err* sentinels. Callers should inspect the returned sql.Result to detect zero-row updates; the proxy does not convert "no rows affected" into store.ErrNotFound.
func (*UpdateQuery) Model ¶
func (q *UpdateQuery) Model(model any) *UpdateQuery
Model sets the model for the update.
func (*UpdateQuery) OmitZero ¶
func (q *UpdateQuery) OmitZero() *UpdateQuery
OmitZero omits zero values from the update.
func (*UpdateQuery) Returning ¶
func (q *UpdateQuery) Returning(query string, args ...any) *UpdateQuery
Returning adds a RETURNING clause.
func (*UpdateQuery) Set ¶
func (q *UpdateQuery) Set(query string, args ...any) *UpdateQuery
Set adds a SET clause.
func (*UpdateQuery) Unwrap ¶
func (q *UpdateQuery) Unwrap() *bun.UpdateQuery
Unwrap returns the underlying *bun.UpdateQuery for builder-only use.
func (*UpdateQuery) Where ¶
func (q *UpdateQuery) Where(query string, args ...any) *UpdateQuery
Where adds a WHERE condition.
func (*UpdateQuery) WherePK ¶
func (q *UpdateQuery) WherePK(cols ...string) *UpdateQuery
WherePK adds a WHERE clause for the primary key columns.