Documentation
¶
Overview ¶
Package sqlb is a typed SQL layer for Go libraries that own database tables and cannot depend on an ORM.
The problem it solves is a specific one. A library such as an auth package ships its own tables, and the application that embeds it has tables of its own. The library must let the application join across that boundary, filter on its own columns and scan into its own structs, without the library knowing any of it, and without dragging in a code generator or an ORM that the application may already have a different copy of.
One package declares tables with typed columns; another joins them, and the compiler checks every column, join condition and scan target:
var Users = sqlb.Table{Name: "app_user", Alias: "u"}
var (
UserID = sqlb.Col[string](Users, "id")
UserEmail = sqlb.Col[string](Users, "email")
)
var id, email string
q, err := sqlb.NewSelect(sqlb.PostgresDialect{}).
Columns(sqlb.Bind(UserID, &id), sqlb.Bind(UserEmail, &email)).
From(Users).
Where(sqlb.Eq(UserEmail, "a@example.com")).
Build()
err = sqlb.One(ctx, db, q)
Nothing is passed to One for the destination, because the query already carries it. Bind captured the pointer, Build collected the pointers in SELECT order, and Scan writes straight through them. The column list and the scan targets come from one slice, so they cannot drift.
The condition that follows from it: a Query is not safe for concurrent use. Executing one from two goroutines is a data race, because those pointers are the caller's variables. Build the query where its destination lives, per call. One and Each refuse an overlapping execution with ErrQueryInUse rather than interleaving rows, which is detection and not prevention.
github.com/ubgo/sqlb/scan is the other strategy and does not have that hazard: it returns values rather than writing through pointers, so one Reader is safe to share across any number of concurrent executions. Neither is deprecated. Binding is shorter to write and fits most queries; scanning is what a query shared between goroutines, cached, or held in a struct field needs.
This package is a facade ¶
Everything here is an alias or a forwarder. The implementation lives in one package per layer, and a caller who wants only part of it can import that part directly:
render placeholders, identifier quoting, bound values; standard library only dialect one package per engine: dialect/postgres, dialect/sqlite, dialect/mysql, dialect/clickhouse expr tables, typed columns, predicates, aggregates, windows stmt SELECT, INSERT, UPDATE, DELETE, clause slots, Query exec running a statement and iterating its rows bind results written through caller pointers, re-exported here scan results returned as values, imported directly schema what tables exist, for generators and migrations, imported directly
Every layer compiles and is useful without anything above it and never imports upward, which is what lets a package outside this module replace any one of them. scan and schema are absent from this facade because their names would collide with ones already here, not because they are lesser.
What belongs here ¶
The core holds only what Postgres, MySQL 8, SQLite and ClickHouse all accept with the same syntax and the same meaning. Anything one engine spells differently lives in that engine's package, github.com/ubgo/sqlb/pg, github.com/ubgo/sqlb/sqlite or github.com/ubgo/sqlb/ch, even when two engines agree.
MySQL is a reference engine only. This module has no MySQL dialect and cannot render for it, so that quarter of the rule is checked by reading MySQL's documentation rather than by building a statement. The other three are real: each has a dialect package under dialect/ and a construct package. Every engine construct records its name through Args.Unsupported, so rendering it under the wrong dialect fails at Build with ErrUnsupportedDialect rather than at the database.
What it is not ¶
It is not an ORM. There is no relation graph, no code generation, no derived DDL and no lazy loading in this module, and there will not be.
That is a statement about this module rather than about the repository. github.com/ubgo/sqlb/schema describes what tables exist, and contrib modules act on that description, which is how DDL gets derived without any of it leaking down here. The separation is the point: a library that only needs to build a query pays for none of it.
Zero dependencies ¶
This module imports nothing outside the standard library, and a CI gate fails the build if that changes. A driver is a dependency, so driver integrations are separate modules under contrib/, and each one proves itself by running the shared conformance suite in github.com/ubgo/sqlb/sqlbtest against a real database.
Index ¶
- Constants
- Variables
- func CheckedFunctionName(a *render.Args, name, what string) string
- func CheckedKeyword(a *render.Args, s, what string) string
- func CheckedOperator(a *render.Args, op, what string) string
- func DialectName(d Dialect) string
- func Each(ctx context.Context, db DBTX, q Query, fn func() error) error
- func EngineGuard(a *Args, engine, construct string) bool
- func EngineList(a *Args, items []SQLer) string
- func EscapeLike(s string) string
- func One(ctx context.Context, db DBTX, q Query) error
- func PredicateSQL(p Predicate, a *render.Args) string
- func Quote(s string, q byte) string
- func QuoteList(d render.Dialect, names []string) string
- func Row(items ...render.SQLer) render.SQLer
- func Targets(bs []Binding) []any
- type AggOption
- type AggSpec
- type AnyClause
- type AnySelect
- type Args
- type Assignment
- type Binding
- type CTE
- type CaseBuilder
- type CaseInsensitiveLike
- type Clause
- type ClickHouseDialect
- type CombinedAlter
- type DBTX
- type Delete
- type DeleteKind
- type Dialect
- type Expr
- func Add[T Number](l, r Expr[T]) Expr[T]
- func Aggregate[R any](name string, args []render.SQLer, opts ...AggOption) Expr[R]
- func As[T any](e Expr[T], name string) Expr[T]
- func AssertNotNull[T any](e Expr[*T]) Expr[T]
- func Avg[T Number](e Expr[T], opts ...AggOption) Expr[float64]
- func Binary[R any](left render.SQLer, op string, right render.SQLer) Expr[R]
- func BoolExpr(p Predicate) Expr[bool]
- func Cast[R, T any](e Expr[T], sqlType string) Expr[R]
- func Coalesce[T any](first Expr[T], rest ...Expr[T]) Expr[T]
- func Col[T any](t Table, name string) Expr[T]
- func Concat(parts ...Expr[string]) Expr[string]
- func Count(opts ...AggOption) Expr[int64]
- func CountOf[T any](e Expr[T], opts ...AggOption) Expr[int64]
- func Div[T Number](l, r Expr[T]) Expr[T]
- func EngineBinOp[R any](engine, construct, op string, l, r SQLer) Expr[R]
- func EngineExpr[T any](engine, construct string, render func(a *Args) string) Expr[T]
- func EngineFn[R any](engine, construct, name string, args ...SQLer) Expr[R]
- func EngineLit[T any](engine, construct, sql string) Expr[T]
- func Fn[R any](name string, args ...render.SQLer) Expr[R]
- func Literal[T any](sql string) Expr[T]
- func Lower(e Expr[string]) Expr[string]
- func Max[T any](e Expr[T], opts ...AggOption) Expr[T]
- func Min[T any](e Expr[T], opts ...AggOption) Expr[T]
- func Mod[T Number](l, r Expr[T]) Expr[T]
- func Mul[T Number](l, r Expr[T]) Expr[T]
- func Neg[T Number](e Expr[T]) Expr[T]
- func New[T any](render func(a *render.Args) string) Expr[T]
- func NullIf[T any](l, r Expr[T]) Expr[*T]
- func Nullable[T any](e Expr[T]) Expr[*T]
- func OutputCol[T any](name string) Expr[T]
- func Over[T any](e Expr[T], w Window) Expr[T]
- func OverNamed[T any](e Expr[T], name string) Expr[T]
- func Param[T any](v T) Expr[T]
- func Sub[T Number](l, r Expr[T]) Expr[T]
- func Subquery[T any, D render.Dialect](s *Select[D]) Expr[*T]
- func Sum[T Number](e Expr[T], opts ...AggOption) Expr[T]
- func Upper(e Expr[string]) Expr[string]
- type FilteredDelete
- type FilteredUpdate
- type FrameBound
- type FrameExclude
- type FrameMode
- type Guard
- type Insert
- type InsertAliasing
- type InsertKind
- type InsertReady
- type Join
- type JoinType
- type LikeEscaping
- type LiteralQuoting
- type MySQLDialect
- type Named
- type NullsOrder
- type Number
- type NumericParameters
- type Option
- type OrderTerm
- type PostgresDialect
- type Predicate
- func And(preds ...Predicate) Predicate
- func Between[T any](e Expr[T], lo, hi T) Predicate
- func Compare(left render.SQLer, op string, right render.SQLer) Predicate
- func Contains(e Expr[string], value string) Predicate
- func ContainsFold(e Expr[string], value string) Predicate
- func EndsWith(e Expr[string], value string) Predicate
- func EndsWithFold(e Expr[string], value string) Predicate
- func EngineBinPred(engine, construct, op string, l, r SQLer) Predicate
- func EnginePred(engine, construct string, render func(a *Args) string) Predicate
- func Eq[T any](e Expr[T], v T) Predicate
- func EqExpr[T any](left, right Expr[T]) Predicate
- func EqFold(e Expr[string], value string) Predicate
- func Exists[D render.Dialect](s *Select[D]) Predicate
- func False() Predicate
- func Greater[T any](e Expr[T], v T) Predicate
- func GreaterEq[T any](e Expr[T], v T) Predicate
- func GreaterEqExpr[T any](left, right Expr[T]) Predicate
- func GreaterExpr[T any](left, right Expr[T]) Predicate
- func In[T any](e Expr[T], values ...T) Predicate
- func InExprs[T any](e Expr[T], items ...Expr[T]) Predicate
- func InFold(e Expr[string], values ...string) Predicate
- func InSubquery[T any, D render.Dialect](e Expr[T], s *Select[D]) Predicate
- func IsNotNull[T any](e Expr[T]) Predicate
- func IsNull[T any](e Expr[T]) Predicate
- func Less[T any](e Expr[T], v T) Predicate
- func LessEq[T any](e Expr[T], v T) Predicate
- func LessEqExpr[T any](left, right Expr[T]) Predicate
- func LessExpr[T any](left, right Expr[T]) Predicate
- func Like(e Expr[string], pattern string) Predicate
- func Not(p Predicate) Predicate
- func NotBetween[T any](e Expr[T], lo, hi T) Predicate
- func NotContains(e Expr[string], value string) Predicate
- func NotEq[T any](e Expr[T], v T) Predicate
- func NotEqExpr[T any](left, right Expr[T]) Predicate
- func NotExists[D render.Dialect](s *Select[D]) Predicate
- func NotIn[T any](e Expr[T], values ...T) Predicate
- func NotInFold(e Expr[string], values ...string) Predicate
- func NotInSubquery[T any, D render.Dialect](e Expr[T], s *Select[D]) Predicate
- func NotLike(e Expr[string], pattern string) Predicate
- func Or(preds ...Predicate) Predicate
- func PredicateOf(render func(a *render.Args) string) Predicate
- func RowEq(l, r render.SQLer) Predicate
- func RowGreater(l, r render.SQLer) Predicate
- func RowIn(row render.SQLer, rows ...render.SQLer) Predicate
- func RowLess(l, r render.SQLer) Predicate
- func RowNotIn(row render.SQLer, rows ...render.SQLer) Predicate
- func StartsWith(e Expr[string], value string) Predicate
- func StartsWithFold(e Expr[string], value string) Predicate
- func SubqueryCompare[D render.Dialect](e SQLer, op, quantifier string, s *Select[D]) Predicate
- func True() Predicate
- type Query
- type Returning
- type ReturningDialect
- type SQLer
- type SQLiteDialect
- type Select
- type SelectKind
- type Slot
- type SortDirection
- type Source
- type Statement
- type Table
- type UnrestrictedAddColumn
- type UntypedParameters
- type Update
- type UpdateKind
- type WinFn
- type Window
Constants ¶
const ( FrameRange = expr.FrameRange FrameRows = expr.FrameRows LogicAnd = expr.LogicAnd LogicNot = expr.LogicNot LogicOr = expr.LogicOr OpAdd = expr.OpAdd OpConcat = expr.OpConcat OpDiv = expr.OpDiv OpEq = expr.OpEq OpGreater = expr.OpGreater OpGreaterEq = expr.OpGreaterEq OpIn = expr.OpIn OpIsDistinctFrom = expr.OpIsDistinctFrom OpIsFalse = expr.OpIsFalse OpIsNotDistinctFrom = expr.OpIsNotDistinctFrom OpIsNotNull = expr.OpIsNotNull OpIsNull = expr.OpIsNull OpIsTrue = expr.OpIsTrue OpIsUnknown = expr.OpIsUnknown OpLess = expr.OpLess OpLessEq = expr.OpLessEq OpLike = expr.OpLike OpMod = expr.OpMod OpMul = expr.OpMul OpNotEq = expr.OpNotEq OpNotIn = expr.OpNotIn OpNotLike = expr.OpNotLike OpSub = expr.OpSub SortAsc = expr.SortAsc SortDesc = expr.SortDesc NullsFirst = expr.NullsFirst NullsLast = expr.NullsLast )
Constants re-exported from the expr layer. Go cannot alias a constant, so each is a new constant with the same value.
const ( DialectPostgres = render.DialectPostgres DialectSQLite = render.DialectSQLite DialectClickHouse = render.DialectClickHouse DialectMySQL = render.DialectMySQL DialectUnknown = render.DialectUnknown )
The engine names this module ships. Not a closed set; see render.
const ( JoinCross = stmt.JoinCross JoinInner = stmt.JoinInner JoinLeft = stmt.JoinLeft JoinRight = stmt.JoinRight SlotAfterColumns = stmt.SlotAfterColumns SlotAfterFrom = stmt.SlotAfterFrom SlotAfterGroupBy = stmt.SlotAfterGroupBy SlotAfterHaving = stmt.SlotAfterHaving SlotAfterInsert = stmt.SlotAfterInsert SlotAfterOffset = stmt.SlotAfterOffset SlotAfterOrder = stmt.SlotAfterOrder SlotAfterSelect = stmt.SlotAfterSelect SlotAfterSet = stmt.SlotAfterSet SlotAfterTarget = stmt.SlotAfterTarget SlotAfterVerb = stmt.SlotAfterVerb SlotAfterWhere = stmt.SlotAfterWhere SlotBeforeOrder = stmt.SlotBeforeOrder SlotBeforeValues = stmt.SlotBeforeValues SlotBeforeWhere = stmt.SlotBeforeWhere SlotInsertBody = stmt.SlotInsertBody SlotTail = stmt.SlotTail )
Constants re-exported from the stmt layer. Go cannot alias a constant, so each is a new constant with the same value.
Variables ¶
var ( // ErrNoRows is returned by One when the statement matched nothing. ErrNoRows = exec.ErrNoRows // ErrMultipleRows is returned by One when a statement expected to be // unique matched more than one row. ErrMultipleRows = exec.ErrMultipleRows )
Variables re-exported from the execution layer.
var ( OpValues = expr.OpValues SortDirectionValues = expr.SortDirectionValues NullsOrderValues = expr.NullsOrderValues FrameModeValues = expr.FrameModeValues ErrUnknownValue = expr.ErrUnknownValue )
Variables re-exported from the expr layer.
var ( ErrDuplicateAlias = stmt.ErrDuplicateAlias ErrJoinWithoutFrom = stmt.ErrJoinWithoutFrom ErrNoAssignments = stmt.ErrNoAssignments ErrNoColumns = stmt.ErrNoColumns ErrNoReturning = stmt.ErrNoReturning ErrNoTargets = stmt.ErrNoTargets ErrNoWhere = stmt.ErrNoWhere ErrNotAColumn = stmt.ErrNotAColumn ErrQueryInUse = stmt.ErrQueryInUse ErrRowWidth = stmt.ErrRowWidth ErrSetOpArity = stmt.ErrSetOpArity ErrUnknownSlot = stmt.ErrUnknownSlot JoinTypeValues = stmt.JoinTypeValues SlotValues = stmt.SlotValues )
Variables re-exported from the stmt layer.
var ErrNoLikeEscape = expr.ErrNoLikeEscape
ErrNoLikeEscape is recorded when a dialect cannot express an ESCAPE clause, so a user's text cannot be escaped safely.
var ErrNoLiteralQuoting = render.ErrNoLiteralQuoting
ErrNoLiteralQuoting reports a literal requested of a dialect without the capability.
var ErrNotInlinable = render.ErrNotInlinable
ErrNotInlinable reports a value a dialect will not write as a literal.
var ErrUnsupportedDialect = render.ErrUnsupportedDialect
ErrUnsupportedDialect is returned by Build when a construct was rendered through a dialect that does not support it.
var ErrZeroExpr = expr.ErrZeroExpr
ErrZeroExpr is recorded when a zero Expr is rendered. See expr.ErrZeroExpr.
Functions ¶
func CheckedFunctionName ¶
CheckedFunctionName writes a function name, or fails the render naming it. A name may be schema-qualified, which is why it is not one identifier. See expr.CheckedFunctionName.
func CheckedKeyword ¶
CheckedKeyword writes a keyword, or fails the render naming it. It is what makes JoinType and SetOp open in their set while checked in their text. See expr.CheckedKeyword.
func CheckedOperator ¶
CheckedOperator writes an operator, or fails the render naming it.
An operator cannot be quoted, so it reaches the statement text as the author wrote it; the shape check is what keeps that from being a hole. See expr.CheckedOperator.
func DialectName ¶
DialectName reports the engine name of d, or DialectUnknown.
func EngineGuard ¶
EngineGuard reports whether a is rendering for engine, and records the
func EngineList ¶
EngineList renders SQLers comma-separated, for a constructor assembling its
func EscapeLike ¶
EscapeLike escapes the characters LIKE treats as syntax, so a value can be used inside a pattern the caller builds.
func PredicateSQL ¶
PredicateSQL renders p to a string with the statement's Args. Engine
Types ¶
type AnyClause ¶
AnyClause is a clause with no dialect or kind in its type: what a Join carries for a per-table hint, and what every typed clause also satisfies.
type AnySelect ¶
AnySelect is a Select whose engine is only known at runtime; it accepts every universal construct and no engine clause.
type Args ¶
Args collects bound values during one render and carries the first error.
func NewInlineArgs ¶
NewInlineArgs returns Args whose Next writes every value as a literal, for a statement that takes no parameters. See render.NewInlineArgs.
type Assignment ¶
type Assignment = stmt.Assignment
Assignment is one column = value pair for INSERT and UPDATE. Built with
func AssignTarget ¶
func AssignTarget(col string, target func(a *Args) string, value SQLer) Assignment
AssignTarget makes an assignment whose target is an expression over col,
func Set ¶
func Set[T any](col Expr[T], v T) Assignment
Set assigns a bound value to a column of the same Go type.
type Binding ¶
Binding is a select or RETURNING item that carries a scan destination.
It is an interface defined by the statement layer, which knows only that an item renders and may carry a target. That the target is a pointer into a caller variable is decided by the bind package, which is also where the concurrency warning lives, because it is the layer that captured the memory.
func Bind ¶
Bind pairs e with dst. The compiler rejects a dst whose type is not *T.
The pointer is captured, not the value, and it lives as long as the query does. Two consequences worth knowing before they bite: Each writes every row through the same pointer, so a callback keeping a row must copy it; and a query built this way is NOT SAFE FOR CONCURRENT USE, because two goroutines would write through these pointers at once, which is a DATA RACE. Build the query where its destination lives. See One and ErrQueryInUse, and see github.com/ubgo/sqlb/scan for the strategy that returns values instead.
type CaseBuilder ¶
type CaseBuilder[T any] = expr.CaseBuilder[T]
CaseBuilder accumulates a searched CASE. Else yields Expr[T]; End yields
type CaseInsensitiveLike ¶
type CaseInsensitiveLike = render.CaseInsensitiveLike
CaseInsensitiveLike is satisfied by a dialect with ILIKE. See render.CaseInsensitiveLike for why the fold predicates ask for it.
type ClickHouseDialect ¶
type ClickHouseDialect = clickhouse.Dialect
ClickHouseDialect renders ? placeholders and backquoted identifiers. It deliberately does not satisfy Returning; ClickHouse has no RETURNING.
type CombinedAlter ¶
type CombinedAlter = render.CombinedAlter
CombinedAlter is satisfied by dialects that accept several actions in one ALTER TABLE. See render.CombinedAlter.
type Dialect ¶
Dialect is the two things SQL engines disagree on: how a bound parameter is written and how an identifier is quoted. See render.Dialect.
type Expr ¶
Expr is a SQL expression that evaluates to the Go type T.
func AssertNotNull ¶
AssertNotNull reinterprets a nullable expression as T without changing the
func EngineBinOp ¶
EngineBinOp renders "left op right" as a guarded expression typed R.
func EngineExpr ¶
EngineExpr makes a guarded expression typed T from a render function. It is
type FilteredDelete ¶
type FilteredDelete[D render.Dialect] = stmt.FilteredDelete[D]
FilteredDelete is a DELETE whose rows are stated, the only form that has Build; Where and All return it.
func DeleteReturning ¶
func DeleteReturning[D ReturningDialect](s *FilteredDelete[D], bs ...Binding) *FilteredDelete[D]
DeleteReturning adds RETURNING to a DELETE on a dialect that has it.
type FilteredUpdate ¶
type FilteredUpdate[D render.Dialect] = stmt.FilteredUpdate[D]
FilteredUpdate is an UPDATE whose rows are stated, the only form that has Build; Where and All return it.
func UpdateReturning ¶
func UpdateReturning[D ReturningDialect](s *FilteredUpdate[D], bs ...Binding) *FilteredUpdate[D]
UpdateReturning adds RETURNING to an UPDATE on a dialect that has it.
type FrameBound ¶
type FrameBound = expr.FrameBound
FrameBound is one end of a frame. Use the constructors below.
func CurrentRow ¶
func CurrentRow() FrameBound
CurrentRow bounds a frame at the current row. Under RANGE that means the
func FollowingExpr ¶
func FollowingExpr(sql string) FrameBound
FollowingExpr bounds a frame with an expression rather than a count, for a
func Preceding ¶
func Preceding(n int) FrameBound
Preceding bounds a frame n rows back under ROWS, or n units back under
func PrecedingExpr ¶
func PrecedingExpr(sql string) FrameBound
PrecedingExpr and FollowingExpr take a constant SQL expression as the
func UnboundedFollowing ¶
func UnboundedFollowing() FrameBound
UnboundedFollowing ends a frame at the last row of the partition.
func UnboundedPreceding ¶
func UnboundedPreceding() FrameBound
UnboundedPreceding starts a frame at the first row of the partition.
type FrameExclude ¶
type FrameExclude = expr.FrameExclude
FrameExclude is the EXCLUDE part of a frame. The constants are in pg,
type Guard ¶
Guard is the execution guard an engine package's statement builder owns, so every Query it and its derived statements build shares one.
type InsertAliasing ¶
type InsertAliasing = render.InsertAliasing
InsertAliasing is satisfied by dialects that accept "INSERT INTO t AS alias".
type InsertReady ¶
type InsertReady[D render.Dialect] = stmt.InsertReady[D]
InsertReady is an INSERT with a body, the only form that has Build; Row, Select and Body return it.
func InsertReturning ¶
func InsertReturning[D ReturningDialect](s *InsertReady[D], bs ...Binding) *InsertReady[D]
InsertReturning adds RETURNING to an INSERT on a dialect that has it.
type LikeEscaping ¶
type LikeEscaping = render.LikeEscaping
LikeEscaping is satisfied by dialects that accept an ESCAPE clause on LIKE. See render.LikeEscaping for why escaping a pattern is not portable.
type LiteralQuoting ¶
type LiteralQuoting = render.LiteralQuoting
LiteralQuoting is satisfied by a dialect that can write a value as a literal the engine reads back exactly. See render.LiteralQuoting.
type MySQLDialect ¶
MySQLDialect renders ? placeholders and backquoted identifiers. It does not satisfy Returning; MySQL has no RETURNING.
type NullsOrder ¶
type NullsOrder = expr.NullsOrder
NullsOrder is where NULLs sort relative to values; see expr.NullsOrder.
type NumericParameters ¶
type NumericParameters = render.NumericParameters
NumericParameters is satisfied by a dialect that widens an untyped integer parameter beside a DECIMAL. See render.NumericParameters for the MySQL measurement behind it.
type Option ¶
Option extends a statement that a library built, from code that the library
func WithColumns ¶
WithColumns adds bindings after the library's own, so the library's scan
type PostgresDialect ¶
PostgresDialect renders $1, $2 placeholders and double-quoted identifiers.
The three dialects below are aliases because each one now lives in its own package under dialect/, built the way a dialect from another repository is built: importing the render layer and nothing else. Keeping the old names here means the split cost no caller an import, and it keeps a one-import entry point for code that just needs to say which engine it targets.
type Predicate ¶
Predicate is a boolean condition for WHERE or ON.
func Contains ¶
Contains renders e LIKE '%value%' with value escaped, the predicate behind a search box.
func ContainsFold ¶
ContainsFold is Contains regardless of case: ILIKE on a dialect that has it, lower() LIKE lower() elsewhere.
func EndsWithFold ¶
EndsWithFold is EndsWith regardless of case.
func EngineBinPred ¶
EngineBinPred renders "left op right" as a guarded predicate.
func EnginePred ¶
EnginePred makes a guarded predicate from a render function.
func EqFold ¶
EqFold matches e against value regardless of case, lower(e) = lower(value) on every engine. See expr.EqFold for the index and collation notes.
func False ¶
func False() Predicate
False renders FALSE, which fails a query closed. It is what an empty IN
func GreaterEqExpr ¶
GreaterEqExpr renders left >= right.
func GreaterExpr ¶
GreaterExpr renders left > right.
func InSubquery ¶
InSubquery renders e IN (SELECT ...). The subquery must select one item
func LessEqExpr ¶
LessEqExpr renders left <= right.
func NotBetween ¶
NotBetween is the negated form.
func NotContains ¶
NotContains renders e NOT LIKE '%value%' with value escaped.
func NotInFold ¶
NotInFold matches e against none of values regardless of case; an empty list is TRUE.
func NotInSubquery ¶
NotInSubquery renders e NOT IN (SELECT ...). Beware the NULL rule: if the
func PredicateOf ¶
PredicateOf makes a Predicate from a render function. Engine packages use
func RowGreater ¶
RowGreater renders l > r for two row constructors.
func RowIn ¶
RowIn renders (a, b) IN ((?, ?), ...), the composite-key membership test. An empty list renders FALSE.
func RowNotIn ¶
RowNotIn renders (a, b) NOT IN ((?, ?), ...). An empty list renders TRUE, and a NULL anywhere in the list makes the whole predicate NULL.
func StartsWith ¶
StartsWith renders e LIKE 'value%' with value escaped. Prefer it to Contains where it fits: a prefix match can use an index and a leading wildcard cannot.
func StartsWithFold ¶
StartsWithFold is StartsWith regardless of case.
func SubqueryCompare ¶
SubqueryCompare renders "e op [quantifier] (SELECT ...)". It is the
type Query ¶
Query is a rendered statement: SQL text, the bound values in placeholder
func NewGuardedQuery ¶
NewGuardedQuery is NewQuery for a builder that owns a Guard.
type ReturningDialect ¶
type ReturningDialect = stmt.ReturningDialect
ReturningDialect is a dialect that has RETURNING; see stmt.ReturningDialect.
type SQLer ¶
SQLer is anything that can render itself into SQL text using the statement's Args.
func EngineQuoteLit ¶
EngineQuoteLit renders s as a single-quoted SQL literal with embedded
type SQLiteDialect ¶
SQLiteDialect renders ? placeholders and double-quoted identifiers.
type SortDirection ¶
type SortDirection = expr.SortDirection
SortDirection is the ORDER BY direction.
type Source ¶
Source is anything that can stand in FROM or be joined: a table, a derived
func EngineSource ¶
EngineSource makes a guarded FROM source, for a set-returning function or
type UnrestrictedAddColumn ¶
type UnrestrictedAddColumn = render.UnrestrictedAddColumn
UnrestrictedAddColumn is satisfied by dialects whose ADD COLUMN takes any column. See render.UnrestrictedAddColumn.
type UntypedParameters ¶
type UntypedParameters = render.UntypedParameters
UntypedParameters is satisfied by a dialect that must be told a bound parameter's type in a function taking any. See render.UntypedParameters.
type WinFn ¶
WinFn is a window function or an aggregate that has not yet been given its
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package bind is the result strategy that writes rows through pointers the caller supplied.
|
Package bind is the result strategy that writes rows through pointers the caller supplied. |
|
Package ch holds the ClickHouse dialect and what only ClickHouse has: PREWHERE, FINAL, SAMPLE, ARRAY JOIN, LIMIT BY, SETTINGS, the argMax and uniq aggregates, the -If combinator and the toStartOf* time functions.
|
Package ch holds the ClickHouse dialect and what only ClickHouse has: PREWHERE, FINAL, SAMPLE, ARRAY JOIN, LIMIT BY, SETTINGS, the argMax and uniq aggregates, the -If combinator and the toStartOf* time functions. |
|
contrib
|
|
|
debug
module
|
|
|
driver-mysql
module
|
|
|
driver-pgx
module
|
|
|
driver-sqlite
module
|
|
|
migrate
module
|
|
|
structbind
module
|
|
|
vet
module
|
|
|
Package ddl builds the statements that create, change and remove what a library's tables are: CREATE TABLE, ALTER TABLE, DROP TABLE and the rest.
|
Package ddl builds the statements that create, change and remove what a library's tables are: CREATE TABLE, ALTER TABLE, DROP TABLE and the rest. |
|
dialect
|
|
|
clickhouse
Package clickhouse is the ClickHouse dialect: positional placeholders and backtick-quoted identifiers.
|
Package clickhouse is the ClickHouse dialect: positional placeholders and backtick-quoted identifiers. |
|
mysql
Package mysql is the MySQL dialect: how MySQL 8 writes a bound parameter and quotes an identifier, and which optional capabilities it has.
|
Package mysql is the MySQL dialect: how MySQL 8 writes a bound parameter and quotes an identifier, and which optional capabilities it has. |
|
postgres
Package postgres is the Postgres dialect: how Postgres writes a bound parameter and quotes an identifier, and which optional capabilities it has.
|
Package postgres is the Postgres dialect: how Postgres writes a bound parameter and quotes an identifier, and which optional capabilities it has. |
|
sqlite
Package sqlite is the SQLite dialect: positional placeholders and double-quoted identifiers.
|
Package sqlite is the SQLite dialect: positional placeholders and double-quoted identifiers. |
|
examples
|
|
|
cookbook/app
Package app is the application side of the cross-package story: the code that owns no library, imports three of them, and consolidates what they each own into one statement.
|
Package app is the application side of the cross-package story: the code that owns no library, imports three of them, and consolidates what they each own into one statement. |
|
cookbook/authlite
Package authlite is a deliberately small stand-in for a ubgo library that owns tables, for the cookbook.
|
Package authlite is a deliberately small stand-in for a ubgo library that owns tables, for the cookbook. |
|
cookbook/phone
Package phone is the plugin shape: it borrows a core table under its own alias and contributes a join plus bindings to a composite user.
|
Package phone is the plugin shape: it borrows a core table under its own alias and contributes a join plus bindings to a composite user. |
|
cookbook/workspace
Package workspace is the second-library shape: it owns tables that refer to a user by id, and it does not import the auth library.
|
Package workspace is the second-library shape: it owns tables that refer to a user by id, and it does not import the auth library. |
|
pgsurface/advancedsql
Package advancedsql translates an external catalogue of advanced PostgreSQL queries into sqlb and checks the rendered SQL.
|
Package advancedsql translates an external catalogue of advanced PostgreSQL queries into sqlb and checks the rendered SQL. |
|
pgsurface/periodcompare
Package periodcompare builds a period-comparison report over several fact tables in Postgres: sales for the current, previous and third-year periods, current stock, stock at a past snapshot date, open purchase orders and advertising spend, all keyed by one chosen dimension.
|
Package periodcompare builds a period-comparison report over several fact tables in Postgres: sales for the current, previous and third-year periods, current stock, stock at a past snapshot date, open purchase orders and advertising spend, all keyed by one chosen dimension. |
|
pgsurface/snippets
Package snippets translates a catalogue of advanced PostgreSQL snippets into sqlb, section by section and in the catalogue's own order and numbering.
|
Package snippets translates a catalogue of advanced PostgreSQL snippets into sqlb, section by section and in the catalogue's own order and numbering. |
|
Package exec runs a built statement against a database and iterates its rows.
|
Package exec runs a built statement against a database and iterates its rows. |
|
Package expr is the typed half of the builder: a table, a column with a Go type, a bound parameter, a predicate, an aggregate, a window, and the operators that join them.
|
Package expr is the typed half of the builder: a table, a column with a Go type, a bound parameter, a predicate, an aggregate, a window, and the operators that join them. |
|
Package mysql holds what only MySQL has, and is where a MySQL statement starts.
|
Package mysql holds what only MySQL has, and is where a MySQL statement starts. |
|
Package pg holds what only Postgres has.
|
Package pg holds what only Postgres has. |
|
crypto
Package crypto is the pgcrypto extension: hashing, password hashing and symmetric encryption on the server.
|
Package crypto is the pgcrypto extension: hashing, password hashing and symmetric encryption on the server. |
|
earth
Package earth is the earthdistance extension (with cube): great-circle distance and bounding boxes on the sphere.
|
Package earth is the earthdistance extension (with cube): great-circle distance and bounding boxes on the sphere. |
|
fuzzy
Package fuzzy is the fuzzystrmatch extension: phonetic and edit-distance matching.
|
Package fuzzy is the fuzzystrmatch extension: phonetic and edit-distance matching. |
|
ltree
Package ltree is the ltree extension: a materialized-path label tree with its own operators.
|
Package ltree is the ltree extension: a materialized-path label tree with its own operators. |
|
postgis
Package postgis is the template for adding a Postgres extension without touching pg.
|
Package postgis is the template for adding a Postgres extension without touching pg. |
|
trgm
Package trgm is the pg_trgm extension: trigram similarity operators and functions.
|
Package trgm is the pg_trgm extension: trigram similarity operators and functions. |
|
unaccent
Package unaccent is the unaccent extension: strip diacritics before comparing or indexing text.
|
Package unaccent is the unaccent extension: strip diacritics before comparing or indexing text. |
|
vector
Package vector is the pgvector extension: the four vector types, every distance operator and function, the utility functions, aggregates, arithmetic, casts, and the query-time settings.
|
Package vector is the pgvector extension: the four vector types, every distance operator and function, the utility functions, aggregates, arithmetic, casts, and the query-time settings. |
|
Package render is the bottom of the builder: how a value becomes a bound parameter, how an identifier is escaped, and how the first error of a render is carried out.
|
Package render is the bottom of the builder: how a value becomes a bound parameter, how an identifier is escaped, and how the first error of a render is carried out. |
|
Package scan is a result strategy that returns values instead of writing through pointers.
|
Package scan is a result strategy that returns values instead of writing through pointers. |
|
Package schema describes what tables exist, so that two packages which do not know about each other can still be migrated together.
|
Package schema describes what tables exist, so that two packages which do not know about each other can still be migrated together. |
|
Package sqlbtest is the conformance suite every sqlb driver integration runs.
|
Package sqlbtest is the conformance suite every sqlb driver integration runs. |
|
Package sqlite holds what only SQLite has.
|
Package sqlite holds what only SQLite has. |
|
Package stmt assembles SQL statements: SELECT, INSERT, UPDATE and DELETE, the clause positions they can carry, and the Query a build produces.
|
Package stmt assembles SQL statements: SELECT, INSERT, UPDATE and DELETE, the clause positions they can carry, and the Query a build produces. |