dba

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 15 Imported by: 9

README

dba

An immutable, chainable SQL builder for sqlx — SQL as the language, not as a DSL.

No ORM, no code generation, no query-builder API to learn. You write SQL; dba handles the plumbing: parameters, quoting, fragments, execution.

Quick start

q := dba.NewFromSqlx(db)

// SQL is the template — macros add plumbing, never replace the language
q.Add("SELECT * FROM users WHERE status = #{1} AND age >= #{2}",
    "active", 18)

// Conditional clauses
q.AddIf(minAge > 0, "AND age >= #{1}", minAge)

// Reusable fragments with parameters attached
q.Var("where", " WHERE status = #{1}", "active")
q.Add("SELECT * FROM users${where} ${order:ORDER BY id}")

// Execute
user := User{}
found, err := q.Get(&user)

Why not just sqlx?

// sqlx — string wrangling, manual arg spread, sqlx.In in a separate call
query := "SELECT * FROM users WHERE status = ?"
args := []any{"active"}
if name != "" {
    query += " AND name = ?"
    args = append(args, name)
}
query, args, _ = sqlx.In("SELECT * FROM users WHERE id IN (?)", ids)

// dba — the SQL reads as SQL
q.Add("SELECT * FROM users WHERE status = #{1}", "active").
    AddIf(name != "", "AND name = #{1}", name).
    Add("AND id IN (#{1|expand})", ids)
Pain point Raw sqlx dba
IN (?) expansion sqlx.In() in a separate call #{1|expand} explicit expansion
Conditional clauses String concat + manual args AddIf(cond, ...)
Reusable fragments Copy-paste SQL Var(key, fragment, args...)
Count + data pagination Two maintained SQL strings Page[T](q, page, size)
Identifier quoting Manual per dialect @{table} / #{1|quote} / quoter
Tracing/logging Wrap every call Use(LogHook(...)) — once

Core ideas

