pg

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

pg — PostgreSQL statements and constructs

Everything Postgres in one import. Statements start here, pg.Select, pg.Insert, pg.Update and pg.Delete, with the dialect in their type; and every Postgres construct that goes inside them is here too: arrays, JSONB, ranges, full-text search, DISTINCT ON, ON CONFLICT, MERGE, locking, and eight extension sub-packages built on the guarded constructors it exports.

A rendering test proves the text, and only execution proves the SQL. Running these constructs against a real Postgres 17 from contrib/driver-pgx found eleven whose rendering tests passed and whose SQL Postgres rejects. A new construct here is not done until it has an entry in that driver's catalogue. Extensions never edit this package — that is what the exported guarded constructors are for.

Full documentation

The page for this package is docs/pg/README.md, with runnable snippets — every one of them copied from a test whose expected output go test checks. The documentation index is ../docs/README.md and the repository README is ../README.md.

Documentation

Overview

Package pg holds what only Postgres has. A library that imports it is a Postgres library, and its import list says so. Every construct here records Args.Unsupported when rendered through another dialect, so Build fails closed instead of the database failing at runtime.

The dialect itself is sqlb.PostgresDialect in the core; it is ten lines and every engine needs its dialect available without an extra import.

Files: json.go, sqljson.go, jsontable.go, array.go, text.go, time.go, range.go, fts.go, math.go, source.go, lock.go, write.go (ON CONFLICT), merge.go, recursive.go, misc.go, more.go, ext.go.

Extensions live in sub-packages, one per CREATE EXTENSION: pg/vector, pg/trgm, pg/fuzzy, pg/ltree, pg/crypto, pg/earth, pg/unaccent, and pg/postgis as the template. Each builds on ext.go and imports nothing else from here.

Index

Constants

View Source
const (
	ExcludeCurrentRow sqlb.FrameExclude = "EXCLUDE CURRENT ROW"
	ExcludeGroup      sqlb.FrameExclude = "EXCLUDE GROUP"
	ExcludeTies       sqlb.FrameExclude = "EXCLUDE TIES"
	ExcludeNoOthers   sqlb.FrameExclude = "EXCLUDE NO OTHERS"
)

Frame EXCLUDE values. Postgres and SQLite only.

View Source
const FrameGroups sqlb.FrameMode = "GROUPS"

FrameGroups is the GROUPS frame mode. Postgres and SQLite only.

View Source
const JoinFull sqlb.JoinType = "FULL JOIN"

JoinFull is FULL OUTER JOIN. MySQL has none, so it is here.

Variables

View Source
var (
	InsertReturning = sqlb.InsertReturning[Dialect]
	UpdateReturning = sqlb.UpdateReturning[Dialect]
	DeleteReturning = sqlb.DeleteReturning[Dialect]
)

InsertReturning, UpdateReturning and DeleteReturning add RETURNING to a complete write. They are the core's functions constrained to a dialect with the capability, instantiated for Postgres; an engine without RETURNING has no such names in its package, so the line cannot be written there.

View Source
var (
	JSONBPathOps = NewOpClass[json.RawMessage]("jsonb_path_ops")
	JSONBOps     = NewOpClass[json.RawMessage]("jsonb_ops")
)

The jsonb operator classes. JSONBPathOps is smaller and faster and serves only @>; JSONBOps, the default, also serves the key-existence operators.

BoundsValues is the four inclusivity combinations.

DateFieldValues is every field extract and date_trunc accept, the four in more.go included. A field added to either list belongs here too, which TestClosedSets_EveryConstantIsInItsValues checks by reading the source.

View Source
var ErrBadCache = errors.New("sqlb/pg: a sequence cache must be at least 1")

ErrBadCache is returned for a sequence cache below 1, which Postgres refuses.

View Source
var ErrCascadeNeedsDrop = errors.New("sqlb/pg: CASCADE follows DROP CONSTRAINT and no other domain action")

ErrCascadeNeedsDrop is returned for a CASCADE on an ALTER DOMAIN action that is not a DROP CONSTRAINT, the one action Postgres allows it after.

View Source
var ErrConflictTarget = errors.New("sqlb/pg: ON CONFLICT DO UPDATE needs conflict columns or a constraint")

ErrConflictTarget is returned for ON CONFLICT DO UPDATE with no conflict target: Postgres accepts DO NOTHING without one and refuses DO UPDATE, because it cannot tell which unique key's row to update.

View Source
var ErrConstraintAlterMix = errors.New("sqlb/pg: ALTER CONSTRAINT takes INHERIT or NO INHERIT alone")

ErrConstraintAlterMix is returned for an ALTER CONSTRAINT that combines INHERIT or NO INHERIT with the other options: Postgres 18's grammar has them as two separate forms.

View Source
var ErrEmptyBody = errors.New("sqlb/pg: a function needs a body")

ErrEmptyBody is returned for a trigger function with no body.

View Source
var ErrEmptyName = errors.New("sqlb/pg: object has no name")

ErrEmptyName is returned for an object value with no name.

View Source
var ErrForeignDomain = errors.New("sqlb/pg: constraint belongs to another domain")

ErrForeignDomain is returned for a DomainConstraint of one domain used in a statement about another.

View Source
var ErrIncompleteMerge = errors.New("sqlb/pg: MERGE needs Into, Using, On and at least one WHEN branch")

ErrIncompleteMerge is returned by Build for a MERGE without its target, its source, its join condition or a WHEN branch. Each is required by the grammar; a MERGE with no USING dereferenced a nil source inside Build until 2026-09-22, and that was reachable through NewMerge, not only a literal.

View Source
var ErrIncompleteSpec = errors.New("sqlb/pg: a column, column list or JSON pair is missing a required part")

ErrIncompleteSpec is returned for a caller-written specification with a required part empty: a RecordSet or JSON_TABLE column list with no columns, a column with no name or type, a NESTED PATH with no path, a JSON object pair with no value. Those types have exported fields and are written as literals, so the zero value is the easy mistake; before this, a pair with no value panicked inside Build and an empty column rendered "" for the server to reject.

View Source
var ErrIndexSchema = errors.New("sqlb/pg: the index and its table are declared in different schemas")

ErrIndexSchema is returned when the Index handed to AddUniqueUsingIndex or AddPrimaryKeyUsingIndex declares a schema its table does not, which is a declaration the statement cannot honour: the index name is written bare, so a schema set here would otherwise be dropped in silence.

View Source
var ErrMixedReferences = errors.New("sqlb/pg: a foreign key references one table")

ErrMixedReferences is returned for a foreign key whose referenced columns are on more than one table, which no engine accepts.

View Source
var ErrNoBound = errors.New("sqlb/pg: a partition needs bounds or Default")

ErrNoBound is returned for a partition with neither bounds nor Default.

View Source
var ErrNoLockTables = errors.New("pg: LOCK TABLE names no table")

ErrNoLockTables is returned by Build when no table was named.

View Source
var ErrNoResult = errors.New("sqlb/pg: a function needs a result type or an output parameter")

ErrNoResult is returned for a function that neither says what it returns nor carries an output parameter, which Postgres refuses: there is nothing to call the function for and nothing to type the call site with.

View Source
var ErrNoTables = errors.New("pg: TRUNCATE names no table")

ErrNoTables is returned by Build when no table was named, which would otherwise render a statement the database rejects.

View Source
var ErrNotBits = errors.New("sqlb/pg: a bit literal holds only the digits 0 and 1")

ErrNotBits is returned by BitLit for text that is not a bit string. A bit literal cannot be written through the dialect's quoting — B'1011' is its own syntax and the quoting would make it an ordinary string — so the only defence is the shape, and Postgres's shape for it is exactly the digits 0 and 1.

View Source
var ErrRecursiveColumns = errors.New("sqlb/pg: a recursive view needs a column list")

ErrRecursiveColumns is returned for a recursive view with no column list, which Postgres refuses: the recursive reference in the body needs names before the body has produced any.

View Source
var ErrRenameAcrossTables = errors.New("sqlb/pg: RenameConstraint names constraints of two tables")

ErrRenameAcrossTables is returned by RenameConstraint for two constraints of different tables: a constraint is renamed within its table and cannot move to another.

View Source
var ErrRenameAlone = errors.New("sqlb/pg: a sequence rename takes no other option")

ErrRenameAlone is returned for a sequence rename given another option too: RENAME TO is a statement of its own in Postgres's grammar.

View Source
var ErrRenamePolicyAlone = errors.New("sqlb/pg: a policy rename takes no other change")

ErrRenamePolicyAlone is returned for an ALTER POLICY that both renames the policy and changes it, which Postgres has no form for.

View Source
var ErrSingleExpression = errors.New("sqlb/pg: a single-expression statistics object takes one element and no kinds")

ErrSingleExpression is returned for a one-expression statistics object given a second element or a kind, which Postgres's grammar has no form for: the single-expression form measures one expression's own distribution and the multi-element form measures how elements depend on each other.

View Source
var ErrTriggerSignature = errors.New("sqlb/pg: a trigger function declares no parameters")

ErrTriggerSignature is returned by CreateTriggerFunction for a Function that declares parameters. A trigger function takes none: Postgres passes it the rows through PL/pgSQL's OLD and NEW, and a declared parameter would be silently dropped from the statement it renders.

View Source
var ErrUnknownKeyword = errors.New("sqlb/pg: value outside its named constants")

ErrUnknownKeyword is returned for a referential action, deferral or identity kind outside the named constants, such as a zero value.

View Source
var ErrUnknownValue = errors.New("sqlb/pg: value is not one of this type's constants")

ErrUnknownValue is returned for a value of a closed named string type that is not one of the package's own constants: pg.TrimSide("; DROP TABLE t") compiles, and this is where it stops.

View Source
var ErrUnnamedConstraint = errors.New("sqlb/pg: a guarded constraint needs a name")

ErrUnnamedConstraint is returned for an unnamed constraint where a name is what makes repeating the statement safe: under Guarded, an unnamed foreign key raises no duplicate_object and is simply added a second time.

JSONKindValues is every qualifier IS JSON accepts, the empty one included: JSONAny is a legitimate value and tests only that the text parses as JSON.

View Source
var NormalFormValues = []NormalForm{NFC, NFD, NFKC, NFKD}

NormalFormValues is every Unicode normalization form.

View Source
var SampleMethodValues = []SampleMethod{SampleBernoulli, SampleSystem}

SampleMethodValues is the two sampling methods every Postgres has. It is NOT the set a value is validated against: an extension brings its own, so TableSample checks the shape of a keyword instead. The slice is here for a caller iterating what this package names.

TableLockModeValues is the canonical iteration order over the lock modes, weakest first, so a validator or a documentation generator reads the same list this package writes from.

TrimSideValues is every side trim accepts.

View Source
var WeightValues = []Weight{WeightA, WeightB, WeightC, WeightD}

WeightValues is the four tsvector labels.

Functions

func Abs

