Documentation
¶
Index ¶
- Constants
- func AnsiQuoter(s string) string
- func ColumnsAndValues(model any, omitempty bool) ([]string, []any, error)
- func DollarFormat(idx int) string
- func GroupBy[T any, K comparable](slice []T, fn func(T) K) map[K][]T
- func IndexBy[T any, K comparable](slice []T, fn func(T) K) (map[K]T, error)
- func IsOk(v any) bool
- func LimitOffsetPager(limit, offset string) string
- func Map[T any, R any](slice []T, fn func(T) R) []R
- func MySQLQuoter(s string) string
- func OffsetFetchPager(limit, offset string) string
- func QmarkFormat(_ int) string
- type BeforeCreate
- type BeforeUpdate
- type Dao
- func (d *Dao[T]) Batch(entities []T) (int64, error)
- func (d *Dao[T]) Count(where string, args ...any) (int64, error)
- func (d *Dao[T]) CountAll() (int64, error)
- func (d *Dao[T]) Create(data any) (int64, error)
- func (d *Dao[T]) Delete(where string, args ...any) (int64, error)
- func (d *Dao[T]) Exists(where string, args ...any) (bool, error)
- func (d *Dao[T]) FetchAll() ([]T, error)
- func (d *Dao[T]) FetchByPK(id any) (*T, error)
- func (d *Dao[T]) FetchList(where string, args ...any) ([]T, error)
- func (d *Dao[T]) FetchOne(where string, args ...any) (*T, error)
- func (d *Dao[T]) FetchPage(page, size int, where string, args ...any) ([]T, int64, error)
- func (d *Dao[T]) PK(pk string) *Dao[T]
- func (d *Dao[T]) RawBatch(entities []T) *SQL
- func (d *Dao[T]) RawCreate(data any) *SQL
- func (d *Dao[T]) RawSelect(where string, args ...any) *SQL
- func (d *Dao[T]) SQL() *SQL
- func (d *Dao[T]) Table(table string) *Dao[T]
- func (d *Dao[T]) Update(data any, where string, args ...any) (int64, error)
- func (d *Dao[T]) Vars(alias string) map[string]Node
- func (d *Dao[T]) WithCtx(ctx context.Context) *Dao[T]
- func (d *Dao[T]) WithTx(tx *SQL) *Dao[T]
- type Formatter
- type H
- type LogFunc
- type Node
- type Pager
- type Pipe
- type Quoter
- type RenderCtx
- type SQL
- func (d *SQL) Add(query string, args ...any) *SQL
- func (d *SQL) AddIf(cond bool, query string, args ...any) *SQL
- func (d *SQL) Batch(rows [][]any) *SQL
- func (d *SQL) BatchInsert(table string, entities []any) *SQL
- func (d *SQL) Begin() (*SQL, error)
- func (d *SQL) Close() error
- func (d *SQL) Commit() error
- func (d *SQL) Delete(table string, where string, args ...any) *SQL
- func (d *SQL) Error() error
- func (d *SQL) Exec() (sql.Result, error)
- func (d *SQL) FetchGrouped[K comparable, V any](key func(V) K) (map[K][]V, error)
- func (d *SQL) FetchIndexed[K comparable, V any](key func(V) K) (map[K]V, error)
- func (d *SQL) FetchList[T any]() ([]T, error)
- func (d *SQL) FetchMaps() ([]map[string]any, error)
- func (d *SQL) FetchOne[T any]() (*T, error)
- func (d *SQL) FetchOneMap() (map[string]any, error)
- func (d *SQL) FetchPage[T any](page, size int) ([]T, int64, error)
- func (d *SQL) FetchRows() (*sqlx.Rows, error)
- func (d *SQL) Formatter(formatter Formatter) *SQL
- func (d *SQL) Insert(table string, data any) *SQL
- func (d *SQL) Iter[T any]() iter.Seq2[T, error]
- func (d *SQL) Pager(pager Pager) *SQL
- func (d *SQL) Pool() *sqlx.DB
- func (d *SQL) Quoter(quoter Quoter) *SQL
- func (d *SQL) RegisterMacro(prefix byte, pipe string) *SQL
- func (d *SQL) RegisterPipe(name string, fn Pipe) *SQL
- func (d *SQL) Rollback() error
- func (d *SQL) Select(table string, where string, args ...any) *SQL
- func (d *SQL) SetLogger(fn LogFunc) *SQL
- func (d *SQL) ToSQL() (string, []any, error)
- func (d *SQL) Transaction(fn func(*SQL) error) error
- func (d *SQL) Unsafe() *SQL
- func (d *SQL) Update(table string, data any, where string, args ...any) *SQL
- func (d *SQL) Var(key string, query string, args ...any) *SQL
- func (d *SQL) Vars(vars map[string]Node) *SQL
- func (d *SQL) WithCtx(ctx context.Context) *SQL
Constants ¶
const F = "F"
F is the slot variable name for the column set, used by Select and Page.
Contract:
- Select renders "${F:*}" (default *); FetchPage swaps it for Var(F, "COUNT(1)") to build the count query.
- To feed hand-written SQL into FetchPage, the main chain must contain either ${F:...} or a bare ${F} (see its probe).
- The F slot belongs on the main chain (mainNodes); a ${F} hidden inside a varNode is not recognised by FetchPage.
const I = "I"
I is the slot variable name for an INSERT modifier (INSERT ${I:} INTO ...), empty by default.
Rationale: once Insert has generated a statement, chained Add calls can only append at the end — which is where ON DUPLICATE KEY / RETURNING / ON CONFLICT naturally belong. The gap between INSERT and INTO is the one dead spot, and this slot is the only vent for it:
db.Var(I, "IGNORE").Insert("users", u) // INSERT IGNORE INTO ...
const O = "order"
O is the slot variable name for ORDER BY. FetchPage issues two queries whose ORDER BY requirements are exact opposites:
data query: keep it (SQL Server's OFFSET...FETCH requires ORDER BY)
count query: clear it (an aggregate carrying the ORDER BY source column
is a hard error on PG/mssql)
Queries meant for FetchPage should therefore write ORDER BY as ${order:...} rather than bare text (variable names are matched literally, so the slot name "order" equals the const value):
q.Add("SELECT ... WHERE x ${order:ORDER BY id DESC}")
Variables ¶
This section is empty.
Functions ¶
func ColumnsAndValues ¶ added in v0.5.2
ColumnsAndValues converts a struct or map into column names and bind values.
Struct strategy: fieldList (derived from the reflectx TypeMap — the same mapper used by #{name} resolution and row scanning) builds the field list, with dba's atomicity decision (isAtomicColumn) applied per field:
- atomic types (driver.Valuer implementers / time.Time and convertible aliases / Node) collapse to a single column;
- structs (embedded or plain, value or pointer) expand recursively;
- other basic types / []byte are single columns.
Collected field values pass through normalizeBindValue before entering vals. The map branch does no normalization (same level as Add arguments: bind exactly what the caller passed).
func GroupBy ¶
func GroupBy[T any, K comparable](slice []T, fn func(T) K) map[K][]T
GroupBy groups slice elements by fn(element): 1 key → N values.
func IndexBy ¶
func IndexBy[T any, K comparable](slice []T, fn func(T) K) (map[K]T, error)
IndexBy converts a slice into a map keyed by fn(element). Returns an error if duplicate keys are found.
func LimitOffsetPager ¶ added in v0.14.0
LimitOffsetPager generates "LIMIT n OFFSET m" (the mysql/sqlite family; NewFromSqlx selects it automatically for those drivers).
func OffsetFetchPager ¶ added in v0.14.0
OffsetFetchPager generates "OFFSET m ROWS FETCH NEXT n ROWS ONLY" (SQL:2008 standard; the default, supported by PostgreSQL / SQL Server 2012+ / Oracle 12c+ / DB2 11.1+).
Note: SQL Server/Oracle/DB2 require ORDER BY — the query must carry the ${order:...} slot or a bare ORDER BY.
Types ¶
type BeforeCreate ¶
type BeforeCreate interface {
BeforeCreate() error
}
BeforeCreate is implemented by structs that need a hook before INSERT.
type BeforeUpdate ¶
type BeforeUpdate interface {
BeforeUpdate() error
}
BeforeUpdate is implemented by structs that need a hook before UPDATE.
type Dao ¶
type Dao[T any] struct { // contains filtered or unexported fields }
Dao is a generic single-table CRUD helper.
func (*Dao[T]) Create ¶
Create inserts a single record and returns the generated primary key. On PostgreSQL, uses RETURNING. On other drivers, uses LastInsertId.
func (*Dao[T]) FetchByPK ¶ added in v0.15.0
FetchByPK fetches a single record by primary key. The primary key is unique, so this goes through the strict FetchOne (more than one row means corrupt data and is reported as an error). Returns (nil, nil) when nothing is found — "no result" is a normal business outcome rather than an error (sql.ErrNoRows is not returned); callers must check for nil before dereferencing.
func (*Dao[T]) FetchOne ¶ added in v0.14.0
FetchOne fetches a single record by condition (strictly 0..1: more than one row is an error). Returns (nil, nil) when nothing is found — "no result" is a normal business outcome rather than an error (sql.ErrNoRows is not returned); callers must check for nil before dereferencing. Use FetchList when the condition is not guaranteed to be unique.
func (*Dao[T]) RawBatch ¶
RawBatch bulk-inserts multiple records and returns a SQL builder for chaining.
func (*Dao[T]) RawCreate ¶
RawCreate inserts a single record and returns the SQL builder for chaining (e.g. ON CONFLICT, RETURNING).
func (*Dao[T]) Vars ¶
Vars generates the table alias reference variables (table name and primary key are maintained in one place, the Dao):
${u.as} → `users` AS `u` (FROM/JOIN table declaration)
${u} → `u` (alias reference: ${u}.name / ${u}.*)
${u.pk} → `u`.`id` (primary key reference, kept by Dao.PK)
Column references are not generated (write them bare: ${u}.email) — the column set is not part of the Dao's maintenance duty. Without an alias (single-table case) it returns nil; just write the table name bare.
type LogFunc ¶ added in v0.11.0
LogFunc is the SQL execution log callback: it runs once after every execution. begin is the start time, so observers compute the duration or open a span themselves. It does not change the execution flow, and a panic raised inside it does not affect the result.
func NewLogger ¶ added in v0.11.0
NewLogger is the default execution log callback, based on slog: slow queries are logged at Warn, errors at Error, and everything else at Debug. Set doClean to true to fold whitespace for single-line display. SQL syntax (comments/dialect) is preserved as-is — dba does not interpret SQL.
type Node ¶
Node is a SQL fragment together with its own positional arguments, as returned by Expr. It makes "arguments as subtrees" possible: a Node passed in an argument position is inlined into the SQL instead of being bound as a placeholder, and a Node stored in a struct field collapses to a single column value.
Argument numbering inside Text restarts at #{1}, independently of the fragment the Node is inlined into.
type Pager ¶ added in v0.14.0
Pager generates the row-limiting clause appended by FetchPage.
limit and offset are two placeholder tokens (e.g. "#{1}", "#{2}") whose positions in the clause the pager decides. FetchPage always passes arguments in the semantic order (limit=size, offset), so a pager is free to swap the two tokens to match its dialect without affecting the caller.
type Pipe ¶ added in v0.8.0
Pipe is a pipe: the interpreter of macro content.
A pipe receives the literal macro content (e.g. "1" for #{1|pipe}, "users" for @{users}) and decides what to do with it: use the literal as-is (ident), or turn it into an argument via ctx.Resolve (bind/raw/expand). User pipes are free to choose — that freedom is the whole point. Built-ins: bind/expand/raw/quote/literalquote; register your own with RegisterPipe.
type RenderCtx ¶ added in v0.8.0
type RenderCtx interface {
// Bind binds a value: a Node is rendered inline (arguments as subtrees),
// any other value writes a placeholder and collects the argument.
// This is the single implementation point of the "arguments as subtrees"
// invariant — pipes always route argument values through Bind.
Bind(v any) error
// Render renders a Node sub-fragment inline, recursively, using that
// Node's own Args.
Render(n Node) error
// WriteString writes raw SQL text.
WriteString(s string)
// QuoteIdent writes a dialect-quoted identifier.
QuoteIdent(s string)
// Resolve resolves macro content as an argument key (positional or named);
// pipes call it as needed.
Resolve(key string) (any, error)
}
RenderCtx is the rendering context: the output port for pipes and macros.
type SQL ¶
type SQL struct {
// contains filtered or unexported fields
}
SQL is an immutable, chainable query builder backed by sqlx.
func NewFromSqlx ¶
NewFromSqlx creates a SQL builder from a sqlx.DB. Auto-detects driver for placeholder formatter, identifier quoting, and FetchPage's row-limiting clause (SQL:2008 OFFSET...FETCH by default; LIMIT/OFFSET for mysql/sqlite).
func Open ¶
Open connects to a database and returns a SQL builder. It is a convenience over sqlx.Connect + NewFromSqlx.
func (*SQL) BatchInsert ¶
BatchInsert builds a complete INSERT from a slice of entities. All entities must have the same column structure.
func (*SQL) Close ¶
Close closes the underlying connection pool. Builders created with NewFromSqlx share the caller's *sqlx.DB, so closing them also closes that shared pool.
func (*SQL) FetchGrouped ¶ added in v0.14.0
func (d *SQL) FetchGrouped[K comparable, V any](key func(V) K) (map[K][]V, error)
FetchGrouped fetches all rows and groups them into a map keyed by key(v) — the query-side GroupBy. Each key maps to a slice of values, in query order.
func (*SQL) FetchIndexed ¶ added in v0.14.0
func (d *SQL) FetchIndexed[K comparable, V any](key func(V) K) (map[K]V, error)
FetchIndexed fetches all rows and indexes them into a map keyed by key(v) — the query-side IndexBy. Duplicate keys are an error (same as IndexBy).
func (*SQL) FetchList ¶ added in v0.14.0
FetchList scans multiple rows and returns them as a slice (struct/basic types, sqlx mapping). For dynamic queries with unknown columns use FetchMaps.
func (*SQL) FetchMaps ¶ added in v0.14.0
FetchMaps scans multiple rows into a slice of maps — for queries whose columns are not known at compile time.
func (*SQL) FetchOne ¶ added in v0.14.0
FetchOne scans a single row and returns a pointer to it. Strictly 0..1: no row → (nil, nil); more than one row → an error (it fetches one extra row, catching a missing LIMIT 1). When "any row will do", write LIMIT 1 explicitly in the SQL.
T is meant to be a value type (FetchOne[User]() returns *User; the pointer comes from the return value). Passing a pointer type yields **T, so do not write FetchOne[*User]().
func (*SQL) FetchOneMap ¶ added in v0.14.0
FetchOneMap scans a single row into a map — for queries whose columns are not known at compile time. Same contract as FetchOne: strictly 0..1, more than one row is an error; no row → (nil, nil).
func (*SQL) FetchPage ¶ added in v0.14.0
FetchPage fetches a page of rows and the total count.
Contract: the query must contain the ${F:...} slot (or bare ${F}) on the main chain — the F slot is substituted with COUNT(1) for the count query. Constraints: no GROUP BY / DISTINCT in the F slot content (the count query reuses the same template).
ORDER BY must live in the ${order:...} slot: the count query clears it with Var(O, ""). Under strict dialects (PG/mssql) an aggregate query carrying the ORDER BY source column is a hard error, while SQL Server's OFFSET...FETCH forces the data query to carry ORDER BY — only the ${order} slot satisfies both at once. Example:
q.Add("SELECT ... WHERE x ${order:ORDER BY id DESC}") // then q.FetchPage[User](1, 20)
The row-limiting clause defaults to the SQL:2008 standard (OFFSET...FETCH); the mysql/sqlite family switches to LIMIT/OFFSET automatically, and Pager() overrides either. The SQL Server/Oracle/DB2 family requires ORDER BY. page/size must be >= 1, otherwise an error is returned (no silent clamping — the caller's parameter bug surfaces early). The total==0 case skips the data query entirely. The total==0 case skips the data query entirely.
func (*SQL) FetchRows ¶ added in v0.14.0
FetchRows returns a raw *sqlx.Rows cursor (the query executes immediately, which suits streaming scenarios; for lazy streaming use Iter).
func (*SQL) Formatter ¶ added in v0.12.0
Formatter returns a new builder with the given placeholder formatter.
func (*SQL) Iter ¶ added in v0.14.0
Iter returns a lazy iterator over the rows (struct/basic types, sqlx mapping). Lazy: the query runs when the for-range starts, and an early break still releases the connection. Each row needs an err check (inherent to iter.Seq2[T, error]).
for u, err := range q.Iter[User]() {
if err != nil {
return err
}
// ...
}
func (*SQL) Pager ¶ added in v0.14.0
Pager returns a new builder using the given renderer for the row-limiting clause appended by FetchPage, overriding the driverName auto-detection.
func (*SQL) RegisterMacro ¶ added in v0.8.0
RegisterMacro registers a macro alias (prefix → pipe name) and returns a new builder:
q := db.RegisterMacro('^', "upper")
q.Add("WHERE name = ^{1}", "bob") → equivalent to #{1|upper}
'#' and '$' are reserved prefixes and cannot be registered; the pipe name may point at a pipe that is not registered yet (the error surfaces at render time).
func (*SQL) RegisterPipe ¶ added in v0.8.0
RegisterPipe registers a custom pipe and returns a new builder:
q := db.RegisterPipe("upper", func(ctx RenderCtx, content string) error {
v, err := ctx.Resolve(content)
if err != nil {
return err
}
return ctx.Bind(strings.ToUpper(fmt.Sprint(v))) // Bind: Node inlines, plain values become placeholders
})
q.Add("WHERE name = #{1|upper}", "bob") → $1 = "BOB"
func (*SQL) SetLogger ¶ added in v0.11.0
SetLogger sets the execution log callback (nil disables logging). Copy-on-write: the receiver is not modified.
func (*SQL) Transaction ¶
Transaction executes fn inside a transaction. If fn returns an error or panics, the transaction is rolled back. If already in a transaction, fn is executed directly without nesting.