SQL is the language. SQL (recursive CTEs, window functions, set operations) is a complete language — any DSL that tries to cover it either surrenders to Raw() on complex queries or balloons into its own language (GORM's API surface). dba doesn't abstract SQL; it adds plumbing around it. The template is the final SQL — ToSQL() shows exactly what runs.

Three mechanisms, each with one job:

Mechanism Layer Job
#{...} !{...} @{...} rendering values, identifiers, raw text
|pipe rendering value rendering control (the only semantic layer)
${...} structure template fragments (reuse, override, defer decisions)

Syntax reference

Macros
Syntax What it does Example
#{1} Positional parameter, single value WHERE id = #{1} → WHERE id = $1
#{name} Named parameter from map/struct #{id} + map["id"]
#{1|pipe} Pipe override — custom rendering IN (#{1|expand}) → $1, $2, $3
!{1} Raw injection of parameter 1 (caller is responsible for safety) to !{1} → to /tmp/out.csv
@{users} Literal identifier — content is the identifier name, quoted safely SELECT @{users}.name → SELECT `users`.name
${key:default} Fillable fragment with fallback ${order:ORDER BY id}
XX{...} Double prefix escapes to a literal X{ ##{1} → literal #{1}

Macros are only recognized when the prefix immediately precedes { (#{1} yes, # {1} no) — so MySQL # comments, PG $1, @x variables, #temp tables and != are all untouched. Quoted strings ('...', "...", `...`) are skipped entirely — JSON literals and LIKE '%{x}%' are safe.

Pipes — the rendering layer

Pipes receive the macro content as a literal string and decide what to do with it: use it directly, or resolve it as a parameter key via ctx.Resolve.

Pipe Kind Behavior
bind parameter one value → placeholder + arg (#{} default)
expand parameter slice → separate placeholders (IN (#{1|expand}))
raw parameter value → raw text (to !{1})
quote parameter value → quoted identifier (SELECT #{1|quote} FROM t, "name")
literalquote literal content is the identifier name → quoted (@{users})

# is a plain macro whose default pipe is bind — no privileges. Any macro content can carry its own pipe: #{1|quote}, @{x|raw}.

Variables — the structure layer
// Fillable slots with inline defaults. Spacing conventions:
//   • a variable sits flush against the preceding text
//   • spacing between variables is written before the later one
//   • Var content conventionally starts with a space
//   • inline default text is trimmed — keep spacing in the template
q.Add("SELECT ${F:*} FROM users${where:} ${order:ORDER BY id}")
// → SELECT * FROM users ORDER BY id          (defaults apply)
// → SELECT id, name FROM users WHERE status = $1 ORDER BY id DESC
//   (after Var("where", ...) + Var(F, "id, name") + Var("order", ...))

// Parameters are attached to the fragment, not the call site
q.Var("where", " WHERE status = #{1} AND age >= #{2}", "active", 18)
q.Add("SELECT * FROM users${where}")   // caller doesn't know the args

// Immutable — each Var returns a new copy; the base is untouched
base  := q.Add("SELECT ${F:*} FROM users${where:} ${order:ORDER BY id}")
count := base.Var(dba.F, "COUNT(1)")          // independent query
data  := base.Var("where", " WHERE id > #{1}", 100)

Variables are the structure layer: their content is a template (macros included) and renders recursively. They are deliberately invisible to pipes — the dependency is one-way (structure → rendering), so a pipe can never reach back into the structure layer.

Building

q.Add("SELECT * FROM users WHERE id = #{1}", 42)           // positional
q.Add("SELECT * FROM users WHERE id = #{id}", map{"id": 42}) // named (map/struct)
q.AddIf(name != "", "AND name = #{1}", name)               // conditional
q.Var("where", "WHERE x = #{1}", 1)                        // fragment
q.Batch(rows)                                              // parenthesized value groups

Unsafe() disables macro parsing for raw dialect SQL you don't want touched.

DML helpers

Columns are sorted lexicographically for stable SQL; omitempty drops zero values (including sql.Null* with Valid=false).

type User struct {
    ID        int    `db:"id,omitempty"`
    Name      string `db:"name"`
    CreatedAt string `db:"created_at,omitempty"`
}

q.Insert("users", User{Name: "alice"})
// INSERT INTO "users" ("name") VALUES ($1)     — ID and CreatedAt omitted

q.Update("users", map[string]any{"name": "bob"}, "id = #{1}", 42)
// UPDATE "users" SET "name"=$1 WHERE id = $2

q.Delete("users", "id = #{1}", 42)

q.BatchInsert("users", anySlice(users))        // one statement, N rows
// INSERT INTO "users" ("name") VALUES ($1), ($2), ($3)

q.Update("stats", map[string]any{
    "views": dba.Expr("views + 1"),            // raw SQL expressions in values
    "score": dba.Expr("score + #{1}", 10),
}, "id = #{1}", 1)

Executing

found, err := q.Get(&user)             // single row; (false, nil) when not found
err := q.List(&users)                  // slice pointer; also *[]map[string]any
res, err := q.Exec()                   // INSERT/UPDATE/DELETE
rows, err := q.Rows()                  // streaming large result sets
sql, args, err := q.ToSQL()            // inspect without executing

Dialects

Two pure functions, nothing else. dba never rewrites SQL syntax — dialect differences (LIMIT ? OFFSET ?, JSON operators, casts) live in your template, as SQL should. Quoting and placeholders are pluggable:

q := dba.NewFromSqlx(db).
    Quoter(dba.MySQLQuoter)   // `name`  — default is MySQL-style
    // Quoter(dba.AnsiQuoter) // "name"  — PG/SQLite/SQL Server
    // Formater(dba.DollarFormat) // $1, $2 — PG

No dialect matrix, no database-version coupling — a new database costs two functions, and you are never forced to upgrade a database to use the library.

Generic DAO

type User struct {
    ID        int       `db:"id,omitempty"`
    Name      string    `db:"name"`
    CreatedAt time.Time `db:"created_at"`
}
func (u *User) BeforeCreate() error {   // hooks for timestamps, defaults
    u.CreatedAt = time.Now()
    return nil
}

dao := dba.NewDao[User](q, "users")

id, _ := dao.Create(User{Name: "alice"})      // hook runs; returns new ID
user, _ := dao.GetByID(id)                     // *User, nil when not found
items, _ := dao.List("age > #{1}", 18)         // []User
count, _ := dao.Count("age > #{1}", 18)
affected, _ := dao.Update(data, "id = #{1}", id)
deleted, _ := dao.Delete("id = #{1}", id)

// Join with the table's own quoting, via alias variables:
m := dao.Vars("u")   // {"u.as": "`users` AS `u`", "u": "`u`", "u.pk": "`u`.`id`"}
q = q.Vars(m)         // register the fragment map
q.Add("SELECT ${u.pk} FROM ${u.as} JOIN orders o ON o.user_id = ${u.pk}")

// Cross-DAO transactions
q.Transaction(func(tx *dba.SQL) error {
    uid, err := userDao.WithTx(tx).Create(User{Name: "alice"})
    if err != nil {
        return err
    }
    _, err = orderDao.WithTx(tx).Create(Order{UserID: int(uid)})
    return err // nil → commit, error → rollback
})

Extending

Pipes are the single semantic extension point. Register once, use in any template:

q := db.RegisterPipe("upper", func(ctx dba.RenderCtx, content string) error {
    v, err := ctx.Resolve(content)              // parameter, or literal?
    if err != nil {
        return err
    }
    ctx.AddParam(strings.ToUpper(fmt.Sprint(v)))
    return nil
})
q.Add("WHERE name = #{1|upper}", "bob")

// Macros are syntax aliases for pipes — local dialect, shared semantics
q = q.RegisterMacro('^', "upper")
q.Add("WHERE name = ^{1}", "bob")               // same as #{1|upper}

The pipe receives the macro content literally and decides itself whether to treat it as a parameter key (ctx.Resolve) or use it directly — so custom pipes are free to do either. Dialect-specific needs (e.g. DuckDB's COPY ... TO not accepting bound output paths) are solved with a 10-line custom pipe at the project level — never by growing the library.

Both registrations are instance-scoped and copy-on-write — no global state, no concurrency issues. $ is the reserved structure-layer prefix.

Middleware

Onion model — every query passes through the chain:

q = q.Use(dba.LogHook(slog.Default(), 200*time.Millisecond, true))
// or
q = q.Use(func(next dba.ExecFunc) dba.ExecFunc {
    return func(ctx context.Context, query string, args []any) (any, error) {
        start := time.Now()
        result, err := next(ctx, query, args)
        log.Printf("[%s] %s", time.Since(start), query)
        return result, err
    }
})

Utilities

count, found, _ := dba.Scalar[int64](q.Add("SELECT COUNT(1) FROM users"))
items, total, _ := dba.Page[User](q, page, size)   // skips data query when total==0
ok := dba.IsOk(v)                    // non-nil, non-empty string/slice/map
dba.Map / dba.IndexBy / dba.GroupBy  // generic slice helpers

Design notes

  • No DSL. SQL is a complete language; abstracting it means either a surrender-to-Raw() split brain or an API surface that chases SQL's capabilities forever. The template is the SQL — the only abstraction is plumbing (parameters, quoting, fragments).
  • Pipes receive literals, not values. The pipe decides whether content is a parameter key or a literal — value-source decisions live in the rendering layer, so custom pipes are free to do either.
  • Structure and rendering are separate layers. ${} fragments render recursively and may contain macros; pipes can never reach back into fragments (one-way dependency — no cycles, no cross-layer coupling).
  • Dialect cost is two functions. Quoter + Formater, and nothing else parses or rewrites SQL. New databases, old versions — both are free.
  • Mechanisms over features. Everything is a small, composable mechanism (macro, pipe, variable, hook, quoter). Features are assembled from mechanisms at the call site, not added to the library.

Tests

go test ./...          # 191 tests
go test -race ./...    # race detector

Documentation

Index

Constants

View Source
const (
	F = "F"
	I = "I"
)

F is the default field variable name used by Select and Page.

Variables

This section is empty.

Functions

func AnsiQuoter

func AnsiQuoter(s string) string

AnsiQuoter wraps identifiers in double quotes.

func ColumnsAndValues added in v0.5.2

func ColumnsAndValues(model any, omitempty bool) ([]string, []any, error)

ColumnsAndValues 把 struct 或 map 转换为列名与参数值列表。

struct 策略: 自建递归遍历 (fieldList) 生成字段清单, 遍历时即时判定:

  • 原子类型 (driver.Valuer 实现者 / time.Time 及其可转换别名) 作为单列收束;
  • struct (匿名嵌入或普通字段, 值或指针) 递归展开子字段;
  • 其余基本类型/[]byte 直接作为单列。

time.Time 不实现 Valuer (database/sql 原生参数类型), 由 isAtomicColumn 显式特判。

func DollarFormat

func DollarFormat(idx int) string

DollarFormat returns "$1", "$2", ...

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 IsOk

func IsOk(v any) bool

IsOk returns true if v is non-nil, non-blank string, or non-empty slice/array/map.

func Map

func Map[T any, R any](slice []T, fn func(T) R) []R

Map transforms each element of a slice using fn and returns a new slice.

func MySQLQuoter

func MySQLQuoter(s string) string

MySQLQuoter wraps identifiers in backticks.

func Page

func Page[T any](q *SQL, page, size int) ([]T, int64, error)

Page the query must contain ${F:...} so that Page can swap the field list for COUNT(1).

func QmarkFormat

func QmarkFormat(_ int) string

QmarkFormat returns "?" for every index.

func Scalar

func Scalar[T any](d *SQL) (T, bool, error)

Scalar returns a single scalar value from a query.

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 NewDao

func NewDao[T any](q *SQL, table string) *Dao[T]

NewDao creates a Dao bound to the given table. Default primary key is "id".

func (*Dao[T]) All

func (d *Dao[T]) All() ([]T, error)

All fetches all records from the table.

func (*Dao[T]) Batch

func (d *Dao[T]) Batch(entities []T) (int64, error)

Batch bulk-inserts multiple records and returns affected rows.

func (*Dao[T]) Count

func (d *Dao[T]) Count(where string, args ...any) (int64, error)

Count returns the number of matching records.

func (*Dao[T]) CountAll

func (d *Dao[T]) CountAll() (int64, error)

CountAll returns the total number of records in the table.

func (*Dao[T]) Create

func (d *Dao[T]) Create(data any) (int64, error)

Create inserts a single record and returns the generated primary key. On PostgreSQL, uses RETURNING. On other drivers, uses LastInsertId.

func (*Dao[T]) Delete

func (d *Dao[T]) Delete(where string, args ...any) (int64, error)

Delete deletes records matching the given condition.

func (*Dao[T]) Exists

func (d *Dao[T]) Exists(where string, args ...any) (bool, error)

Exists returns true if at least one matching record exists.

func (*Dao[T]) Get

func (d *Dao[T]) Get(where string, args ...any) (*T, error)

Get fetches a single record by condition. 未找到时返回 (nil, nil) —— “无结果”是正常业务结果而非错误 (不返回 sql.ErrNoRows); 调用方必须先判 nil 再解引用。

func (*Dao[T]) GetByID

func (d *Dao[T]) GetByID(id any) (*T, error)

GetByID fetches a single record by primary key. 未找到时返回 (nil, nil) —— “无结果”是正常业务结果而非错误 (不返回 sql.ErrNoRows); 调用方必须先判 nil 再解引用。

func (*Dao[T]) List

func (d *Dao[T]) List(where string, args ...any) ([]T, error)

List fetches multiple records by condition.

func (*Dao[T]) PK

func (d *Dao[T]) PK(pk string) *Dao[T]

PK returns a new Dao with the given primary key column.

func (*Dao[T]) Page

func (d *Dao[T]) Page(page, size int, where string, args ...any) ([]T, int64, error)

func (*Dao[T]) RawBatch

func (d *Dao[T]) RawBatch(entities []T) *SQL

RawBatch bulk-inserts multiple records and returns a SQL builder for chaining.

func (*Dao[T]) RawCreate

func (d *Dao[T]) RawCreate(data any) *SQL

RawCreate inserts a single record and returns the SQL builder for chaining (e.g. ON CONFLICT, RETURNING).

func (*Dao[T]) RawSelect

func (d *Dao[T]) RawSelect(where string, args ...any) *SQL

func (*Dao[T]) SQL

func (d *Dao[T]) SQL() *SQL

SQL returns the underlying SQL builder for custom queries.

func (*Dao[T]) Table

func (d *Dao[T]) Table(table string) *Dao[T]

Table returns a new Dao with the given table name.

func (*Dao[T]) Update

func (d *Dao[T]) Update(data any, where string, args ...any) (int64, error)

Update updates records matching the given condition.

func (*Dao[T]) Vars

func (d *Dao[T]) Vars(alias string) map[string]Node

Vars 生成表别名引用变量 (表名/主键在 DAO 一处维护):

${u.as}  → ` + "`users` AS `u`" + `   (FROM/JOIN 表声明)
${u}     → ` + "`u`" + `              (别名引用: ${u}.name / ${u}.*)
${u.pk}  → ` + "`u`.`id`" + `          (主键引用: 主键列名 DAO.PK 维护)

列引用不生成 (列名裸写: `${u}.email`), 列集不属于 DAO 的维护职责。 无 alias (单表场景) 返回 nil, 表名裸写即可。

func (*Dao[T]) WithCtx

func (d *Dao[T]) WithCtx(ctx context.Context) *Dao[T]

func (*Dao[T]) WithTx

func (d *Dao[T]) WithTx(tx *SQL) *Dao[T]

WithTx returns a Dao backed by the given transaction.

type Formater

type Formater func(idx int) string

Formater generates a placeholder for the n-th parameter.

type H

type H = map[string]any

H is a shorthand for map[string]any.

type LogFunc added in v0.11.0

type LogFunc func(ctx context.Context, begin time.Time, query string, args []any, err error)

LogFunc SQL 执行日志回调: 每次执行后调用一次 (begin 为执行开始时间, 观察者自行计算耗时/开 span; 不改变执行流, panic 不影响执行结果)。

func NewLogger added in v0.11.0

func NewLogger(logger *slog.Logger, slowThreshold time.Duration, doClean bool) LogFunc

NewLogger 默认执行日志回调 (基于 slog): 慢查询 Warn / 错误 Error / 常规 Debug。 Set cleanSpec to true to fold whitespace for single-line display. SQL 语法 (注释/方言) 原样保留 —— dba 不解释 SQL。

type Node

type Node struct {
	RawSQL string
	Args   []any
}

type Pipe added in v0.8.0

type Pipe func(ctx RenderCtx, content string) error

Pipe 管道: 宏内容的解读者。

管道收到宏内容的字面量 (如 #{1|pipe} 的 "1"、@{users} 的 "users"), 由管道自行决定: 字面量直接用 (ident), 或经 ctx.Resolve 取参数 (bind/raw/expand)。 用户管道可自由选择 — 这是管道的灵活性所在。 内置: bind/expand/raw/ident; 用户通过 RegisterPipe 注册。

type Quoter

type Quoter func(string) string

Quoter quotes an identifier for the target dialect.

type RenderCtx added in v0.8.0

type RenderCtx interface {
	// AddParam 写入一个占位符并收集绑定参数 (内部维护序号与方言格式)。
	AddParam(v any)
	// WriteString 写入原始 SQL 文本。
	WriteString(s string)
	// QuoteIdent 写入方言 quoting 的标识符。
	QuoteIdent(s string)
	// Resolve 把宏内容作为参数 key 解析 (位置/命名); 管道按需调用。
	Resolve(key string) (any, error)
}

RenderCtx 渲染上下文: 管道与宏的渲染出口。

type SQL

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

SQL is an immutable, chainable query builder backed by sqlx.

func NewFromSqlx

func NewFromSqlx(db *sqlx.DB) *SQL

NewFromSqlx creates a SQL builder from a sqlx.DB. Auto-detects driver for placeholder formater and identifier quoting.

func Open

func Open(driver, dsn string) (*SQL, error)

Open connects to a database and returns a SQL builder. It is a convenience over sqlx.Connect + NewFromSqlx.

func (*SQL) Add

func (d *SQL) Add(query string, args ...any) *SQL

Add appends a SQL fragment and returns a new builder.

func (*SQL) AddIf

func (d *SQL) AddIf(cond bool, query string, args ...any) *SQL

AddIf conditionally appends a SQL fragment.

func (*SQL) Batch

func (d *SQL) Batch(rows [][]any) *SQL

Batch generates parenthesized value groups for bulk INSERT.

func (*SQL) BatchInsert

func (d *SQL) BatchInsert(table string, entities []any) *SQL

BatchInsert builds a complete INSERT from a slice of entities. All entities must have the same column structure.

func (*SQL) Begin

func (d *SQL) Begin() (*SQL, error)

Begin starts a transaction and returns a new builder backed by the Tx.

func (*SQL) Close

func (d *SQL) Close() error

func (*SQL) Commit

func (d *SQL) Commit() error

Commit commits the active transaction.

func (*SQL) Delete

func (d *SQL) Delete(table string, where string, args ...any) *SQL

Delete generates and appends a DELETE FROM statement.

func (*SQL) Error

func (d *SQL) Error() error

Error returns the accumulated error on this builder.

func (*SQL) Exec

func (d *SQL) Exec() (sql.Result, error)

Exec builds and executes a non-query statement.

func (*SQL) Formater

func (d *SQL) Formater(formatter Formater) *SQL

Formater returns a new builder with the given placeholder formater.

func (*SQL) Get

func (d *SQL) Get(dest any) (found bool, err error)

Get scans a single row. Returns (false, nil) when no row is found.

func (*SQL) Insert

func (d *SQL) Insert(table string, data any) *SQL

Insert generates and appends an INSERT INTO statement.

func (*SQL) List

func (d *SQL) List(dest interface{}) error

List scans multiple rows into a slice pointer.

func (*SQL) Pool

func (d *SQL) Pool() *sqlx.DB

func (*SQL) Quoter

func (d *SQL) Quoter(quoter Quoter) *SQL

Quoter returns a new builder with the given identifier quoter.

func (*SQL) RegisterMacro added in v0.8.0

func (d *SQL) RegisterMacro(prefix byte, pipe string) *SQL

RegisterMacro 注册宏别名 (前缀 → 管道名), 返回新 builder:

q := db.RegisterMacro('^', "upper")
q.Add("WHERE name = ^{1}", "bob") → 等价 #{1|upper}

'#'/'$' 为保留前缀不可注册; 管道名允许指向尚未注册的管道 (渲染时报错)。

func (*SQL) RegisterPipe added in v0.8.0

func (d *SQL) RegisterPipe(name string, fn Pipe) *SQL

RegisterPipe 注册自定义管道, 返回新 builder:

q := db.RegisterPipe("upper", func(ctx RenderCtx, v any) error {
	ctx.AddParam(strings.ToUpper(fmt.Sprint(v)))
	return nil
})
q.Add("WHERE name = #{1|upper}", "bob") → $1 = "BOB"

func (*SQL) Rollback

func (d *SQL) Rollback() error

Rollback rolls back the active transaction.

func (*SQL) Rows

func (d *SQL) Rows() (*sqlx.Rows, error)

Rows returns a raw *sqlx.Rows cursor for streaming.

func (*SQL) Select

func (d *SQL) Select(table string, where string, args ...any) *SQL

Select generates a SELECT statement with ${F:*} for field expansion.

func (*SQL) SetLogger added in v0.11.0

func (d *SQL) SetLogger(fn LogFunc) *SQL

SetLogger 设置执行日志回调 (nil 关闭)。copy-on-write。

func (*SQL) ToSQL

func (d *SQL) ToSQL() (string, []any, error)

ToSQL returns the built SQL and arguments without executing.

func (*SQL) Transaction

func (d *SQL) Transaction(fn func(*SQL) error) error

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.

func (*SQL) Unsafe

func (d *SQL) Unsafe() *SQL

Unsafe returns a new builder that ignores unmapped columns.

func (*SQL) Update

func (d *SQL) Update(table string, data any, where string, args ...any) *SQL

Update generates and appends an UPDATE ... SET statement.

func (*SQL) Var

func (d *SQL) Var(key string, query string, args ...any) *SQL

Var registers a named variable for ${key} expansion.

func (*SQL) Vars

func (d *SQL) Vars(vars map[string]Node) *SQL

func (*SQL) WithCtx

func (d *SQL) WithCtx(ctx context.Context) *SQL

WithCtx returns a new builder with the given context.

type SQLExpr

type SQLExpr struct {
	Sql  string
	Args []any
}

SQLExpr wraps a raw SQL expression for Insert/Update values.

func Expr

func Expr(sql string, args ...any) SQLExpr

Expr creates a SQLExpr with optional bind arguments.

Jump to

Keyboard shortcuts

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