func Abs[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

Abs renders abs(e).

This and the three below keep the operand type, because Postgres does: rounding an integer column does not silently widen it to a float in the Go type, so a bound target stays the type the column actually returns.

func AddInterval

func AddInterval(e sqlb.Expr[time.Time], iv Interval) sqlb.Expr[time.Time]

AddInterval renders e + $n::interval; SubInterval renders e - $n::interval.

func AddIntervalExpr

func AddIntervalExpr(e sqlb.Expr[time.Time], iv sqlb.Expr[Interval]) sqlb.Expr[time.Time]

AddIntervalExpr renders (e + iv) for an interval expression, so a literal interval and a bound one use the same form.

func Adjacent

func Adjacent[T any](l, r sqlb.Expr[Range[T]]) sqlb.Predicate

Adjacent renders l -|- r: the two touch without overlapping. Only meaningful with half-open bounds; two inclusive ranges that touch overlap.

func AdvisoryXactLock

func AdvisoryXactLock(key sqlb.SQLer) sqlb.Expr[[]byte]

AdvisoryXactLock renders pg_advisory_xact_lock(key), a transaction-scoped advisory lock.

Transaction-scoped is the safe half of the advisory-lock family: the lock is released when the transaction ends, so a crashed process cannot hold it forever. The session-scoped variants are deliberately absent.

func AdvisoryXactLock2

func AdvisoryXactLock2(namespace int32, key sqlb.SQLer) sqlb.Expr[[]byte]

AdvisoryXactLock2 renders pg_advisory_xact_lock(namespace, key), the two-argument form. The namespace keeps one application's keys from colliding with another's in the single global lock space.

func Age

func Age(l, r sqlb.Expr[time.Time]) sqlb.Expr[Interval]

Age renders age(l, r).

func AllExpr

func AllExpr[T any](left sqlb.Expr[T], op CompareOp, arr sqlb.Expr[[]T]) sqlb.Predicate

AllExpr renders left op ALL(array): the comparison holds against every element. An empty array makes it true, which is the opposite of AnyExpr.

func AllOf

func AllOf[T any](e sqlb.Expr[T], op string, s *sqlb.Select[Dialect]) sqlb.Predicate

AllOf renders e op ALL (SELECT ...): the comparison holds against every row the subquery returns, and an empty subquery makes it true.

func AllOp

func AllOp[T any](col sqlb.Expr[[]T], op string, v T) sqlb.Predicate

AllOp renders $n op ALL(col).

func Any

func Any[T any](col sqlb.Expr[[]T], v T) sqlb.Predicate

Any renders $n = ANY(col): the array holds v. AnyOp renders $n op ANY(col).

func AnyExpr

func AnyExpr[T any](left sqlb.Expr[T], op CompareOp, arr sqlb.Expr[[]T]) sqlb.Predicate

AnyExpr renders left op ANY(array) and AllExpr left op ALL(array), for an array expression such as a path column, where Any and AllOp take a value.

func AnyOf

func AnyOf[T any](e sqlb.Expr[T], op string, s *sqlb.Select[Dialect]) sqlb.Predicate

AnyOf renders e op ANY (SELECT ...); AllOf renders e op ALL (SELECT ...). SQLite has neither.

func AnyOp

func AnyOp[T any](col sqlb.Expr[[]T], op string, v T) sqlb.Predicate

AnyOp renders $n op ANY(col) for an operator other than equality, such as a comparison or a pattern match against every element.

func Array

func Array[T any](vals ...T) sqlb.Expr[[]T]

Array renders ARRAY[$1::type, $2::type, ...] with every element bound and cast to the type T binds as. The cast is not decoration: ARRAY[$1, $2] gives Postgres nothing to type the parameters by, so it resolves them to text and the driver refuses to encode an integer there. Found by running this against a real server; every rendering test had passed.

func ArrayAgg

func ArrayAgg[T any](e sqlb.Expr[T], opts ...sqlb.AggOption) sqlb.Expr[[]T]

ArrayAgg collects values into a slice.

func ArrayAppend

func ArrayAppend[T any](col sqlb.Expr[[]T], v T) sqlb.Expr[[]T]

ArrayAppend renders array_append(col, v), adding one element at the end.

func ArrayCat

func ArrayCat[T any](l, r sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArrayCat renders array_cat(l, r), the two arrays end to end.

func ArrayConcat

func ArrayConcat[T any](l, r sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArrayConcat renders l || r.

func ArrayContainedBy

func ArrayContainedBy[T any](col sqlb.Expr[[]T], v []T) sqlb.Predicate

ArrayContainedBy renders col <@ $n: every element of col appears in v. It is the mirror of ArrayContains, and getting the direction wrong is easy enough that the Go names say which side is which.

func ArrayContainedByExpr

func ArrayContainedByExpr[T any](l, r sqlb.Expr[[]T]) sqlb.Predicate

ArrayContainedByExpr renders l <@ r for two array expressions.

func ArrayContains

func ArrayContains[T any](col sqlb.Expr[[]T], v []T) sqlb.Predicate

ArrayContains renders col @> $n; ArrayContainedBy col <@ $n; Overlaps col && $n.

func ArrayContainsExpr

func ArrayContainsExpr[T any](l, r sqlb.Expr[[]T]) sqlb.Predicate

ArrayContainsExpr renders l @> r for two array expressions.

func ArrayDims

func ArrayDims[T any](col sqlb.Expr[[]T]) sqlb.Expr[*string]

ArrayDims renders array_dims(col), the shape as a text literal such as "[1:3]". Nullable: an empty array has no dimensions at all.

func ArrayElements

func ArrayElements(col sqlb.Expr[json.RawMessage], alias string) (sqlb.Source, sqlb.Expr[json.RawMessage])

ArrayElements renders jsonb_array_elements(col) AS alias (value).

func ArrayElementsScalar

func ArrayElementsScalar(doc sqlb.SQLer) sqlb.Expr[json.RawMessage]

ArrayElementsScalar renders jsonb_array_elements(doc) in the select list.

func ArrayElementsText

func ArrayElementsText(col sqlb.Expr[json.RawMessage], alias string) (sqlb.Source, sqlb.Expr[string])

ArrayElementsText renders jsonb_array_elements_text(col) AS alias (value).

func ArrayLength

func ArrayLength[T any](col sqlb.Expr[[]T], dim int) sqlb.Expr[*int32]

ArrayLength renders array_length(col, dim), 1-based. It is nullable on purpose: Postgres returns NULL for an empty array rather than 0, and a caller that treats the two alike writes a bug the type system can catch.

func ArrayLit

func ArrayLit[T any](text, sqlType string) sqlb.Expr[[]T]

ArrayLit renders an array literal in text form, for the odd shapes a Param cannot express such as a non-default lower bound.

text is written by the dialect's literal quoting, so it may hold anything; sqlType is written as is and is the author's text, for the reason EmptyArray gives.

func ArrayLower

func ArrayLower[T any](col sqlb.Expr[[]T], dim int) sqlb.Expr[*int32]

ArrayLower renders array_lower(col, dim), the first subscript of a dimension.

Postgres arrays are not necessarily 1-based, which is the trap this exists for: a slice built by array_remove or by a slice expression can start at any index, so code that assumes 1 is wrong on arrays it did not construct.

func ArrayNDims

func ArrayNDims[T any](col sqlb.Expr[[]T]) sqlb.Expr[*int32]

ArrayNDims renders array_ndims(col), the number of dimensions. Nullable for the same reason as ArrayDims.

func ArrayOf

func ArrayOf[T any](items ...sqlb.Expr[T]) sqlb.Expr[[]T]

ArrayOf renders ARRAY[e1, e2, ...] from expressions, typed by the element.

func ArrayPosition

func ArrayPosition[T any](col sqlb.Expr[[]T], v T) sqlb.Expr[*int32]

ArrayPosition renders array_position(col, v): the 1-based index of the first match. Nullable, because a value that is absent yields NULL and not a sentinel index.

func ArrayPositions

func ArrayPositions[T any](col sqlb.Expr[[]T], v T) sqlb.Expr[[]int32]

ArrayPositions renders array_positions(col, v).

func ArrayPrepend

func ArrayPrepend[T any](v T, col sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArrayPrepend renders array_prepend(v, col). The value comes first, matching Postgres and reversing the argument order of ArrayAppend.

func ArrayRemove

func ArrayRemove[T any](col sqlb.Expr[[]T], v T) sqlb.Expr[[]T]

ArrayRemove renders array_remove(col, v), dropping every element equal to v rather than the first.

func ArrayRemoveNull

func ArrayRemoveNull[T any](col sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArrayRemoveNull renders array_remove(col, NULL).

func ArrayReplace

func ArrayReplace[T any](col sqlb.Expr[[]T], from, to T) sqlb.Expr[[]T]

ArrayReplace renders array_replace(col, from, to), replacing every match.

func ArrayReverse

func ArrayReverse[T any](col sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArrayReverse renders array_reverse(col). Postgres 18.

func ArraySample

func ArraySample[T any](col sqlb.Expr[[]T], n int) sqlb.Expr[[]T]

ArraySample renders array_sample(col, n), n elements chosen at random. Postgres 16.

func ArrayShuffle

func ArrayShuffle[T any](col sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArrayShuffle renders array_shuffle(col). Postgres 16.

func ArraySort

func ArraySort[T any](col sqlb.Expr[[]T]) sqlb.Expr[[]T]

ArraySort renders array_sort(col). Postgres 18.

func ArraySortDesc

func ArraySortDesc[T any](col sqlb.Expr[[]T], descending bool) sqlb.Expr[[]T]

ArraySortDesc renders array_sort(col, descending), with the direction bound.

A separate constructor rather than an option so the version requirement is visible at the call: array_sort in both forms is Postgres 18, and a server one release behind reports "function does not exist" at run time, which is how the number in this comment was corrected from 17.

func ArraySubquery

func ArraySubquery[T any](s *sqlb.Select[Dialect]) sqlb.Expr[[]T]

ArraySubquery renders ARRAY(SELECT ...), typed as a slice of the author's element type.

func ArrayToString

func ArrayToString[T any](col sqlb.Expr[[]T], sep string) sqlb.Expr[string]

ArrayToString renders array_to_string(col, sep). NULL elements are dropped rather than rendered, which is why it is not the inverse of StringToArray.

func ArrayUpper

func ArrayUpper[T any](col sqlb.Expr[[]T], dim int) sqlb.Expr[*int32]

ArrayUpper renders array_upper(col, dim), the last subscript of a dimension. With ArrayLower it is how a caller iterates an array whose bounds it does not control; ArrayLength is the count and is not the same thing.

func Asin

func Asin[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Asin renders asin(e), returning radians.

func AtTimeZone

func AtTimeZone(e sqlb.Expr[time.Time], zone string) sqlb.Expr[time.Time]

AtTimeZone renders e AT TIME ZONE $n.

func BackendPID

func BackendPID() sqlb.Expr[int32]

BackendPID renders pg_backend_pid(), the server-side process id of this connection. It is what pg_stat_activity and pg_cancel_backend key on.

func BinOp

func BinOp[R any](construct, op string, l, r sqlb.SQLer) sqlb.Expr[R]

BinOp renders "left op right" as a guarded expression typed R.

func BinPred

func BinPred(construct, op string, l, r sqlb.SQLer) sqlb.Predicate

BinPred renders "left op right" as a guarded predicate.

op, like BinOp's and Func's name, is written into the statement as is: an operator cannot be quoted and a function name may be schema-qualified. These are the extension author's text and the one place in this package where a string reaches the statement unchecked, which is what makes them the escape hatch rather than the ordinary path. A value from a request never reaches one; pg.AnyExpr and pg.Exclude, which a caller does reach for, take a typed operator that is checked.

func BitAnd

func BitAnd[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[T]

BitAnd renders l & r.

This and the five below are Postgres helpers even though SQLite and MySQL share the spelling, because ClickHouse spells them as bitAnd() functions. Three of four engines agreeing is not the rule the core lives by.

func BitCount

func BitCount(e sqlb.Expr[BitString]) sqlb.Expr[int64]

BitCount renders bit_count(e), the number of set bits.

func BitLit

func BitLit(bits string) sqlb.Expr[BitString]

BitLit renders B'1011'.

func BitNot

func BitNot[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

BitNot renders ~e.

func BitOr

func BitOr[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[T]

BitOr renders l | r.

func BitStringOr

func BitStringOr(l, r sqlb.Expr[BitString]) sqlb.Expr[BitString]

BitStringOr renders l | r for two bit strings, which is a different operand type from BitOr even though the operator is the same.

func BitXor

func BitXor[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[T]

BitXor renders l # r. Postgres spells bitwise XOR with #, not ^, which is exponentiation there.

func BlockingPids

func BlockingPids(pid sqlb.SQLer) sqlb.Expr[[]int32]

BlockingPids renders pg_blocking_pids(pid), the backends holding the locks that pid is waiting for. The first call in any lock investigation.

func BoolAnd

func BoolAnd(e sqlb.Expr[bool], opts ...sqlb.AggOption) sqlb.Expr[bool]

BoolAnd renders bool_and(e): true when every row in the group is true.

func BoolOr

func BoolOr(e sqlb.Expr[bool], opts ...sqlb.AggOption) sqlb.Expr[bool]

BoolOr renders bool_or(e): true when any row is.

func Both

func Both(first, second sqlb.SQLer) sqlb.SQLer

Both renders "search cycle" so one CTE.Suffix carries both clauses.

Deliberately unguarded: it renders nothing of its own beyond a space, and both operands are already guarded constructors, so the dialect error comes from whichever of them renders first.

func BuildArray

func BuildArray(items ...sqlb.SQLer) sqlb.Expr[json.RawMessage]

BuildArray renders jsonb_build_array(...).

func BuildObject

func BuildObject(pairs ...sqlb.SQLer) sqlb.Expr[json.RawMessage]

BuildObject renders jsonb_build_object(k1, v1, ...). Keys are bound.

func CancelBackend

func CancelBackend(pid sqlb.SQLer) sqlb.Expr[bool]

CancelBackend renders pg_cancel_backend(pid), cancelling the current query on that connection but leaving it open.

func Cardinality

func Cardinality[T any](col sqlb.Expr[[]T]) sqlb.Expr[int32]

Cardinality renders cardinality(col): the total element count across every dimension. ArrayLength counts one dimension; on a one-dimensional array the two agree, and on anything else they do not.

func Ceil

func Ceil[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

Ceil renders ceil(e), rounding toward positive infinity.

func ClauseIn

func ClauseIn[K any](slot sqlb.Slot, construct string, render func(a *sqlb.Args) string) sqlb.Clause[Dialect, K]

ClauseIn makes a guarded clause for a statement slot, typed to this engine and to the statement kind K, which the caller names: an extension package writing a SELECT clause instantiates ClauseIn[sqlb.SelectKind].

func ClockTimestamp

func ClockTimestamp() sqlb.Expr[time.Time]

ClockTimestamp renders clock_timestamp(), the wall clock.

func Collate

func Collate(e sqlb.Expr[string], collation string) sqlb.Expr[string]

Collate renders e COLLATE "name".

func ColumnCollate

func ColumnCollate[T collatable](col sqlb.Expr[T], collation string) ddl.ColumnClause[Dialect]

ColumnCollate gives a text column a collation, written straight after its type. It is not Collate, which is the expression-level COLLATE a query uses.

func ColumnCollation

func ColumnCollation[T collatable](col sqlb.Expr[T], c Collation) ddl.ColumnClause[Dialect]

ColumnCollation gives a text column a declared collation, qualified by its schema; ColumnCollate takes a built-in collation's name.

func ColumnCompression

func ColumnCompression[T any](col sqlb.Expr[T], method string) ddl.ColumnClause[Dialect]

ColumnCompression names the algorithm a variable-length column's values are compressed with, pglz or lz4 where the server was built with it. It renders after the storage strategy and before a collation.

func ColumnSize

func ColumnSize(e sqlb.SQLer) sqlb.Expr[int32]

ColumnSize renders pg_column_size(e), the on-disk bytes of one value including compression. Useful for deciding whether a jsonb column is worth splitting out.

func ColumnStorage

func ColumnStorage[T any](col sqlb.Expr[T], s TypeStorage) ddl.ColumnClause[Dialect]

ColumnStorage says what the server may do with one column's value when it is too wide for its row: the column-level counterpart of the type's own strategy. It renders immediately after the type and BEFORE a collation, which Postgres's grammar requires and which is a syntax error the other way round.

On a column inherited through Inherits the parent's strategy wins and this one is dropped in silence, measured on 17.10: the same column reads extended under INHERITS and external without it. Set it on the parent.

func ConcatOp

func ConcatOp(l, r sqlb.Expr[string]) sqlb.Expr[string]

ConcatOp renders (a || b), the operator form. The core's Concat renders the concat() function, which every engine has.

func ConcatWs

func ConcatWs(sep string, parts ...sqlb.SQLer) sqlb.Expr[string]

ConcatWs renders concat_ws(sep, parts...), joining with a separator and skipping NULL parts rather than propagating them. That skipping is the reason to prefer it over the || operator for optional fields.

func ContainedBy

func ContainedBy(col sqlb.Expr[json.RawMessage], v json.RawMessage) sqlb.Predicate

ContainedBy renders col <@ $n.

func Contains

Contains renders col @> $n: true when col contains the JSON document v. Usable with a GIN index.

func Cos

func Cos[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Cos renders cos(e), the operand in radians.

func Cube

func Cube(items ...sqlb.SQLer) sqlb.SQLer

Cube renders CUBE (a, b), every combination of the items, which is 2^n groups. Watch the count before reaching for it on more than a few columns.

func CumeDist

func CumeDist() sqlb.WinFn[float64]

CumeDist renders cume_dist(), the cumulative distribution. It differs from PercentRank on ties, where it counts the whole peer group.

func CurrentDatabase

func CurrentDatabase() sqlb.Expr[string]

CurrentDatabase renders current_database().

This and the helpers below report session, transaction and replication state. They are for health checks, diagnostics and replication lag monitoring, not for application logic.

func CurrentDate

func CurrentDate() sqlb.Expr[time.Time]

CurrentDate renders current_date, which takes no parentheses.

func CurrentSetting

func CurrentSetting(name string) sqlb.Expr[*string]

CurrentSetting renders current_setting('name', true): NULL when unset.

func CurrentUser

func CurrentUser() sqlb.Expr[string]

CurrentUser renders current_user, which takes no parentheses.

func CurrentWalLsn

func CurrentWalLsn() sqlb.Expr[string]

CurrentWalLsn renders pg_current_wal_lsn(), the primary's write position.

func CurrentXactID

func CurrentXactID() sqlb.Expr[int64]

CurrentXactID renders pg_current_xact_id(), assigning one if this transaction has not written yet. Use CurrentXactIDIfAssigned to observe without forcing an assignment.

func CurrentXactIDIfAssigned

func CurrentXactIDIfAssigned() sqlb.Expr[*int64]

CurrentXactIDIfAssigned renders pg_current_xact_id_if_assigned(), NULL when the transaction has not written. It does not consume an id.

func Cycle

func Cycle(flagCol, pathCol string, cols ...string) sqlb.SQLer

Cycle is a recursive-CTE suffix (PG14): CYCLE cols SET flagcol USING pathcol. Recursion stops at the repeated row and flags it.

func DateBin

func DateBin(stride Interval, e sqlb.Expr[time.Time], origin time.Time) sqlb.Expr[time.Time]

DateBin renders date_bin(stride, e, origin): fixed-width buckets.

func DateLit

func DateLit(s string) sqlb.Expr[time.Time]

DateLit renders date '...'.

func DateMinusDays

func DateMinusDays(d sqlb.Expr[time.Time], days sqlb.SQLer) sqlb.Expr[time.Time]

DateMinusDays renders d - days.

func DatePlusDays

func DatePlusDays(d sqlb.Expr[time.Time], days sqlb.SQLer) sqlb.Expr[time.Time]

DatePlusDays renders d + days, where an integer added to a date means days.

func DateRange

func DateRange(lo, hi sqlb.SQLer, bounds Bounds) sqlb.Expr[Range[time.Time]]

DateRange renders daterange(lo, hi, bounds).

func DateTrunc

func DateTrunc(field DateField, e sqlb.Expr[time.Time]) sqlb.Expr[time.Time]

DateTrunc renders date_trunc('field', e). The field is a constant.

func DateTruncZone

func DateTruncZone(field DateField, e sqlb.Expr[time.Time], zone string) sqlb.Expr[time.Time]

DateTruncZone renders date_trunc('field', e, 'zone') (PG12).

func DaysBetween

func DaysBetween(l, r sqlb.Expr[time.Time]) sqlb.Expr[int32]

DaysBetween renders l - r for two dates, which Postgres types as an integer day count rather than an interval. That typing is Postgres specific, which is why these three are here and not in the core.

func DeleteKey

func DeleteKey(col sqlb.Expr[json.RawMessage], key string) sqlb.Expr[json.RawMessage]

DeleteKey renders col - key, removing a top-level key.

func DeletePath

func DeletePath(col sqlb.Expr[json.RawMessage], path []string) sqlb.Expr[json.RawMessage]

DeletePath renders col #- path, removing a nested key by path.

func Diff

func Diff(l, r sqlb.Expr[time.Time]) sqlb.Expr[Interval]

Diff renders (l - r), a timestamp difference, as an Interval.

func Div

func Div[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[T]

Div renders div(l, r), integer division truncated toward zero. The / operator on integers already truncates; this is the explicit spelling and the one that works on numeric.

func DivExact

func DivExact[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[float64]

DivExact renders (l::numeric / r), so integer division does not truncate.

func DomainValue

func DomainValue[T any]() sqlb.Expr[T]

DomainValue is the VALUE keyword, the value being checked in a domain's CHECK, typed to the domain.

func Each

Each renders jsonb_each(col) AS alias (key, value).

func EmptyArray

func EmptyArray[T any](sqlType string) sqlb.Expr[[]T]

EmptyArray renders '{}'::type[], the typed empty array. An ARRAY[] of nothing needs the cast.

sqlType is written into the statement as is, because no engine takes a placeholder where a type name goes and a type name is not one identifier: "character varying(10)" and "int[]" are both legal and neither survives quoting. It is the author's text, never a value from a request.

func EmptyJSONArray

func EmptyJSONArray() sqlb.Expr[json.RawMessage]

EmptyJSONArray and EmptyJSONObject are the COALESCE fallbacks for an aggregate over zero rows.

func EmptyJSONObject

func EmptyJSONObject() sqlb.Expr[json.RawMessage]

EmptyJSONObject renders '{}'::jsonb, the COALESCE fallback for an object aggregate over zero rows.

func Encode

func Encode(e sqlb.Expr[[]byte], format string) sqlb.Expr[string]

Encode renders encode(bytes, format), core Postgres: format is 'hex', 'base64' or 'escape'.

func EpochSeconds

func EpochSeconds(e sqlb.Expr[float64]) sqlb.Expr[time.Time]

EpochSeconds renders to_timestamp(seconds) for a float epoch.

func ExceptAll

func ExceptAll(s, other *sqlb.Select[Dialect]) *sqlb.Select[Dialect]

ExceptAll renders EXCEPT ALL, subtracting one occurrence per duplicate rather than every occurrence.

func Excluded

func Excluded[T any](col sqlb.Expr[T]) sqlb.Expr[T]

Excluded references the row proposed for insertion: EXCLUDED.column.

func Exp

func Exp[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Exp renders exp(e), e raised to the operand.

func ExportSnapshot

func ExportSnapshot() sqlb.Expr[string]

ExportSnapshot renders pg_export_snapshot(), so another session can see exactly this transaction's view. The mechanism behind a consistent parallel dump.

func Expr

func Expr[T any](construct string, render func(a *sqlb.Args) string) sqlb.Expr[T]

Expr makes a guarded typed expression from a render function.

func Extract

func Extract(field DateField, e sqlb.Expr[time.Time]) sqlb.Expr[float64]

Extract renders extract(field FROM e). Postgres returns numeric; float64 is the Go choice and the precision note is in the builder spec.

func ExtractFrom

func ExtractFrom(field DateField, e sqlb.SQLer) sqlb.Expr[float64]

ExtractFrom renders extract(field FROM e) for any operand, such as an interval or an age() result. Extract is the timestamp form.

func Filter

func Filter(p sqlb.Predicate) sqlb.AggOption

Filter adds FILTER (WHERE p) after an aggregate. Postgres and SQLite have it; MySQL and ClickHouse do not, so it guards.

func Floor

func Floor[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

Floor renders floor(e), rounding toward negative infinity.

func Format

func Format(format string, args ...sqlb.SQLer) sqlb.Expr[string]

Format renders format(fmt, args...).

func FormatType

func FormatType(typid, typmod sqlb.SQLer) sqlb.Expr[string]

FormatType renders format_type(typid, typmod), the SQL name of a type as it would be written in DDL.

func Func

func Func[R any](construct, name string, args ...sqlb.SQLer) sqlb.Expr[R]

Func renders a guarded function call typed R.

func FuncSource

func FuncSource(call sqlb.SQLer, alias string, columns ...string) sqlb.Source

FuncSource makes a set-returning function call a source: "generate_series($1, $2) AS g (n)". Column names are optional; with none the alias is also the column name, as Postgres does for a scalar function.

func GCD

func GCD[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[T]

GCD renders gcd(l, r), the greatest common divisor.

func GenRandomUUID

func GenRandomUUID() sqlb.Expr[string]

GenRandomUUID renders gen_random_uuid(), typed string.

func GenerateSeries

func GenerateSeries(from, to, step int64, alias string) (sqlb.Source, sqlb.Expr[int64])

GenerateSeries renders generate_series(CAST($1 AS bigint), ...) AS alias (n) for integers. Step 0 means no step argument.

The casts are load-bearing. generate_series has integer, bigint, numeric and timestamp overloads, and a bare bound parameter carries no type, so Postgres reports "function generate_series(unknown, unknown, unknown) is not unique". The text rendered fine on every reading of it; running it against a server is what found this, which is the argument for the driver module in one construct.

func GenerateSeriesExpr

func GenerateSeriesExpr(from, to sqlb.SQLer, step sqlb.Expr[Interval], alias string) (sqlb.Source, sqlb.Expr[time.Time])

GenerateSeriesExpr renders generate_series(from, to, step) from expressions.

func GenerateSeriesScalar

func GenerateSeriesScalar(from, to sqlb.SQLer) sqlb.Expr[int64]

GenerateSeriesScalar renders generate_series(from, to) in the select list rather than in FROM.

This and the helpers below are the expression forms of functions whose other helpers take Go values. They exist so an argument can be a column or another expression instead of a constant.

func GenerateSeriesTime

func GenerateSeriesTime(from, to time.Time, step string, alias string) (sqlb.Source, sqlb.Expr[time.Time])

GenerateSeriesTime renders generate_series($from, $to, interval) AS alias (ts) over timestamps, with the step an author constant.

func GenerateSubscripts

func GenerateSubscripts[T any](col sqlb.Expr[[]T], dim int, alias string) (sqlb.Source, sqlb.Expr[int32])

GenerateSubscripts renders generate_subscripts(col, dim) AS alias (i).

func GeneratedStored

func GeneratedStored[T any](col, e sqlb.Expr[T]) ddl.ColumnClause[Dialect]

GeneratedStored makes col a stored generated column computed by e, which is of the column's own Go type. The application never writes it, so NOT NULL is not written and a default is refused; e names the table's columns bare.

func GeneratedVirtual

func GeneratedVirtual[T any](col, e sqlb.Expr[T]) ddl.ColumnClause[Dialect]

GeneratedVirtual makes col a virtual generated column computed by e, evaluated when read rather than stored, which is Postgres 18's default for GENERATED ALWAYS AS. It takes no disk space and cannot be indexed; use GeneratedStored for one that must be. Postgres 18 or later.

func Get

Get renders col->key, a JSON value at a bound key. Always nullable: a missing key is NULL.

func GetBit

func GetBit(e sqlb.Expr[BitString], n int) sqlb.Expr[int32]

GetBit renders get_bit(e, n), the 0-based bit at n.

func GetIndex

func GetIndex(col sqlb.Expr[json.RawMessage], n int) sqlb.Expr[json.RawMessage]

GetIndex renders col->$1::int for an array element. The cast decides the operator: -> with a text parameter is the key form, so without it Postgres would look up the key "0" rather than the first element.

func GetSerialSequence

func GetSerialSequence(table, column string) sqlb.Expr[string]

GetSerialSequence renders pg_get_serial_sequence(table, column), the sequence name behind a serial or identity column. The argument to Setval after a bulk load that wrote explicit ids.

func Greatest

func Greatest[T any](first sqlb.Expr[T], rest ...sqlb.Expr[T]) sqlb.Expr[T]

Greatest renders greatest(a, b, ...), the largest argument, skipping NULLs. SQLite has neither this nor Least.

func Grouping

func Grouping(items ...sqlb.SQLer) sqlb.Expr[int32]

Grouping renders grouping(e): 1 on a super-aggregate row, else 0.

func GroupingSets

func GroupingSets(sets ...[]sqlb.SQLer) sqlb.SQLer

GroupingSets renders GROUPING SETS ((a), (b)), one result group per set.

This and the two below are GROUP BY items rather than expressions. The trap they share: a column not in the current set is NULL on that row, so every grouped column must be bound through Nullable or the scan fails on the super-aggregate rows.

func Guard

func Guard(a *sqlb.Args, construct string) bool

Guard reports whether rendering may continue under the dialect in a. When it returns false it has already recorded the construct as unsupported.

func HasAllKeys

func HasAllKeys(col sqlb.Expr[json.RawMessage], keys []string) sqlb.Predicate

HasAllKeys renders col ?& keys: every key is present.

func HasAnyKey

func HasAnyKey(col sqlb.Expr[json.RawMessage], keys []string) sqlb.Predicate

HasAnyKey renders col ?| keys: at least one of the keys is present.

func HasKey

func HasKey(col sqlb.Expr[json.RawMessage], key string) sqlb.Predicate

HasKey renders col ? key: the object has that top-level key.

The ? in these three is a jsonb operator, not a placeholder. Drivers that use ? for parameters, which is most of them outside Postgres, need it escaped, and that is one more reason these live in the pg package.

func HasRole

func HasRole(user sqlb.SQLer, role, privilege string) sqlb.Expr[bool]

HasRole renders pg_has_role(user, role, privilege), where privilege is MEMBER or USAGE.

func Hashtext

func Hashtext(e sqlb.Expr[string]) sqlb.Expr[int32]

Hashtext renders hashtext(e), the hash Postgres uses internally. It is the usual way to turn a string key into the bigint an advisory lock needs. Not stable across major versions, so never persist it.

func ILike

func ILike(e sqlb.Expr[string], pattern string) sqlb.Predicate

ILike renders e ILIKE $n, case-insensitive LIKE with a bound pattern. Postgres only; the other engines spell case-insensitive matching with lower() or a collation.

func Identity

func Identity[T identityInteger](col sqlb.Expr[T], k IdentityKind) ddl.ColumnClause[Dialect]

Identity makes col an identity column, its value drawn from a sequence Postgres owns. It is the standard form of what serial did, without serial's separately owned sequence. The column cannot also have a default, which Build refuses. Typed to the integer kinds Postgres accepts, so an identity on a text column does not compile.

func InArray

func InArray[T any](col sqlb.Expr[T], vals []T) sqlb.Predicate

InArray renders col = ANY($1) with one bound array. The statement text is then stable for any list length, so the prepared-statement cache hits and there is no parameter-count limit; prefer it over In for user-sized lists.

func IndexesSize

func IndexesSize(oid sqlb.SQLer) sqlb.Expr[int64]

IndexesSize renders pg_indexes_size(oid), the indexes alone.

func Infinity

func Infinity() sqlb.Expr[time.Time]

Infinity renders 'infinity'::timestamptz for open-ended validity.

func Initcap

func Initcap(e sqlb.Expr[string]) sqlb.Expr[string]

Initcap renders initcap(e), capitalising the first letter of each word. Word boundaries are non-alphanumeric characters, so "o'brien" becomes "O'Brien" and not "O'brien".

func InputIsValid

func InputIsValid(value, sqlType string) sqlb.Expr[bool]

InputIsValid renders pg_input_is_valid(value, type) (PG16): whether the text parses as that type. It answers without raising, which is what makes it usable in a validation query over existing rows.

func Int4Range

func Int4Range(lo, hi int32, bounds Bounds) sqlb.Expr[Range[int32]]

Int4Range renders int4range(lo, hi, bounds) from two bound values.

func Int8Range

func Int8Range(from, to int64, bounds Bounds) sqlb.Expr[Range[int64]]

Int8Range renders int8range($1, $2, 'bounds').

func IntersectAll

func IntersectAll(s, other *sqlb.Select[Dialect]) *sqlb.Select[Dialect]

IntersectAll renders INTERSECT ALL, which keeps duplicate rows where INTERSECT collapses them. SQLite lacks both ALL forms.

func IntervalLit

func IntervalLit(text string) sqlb.Expr[Interval]

IntervalLit renders the literal interval 'text'. An author constant such as "7 days"; a request-controlled interval goes through sqlb.Param with a cast.

The text is written by the dialect's literal quoting rather than by doubling the quote here. The difference is not cosmetic: with standard_conforming_strings off, Postgres reads a backslash in a plain literal as an escape, so doubling the quote alone leaves a string holding one backslash meaning something else and a lone backslash unterminated. The dialect knows which form reads the same under both settings, and it fails the build rather than guessing for an engine that has no rule.

func IntervalMul

func IntervalMul(iv sqlb.Expr[Interval], n sqlb.SQLer) sqlb.Expr[Interval]

IntervalMul renders (iv * n), for random() * interval '365 days'.

func Is

func Is(d sqlb.Dialect) bool

Is reports whether d is the Postgres dialect.

func IsDistinctFrom

func IsDistinctFrom[T any](l, r sqlb.Expr[T]) sqlb.Predicate

IsDistinctFrom is the null-safe inequality; IsNotDistinctFrom the null-safe equality. MySQL spells the second <=>, so both are here.

func IsEmpty

func IsEmpty[T any](r sqlb.Expr[Range[T]]) sqlb.Predicate

IsEmpty renders isempty(r). An empty range contains no points and is not the same as a range whose bounds are equal and inclusive.

func IsFalse

func IsFalse(e sqlb.Expr[bool]) sqlb.Predicate

IsFalse renders e IS FALSE, which is true for false and not for NULL.

func IsJSON

func IsJSON(e sqlb.SQLer, kind JSONKind, uniqueKeys bool) sqlb.Predicate

IsJSON renders e IS JSON [kind] [WITH UNIQUE KEYS] (PG16).

func IsNotDistinctFrom

func IsNotDistinctFrom[T any](l, r sqlb.Expr[T]) sqlb.Predicate

IsNotDistinctFrom renders l IS NOT DISTINCT FROM r, equality that treats two NULLs as equal. The operator a merge key needs when the key is nullable, because = answers NULL there.

func IsTrue

func IsTrue(e sqlb.Expr[bool]) sqlb.Predicate

IsTrue renders e IS TRUE.

SQL booleans have three values, so a NULL boolean is neither true nor false. These three test for each without the NULL propagating, which a plain comparison would. ClickHouse has none of them.

func IsUnknown

func IsUnknown(e sqlb.Expr[bool]) sqlb.Predicate

IsUnknown renders e IS UNKNOWN, true only for NULL.

func JSONAgg

func JSONAgg(e sqlb.SQLer, opts ...sqlb.AggOption) sqlb.Expr[json.RawMessage]

JSONAgg renders json_agg(e), the json rather than jsonb form. It preserves key order and duplicate keys, which jsonb does not.

func JSONArrayAgg

func JSONArrayAgg(e sqlb.SQLer, opts ...JSONOption) sqlb.Expr[json.RawMessage]

JSONArrayAgg renders JSON_ARRAYAGG(e [ORDER BY ...] [ABSENT ON NULL]).

func JSONBAgg

func JSONBAgg(e sqlb.SQLer, opts ...sqlb.AggOption) sqlb.Expr[json.RawMessage]

JSONBAgg renders jsonb_agg(e), the group as a JSON array.

All four aggregates here return NULL over zero rows, not an empty array or object. Wrap them in COALESCE with EmptyJSONArray or EmptyJSONObject when the caller expects a container.

func JSONBArrayLength

func JSONBArrayLength(e sqlb.Expr[json.RawMessage]) sqlb.Expr[int32]

JSONBArrayLength renders jsonb_array_length(e). It raises on a value that is not an array, so guard it with JSONBTypeof over mixed data.

func JSONBInsert

func JSONBInsert(col sqlb.Expr[json.RawMessage], path []string, value json.RawMessage) sqlb.Expr[json.RawMessage]

JSONBInsert renders jsonb_insert(col, path, value).

func JSONBObjectAgg

func JSONBObjectAgg(key, value sqlb.SQLer, opts ...sqlb.AggOption) sqlb.Expr[json.RawMessage]

JSONBObjectAgg renders jsonb_object_agg(key, value), the group as a JSON object. A NULL key raises rather than being skipped.

func JSONBSet

func JSONBSet(col sqlb.Expr[json.RawMessage], path []string, value json.RawMessage, createMissing bool) sqlb.Expr[json.RawMessage]

JSONBSet renders jsonb_set(col, path, value, create_missing).

func JSONBSetExpr

func JSONBSetExpr(col sqlb.SQLer, path []string, value sqlb.SQLer, createMissing bool) sqlb.Expr[json.RawMessage]

JSONBSetExpr is JSONBSet with the new value as an expression, for a subquery that rebuilds an array.

func JSONBSetLax

func JSONBSetLax(col sqlb.SQLer, path []string, value sqlb.SQLer, createMissing bool, nullTreatment string) sqlb.Expr[json.RawMessage]

JSONBSetLax renders jsonb_set_lax(col, path, value, create_missing, null_treatment). NullTreatment is one of the strings Postgres accepts: raise_exception, use_json_null, delete_key, return_target.

func JSONBTypeof

func JSONBTypeof(e sqlb.Expr[json.RawMessage]) sqlb.Expr[string]

JSONBTypeof renders jsonb_typeof(e): "object", "array", "string", "number", "boolean" or "null".

func JSONConcat

func JSONConcat(l, r sqlb.Expr[json.RawMessage]) sqlb.Expr[json.RawMessage]

JSONConcat renders l || r, a shallow merge.

func JSONExists

func JSONExists(doc sqlb.SQLer, path string) sqlb.Predicate

JSONExists renders JSON_EXISTS(doc, 'path') (PG17).

func JSONNull

func JSONNull() sqlb.Expr[json.RawMessage]

JSONNull is the JSON null literal, distinct from SQL NULL.

func JSONObject

func JSONObject(pairs []JSONPair, opts ...JSONOption) sqlb.Expr[json.RawMessage]

JSONObject renders JSON_OBJECT('k': v, ... [options]) (PG16).

func JSONObjectAgg

func JSONObjectAgg(key, value sqlb.SQLer, opts ...JSONOption) sqlb.Expr[json.RawMessage]

JSONObjectAgg renders JSON_OBJECTAGG(k: v [ABSENT ON NULL]).

func JSONQuery

func JSONQuery(doc sqlb.SQLer, path string, opts ...JSONValueOption) sqlb.Expr[json.RawMessage]

JSONQuery renders JSON_QUERY(doc, 'path' ...) (PG17).

func JSONSubscript

func JSONSubscript(doc sqlb.Expr[json.RawMessage], keys ...string) sqlb.Expr[json.RawMessage]

JSONSubscript renders doc['a']['b'] (PG14), the subscript form of a path lookup. It reads more like the Go it came from than the -> chain does.

func JSONTable

func JSONTable(doc sqlb.SQLer, path string, alias string, cols ...JSONTableColumn) sqlb.Source

JSONTable renders JSON_TABLE(doc, 'path' COLUMNS (...)) AS alias, a FROM source. Reference its columns with sqlb.Col against sqlb.Ref(source).

func JSONText

func JSONText(col sqlb.Expr[json.RawMessage], key string) sqlb.Expr[string]

JSONText renders col->>key, the text at a bound key.

func JSONValue

func JSONValue[R any](doc sqlb.SQLer, path string, opts ...JSONValueOption) sqlb.Expr[R]

JSONValue renders JSON_VALUE(doc, 'path' ...) typed R (PG17). The path is an author constant.

func JustifyInterval

func JustifyInterval(iv sqlb.Expr[Interval]) sqlb.Expr[Interval]

JustifyInterval renders justify_interval(iv).

func Key

func Key(k string) sqlb.SQLer

Key is a bound object key for BuildObject, cast to text because the function is variadic "any" and gives a bare parameter no type.

func LPad

func LPad(e sqlb.Expr[string], n int, fill string) sqlb.Expr[string]

LPad renders lpad(e, n, fill). It also truncates: a value longer than n comes back cut to n, which is the half everyone forgets.

func LTrim

func LTrim(e sqlb.Expr[string]) sqlb.Expr[string]

LTrim renders ltrim(e), the leading end only.

func Lag

func Lag[T any](e sqlb.Expr[T], offset int) sqlb.WinFn[*T]

Lag and Lead without a default are nullable: the row may not exist. ClickHouse spells these lagInFrame and leadInFrame, which is why they are here and not in the core.

func LagDefault

func LagDefault[T any](e sqlb.Expr[T], offset int, def sqlb.Expr[T]) sqlb.WinFn[T]

LagDefault renders lag(e, offset, default). Supplying a default is what makes the result non-null, which is why it is typed T and not *T.

func LastXactReplayTimestamp

func LastXactReplayTimestamp() sqlb.Expr[time.Time]

LastXactReplayTimestamp renders pg_last_xact_replay_timestamp(), the commit time of the last replayed transaction. Replication lag in time, which is the number an alert should use.

func Lateral

func Lateral(src sqlb.Source) sqlb.Source

Lateral marks a source as LATERAL, so its body may reference columns of sources to its left. Postgres and MySQL 8; not SQLite or ClickHouse.

func Lead

func Lead[T any](e sqlb.Expr[T], offset int) sqlb.WinFn[*T]

Lead renders lead(e, offset), the row ahead. Nullable: the last rows of a partition have nothing ahead of them.

func LeadDefault

func LeadDefault[T any](e sqlb.Expr[T], offset int, def sqlb.Expr[T]) sqlb.WinFn[T]

LeadDefault renders lead(e, offset, default), non-null for the same reason.

func Least

func Least[T any](first sqlb.Expr[T], rest ...sqlb.Expr[T]) sqlb.Expr[T]

Least renders least(a, b, ...), the smallest argument, skipping NULLs.

func Left

func Left(e sqlb.Expr[string], n int) sqlb.Expr[string]

Left renders left(e, n), the first n characters. A negative n means all but the last n.

func Length

func Length(e sqlb.Expr[string]) sqlb.Expr[int32]

Length renders length(e), in characters. OctetLength counts bytes, and the two differ for anything that is not pure ASCII.

func LikeEscape

func LikeEscape(e sqlb.Expr[string], pattern, escape string) sqlb.Predicate

LikeEscape renders LIKE $1 ESCAPE $2 so a literal % or _ can be matched.

func List

func List(a *sqlb.Args, items []sqlb.SQLer) string

List renders SQLers comma-separated.

func Ln

func Ln[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Ln renders ln(e), the natural logarithm.

func Log10

func Log10[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Log10 renders log(e). Postgres spells the base-10 logarithm log, and the natural one ln, which is the reverse of several other engines; the Go name says which one you get.

func LowerBound

func LowerBound[T any](r sqlb.Expr[Range[T]]) sqlb.Expr[*T]

LowerBound and UpperBound are nullable: an unbounded side is NULL.

func LowerInc

func LowerInc[T any](r sqlb.Expr[Range[T]]) sqlb.Expr[bool]

LowerInc renders lower_inc(r): whether the lower bound is inclusive.

func LowerInf

func LowerInf[T any](r sqlb.Expr[Range[T]]) sqlb.Predicate

LowerInf renders lower_inf(r): the range has no lower bound.

func MD5

func MD5(e sqlb.Expr[string]) sqlb.Expr[string]

MD5 renders md5(e), returning hex text. For a checksum or a cache key only: it is not a password hash, and pg/crypto has the ones that are.

func MakeInterval

func MakeInterval(days, hours int) sqlb.Expr[Interval]

MakeInterval renders make_interval(days => $1, hours => $2).

func Matches

func Matches(v sqlb.Expr[TSVector], q sqlb.Expr[TSQuery]) sqlb.Predicate

Matches renders vector @@ query.

func Materialized

func Materialized(on bool) sqlb.SQLer

Materialized is a CTE prefix: MATERIALIZED (true) or NOT MATERIALIZED (false).

func MergeAction

func MergeAction() sqlb.Expr[string]

MergeAction renders merge_action() for RETURNING: 'INSERT', 'UPDATE' or 'DELETE'.

func ModFn

func ModFn[T sqlb.Number](l, r sqlb.Expr[T]) sqlb.Expr[T]

ModFn renders mod(l, r). Named for the function rather than Mod because the operator form is %, which a caller may also want.

func Mode

func Mode[T any](e sqlb.Expr[T]) sqlb.Expr[T]

Mode renders mode() WITHIN GROUP (ORDER BY e).

func MultirangeDiff

func MultirangeDiff[T any](a, b sqlb.Expr[Multirange[T]]) sqlb.Expr[Multirange[T]]

MultirangeDiff renders (a - b) for multiranges.

func Named

func Named(name string, value sqlb.SQLer) sqlb.SQLer

Named renders name => value, the named-argument notation.

func New

func New[T any](col sqlb.Expr[T]) sqlb.Expr[T]

New is a column's value after the change, in a row trigger's WHEN.

func NextVal

func NextVal[T sequenceInteger](s Sequence[T]) sqlb.Expr[T]

NextVal is nextval(s), the sequence's next value, typed to it.

func Nextval

func Nextval(sequence string) sqlb.Expr[int64]

Nextval renders nextval('seq'). The sequence name is a constant.

func Normalize

func Normalize(e sqlb.Expr[string], form NormalForm) sqlb.Expr[string]

Normalize renders normalize(e, FORM) (PG13). The form is a keyword.

func NotILike

func NotILike(e sqlb.Expr[string], pattern string) sqlb.Predicate

NotILike renders e NOT ILIKE $n.

func NotRegex

func NotRegex(e sqlb.Expr[string], pattern string) sqlb.Predicate

NotRegex renders e !~ $n.

func NotRegexI

func NotRegexI(e sqlb.Expr[string], pattern string) sqlb.Predicate

NotRegexI renders e !~* $n.

func Now

func Now() sqlb.Expr[time.Time]

Now renders now(), the transaction start time.

func Ntile

func Ntile(n int) sqlb.WinFn[int32]

Ntile splits the partition into n buckets. n is bound.

func NullBound

func NullBound() sqlb.SQLer

NullBound is the unbounded side of a range, rendered as NULL.

func NumNonnulls

func NumNonnulls(items ...sqlb.SQLer) sqlb.Expr[int32]

NumNonnulls renders num_nonnulls(items...), counting how many arguments are not NULL. The usual use is a check that exactly one of several mutually exclusive columns is set.

func NumRange

func NumRange(lo, hi sqlb.SQLer, bounds Bounds) sqlb.Expr[Range[float64]]

NumRange renders numrange(lo, hi, bounds).

func ObjectKeys

func ObjectKeys(col sqlb.Expr[json.RawMessage], alias string) (sqlb.Source, sqlb.Expr[string])

ObjectKeys renders jsonb_object_keys(col) AS alias (key).

func OctetLength

func OctetLength(e sqlb.Expr[string]) sqlb.Expr[int32]

OctetLength renders octet_length(e), the byte count. It differs from length() for any text that is not pure ASCII, which is the point of it.

func Old

func Old[T any](col sqlb.Expr[T]) sqlb.Expr[T]

Old is a column's value before the change, in a row trigger's WHEN.

func OrderByNulls

func OrderByNulls[T any](e sqlb.Expr[T], dir sqlb.SortDirection, first bool) sqlb.OrderTerm

OrderByNulls makes an order term with NULLS FIRST or NULLS LAST.

func OrderUsing

func OrderUsing[T any](e sqlb.Expr[T], op string) sqlb.OrderTerm

OrderUsing makes an "ORDER BY expr USING op" term, for operator classes such as pgvector's distance operators.

func OrderWithin

func OrderWithin(ts ...sqlb.OrderTerm) sqlb.AggOption

OrderWithin adds ORDER BY inside the aggregate: array_agg(x ORDER BY y).

func Overlaps

func Overlaps[T any](col sqlb.Expr[[]T], v []T) sqlb.Predicate

Overlaps renders col && $n: the two arrays share at least one element.

func OverlapsExpr

func OverlapsExpr[T any](l, r sqlb.Expr[[]T]) sqlb.Predicate

OverlapsExpr renders l && r for two array expressions.

These three are the expression forms of Overlaps, ArrayContains and ArrayContainedBy, which compare against a Go slice. Both sides here are expressions, so a column can be compared with another column.

func OverlapsInterval

func OverlapsInterval(s1 sqlb.Expr[time.Time], i1 sqlb.Expr[Interval], s2 sqlb.Expr[time.Time], i2 sqlb.Expr[Interval]) sqlb.Predicate

OverlapsInterval renders (start1, interval1) OVERLAPS (start2, interval2).

func OverlapsPeriod

func OverlapsPeriod(s1, e1, s2, e2 sqlb.Expr[time.Time]) sqlb.Predicate

OverlapsPeriod renders (s1, e1) OVERLAPS (s2, e2).

func PathExists

func PathExists(col sqlb.Expr[json.RawMessage], jsonpath string) sqlb.Predicate

PathExists renders col @? jsonpath: the path matches anything.

The path is bound and cast rather than rendered, so a path built from request data cannot reach the statement text. PathMatch is the variant that evaluates the path as a predicate instead of testing for a match.

func PathGet

func PathGet(col sqlb.Expr[json.RawMessage], path []string) sqlb.Expr[json.RawMessage]

PathGet renders col#>path with a bound text[] path.

func PathMatch

func PathMatch(col sqlb.Expr[json.RawMessage], jsonpath string) sqlb.Predicate

PathMatch renders col @@ jsonpath, evaluating the path as a boolean expression. @? asks whether anything matched; @@ asks what it evaluated to.

func PathQuery

func PathQuery(col sqlb.Expr[json.RawMessage], jsonpath string, alias string) (sqlb.Source, sqlb.Expr[json.RawMessage])

PathQuery renders jsonb_path_query(col, path) AS alias (value).

func PathQueryArray

func PathQueryArray(doc sqlb.SQLer, path string) sqlb.Expr[json.RawMessage]

PathQueryArray renders jsonb_path_query_array(doc, 'path').

func PathQueryFirst

func PathQueryFirst(col sqlb.Expr[json.RawMessage], jsonpath string) sqlb.Expr[json.RawMessage]

PathQueryFirst renders jsonb_path_query_first(col, path) as a scalar.

func PathQueryScalar

func PathQueryScalar(doc sqlb.SQLer, path string) sqlb.Expr[json.RawMessage]

PathQueryScalar renders jsonb_path_query(doc, path) in the select list.

func PathQueryVars

func PathQueryVars(col sqlb.SQLer, jsonpath string, vars []byte, alias string) (sqlb.Source, sqlb.Expr[[]byte])

PathQueryVars renders jsonb_path_query(col, path, vars) AS alias (value).

func PathText

func PathText(col sqlb.Expr[json.RawMessage], path []string) sqlb.Expr[string]

PathText renders col#>>path.

func PercentRank

func PercentRank() sqlb.WinFn[float64]

PercentRank renders percent_rank(), the rank as a fraction from 0 to 1. Never null: a rank always exists for a row.

func PercentileCont

func PercentileCont(fraction float64, order sqlb.OrderTerm) sqlb.Expr[float64]

PercentileCont renders percentile_cont(f) WITHIN GROUP (ORDER BY e).

func PercentileDisc

func PercentileDisc[T any](fraction float64, e sqlb.Expr[T], dir sqlb.SortDirection) sqlb.Expr[T]

PercentileDisc keeps the ordered expression's type.

func PhraseToTSQuery

func PhraseToTSQuery(config, text string) sqlb.Expr[TSQuery]

PhraseToTSQuery renders phraseto_tsquery(config, $n): the words in order and adjacent, which is a phrase search.

func PlainToTSQuery

func PlainToTSQuery(config, text string) sqlb.Expr[TSQuery]

PlainToTSQuery renders plainto_tsquery(config, $n): every word ANDed, with operators in the input treated as text. Safe for raw user input.

func Position

func Position(e sqlb.Expr[string], needle string) sqlb.Expr[int32]

Position renders strpos(e, needle): 1-based, 0 when absent.

func Power

func Power[T sqlb.Number](base sqlb.Expr[T], exp float64) sqlb.Expr[float64]

Power renders power(base, exp). The result is float64 whatever the operand type, because an integer base with a fractional exponent is not an integer.

func PowerExpr

func PowerExpr[T sqlb.Number](base sqlb.Expr[T], exp sqlb.SQLer) sqlb.Expr[float64]

PowerExpr renders power(base, exp) with an expression exponent.

func PowerOp

func PowerOp[T sqlb.Number](base sqlb.Expr[T], exp sqlb.SQLer) sqlb.Expr[float64]

PowerOp renders (base ^ exp), the operator form of exponentiation. In Postgres ^ is power, not XOR; BitXor is the XOR helper.

func Pred

func Pred(construct string, render func(a *sqlb.Args) string) sqlb.Predicate

Pred makes a guarded predicate from a render function.

func Pretty

func Pretty(e sqlb.Expr[json.RawMessage]) sqlb.Expr[string]

Pretty renders jsonb_pretty(e), indented text. For human output; it is larger than the compact form and not what you store.

func QuoteIdent

func QuoteIdent(e sqlb.Expr[string]) sqlb.Expr[string]

QuoteIdent renders quote_ident(e), quoting a value for use as an identifier. For building dynamic SQL inside a server-side function; the builder quotes its own identifiers through the dialect.

func QuoteLit

func QuoteLit(s string) sqlb.SQLer

QuoteLit renders an author-chosen constant as a string literal, written by the dialect's own quoter: plainly when it holds no backslash, and in the E'...' form when it does, so it reads the same whatever the server's standard_conforming_strings. Never for request data; that goes through sqlb.Param.

func QuoteLiteral

func QuoteLiteral(e sqlb.Expr[string]) sqlb.Expr[string]

QuoteLiteral renders quote_literal(e), quoting a value for use as a literal. Same caveat as QuoteIdent: request data belongs in a Param.

func RPad

func RPad(e sqlb.Expr[string], n int, fill string) sqlb.Expr[string]

RPad renders rpad(e, n, fill), padding and truncating on the right.

func RTrim

func RTrim(e sqlb.Expr[string]) sqlb.Expr[string]

RTrim renders rtrim(e), the trailing end only.

func Radians

func Radians[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Radians renders radians(e), converting degrees to radians. The trigonometric functions below take radians, so a latitude or longitude has to pass through here first.

func Random

func Random() sqlb.Expr[float64]

Random renders random(), a value in [0,1). It is volatile, so a query that names it twice gets two different values.

func RandomNormal

func RandomNormal(mean, stddev float64) sqlb.Expr[float64]

RandomNormal renders random_normal(mean, stddev) (PG16), a normally distributed value rather than the uniform one random() gives.

func RangeAgg

func RangeAgg[T any](r sqlb.Expr[Range[T]], opts ...sqlb.AggOption) sqlb.Expr[string]

RangeAgg renders range_agg(r), a multirange, typed as text here.

func RangeAggTyped

func RangeAggTyped[T any](r sqlb.Expr[Range[T]], opts ...sqlb.AggOption) sqlb.Expr[Multirange[T]]

RangeAggTyped renders range_agg(r) typed as a multirange, and RangeIntersectAgg renders range_intersect_agg(r).

func RangeContainedBy

func RangeContainedBy[T any](l, r sqlb.Expr[Range[T]]) sqlb.Predicate

RangeContainedBy renders l <@ r: every point of l lies in r.

func RangeContains

func RangeContains[T any](r sqlb.Expr[Range[T]], v T) sqlb.Predicate

RangeContains renders range @> $n for an element.

func RangeContainsRange

func RangeContainsRange[T any](l, r sqlb.Expr[Range[T]]) sqlb.Predicate

RangeContainsRange renders l @> r; RangeOverlaps l && r; Adjacent l -|- r; StrictlyLeft l << r; StrictlyRight l >> r.

func RangeDiff

func RangeDiff[T any](l, r sqlb.Expr[Range[T]]) sqlb.Expr[Range[T]]

RangeDiff renders l - r. It raises when the result would be two ranges, which happens when r sits strictly inside l.

func RangeExpr

func RangeExpr[T any](constructor string, lo, hi sqlb.SQLer, bounds Bounds) sqlb.Expr[Range[T]]

RangeExpr builds a range from two expressions, so a bound may be NULL or a column rather than a value. constructor is the Postgres range function name, such as daterange or numrange.

constructor is written into the statement as is: a function name may be schema-qualified, so quoting it would make one identifier of two. It is the author's text, never a value from a request; bounds is checked, because it is a closed set.

func RangeIntersect

func RangeIntersect[T any](l, r sqlb.Expr[Range[T]]) sqlb.Expr[Range[T]]

RangeIntersect renders l * r, the common part, empty when they do not meet.

func RangeIntersectAgg

func RangeIntersectAgg[T any](r sqlb.Expr[Range[T]], opts ...sqlb.AggOption) sqlb.Expr[Range[T]]

RangeIntersectAgg renders range_intersect_agg(r), the range common to every row in the group. Empty when any two rows do not overlap.

func RangeMerge

func RangeMerge[T any](l, r sqlb.Expr[Range[T]]) sqlb.Expr[Range[T]]

RangeMerge renders range_merge(l, r), the smallest range containing both. Unlike RangeUnion it never raises: it fills the gap instead.

func RangeOverlaps

func RangeOverlaps[T any](l, r sqlb.Expr[Range[T]]) sqlb.Predicate

RangeOverlaps renders l && r: the two share at least one point.

func RangeUnion

func RangeUnion[T any](l, r sqlb.Expr[Range[T]]) sqlb.Expr[Range[T]]

RangeUnion renders l + r. It raises unless the two ranges overlap or are adjacent, because the result must be a single range; RangeMerge is the forgiving version.

func RecordSet

func RecordSet(call sqlb.SQLer, alias string, cols ...ColumnDef) sqlb.Source

RecordSet makes a function call a source with a typed column list, which jsonb_to_recordset and crosstab need. The types are author constants.

func Regclass

func Regclass(name string) sqlb.Expr[int64]

Regclass renders 'name'::regclass, an author constant naming a relation.

func Regex

func Regex(e sqlb.Expr[string], pattern string) sqlb.Predicate

Regex renders e ~ $n, a case-sensitive POSIX regular-expression match.

The four operators in this family are ~, ~*, !~ and !~*: the star is case-insensitive and the bang negates. The pattern always binds.

func RegexI

func RegexI(e sqlb.Expr[string], pattern string) sqlb.Predicate

RegexI renders e ~* $n, the case-insensitive match.

func RegexpCount

func RegexpCount(e sqlb.Expr[string], pattern string) sqlb.Expr[int32]

RegexpCount renders regexp_count(e, pattern) (PG15), the number of matches.

func RegexpInstr

func RegexpInstr(e sqlb.Expr[string], pattern string) sqlb.Expr[int32]

RegexpInstr renders regexp_instr(e, pattern): the 1-based position of the first match, or 0 when there is none.

func RegexpMatch

func RegexpMatch(e sqlb.Expr[string], pattern string) sqlb.Expr[[]string]

RegexpMatch renders regexp_match(e, pattern): the capture groups, or NULL.

func RegexpReplace

func RegexpReplace(e sqlb.Expr[string], pattern, replacement, flags string) sqlb.Expr[string]

RegexpReplace renders regexp_replace(e, pattern, replacement, flags).

func RegexpSplitToArray

func RegexpSplitToArray(e sqlb.Expr[string], pattern string) sqlb.Expr[[]string]

RegexpSplitToArray renders regexp_split_to_array(e, pattern).

func RegexpSplitToTable

func RegexpSplitToTable(e sqlb.Expr[string], pattern string, alias string) (sqlb.Source, sqlb.Expr[string])

RegexpSplitToTable renders regexp_split_to_table(e, pattern) AS alias (part).

func RegexpSubstr

func RegexpSubstr(e sqlb.Expr[string], pattern string) sqlb.Expr[*string]

RegexpSubstr renders regexp_substr(e, pattern). Nullable: no match is NULL, not the empty string, and the two mean different things.

func RelationSize

func RelationSize(oid sqlb.SQLer) sqlb.Expr[int64]

RelationSize renders pg_relation_size(oid): the table alone, without indexes. The difference from TotalRelationSize is what the indexes cost.

func Repeat

func Repeat(e sqlb.Expr[string], n int) sqlb.Expr[string]

Repeat renders repeat(e, n).

func RepeatExpr

func RepeatExpr(e sqlb.Expr[string], n sqlb.SQLer) sqlb.Expr[string]

RepeatExpr renders repeat(e, n) with an expression count.

func Replace

func Replace(e sqlb.Expr[string], from, to string) sqlb.Expr[string]

Replace renders replace(e, from, to), every occurrence. It is plain text, not a pattern; RegexpReplace is the pattern form.

func Reverse

func Reverse(e sqlb.Expr[string]) sqlb.Expr[string]

Reverse renders reverse(e). Reverses by character, which is not the same as reversing by grapheme: a combining accent ends up on the wrong letter.

func Right(e sqlb.Expr[string], n int) sqlb.Expr[string]

Right renders right(e, n), the last n characters.

func Rollup

func Rollup(items ...sqlb.SQLer) sqlb.SQLer

Rollup renders ROLLUP (a, b), the hierarchical subtotals: (a, b), (a) and the grand total, which is n+1 groups rather than 2^n.

func Round

func Round[T sqlb.Number](e sqlb.Expr[T], places int) sqlb.Expr[float64]

Round renders round(e, places). Postgres accepts places only for numeric, so the operand is cast: round(e::numeric, $n).

func RoundHalf

func RoundHalf[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

RoundHalf renders round(e), to the nearest integer with halves away from zero. Round takes a digit count; this one does not.

func RowRef

func RowRef(t sqlb.Table) sqlb.SQLer

RowRef references a whole row by its table alias, for to_jsonb(t) and count(t.*)-style uses.

Deliberately unguarded, and the only construct here that is. It renders a bare quoted identifier, which parses on every engine; verified against SQLite, which accepts it. What makes the use Postgres-specific is the function wrapped around it, and that function guards.

func RowToJSON

func RowToJSON(t sqlb.Table) sqlb.Expr[json.RawMessage]

RowToJSON renders row_to_json(alias), the whole row as a JSON object. ToJSONB is usually the better choice: jsonb is the indexable type.

func RowsFrom

func RowsFrom(alias string, calls []sqlb.SQLer, ordinality bool, columns ...string) sqlb.Source

RowsFrom renders ROWS FROM (f1(), f2(), ...) [WITH ORDINALITY] AS alias (cols), which zips several set-returning functions and pads the shorter with NULL.

func SHA256Hex

func SHA256Hex(e sqlb.Expr[string]) sqlb.Expr[string]

SHA256Hex renders encode(sha256(e::bytea), 'hex').

func SearchBreadthFirst

func SearchBreadthFirst(setCol string, by ...string) sqlb.SQLer

SearchBreadthFirst is the breadth-first form.

func SearchDepthFirst

func SearchDepthFirst(setCol string, by ...string) sqlb.SQLer

SearchDepthFirst is a recursive-CTE suffix (PG14): SEARCH DEPTH FIRST BY cols SET ordercol. Sorting by ordercol yields depth-first order.

func SetConfig

func SetConfig(name, value string, local bool) sqlb.Expr[string]

SetConfig renders set_config(name, value, is_local), which is how a session setting takes a bound value.

SET accepts no bind parameter; set_config does, and with is_local true it lasts for the transaction exactly like SET LOCAL. The name is an author constant and is rendered into the statement; only the value binds.

func SetLocal

func SetLocal(name, value string) sqlb.Expr[string]

SetLocal binds a setting for the current transaction.

func SetSubscript

func SetSubscript(col sqlb.Expr[json.RawMessage], keys []string, value sqlb.SQLer) sqlb.Assignment

SetSubscript is an UPDATE target: SET doc['customer']['tier'] = value. It updates one field in place without rewriting the document, and creates the intermediate objects when they are missing.

func SetWeight

func SetWeight(v sqlb.Expr[TSVector], w Weight) sqlb.Expr[TSVector]

SetWeight renders setweight(v, 'A').

func Setseed

func Setseed(seed float64) sqlb.Expr[[]byte]

Setseed renders setseed(seed), making the following random() calls reproducible in the same session. For tests and for a sampled query that must return the same sample twice.

func Setval

func Setval(sequence sqlb.SQLer, value sqlb.SQLer) sqlb.Expr[int64]

Setval renders setval(sequence, value), moving a sequence forward. The repair after a load that inserted ids the sequence does not know about.

func ShiftLeft

func ShiftLeft[T sqlb.Number](e sqlb.Expr[T], n int) sqlb.Expr[T]

ShiftLeft renders e << n.

func ShiftRight

func ShiftRight[T sqlb.Number](e sqlb.Expr[T], n int) sqlb.Expr[T]

ShiftRight renders e >> n.

func Sign

func Sign[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

Sign renders sign(e): -1, 0 or 1.

func SimilarTo

func SimilarTo(e sqlb.Expr[string], pattern string) sqlb.Predicate

SimilarTo renders e SIMILAR TO $n.

func Sin

func Sin[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Sin renders sin(e), the operand in radians.

func SizePretty

func SizePretty(bytes sqlb.SQLer) sqlb.Expr[string]

SizePretty renders pg_size_pretty(bytes), a human-readable byte count.

This and the helpers below read the catalogue rather than application tables. They belong in an admin query or a health check, not in a request path: several of them take a lock or scan the whole relation.

func Slice

func Slice[T any](col sqlb.Expr[[]T], lo, hi int) sqlb.Expr[[]T]

Slice renders col[lo:hi].

func SliceExprs

func SliceExprs[T any](col sqlb.Expr[[]T], lo, hi sqlb.SQLer) sqlb.Expr[[]T]

SliceExprs renders (col)[lo:hi] with expression bounds.

func SliceFrom

func SliceFrom[T any](col sqlb.Expr[[]T], lo int) sqlb.Expr[[]T]

SliceFrom renders col[lo:], a slice with an open upper end.

func SliceTo

func SliceTo[T any](col sqlb.Expr[[]T], hi int) sqlb.Expr[[]T]

SliceTo renders col[:hi], a slice with an open lower end.

func SplitPart

func SplitPart(e sqlb.Expr[string], sep string, n int) sqlb.Expr[string]

SplitPart renders split_part(e, sep, n), the nth field, 1-based. Returns the empty string when n is past the end, not NULL.

func Sqrt

func Sqrt[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[float64]

Sqrt renders sqrt(e).

func StartsWith

func StartsWith(e sqlb.Expr[string], prefix string) sqlb.Predicate

StartsWith renders starts_with(e, prefix). Unlike LIKE it needs no escaping of the prefix, so a user-supplied string with % or _ in it means what it says.

func StatementTimestamp

func StatementTimestamp() sqlb.Expr[time.Time]

StatementTimestamp renders statement_timestamp(), fixed for the statement. It sits between now(), which is fixed for the transaction, and ClockTimestamp, which moves within a statement.

func Stddev

func Stddev[T sqlb.Number](e sqlb.Expr[T], opts ...sqlb.AggOption) sqlb.Expr[float64]

Stddev renders stddev(e), the sample standard deviation.

func StrictlyLeft

func StrictlyLeft[T any](l, r sqlb.Expr[Range[T]]) sqlb.Predicate

StrictlyLeft renders l << r: every point of l is before every point of r.

func StrictlyRight

func StrictlyRight[T any](l, r sqlb.Expr[Range[T]]) sqlb.Predicate

StrictlyRight renders l >> r.

func StringAgg

func StringAgg(e sqlb.Expr[string], sep string, opts ...sqlb.AggOption) sqlb.Expr[string]

StringAgg joins strings with a bound separator.

func StringToArray

func StringToArray(e sqlb.Expr[string], sep string) sqlb.Expr[[]string]

StringToArray renders string_to_array(e, sep). An empty input yields an array with one empty element, not an empty array.

func StringToArrayNull

func StringToArrayNull(e sqlb.Expr[string], sep, nullStr string) sqlb.Expr[[]*string]

StringToArrayNull renders string_to_array(e, sep, nullStr), the three-argument form.

func StringToTable

func StringToTable(e sqlb.Expr[string], sep string, alias string) (sqlb.Source, sqlb.Expr[string])

StringToTable renders string_to_table(e, sep) AS alias (part) (PG14).

func Strip

func Strip(v sqlb.Expr[TSVector]) sqlb.Expr[TSVector]

Strip renders strip(v), dropping positions and weights. It makes a vector smaller to store, at the cost of phrase search and weighted ranking.

func StripNulls

func StripNulls(e sqlb.Expr[json.RawMessage]) sqlb.Expr[json.RawMessage]

StripNulls renders jsonb_strip_nulls(e), dropping object keys whose value is null. It does not touch nulls inside arrays, where removing an element would shift the indexes of the rest.

func SubInterval

func SubInterval(e sqlb.Expr[time.Time], iv Interval) sqlb.Expr[time.Time]

SubInterval renders (e - interval '...') with a constant interval.

func SubIntervalExpr

func SubIntervalExpr(e sqlb.Expr[time.Time], iv sqlb.Expr[Interval]) sqlb.Expr[time.Time]

SubIntervalExpr renders e - iv with an interval expression.

func Subscript

func Subscript[T any](col sqlb.Expr[[]T], n int) sqlb.Expr[*T]

Subscript renders col[n]. Nullable: an index out of range yields NULL, not an error. The index is a literal because Postgres needs it constant inside an index expression; it is an author's choice, never request data.

func SubscriptExpr

func SubscriptExpr[T any](col sqlb.Expr[[]T], index sqlb.SQLer) sqlb.Expr[*T]

SubscriptExpr renders col[index] with an expression index.

func SubstrExpr

func SubstrExpr(e sqlb.Expr[string], from, count sqlb.SQLer) sqlb.Expr[string]

SubstrExpr renders substr(e, from, count) with expression bounds.

func Substring

func Substring(e sqlb.Expr[string], from, count int) sqlb.Expr[string]

Substring renders substring(e, from, count) with bound positions.

func SubstringRegex

func SubstringRegex(e sqlb.Expr[string], pattern string) sqlb.Expr[*string]

SubstringRegex renders substring(e FROM pattern): the first capture group, or the whole match with no group. Nullable: no match is NULL.

func TSAnd

func TSAnd(l, r sqlb.Expr[TSQuery]) sqlb.Expr[TSQuery]

TSAnd renders l && r, both terms required.

The four combinators build a query from smaller ones, which is how a filter interface composes a search without ever concatenating query text.

func TSFollowedBy

func TSFollowedBy(l, r sqlb.Expr[TSQuery]) sqlb.Expr[TSQuery]

TSFollowedBy renders l <-> r: l immediately followed by r, the phrase operator.

func TSHeadline

func TSHeadline(config string, text sqlb.Expr[string], q sqlb.Expr[TSQuery], options string) sqlb.Expr[string]

TSHeadline renders ts_headline(config, text, query, options).

func TSNot

func TSNot(q sqlb.Expr[TSQuery]) sqlb.Expr[TSQuery]

TSNot renders !! q, excluding the term.

func TSOr

func TSOr(l, r sqlb.Expr[TSQuery]) sqlb.Expr[TSQuery]

TSOr renders l || r, either term.

func TSRank

func TSRank(v sqlb.Expr[TSVector], q sqlb.Expr[TSQuery]) sqlb.Expr[float32]

TSRank and TSRankCD.

func TSRankCD

func TSRankCD(v sqlb.Expr[TSVector], q sqlb.Expr[TSQuery]) sqlb.Expr[float32]

TSRankCD renders ts_rank_cd(v, q), the cover-density ranking. It accounts for how close the matched terms are to each other, which ts_rank ignores.

func TSRankCDNormalized

func TSRankCDNormalized(v sqlb.Expr[TSVector], q sqlb.Expr[TSQuery], normalization int) sqlb.Expr[float32]

TSRankCDNormalized renders ts_rank_cd(vector, query, normalization).

func TSVectorConcat

func TSVectorConcat(l, r sqlb.Expr[TSVector]) sqlb.Expr[TSVector]

TSVectorConcat renders a || b for weighted vectors.

func TerminateBackend

func TerminateBackend(pid sqlb.SQLer) sqlb.Expr[bool]

TerminateBackend renders pg_terminate_backend(pid), closing the connection outright. CancelBackend is the one to try first.

func TimestampLit

func TimestampLit(s string) sqlb.Expr[time.Time]

TimestampLit renders timestamp '...', a typed literal for an author constant. Never for request data, which belongs in a Param.

func TimestamptzLit

func TimestamptzLit(s string) sqlb.Expr[time.Time]

TimestamptzLit renders '...'::timestamptz, the zone-aware form.

func ToChar

func ToChar(e sqlb.SQLer, format string) sqlb.Expr[string]

ToChar renders to_char(e, format) for any input type.

func ToDate

func ToDate(e sqlb.Expr[string], format string) sqlb.Expr[time.Time]

ToDate renders to_date(e, format), parsing text with a Postgres format string such as 'YYYY-MM-DD'. The format is bound, not interpolated.

func ToJSONB

func ToJSONB(e sqlb.SQLer) sqlb.Expr[json.RawMessage]

ToJSONB renders to_jsonb(e). RowToJSON renders row_to_json(alias).

func ToTSQuery

func ToTSQuery(config, text string) sqlb.Expr[TSQuery]

ToTSQuery raises a syntax error on malformed input. Use it for author-written queries, never for raw user input.

func ToTSVector

func ToTSVector(config string, e sqlb.Expr[string]) sqlb.Expr[TSVector]

ToTSVector renders to_tsvector(config, e). The config is a constant.

func ToTimestamp

func ToTimestamp(e sqlb.Expr[string], format string) sqlb.Expr[time.Time]

ToTimestamp renders to_timestamp(e, format). ToDate renders to_date.

func TotalRelationSize

func TotalRelationSize(oid sqlb.SQLer) sqlb.Expr[int64]

TotalRelationSize renders pg_total_relation_size(oid): the table, its indexes and its TOAST data together.

func Trim

func Trim(e sqlb.Expr[string]) sqlb.Expr[string]

Trim renders btrim(e), removing whitespace from both ends. TrimChars is the form that takes the characters to strip.

func TrimArray

func TrimArray[T any](col sqlb.Expr[[]T], n int) sqlb.Expr[[]T]

TrimArray renders trim_array(col, n), the array without its last n elements. Postgres 14.

func TrimChars

func TrimChars(side TrimSide, chars string, e sqlb.Expr[string]) sqlb.Expr[string]

TrimChars renders trim(side chars FROM e).

func Trunc

func Trunc[T sqlb.Number](e sqlb.Expr[T], places int) sqlb.Expr[float64]

Trunc renders trunc(e, places), rounding toward zero. Like Round it casts to numeric, because Postgres accepts a digit count only for that type.

func TruncZero

func TruncZero[T sqlb.Number](e sqlb.Expr[T]) sqlb.Expr[T]

TruncZero renders trunc(e), toward zero, with no digit count.

func TryAdvisoryXactLock

func TryAdvisoryXactLock(key sqlb.SQLer) sqlb.Expr[bool]

TryAdvisoryXactLock renders pg_try_advisory_xact_lock(key), which returns false rather than waiting. The non-blocking form a queue worker wants.

func TstzMultirange

func TstzMultirange(r sqlb.Expr[Range[time.Time]]) sqlb.Expr[Multirange[time.Time]]

TstzMultirange renders tstzmultirange(r).

func TstzRange

func TstzRange(from, to time.Time, bounds Bounds) sqlb.Expr[Range[time.Time]]

TstzRange renders tstzrange($1, $2, 'bounds').

func TstzRangeExpr

func TstzRangeExpr(lo, hi sqlb.SQLer, bounds Bounds) sqlb.Expr[Range[time.Time]]

TstzRangeExpr renders tstzrange(lo, hi, bounds) from expressions.

func TxidCurrent

func TxidCurrent() sqlb.Expr[int64]

TxidCurrent renders txid_current(), the pre-PG13 spelling of CurrentXactID. Kept for servers older than 13.

func UUIDv7Timestamp

func UUIDv7Timestamp(u sqlb.Expr[string]) sqlb.Expr[time.Time]

UUIDv7Timestamp extracts the millisecond timestamp from a UUID v7 on any Postgres version: the first 48 bits, read as hex, as epoch milliseconds. Needs no extension; it is text and bit-string arithmetic.

func Unnest

func Unnest[T any](col sqlb.Expr[[]T], alias string) (sqlb.Source, sqlb.Expr[T])

Unnest renders unnest(col) AS alias (elem) and returns the typed element.

func UnnestMulti

func UnnestMulti(alias string, arrays []sqlb.SQLer, ordinality bool, columns ...string) sqlb.Source

UnnestMulti renders unnest(a1, a2, ...) [WITH ORDINALITY] AS alias (cols): several arrays zipped, the shorter padded with NULL.

func UnnestMultirange

func UnnestMultirange[T any](m sqlb.Expr[Multirange[T]]) sqlb.Expr[Range[T]]

UnnestMultirange renders unnest(m) as a scalar set-returning expression.

func UnnestOrdinal

func UnnestOrdinal[T any](col sqlb.Expr[[]T], alias string) (sqlb.Source, sqlb.Expr[T], sqlb.Expr[int64])

UnnestOrdinal is Unnest WITH ORDINALITY: (elem, n).

func UnnestScalar

func UnnestScalar[T any](arr sqlb.Expr[[]T]) sqlb.Expr[T]

UnnestScalar renders unnest(arr) in the select list. A set-returning function there multiplies the rows, which is legal in Postgres and a surprise to everyone the first time.

func Upper

func Upper(e sqlb.Expr[string]) sqlb.Expr[string]

Upper renders upper(e). The core has Lower, because every engine has it; upper() is here because ClickHouse spells it upperUTF8 for non-ASCII.

func UpperBound

func UpperBound[T any](r sqlb.Expr[Range[T]]) sqlb.Expr[*T]

UpperBound renders upper(r), NULL when the range is unbounded above.

func UpperInc

func UpperInc[T any](r sqlb.Expr[Range[T]]) sqlb.Expr[bool]

UpperInc renders upper_inc(r).

func UpperInf

func UpperInf[T any](r sqlb.Expr[Range[T]]) sqlb.Predicate

UpperInf and LowerInf test for an unbounded side.

func Values

func Values(alias string, columns []string, rows ...[]sqlb.SQLer) sqlb.Source

Values makes a VALUES list a source: "(VALUES ($1, $2), ($3, $4)) AS alias (a, b)". Every cell is a SQLer, so a bound Param and a typed expression both work.

func Variadic

func Variadic(arr sqlb.SQLer) sqlb.SQLer

Variadic marks an array argument as VARIADIC in a function call.

func Variance

func Variance[T sqlb.Number](e sqlb.Expr[T], opts ...sqlb.AggOption) sqlb.Expr[float64]

Variance renders variance(e), the sample variance.

func Version

func Version() sqlb.Expr[string]

Version renders version(), the server version banner. Useful in a health check; never parse it to gate behaviour, because its shape is not stable.

func WalLsnDiff

func WalLsnDiff(a, b sqlb.SQLer) sqlb.Expr[int64]

WalLsnDiff renders pg_wal_lsn_diff(a, b), the byte distance between two WAL positions. Replication lag in bytes.

func WebsearchToTSQuery

func WebsearchToTSQuery(config, text string) sqlb.Expr[TSQuery]

WebsearchToTSQuery is the safe form for user input: it never raises a syntax error. ToTSQuery can, and the doc on it says so.

func WidthBucket

func WidthBucket[T sqlb.Number](e sqlb.Expr[T], lo, hi T, count int) sqlb.Expr[int32]

WidthBucket renders width_bucket(e, lo, hi, count).

func WidthBucketThresholds

func WidthBucketThresholds[T sqlb.Number](e sqlb.Expr[T], thresholds []T) sqlb.Expr[int32]

WidthBucketThresholds renders width_bucket(e, thresholds[]), the array form, for weighted picks.

func WithOrdinality

func WithOrdinality(src sqlb.Source) sqlb.Source

WithOrdinality adds "WITH ORDINALITY", which appends a bigint row number column. Name it as the last entry of columns.

func WithinGroup

func WithinGroup[R any](name string, args []sqlb.SQLer, order ...sqlb.OrderTerm) sqlb.Expr[R]

WithinGroup renders an ordered-set aggregate: name(args) WITHIN GROUP (ORDER BY ...).

func XidAge

func XidAge(xid sqlb.SQLer) sqlb.Expr[int64]

XidAge renders age(xid), transactions elapsed since xid. The number a wraparound-vacuum alert watches.

Types

type AccessMethod

type AccessMethod string

AccessMethod is a table access method, the storage engine a table or a materialized view's rows are kept in. It is an open set for the reason IndexMethod is: an extension adds one.

const Heap AccessMethod = "heap"

Heap is the access method a stock Postgres has and every table uses unless an extension provides another.

type AddValueStatement

type AddValueStatement[T ~string] struct {
	// contains filtered or unexported fields
}

AddValueStatement is ALTER TYPE ... ADD VALUE.

func (*AddValueStatement[T]) After

func (x *AddValueStatement[T]) After(v T) *AddValueStatement[T]

After places the label after another.

func (*AddValueStatement[T]) Before

func (x *AddValueStatement[T]) Before(v T) *AddValueStatement[T]

Before places the label before another.

func (*AddValueStatement[T]) Build

func (x *AddValueStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*AddValueStatement[T]) IfNotExists

func (x *AddValueStatement[T]) IfNotExists() *AddValueStatement[T]

IfNotExists makes adding an existing label a no-op.

type AlterBaseTypeQuery

type AlterBaseTypeQuery[T any] struct {
	// contains filtered or unexported fields
}

AlterBaseTypeQuery is ALTER TYPE on a base type with no action yet, which has no Build.

func AlterBaseType

func AlterBaseType[T any](b BaseType[T]) *AlterBaseTypeQuery[T]

AlterBaseType starts an ALTER TYPE on a base type.

func (*AlterBaseTypeQuery[T]) RenameTo

func (x *AlterBaseTypeQuery[T]) RenameTo(to BaseType[T]) *AlterTypeNameStatement

RenameTo renames the base type to to's name.

func (*AlterBaseTypeQuery[T]) SetProperties

func (x *AlterBaseTypeQuery[T]) SetProperties() *AlterBaseTypeStatement[T]

SetProperties fills in the functions and the storage strategy a base type was created without, which is the only way to add them: the receive, send and type-modifier functions each take or return the type, so they cannot exist when CREATE TYPE runs and the type cannot be created without them either. It is the same shell-then-fill order CreateShellType exists for, one level further on.

type AlterBaseTypeStatement

type AlterBaseTypeStatement[T any] struct {
	// contains filtered or unexported fields
}

AlterBaseTypeStatement is ALTER TYPE ... SET ( property = value ).

func (*AlterBaseTypeStatement[T]) Analyze

Analyze names the function that gathers the planner's statistics.

func (*AlterBaseTypeStatement[T]) Build

func (x *AlterBaseTypeStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterBaseTypeStatement[T]) Receive

Receive names the function that reads the type's binary form.

func (*AlterBaseTypeStatement[T]) Send

Send names the function that writes the type's binary form.

func (*AlterBaseTypeStatement[T]) Storage

Storage widens what the server may do with a value too large for its row. Postgres allows this one property to change only in the widening direction, plain to extended and not back, because values already stored in the old strategy stay as they are.

func (*AlterBaseTypeStatement[T]) Subscript

Subscript names the function that implements value[i].

func (*AlterBaseTypeStatement[T]) TypmodIn

TypmodIn names the function that parses a type modifier.

func (*AlterBaseTypeStatement[T]) TypmodOut

TypmodOut names the function that prints a type modifier back.

type AlterClause

type AlterClause = ddl.AlterClause[Dialect]

AlterClause is a Postgres ALTER TABLE action.

func AddColumnIfNotExists

func AddColumnIfNotExists(c ddl.ColumnSpec, with ...ddl.ColumnClause[Dialect]) AlterClause

AddColumnIfNotExists adds a column unless it exists, which makes the action safe to run on every boot. Like IF NOT EXISTS on a table it checks the name only. The column clauses, a collation or an identity, must name the column.

func AddConstraint

func AddConstraint(c Constraint) AlterClause

AddConstraint adds a constraint to an existing table, checking every row under a lock that blocks writes for the whole scan. Postgres has no IF NOT EXISTS for it.

func AddConstraintNotValid

func AddConstraintNotValid(c Validatable) AlterClause

AddConstraintNotValid adds a foreign key or check without checking existing rows, so the strong lock is brief; ValidateConstraint then checks them under a lock that allows writes. On a large table the two steps are the difference between a migration and an outage.

func AddIdentity

func AddIdentity[T identityInteger](col sqlb.Expr[T], k IdentityKind) AlterClause

AddIdentity makes an existing integer column an identity column.

func AddPrimaryKeyUsingIndex

func AddPrimaryKeyUsingIndex(c TableConstraint, ix Index) AlterClause

AddPrimaryKeyUsingIndex promotes an existing unique index to the table's primary key, the same zero-downtime step as AddUniqueUsingIndex. Every column of the index must already be NOT NULL, which Postgres checks.

func AddUniqueUsingIndex

func AddUniqueUsingIndex(c TableConstraint, ix Index) AlterClause

AddUniqueUsingIndex promotes an existing unique index to a named unique constraint. It is the second half of a zero-downtime migration: build the index with CreateIndex(...).Concurrently() outside a transaction, which scans without blocking writes, then attach it here, which takes the strong lock for the length of a catalogue update rather than a table scan. Postgres renames the index to the constraint's name, so declare the constraint and the index with the same name to keep both declarations true.

func AttachPartition

func AttachPartition(child sqlb.Table, b PartitionBound) AlterClause

AttachPartition attaches an existing table as a partition, scanning it to check the bounds; a CHECK constraint matching them lets Postgres skip the scan. A statement of its own in Postgres's grammar.

func DisableRowLevelSecurity

func DisableRowLevelSecurity() AlterClause

DisableRowLevelSecurity turns row-level security off for the table, the inverse of EnableRowLevelSecurity.

func DisableRule

func DisableRule(r Rule) AlterClause

DisableRule stops a rule rewriting anything, without dropping it. It is the safe first half of removing a rule: disable it, watch, then drop it, rather than dropping it and finding out what depended on the rewrite.

func DropDefault

func DropDefault[T any](col sqlb.Expr[T]) AlterClause

DropDefault removes a column's default.

func DropNotNull

func DropNotNull[T any](col sqlb.Expr[T]) AlterClause

DropNotNull allows NULL.

func EnableAlwaysRule

func EnableAlwaysRule(r Rule) AlterClause

EnableAlwaysRule turns the rule on in every session_replication_role, replication included.

func EnableReplicaRule

func EnableReplicaRule(r Rule) AlterClause

EnableReplicaRule turns the rule on only where session_replication_role is replica, which is how a rule applies on a subscriber and not on the origin.

func EnableRowLevelSecurity

func EnableRowLevelSecurity() AlterClause

EnableRowLevelSecurity turns on row security, after which a role that is not the owner sees no row until a policy grants it. The policies come with CREATE POLICY.

func EnableRule

func EnableRule(r Rule) AlterClause

EnableRule turns a rule back on for ordinary statements, the default state of a rule that has been disabled.

func ForceRowLevelSecurity

func ForceRowLevelSecurity() AlterClause

ForceRowLevelSecurity applies the table's policies to its owner too. Postgres exempts the owner otherwise, so a library whose own role owns its tables needs this for its policies to bind it.

func Inherit

func Inherit(parent sqlb.Table) AlterClause

Inherit makes the table a child of parent, so a query on the parent also reads this table's rows and the child must already have every one of the parent's columns with the same types.

Inheritance predates declarative partitioning, which replaces it for the one thing most people used it for, and a new schema should use CreatePartition instead: a partition is checked to be disjoint, is pruned by the planner and cannot be forgotten. This form exists for the schema that already inherits, where detaching a child is a migration somebody has to write.

func NoForceRowLevelSecurity

func NoForceRowLevelSecurity() AlterClause

NoForceRowLevelSecurity exempts the owner again, the inverse of ForceRowLevelSecurity.

func NoInherit

func NoInherit(parent sqlb.Table) AlterClause

NoInherit detaches the table from parent, leaving both tables and all their rows in place; the parent simply stops seeing this table's rows.

func NotOfType

func NotOfType() AlterClause

NotOfType breaks the tie between a typed table and its composite type, leaving the table with the columns it has as its own declaration.

func OfType

func OfType[T any](c Composite[T]) AlterClause

OfType makes the table a typed table of a composite type, so its column list is that type's attribute list and changing the type changes the table. It is the one form where a table's shape is declared somewhere other than the table, which is why a new schema should declare the columns instead; the table's columns must already match the type exactly, which Postgres checks.

func RenameConstraint

func RenameConstraint(from, to TableConstraint) AlterClause

RenameConstraint renames a constraint within its table, the one migration a declared constraint needs when its name changes. It is a statement of its own, as every RENAME is on Postgres. Declare the new name as a second TableConstraint and switch the code to it in the same release.

func RenameTo

func RenameTo(to sqlb.Table) AlterClause

RenameTo renames the table to to's name; the schema is unchanged, which is SetSchema's job. It takes the new declaration, the value the queries will use, rather than a string. A statement of its own.

func SetColumnCompression

func SetColumnCompression[T any](col sqlb.Expr[T], method string) AlterClause

SetColumnCompression changes an existing column's compression algorithm, the ALTER half of ColumnCompression, and like it applies to values written from now on.

func SetColumnStorage

func SetColumnStorage[T any](col sqlb.Expr[T], s TypeStorage) AlterClause

SetColumnStorage changes an existing column's storage strategy, the ALTER half of ColumnStorage. It was the operator's until the second pass noticed the asymmetry: a strategy that can be declared at CREATE and not changed afterwards is a declaration a migration cannot follow. It rewrites nothing, so it applies to values written from now on and leaves the ones already stored as they are.

func SetDefault

func SetDefault[T any](col sqlb.Expr[T], v T) AlterClause

SetDefault sets a column's default to a value of its own Go type, written as a literal. It affects rows inserted from now on, never existing ones.

func SetDefaultExpr

func SetDefaultExpr[T any](col, e sqlb.Expr[T]) AlterClause

SetDefaultExpr sets a column's default to an expression of its own type.

func SetExpression

func SetExpression[T any](col, e sqlb.Expr[T]) AlterClause

SetExpression changes a generated column's expression to e, an expression of the column's own Go type, so a column of another type does not compile. Postgres 17 and later. It rewrites the table under a lock that blocks reads, which is why the alternative on a large table is to add a second column and drop the first.

func SetIdentityKind

func SetIdentityKind[T identityInteger](col sqlb.Expr[T], k IdentityKind) AlterClause

SetIdentityKind changes whether an identity column refuses an explicit value, between Always and ByDefault. It is the migration a library writes when a caller must be allowed to supply its own key, and it changes nothing about the sequence or the values already stored.

func SetNotNull

func SetNotNull[T any](col sqlb.Expr[T]) AlterClause

SetNotNull refuses NULL from now on. It scans the table and fails if any row holds NULL, which is why adding a NOT NULL column to a table with rows is three steps: add it nullable, backfill, then this.

func SetSchema

func SetSchema(schema string) AlterClause

SetSchema moves the table to another schema. A statement of its own.

func ValidateConstraint

func ValidateConstraint(c TableConstraint) AlterClause

ValidateConstraint checks existing rows against a constraint added NOT VALID. Build it separately from AddConstraintNotValid and run it in its own transaction: in one statement the strong lock is held through the scan, which is exactly what NOT VALID exists to avoid.

type AlterCompositeQuery

type AlterCompositeQuery[T any] struct {
	// contains filtered or unexported fields
}

AlterCompositeQuery is ALTER TYPE on a composite with no action yet, which has no Build.

func AlterComposite

func AlterComposite[T any](c Composite[T]) *AlterCompositeQuery[T]

AlterComposite starts an ALTER TYPE on a composite.

func (*AlterCompositeQuery[T]) AddAttribute

func (x *AlterCompositeQuery[T]) AddAttribute(at Attribute) *AlterCompositeStatement[T]

AddAttribute adds an attribute; existing values have it NULL.

func (*AlterCompositeQuery[T]) AlterAttributeType

func (x *AlterCompositeQuery[T]) AlterAttributeType(at Attribute) *AlterCompositeStatement[T]

AlterAttributeType changes an attribute's type to the one at gives; the attribute is named by at.

func (*AlterCompositeQuery[T]) DropAttribute

func (x *AlterCompositeQuery[T]) DropAttribute(name string) *AlterCompositeStatement[T]

DropAttribute drops an attribute if it exists, and its data in every value.

func (*AlterCompositeQuery[T]) RenameAttribute

func (x *AlterCompositeQuery[T]) RenameAttribute(from, to string) *AlterCompositeStatement[T]

RenameAttribute renames an attribute.

func (*AlterCompositeQuery[T]) RenameTo

func (x *AlterCompositeQuery[T]) RenameTo(to Composite[T]) *AlterTypeNameStatement

RenameTo renames the composite type to to's name.

type AlterCompositeStatement

type AlterCompositeStatement[T any] struct {
	// contains filtered or unexported fields
}

AlterCompositeStatement is a complete ALTER TYPE on a composite, one action.

func (*AlterCompositeStatement[T]) Build

func (x *AlterCompositeStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterCompositeStatement[T]) Cascade

Cascade also changes everything that uses the type: a typed table made with AlterTable's OfType, and any composite type holding this one. Without it Postgres refuses the change while anything depends on it, which is the safe default and not always the one that can be acted on.

type AlterConstraintClause

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

AlterConstraintClause is ALTER CONSTRAINT on a declared constraint: its deferrability, whether it is enforced, or whether a NOT NULL constraint is inherited. It is an ALTER TABLE action, refused on another table's ALTER TABLE.

func AlterConstraint

func AlterConstraint(c TableConstraint) AlterConstraintClause

AlterConstraint starts an ALTER CONSTRAINT on c.

func (AlterConstraintClause) AlterClauseOf

func (AlterConstraintClause) AlterClauseOf(Dialect)

AlterClauseOf marks the action as Postgres's.

func (AlterConstraintClause) ClauseTable

func (x AlterConstraintClause) ClauseTable() sqlb.Table

ClauseTable is the constraint's table, for ALTER TABLE's check.

func (AlterConstraintClause) Deferrable

Deferrable makes the constraint deferrable, checked when d says. Changing deferrability works for foreign keys on Postgres 17, and for the other constraint kinds on 18.

func (AlterConstraintClause) Enforced

Enforced turns an unenforced foreign key on, checking every row. Postgres 18 changes enforceability for foreign keys only and refuses it for a check, measured. Postgres 18 or later.

func (AlterConstraintClause) Inherit

Inherit makes a NOT NULL constraint apply to inheriting tables. Postgres 18 or later.

func (AlterConstraintClause) NoInherit

NoInherit stops a NOT NULL constraint applying to inheriting tables. Postgres 18 or later.

func (AlterConstraintClause) NotDeferrable

func (x AlterConstraintClause) NotDeferrable() AlterConstraintClause

NotDeferrable makes the constraint checked at once, the default.

func (AlterConstraintClause) NotEnforced

NotEnforced stops enforcing a foreign key; a check is refused, as for Enforced. Postgres 18 or later.

func (AlterConstraintClause) Standalone

func (AlterConstraintClause) Standalone() bool

Standalone reports that the action may share a statement.

func (AlterConstraintClause) WriteSQL

func (x AlterConstraintClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type AlterDomainQuery

type AlterDomainQuery[T any] struct {
	// contains filtered or unexported fields
}

AlterDomainQuery is ALTER DOMAIN with no action yet, which has no Build.

func AlterDomain

func AlterDomain[T any](d Domain[T]) *AlterDomainQuery[T]

AlterDomain starts an ALTER DOMAIN.

func (*AlterDomainQuery[T]) AddConstraint

func (x *AlterDomainQuery[T]) AddConstraint(c DomainConstraint[T], p sqlb.Predicate) *AlterDomainStatement[T]

AddConstraint adds a named check; NotValid skips checking existing values.

func (*AlterDomainQuery[T]) DropConstraint

func (x *AlterDomainQuery[T]) DropConstraint(c DomainConstraint[T]) *AlterDomainStatement[T]

DropConstraint drops a named check if it exists.

func (*AlterDomainQuery[T]) DropDefault

func (x *AlterDomainQuery[T]) DropDefault() *AlterDomainStatement[T]

DropDefault removes the domain's default. Columns of the domain that have one of their own keep it.

func (*AlterDomainQuery[T]) DropNotNull

func (x *AlterDomainQuery[T]) DropNotNull() *AlterDomainStatement[T]

DropNotNull allows NULL again.

func (*AlterDomainQuery[T]) RenameConstraint

func (x *AlterDomainQuery[T]) RenameConstraint(from, to DomainConstraint[T]) *AlterDomainStatement[T]

RenameConstraint renames one of the domain's constraints, the migration a declared DomainConstraint needs when its name changes. Both constraints must name this domain, which Build checks, because the server would report one of another domain as a constraint that does not exist.

func (*AlterDomainQuery[T]) RenameTo

func (x *AlterDomainQuery[T]) RenameTo(to Domain[T]) *AlterDomainStatement[T]

RenameTo renames the domain to to's name; its schema is unchanged, which is SetObjectSchema's job. Both are declarations of the same Go type, so a rename cannot change what the domain's values are.

func (*AlterDomainQuery[T]) SetDefault

func (x *AlterDomainQuery[T]) SetDefault(v T) *AlterDomainStatement[T]

SetDefault gives the domain a default, written as a literal of its own Go type. A domain's default applies where a column of the domain has none of its own, so it is the answer for a value every column of the type should start at; a default that differs per column belongs on the column, which is why this was left out until the detector asked for it by name.

func (*AlterDomainQuery[T]) SetDefaultExpr

func (x *AlterDomainQuery[T]) SetDefaultExpr(e sqlb.Expr[T]) *AlterDomainStatement[T]

SetDefaultExpr gives the domain a default computed by e, for a default that is a call rather than a constant.

func (*AlterDomainQuery[T]) SetNotNull

func (x *AlterDomainQuery[T]) SetNotNull() *AlterDomainStatement[T]

SetNotNull refuses NULL in every column of the domain from now on. It scans every table with a column of the type and fails if any row holds NULL, which is why the migration is the three-step one a column's NOT NULL needs.

func (*AlterDomainQuery[T]) ValidateConstraint

func (x *AlterDomainQuery[T]) ValidateConstraint(c DomainConstraint[T]) *AlterDomainStatement[T]

ValidateConstraint checks existing values against a constraint added NOT VALID.

type AlterDomainStatement

type AlterDomainStatement[T any] struct {
	// contains filtered or unexported fields
}

AlterDomainStatement is a complete ALTER DOMAIN.

func (*AlterDomainStatement[T]) Build

func (x *AlterDomainStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterDomainStatement[T]) Cascade

func (x *AlterDomainStatement[T]) Cascade() *AlterDomainStatement[T]

Cascade also drops what depends on the constraint being dropped. It applies to DropConstraint alone, which is the only ALTER DOMAIN action Postgres allows it after, and Build refuses it anywhere else rather than rendering a statement the server would reject.

func (*AlterDomainStatement[T]) NotValid

func (x *AlterDomainStatement[T]) NotValid() *AlterDomainStatement[T]

NotValid adds the constraint without checking existing values; only an added constraint takes it.

type AlterEnumQuery

type AlterEnumQuery[T ~string] struct {
	// contains filtered or unexported fields
}

AlterEnumQuery is ALTER TYPE on an enum with no action yet, which has no Build.

func AlterEnum

func AlterEnum[T ~string](e Enum[T]) *AlterEnumQuery[T]

AlterEnum starts an ALTER TYPE on an enum.

func (*AlterEnumQuery[T]) AddValue

func (x *AlterEnumQuery[T]) AddValue(v T) *AddValueStatement[T]

AddValue adds a label, at the end unless Before or After says otherwise. It runs inside a transaction since Postgres 12, but the new label cannot be used until that transaction commits.

func (*AlterEnumQuery[T]) RenameTo

func (x *AlterEnumQuery[T]) RenameTo(to Enum[T]) *AlterEnumStatement[T]

RenameTo renames the type to to's name; its schema is unchanged.

func (*AlterEnumQuery[T]) RenameValue

func (x *AlterEnumQuery[T]) RenameValue(from, to T) *AlterEnumStatement[T]

RenameValue renames a label. Both are values of T: the old constant is what the code still uses and the new one what it will.

type AlterEnumStatement

type AlterEnumStatement[T ~string] struct {
	// contains filtered or unexported fields
}

AlterEnumStatement is an ALTER TYPE that renames a label or the type.

func (*AlterEnumStatement[T]) Build

func (x *AlterEnumStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

type AlterExtensionStatement

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

AlterExtensionStatement is ALTER EXTENSION ... UPDATE.

func UpdateExtension

func UpdateExtension(e Extension) *AlterExtensionStatement

UpdateExtension updates an installed extension to the version its package files provide, which is how a library picks up a new pgvector.

func (*AlterExtensionStatement) Build

func (x *AlterExtensionStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterExtensionStatement) To

To names the target version rather than the newest installed.

type AlterIndexQuery

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

AlterIndexQuery is ALTER INDEX with no action yet, which has no Build.

func AlterIndex

func AlterIndex(ix Index) *AlterIndexQuery

AlterIndex starts an ALTER INDEX on a declared index. A rename is RenameIndex, which is a statement of its own as every RENAME is.

func (*AlterIndexQuery) AttachPartition

func (x *AlterIndexQuery) AttachPartition(part Index) *AlterIndexStatement

AttachPartition makes an existing index on a partition the partition's copy of this partitioned index. It is how a partitioned index is built without a long lock: create the index on each partition, attach each one here, and the parent index becomes valid when the last partition has been attached. The partition's index must match this one in columns, operator classes and uniqueness, which Postgres checks.

func (*AlterIndexQuery) ResetStorage

func (x *AlterIndexQuery) ResetStorage(first string, more ...string) *AlterIndexStatement

ResetStorage puts the named storage parameters back to the access method's defaults.

func (*AlterIndexQuery) SetStorage

SetStorage sets storage parameters on the index. They are the index's own, not its table's: fillfactor on a b-tree decides how full a page is packed when the index is built, which is a trade a library makes for its own read-heavy or write-heavy index and cannot make for a table it does not own. A change takes effect as pages are rewritten, so it is usually followed by a REINDEX, which is the operator's.

type AlterIndexStatement

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

AlterIndexStatement is a complete ALTER INDEX.

func (*AlterIndexStatement) Build

func (x *AlterIndexStatement) Build() (ddl.Script, error)

Build renders the statement.

type AlterMaterializedViewQuery

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

AlterMaterializedViewQuery is ALTER MATERIALIZED VIEW with no action yet, which has no Build.

func AlterMaterializedView

func AlterMaterializedView(v MaterializedView) *AlterMaterializedViewQuery

AlterMaterializedView starts an ALTER MATERIALIZED VIEW. Renaming the view is RenameMaterializedView, moving it is SetObjectSchema and giving it away is SetOwner, each a standalone form in Postgres's grammar.

func (*AlterMaterializedViewQuery) RenameColumn

RenameColumn renames one of the view's output columns. The names are strings rather than column values because a materialized view's columns are named by its body's select list, which is where their declaration lives.

func (*AlterMaterializedViewQuery) ResetStorage

ResetStorage puts the named storage parameters back to their defaults.

func (*AlterMaterializedViewQuery) SetAccessMethod

SetAccessMethod rewrites the view's rows into another table access method.

func (*AlterMaterializedViewQuery) SetStorage

SetStorage sets storage parameters on the view's own table, a fillfactor or an autovacuum setting, which a view refreshed in full wants set differently from a table written a row at a time.

type AlterMaterializedViewStatement

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

AlterMaterializedViewStatement is a complete ALTER MATERIALIZED VIEW.

func (*AlterMaterializedViewStatement) Build

Build renders the statement.

type AlterPolicyQuery

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

AlterPolicyQuery is ALTER POLICY with no action yet, which has no Build.

func AlterPolicy

func AlterPolicy(p Policy) *AlterPolicyQuery

AlterPolicy starts an ALTER POLICY.

func (*AlterPolicyQuery) RenameTo

func (x *AlterPolicyQuery) RenameTo(to Policy) *AlterPolicyStatement

RenameTo renames the policy; to names the same table.

func (*AlterPolicyQuery) To

func (x *AlterPolicyQuery) To(first RoleRef, more ...RoleRef) *AlterPolicyStatement

To replaces the set of roles the policy applies to, which is the whole set and not an addition: a policy that named PUBLIC and is given a Role here stops applying to everyone else. It is how a library hands its tables to a named application role after an install ran as somebody else.

func (*AlterPolicyQuery) Using

Using replaces the policy's USING predicate, which is how a policy's rule changes without a window in which it is dropped.

func (*AlterPolicyQuery) WithCheck

WithCheck replaces the policy's WITH CHECK predicate.

type AlterPolicyStatement

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

AlterPolicyStatement is a complete ALTER POLICY.

Its three changeable parts accumulate into one statement rather than one each, because Postgres's grammar takes them together and a policy changed in three statements has two windows in which it is half changed: the roles are the new ones and the predicate is still the old one. RenameTo is the exception and is a form of its own in the grammar, so it cannot be combined and Build refuses the combination.

func (*AlterPolicyStatement) Build

func (x *AlterPolicyStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterPolicyStatement) To

To replaces the roles, beside whatever else this statement changes.

func (*AlterPolicyStatement) Using

Using replaces the policy's USING predicate, beside whatever else this statement changes.

func (*AlterPolicyStatement) WithCheck

WithCheck replaces the policy's WITH CHECK predicate, beside whatever else this statement changes.

type AlterRangeTypeQuery

type AlterRangeTypeQuery[T any] struct {
	// contains filtered or unexported fields
}

AlterRangeTypeQuery is ALTER TYPE on a range type with no action yet, which has no Build.

func AlterRangeType

func AlterRangeType[T any](r RangeType[T]) *AlterRangeTypeQuery[T]

AlterRangeType starts an ALTER TYPE on a range type. Moving it is SetObjectSchema and giving it away is SetOwner, as for every other declared object.

func (*AlterRangeTypeQuery[T]) RenameTo

func (x *AlterRangeTypeQuery[T]) RenameTo(to RangeType[T]) *AlterTypeNameStatement

RenameTo renames the range type to to's name.

type AlterSequenceQuery

type AlterSequenceQuery[T sequenceInteger] struct {
	// contains filtered or unexported fields
}

AlterSequenceQuery is ALTER SEQUENCE with no action yet, which has no Build.

func AlterSequence

func AlterSequence[T sequenceInteger](s Sequence[T]) *AlterSequenceQuery[T]

AlterSequence starts an ALTER SEQUENCE.

func (*AlterSequenceQuery[T]) Cache

func (x *AlterSequenceQuery[T]) Cache(n int64) *AlterSequenceStatement[T]

Cache changes how many values a session preallocates, at least 1.

func (*AlterSequenceQuery[T]) Cycle

func (x *AlterSequenceQuery[T]) Cycle() *AlterSequenceStatement[T]

Cycle makes the sequence wrap past its bound instead of failing.

func (*AlterSequenceQuery[T]) IncrementBy

func (x *AlterSequenceQuery[T]) IncrementBy(n T) *AlterSequenceStatement[T]

IncrementBy changes the step.

func (*AlterSequenceQuery[T]) MaxValue

func (x *AlterSequenceQuery[T]) MaxValue(n T) *AlterSequenceStatement[T]

MaxValue changes the highest value.

func (*AlterSequenceQuery[T]) MinValue

func (x *AlterSequenceQuery[T]) MinValue(n T) *AlterSequenceStatement[T]

MinValue changes the lowest value.

func (*AlterSequenceQuery[T]) NoCycle

func (x *AlterSequenceQuery[T]) NoCycle() *AlterSequenceStatement[T]

NoCycle makes the sequence fail past its bound, the default.

func (*AlterSequenceQuery[T]) NoMaxValue

func (x *AlterSequenceQuery[T]) NoMaxValue() *AlterSequenceStatement[T]

NoMaxValue starts an ALTER SEQUENCE removing the upper bound.

func (*AlterSequenceQuery[T]) NoMinValue

func (x *AlterSequenceQuery[T]) NoMinValue() *AlterSequenceStatement[T]

NoMinValue starts an ALTER SEQUENCE removing the lower bound.

func (*AlterSequenceQuery[T]) OwnedBy

func (x *AlterSequenceQuery[T]) OwnedBy(col sqlb.Expr[T]) *AlterSequenceStatement[T]

OwnedBy ties the sequence to a column, so dropping the column drops it. The column is of the sequence's own type.

func (*AlterSequenceQuery[T]) OwnedByNone

func (x *AlterSequenceQuery[T]) OwnedByNone() *AlterSequenceStatement[T]

OwnedByNone unties the sequence from its column.

func (*AlterSequenceQuery[T]) RenameTo

func (x *AlterSequenceQuery[T]) RenameTo(to Sequence[T]) *AlterSequenceStatement[T]

RenameTo renames the sequence to to's name, taking the new declaration the code will use rather than a string. A statement of its own: chaining an option onto it fails Build with ErrRenameAlone.

func (*AlterSequenceQuery[T]) Restart

func (x *AlterSequenceQuery[T]) Restart(n T) *AlterSequenceStatement[T]

Restart makes the next value n.

func (*AlterSequenceQuery[T]) SetLogged

func (x *AlterSequenceQuery[T]) SetLogged() *AlterSequenceStatement[T]

SetLogged starts an ALTER SEQUENCE making the sequence crash-safe.

func (*AlterSequenceQuery[T]) SetType

func (x *AlterSequenceQuery[T]) SetType() *AlterSequenceStatement[T]

SetType starts an ALTER SEQUENCE writing AS the sequence's own integer type.

func (*AlterSequenceQuery[T]) SetUnlogged

func (x *AlterSequenceQuery[T]) SetUnlogged() *AlterSequenceStatement[T]

SetUnlogged starts an ALTER SEQUENCE making the sequence unlogged.

func (*AlterSequenceQuery[T]) StartWith

func (x *AlterSequenceQuery[T]) StartWith(n T) *AlterSequenceStatement[T]

StartWith starts an ALTER SEQUENCE changing the start value.

type AlterSequenceStatement

type AlterSequenceStatement[T sequenceInteger] struct {
	// contains filtered or unexported fields
}

AlterSequenceStatement is a complete ALTER SEQUENCE: one or more options, which Postgres applies together, or a rename, which must stand alone.

func (*AlterSequenceStatement[T]) Build

func (x *AlterSequenceStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterSequenceStatement[T]) Cache

Cache adds CACHE n.

func (*AlterSequenceStatement[T]) Cycle

Cycle adds CYCLE.

func (*AlterSequenceStatement[T]) IfExists

func (x *AlterSequenceStatement[T]) IfExists() *AlterSequenceStatement[T]

IfExists makes altering a missing sequence a no-op.

func (*AlterSequenceStatement[T]) IncrementBy

func (x *AlterSequenceStatement[T]) IncrementBy(n T) *AlterSequenceStatement[T]

IncrementBy adds INCREMENT BY n.

func (*AlterSequenceStatement[T]) MaxValue

func (x *AlterSequenceStatement[T]) MaxValue(n T) *AlterSequenceStatement[T]

MaxValue adds MAXVALUE n.

func (*AlterSequenceStatement[T]) MinValue

func (x *AlterSequenceStatement[T]) MinValue(n T) *AlterSequenceStatement[T]

MinValue adds MINVALUE n.

func (*AlterSequenceStatement[T]) NoCycle

func (x *AlterSequenceStatement[T]) NoCycle() *AlterSequenceStatement[T]

NoCycle adds NO CYCLE.

func (*AlterSequenceStatement[T]) NoMaxValue

func (x *AlterSequenceStatement[T]) NoMaxValue() *AlterSequenceStatement[T]

NoMaxValue puts the sequence's upper bound back to the type's own.

func (*AlterSequenceStatement[T]) NoMinValue

func (x *AlterSequenceStatement[T]) NoMinValue() *AlterSequenceStatement[T]

NoMinValue puts the sequence's lower bound back to the type's own, which is how a bound set by an earlier migration is removed rather than widened by a guess at what the type's minimum is.

func (*AlterSequenceStatement[T]) OwnedBy

func (x *AlterSequenceStatement[T]) OwnedBy(col sqlb.Expr[T]) *AlterSequenceStatement[T]

OwnedBy adds OWNED BY col.

func (*AlterSequenceStatement[T]) OwnedByNone

func (x *AlterSequenceStatement[T]) OwnedByNone() *AlterSequenceStatement[T]

OwnedByNone adds OWNED BY NONE.

func (*AlterSequenceStatement[T]) Restart

func (x *AlterSequenceStatement[T]) Restart(n T) *AlterSequenceStatement[T]

Restart adds RESTART WITH n.

func (*AlterSequenceStatement[T]) SetLogged

func (x *AlterSequenceStatement[T]) SetLogged() *AlterSequenceStatement[T]

SetLogged makes the sequence crash-safe again, the default. Postgres 15 and later.

func (*AlterSequenceStatement[T]) SetType

func (x *AlterSequenceStatement[T]) SetType() *AlterSequenceStatement[T]

SetType writes AS, changing the sequence's integer type to T's. Declare the sequence with its new Go type, Sequence[int64] where it was Sequence[int32], and this migration follows from the declaration rather than from a string. Postgres adjusts MINVALUE and MAXVALUE to the new type's range unless the same statement sets them.

func (*AlterSequenceStatement[T]) SetUnlogged

func (x *AlterSequenceStatement[T]) SetUnlogged() *AlterSequenceStatement[T]

SetUnlogged stops writing the sequence to the write-ahead log, which is faster and resets it to its start value after a crash. It is for a sequence whose gaps and losses do not matter, and a logged table's identity column may not use one. Postgres 15 and later.

func (*AlterSequenceStatement[T]) StartWith

func (x *AlterSequenceStatement[T]) StartWith(n T) *AlterSequenceStatement[T]

StartWith changes the value RESTART with no argument goes back to. It does not move the sequence: Restart does that.

type AlterTableQuery

type AlterTableQuery = ddl.AlterTable[Dialect]

AlterTableQuery is an ALTER TABLE with no action yet, which has no Build.

func AlterTable

func AlterTable(t sqlb.Table) *AlterTableQuery

AlterTable starts an ALTER TABLE of t for Postgres.

type AlterTableReady

type AlterTableReady = ddl.AlterTableReady[Dialect]

AlterTableReady is an ALTER TABLE with at least one action.

type AlterTypeClause

type AlterTypeClause[T any] struct {
	// contains filtered or unexported fields
}

AlterTypeClause is ALTER COLUMN ... SET DATA TYPE, optionally with USING.

func AlterType

func AlterType[T any](col sqlb.Expr[T], t ddl.SQLType[T]) AlterTypeClause[T]

AlterType changes a column's type. col is the column's new declaration, so the SQL type is checked against its Go type as a column definition's is; the old declaration is what the code being changed still uses.

func (AlterTypeClause[T]) AlterClauseOf

func (AlterTypeClause[T]) AlterClauseOf(Dialect)

AlterClauseOf marks the action as Postgres's.

func (AlterTypeClause[T]) Collate

func (x AlterTypeClause[T]) Collate(collation string) AlterTypeClause[T]

Collate gives the column a collation as its type changes, written straight after the type as Postgres's grammar requires.

func (AlterTypeClause[T]) NamedColumns

func (x AlterTypeClause[T]) NamedColumns() []ddl.ColumnRef

NamedColumns is the column being changed.

func (AlterTypeClause[T]) Standalone

func (AlterTypeClause[T]) Standalone() bool

Standalone reports that the action may share a statement.

func (AlterTypeClause[T]) Using

func (x AlterTypeClause[T]) Using(e sqlb.Expr[T]) AlterTypeClause[T]

Using converts each existing value with e, an expression of the new type. Without it Postgres casts implicitly, and refuses a type it has no implicit cast to.

func (AlterTypeClause[T]) WriteSQL

func (x AlterTypeClause[T]) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type AlterTypeNameStatement

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

AlterTypeNameStatement is ALTER TYPE ... RENAME TO, which every kind of type shares: the statement is the same whatever the type is, and the type's Go parameter has already done its work in the constructor that made it.

func (*AlterTypeNameStatement) Build

func (x *AlterTypeNameStatement) Build() (ddl.Script, error)

Build renders the statement.

type AlterViewOptionsStatement

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

AlterViewOptionsStatement is the ALTER VIEW statement that sets and resets a view's options. Postgres keeps SET and RESET apart in its grammar, so a statement that both sets and resets builds a Script of two.

func AlterViewOptions

func AlterViewOptions(v View) *AlterViewOptionsStatement

AlterViewOptions starts a change to a view's options. The view's body is changed with CreateView(v).OrReplace() instead, which is the only way to rewrite one.

func (*AlterViewOptionsStatement) Build

func (x *AlterViewOptionsStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*AlterViewOptionsStatement) CheckOption

CheckOption refuses a write through the view that the view would not show, the option CreateView writes as WITH ... CHECK OPTION. Setting it on an existing view is how it is turned on without rewriting the body.

func (*AlterViewOptionsStatement) Reset

Reset puts the named options back to their defaults. It renders as a second statement beside anything the same builder sets.

func (*AlterViewOptionsStatement) SecurityBarrier

SecurityBarrier stops Postgres pushing a caller's own WHERE condition below the view's, which would otherwise let a cheap function in that condition see rows the view hides. It costs plans, so it is off by default.

func (*AlterViewOptionsStatement) SecurityInvoker

SecurityInvoker runs the view's own query with the caller's privileges rather than the view owner's, so the caller's row-level security policies apply to the tables under it. A library shipping a view over its own RLS-protected tables wants this on.

type AlterViewStatement

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

AlterViewStatement is ALTER VIEW ... ALTER COLUMN, the default of a view's column, which an INSERT through an updatable view uses.

func DropViewColumnDefault

func DropViewColumnDefault[T any](v View, col sqlb.Expr[T]) *AlterViewStatement

DropViewColumnDefault removes a view column's default.

func SetViewColumnDefault

func SetViewColumnDefault[T any](v View, col sqlb.Expr[T], value T) *AlterViewStatement

SetViewColumnDefault gives a view's column a default, a literal of the column's own Go type. It is a function rather than a method because the value's type comes from the column.

func (*AlterViewStatement) Build

func (x *AlterViewStatement) Build() (ddl.Script, error)

Build renders the statement.

type Attribute

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

Attribute is one attribute of a composite type: a name and a typed SQL type, the type's Go parameter checked when the attribute is made and erased after, since a composite's attributes are of different types.

func Attr

func Attr[T any](name string, t ddl.SQLType[T]) Attribute

Attr makes an attribute of type t.

type BaseType

type BaseType[T any] struct{ Schema, Name string }

BaseType is a Postgres base type, a type implemented by functions rather than composed from other types, whose values a Go program sees as T. It is also the SQL type of a column holding one.

func (BaseType[T]) Spelling

func (b BaseType[T]) Spelling(d sqlb.Dialect) (string, error)

Spelling is the type's qualified name, as a column definition writes it.

func (BaseType[T]) TypeOf

func (BaseType[T]) TypeOf(T)

TypeOf types the base type to T for ddl.SQLType.

type BitString

type BitString string

BitString is a bit(n) or varbit value in text form.

type Bounds

type Bounds string

Bounds is the inclusivity string a range constructor takes: "[)", "[]", "(]", "()".

const (
	BoundsIncExc Bounds = "[)"
	BoundsIncInc Bounds = "[]"
	BoundsExcInc Bounds = "(]"
	BoundsExcExc Bounds = "()"
)

The four inclusivity combinations. Half-open "[)" is the one to reach for: adjacent ranges meet without overlapping, which is what makes Adjacent and an exclusion constraint behave.

type CheckClause

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

CheckClause is a named CHECK table constraint, the same one ddl.Check writes.

func Check

Check makes a named CHECK constraint. In CREATE TABLE it is the same as ddl.Check; it exists because ALTER TABLE ... ADD CONSTRAINT is Postgres's and takes a Postgres constraint.

func (CheckClause) ClauseTable

func (c CheckClause) ClauseTable() sqlb.Table

ClauseTable is the constraint's declared table.

func (CheckClause) NoInherit

func (c CheckClause) NoInherit() CheckClause

NoInherit keeps the check on this table alone, so a child table created by Inherits does not get it. It means nothing on a table nothing inherits from, and it is the one column-level difference inheritance makes to a constraint.

func (CheckClause) NotEnforced

func (c CheckClause) NotEnforced() CheckClause

NotEnforced declares the check without enforcing it: Postgres records it, but rows that break it are accepted. A check cannot be switched to enforced afterwards, measured on Postgres 18, which refuses ALTER CONSTRAINT ... ENFORCED on one; drop it and add it enforced instead. Postgres 18 or later.

func (CheckClause) Position

func (CheckClause) Position() ddl.Position

Position places the constraint among the table's elements.

func (CheckClause) TableClauseOf

func (CheckClause) TableClauseOf(Dialect)

TableClauseOf marks the clause as Postgres's.

func (CheckClause) WriteSQL

func (c CheckClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the constraint, with columns bare as a CHECK requires.

type CheckOption

type CheckOption int

CheckOption is what a view's WITH CHECK OPTION checks: an INSERT or UPDATE through the view must produce a row the view shows.

const (
	Local CheckOption = iota + 1
	Cascaded
)

The check options. Local checks this view's condition; Cascaded also checks every view it is built on.

type Collation

type Collation struct{ Schema, Name string }

Collation is a Postgres collation.

type ColumnDef

type ColumnDef struct {
	Name string
	Type string
}

ColumnDef is one typed column of a record-set alias: AS x(sku text, ...).

type ColumnPair

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

ColumnPair is one column of a foreign key and the column it references.

func RefPair

func RefPair[T any](local, ref sqlb.Expr[T]) ColumnPair

RefPair pairs a column with the column it references. Both are of one Go type, so a bigint referencing a text column does not compile. A composite key is a list of pairs rather than two column lists, because Go generics cannot express two variadic lists of matching types; that is the reason scan.Map2 is pairwise too.

type CommentQuery

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

CommentQuery is COMMENT ON an object with no text yet, which has no Build.

func CommentOn

func CommentOn(o Commentable) *CommentQuery

CommentOn starts a comment on a declared object: an Index, a Schema, an Extension or an Enum.

func CommentOnColumn

func CommentOnColumn[T any](c sqlb.Expr[T]) *CommentQuery

CommentOnColumn starts a comment on a column.

func CommentOnConstraint

func CommentOnConstraint(c TableConstraint) *CommentQuery

CommentOnConstraint starts a comment on a declared table constraint: COMMENT ON CONSTRAINT name ON table.

func CommentOnDomainConstraint

func CommentOnDomainConstraint[T any](c DomainConstraint[T]) *CommentQuery

CommentOnDomainConstraint starts a comment on a domain's constraint: COMMENT ON CONSTRAINT name ON DOMAIN domain. It is a separate constructor from CommentOnConstraint because Postgres spells the two differently and a domain's constraint is a different object from a table's.

func CommentOnTable

func CommentOnTable(t sqlb.Table) *CommentQuery

CommentOnTable starts a comment on a table.

func (*CommentQuery) Is

func (x *CommentQuery) Is(text string) *CommentStatement

Is sets the comment. The text is written as a literal by the dialect, so quotes and backslashes are stored exactly.

func (*CommentQuery) IsNull

func (x *CommentQuery) IsNull() *CommentStatement

IsNull removes the comment.

type CommentStatement

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

CommentStatement is a complete COMMENT ON.

func (*CommentStatement) Build

func (x *CommentStatement) Build() (ddl.Script, error)

Build renders the statement.

type Commentable

type Commentable interface {
	// contains filtered or unexported methods
}

Commentable is a declared object COMMENT ON can name. The object kind comes from the Go type, so the statement cannot say INDEX of a table; the set is closed to this package's object values and the two constructors below.

type CompareOp

type CompareOp string

CompareOp is the operator a comparison against ANY or ALL uses. It is a named type rather than a bare string because the value is written into the statement as a token and cannot be quoted: an operator in quotes is not an operator. The core's untyped operator constants, sqlb.OpEq and its siblings, are still what a caller passes.

It is an open set, as ExcludeOp is, because an extension brings its own operators; what it is not is a free string.

type Composite

type Composite[T any] struct{ Schema, Name string }

Composite is a composite type, declared once: a named row of typed attributes, CREATE TYPE ... AS (...). It is a ddl.SQLType[T] for the Go type T a column of it scans into, a struct with a Scan method say, so ddl.Column(c).As(money) compiles only on a Col[T].

func (Composite[T]) Spelling

func (c Composite[T]) Spelling(d sqlb.Dialect) (string, error)

Spelling is the type's qualified name, as a column definition writes it.

func (Composite[T]) TypeOf

func (Composite[T]) TypeOf(T)

TypeOf types the composite to T for ddl.SQLType.

type Conflict

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

Conflict accumulates an ON CONFLICT clause for an Insert. Build it with OnConflict or OnConstraint, then DoNothing or DoUpdate.

func OnConflict

func OnConflict(cols ...sqlb.SQLer) *Conflict

OnConflict targets the given columns (a unique index). No columns means any conflict, which is valid only with DoNothing.

func OnConstraint

func OnConstraint(c TableConstraint) *Conflict

OnConstraint targets a named constraint.

func (*Conflict) Clause

func (c *Conflict) Clause() InsertClause

Clause finishes a DoUpdate chain.

func (*Conflict) DoNothing

func (c *Conflict) DoNothing() InsertClause

DoNothing renders DO NOTHING.

func (*Conflict) DoUpdate

func (c *Conflict) DoUpdate(as ...sqlb.Assignment) *Conflict

DoUpdate renders DO UPDATE SET assignments. Use Excluded for the proposed row.

func (*Conflict) TargetWhere

func (c *Conflict) TargetWhere(ps ...sqlb.Predicate) *Conflict

TargetWhere adds the WHERE of a partial unique index to the target.

func (*Conflict) UpdateWhere

func (c *Conflict) UpdateWhere(ps ...sqlb.Predicate) *Conflict

UpdateWhere adds a condition to the DO UPDATE.

type Constraint

type Constraint interface {
	TableClause
	// contains filtered or unexported methods
}

Constraint is a Postgres table constraint that ALTER TABLE can add: a primary key, a unique constraint, a foreign key or a check. The set is closed, so the unexported method keeps anything else out.

type ConstraintStatement

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

ConstraintStatement is ALTER TABLE ... ADD CONSTRAINT as a statement on its own, which is the form Guarded accepts: Postgres raises duplicate_object when a constraint of that name exists, and has no IF NOT EXISTS for it.

func AddConstraintStatement

func AddConstraintStatement(c Constraint) *ConstraintStatement

AddConstraintStatement is ALTER TABLE ADD c as its own statement, for Guarded, on the table the constraint's TableConstraint names. On pg.AlterTable, AddConstraint is the same action among others.

func (*ConstraintStatement) Build

func (x *ConstraintStatement) Build() (ddl.Script, error)

Build renders the statement.

type CreateBaseTypeStatement

type CreateBaseTypeStatement[T any] struct {
	// contains filtered or unexported fields
}

CreateBaseTypeStatement is the CREATE TYPE that fills in a shell type.

func CreateBaseType

func CreateBaseType[T any](b BaseType[T], input, output Function) *CreateBaseTypeStatement[T]

CreateBaseType turns a shell type into a base type, with input the function that parses a value's text form and output the one that prints it. Both must already exist and both must name the shell type, which is why CreateShellType runs first.

A base type is the one thing in this package that cannot be undone by declaration alone: dropping it takes everything that uses it, and getting the length, alignment or storage wrong corrupts every value stored under it rather than failing. It is built here because the statement is a statement like any other, not because a library should reach for one.

func (*CreateBaseTypeStatement[T]) Alignment

Alignment is the boundary a stored value starts on.

func (*CreateBaseTypeStatement[T]) Analyze

Analyze names the function that gathers the planner's statistics for the type; without it the type has none and every estimate over it is a guess.

func (*CreateBaseTypeStatement[T]) Build

func (x *CreateBaseTypeStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateBaseTypeStatement[T]) Category

Category puts the type in a class for the parser's cast resolution.

func (*CreateBaseTypeStatement[T]) Collatable

func (x *CreateBaseTypeStatement[T]) Collatable(on bool) *CreateBaseTypeStatement[T]

Collatable allows a column of the type to carry a collation, which its own functions must then honour.

func (*CreateBaseTypeStatement[T]) Default

func (x *CreateBaseTypeStatement[T]) Default(v T) *CreateBaseTypeStatement[T]

Default is the value a column of the type holds where neither the insert nor the column definition gives one, written as a literal of T.

func (*CreateBaseTypeStatement[T]) Delimiter

Delimiter is the character separating two values in the text form of an array of this type.

func (*CreateBaseTypeStatement[T]) Element

Element declares the type an array of r, so subscripting it is defined.

func (*CreateBaseTypeStatement[T]) InternalLength

func (x *CreateBaseTypeStatement[T]) InternalLength(n int) *CreateBaseTypeStatement[T]

InternalLength is the fixed width of a value in bytes. It must match what the input function actually produces: a wrong length is not rejected, it reads the wrong bytes out of every row.

func (*CreateBaseTypeStatement[T]) Like

Like copies another type's length, alignment, storage and by-value properties, which is how a type that is an int4 underneath is declared without repeating what an int4 is.

func (*CreateBaseTypeStatement[T]) PassedByValue

func (x *CreateBaseTypeStatement[T]) PassedByValue() *CreateBaseTypeStatement[T]

PassedByValue passes a value in a register rather than by reference, which only a type no wider than a pointer may do.

func (*CreateBaseTypeStatement[T]) Preferred

func (x *CreateBaseTypeStatement[T]) Preferred(on bool) *CreateBaseTypeStatement[T]

Preferred makes the type the one the parser casts towards within its category, which a user-defined type should almost never claim.

func (*CreateBaseTypeStatement[T]) Receive

Receive names the function that reads the type's binary form, without which the type cannot be sent over the binary protocol.

func (*CreateBaseTypeStatement[T]) Send

Send names the function that writes the type's binary form.

func (*CreateBaseTypeStatement[T]) Storage

Storage is what the server may do with a value too wide for its row.

func (*CreateBaseTypeStatement[T]) Subscript

Subscript names the function that implements value[i] for the type.

func (*CreateBaseTypeStatement[T]) TypmodIn

TypmodIn names the function that parses a type modifier, the (n) in a declaration like numeric(10,2).

func (*CreateBaseTypeStatement[T]) TypmodOut

TypmodOut names the function that prints a type modifier back.

func (*CreateBaseTypeStatement[T]) VariableLength

func (x *CreateBaseTypeStatement[T]) VariableLength() *CreateBaseTypeStatement[T]

VariableLength declares the type's values variable width, the form whose first four bytes are the length.

type CreateCollationStatement

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

CreateCollationStatement is CREATE COLLATION.

func CreateCollation

func CreateCollation(c Collation, locale string) *CreateCollationStatement

CreateCollation creates a collation for locale, from the operating system's library unless ICU is given.

func CreateCollationFrom

func CreateCollationFrom(c, existing Collation) *CreateCollationStatement

CreateCollationFrom copies an existing collation under a new name, the form that takes no options at all. It is how a library gives a stable name of its own to whatever the deployment's default collation is.

func (*CreateCollationStatement) Build

func (x *CreateCollationStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateCollationStatement) ICU

ICU takes the collation from ICU, which is the only provider that can be nondeterministic.

func (*CreateCollationStatement) IfNotExists

IfNotExists makes creating an existing collation a no-op.

func (*CreateCollationStatement) LcCollate

LcCollate sets the collation's sort order separately from its character classification, the libc provider's two halves. It is mutually exclusive with the locale CreateCollation takes, which sets both.

func (*CreateCollationStatement) LcCtype

LcCtype sets the collation's character classification.

func (*CreateCollationStatement) Nondeterministic

func (x *CreateCollationStatement) Nondeterministic() *CreateCollationStatement

Nondeterministic makes strings that compare equal under the locale equal, so an ICU level-2 collation makes a UNIQUE on an email case-insensitive without a lower() column. It needs ICU.

func (*CreateCollationStatement) Rules

Rules adds ICU tailoring rules on top of the locale, which is how a collation sorts one character out of its usual place without a locale of its own. Postgres 16 and later, ICU only.

func (*CreateCollationStatement) Version

Version records the collation library's version the collation was made against, so the server can warn when an upgrade changes the sort order and an index built under the old one is silently wrong.

It may only be given where the provider reports a version at all: ICU always does, and the libc C locale never does, which Postgres 18.6 refuses with "collation has no actual version, but a version was recorded" where 17.10 on macOS accepted it. Measured on both.

type CreateCompositeStatement

type CreateCompositeStatement[T any] struct {
	// contains filtered or unexported fields
}

CreateCompositeStatement is CREATE TYPE ... AS (...). Postgres has no IF NOT EXISTS for it; wrap it in Guarded.

func CreateComposite

func CreateComposite[T any](c Composite[T], first Attribute, more ...Attribute) *CreateCompositeStatement[T]

CreateComposite creates a composite type with at least one attribute.

func (*CreateCompositeStatement[T]) Build

func (x *CreateCompositeStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

type CreateDomainStatement

type CreateDomainStatement[T any] struct {
	// contains filtered or unexported fields
}

CreateDomainStatement is CREATE DOMAIN.

func CreateDomain

func CreateDomain[T any](d Domain[T], base ddl.SQLType[T]) *CreateDomainStatement[T]

CreateDomain creates a domain over base, a type for the same Go type. Postgres has no IF NOT EXISTS for it; wrap it in Guarded.

func (*CreateDomainStatement[T]) Build

func (x *CreateDomainStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateDomainStatement[T]) Check

Check adds a named constraint on DomainValue.

func (*CreateDomainStatement[T]) Collate

Collate gives the domain a collation, which every column of the type then carries; it is how a case-insensitive text type is declared once rather than on each column.

func (*CreateDomainStatement[T]) Default

func (x *CreateDomainStatement[T]) Default(v T) *CreateDomainStatement[T]

Default gives the domain a default at creation, written as a literal of its own Go type; AlterDomain's SetDefault changes it afterwards.

func (*CreateDomainStatement[T]) DefaultExpr

func (x *CreateDomainStatement[T]) DefaultExpr(e sqlb.Expr[T]) *CreateDomainStatement[T]

DefaultExpr gives the domain a default computed by e.

func (*CreateDomainStatement[T]) NotNull

func (x *CreateDomainStatement[T]) NotNull() *CreateDomainStatement[T]

NotNull refuses NULL wherever the domain is used.

type CreateEnumStatement

type CreateEnumStatement[T ~string] struct {
	// contains filtered or unexported fields
}

CreateEnumStatement is CREATE TYPE ... AS ENUM.

func CreateEnum

func CreateEnum[T ~string](e Enum[T], first T, more ...T) *CreateEnumStatement[T]

CreateEnum creates an enum with its labels in order. Postgres has no IF NOT EXISTS for it, so there is no such method; wrap it in Guarded to make it safe to run twice.

func (*CreateEnumStatement[T]) Build

func (x *CreateEnumStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

type CreateExtensionStatement

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

CreateExtensionStatement is CREATE EXTENSION.

func CreateExtension

func CreateExtension(e Extension) *CreateExtensionStatement

CreateExtension installs an extension into the database. It needs a role allowed to, which a library's own role often is not; the operator may run it instead, which is why it is a statement of its own.

func (*CreateExtensionStatement) Build

func (x *CreateExtensionStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateExtensionStatement) Cascade

Cascade installs the extensions this one depends on, rather than failing on the first one missing.

func (*CreateExtensionStatement) IfNotExists

IfNotExists makes installing an installed extension a no-op.

func (*CreateExtensionStatement) Schema

Schema installs the extension's objects into a named schema rather than the first of the search path, which is what a library does when it keeps its dependencies out of the schema its caller's tables live in. An extension that declares itself non-relocatable has its own schema and refuses this.

func (*CreateExtensionStatement) Version

Version pins the extension version to install, rather than the newest the package files offer. A library that depends on a function an extension added in a known version pins it here and updates with UpdateExtension.

type CreateFunctionStatement

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

CreateFunctionStatement is CREATE FUNCTION ... RETURNS trigger.

func CreateTriggerFunction

func CreateTriggerFunction(f Function, body string) *CreateFunctionStatement

CreateTriggerFunction creates a PL/pgSQL trigger function with body, which is a program rather than an expression and so the one place a whole body is a string: the library author writes it, it is never built from input, and it is dollar-quoted with a tag it does not contain.

func (*CreateFunctionStatement) Build

func (x *CreateFunctionStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateFunctionStatement) OrReplace

OrReplace replaces an existing function of the name, which is the idempotent form; Postgres has no CREATE FUNCTION IF NOT EXISTS.

type CreateIndexQuery

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

CreateIndexQuery is a CREATE INDEX with no key yet, which has no Build.

func CreateIndex

func CreateIndex(ix Index, t sqlb.Table) *CreateIndexQuery

CreateIndex starts an index ix on table t.

func (*CreateIndexQuery) Concurrently

func (x *CreateIndexQuery) Concurrently() *CreateIndexQuery

Concurrently builds without blocking writes; see CreateIndexReady.Concurrently.

func (*CreateIndexQuery) IfNotExists

func (x *CreateIndexQuery) IfNotExists() *CreateIndexQuery

IfNotExists makes creating an existing index a no-op.

func (*CreateIndexQuery) On

On gives the keys, at least one, and so completes the statement.

func (*CreateIndexQuery) Unique

func (x *CreateIndexQuery) Unique() *CreateIndexQuery

Unique makes the index refuse duplicate keys.

func (*CreateIndexQuery) Using

Using picks the access method; btree when not given.

type CreateIndexReady

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

CreateIndexReady is a CREATE INDEX with at least one key.

func (*CreateIndexReady) Build

func (x *CreateIndexReady) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateIndexReady) Concurrently

func (x *CreateIndexReady) Concurrently() *CreateIndexReady

Concurrently builds the index without blocking writes. Postgres refuses it inside a transaction, so the Statement is marked non-transactional and a runner must execute it on its own; a failed concurrent build leaves an invalid index that must be dropped before it is tried again.

func (*CreateIndexReady) IfNotExists

func (x *CreateIndexReady) IfNotExists() *CreateIndexReady

IfNotExists makes creating an existing index a no-op. It checks the name only: an index of that name on other columns is left as it is.

func (*CreateIndexReady) Include

func (x *CreateIndexReady) Include(cols ...ddl.ColumnRef) *CreateIndexReady

Include adds non-key columns, so a query reading only those is answered from the index alone.

func (*CreateIndexReady) NullsNotDistinct

func (x *CreateIndexReady) NullsNotDistinct() *CreateIndexReady

NullsNotDistinct makes a unique index treat NULLs as equal. Postgres 15 or later.

func (*CreateIndexReady) OnOnly

func (x *CreateIndexReady) OnOnly() *CreateIndexReady

OnOnly creates the index on the named table alone rather than on its partitions, which is the first half of building a partitioned index without a long lock: the parent index is created invalid, each partition's index is built separately, and AlterIndex's AttachPartition makes the parent valid as the last one is attached.

func (*CreateIndexReady) Unique

func (x *CreateIndexReady) Unique() *CreateIndexReady

Unique makes the index refuse duplicate keys.

func (*CreateIndexReady) Using

Using picks the access method; btree when not given.

func (*CreateIndexReady) Where

Where makes the index partial: only rows matching p are indexed, and a query uses it only when its own filter implies p.

func (*CreateIndexReady) With

With sets storage parameters.

type CreateMaterializedViewQuery

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

CreateMaterializedViewQuery is CREATE MATERIALIZED VIEW with no body yet.

func CreateMaterializedView

func CreateMaterializedView(v MaterializedView) *CreateMaterializedViewQuery

CreateMaterializedView starts a materialized view.

func (*CreateMaterializedViewQuery) As

As gives the body.

func (*CreateMaterializedViewQuery) IfNotExists

IfNotExists makes creating an existing materialized view a no-op.

type CreateMaterializedViewStatement

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

CreateMaterializedViewStatement is a complete CREATE MATERIALIZED VIEW.

func (*CreateMaterializedViewStatement) Build

Build renders the statement.

func (*CreateMaterializedViewStatement) Columns

Columns names the materialized view's output columns.

func (*CreateMaterializedViewStatement) IfNotExists

IfNotExists makes creating an existing materialized view a no-op.

func (*CreateMaterializedViewStatement) Using

Using stores the view's rows in an access method other than the default.

func (*CreateMaterializedViewStatement) WithNoData

WithNoData creates it empty, so the install does not run the query; it cannot be read until the first refresh.

func (*CreateMaterializedViewStatement) WithStorage

WithStorage sets the storage parameters of the table behind the view, which a view refreshed in full wants set differently from a table written a row at a time.

type CreatePartitionQuery

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

CreatePartitionQuery is CREATE TABLE ... PARTITION OF with no bounds yet, which has no Build.

func CreatePartition

func CreatePartition(child, parent sqlb.Table) *CreatePartitionQuery

CreatePartition starts a partition child of parent. It has no column list: the partition takes the parent's.

func (*CreatePartitionQuery) For

For gives the bounds, and so completes the statement.

func (*CreatePartitionQuery) IfNotExists

func (x *CreatePartitionQuery) IfNotExists() *CreatePartitionQuery

IfNotExists makes creating an existing partition a no-op.

type CreatePartitionStatement

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

CreatePartitionStatement is a complete CREATE TABLE ... PARTITION OF.

func (*CreatePartitionStatement) Build

func (x *CreatePartitionStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreatePartitionStatement) IfNotExists

IfNotExists makes creating an existing partition a no-op.

type CreatePolicyStatement

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

CreatePolicyStatement is CREATE POLICY.

func CreatePolicy

func CreatePolicy(p Policy) *CreatePolicyStatement

CreatePolicy creates a policy. Postgres has no IF NOT EXISTS for it; wrap it in Guarded. It has no effect until row security is enabled on the table with EnableRowLevelSecurity, and none on the table's owner unless forced.

func (*CreatePolicyStatement) Build

func (x *CreatePolicyStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreatePolicyStatement) For

For limits the policy to one command.

func (*CreatePolicyStatement) Permissive

Permissive makes the policy one of those any of which may grant a row, the default.

func (*CreatePolicyStatement) Restrictive

func (x *CreatePolicyStatement) Restrictive() *CreatePolicyStatement

Restrictive makes the policy one every row must also pass.

func (*CreatePolicyStatement) To

To names who the policy applies to, a declared Role or one of the keyword roles; PUBLIC when not given.

func (*CreatePolicyStatement) Using

Using is which existing rows the policy shows or lets a command change.

func (*CreatePolicyStatement) WithCheck

WithCheck is which new rows an INSERT or UPDATE may write.

type CreateRangeTypeStatement

type CreateRangeTypeStatement[T any] struct {
	// contains filtered or unexported fields
}

CreateRangeTypeStatement is CREATE TYPE ... AS RANGE.

func CreateRangeType

func CreateRangeType[T any](r RangeType[T], subtype ddl.SQLType[T]) *CreateRangeTypeStatement[T]

CreateRangeType creates a range type over subtype, the SQL type of the values the range bounds. Postgres has no IF NOT EXISTS for CREATE TYPE, so wrap it in Guarded to make it safe to run twice.

Postgres derives a multirange type beside it, named after this one unless MultirangeTypeName says otherwise, and works out the default operator class and collation from the subtype; a subtype with no default b-tree operator class is the one case SubtypeOpClass is required.

func (*CreateRangeTypeStatement[T]) Build

func (x *CreateRangeTypeStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateRangeTypeStatement[T]) Canonical

Canonical names a function that puts every equal range in one form, which a range over a discrete type needs: without it [1,2] and [1,3) are two values the server cannot tell are the same. The function takes and returns the range type, so it can only be written after this statement has run, which is why it is usually added with a second pass rather than declared here.

func (*CreateRangeTypeStatement[T]) Collation

Collation names the collation the range's ordering uses, for a subtype whose ordering depends on one.

func (*CreateRangeTypeStatement[T]) MultirangeTypeName

func (x *CreateRangeTypeStatement[T]) MultirangeTypeName(name string) *CreateRangeTypeStatement[T]

MultirangeTypeName names the multirange type Postgres creates beside this one, rather than letting it derive the name.

func (*CreateRangeTypeStatement[T]) SubtypeDiff

SubtypeDiff names a function returning the distance between two subtype values as a float8, which is what lets the planner estimate selectivity over the range and what a GiST index uses to split a page well.

func (*CreateRangeTypeStatement[T]) SubtypeOpClass

func (x *CreateRangeTypeStatement[T]) SubtypeOpClass(o OpClass[T]) *CreateRangeTypeStatement[T]

SubtypeOpClass names the b-tree operator class that orders the subtype, which is what decides which values a range contains. It is required for a subtype with no default class, and is how a range is ordered by something other than the subtype's usual ordering.

type CreateRoutineStatement

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

CreateRoutineStatement is CREATE FUNCTION for a function that is not a trigger function: a signature, what it returns, a language and a body.

It is a separate type from CreateFunctionStatement, which is the trigger form, because the two have almost nothing in common: a trigger function's result, language and signature are all fixed, and every option here would be a method that could not be written on it.

func CreateCFunction

func CreateCFunction(f Function, objFile, linkSymbol string) *CreateRoutineStatement

CreateCFunction creates a function implemented by linkSymbol in the shared object objFile, the two-string form of CREATE FUNCTION. It is how an extension's own C functions are declared, and it needs a superuser.

func CreateFunction

func CreateFunction(f Function, lang Language, body string) *CreateRoutineStatement

CreateFunction creates a function whose body is written in lang. The body is not checked, parsed or built here: it is another language, the library author writes it, and the server is what reports a body that does not compile.

Postgres has no CREATE FUNCTION IF NOT EXISTS, so OrReplace is the form that is safe to run on every boot; unlike a guarded create it also updates the body, which is what a function's migration usually is.

func (*CreateRoutineStatement) Build

func (x *CreateRoutineStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateRoutineStatement) Cost

Cost is the planner's estimated execution cost in cpu_operator_cost units, which decides whether the function is called before or after a cheaper filter.

func (*CreateRoutineStatement) Leakproof

Leakproof promises the function reveals nothing about its arguments beyond its result, not through an error message and not through timing, which is what lets the planner push it below a security barrier or an RLS policy. A wrong promise here is an information leak, so it needs a superuser.

func (*CreateRoutineStatement) NullInput

NullInput declares what a NULL argument does.

func (*CreateRoutineStatement) OrReplace

OrReplace replaces an existing function of the same name and argument types, keeping its privileges; it cannot change the name, the argument types or the result type, which Postgres refuses.

func (*CreateRoutineStatement) Parallel

Parallel declares whether the function may run in a parallel plan.

func (*CreateRoutineStatement) Returns

Returns says what the function returns. A function with an output parameter needs no result type and may not have both a table result and one.

func (*CreateRoutineStatement) Rows

Rows is the planner's estimate of how many rows a set-returning function returns. It is meaningless on a function that returns one value, which Postgres refuses.

func (*CreateRoutineStatement) Security

Security declares whose privileges the body runs with.

func (*CreateRoutineStatement) Set

Set pins a configuration parameter for the duration of a call, the setting a Definer function must carry: without a pinned search_path a caller can put a table of their own ahead of the library's and have the body find it.

func (*CreateRoutineStatement) SetFromCurrent

func (x *CreateRoutineStatement) SetFromCurrent(name string) *CreateRoutineStatement

SetFromCurrent pins a configuration parameter to the value it has where the statement runs, which is the form a migration uses when the right value is the deployment's rather than the library's.

func (*CreateRoutineStatement) Support

Support names a planner support function, a C function the planner calls to estimate this one's selectivity or to rewrite a call into something cheaper.

func (*CreateRoutineStatement) Transform

func (x *CreateRoutineStatement) Transform(first TypeRef, more ...TypeRef) *CreateRoutineStatement

Transform names a type whose transform this function uses, which is how a procedural language sees a Postgres type as one of its own rather than as text.

func (*CreateRoutineStatement) Volatility

Volatility declares what the planner may assume about the function, which is what decides whether it can be used in an index expression or folded away. Without it Postgres assumes the weakest, Volatile.

func (*CreateRoutineStatement) Window

Window declares the function a window function, which only a C function can be: the implementation reads its frame through the server's window API and there is no procedural-language equivalent.

type CreateSchemaStatement

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

CreateSchemaStatement is CREATE SCHEMA.

func CreateSchema

func CreateSchema(s Schema) *CreateSchemaStatement

CreateSchema creates a schema.

func (*CreateSchemaStatement) Authorization

Authorization gives the new schema to a role, which is the form a library's installer runs when the role creating the schema is not the role that will own it. Postgres also allows the schema's name to be omitted so it takes the role's, which is not offered: a schema whose name is not in the declaration is a schema no Table value can name.

func (*CreateSchemaStatement) Build

func (x *CreateSchemaStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateSchemaStatement) IfNotExists

func (x *CreateSchemaStatement) IfNotExists() *CreateSchemaStatement

IfNotExists makes creating an existing schema a no-op.

type CreateSequenceStatement

type CreateSequenceStatement[T sequenceInteger] struct {
	// contains filtered or unexported fields
}

CreateSequenceStatement is CREATE SEQUENCE.

func CreateSequence

func CreateSequence[T sequenceInteger](s Sequence[T]) *CreateSequenceStatement[T]

CreateSequence creates a sequence of T, written AS its SQL integer type.

func (*CreateSequenceStatement[T]) Build

func (x *CreateSequenceStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateSequenceStatement[T]) Cache

Cache preallocates n values per session: faster, and leaves gaps when a session ends, which a sequence may always do.

func (*CreateSequenceStatement[T]) Cycle

Cycle starts the sequence again at its minimum when it runs out. On a key column that means the next value collides with a row that is still there, which is why it is off by default and why it is worth writing out where it is wanted.

func (*CreateSequenceStatement[T]) IfNotExists

func (x *CreateSequenceStatement[T]) IfNotExists() *CreateSequenceStatement[T]

IfNotExists makes creating an existing sequence a no-op.

func (*CreateSequenceStatement[T]) IncrementBy

func (x *CreateSequenceStatement[T]) IncrementBy(n T) *CreateSequenceStatement[T]

IncrementBy sets the step, 1 by default; negative counts down.

func (*CreateSequenceStatement[T]) MaxValue

func (x *CreateSequenceStatement[T]) MaxValue(n T) *CreateSequenceStatement[T]

MaxValue sets the highest value; the sequence fails when it passes it.

func (*CreateSequenceStatement[T]) MinValue

func (x *CreateSequenceStatement[T]) MinValue(n T) *CreateSequenceStatement[T]

MinValue sets the lowest value.

func (*CreateSequenceStatement[T]) NoCycle

NoCycle fails when the sequence runs out, the default.

func (*CreateSequenceStatement[T]) NoMaxValue

func (x *CreateSequenceStatement[T]) NoMaxValue() *CreateSequenceStatement[T]

NoMaxValue leaves the upper bound at the type's own, the default, written out.

func (*CreateSequenceStatement[T]) NoMinValue

func (x *CreateSequenceStatement[T]) NoMinValue() *CreateSequenceStatement[T]

NoMinValue leaves the lower bound at the type's own, the default, written out.

func (*CreateSequenceStatement[T]) OwnedBy

func (x *CreateSequenceStatement[T]) OwnedBy(col sqlb.Expr[T]) *CreateSequenceStatement[T]

OwnedBy ties the sequence to a column, so dropping the column or its table drops the sequence. It is what a declared sequence backing a column should almost always carry, and the reason it is not the default is that a sequence shared by two tables must not have it.

func (*CreateSequenceStatement[T]) OwnedByNone

func (x *CreateSequenceStatement[T]) OwnedByNone() *CreateSequenceStatement[T]

OwnedByNone leaves the sequence standing on its own, the default, written out.

func (*CreateSequenceStatement[T]) Start

func (x *CreateSequenceStatement[T]) Start(n T) *CreateSequenceStatement[T]

Start sets the first value.

func (*CreateSequenceStatement[T]) Temporary

func (x *CreateSequenceStatement[T]) Temporary() *CreateSequenceStatement[T]

Temporary makes the sequence live in the session's temporary schema and vanish when the session ends.

func (*CreateSequenceStatement[T]) Unlogged

func (x *CreateSequenceStatement[T]) Unlogged() *CreateSequenceStatement[T]

Unlogged keeps the sequence out of the write-ahead log, which is faster and resets it to its start value after a crash. A logged table's identity column may not use one.

type CreateShellTypeStatement

type CreateShellTypeStatement[T any] struct {
	// contains filtered or unexported fields
}

CreateShellTypeStatement is CREATE TYPE with nothing after the name.

func CreateShellType

func CreateShellType[T any](b BaseType[T]) *CreateShellTypeStatement[T]

CreateShellType declares the name of a base type before the type itself exists. It is not optional and it is not a convenience: a base type's input function takes a cstring and returns the type, and its output function takes the type, so neither can be created until the name exists, and the name cannot be created with its functions because they do not exist yet. The shell breaks the cycle, and CreateBaseType then fills it in.

func (*CreateShellTypeStatement[T]) Build

func (x *CreateShellTypeStatement[T]) Build() (ddl.Script, error)

Build renders the statement.

type CreateStatisticsStatement

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

CreateStatisticsStatement is CREATE STATISTICS.

func CreateStatistics

func CreateStatistics(s Statistics, t sqlb.Table, a, b ddl.ColumnRef, more ...ddl.ColumnRef) *CreateStatisticsStatement

CreateStatistics creates statistics over at least two columns of t, which is the fewest Postgres accepts, so fewer does not compile.

func CreateStatisticsExpr

func CreateStatisticsExpr(s Statistics, t sqlb.Table, e sqlb.SQLer) *CreateStatisticsStatement

CreateStatisticsExpr creates statistics for one expression, the form that takes a single element and no kinds. It exists beside CreateStatistics because Postgres's grammar separates them: two elements or more measure how the elements depend on each other, and one expression measures the expression's own distribution.

func (*CreateStatisticsStatement) Build

func (x *CreateStatisticsStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateStatisticsStatement) Expression

Expression adds an expression as one of the statistics object's elements, beside its columns. The planner keeps statistics for the expression itself, which is what makes a WHERE on lower(email) estimable rather than guessed.

func (*CreateStatisticsStatement) IfNotExists

IfNotExists makes creating existing statistics a no-op.

func (*CreateStatisticsStatement) Kinds

Kinds limits what is measured; all kinds when not given.

type CreateTableAsStatement

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

CreateTableAsStatement is CREATE TABLE ... AS, which makes a table and fills it from a query in one statement.

func CreateTableAs

func CreateTableAs(t sqlb.Table, body *SelectQuery) *CreateTableAsStatement

CreateTableAs makes a table whose columns come from a query's select list and fills it with that query's rows. It is a statement of its own rather than a form of CreateTable because the two declare their columns in different places: CreateTable takes Col values the queries also use, and this takes none at all, so nothing here can be checked against a declaration. That is the trade, and the reason to reach for it is the case where there is nothing to declare — a summary table rebuilt from a query that is already written.

It was classified as the operator's until 2026-09-24, on the reading that a table without a declaration is not a library's. SQLite and MySQL both build it, which made the reading a difference between engines rather than a decision, and this is the statement a library rebuilding its own derived table writes.

func (*CreateTableAsStatement) Build

func (x *CreateTableAsStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateTableAsStatement) Columns

func (x *CreateTableAsStatement) Columns(first string, more ...string) *CreateTableAsStatement

Columns names the new table's columns rather than taking the names the query's select list produces.

func (*CreateTableAsStatement) IfNotExists

IfNotExists makes creating an existing table a no-op, and on this form that means the query does not run either: the table keeps the rows it had and nothing is appended.

func (*CreateTableAsStatement) OnCommit

OnCommit says what happens to a temporary table's rows at commit.

func (*CreateTableAsStatement) Temporary

Temporary makes the table live in the session's temporary schema.

func (*CreateTableAsStatement) Unlogged

Unlogged keeps the table out of the write-ahead log, which is faster and loses the table's contents after a crash. It is what a table rebuilt from a query on every boot should be.

func (*CreateTableAsStatement) Using

Using stores the new table's rows in another access method.

func (*CreateTableAsStatement) WithNoData

WithNoData creates the table with the query's column types and none of its rows, which is how the shape is made now and filled later.

func (*CreateTableAsStatement) WithStorage

WithStorage sets the new table's storage parameters.

type CreateTableLikeStatement

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

CreateTableLikeStatement is CREATE TABLE t (LIKE src ...).

func CreateTableLike

func CreateTableLike(t, src sqlb.Table, opts ...LikeOption) *CreateTableLikeStatement

CreateTableLike creates t with src's columns, and whatever of src the options name. It is its own statement because it has no column list of its own, which CreateTable's typestate requires; an archive or staging table is what it is for.

func (*CreateTableLikeStatement) Build

func (x *CreateTableLikeStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateTableLikeStatement) IfNotExists

IfNotExists makes creating an existing table a no-op.

type CreateTableQuery

type CreateTableQuery = ddl.CreateTable[Dialect]

CreateTableQuery is a CREATE TABLE with no column yet, which has no Build.

func CreateTable

func CreateTable(t sqlb.Table) *CreateTableQuery

CreateTable starts a CREATE TABLE of t for Postgres.

type CreateTableReady

type CreateTableReady = ddl.CreateTableReady[Dialect]

CreateTableReady is a CREATE TABLE with at least one column, the only form with Build.

type CreateTriggerQuery

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

CreateTriggerQuery is CREATE TRIGGER with no timing yet, which has no Build.

func CreateTrigger

func CreateTrigger(tr Trigger) *CreateTriggerQuery

CreateTrigger starts a trigger.

func (*CreateTriggerQuery) After

After fires the trigger after the change.

func (*CreateTriggerQuery) Before

Before fires the trigger before the change, where a row trigger can modify NEW or return NULL to skip the row.

func (*CreateTriggerQuery) Constraint

func (x *CreateTriggerQuery) Constraint() *CreateTriggerQuery

Constraint makes the trigger a constraint trigger, which can be deferred to the end of the transaction with Deferrable. It is how a rule that spans several rows is enforced without refusing each intermediate state: a check that runs at commit sees the finished work rather than the half of it the first statement wrote.

func (*CreateTriggerQuery) InsteadOf

func (x *CreateTriggerQuery) InsteadOf(first TriggerEvent, more ...TriggerEvent) *TimedTriggerQuery

InsteadOf replaces the statement on a view with the trigger's own work, which is how a view that Postgres cannot update automatically is made writable. It is a row trigger on a view and nothing else, which the server checks.

func (*CreateTriggerQuery) OrReplace

func (x *CreateTriggerQuery) OrReplace() *CreateTriggerQuery

OrReplace replaces an existing trigger of the name on the table, the idempotent form since Postgres 14.

type CreateTriggerStatement

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

CreateTriggerStatement is a complete CREATE TRIGGER.

func (*CreateTriggerStatement) Build

func (x *CreateTriggerStatement) Build() (ddl.Script, error)

Build renders the statement.

type CreateViewQuery

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

CreateViewQuery is CREATE VIEW with no body yet, which has no Build.

func CreateView

func CreateView(v View) *CreateViewQuery

CreateView starts a view.

func (*CreateViewQuery) As

As gives the view's body, a Postgres SELECT built with the query builder, so a view is typed like any other query. Its bound values become literals.

func (*CreateViewQuery) OrReplace

func (x *CreateViewQuery) OrReplace() *CreateViewQuery

OrReplace replaces an existing view of the name, which Postgres allows only when the new body keeps every existing column, in order, with its type. It is the idempotent form: Postgres has no CREATE VIEW IF NOT EXISTS.

type CreateViewStatement

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

CreateViewStatement is a complete CREATE VIEW.

func (*CreateViewStatement) Build

func (x *CreateViewStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*CreateViewStatement) Columns

func (x *CreateViewStatement) Columns(first string, more ...string) *CreateViewStatement

Columns names the view's output columns, rather than taking the names its body's select list happens to produce. It is what makes a view's interface a declaration: the body can then be rewritten with OrReplace without the column names moving under a caller.

func (*CreateViewStatement) OrReplace

func (x *CreateViewStatement) OrReplace() *CreateViewStatement

OrReplace replaces an existing view of the name.

func (*CreateViewStatement) Recursive

func (x *CreateViewStatement) Recursive() *CreateViewStatement

Recursive makes the view refer to itself, the form whose body is a UNION of a seed and a step that selects from the view. Postgres requires the column list, which is why Build refuses a recursive view without one: the recursive reference needs names before the body has produced any.

func (*CreateViewStatement) Temporary

func (x *CreateViewStatement) Temporary() *CreateViewStatement

Temporary makes the view live in the session's temporary schema.

func (*CreateViewStatement) WithCheckOption

func (x *CreateViewStatement) WithCheckOption(o CheckOption) *CreateViewStatement

WithCheckOption refuses a write through the view that the view would not show.

func (*CreateViewStatement) WithOptions

func (x *CreateViewStatement) WithOptions(first ViewSetting, more ...ViewSetting) *CreateViewStatement

WithOptions sets the view's options at creation, which is the difference between a view that is security-invoker from its first moment and one that is created and then altered. A library shipping a view over its own row-level-secured tables wants SecurityInvoker on, and the window between the two statements is a window in which it is off.

type DateField

type DateField string

DateField names the field for Extract and DateTrunc. A closed set, so a typo is a compile error.

const (
	FieldIsoDow         DateField = "isodow"
	FieldIsoYear        DateField = "isoyear"
	FieldTimezone       DateField = "timezone"
	FieldMillennium     DateField = "millennium"
	FieldMicroseconds   DateField = "microseconds"
	FieldMilliseconds   DateField = "milliseconds"
	FieldDecade         DateField = "decade"
	FieldCentury        DateField = "century"
	FieldTimezoneHour   DateField = "timezone_hour"
	FieldTimezoneMinute DateField = "timezone_minute"
	FieldJulian         DateField = "julian"
)

More date fields.

The seven after the first four were missing until 2026-09-24, when a closed check made the absence matter: extract takes twenty-two units on Postgres 17, measured one at a time, and this package named fifteen. A list that validates has to be complete, which is the cost of choosing a list over a shape; TestTask_EveryDateFieldIsAcceptedByTheServer is what keeps it so.

const (
	FieldYear    DateField = "year"
	FieldQuarter DateField = "quarter"
	FieldMonth   DateField = "month"
	FieldWeek    DateField = "week"
	FieldDay     DateField = "day"
	FieldHour    DateField = "hour"
	FieldMinute  DateField = "minute"
	FieldSecond  DateField = "second"
	FieldDow     DateField = "dow"
	FieldDoy     DateField = "doy"
	FieldEpoch   DateField = "epoch"
)

Every field date_trunc and extract accept. A named type rather than a string, so a typo is a compile error and not a run-time surprise.

type Deferral

type Deferral int

Deferral is when a deferrable constraint is checked.

const (
	InitiallyImmediate Deferral = iota + 1
	InitiallyDeferred
)

The deferrals. InitiallyDeferred checks at COMMIT, which is what lets a transaction insert two rows that reference each other in either order.

type DeleteClause

type DeleteClause = sqlb.Clause[Dialect, sqlb.DeleteKind]

DeleteClause is a clause for a DELETE on this engine.

func DeleteUsing

func DeleteUsing(srcs ...sqlb.Source) DeleteClause

DeleteUsing renders DELETE FROM t USING sources.

type DeleteQuery

type DeleteQuery = sqlb.Delete[Dialect]

DeleteQuery is the statement Delete returns, with no Build until Where or All.

func Delete

func Delete(t sqlb.Table) *DeleteQuery

Delete starts a DELETE from t for Postgres.

type Dependable

type Dependable interface {
	// contains filtered or unexported methods
}

Dependable is an object that can be made to depend on an extension. The set is Postgres's: an index, a trigger, a materialized view and a function, the objects an extension's script creates but does not own. It is not the same set as ExtensionMember, which is why it is its own interface.

type DependsOnExtensionStatement

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

DependsOnExtensionStatement is the [NO] DEPENDS ON EXTENSION form, which says an object is dropped with an extension without being a member of it.

func DependsOnExtension

func DependsOnExtension(o Dependable, e Extension) *DependsOnExtensionStatement

DependsOnExtension makes an object depend on an extension, so that dropping the extension drops the object too. It is the weaker half of extension membership and the answer for the objects that cannot be members: an index and a statistics object are refused by ALTER EXTENSION ADD, and an index created by an extension's script is tied to it this way instead.

func NoDependsOnExtension

func NoDependsOnExtension(o Dependable, e Extension) *DependsOnExtensionStatement

NoDependsOnExtension breaks that tie, leaving the object in place when the extension is dropped.

func (*DependsOnExtensionStatement) Build

Build renders the statement.

type DetachStatement

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

DetachStatement is ALTER TABLE ... DETACH PARTITION, its own builder because CONCURRENTLY makes it non-transactional, which an ALTER TABLE action cannot say.

func DetachPartition

func DetachPartition(parent, child sqlb.Table) *DetachStatement

DetachPartition detaches child from parent, leaving it an ordinary table.

func (*DetachStatement) Build

func (x *DetachStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DetachStatement) Concurrently

func (x *DetachStatement) Concurrently() *DetachStatement

Concurrently detaches without blocking queries on the parent. Postgres refuses it inside a transaction and while a default partition exists, so the Statement is non-transactional.

func (*DetachStatement) Finalize

func (x *DetachStatement) Finalize() *DetachStatement

Finalize completes a concurrent detach that was interrupted.

type Dialect

type Dialect = postgres.Dialect

Dialect is the Postgres dialect, re-exported so a caller that already imports this package for its constructs does not need a second import to name the engine. The definition lives in github.com/ubgo/sqlb/dialect/postgres, which imports the render layer and nothing else.

type Domain

type Domain[T any] struct{ Schema, Name string }

Domain is a Postgres domain: a base type with constraints, whose values are T, so it is a ddl.SQLType[T] and a column of another Go type cannot use it.

func (Domain[T]) Spelling

func (d Domain[T]) Spelling(dl sqlb.Dialect) (string, error)

Spelling is the domain's qualified name, as a column definition writes it.

func (Domain[T]) TypeOf

func (Domain[T]) TypeOf(T)

TypeOf types the domain to T for ddl.SQLType.

type DomainCheck

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

DomainCheck is one named CHECK of a domain.

type DomainConstraint

type DomainConstraint[T any] struct {
	Domain Domain[T]
	Name   string
}

DomainConstraint is a named constraint of one domain, declared once, the domain's counterpart of TableConstraint: CreateDomain's Check, and AlterDomain's AddConstraint, ValidateConstraint and DropConstraint all take it and refuse one declared on another domain.

type DropClause

type DropClause = ddl.DropClause[Dialect]

DropClause is a Postgres option after DROP TABLE's table name.

func Cascade

func Cascade() DropClause

Cascade makes DROP TABLE also drop what depends on the table: views and the foreign keys of other tables, never the other tables themselves.

type DropColumnClause

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

DropColumnClause is DROP COLUMN IF EXISTS, optionally with CASCADE.

func DropColumnIfExists

func DropColumnIfExists[T any](col sqlb.Expr[T]) DropColumnClause

DropColumnIfExists drops a column if it exists, so an uninstall or a second run of a migration is not an error.

func (DropColumnClause) AlterClauseOf

func (DropColumnClause) AlterClauseOf(Dialect)

func (DropColumnClause) Cascade

func (x DropColumnClause) Cascade() DropColumnClause

Cascade also drops what depends on the column: an index, a view, a constraint of another table.

func (DropColumnClause) ClauseTable

func (x DropColumnClause) ClauseTable() sqlb.Table

ClauseTable is the table the action names, for ALTER TABLE's check.

func (DropColumnClause) NamedColumns

func (x DropColumnClause) NamedColumns() []ddl.ColumnRef

func (DropColumnClause) Standalone

func (x DropColumnClause) Standalone() bool

func (DropColumnClause) WriteSQL

func (x DropColumnClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type DropColumnPartClause

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

DropColumnPartClause is an ALTER COLUMN action that removes something a column carries and takes IF EXISTS: DROP EXPRESSION and DROP IDENTITY. Both keep the column and the values already in it, and both are one-way, so IF EXISTS is what makes the migration safe to run twice.

func DropExpression

func DropExpression[T any](col sqlb.Expr[T]) DropColumnPartClause

DropExpression turns a generated column into a plain one, keeping the values it holds; from then on the column is written like any other.

func DropIdentity

func DropIdentity[T identityInteger](col sqlb.Expr[T]) DropColumnPartClause

DropIdentity stops a column generating values, keeping those it holds and dropping the sequence behind it. It is the inverse of AddIdentity.

func (DropColumnPartClause) AlterClauseOf

func (DropColumnPartClause) AlterClauseOf(Dialect)

AlterClauseOf marks the action as Postgres's.

func (DropColumnPartClause) ClauseTable

func (x DropColumnPartClause) ClauseTable() sqlb.Table

ClauseTable is the table the action names, for ALTER TABLE's check.

func (DropColumnPartClause) IfExists

IfExists makes the action a no-op on a column that carries nothing to drop, so a migration re-run is not an error.

func (DropColumnPartClause) NamedColumns

func (x DropColumnPartClause) NamedColumns() []ddl.ColumnRef

func (DropColumnPartClause) Standalone

func (DropColumnPartClause) Standalone() bool

Standalone reports that the action may share a statement.

func (DropColumnPartClause) WriteSQL

func (x DropColumnPartClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type DropConstraintClause

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

DropConstraintClause is DROP CONSTRAINT, optionally IF EXISTS and CASCADE.

func DropConstraint

func DropConstraint(c TableConstraint) DropConstraintClause

DropConstraint drops a declared constraint. ALTER TABLE refuses one of another table.

func (DropConstraintClause) AlterClauseOf

func (DropConstraintClause) AlterClauseOf(Dialect)

AlterClauseOf marks the action as Postgres's.

func (DropConstraintClause) Cascade

Cascade also drops what depends on the constraint, a foreign key of another table referencing this unique key.

func (DropConstraintClause) ClauseTable

func (x DropConstraintClause) ClauseTable() sqlb.Table

ClauseTable is the constraint's table, for ALTER TABLE's check.

func (DropConstraintClause) IfExists

IfExists makes dropping a missing constraint a no-op.

func (DropConstraintClause) Standalone

func (DropConstraintClause) Standalone() bool

Standalone reports that the action may share a statement.

func (DropConstraintClause) WriteSQL

func (x DropConstraintClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type DropExtensionStatement

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

DropExtensionStatement is DROP EXTENSION.

func DropExtension

func DropExtension(e Extension) *DropExtensionStatement

DropExtension removes an extension, which fails while a column uses one of its types unless Cascade is given.

func (*DropExtensionStatement) Build

func (x *DropExtensionStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DropExtensionStatement) Cascade

Cascade also drops what uses the extension, columns included.

func (*DropExtensionStatement) IfExists

IfExists makes removing a missing extension a no-op.

type DropIndexStatement

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

DropIndexStatement is DROP INDEX.

func DropIndex

func DropIndex(first Index, more ...Index) *DropIndexStatement

DropIndex drops one or more indexes, one statement each, since DROP INDEX CONCURRENTLY takes one index.

func (*DropIndexStatement) Build

func (x *DropIndexStatement) Build() (ddl.Script, error)

Build renders one statement per index.

func (*DropIndexStatement) Cascade

func (x *DropIndexStatement) Cascade() *DropIndexStatement

Cascade also drops what depends on the index, a constraint using it.

func (*DropIndexStatement) Concurrently

func (x *DropIndexStatement) Concurrently() *DropIndexStatement

Concurrently drops without blocking reads and writes; not in a transaction.

func (*DropIndexStatement) IfExists

func (x *DropIndexStatement) IfExists() *DropIndexStatement

IfExists makes dropping a missing index a no-op.

type DropObjectStatement

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

DropObjectStatement is DROP SEQUENCE, DROP VIEW, DROP MATERIALIZED VIEW or DROP FUNCTION: one object, with IF EXISTS and CASCADE.

func DropCollation

func DropCollation(c Collation) *DropObjectStatement

DropCollation drops a collation.

func DropComposite

func DropComposite[T any](c Composite[T]) *DropObjectStatement

DropComposite drops a composite type, which fails while a column uses it unless Cascade is given.

func DropDomain

func DropDomain[T any](d Domain[T]) *DropObjectStatement

DropDomain drops a domain, which fails while a column uses it unless Cascade is given.

func DropFunction

func DropFunction(f Function) *DropObjectStatement

DropFunction drops a function, naming it by the signature its declaration carries, which is what tells two functions of one name apart. It fails while a trigger or another function uses it unless Cascade is given.

func DropMaterializedView

func DropMaterializedView(v MaterializedView) *DropObjectStatement

DropMaterializedView drops a materialized view.

func DropSequence

func DropSequence[T sequenceInteger](s Sequence[T]) *DropObjectStatement

DropSequence drops a sequence, which fails while a default uses it unless Cascade is given.

func DropStatistics

func DropStatistics(s Statistics) *DropObjectStatement

DropStatistics drops a statistics object.

func DropView

func DropView(v View) *DropObjectStatement

DropView drops a view.

func (*DropObjectStatement) Build

func (x *DropObjectStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DropObjectStatement) Cascade

Cascade also drops what depends on the object.

func (*DropObjectStatement) IfExists

IfExists makes dropping a missing object a no-op.

func (*DropObjectStatement) Restrict

Restrict refuses the drop while anything depends on the object, which is what Postgres does anyway when Cascade is not given. It is here because the keyword written out is a statement of intent a reader can see, where its absence is indistinguishable from not having thought about it.

type DropPolicyStatement

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

DropPolicyStatement is DROP POLICY ... ON.

func DropPolicy

func DropPolicy(p Policy) *DropPolicyStatement

DropPolicy drops a policy from its table.

func (*DropPolicyStatement) Build

func (x *DropPolicyStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DropPolicyStatement) Cascade

Cascade also drops what depends on the policy.

func (*DropPolicyStatement) IfExists

IfExists makes dropping a missing policy a no-op.

func (*DropPolicyStatement) Restrict

Restrict refuses the drop while anything depends on the policy, the default written out.

type DropSchemaStatement

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

DropSchemaStatement is DROP SCHEMA.

func DropSchema

func DropSchema(s Schema) *DropSchemaStatement

DropSchema drops a schema, which fails while it holds anything unless Cascade is given.

func (*DropSchemaStatement) Build

func (x *DropSchemaStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DropSchemaStatement) Cascade

Cascade also drops everything in the schema.

func (*DropSchemaStatement) IfExists

IfExists makes dropping a missing schema a no-op.

type DropTableQuery

type DropTableQuery = ddl.DropTable[Dialect]

DropTableQuery is a DROP TABLE, complete from its constructor.

func DropTable

func DropTable(first sqlb.Table, more ...sqlb.Table) *DropTableQuery

DropTable drops one or more tables for Postgres, one statement per table.

type DropTriggerStatement

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

DropTriggerStatement is DROP TRIGGER ... ON.

func DropTrigger

func DropTrigger(tr Trigger) *DropTriggerStatement

DropTrigger drops a trigger from its table.

func (*DropTriggerStatement) Build

func (x *DropTriggerStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DropTriggerStatement) Cascade

Cascade also drops what depends on the trigger.

func (*DropTriggerStatement) IfExists

IfExists makes dropping a missing trigger a no-op; the table must exist.

func (*DropTriggerStatement) Restrict

Restrict refuses the drop while anything depends on the trigger, the default written out.

type DropTypeStatement

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

DropTypeStatement is DROP TYPE.

func DropType

func DropType[T ~string](e Enum[T]) *DropTypeStatement

DropType drops an enum, which fails while a column uses it unless Cascade is given.

func (*DropTypeStatement) Build

func (x *DropTypeStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*DropTypeStatement) Cascade

func (x *DropTypeStatement) Cascade() *DropTypeStatement

Cascade also drops the columns that use the type.

func (*DropTypeStatement) IfExists

func (x *DropTypeStatement) IfExists() *DropTypeStatement

IfExists makes dropping a missing type a no-op.

type Enum

type Enum[T ~string] struct{ Schema, Name string }

Enum is a Postgres enum type whose labels are values of the Go type T, so a typo in a label is a compile error and a column using the type must be a Col[T]. It is also the column's SQL type: ddl.Column(c).As(StatusType).

func (Enum[T]) Spelling

func (e Enum[T]) Spelling(d sqlb.Dialect) (string, error)

Spelling is the type's qualified name, as a column definition writes it.

func (Enum[T]) TypeOf

func (Enum[T]) TypeOf(T)

TypeOf types the enum to T for ddl.SQLType.

type ExcludeClause

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

ExcludeClause is an EXCLUDE table constraint.

func Exclude

Exclude makes a named exclusion constraint: no two rows may have every element's operator true at once. It is backed by an index of method m, usually pg.GiST. It is the constraint a UNIQUE cannot express, a room booked for two overlapping time ranges.

func (ExcludeClause) ClauseTable

func (x ExcludeClause) ClauseTable() sqlb.Table

ClauseTable is the constraint's declared table.

func (ExcludeClause) Include

func (x ExcludeClause) Include(first ddl.ColumnRef, more ...ddl.ColumnRef) ExcludeClause

Include adds covering columns to the exclusion constraint's index.

func (ExcludeClause) NamedColumns

func (x ExcludeClause) NamedColumns() []ddl.ColumnRef

NamedColumns is the constraint's columns.

func (ExcludeClause) Position

func (ExcludeClause) Position() ddl.Position

Position places the constraint among the table's elements.

func (ExcludeClause) TableClauseOf

func (ExcludeClause) TableClauseOf(Dialect)

TableClauseOf marks the clause as Postgres's.

func (ExcludeClause) Where

Where limits the constraint to rows matching p, cancelled bookings excluded.

func (ExcludeClause) With

With sets the storage parameters of the index behind the constraint.

func (ExcludeClause) WriteSQL

func (x ExcludeClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the constraint.

type ExcludeElement

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

ExcludeElement is one column of an exclusion constraint and its operator.

func ExcludeOn

func ExcludeOn[T any](col sqlb.Expr[T], op ExcludeOp) ExcludeElement

ExcludeOn pairs a column with the operator two rows' values are compared by.

type ExcludeOp

type ExcludeOp string

ExcludeOp is the operator an exclusion constraint compares with: two rows conflict when every element's operator returns true. It is open, as index methods are, because an extension brings its own operators; the ones a library reaches for are named.

const (
	OpOverlaps ExcludeOp = "&&"
	OpEquals   ExcludeOp = "="
	OpAdjacent ExcludeOp = "-|-"
)

The exclusion operators a library uses. OpOverlaps on a range is the no-double-booking constraint; OpEquals on a second column scopes it, which needs the btree_gist extension for a scalar under GiST.

type Extension

type Extension struct{ Name string }

Extension is a Postgres extension. Each extension sub-package exports the one it needs, vector.Extension and trgm.Extension, so a library installs what it uses without spelling the name.

type ExtensionMember

type ExtensionMember interface {
	// contains filtered or unexported methods
}

ExtensionMember is a declared object an extension can own. The kind comes from the Go type, as it does for Commentable, and the set is closed to this package's object values and the one constructor for a table.

An Index and a Statistics are deliberately not members, and this is the one thing in this file measured rather than read: Postgres refuses both with "cannot add an object of this type to an extension", on 17.10, however well formed the statement is. Both were members here for a few hours on 2026-09-24 because the member list in the grammar was skimmed rather than read, and the rendering test passed. An index that an extension's script creates is tied to it with DependsOnExtension instead, which is what that statement is for.

func MemberTable

func MemberTable(t sqlb.Table) ExtensionMember

MemberTable names a table as an extension's member, the one member kind that is not a declared object value of this package: a table is a sqlb.Table.

type ExtensionMemberStatement

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

ExtensionMemberStatement is ALTER EXTENSION ... ADD or DROP one object.

func AddExtensionMember

func AddExtensionMember(e Extension, o ExtensionMember) *ExtensionMemberStatement

AddExtensionMember makes an existing object part of an extension, so that dropping the extension drops the object and a dump writes the extension rather than the object. It is the statement an extension's own upgrade script runs, and the reason it is here is that a library shipping its schema as an extension has no other way to say what the extension contains.

func DropExtensionMember

func DropExtensionMember(e Extension, o ExtensionMember) *ExtensionMemberStatement

DropExtensionMember takes an object back out of an extension, leaving the object in place; it is what an upgrade runs for an object the new version no longer ships.

func (*ExtensionMemberStatement) Build

func (x *ExtensionMemberStatement) Build() (ddl.Script, error)

Build renders the statement.

type FilteredDelete

type FilteredDelete = sqlb.FilteredDelete[Dialect]

FilteredDelete is a DELETE that has said which rows, the only form with Build.

type FilteredUpdate

type FilteredUpdate = sqlb.FilteredUpdate[Dialect]

FilteredUpdate is an UPDATE that has said which rows, the only form with Build.

type ForeignKeyClause

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

ForeignKeyClause is a FOREIGN KEY table constraint.

func ForeignKey

func ForeignKey(c TableConstraint, first ColumnPair, more ...ColumnPair) ForeignKeyClause

ForeignKey makes a named foreign key from one or more pairs, all referencing one table.

func References

func References[T any](local, ref sqlb.Expr[T]) ForeignKeyClause

References is the one-column foreign key, left for Postgres to name.

func (ForeignKeyClause) ClauseTable

func (f ForeignKeyClause) ClauseTable() sqlb.Table

ClauseTable is the constraint's declared table, empty for References.

func (ForeignKeyClause) Deferrable

func (f ForeignKeyClause) Deferrable(d Deferral) ForeignKeyClause

Deferrable makes the constraint deferrable, checked when d says.

func (ForeignKeyClause) DescribeInto

func (f ForeignKeyClause) DescribeInto(t *schema.Table)

DescribeInto adds the foreign key.

func (ForeignKeyClause) Match

Match says how the key treats a partly NULL row. It renders after the referenced columns and before ON DELETE.

func (ForeignKeyClause) NamedColumns

func (f ForeignKeyClause) NamedColumns() []ddl.ColumnRef

NamedColumns is the constraint's local columns; the referenced ones are on another table by definition.

func (ForeignKeyClause) NotEnforced

func (f ForeignKeyClause) NotEnforced() ForeignKeyClause

NotEnforced declares the foreign key without enforcing it, which is how a reference is introduced on data not yet clean: AlterConstraint(...).Enforced() later turns it on and checks every row. Postgres 18 or later.

func (ForeignKeyClause) OnDelete

OnDelete says what happens to this row when the referenced one is deleted.

func (ForeignKeyClause) OnUpdate

OnUpdate says what happens when the referenced key changes.

func (ForeignKeyClause) Period

func (f ForeignKeyClause) Period(local, ref PeriodColumn) ForeignKeyClause

Period makes the foreign key temporal: each row's period must be covered by the union of the referenced rows' periods, over a temporal key of the referenced table. local is this table's range column, ref the referenced table's. Postgres 18 or later.

func (ForeignKeyClause) Position

func (ForeignKeyClause) Position() ddl.Position

Position places the constraint among the table's elements.

func (ForeignKeyClause) TableClauseOf

func (ForeignKeyClause) TableClauseOf(Dialect)

TableClauseOf marks the clause as Postgres's.

func (ForeignKeyClause) WriteSQL

func (f ForeignKeyClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the constraint.

type Function

type Function struct {
	Schema, Name string
	Params       []FunctionArg
}

Function is a Postgres function, declared once as a value and named by every statement that creates, drops, comments on or executes it.

Params is part of the declaration rather than of one statement because a function's argument types are part of its name: Postgres allows several functions to share a bare name, so DROP FUNCTION, COMMENT ON FUNCTION and ALTER EXTENSION each identify one by its signature. Declaring the parameters once is what keeps those statements from having to be told again, and a trigger function simply leaves it empty, which is the one signature Postgres fixes for you.

type FunctionArg

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

FunctionArg is one parameter of a function: a mode, a name and a typed SQL type. The type's Go parameter is checked when the argument is made and erased after, since a function's parameters are of different types, which is what Attribute does for a composite type's fields.

func Arg

func Arg[T any](name string, t ddl.SQLType[T]) FunctionArg

Arg is an input parameter of type t. The name is written out, so the body may use it, and it is part of the signature every other statement naming the function renders.

func InOutArg

func InOutArg[T any](name string, t ddl.SQLType[T]) FunctionArg

InOutArg is a parameter that is both read and returned.

func OutArg

func OutArg[T any](name string, t ddl.SQLType[T]) FunctionArg

OutArg is an output parameter, one of the values the function returns. A function with output parameters and no result type returns a record of them, which is why it needs no Returns.

func VariadicArg

func VariadicArg[T any](name string, t ddl.SQLType[T]) FunctionArg

VariadicArg is the last parameter, an array type whose elements the caller passes one by one.

type FunctionResult

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

FunctionResult is what a function returns: one value of a type, a set of them, or a table of named columns. The Go type is checked by the constructor and erased after, as a FunctionArg's is.

func Returns

func Returns[T any](t ddl.SQLType[T]) FunctionResult

Returns one value of type t.

func ReturnsSetOf

func ReturnsSetOf[T any](t ddl.SQLType[T]) FunctionResult

ReturnsSetOf returns a set of values of type t, which a query reads as rows.

func ReturnsTable

func ReturnsTable(first Attribute, more ...Attribute) FunctionResult

ReturnsTable returns a set of rows of the named columns, the form a query reads as a table without a column definition list at the call site.

type Guardable

type Guardable interface {
	Build() (ddl.Script, error)
	// contains filtered or unexported methods
}

Guardable is a statement Postgres has no IF NOT EXISTS for, which knows the one condition it raises when repeated. The set is closed, so Guarded cannot be handed a statement whose failure it would silently swallow, and each statement names its own condition, so Guarded swallows that and no other.

type GuardedStatement

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

GuardedStatement is a statement wrapped so that running it twice is a no-op.

func Guarded

func Guarded(s Guardable) *GuardedStatement

Guarded makes a create that Postgres cannot write IF NOT EXISTS for safe to repeat, by catching the one condition that statement raises on a second run and nothing else:

DO $sqlb$ BEGIN CREATE TYPE ...; EXCEPTION WHEN duplicate_object THEN NULL; END $sqlb$

Like IF NOT EXISTS it checks the name only: an object of that name with another definition is left as it is. The dollar-quote tag is chosen so the statement cannot contain it.

func (*GuardedStatement) Build

func (x *GuardedStatement) Build() (ddl.Script, error)

Build renders the guarded statement.

type IdentityKind

type IdentityKind int

IdentityKind is whether an identity column refuses an explicit value.

const (
	Always IdentityKind = iota + 1
	ByDefault
)

The identity kinds. Always refuses an INSERT that names the column unless it says OVERRIDING SYSTEM VALUE; ByDefault takes an explicit value.

type IdentitySequenceClause

type IdentitySequenceClause[T identityInteger] struct {
	// contains filtered or unexported fields
}

IdentitySequenceClause is the ALTER COLUMN action that changes the sequence behind an identity column.

func AlterIdentitySequence

func AlterIdentitySequence[T identityInteger](col sqlb.Expr[T]) IdentitySequenceClause[T]

AlterIdentitySequence changes the sequence an identity column draws from, naming it through the column because it has no name of its own that a declaration could hold: Postgres creates it with the column, owns it and drops it with the column, so AlterSequence, which takes a declared pg.Sequence, has nothing to be handed.

Every option is typed to the column's own integer type, so a bound that the column cannot hold does not compile. Restarting the sequence is RestartIdentity, which is its own action because Postgres writes RESTART without the SET each option here carries.

func (IdentitySequenceClause[T]) AlterClauseOf

func (IdentitySequenceClause[T]) AlterClauseOf(Dialect)

AlterClauseOf marks the action as Postgres's.

func (IdentitySequenceClause[T]) Cache

Cache is how many values the server hands a session at once. A cache above one leaves gaps whenever a session ends, which for an identity key is usually fine and is never fine where the key is expected to be dense.

func (IdentitySequenceClause[T]) Cycle

Cycle starts the sequence again at its minimum when it runs out, which for a key column means the next value collides with a row that is still there.

func (IdentitySequenceClause[T]) IncrementBy

func (x IdentitySequenceClause[T]) IncrementBy(n T) IdentitySequenceClause[T]

IncrementBy is how far the sequence moves per value; a negative step counts down.

func (IdentitySequenceClause[T]) MaxValue

func (x IdentitySequenceClause[T]) MaxValue(n T) IdentitySequenceClause[T]

MaxValue is the highest value the sequence may hand out, after which it fails unless Cycle is set.

func (IdentitySequenceClause[T]) MinValue

func (x IdentitySequenceClause[T]) MinValue(n T) IdentitySequenceClause[T]

MinValue is the lowest value the sequence may hand out.

func (IdentitySequenceClause[T]) NamedColumns

func (x IdentitySequenceClause[T]) NamedColumns() []ddl.ColumnRef

NamedColumns is the identity column whose sequence is changed.

func (IdentitySequenceClause[T]) NoCycle

NoCycle fails when the sequence runs out, the default.

func (IdentitySequenceClause[T]) Standalone

func (IdentitySequenceClause[T]) Standalone() bool

Standalone reports that the action may share a statement.

func (IdentitySequenceClause[T]) StartWith

func (x IdentitySequenceClause[T]) StartWith(n T) IdentitySequenceClause[T]

StartWith is the value a later RESTART with no argument goes back to. It does not move the sequence now, which is RestartIdentity's job.

func (IdentitySequenceClause[T]) WriteSQL

func (x IdentitySequenceClause[T]) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type Index

type Index struct{ Schema, Name string }

Index is a Postgres index, declared once as a value and named by every statement that creates, renames, drops or comments on it.

type IndexElement

type IndexElement interface {
	WriteIndexElement(b *strings.Builder, a *sqlb.Args)
	// IndexColumns is the table's columns the element names, which the
	// statement checks belong to the indexed table.
	IndexColumns() []ddl.ColumnRef
}

IndexElement is one key of an index: a column or an expression, with its sort order and operator class. IndexKey and IndexExpr make them.

type IndexKeyElem

type IndexKeyElem[T any] struct {
	// contains filtered or unexported fields
}

IndexKeyElem is a column or expression key.

func IndexExpr

func IndexExpr[T any](e sqlb.Expr[T]) IndexKeyElem[T]

IndexExpr indexes an expression, lower(email) say; a query uses the index only when it filters on the same expression.

func IndexKey

func IndexKey[T any](col sqlb.Expr[T]) IndexKeyElem[T]

IndexKey indexes a column.

func (IndexKeyElem[T]) Asc

func (k IndexKeyElem[T]) Asc() IndexKeyElem[T]

Asc sorts the key ascending, the default, written out.

func (IndexKeyElem[T]) Desc

func (k IndexKeyElem[T]) Desc() IndexKeyElem[T]

Desc sorts the key descending.

func (IndexKeyElem[T]) IndexColumns

func (k IndexKeyElem[T]) IndexColumns() []ddl.ColumnRef

IndexColumns is the column a column key names; an expression key names none that can be checked.

func (IndexKeyElem[T]) NullsFirst

func (k IndexKeyElem[T]) NullsFirst() IndexKeyElem[T]

NullsFirst sorts NULLs first.

func (IndexKeyElem[T]) NullsLast

func (k IndexKeyElem[T]) NullsLast() IndexKeyElem[T]

NullsLast sorts NULLs last.

func (IndexKeyElem[T]) Opclass

func (k IndexKeyElem[T]) Opclass(o OpClass[T]) IndexKeyElem[T]

Opclass gives the key an operator class for its Go type.

func (IndexKeyElem[T]) OpclassWith

func (k IndexKeyElem[T]) OpclassWith(o OpClass[T], first StorageParameter, more ...StorageParameter) IndexKeyElem[T]

OpclassWith gives the key an operator class and the parameters that class takes, which is how an extension's index is tuned: pgvector's HNSW takes its graph parameters here, and nothing else can pass them.

func (IndexKeyElem[T]) WriteIndexElement

func (k IndexKeyElem[T]) WriteIndexElement(b *strings.Builder, a *sqlb.Args)

WriteIndexElement renders the key, its columns bare.

type IndexMethod

type IndexMethod string

IndexMethod is an index access method. It is an open set on purpose: an extension adds one, vector.HNSW, without editing this package.

const (
	BTree  IndexMethod = "btree"
	Hash   IndexMethod = "hash"
	GiST   IndexMethod = "gist"
	SPGiST IndexMethod = "spgist"
	GIN    IndexMethod = "gin"
	BRIN   IndexMethod = "brin"
)

The access methods Postgres ships.

type IndexParam

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

IndexParam is one storage parameter in WITH (...), an extension's tuning knob such as HNSW's m.

func NewIndexParam

func NewIndexParam(name string, value int64) IndexParam

NewIndexParam makes a storage parameter with an integer value, which is what every index parameter a library tunes takes.

type InsertClause

type InsertClause = sqlb.Clause[Dialect, sqlb.InsertKind]

InsertClause is a clause for an INSERT on this engine.

func DefaultValues

func DefaultValues() InsertClause

DefaultValues renders INSERT INTO t DEFAULT VALUES. MySQL and ClickHouse have no such form.

func OverridingSystemValue

func OverridingSystemValue() InsertClause

OverridingSystemValue and OverridingUserValue are INSERT clauses for identity columns.

func OverridingUserValue

func OverridingUserValue() InsertClause

OverridingUserValue renders OVERRIDING USER VALUE, which makes the column take the generated value and ignore the one supplied. The clause a bulk load wants on a GENERATED ALWAYS identity column.

type InsertQuery

type InsertQuery = sqlb.Insert[Dialect]

InsertQuery is the statement Insert returns. It has no Build until a row, a query or a body completes it.

func Insert

func Insert(t sqlb.Table) *InsertQuery

Insert starts an INSERT into t for Postgres.

type InsertReady

type InsertReady = sqlb.InsertReady[Dialect]

InsertReady is a complete INSERT, the only form with Build.

type Interval

type Interval string

Interval is a Postgres interval in its text form, for example "1 day" or "01:30:00". Scanned and valued as text; the driver casts.

type JSON

type JSON[T any] struct{ V T }

JSON is the typed form of a json or jsonb column: it scans into T and values T as JSON, so the Go struct is the schema.

The alternative is json.RawMessage plus a marshal at every use, which puts the shape of the column in each caller instead of in one type.

func (*JSON[T]) Scan

func (j *JSON[T]) Scan(src any) error

Scan unmarshals the column into V. A NULL clears V to its zero value rather than leaving the previous row's, which matters because Each reuses the same destination for every row.

func (JSON[T]) Value

func (j JSON[T]) Value() (driver.Value, error)

Value marshals V. It returns a string rather than bytes: driver.Value permits both, and every driver this package targets accepts the string form for a json or jsonb parameter.

type JSONKind

type JSONKind string

JSONKind is the IS JSON qualifier.

const (
	JSONAny      JSONKind = ""
	JSONAnyValue JSONKind = "VALUE"
	JSONObj      JSONKind = "OBJECT"
	JSONArr      JSONKind = "ARRAY"
	JSONScalar   JSONKind = "SCALAR"
)

The qualifiers IS JSON accepts, measured against the server rather than read: JSONAny, the empty one, tests only that the text parses as JSON at all, and JSONAnyValue is the written-out spelling of the same test, which the grammar also takes. JSONValue, without the Any, is the JSON_VALUE function further down this file and a different thing entirely. The set is closed by Postgres's grammar — no extension adds a qualifier — which is why this one is a list and SampleMethod is not.

type JSONOption

type JSONOption func(*jsonSpec)

JSONOption modifies a SQL/JSON constructor or aggregate (PG16).

func AbsentOnNull

func AbsentOnNull() JSONOption

AbsentOnNull drops null values from the object or array.

func JSONOrderBy

func JSONOrderBy(ts ...sqlb.OrderTerm) JSONOption

JSONOrderBy orders the elements of JSON_ARRAYAGG.

func NullOnNull

func NullOnNull() JSONOption

NullOnNull keeps null values, the default, stated explicitly.

func ReturningJSONB

func ReturningJSONB() JSONOption

ReturningJSONB selects jsonb output; the default is json.

func WithUniqueKeys

func WithUniqueKeys() JSONOption

WithUniqueKeys rejects duplicate keys.

type JSONPair

type JSONPair struct {
	Key   string
	Value sqlb.SQLer
}

JSONPair is one 'key': value of JSON_OBJECT. The key is a bound value.

func Pair

func Pair(key string, value sqlb.SQLer) JSONPair

Pair makes a JSONPair.

type JSONTableColumn

type JSONTableColumn struct {
	Name           string
	Type           string
	Path           string
	Ordinality     bool
	Exists         bool
	DefaultOnEmpty string
	DefaultOnError string
	Nested         *JSONTableNested
}

JSONTableColumn is one column of a JSON_TABLE (PG17). Type and Path are author constants, as the SQL grammar requires literals there. Ordinality makes it a FOR ORDINALITY counter and ignores Type and Path. Nested holds the columns of a NESTED PATH.

type JSONTableNested

type JSONTableNested struct {
	Path    string
	Columns []JSONTableColumn
}

JSONTableNested is a NESTED PATH with its own column list.

type JSONValueOption

type JSONValueOption func(*jsonValueSpec)

JSONValueOption configures JSON_VALUE and JSON_QUERY (PG17).

func DefaultOnEmpty

func DefaultOnEmpty(sql string) JSONValueOption

DefaultOnEmpty and DefaultOnError set the fallbacks. The SQL is written into the statement as is, because the grammar wants a literal expression there and there is no placeholder for one: it is the author's text, never a value from a request. A fallback that is a value belongs in a Param on the other side of the call.

func DefaultOnError

func DefaultOnError(sql string) JSONValueOption

DefaultOnError supplies a value when evaluating the path raises, instead of failing the statement. The SQL is an author constant; the grammar requires a literal here, so it cannot be bound.

func Returning

func Returning(sqlType string) JSONValueOption

Returning sets the RETURNING type of JSON_VALUE. The type name is written into the statement as is, because a type name is not one identifier and cannot be quoted; it is the author's text, never a value from a request.

func WithConditionalWrapper

func WithConditionalWrapper() JSONValueOption

WithConditionalWrapper wraps only when the path matched more than one value. Usually the one you want: single matches stay scalar.

func WithWrapper

func WithWrapper() JSONValueOption

WithWrapper wraps the result in an array always.

The three wrapper options decide what JSON_QUERY does when a path matches more or fewer than one value. Without a wrapper, multiple matches raise.

func WithoutWrapper

func WithoutWrapper() JSONValueOption

WithoutWrapper returns the value bare, and raises when the path matched more than one.

type Language

type Language string

Language is the language a function's body is written in. It is an open set on purpose: a deployment installs a procedural language this package has never heard of, and the name is written as an identifier, so it is one name whatever it holds.

const (
	LangPLpgSQL  Language = "plpgsql"
	LangSQL      Language = "sql"
	LangC        Language = "c"
	LangInternal Language = "internal"
)

The languages a stock Postgres has. LangC and LangInternal name a symbol in a shared object or in the server itself rather than source text, and both need a superuser.

type LikeOption

type LikeOption int

LikeOption is what CREATE TABLE ... (LIKE src) copies besides the columns. There is deliberately no "including everything": LIKE without INCLUDING GENERATED silently turns a generated column into a plain one, so each thing copied is named where a reader sees it.

const (
	IncludingDefaults LikeOption = iota + 1
	IncludingConstraints
	IncludingGenerated
	IncludingIdentity
	IncludingIndexes
	IncludingComments
	IncludingStatistics
	IncludingStorage
	IncludingCompression
)

The things LIKE can copy.

type LockOption

type LockOption func(*lockSpec)

LockOption modifies a row-locking clause.

func NoWait

func NoWait() LockOption

NoWait errors instead of waiting for a locked row.

func Of

func Of(tables ...sqlb.Table) LockOption

Of restricts the lock to the named tables.

func SkipLocked

func SkipLocked() LockOption

SkipLocked skips locked rows: the job-queue idiom, with LIMIT.

type LockTable

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

LockTable builds a LOCK TABLE statement. Every method returns a derived statement and leaves its receiver alone, as the core's builders do.

It is here rather than in the core because the statement is Postgres-shaped: MySQL spells it LOCK TABLES with different modes, SQLite has no table locks at all, and ClickHouse has none either.

Worth knowing before using it, because the API cannot warn you: a table lock is held until the end of the transaction and cannot be released early, and LOCK TABLE outside a transaction is an error. The stronger modes block plain readers, so ACCESS EXCLUSIVE on a busy table is how a deployment stalls. Row locking with ForUpdate is what most callers actually want.

func NewLockTable

func NewLockTable(d Dialect, tables ...sqlb.Table) *LockTable

NewLockTable starts a LOCK TABLE for d. The dialect is typed: the statement is Postgres-shaped, so another engine's dialect does not compile.

func (*LockTable) Build

func (l *LockTable) Build() (sqlb.Query, error)

Build renders the statement, or returns the first error it found.

func (*LockTable) In

func (l *LockTable) In(mode TableLockMode) *LockTable

In sets the lock mode. Omitted, Postgres defaults to ACCESS EXCLUSIVE, which is the strongest and blocks every reader, so naming the mode is almost always right.

func (*LockTable) NoWait

func (l *LockTable) NoWait() *LockTable

NoWait fails immediately rather than waiting when the lock is unavailable.

Usually what a background job wants: waiting on a table lock holds the transaction open, which holds its own locks, which is how a queue of blocked transactions becomes an outage.

func (*LockTable) Table

func (l *LockTable) Table(tables ...sqlb.Table) *LockTable

Table adds a table. Locking several in one statement is not a convenience: it takes the locks in one step, which is how a caller avoids deadlocking against another transaction taking the same locks in the other order.

func (*LockTable) WriteSQL

func (l *LockTable) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the statement into b, satisfying sqlb.Statement. A table is written by its qualified name alone: neither statement accepts an alias, which the rendering test asserted the wrong way until a real server rejected it.

type MatchType

type MatchType int

MatchType is how a composite foreign key treats a row with some columns NULL and some not.

const (
	MatchFull MatchType = iota + 1
	MatchSimple
)

The match types. MatchSimple, the default, allows the reference when any column is NULL; MatchFull allows it only when all are NULL or none is, which is what a key that must be wholly present or wholly absent needs. Postgres parses MatchPartial and refuses to implement it, which is why it is not offered here: a constructor for a form the server rejects is a compile-time promise the server breaks.

type MaterializedView

type MaterializedView struct{ Schema, Name string }

MaterializedView is a Postgres materialized view: a view whose rows are stored, and read stale until refreshed.

type Merge

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

Merge builds a MERGE statement (Postgres 15; BY SOURCE and RETURNING need 17). It is a Statement, so it can be a CTE body.

Every method returns a derived statement and leaves its receiver alone, as the core's builders do, including the WHEN branches: finishing a branch derives from the Merge it started from. Derived statements share one Guard, because RETURNING captures the caller's scan targets and every Query built from the family writes into the same variables; two of them executing at once is the overlap ErrQueryInUse reports.

func NewMerge

func NewMerge(d Dialect) *Merge

NewMerge starts a MERGE for d. The dialect is typed: MERGE is here as a Postgres construct, so another engine's dialect does not compile.

func (*Merge) Build

func (m *Merge) Build() (sqlb.Query, error)

Build renders the MERGE, or returns the first error it found.

func (*Merge) Into

func (m *Merge) Into(t sqlb.Table) *Merge

Into names the target table, the one rows are merged into.

func (*Merge) Returning

func (m *Merge) Returning(bs ...sqlb.Binding) *Merge

Returning adds RETURNING with scan targets (PG17). Pair it with MergeAction to learn which branch each returned row took.

func (*Merge) Using

func (m *Merge) Using(src sqlb.Source, on ...sqlb.Predicate) *Merge

Using sets the source and the ON condition.

func (*Merge) WhenMatched

func (m *Merge) WhenMatched(cond ...sqlb.Predicate) WhenBuilder

WhenMatched starts a branch for rows the ON condition matched. The optional conditions narrow it further, and branches are evaluated in the order they were added, so the first match wins.

func (*Merge) WhenNotMatched

func (m *Merge) WhenNotMatched(cond ...sqlb.Predicate) WhenBuilder

WhenNotMatched starts a branch for source rows with no target row. This is the insert half of an upsert.

func (*Merge) WhenNotMatchedBySource

func (m *Merge) WhenNotMatchedBySource(cond ...sqlb.Predicate) WhenBuilder

WhenNotMatchedBySource starts a branch for target rows with no source row (PG17). It is how a merge deletes rows the source no longer has, which ON CONFLICT cannot express at all.

func (*Merge) WriteSQL

func (m *Merge) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the MERGE into b, satisfying sqlb.Statement.

type Movable

type Movable interface {
	// contains filtered or unexported methods
}

Movable is a declared object SET SCHEMA can move: a view, a materialized view, a sequence, an enum, a composite type or a domain. The set is closed to this package's object values, and the object kind comes from the Go type, so the statement cannot say VIEW of a sequence. A table moves with AlterTable's SetSchema, because ALTER TABLE takes the rest of its actions beside it; a schema and an extension cannot move at all.

type Multirange

type Multirange[T any] string

Multirange is a Postgres multirange in text form, typed by element.

type NormalForm

type NormalForm string

NormalForm is a Unicode normalization form for Normalize.

const (
	NFC  NormalForm = "NFC"
	NFD  NormalForm = "NFD"
	NFKC NormalForm = "NFKC"
	NFKD NormalForm = "NFKD"
)

The four Unicode normalization forms. NFC and NFD are canonical; NFKC and NFKD are compatibility forms, which fold characters such as the ligature fi and so change the text rather than only its encoding.

type NullInput

type NullInput int

NullInput is what the server does with a call that has a NULL argument.

const (
	Strict NullInput = iota + 1
	CalledOnNullInput
)

The two behaviours. Strict returns NULL without running the body, which is both faster and the only correct declaration for a body that would fail on NULL; CalledOnNullInput, the default, runs it.

type OnCommitAction

type OnCommitAction int

OnCommitAction is what happens to a temporary table's rows when the transaction that created it commits.

const (
	PreserveRows OnCommitAction = iota + 1
	DeleteRows
	DropAtCommit
)

The actions. PreserveRows is the default and keeps the table for the session; DeleteRows empties it at every commit, which is what makes a temporary table usable as a scratch table across a session; DropAtCommit removes it entirely, which is what makes a table that exists for one transaction possible at all.

type OpClass

type OpClass[T any] struct {
	// contains filtered or unexported fields
}

OpClass is an operator class, typed to the Go type of the column it indexes, so jsonb_path_ops on a text column does not compile. An extension makes its own with NewOpClass.

func NewOpClass

func NewOpClass[T any](name string) OpClass[T]

NewOpClass makes an operator class for columns of Go type T.

func NullableOps

func NullableOps[T any](o OpClass[T]) OpClass[*T]

NullableOps is the same operator class for a nullable column of the same type, a *string where the class was made for string. It is a function rather than a method because a method on OpClass[T] returning OpClass[*T] is an instantiation cycle Go refuses.

type Ownable

type Ownable interface {
	// contains filtered or unexported methods
}

Ownable is a declared object OWNER TO can move to another role. The kind comes from the Go type, so the statement cannot say VIEW of a sequence, and the set is closed to the objects whose ALTER command this package builds: a table's owner is the operator's, since ALTER TABLE OWNER TO is one action among the many an operator writes on a table nobody declared here.

type Parallel

type Parallel int

Parallel is whether a function may run in a parallel query plan.

const (
	ParallelSafe Parallel = iota + 1
	ParallelRestricted
	ParallelUnsafe
)

The three levels. ParallelUnsafe, the default, stops the whole query being parallelised; ParallelRestricted allows the plan but keeps the function in the leader; ParallelSafe allows it anywhere.

type PartitionBound

type PartitionBound interface {
	// contains filtered or unexported methods
}

PartitionBound is FOR VALUES ... or DEFAULT: FromTo, ListValues, HashOf and DefaultPartition make one.

func DefaultPartition

func DefaultPartition() PartitionBound

DefaultPartition takes every row no other partition does. While one exists, attaching a new partition scans it, and DETACH ... CONCURRENTLY is refused.

func FromTo

func FromTo[T any](_ sqlb.Expr[T], from, to T) PartitionBound

FromTo is a range partition's bounds, from inclusive to exclusive, typed to the key, so a partition of a timestamp key cannot be bounded by numbers. The key is not rendered, since a partition's bound names no column; it is taken only so its Go type fixes T.

func HashOf

func HashOf(modulus, remainder int) PartitionBound

HashOf is a hash partition: the rows whose key hashes to remainder modulo modulus.

func ListValues

func ListValues[T any](_ sqlb.Expr[T], first T, more ...T) PartitionBound

ListValues is a list partition's values, typed to the key, which is taken only so its Go type fixes T.

type PeriodColumn

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

PeriodColumn is a range column that a temporal key is over: the last column of a primary or unique key WITHOUT OVERLAPS, or the PERIOD of a foreign key. It is made by Period from a column of a range type, so a column of any other type does not compile there.

func Period

func Period[T any](col sqlb.Expr[Range[T]]) PeriodColumn

Period marks a range column for a temporal key.

type Policy

type Policy struct {
	Name  string
	Table sqlb.Table
}

Policy is a row-level security policy on one table; its name is unique per table, which is why the table is part of the value.

type PolicyCommand

type PolicyCommand int

PolicyCommand is the command a policy applies to.

const (
	AllCommands PolicyCommand = iota + 1
	SelectCommand
	InsertCommand
	UpdateCommand
	DeleteCommand
)

The commands. AllCommands is the default.

type PolicyRole

type PolicyRole int

PolicyRole is one of the role-independent targets a policy can name, which a library can write without knowing any of a deployment's role names. A named role is a Role, and both satisfy RoleRef, so To takes either.

const (
	RolePublic PolicyRole = iota + 1
	RoleCurrentUser
	RoleSessionUser
)

The roles a library can name without knowing the deployment's roles.

type PrimaryKeyClause

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

PrimaryKeyClause is a PRIMARY KEY table constraint.

func PrimaryKey

func PrimaryKey(first ddl.ColumnRef, more ...ddl.ColumnRef) PrimaryKeyClause

PrimaryKey makes the table's primary key from one or more of its columns. It is written as a table constraint, which means the same as the column form and is the only form a composite key has.

func (PrimaryKeyClause) ClauseTable

func (k PrimaryKeyClause) ClauseTable() sqlb.Table

ClauseTable is the key's declared table, empty for an unnamed key.

func (PrimaryKeyClause) DescribeInto

func (k PrimaryKeyClause) DescribeInto(t *schema.Table)

DescribeInto sets the table's primary key.

func (PrimaryKeyClause) Include

func (k PrimaryKeyClause) Include(first ddl.ColumnRef, more ...ddl.ColumnRef) PrimaryKeyClause

Include adds columns to the key's index without making them part of the key, so an index-only scan can read them. They are not compared for uniqueness, which is the whole point: a unique key on one column that also carries the two columns every read of it wants.

func (PrimaryKeyClause) Named

Named gives the key a declared name, which ALTER TABLE can later drop by. Unnamed, Postgres names it table_pkey.

func (PrimaryKeyClause) NamedColumns

func (k PrimaryKeyClause) NamedColumns() []ddl.ColumnRef

NamedColumns is the key's columns, which the statement checks it defines.

func (PrimaryKeyClause) Position

func (PrimaryKeyClause) Position() ddl.Position

Position places the key among the table's elements.

func (PrimaryKeyClause) TableClauseOf

func (PrimaryKeyClause) TableClauseOf(Dialect)

TableClauseOf marks the clause as Postgres's.

func (PrimaryKeyClause) With

With sets the storage parameters of the index behind the key.

func (PrimaryKeyClause) WithoutOverlaps

func (k PrimaryKeyClause) WithoutOverlaps(p PeriodColumn) PrimaryKeyClause

WithoutOverlaps makes the key temporal: two rows may share the other key columns as long as their period ranges do not overlap, the key a booking or a price valid over an interval needs. The period is the key's last column. A GiST index backs the key, so scalar columns need the btree_gist extension. Postgres 18 or later.

func (PrimaryKeyClause) WriteSQL

func (k PrimaryKeyClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the constraint.

type Range

type Range[T any] string

Range is a Postgres range in its text form, for example "[2026-01-01,2026-02-01)". It is typed by the Go element type so a tstzrange cannot be compared with an int8range.

type RangeType

type RangeType[T any] struct{ Schema, Name string }

RangeType is a Postgres range type over the values of Go type T, declared once as a value. It is also the SQL type of a column holding one, so a Col[Range[T]] can be declared with it and a column of any other Go type cannot.

func (RangeType[T]) Spelling

func (r RangeType[T]) Spelling(d sqlb.Dialect) (string, error)

Spelling is the type's qualified name, as a column definition writes it.

func (RangeType[T]) TypeOf

func (RangeType[T]) TypeOf(Range[T])

TypeOf types the range type to Range[T] for ddl.SQLType.

type RefAction

type RefAction int

RefAction is what a foreign key does when the row it references is deleted or updated. It is a closed set: a value outside the named constants fails Build with ErrUnknownKeyword rather than being written into the statement.

const (
	RefNoAction RefAction = iota + 1
	RefRestrict
	RefCascade
	RefSetNull
	RefSetDefault
)

The referential actions. They carry a Ref prefix because pg.Cascade is the DROP TABLE clause and pg.SetDefault the ALTER TABLE action.

type RefreshStatement

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

RefreshStatement is REFRESH MATERIALIZED VIEW.

func RefreshMaterializedView

func RefreshMaterializedView(v MaterializedView) *RefreshStatement

RefreshMaterializedView recomputes a materialized view, blocking reads of it while it runs.

func (*RefreshStatement) Build

func (x *RefreshStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*RefreshStatement) Concurrently

func (x *RefreshStatement) Concurrently() *RefreshStatement

Concurrently refreshes without blocking reads. It needs a unique index on the view and a view that has been populated once.

type RenameIndexStatement

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

RenameIndexStatement is ALTER INDEX ... RENAME TO.

func RenameIndex

func RenameIndex(from, to Index) *RenameIndexStatement

RenameIndex renames an index; its schema is unchanged.

func (*RenameIndexStatement) Build

func (x *RenameIndexStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*RenameIndexStatement) IfExists

IfExists makes renaming a missing index a no-op.

type RenameMaterializedViewStatement

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

RenameMaterializedViewStatement is ALTER MATERIALIZED VIEW ... RENAME TO.

func RenameMaterializedView

func RenameMaterializedView(from, to MaterializedView) *RenameMaterializedViewStatement

RenameMaterializedView renames a materialized view; its schema is unchanged.

func (*RenameMaterializedViewStatement) Build

Build renders the statement.

func (*RenameMaterializedViewStatement) IfExists

IfExists makes renaming a missing materialized view a no-op.

type RenameSchemaStatement

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

RenameSchemaStatement is ALTER SCHEMA ... RENAME TO.

func RenameSchema

func RenameSchema(from, to Schema) *RenameSchemaStatement

RenameSchema renames a schema. Every object in it moves with it, and every Table value naming the old schema must change with it.

func (*RenameSchemaStatement) Build

func (x *RenameSchemaStatement) Build() (ddl.Script, error)

Build renders the statement.

type RenameTriggerStatement

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

RenameTriggerStatement is ALTER TRIGGER ... RENAME TO.

func RenameTrigger

func RenameTrigger(from, to Trigger) *RenameTriggerStatement

RenameTrigger renames a trigger on its table; to names the same table.

func (*RenameTriggerStatement) Build

func (x *RenameTriggerStatement) Build() (ddl.Script, error)

Build renders the statement.

type RenameViewColumnStatement

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

RenameViewColumnStatement is ALTER VIEW ... RENAME COLUMN.

func RenameViewColumn

func RenameViewColumn(v View, from, to string) *RenameViewColumnStatement

RenameViewColumn renames one of a view's output columns, the migration a library writes when a name it exposed changes without its body changing. The names are strings because a view's columns are named by its select list; every query reading the view through this package names the column through its own Col value, which must change in the same release.

func (*RenameViewColumnStatement) Build

func (x *RenameViewColumnStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*RenameViewColumnStatement) IfExists

IfExists makes renaming a column of a missing view a no-op.

type RenameViewStatement

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

RenameViewStatement is ALTER VIEW ... RENAME TO.

func RenameView

func RenameView(from, to View) *RenameViewStatement

RenameView renames a view; its schema is unchanged.

func (*RenameViewStatement) Build

func (x *RenameViewStatement) Build() (ddl.Script, error)

Build renders the statement.

func (*RenameViewStatement) IfExists

IfExists makes renaming a missing view a no-op.

type RestartIdentityClause

type RestartIdentityClause[T identityInteger] struct {
	// contains filtered or unexported fields
}

RestartIdentityClause is the ALTER COLUMN action that sets an identity column's sequence back to its start value, or to With's.

func RestartIdentity

func RestartIdentity[T identityInteger](col sqlb.Expr[T]) RestartIdentityClause[T]

RestartIdentity restarts an identity column's sequence from the value the column was declared with. Use it after loading rows with explicit keys, where the sequence is behind the data and the next insert would collide.

func (RestartIdentityClause[T]) AlterClauseOf

func (RestartIdentityClause[T]) AlterClauseOf(Dialect)

AlterClauseOf marks the action as Postgres's.

func (RestartIdentityClause[T]) NamedColumns

func (x RestartIdentityClause[T]) NamedColumns() []ddl.ColumnRef

NamedColumns is the column being restarted.

func (RestartIdentityClause[T]) Standalone

func (RestartIdentityClause[T]) Standalone() bool

Standalone reports that the action may share a statement.

func (RestartIdentityClause[T]) With

func (x RestartIdentityClause[T]) With(n T) RestartIdentityClause[T]

With restarts from n instead, a value of the column's own Go type.

func (RestartIdentityClause[T]) WriteSQL

func (x RestartIdentityClause[T]) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the action.

type Role

type Role struct{ Name string }

Role is a Postgres role, declared once as a value and named by every statement that gives it something to own or a policy to be subject to. The name is written as an identifier by the dialect, so a role name holding a quote stays one identifier; it is never a parameter, because no engine takes a placeholder where a role name goes.

type RoleRef

type RoleRef interface {
	// contains filtered or unexported methods
}

RoleRef is a role a statement can name: a Role the deployment declared, or one of the role-independent keywords a library can write without knowing any of a deployment's names. The set is closed to those two, so a statement cannot be handed a bare string that is interpolated into SQL.

type Rule

type Rule struct {
	Name  string
	Table sqlb.Table
}

Rule is a Postgres rewrite rule on one table, declared as a value so that the statements enabling and disabling one need not be told the name twice. Its name is unique per table, which is why the table is part of the value, exactly as a Trigger's and a Policy's are.

This package creates no rule. A rule rewrites a statement before it runs, which means a caller's INSERT can silently become something else, and every use of one a trigger cannot serve is a use nobody should start today; the rules that exist are in schemas older than that advice, and their migrations are what these statements are for. The exception Postgres itself depends on, the rule behind a view, is created by CREATE VIEW and not by hand.

type SampleMethod

type SampleMethod string

SampleMethod is the sampling method TABLESAMPLE uses.

The set is the SERVER'S, not this module's, and that is why the two constants below are a starting point rather than a list to validate against: TABLESAMPLE takes whatever sampling method is installed, and tsm_system_rows and tsm_system_time each bring one. SYSTEM_ROWS is the method that takes a row count instead of a percentage, and this repository's own snippet catalogue builds it.

It is checked in shape rather than membership for exactly the reason AccessMethod and IndexMethod are not checked at all: a list would refuse the extension that brings a real one. A list here was an over-closure that shipped for a few hours on 2026-09-24 and was caught by the examples, the only gate that had a SYSTEM_ROWS in it.

Unlike AccessMethod it is NOT quoted, and that is measured rather than assumed: the method name folds to lower case unquoted, and the catalogue stores it lower case, so TABLESAMPLE "SYSTEM" (50) fails with "tablesample method SYSTEM does not exist" where TABLESAMPLE SYSTEM (50) works. Quoting this would have broken both constants below. The shape is therefore the only defence available, and the shape is an identifier's: the same check a function name gets, since a sampling method is a name the server looks up rather than a keyword its grammar knows.

const (
	SampleBernoulli SampleMethod = "BERNOULLI"
	SampleSystem    SampleMethod = "SYSTEM"
)

The two sampling methods every Postgres has. An extension's method is written out: SampleMethod("SYSTEM_ROWS").

type Schema

type Schema struct{ Name string }

Schema is a Postgres schema.

type Security

type Security int

Security is whose privileges a function's body runs with.

const (
	Invoker Security = iota + 1
	Definer
)

The two modes. Invoker, the default, runs the body as the caller, so the caller's own privileges and row-level security policies apply; Definer runs it as the function's owner, which is how a library exposes one controlled operation on a table the caller may not touch directly, and is why a definer function's search_path must be pinned with Set.

type SelectClause

type SelectClause = sqlb.Clause[Dialect, sqlb.SelectKind]

SelectClause is a clause for a SELECT on this engine.

func DistinctOn

func DistinctOn(exprs ...sqlb.SQLer) SelectClause

DistinctOn renders DISTINCT ON (exprs) after SELECT. The expressions may be of mixed Go types, which is why it takes SQLer rather than Expr[T].

func FetchFirst

func FetchFirst(n int, withTies bool) SelectClause

FetchFirst renders FETCH FIRST $n ROWS ONLY, or ROWS WITH TIES, after OFFSET. WITH TIES needs an ORDER BY; the database enforces that.

func ForKeyShare

func ForKeyShare(opts ...LockOption) SelectClause

ForKeyShare renders FOR KEY SHARE, the weakest: it blocks only a change to the key. It is the lock a foreign-key check takes.

func ForNoKeyUpdate

func ForNoKeyUpdate(opts ...LockOption) SelectClause

ForNoKeyUpdate renders FOR NO KEY UPDATE, which still allows another transaction to reference the row with a foreign key. The right lock when you are updating a non-key column of a row other tables point at.

func ForShare

func ForShare(opts ...LockOption) SelectClause

ForShare renders FOR SHARE: several readers may hold it, and it blocks writers.

func ForUpdate

func ForUpdate(opts ...LockOption) SelectClause

ForUpdate renders FOR UPDATE, the strongest row lock: it blocks another FOR UPDATE, a FOR SHARE, and any update or delete of the row.

The four here are ordered from strongest to weakest. Take the weakest that holds the invariant you need, because each stronger one blocks more writers.

func ForUpdateSkipLocked

func ForUpdateSkipLocked() SelectClause

ForUpdateSkipLocked is the queue idiom in one call.

func LimitAll

func LimitAll() SelectClause

LimitAll renders LIMIT ALL in the after-order slot: explicit "no limit".

func TableSample

func TableSample(method SampleMethod, percent float64, seed int) SelectClause

TableSample renders TABLESAMPLE method (percent) [REPEATABLE (seed)] after a table reference. Postgres requires the percentage as a literal expression; it is an author constant, never request data. seed < 0 omits REPEATABLE.

TABLESAMPLE is per table reference, not per statement, so where the clause goes decides which table it samples. On the driving table it goes in the statement; on a joined table it goes in that join:

sel.From(t).Clause(pg.TableSample(pg.SampleSystem, 10, -1))
sel.Join(sqlb.Join{Type: sqlb.JoinInner, Table: other, On: ...,
	Clauses: []sqlb.AnyClause{pg.TableSample(pg.SampleSystem, 10, -1)}})

Putting a joined table's sample in the statement samples the driving table instead, which is a different query that still runs.

type SelectQuery

type SelectQuery = sqlb.Select[Dialect]

SelectQuery is the statement type Select returns. The aliases below carry a Query suffix because Go cannot give a type and a function one name in a package; an alias is the type itself, so a value passes through either name with no conversion.

func Select

func Select(items ...sqlb.SQLer) *SelectQuery

Select starts a SELECT for Postgres. Items passed here are added without scan targets, for a subquery, a CTE body or a view; a query that will be scanned calls Select() with no items and adds bindings with Columns.

type Sequence

type Sequence[T sequenceInteger] struct{ Schema, Name string }

Sequence is a Postgres sequence whose values are T, so NextVal(s) is an Expr[T] and DefaultExpr accepts it only on a column of T. Prefer an identity column for a new table; a free sequence is for a number shared by several tables or read before an insert.

type SetExtensionSchemaStatement

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

SetExtensionSchemaStatement is ALTER EXTENSION ... SET SCHEMA.

func SetExtensionSchema

func SetExtensionSchema(e Extension, to Schema) *SetExtensionSchemaStatement

SetExtensionSchema moves an extension's objects into another schema, the statement a library runs when it stops leaving an extension's types in the search path. Only an extension that declares itself relocatable can move, which Postgres checks, and every Table and Col naming one of its types must carry the new schema in the same release.

func (*SetExtensionSchemaStatement) Build

Build renders the statement.

type SetOwnerStatement

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

SetOwnerStatement is the OWNER TO statement of one declared object, whose ALTER keyword names the object kind.

func SetOwner

func SetOwner(o Ownable, to RoleRef) *SetOwnerStatement

SetOwner gives a declared object to another role, the migration a library writes when the role that ran its install is not the role that will run it from then on. Ownership decides who may drop or alter the object and whose privileges a SECURITY DEFINER function runs with, which is why it is a migration rather than a grant.

func (*SetOwnerStatement) Build

func (x *SetOwnerStatement) Build() (ddl.Script, error)

Build renders the statement.

type SetSchemaStatement

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

SetSchemaStatement is the SET SCHEMA statement of one declared object, whose ALTER keyword names the object kind.

func SetObjectSchema

func SetObjectSchema(o Movable, to Schema) *SetSchemaStatement

SetObjectSchema moves a declared object into another schema, the migration a library writes when it stops living in the search path and takes a schema of its own. Every value naming the object, and every Table whose columns it types, must carry the new schema in the same release, which is why the object is a value declared once.

func (*SetSchemaStatement) Build

func (x *SetSchemaStatement) Build() (ddl.Script, error)

Build renders the statement.

type StatKind

type StatKind int

StatKind is what an extended statistics object measures.

const (
	NDistinct StatKind = iota + 1
	Dependencies
	MCV
)

The kinds.

type Statistics

type Statistics struct{ Schema, Name string }

Statistics is an extended statistics object, which tells the planner that two columns are correlated so it stops multiplying their selectivities.

type StorageParameter

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

StorageParameter is one storage parameter of an index, a table or a materialized view: a name and a typed value. The names are an open set, because an access method and an extension each add their own, so the name is written as an identifier; the value is written by the dialect as a literal of its Go type, which is what keeps a text parameter one string.

func BoolParameter

func BoolParameter(name string, v bool) StorageParameter

BoolParameter is an on-or-off parameter.

func FloatParameter

func FloatParameter(name string, v float64) StorageParameter

FloatParameter is a fractional parameter, an autovacuum scale factor being the usual one.

func IntParameter

func IntParameter(name string, v int64) StorageParameter

IntParameter is a whole-numbered parameter, fillfactor being the usual one.

func TextParameter

func TextParameter(name string, v string) StorageParameter

TextParameter is a parameter whose value is a word or a phrase.

type TSQuery

type TSQuery string

TSQuery is a Postgres tsquery in text form: the search expression matched against a TSVector. See TSVector for why the two are separate types.

type TSVector

type TSVector string

TSVector is a Postgres tsvector in text form: a document reduced to its lexemes, with their positions and weights.

It and TSQuery are distinct Go types so the compiler refuses to pass a query where a document is expected. SQL accepts that mistake and answers it wrongly, because both are text on the wire.

type TableClause

type TableClause = ddl.TableClause[Dialect]

TableClause is a Postgres clause for CREATE TABLE.

func Inherits

func Inherits(first sqlb.Table, more ...sqlb.Table) TableClause

Inherits makes the new table a child of one or more parents, so a query on a parent also reads this table's rows. It is the CREATE TABLE half of Inherit, and the same advice applies: partitioning replaces it for a new schema. It renders first of the table's options, before PARTITION BY.

func OnCommit

func OnCommit(o OnCommitAction) TableClause

OnCommit says what happens to a temporary table's rows at commit. Postgres refuses it on an ordinary table with "ON COMMIT can only be used on temporary tables", so it belongs beside Temporary. It renders last of the table's options wherever the caller places it; see the rank table above.

func PartitionByHash

func PartitionByHash(first ddl.ColumnRef, more ...ddl.ColumnRef) TableClause

PartitionByHash spreads rows over a fixed number of partitions by hash.

func PartitionByList

func PartitionByList(col ddl.ColumnRef) TableClause

PartitionByList partitions by listed values of one column, a tenant or a region.

func PartitionByRange

func PartitionByRange(first ddl.ColumnRef, more ...ddl.ColumnRef) TableClause

PartitionByRange partitions the table by ranges of its key, time most often. A primary or unique key on a partitioned table must include the key.

func TableAccessMethod

func TableAccessMethod(m AccessMethod) TableClause

TableAccessMethod stores the table's rows in an access method other than the server's default. It renders after PARTITION BY and before the storage parameters.

func TableStorage

func TableStorage(first StorageParameter, more ...StorageParameter) TableClause

TableStorage sets the table's storage parameters at creation, the same open set AlterIndex and AlterMaterializedView take. It renders after the access method and before ON COMMIT.

func Temporary

func Temporary() TableClause

Temporary makes the table live in the session's temporary schema and vanish when the session ends. Postgres also accepts GLOBAL and LOCAL before it, which it documents as accepted for compatibility and ignores, so neither is offered: a keyword that changes nothing is a keyword that misleads.

It goes between CREATE and TABLE, beside Unlogged, and the two are mutually exclusive.

func Unlogged

func Unlogged() TableClause

Unlogged makes the table skip the write-ahead log: faster, lost on a crash, and not replicated. For data a library can rebuild, such as rate-limit counters.

type TableConstraint

type TableConstraint = ddl.TableConstraint

TableConstraint is a named constraint of one table, declared once. See ddl.TableConstraint.

type TableLockMode

type TableLockMode string

TableLockMode is one of the eight table-level lock modes Postgres defines.

A distinct string type rather than a bare string so a caller cannot pass an arbitrary fragment into a statement whose whole purpose is to block other transactions, and so the set is discoverable from the type.

const (
	LockAccessShare          TableLockMode = "ACCESS SHARE"
	LockRowShare             TableLockMode = "ROW SHARE"
	LockRowExclusive         TableLockMode = "ROW EXCLUSIVE"
	LockShareUpdateExclusive TableLockMode = "SHARE UPDATE EXCLUSIVE"
	LockShare                TableLockMode = "SHARE"
	LockShareRowExclusive    TableLockMode = "SHARE ROW EXCLUSIVE"
	LockExclusive            TableLockMode = "EXCLUSIVE"
	LockAccessExclusive      TableLockMode = "ACCESS EXCLUSIVE"
)

The table lock modes, weakest first. Each conflicts with a documented set of the others; the ordering here is the conflict ordering, so a reader can see that ACCESS SHARE blocks almost nothing and ACCESS EXCLUSIVE blocks everything including a plain SELECT.

type TimedTriggerQuery

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

TimedTriggerQuery is CREATE TRIGGER with its timing and events and no function yet, which has no Build.

func (*TimedTriggerQuery) Deferrable

func (x *TimedTriggerQuery) Deferrable(d Deferral) *TimedTriggerQuery

Deferrable makes a constraint trigger deferrable, checked when d says.

func (*TimedTriggerQuery) Execute

Execute names the trigger function, and so completes the statement.

func (*TimedTriggerQuery) ExecuteWith

func (x *TimedTriggerQuery) ExecuteWith(f Function, args ...string) *CreateTriggerStatement

ExecuteWith names the trigger function and the constant arguments Postgres passes it, which every trigger function reads out of TG_ARGV rather than as parameters — which is why the Function still declares none. The arguments are written as literals by the dialect, and they are the author's text, not a value from a request.

func (*TimedTriggerQuery) ForEachRow

func (x *TimedTriggerQuery) ForEachRow() *TimedTriggerQuery

ForEachRow fires once per row changed, the form that sees OLD and NEW. Without it the trigger fires once per statement.

func (*TimedTriggerQuery) From

From names the table a constraint trigger's other side is on, which is what a foreign-key-shaped constraint trigger points at. It has meaning only on a constraint trigger, which the server enforces.

func (*TimedTriggerQuery) Referencing

func (x *TimedTriggerQuery) Referencing(oldTable, newTable string) *TimedTriggerQuery

Referencing gives a statement trigger the rows the statement changed, as two transition tables its function can query. Without them a statement trigger knows only that something happened, which is why a per-statement audit had to be a row trigger and pay for a call per row.

Both names are optional: an INSERT has no old rows and a DELETE no new ones, and Postgres refuses the table that does not apply to the events declared.

func (*TimedTriggerQuery) When

When fires the trigger only for rows matching p, written with Old and New.

type Trigger

type Trigger struct {
	Name  string
	Table sqlb.Table
}

Trigger is a trigger on one table. Its name is unique per table, not per schema, which is why the table is part of the value.

type TriggerEvent

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

TriggerEvent is what fires a trigger: an INSERT, an UPDATE, an UPDATE of named columns, or a DELETE.

func OnDelete

func OnDelete() TriggerEvent

OnDelete fires on DELETE.

func OnInsert

func OnInsert() TriggerEvent

OnInsert fires on INSERT.

func OnTruncate

func OnTruncate() TriggerEvent

OnTruncate fires on TRUNCATE. It is a statement trigger only — there are no rows to see, which is why Postgres refuses it FOR EACH ROW — and it is the one event a row trigger cannot have.

func OnUpdate

func OnUpdate() TriggerEvent

OnUpdate fires on any UPDATE.

func OnUpdateOf

func OnUpdateOf(first ddl.ColumnRef, more ...ddl.ColumnRef) TriggerEvent

OnUpdateOf fires on an UPDATE whose SET names one of cols. A generated column cannot be named: it is never in a SET.

type TrimSide

type TrimSide string

TrimSide is BOTH, LEADING or TRAILING.

const (
	TrimBoth     TrimSide = kwBoth
	TrimLeading  TrimSide = kwLeading
	TrimTrailing TrimSide = kwTrailing
)

The three sides Postgres accepts in trim(side chars FROM e).

type Truncate

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

Truncate builds a TRUNCATE statement. Every method returns a derived statement and leaves its receiver alone, as the core's builders do, so deriving two statements from one base is safe.

It is here rather than in the core because SQLite has no TRUNCATE at all and emulates it with an unfiltered DELETE, so the core's rule that a construct ships only when all four engines accept it with the same meaning excludes it.

It is also a second worked example of a statement kind written outside the statement package, after pg.Merge: it satisfies sqlb.Statement, so it can be a CTE body, and it renders through the same guarded constructors every other construct here uses. Nothing in stmt changed to allow it.

Worth stating because the API does not: TRUNCATE is not transactional on every engine and removes every row without firing per-row triggers. This builder will not stop you; Delete with an explicit All() is the checked alternative.

func NewTruncate

func NewTruncate(d Dialect, tables ...sqlb.Table) *Truncate

NewTruncate starts a TRUNCATE for d. The dialect is typed: a TRUNCATE is Postgres-shaped, so passing another engine's dialect does not compile.

func (*Truncate) Build

func (t *Truncate) Build() (sqlb.Query, error)

Build renders the statement, or returns the first error it found.

func (*Truncate) Cascade

func (t *Truncate) Cascade() *Truncate

Cascade also truncates tables with a foreign key to any named here.

Destructive in a way the rest of this library is not: it reaches tables the caller did not name, including tables owned by another package. It is spelled out rather than being an option value so that it is visible at the call site and in a diff.

func (*Truncate) ContinueIdentity

func (t *Truncate) ContinueIdentity() *Truncate

ContinueIdentity leaves sequences alone. It is the default, and naming it makes the choice visible in a statement where the other option is common.

func (*Truncate) Only

func (t *Truncate) Only() *Truncate

Only truncates the named tables without their inheritance children.

func (*Truncate) RestartIdentity

func (t *Truncate) RestartIdentity() *Truncate

RestartIdentity resets owned sequences, which is usually what somebody truncating a table in a test actually wants.

func (*Truncate) Restrict

func (t *Truncate) Restrict() *Truncate

Restrict refuses when another table references one named here, which is the default.

func (*Truncate) Table

func (t *Truncate) Table(tables ...sqlb.Table) *Truncate

Table adds a table. Truncating several together is the reason the statement exists rather than being a DELETE: one statement, one lock, and foreign keys between the named tables do not block each other.

func (*Truncate) WriteSQL

func (t *Truncate) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the statement into b, satisfying sqlb.Statement. A table is written by its qualified name alone: neither statement accepts an alias, which the rendering test asserted the wrong way until a real server rejected it.

type TypeAlignment

type TypeAlignment int

TypeAlignment is the storage alignment a base type's values need.

const (
	AlignChar TypeAlignment = iota + 1
	AlignInt2
	AlignInt4
	AlignDouble
)

The alignments Postgres allows for a base type. AlignInt4 is the default; a type wider than its alignment is stored unaligned and read slowly, and one narrower wastes the difference in every row.

type TypeCategory

type TypeCategory string

TypeCategory is the class a base type belongs to, which decides which implicit casts the parser will consider in an ambiguous call. It is an open set of one-character codes: Postgres reserves the upper-case letters for itself and leaves the rest to a user-defined type.

const (
	CategoryUser      TypeCategory = "U"
	CategoryNumeric   TypeCategory = "N"
	CategoryString    TypeCategory = "S"
	CategoryDateTime  TypeCategory = "D"
	CategoryBoolean   TypeCategory = "B"
	CategoryGeometric TypeCategory = "G"
	CategoryNetwork   TypeCategory = "I"
	CategoryRange     TypeCategory = "R"
	CategoryTimespan  TypeCategory = "T"
)

The categories a user-defined base type is likely to claim. CategoryUser is the default and the safe answer; claiming a built-in category puts the type into the parser's resolution rules for that category, which changes how calls that were never about this type resolve.

type TypeRef

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

TypeRef is a declared SQL type named in a position where its Go type says nothing about the statement, a base type's element or a transform's type. The Go parameter is checked by NamedType and erased after.

func NamedType

func NamedType[T any](t ddl.SQLType[T]) TypeRef

NamedType refers to t where only its name is written.

type TypeStorage

type TypeStorage int

TypeStorage is how a base type's values are stored when they do not fit in a row.

const (
	StoragePlain TypeStorage = iota + 1
	StorageExternal
	StorageExtended
	StorageMain
)

The storage strategies. StoragePlain is the only one a fixed-length type may use; the others allow a variable-length value to be compressed, moved out of line, or both, which is what makes a wide type usable at all.

type UniqueClause

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

UniqueClause is a UNIQUE table constraint.

func Unique

func Unique(c TableConstraint, first ddl.ColumnRef, more ...ddl.ColumnRef) UniqueClause

Unique makes a named unique constraint over one or more columns. The name is required because a unique constraint is the thing a later migration drops or renames, and the name Postgres would choose is not written anywhere a reader of this code can see.

func (UniqueClause) ClauseTable

func (u UniqueClause) ClauseTable() sqlb.Table

ClauseTable is the constraint's declared table.

func (UniqueClause) DescribeInto

func (u UniqueClause) DescribeInto(t *schema.Table)

DescribeInto adds the constraint as a unique index.

func (UniqueClause) Include

func (u UniqueClause) Include(first ddl.ColumnRef, more ...ddl.ColumnRef) UniqueClause

Include adds covering columns to the constraint's index.

func (UniqueClause) NamedColumns

func (u UniqueClause) NamedColumns() []ddl.ColumnRef

NamedColumns is the constraint's columns.

func (UniqueClause) NullsNotDistinct

func (u UniqueClause) NullsNotDistinct() UniqueClause

NullsNotDistinct makes two NULLs collide, so a nullable column holds at most one NULL. Without it every NULL is distinct and any number are allowed. Postgres 15 or later.

func (UniqueClause) Position

func (UniqueClause) Position() ddl.Position

Position places the constraint among the table's elements.

func (UniqueClause) TableClauseOf

func (UniqueClause) TableClauseOf(Dialect)

TableClauseOf marks the clause as Postgres's.

func (UniqueClause) With

With sets the storage parameters of the index behind the constraint.

func (UniqueClause) WithoutOverlaps

func (u UniqueClause) WithoutOverlaps(p PeriodColumn) UniqueClause

WithoutOverlaps makes the unique key temporal; see PrimaryKeyClause.WithoutOverlaps. Postgres 18 or later.

func (UniqueClause) WriteSQL

func (u UniqueClause) WriteSQL(b *strings.Builder, a *sqlb.Args)

WriteSQL renders the constraint.

type UpdateClause

type UpdateClause = sqlb.Clause[Dialect, sqlb.UpdateKind]

UpdateClause is a clause for an UPDATE on this engine.

func UpdateFrom

func UpdateFrom(srcs ...sqlb.Source) UpdateClause

UpdateFrom renders UPDATE ... FROM sources after the SET list, so SET and WHERE may reference them. MySQL uses a multi-table UPDATE instead.

type UpdateQuery

type UpdateQuery = sqlb.Update[Dialect]

UpdateQuery is the statement Update returns. It has no Build until Where or All says which rows, so an unfiltered UPDATE does not compile.

func Update

func Update(t sqlb.Table) *UpdateQuery

Update starts an UPDATE of t for Postgres.

type Validatable

type Validatable interface {
	Constraint
	// contains filtered or unexported methods
}

Validatable is a constraint Postgres can add NOT VALID: a foreign key or a check, and nothing else, so AddConstraintNotValid on a unique key does not compile rather than failing on the server.

type View

type View struct{ Schema, Name string }

View is a Postgres view.

type ViewOption

type ViewOption int

ViewOption is a storage option of a view, the closed set Postgres defines for one. It names an option for Reset; the setters take the option's own value type, so a boolean option cannot be given a check option.

const (
	ViewCheckOption ViewOption = iota + 1
	ViewSecurityBarrier
	ViewSecurityInvoker
)

The view options. ViewCheckOption is what WithCheckOption writes at CREATE VIEW; the two security options decide whose privileges the view's own query runs with, which is what an RLS-aware view turns on.

type ViewSetting

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

ViewSetting is one of a view's options with its value: the closed set of names Postgres defines for a view, each taking its own value type, so a boolean option cannot be given a check option. It exists as a value rather than only as a method because CREATE VIEW and ALTER VIEW both take the same options, and two spellings of one option list is the thing that drifts.

func CheckOptionSetting

func CheckOptionSetting(o CheckOption) ViewSetting

CheckOptionSetting refuses a write through the view that the view would not show, the option CreateView also writes as WITH ... CHECK OPTION.

func SecurityBarrierSetting

func SecurityBarrierSetting(on bool) ViewSetting

SecurityBarrierSetting stops Postgres pushing a caller's own WHERE condition below the view's, which would otherwise let a cheap function in that condition see rows the view hides. It costs plans, so it is off by default.

func SecurityInvokerSetting

func SecurityInvokerSetting(on bool) ViewSetting

SecurityInvokerSetting runs the view's own query with the caller's privileges rather than the view owner's, so the caller's row-level security policies apply to the tables under it. A library shipping a view over its own RLS-protected tables wants this on.

type Volatility

type Volatility int

Volatility is what the planner may assume about a function's result: whether two calls with the same arguments must agree, and for how long.

const (
	Immutable Volatility = iota + 1
	Stable
	Volatile
)

The volatility categories. Immutable is the strongest promise and the only one that may be used in an index expression; Volatile, the default, promises nothing and is what a function reading tables must declare.

type Weight

type Weight string

Weight is a tsvector label: A, B, C or D.

const (
	WeightA Weight = "A"
	WeightB Weight = "B"
	WeightC Weight = "C"
	WeightD Weight = "D"
)

The four weight labels. A is the strongest and D the weakest; ts_rank weights them {D, C, B, A} = {0.1, 0.2, 0.4, 1.0} unless told otherwise.

type WhenBuilder

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

WhenBuilder finishes one WHEN branch.

func (WhenBuilder) ThenDelete

func (w WhenBuilder) ThenDelete() *Merge

ThenDelete finishes the branch with DELETE.

func (WhenBuilder) ThenDoNothing

func (w WhenBuilder) ThenDoNothing() *Merge

ThenDoNothing finishes the branch with DO NOTHING, which is how a branch claims rows so a later branch does not act on them.

func (WhenBuilder) ThenInsert

func (w WhenBuilder) ThenInsert(as ...sqlb.Assignment) *Merge

ThenInsert finishes the branch with INSERT.

func (WhenBuilder) ThenUpdate

func (w WhenBuilder) ThenUpdate(as ...sqlb.Assignment) *Merge

ThenUpdate finishes the branch with UPDATE SET, and returns the Merge so the next branch chains from it.

Directories

Path Synopsis
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.
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.
Package fuzzy is the fuzzystrmatch extension: phonetic and edit-distance matching.
Package fuzzy is the fuzzystrmatch extension: phonetic and edit-distance matching.
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.
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.
Package trgm is the pg_trgm extension: trigram similarity operators and functions.
Package trgm is the pg_trgm extension: trigram similarity operators and functions.
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.
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.

Jump to

Keyboard shortcuts

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