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 Map[T any, R any](slice []T, fn func(T) R) []R
- func MySQLQuoter(s string) string
- func Page[T any](q *SQL, page, size int) ([]T, int64, error)
- func QmarkFormat(_ int) string
- func Scalar[T any](d *SQL) (T, bool, error)
- type BeforeCreate
- type BeforeUpdate
- type Dao
- func (d *Dao[T]) All() ([]T, error)
- 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]) Get(where string, args ...any) (*T, error)
- func (d *Dao[T]) GetByID(id any) (*T, error)
- func (d *Dao[T]) List(where string, args ...any) ([]T, error)
- func (d *Dao[T]) PK(pk string) *Dao[T]
- func (d *Dao[T]) Page(page, size int, where string, args ...any) ([]T, int64, error)
- 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 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) Formatter(formatter Formatter) *SQL
- func (d *SQL) Get(dest any) (found bool, err error)
- func (d *SQL) GetMap() (map[string]any, bool, error)
- func (d *SQL) Insert(table string, data any) *SQL
- func (d *SQL) List(dest interface{}) error
- func (d *SQL) ListMap() ([]map[string]any, error)
- 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) Rows() (*sqlx.Rows, 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 default field variable name used by Select and Page. F 是 Select/Page 的列集槽位变量名。
契约:
- Select 生成 "${F:*}" (默认 *), Page 用 Var(F, "COUNT(1)") 换计数。
- 手写 SQL 接入 Page: 主链必须含 ${F:...} 或裸 ${F} (见 Page 的探测)。
- 约定 F 槽在主链 (mainNodes); 藏在 varNode 里的 ${F} 不被 Page 识别。
const I = "I"
I 是 INSERT 修饰词槽位 (INSERT ${I:} INTO ...), 默认为空。 存在理由: Insert 生成后, 链式 Add 只能追加尾部 (ON DUPLICATE KEY / RETURNING / ON CONFLICT 天然可达), 唯独 INSERT 与 INTO 之间是死角, 此槽是唯一通气孔:
db.Var(I, "IGNORE").Insert("users", u) // INSERT IGNORE INTO ...
const O = "order"
O 是排序槽位变量名。Page 的 count 查询会 Var(O, "") 清空它, 因此接入 Page 的查询应把 ORDER BY 写成 ${O:...} 而非裸文本:
q.Add("SELECT ... WHERE x ${O: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 Page ¶
Page 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 should live in the ${O:...} slot (the count query clears it with Var(O, "") — a bare ORDER BY still works but the count query pays the sort). Example:
q.Add("SELECT ... WHERE x ${O:ORDER BY id DESC}") // then Page(q, 1, 20)
The total==0 case skips the data query entirely.
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]) Get ¶
Get fetches a single record by condition. 未找到时返回 (nil, nil) —— “无结果”是正常业务结果而非错误 (不返回 sql.ErrNoRows); 调用方必须先判 nil 再解引用。
func (*Dao[T]) GetByID ¶
GetByID fetches a single record by primary key. 未找到时返回 (nil, nil) —— “无结果”是正常业务结果而非错误 (不返回 sql.ErrNoRows); 调用方必须先判 nil 再解引用。
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).
type LogFunc ¶ added in v0.11.0
LogFunc SQL 执行日志回调: 每次执行后调用一次 (begin 为执行开始时间, 观察者自行计算耗时/开 span; 不改变执行流, panic 不影响执行结果)。
type Pipe ¶ added in v0.8.0
Pipe 管道: 宏内容的解读者。
管道收到宏内容的字面量 (如 #{1|pipe} 的 "1"、@{users} 的 "users"), 由管道自行决定: 字面量直接用 (ident), 或经 ctx.Resolve 取参数 (bind/raw/expand)。 用户管道可自由选择 — 这是管道的灵活性所在。 内置: bind/expand/raw/quote/literalquote; 用户通过 RegisterPipe 注册。
type RenderCtx ¶ added in v0.8.0
type RenderCtx interface {
// Bind 绑定一个值: Node 内联渲染 (参数即子树), 其他值写占位符并收集参数。
// "参数即子树"不变式的唯一实现点 —— 管道一律经 Bind 处理参数值。
Bind(v any) error
// Render 内联渲染一个 Node 子片段 (递归, 用该 Node 自己的 Args)。
Render(n Node) error
// 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 ¶
NewFromSqlx creates a SQL builder from a sqlx.DB. Auto-detects driver for placeholder formatter and identifier quoting.
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) Formatter ¶ added in v0.12.0
Formatter returns a new builder with the given placeholder formatter.
func (*SQL) GetMap ¶ added in v0.12.0
GetMap scans a single row into a map — for queries whose columns are not known at compile time. found=false (nil map) when no row matches.
func (*SQL) List ¶
List scans multiple rows into a slice pointer (struct/basic types, sqlx mapping). For dynamic queries with unknown columns use ListMap.
func (*SQL) ListMap ¶ added in v0.12.0
ListMap scans multiple rows into a slice of maps — for queries whose columns are not known at compile time.
func (*SQL) RegisterMacro ¶ added in v0.8.0
RegisterMacro 注册宏别名 (前缀 → 管道名), 返回新 builder:
q := db.RegisterMacro('^', "upper")
q.Add("WHERE name = ^{1}", "bob") → 等价 #{1|upper}
'#'/'$' 为保留前缀不可注册; 管道名允许指向尚未注册的管道 (渲染时报错)。
func (*SQL) RegisterPipe ¶ added in v0.8.0
RegisterPipe 注册自定义管道, 返回新 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 内联, 普通值占位符
})
q.Add("WHERE name = #{1|upper}", "bob") → $1 = "BOB"
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.