Documentation
¶
Overview ¶
Package sql contains SQL query builders, expression nodes, and the compiler that turns them into SQL text plus bind arguments.
This package is the untyped core of sqlkit. Most applications should use the typed builders in package sqlkit (backed by code generated with sqlkit), which compile down to the nodes defined here.
Index ¶
- Constants
- Variables
- func CompileInline(dialect Dialect, q Query) (string, error)
- func CompileStatic(dialect Dialect, expr Expression) (string, error)
- func Decompose(q Query, onCTEName func(string), onName func(string), onChild func(Query))
- func IdentNames(ids []Ident) []string
- func Inspect(node Node, f func(Node) bool)
- func Walk(v Visitor, node Node)
- func WalkExpr(e Expression, visit func(Expression))
- func WalkSelectionExpr(s Selection, visit func(Expression))
- func WalkSelectionSubqueries(s Selection, visit func(Query))
- func WalkSubqueries(e Expression, visit func(Query))
- type AliasedSelection
- type AlterTableBuilder
- func (b AlterTableBuilder) AddCheck(name string, expr Expression) AlterTableBuilder
- func (b AlterTableBuilder) AddColumn(c ColumnDef) AlterTableBuilder
- func (b AlterTableBuilder) AddForeignKey(fk ForeignKeyConstraint) AlterTableBuilder
- func (b AlterTableBuilder) AddPrimaryKey(columns ...string) AlterTableBuilder
- func (b AlterTableBuilder) AddUnique(name string, columns ...string) AlterTableBuilder
- func (b AlterTableBuilder) AlterColumnType(name string, t ColumnType) AlterTableBuilder
- func (b AlterTableBuilder) DropColumn(name string) AlterTableBuilder
- func (b AlterTableBuilder) DropConstraint(name string) AlterTableBuilder
- func (b AlterTableBuilder) DropDefault(name string) AlterTableBuilder
- func (b AlterTableBuilder) DropNotNull(name string) AlterTableBuilder
- func (b AlterTableBuilder) DropPrimaryKey() AlterTableBuilder
- func (b AlterTableBuilder) RenameColumn(from, to string) AlterTableBuilder
- func (b AlterTableBuilder) RenameTo(name string) AlterTableBuilder
- func (b AlterTableBuilder) RestateColumn(c ColumnDef) AlterTableBuilder
- func (b AlterTableBuilder) SetDefault(name string, expr Expression) AlterTableBuilder
- func (b AlterTableBuilder) SetNotNull(name string) AlterTableBuilder
- func (b AlterTableBuilder) Stmt() AlterTableStmt
- func (b AlterTableBuilder) ToSQL(d Dialect) (string, []any, error)
- type AlterTableStmt
- type AlterTypeAddValueBuilder
- func (b AlterTypeAddValueBuilder) After(neighbor string) AlterTypeAddValueBuilder
- func (b AlterTypeAddValueBuilder) Before(neighbor string) AlterTypeAddValueBuilder
- func (b AlterTypeAddValueBuilder) IfNotExists() AlterTypeAddValueBuilder
- func (b AlterTypeAddValueBuilder) Stmt() AlterTypeAddValueStmt
- func (b AlterTypeAddValueBuilder) ToSQL(d Dialect) (string, []any, error)
- type AlterTypeAddValueStmt
- type AlterTypeRenameValueStmt
- type Alteration
- type AlterationKind
- type ArrayDialect
- type ArrayExpression
- type Assignment
- type AutoIncrementColumnType
- type BetweenExpression
- type BinaryExpression
- func Add(left, right any) BinaryExpression
- func Div(left, right any) BinaryExpression
- func Eq(left, right any) BinaryExpression
- func Ge(left, right any) BinaryExpression
- func Gt(left, right any) BinaryExpression
- func Le(left, right any) BinaryExpression
- func Like(left, pattern any) BinaryExpression
- func Lt(left, right any) BinaryExpression
- func Mod(left, right any) BinaryExpression
- func Mul(left, right any) BinaryExpression
- func Ne(left, right any) BinaryExpression
- func NotLike(left, pattern any) BinaryExpression
- func Sub(left, right any) BinaryExpression
- type BindParamLimiter
- type CTE
- type CTEOption
- type CaseExpression
- type CaseInsensitiveLiker
- type CastExpression
- type CollateExpression
- type ColumnDef
- type ColumnExpression
- type ColumnReference
- type ColumnType
- type CommentOnColumnStmt
- type CommentOnTableStmt
- type Compiler
- func (c *Compiler) CompileAlterTable(s AlterTableStmt) (string, error)
- func (c *Compiler) CompileCommentOnColumn(s CommentOnColumnStmt) (string, error)
- func (c *Compiler) CompileCommentOnTable(s CommentOnTableStmt) (string, error)
- func (c *Compiler) CompileCompound(q CompoundStmt) (string, []any, error)
- func (c *Compiler) CompileCreateFunction(s CreateFunctionStmt) (string, error)
- func (c *Compiler) CompileCreateIndex(s CreateIndexStmt) (string, error)
- func (c *Compiler) CompileCreateSchema(s CreateSchemaStmt) (string, error)
- func (c *Compiler) CompileCreateTable(s CreateTableStmt) (string, error)
- func (c *Compiler) CompileCreateView(s CreateViewStmt) (string, error)
- func (c *Compiler) CompileDelete(q DeleteStmt) (string, []any, error)
- func (c *Compiler) CompileDropForeignKey(s DropForeignKeyStmt) (string, error)
- func (c *Compiler) CompileDropFunction(s DropFunctionStmt) (string, error)
- func (c *Compiler) CompileDropIndex(s DropIndexStmt) (string, error)
- func (c *Compiler) CompileDropSchema(s DropSchemaStmt) (string, error)
- func (c *Compiler) CompileDropTable(s DropTableStmt) (string, error)
- func (c *Compiler) CompileDropView(s DropViewStmt) (string, error)
- func (c *Compiler) CompileExpression(expr Expression) (string, []any, error)
- func (c *Compiler) CompileGrant(s GrantStmt) (string, error)
- func (c *Compiler) CompileInsert(q InsertStmt) (string, []any, error)
- func (c *Compiler) CompileJoin(join JoinClause) (string, []any, error)
- func (c *Compiler) CompileMerge(q MergeStmt) (string, []any, error)
- func (c *Compiler) CompileRevoke(s RevokeStmt) (string, error)
- func (c *Compiler) CompileSelect(q SelectStmt) (string, []any, error)
- func (c *Compiler) CompileSelection(selection Selection) (string, []any, error)
- func (c *Compiler) CompileSource(source Source) (string, []any, error)
- func (c *Compiler) CompileTruncate(s TruncateStmt) (string, error)
- func (c *Compiler) CompileUpdate(q UpdateStmt) (string, []any, error)
- func (c *Compiler) CompileValues(q ValuesQuery) (string, []any, error)
- type CompoundBuilder
- func (b CompoundBuilder) As(alias string) DerivedTable
- func (b CompoundBuilder) CTE(name string, opts ...CTEOption) CTE
- func (b CompoundBuilder) Except(other Query) CompoundBuilder
- func (b CompoundBuilder) ExceptAll(other Query) CompoundBuilder
- func (b CompoundBuilder) Intersect(other Query) CompoundBuilder
- func (b CompoundBuilder) IntersectAll(other Query) CompoundBuilder
- func (b CompoundBuilder) Limit(n int) CompoundBuilder
- func (b CompoundBuilder) Offset(n int) CompoundBuilder
- func (b CompoundBuilder) OrderBy(terms ...OrderTerm) CompoundBuilder
- func (b CompoundBuilder) SQLSource() SourceExpression
- func (b CompoundBuilder) Stmt() CompoundStmt
- func (b CompoundBuilder) ToSQL(dialect Dialect) (string, []any, error)
- func (b CompoundBuilder) Union(other Query) CompoundBuilder
- func (b CompoundBuilder) UnionAll(other Query) CompoundBuilder
- type CompoundStmt
- type ConcatExpression
- type Concatenator
- type ConflictClause
- type CountExpression
- type CreateEnumStmt
- type CreateExtensionBuilder
- type CreateExtensionStmt
- type CreateFunctionBuilder
- func (b CreateFunctionBuilder) Arg(name, typ string) CreateFunctionBuilder
- func (b CreateFunctionBuilder) Args(args ...FunctionArg) CreateFunctionBuilder
- func (b CreateFunctionBuilder) Body(body string) CreateFunctionBuilder
- func (b CreateFunctionBuilder) Language(language string) CreateFunctionBuilder
- func (b CreateFunctionBuilder) Option(options ...string) CreateFunctionBuilder
- func (b CreateFunctionBuilder) OrReplace() CreateFunctionBuilder
- func (b CreateFunctionBuilder) Returns(returnType string) CreateFunctionBuilder
- func (b CreateFunctionBuilder) Stmt() CreateFunctionStmt
- func (b CreateFunctionBuilder) ToSQL(d Dialect) (string, []any, error)
- type CreateFunctionStmt
- type CreateIndexBuilder
- type CreateIndexStmt
- type CreateMaterializedViewBuilder
- func (b CreateMaterializedViewBuilder) Columns(columns ...string) CreateMaterializedViewBuilder
- func (b CreateMaterializedViewBuilder) IfNotExists() CreateMaterializedViewBuilder
- func (b CreateMaterializedViewBuilder) Stmt() CreateMaterializedViewStmt
- func (b CreateMaterializedViewBuilder) ToSQL(d Dialect) (string, []any, error)
- func (b CreateMaterializedViewBuilder) WithNoData() CreateMaterializedViewBuilder
- type CreateMaterializedViewStmt
- type CreateSchemaBuilder
- type CreateSchemaStmt
- type CreateSequenceBuilder
- func (b CreateSequenceBuilder) Cache(n int64) CreateSequenceBuilder
- func (b CreateSequenceBuilder) Cycle() CreateSequenceBuilder
- func (b CreateSequenceBuilder) IfNotExists() CreateSequenceBuilder
- func (b CreateSequenceBuilder) Increment(n int64) CreateSequenceBuilder
- func (b CreateSequenceBuilder) MaxValue(n int64) CreateSequenceBuilder
- func (b CreateSequenceBuilder) MinValue(n int64) CreateSequenceBuilder
- func (b CreateSequenceBuilder) NoCycle() CreateSequenceBuilder
- func (b CreateSequenceBuilder) NoMaxValue() CreateSequenceBuilder
- func (b CreateSequenceBuilder) NoMinValue() CreateSequenceBuilder
- func (b CreateSequenceBuilder) OwnedBy(column string) CreateSequenceBuilder
- func (b CreateSequenceBuilder) Start(n int64) CreateSequenceBuilder
- func (b CreateSequenceBuilder) Stmt() CreateSequenceStmt
- func (b CreateSequenceBuilder) ToSQL(d Dialect) (string, []any, error)
- type CreateSequenceStmt
- type CreateTableBuilder
- func (b CreateTableBuilder) Check(name string, expr Expression) CreateTableBuilder
- func (b CreateTableBuilder) Column(c ColumnDef) CreateTableBuilder
- func (b CreateTableBuilder) Comment(text string) CreateTableBuilder
- func (b CreateTableBuilder) ForeignKey(fk ForeignKeyConstraint) CreateTableBuilder
- func (b CreateTableBuilder) IfNotExists() CreateTableBuilder
- func (b CreateTableBuilder) Index(name string, columns ...string) CreateTableBuilder
- func (b CreateTableBuilder) PrimaryKey(columns ...string) CreateTableBuilder
- func (b CreateTableBuilder) Stmt() CreateTableStmt
- func (b CreateTableBuilder) Temporary() CreateTableBuilder
- func (b CreateTableBuilder) ToSQL(d Dialect) (string, []any, error)
- func (b CreateTableBuilder) Unique(name string, columns ...string) CreateTableBuilder
- type CreateTableStmt
- type CreateViewBuilder
- type CreateViewStmt
- type DeleteBuilder
- func (b DeleteBuilder) Join(source Source, on Expression) DeleteBuilder
- func (b DeleteBuilder) LeftJoin(source Source, on Expression) DeleteBuilder
- func (b DeleteBuilder) Limit(n int) DeleteBuilder
- func (b DeleteBuilder) OrderBy(terms ...OrderTerm) DeleteBuilder
- func (b DeleteBuilder) Returning(selections ...Selection) DeleteBuilder
- func (b DeleteBuilder) Stmt() DeleteStmt
- func (b DeleteBuilder) ToSQL(dialect Dialect) (string, []any, error)
- func (b DeleteBuilder) Using(sources ...Source) DeleteBuilder
- func (b DeleteBuilder) Where(expr Expression) DeleteBuilder
- func (b DeleteBuilder) WithCTE(ctes ...CTE) DeleteBuilder
- type DeleteStmt
- type DerivedTable
- type DerivedValuesUnionDialect
- type Dialect
- type DistinctOnDialect
- type DistinctPredicate
- type DropExtensionBuilder
- type DropExtensionStmt
- type DropForeignKeyStmt
- type DropFunctionBuilder
- func (b DropFunctionBuilder) ArgTypes(types ...string) DropFunctionBuilder
- func (b DropFunctionBuilder) Cascade() DropFunctionBuilder
- func (b DropFunctionBuilder) IfExists() DropFunctionBuilder
- func (b DropFunctionBuilder) Restrict() DropFunctionBuilder
- func (b DropFunctionBuilder) Stmt() DropFunctionStmt
- func (b DropFunctionBuilder) ToSQL(d Dialect) (string, []any, error)
- type DropFunctionStmt
- type DropIndexStmt
- type DropMaterializedViewBuilder
- type DropMaterializedViewStmt
- type DropSchemaBuilder
- type DropSchemaStmt
- type DropSequenceBuilder
- type DropSequenceStmt
- type DropTableBuilder
- type DropTableStmt
- type DropTypeBuilder
- type DropTypeStmt
- type DropViewBuilder
- type DropViewStmt
- type EngineType
- type ExcludedExpression
- type ExcludedRenderer
- type ExistsExpression
- type Expression
- type ExtractExpression
- type FTSMode
- type FieldExpression
- type ForeignKeyConstraint
- type FullTextSearcher
- type FuncExpression
- type FuncRenderer
- type FunctionArg
- type GeneratedColumn
- type GrantBuilder
- func (b GrantBuilder) On(objects ...string) GrantBuilder
- func (b GrantBuilder) OnType(objectType string, objects ...string) GrantBuilder
- func (b GrantBuilder) Stmt() GrantStmt
- func (b GrantBuilder) To(grantees ...string) GrantBuilder
- func (b GrantBuilder) ToSQL(d Dialect) (string, []any, error)
- func (b GrantBuilder) WithGrantOption() GrantBuilder
- type GrantStmt
- type GroupingExpression
- type GroupingSetsExpression
- type ILikeExpression
- type Ident
- type IdentityKind
- type InExpression
- type InsertBuilder
- func (b InsertBuilder) ColumnCount() int
- func (b InsertBuilder) Columns(columns ...string) InsertBuilder
- func (b InsertBuilder) DoNothing() InsertBuilder
- func (b InsertBuilder) DoUpdate(assignments ...Assignment) InsertBuilder
- func (b InsertBuilder) FromSelect(query Query) InsertBuilder
- func (b InsertBuilder) OnConflict(columns ...string) InsertBuilder
- func (b InsertBuilder) OnConflictConstraint(name string) InsertBuilder
- func (b InsertBuilder) OnConflictExpr(exprs ...Expression) InsertBuilder
- func (b InsertBuilder) Returning(selections ...Selection) InsertBuilder
- func (b InsertBuilder) SplitRows(n int) []InsertBuilder
- func (b InsertBuilder) Stmt() InsertStmt
- func (b InsertBuilder) ToSQL(dialect Dialect) (string, []any, error)
- func (b InsertBuilder) Values(values ...any) InsertBuilder
- func (b InsertBuilder) Where(predicate Expression) InsertBuilder
- type InsertStmt
- type JSONAccessExpression
- type JSONAccessor
- type JSONObjectExpression
- type JSONObjectRenderer
- type JoinClause
- type JoinedUpdateDeleter
- type LockOption
- type LockTablesStmt
- type LogicalExpression
- type MatchBuilder
- type MatchExpression
- type MergeBuilder
- func (b MergeBuilder) As(alias string) MergeBuilder
- func (b MergeBuilder) On(condition Expression) MergeBuilder
- func (b MergeBuilder) Returning(selections ...Selection) MergeBuilder
- func (b MergeBuilder) Stmt() MergeStmt
- func (b MergeBuilder) ToSQL(dialect Dialect) (string, []any, error)
- func (b MergeBuilder) Using(source Source) MergeBuilder
- func (b MergeBuilder) When(whens ...MergeWhen) MergeBuilder
- func (b MergeBuilder) WithCTE(ctes ...CTE) MergeBuilder
- type MergeDialect
- type MergeStmt
- type MergeWhen
- type MergeWhenClause
- type MySQLDialect
- func (d MySQLDialect) AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
- func (MySQLDialect) ColumnCommentStatement(string, string, string) string
- func (MySQLDialect) ColumnType(name string, length, precision, scale int) string
- func (MySQLDialect) Concat(operands []string) string
- func (MySQLDialect) DropForeignKey(qualifiedTable, quotedConstraint string) string
- func (MySQLDialect) DropIndex(_, quotedIndex, qualifiedTable string) string
- func (d MySQLDialect) Excluded(column string) string
- func (MySQLDialect) InlineColumnComment(comment string) string
- func (MySQLDialect) InlineTableComment(comment string) string
- func (MySQLDialect) IsDistinctFrom(left, right string, negate bool) string
- func (MySQLDialect) JSONAccess(operand string, path []any, asText bool) (string, error)
- func (MySQLDialect) JSONObject(funcName string, pairs [][2]string) string
- func (MySQLDialect) LockClause(strength, of, wait string) (string, error)
- func (MySQLDialect) Match(columns []string, query string, boolean bool, _ string) (string, error)
- func (MySQLDialect) MaxBindParams() int
- func (MySQLDialect) Name() string
- func (MySQLDialect) Placeholder(int) string
- func (d MySQLDialect) QuoteIdent(identifier string) string
- func (MySQLDialect) QuoteName(name string) string
- func (MySQLDialect) Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
- func (MySQLDialect) StringAgg(arg, delimiter string) string
- func (MySQLDialect) SupportsReturning() bool
- func (MySQLDialect) TableCommentStatement(string, string) string
- func (MySQLDialect) Upsert(cl UpsertClause) (string, error)
- func (MySQLDialect) UsesInlineJoins() bool
- func (MySQLDialect) UsesValuesUnion() bool
- type NamedWindow
- type Node
- type NotExpression
- type NullPredicate
- type NullSafeEqualityDialect
- type NullsOrderingDialect
- type OrderTerm
- type PositionExpression
- type PostgreSQLDialect
- func (PostgreSQLDialect) ArrayConstructor(elements []string) string
- func (PostgreSQLDialect) AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
- func (p PostgreSQLDialect) ColumnCommentStatement(quotedTable, quotedColumn, comment string) string
- func (PostgreSQLDialect) ColumnType(name string, length, precision, scale int) string
- func (PostgreSQLDialect) DropForeignKey(qualifiedTable, quotedConstraint string) string
- func (PostgreSQLDialect) DropIndex(qualifiedIndex, _, _ string) string
- func (PostgreSQLDialect) ILike(left, pattern string) string
- func (PostgreSQLDialect) InlineColumnComment(string) string
- func (PostgreSQLDialect) InlineTableComment(string) string
- func (PostgreSQLDialect) JSONAccess(operand string, path []any, asText bool) (string, error)
- func (PostgreSQLDialect) LockClause(strength, of, wait string) (string, error)
- func (PostgreSQLDialect) Match(columns []string, query string, boolean bool, config string) (string, error)
- func (PostgreSQLDialect) MaxBindParams() int
- func (PostgreSQLDialect) Name() string
- func (PostgreSQLDialect) Placeholder(position int) string
- func (d PostgreSQLDialect) QuoteIdent(identifier string) string
- func (PostgreSQLDialect) QuoteName(name string) string
- func (PostgreSQLDialect) Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
- func (PostgreSQLDialect) SimilarTo(left, pattern string, negate bool) string
- func (PostgreSQLDialect) SupportsDistinctOn() bool
- func (PostgreSQLDialect) SupportsMerge() bool
- func (PostgreSQLDialect) SupportsNullsOrdering() bool
- func (PostgreSQLDialect) SupportsReturning() bool
- func (p PostgreSQLDialect) TableCommentStatement(quotedTable, comment string) string
- func (PostgreSQLDialect) Upsert(cl UpsertClause) (string, error)
- func (d PostgreSQLDialect) ValuesCastType(value any) (string, bool)
- type QuantifiedArrayExpression
- type QuantifiedExpression
- type Query
- type Quoter
- type RawExpression
- type RawQuery
- type RawType
- type RefreshMaterializedViewBuilder
- func (b RefreshMaterializedViewBuilder) Concurrently() RefreshMaterializedViewBuilder
- func (b RefreshMaterializedViewBuilder) Stmt() RefreshMaterializedViewStmt
- func (b RefreshMaterializedViewBuilder) ToSQL(d Dialect) (string, []any, error)
- func (b RefreshMaterializedViewBuilder) WithNoData() RefreshMaterializedViewBuilder
- type RefreshMaterializedViewStmt
- type RegexpExpression
- type RegexpMatcher
- type RenameColumnStmt
- type RenameTableStmt
- type RevokeBuilder
- func (b RevokeBuilder) Cascade() RevokeBuilder
- func (b RevokeBuilder) From(grantees ...string) RevokeBuilder
- func (b RevokeBuilder) GrantOptionFor() RevokeBuilder
- func (b RevokeBuilder) On(objects ...string) RevokeBuilder
- func (b RevokeBuilder) OnType(objectType string, objects ...string) RevokeBuilder
- func (b RevokeBuilder) Restrict() RevokeBuilder
- func (b RevokeBuilder) Stmt() RevokeStmt
- func (b RevokeBuilder) ToSQL(d Dialect) (string, []any, error)
- type RevokeStmt
- type RowExpression
- type RowLocker
- type ScalarSubqueryExpression
- type SelectBuilder
- func (b SelectBuilder) As(alias string) DerivedTable
- func (b SelectBuilder) CTE(name string, opts ...CTEOption) CTE
- func (b SelectBuilder) CrossJoin(source Source) SelectBuilder
- func (b SelectBuilder) Distinct() SelectBuilder
- func (b SelectBuilder) DistinctOn(exprs ...Expression) SelectBuilder
- func (b SelectBuilder) Except(other Query) CompoundBuilder
- func (b SelectBuilder) ExceptAll(other Query) CompoundBuilder
- func (b SelectBuilder) ForKeyShare(opts ...LockOption) SelectBuilder
- func (b SelectBuilder) ForNoKeyUpdate(opts ...LockOption) SelectBuilder
- func (b SelectBuilder) ForShare(opts ...LockOption) SelectBuilder
- func (b SelectBuilder) ForUpdate(opts ...LockOption) SelectBuilder
- func (b SelectBuilder) From(source Source) SelectBuilder
- func (b SelectBuilder) FullJoin(source Source, on Expression) SelectBuilder
- func (b SelectBuilder) GroupBy(exprs ...Expression) SelectBuilder
- func (b SelectBuilder) Having(expr Expression) SelectBuilder
- func (b SelectBuilder) Intersect(other Query) CompoundBuilder
- func (b SelectBuilder) IntersectAll(other Query) CompoundBuilder
- func (b SelectBuilder) Join(source Source, on Expression) SelectBuilder
- func (b SelectBuilder) JoinUsing(source Source, columns ...string) SelectBuilder
- func (b SelectBuilder) LeftJoin(source Source, on Expression) SelectBuilder
- func (b SelectBuilder) LeftJoinUsing(source Source, columns ...string) SelectBuilder
- func (b SelectBuilder) Limit(n int) SelectBuilder
- func (b SelectBuilder) NaturalJoin(source Source) SelectBuilder
- func (b SelectBuilder) NaturalLeftJoin(source Source) SelectBuilder
- func (b SelectBuilder) Offset(n int) SelectBuilder
- func (b SelectBuilder) OrderBy(terms ...OrderTerm) SelectBuilder
- func (b SelectBuilder) RightJoin(source Source, on Expression) SelectBuilder
- func (b SelectBuilder) SQLSource() SourceExpression
- func (b SelectBuilder) Stmt() SelectStmt
- func (b SelectBuilder) ToSQL(dialect Dialect) (string, []any, error)
- func (b SelectBuilder) Union(other Query) CompoundBuilder
- func (b SelectBuilder) UnionAll(other Query) CompoundBuilder
- func (b SelectBuilder) Where(expr Expression) SelectBuilder
- func (b SelectBuilder) Window(defs ...NamedWindow) SelectBuilder
- func (b SelectBuilder) WithCTE(ctes ...CTE) SelectBuilder
- type SelectStmt
- type Selection
- type SetStmt
- type SetVar
- type SimilarToExpression
- type SimilarToMatcher
- type Source
- type SourceExpression
- func Alias(query Query, alias string) SourceExpression
- func Lateral(source Source) SourceExpression
- func SourceAlias(source Source, alias string) SourceExpression
- func Subquery(query Query, alias string) SourceExpression
- func ValuesSource(rows [][]Expression, alias string, columns ...string) SourceExpression
- type StandardSQLDialect
- func (d StandardSQLDialect) AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
- func (StandardSQLDialect) ColumnCommentStatement(string, string, string) string
- func (StandardSQLDialect) ColumnType(name string, length, precision, scale int) string
- func (StandardSQLDialect) DropForeignKey(qualifiedTable, quotedConstraint string) string
- func (StandardSQLDialect) DropIndex(qualifiedIndex, _, _ string) string
- func (StandardSQLDialect) InlineColumnComment(string) string
- func (StandardSQLDialect) InlineTableComment(string) string
- func (StandardSQLDialect) JSONAccess(operand string, path []any, asText bool) (string, error)
- func (StandardSQLDialect) Name() string
- func (StandardSQLDialect) Placeholder(int) string
- func (d StandardSQLDialect) QuoteIdent(identifier string) string
- func (StandardSQLDialect) QuoteName(name string) string
- func (StandardSQLDialect) Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
- func (StandardSQLDialect) RenderFunc(name string, args []string) (string, bool)
- func (StandardSQLDialect) SimilarTo(left, pattern string, negate bool) string
- func (StandardSQLDialect) SupportsMerge() bool
- func (StandardSQLDialect) SupportsNullsOrdering() bool
- func (StandardSQLDialect) SupportsReturning() bool
- func (StandardSQLDialect) TableCommentStatement(string, string) string
- type StarSelection
- type Statement
- type Statements
- type StringAggExpression
- type StringAggregator
- type SubscriptExpression
- type SubscriptIndex
- type Table
- type TableCheck
- type TableDef
- type TableIndex
- type TableLock
- type TableLockMode
- type TableUnique
- type TransactionStmt
- type TruncateBuilder
- type TruncateStmt
- type UnaryExpression
- type UnlockTablesStmt
- type UpdateBuilder
- func (b UpdateBuilder) From(sources ...Source) UpdateBuilder
- func (b UpdateBuilder) Join(source Source, on Expression) UpdateBuilder
- func (b UpdateBuilder) LeftJoin(source Source, on Expression) UpdateBuilder
- func (b UpdateBuilder) Limit(n int) UpdateBuilder
- func (b UpdateBuilder) OrderBy(terms ...OrderTerm) UpdateBuilder
- func (b UpdateBuilder) Returning(selections ...Selection) UpdateBuilder
- func (b UpdateBuilder) Set(assignments ...Assignment) UpdateBuilder
- func (b UpdateBuilder) Stmt() UpdateStmt
- func (b UpdateBuilder) ToSQL(dialect Dialect) (string, []any, error)
- func (b UpdateBuilder) Where(expr Expression) UpdateBuilder
- func (b UpdateBuilder) WithCTE(ctes ...CTE) UpdateBuilder
- type UpdateStmt
- type UpsertClause
- type UpsertRenderer
- type UseStmt
- type ValueExpression
- type ValuesCaster
- type ValuesClause
- type ValuesQuery
- type Visitor
- type WhenClause
- type WindowExpression
- func (e WindowExpression) Frame(frame string) WindowExpression
- func (e WindowExpression) Named(name string) WindowExpression
- func (e WindowExpression) OrderBy(terms ...OrderTerm) WindowExpression
- func (e WindowExpression) PartitionBy(exprs ...Expression) WindowExpression
- func (p WindowExpression) Pos() int
- func (WindowExpression) SQLExpression()
- func (WindowExpression) SQLSelection()
Constants ¶
const NoPos = -1
NoPos is what Pos reports for a node with no recorded source position — one built with the query builders rather than parsed. It is -1 so that byte offset 0 (the very start of the source, where a top-level statement begins) is a real, distinct position rather than colliding with "no position".
Variables ¶
var ( // Coalesce creates COALESCE(args...), the first non-NULL argument. Coalesce = makeFunc("COALESCE") // NullIf creates NULLIF(a, b), NULL when a equals b and a otherwise. NullIf = makeFunc("NULLIF") // Greatest creates GREATEST(args...), the largest of its arguments. Greatest = makeFunc("GREATEST") // Least creates LEAST(args...), the smallest of its arguments. Least = makeFunc("LEAST") )
var ( // Sum creates a SUM(expr) aggregate. Sum = makeFunc("SUM") // Avg creates an AVG(expr) aggregate. Avg = makeFunc("AVG") // Min creates a MIN(expr) aggregate. Min = makeFunc("MIN") // Max creates a MAX(expr) aggregate. Max = makeFunc("MAX") // BitAnd creates a BIT_AND(expr) aggregate, the bitwise AND of all values. BitAnd = makeFunc("BIT_AND") // BitOr creates a BIT_OR(expr) aggregate, the bitwise OR of all values. BitOr = makeFunc("BIT_OR") // StdDev creates a STDDEV(expr) aggregate, the sample standard deviation (an // alias of StdDevSamp on PostgreSQL and MySQL). StdDev = makeFunc("STDDEV") // StdDevPop creates a STDDEV_POP(expr) aggregate, the population standard // deviation. StdDevPop = makeFunc("STDDEV_POP") // StdDevSamp creates a STDDEV_SAMP(expr) aggregate, the sample standard // deviation. StdDevSamp = makeFunc("STDDEV_SAMP") // Variance creates a VARIANCE(expr) aggregate, the sample variance (an alias // of VarSamp on PostgreSQL and MySQL). Variance = makeFunc("VARIANCE") // VarPop creates a VAR_POP(expr) aggregate, the population variance. VarPop = makeFunc("VAR_POP") // VarSamp creates a VAR_SAMP(expr) aggregate, the sample variance. VarSamp = makeFunc("VAR_SAMP") )
var ( // Lower creates LOWER(s), the lowercase form of a string. Lower = makeFunc("LOWER") // Upper creates UPPER(s), the uppercase form of a string. Upper = makeFunc("UPPER") // Length creates LENGTH(s). Note the engines disagree on the unit: PostgreSQL // counts characters while MySQL counts bytes. Use CharLength for a portable // character count. Length = makeFunc("LENGTH") // CharLength creates CHAR_LENGTH(s), the number of characters in a string. It // is the portable character count (PostgreSQL and MySQL agree), unlike Length. CharLength = makeFunc("CHAR_LENGTH") // Trim creates TRIM(s), the string with leading and trailing spaces removed. Trim = makeFunc("TRIM") // Ltrim creates LTRIM(s), the string with leading spaces removed. Ltrim = makeFunc("LTRIM") // Rtrim creates RTRIM(s), the string with trailing spaces removed. Rtrim = makeFunc("RTRIM") // Reverse creates REVERSE(s), the string with its characters reversed. Reverse = makeFunc("REVERSE") // Md5 creates MD5(s), the hex MD5 hash of a string. Md5 = makeFunc("MD5") // Ascii creates ASCII(s), the numeric code of the first character of a string. Ascii = makeFunc("ASCII") // Left creates LEFT(s, n), the leftmost n characters of a string. Left = makeFunc("LEFT") // Right creates RIGHT(s, n), the rightmost n characters of a string. Right = makeFunc("RIGHT") // Repeat creates REPEAT(s, n), the string repeated n times. Repeat = makeFunc("REPEAT") // Replace creates REPLACE(s, from, to), s with every occurrence of from // replaced by to. Replace = makeFunc("REPLACE") // Lpad creates LPAD(s, length, fill), s left-padded with fill to length. Lpad = makeFunc("LPAD") // Rpad creates RPAD(s, length, fill), s right-padded with fill to length. Rpad = makeFunc("RPAD") // Substring creates SUBSTRING(s, start[, length]), a substring of s from the // 1-based start, as in Substring(Col("name"), 1, 3). Substring = makeFunc("SUBSTRING") // ConcatWs creates CONCAT_WS(separator, args...), the arguments joined with // the separator (NULL arguments are skipped). For plain concatenation that // renders portably as PostgreSQL's || operator, prefer Concat. ConcatWs = makeFunc("CONCAT_WS") )
var ( // Abs creates ABS(x), the absolute value of a number. Abs = makeFunc("ABS") // Ceil creates CEIL(x), the smallest integer not less than x. Ceil = makeFunc("CEIL") // Floor creates FLOOR(x), the largest integer not greater than x. Floor = makeFunc("FLOOR") // Sqrt creates SQRT(x), the square root of x. Sqrt = makeFunc("SQRT") // Exp creates EXP(x), e raised to the x power. Exp = makeFunc("EXP") // Ln creates LN(x), the natural logarithm of x. Ln = makeFunc("LN") // Sign creates SIGN(x), -1, 0, or 1 according to the sign of x. Sign = makeFunc("SIGN") // Sin creates SIN(x), the sine of x (radians). Sin = makeFunc("SIN") // Cos creates COS(x), the cosine of x (radians). Cos = makeFunc("COS") // Tan creates TAN(x), the tangent of x (radians). Tan = makeFunc("TAN") // Cot creates COT(x), the cotangent of x (radians). Cot = makeFunc("COT") // Asin creates ASIN(x), the arc sine of x (radians). Asin = makeFunc("ASIN") // Acos creates ACOS(x), the arc cosine of x (radians). Acos = makeFunc("ACOS") // Atan creates ATAN(x), the arc tangent of x (radians). Atan = makeFunc("ATAN") // Degrees creates DEGREES(x), radians x converted to degrees. Degrees = makeFunc("DEGREES") // Radians creates RADIANS(x), degrees x converted to radians. Radians = makeFunc("RADIANS") // Pi creates PI(), the constant pi. Pi = makeFunc("PI") // Power creates POWER(x, y), x raised to the y power. Power = makeFunc("POWER") // Atan2 creates ATAN2(y, x), the arc tangent of y/x using the signs of both // to pick the quadrant. Atan2 = makeFunc("ATAN2") // Round creates ROUND(x[, places]), x rounded to the given number of decimal // places (zero when omitted). Round = makeFunc("ROUND") )
var ( // RowNumber creates the ROW_NUMBER() window function. RowNumber = makeFunc("ROW_NUMBER") // Rank creates the RANK() window function. Rank = makeFunc("RANK") // DenseRank creates the DENSE_RANK() window function. DenseRank = makeFunc("DENSE_RANK") // PercentRank creates the PERCENT_RANK() window function, the relative rank in // the range [0, 1]. PercentRank = makeFunc("PERCENT_RANK") // CumeDist creates the CUME_DIST() window function, the cumulative // distribution in the range (0, 1]. CumeDist = makeFunc("CUME_DIST") // Ntile creates the NTILE(buckets) window function, which distributes the // partition's rows into the given number of ranked buckets. Ntile = makeFunc("NTILE") // Lag creates the LAG(expr) window function, the value from a preceding row. Lag = makeFunc("LAG") // Lead creates the LEAD(expr) window function, the value from a following row. Lead = makeFunc("LEAD") // FirstValue creates the FIRST_VALUE(expr) window function, the value from the // first row of the window frame. FirstValue = makeFunc("FIRST_VALUE") // LastValue creates the LAST_VALUE(expr) window function, the value from the // last row of the window frame. LastValue = makeFunc("LAST_VALUE") // NthValue creates the NTH_VALUE(expr, n) window function, the value from the // nth row of the window frame. NthValue = makeFunc("NTH_VALUE") )
var JSONArray = makeFunc("JSON_ARRAY")
JSONArray creates a JSON_ARRAY(args...) expression that builds a JSON array from its arguments. The name is SQL/JSON standard (PostgreSQL 16+, MySQL 5.7+); on older PostgreSQL use Func("json_build_array", ...).
var JSONArrayAgg = makeFunc("JSON_ARRAYAGG")
JSONArrayAgg creates a JSON_ARRAYAGG(expr) aggregate that collects the grouped values into a JSON array (PostgreSQL 16+, MySQL 5.7.22+; older PostgreSQL has json_agg / jsonb_agg via Func).
var Now = makeFunc("NOW")
Now creates NOW(), the current date and time (PostgreSQL and MySQL both spell it NOW()).
Functions ¶
func CompileInline ¶
CompileInline compiles q to a single SQL string with every bound value rendered inline as a literal instead of a placeholder, so the result carries no separate args. A ValueExpression marked Quoted (see Val and Quote) is single-quoted with embedded quotes doubled; a nil value is NULL; numbers and booleans render verbatim.
It is for display, logging, and snapshots — NOT for execution: the values are not parameterized, so compiling untrusted input this way risks SQL injection. Use ToSQL for anything sent to a database.
func CompileStatic ¶
func CompileStatic(dialect Dialect, expr Expression) (string, error)
CompileStatic compiles an expression that binds no values into SQL text, for static contexts such as DDL DEFAULT and CHECK clauses where bind placeholders are not allowed. It errors if expr is nil or produces bind values; wrap literals in Raw to inline them.
func Decompose ¶
Decompose reports q's immediate structural pieces for read-only analysis, without copying a snapshot of its clauses:
- onCTEName: each CTE name q declares in its own WITH clause, the scope a FROM/JOIN reference resolves against (a name in scope denotes that CTE, not a base table).
- onName: each base-table (or CTE-reference) name q references directly through a FROM/JOIN/target source.
- onChild: each query nested one level inside q — CTE bodies, subquery sources, set-operation arms, and the subqueries embedded in its expressions.
It does not recurse into nested queries: it is a single-level Walk that prunes at each child query, so callers drive the deeper recursion. Any callback may be nil. It is the public, zero-copy structural seam analysis tools build on instead of the clause-copying Parts accessors.
func IdentNames ¶
IdentNames returns the plain names of ids, the inverse of Idents — for a compiler or accessor that hands a name list back as strings.
func Inspect ¶
Inspect walks node in pre-order, calling f for each node. When f returns false Walk does not recurse into that node's children. It is the function-adapter form of Walk, the counterpart of go/ast.Inspect; f is also called once with a nil node after a node's children have been walked, so f must tolerate nil.
func Walk ¶
Walk traverses the AST rooted at node in depth-first, pre-order, mirroring go/ast.Walk. It calls v.Visit(node); if the returned visitor w is non-nil it walks each child of node with w and then calls w.Visit(nil).
It descends through the whole tree — a statement's clauses, the expressions and subqueries inside them, the FROM/JOIN sources, and on into nested queries — so a single visitor observes every node. A node kind with no modeled structure (a leaf such as a column or value, an unmodeled shape) is simply a stopping point with no children. node must satisfy Node; normalize a builder to its statement with Unwrap before walking.
func WalkExpr ¶
func WalkExpr(e Expression, visit func(Expression))
WalkExpr visits e and every expression nested within its own operands, in pre-order. It does NOT descend into embedded subqueries (a ScalarSubquery, or the subquery of an IN/EXISTS/quantified predicate): each subquery is a separate scope, walked on its own (see Walk and WalkSubqueries).
Where Walk traverses the whole tree and WalkSubqueries finds the subqueries embedded in an expression, WalkExpr is the expression-level traversal within a single scope: analysis tools build on it to collect column references or inspect predicates inside one clause.
func WalkSelectionExpr ¶
func WalkSelectionExpr(s Selection, visit func(Expression))
WalkSelectionExpr walks the expression carried by a SELECT-list item, looking through an AS alias. A "*" selection carries no expression. It is WalkExpr for a Selection, paralleling WalkSelectionSubqueries.
func WalkSelectionSubqueries ¶
WalkSelectionSubqueries is WalkSubqueries for a SELECT-list item, looking through the selection-only nodes (an AS alias, COUNT's target) that are not themselves Expressions to reach the subqueries inside.
func WalkSubqueries ¶
func WalkSubqueries(e Expression, visit func(Query))
WalkSubqueries calls visit for every subquery embedded in e and its sub-expressions: the subquery predicates (IN (subquery), EXISTS, scalar subqueries, and quantified ANY/ALL comparisons) wherever they appear, even nested inside composite predicates, CASE arms, function arguments, or window clauses. It is the basis for finding correlated and uncorrelated subqueries in WHERE / HAVING / SELECT-list and other expression positions.
visit is called with each embedded query but WalkSubqueries does not descend into that query's own structure — the caller decides whether to recurse (for example via Walk). e may be nil.
Types ¶
type AliasedSelection ¶
type AliasedSelection struct {
Selection Selection
Alias Ident
// contains filtered or unexported fields
}
AliasedSelection attaches an AS alias to a SELECT-list item.
func As ¶
func As(selection Selection, alias string) AliasedSelection
As attaches an alias to a SELECT-list item.
func (AliasedSelection) Pos ¶
func (p AliasedSelection) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (AliasedSelection) SQLSelection ¶
func (AliasedSelection) SQLSelection()
type AlterTableBuilder ¶
type AlterTableBuilder struct {
// contains filtered or unexported fields
}
AlterTableBuilder is the fluent constructor for an AlterTableStmt.
func AlterTable ¶
func AlterTable(table Table) AlterTableBuilder
AlterTable starts an ALTER TABLE builder for a table.
func (AlterTableBuilder) AddCheck ¶
func (b AlterTableBuilder) AddCheck(name string, expr Expression) AlterTableBuilder
AddCheck appends an ADD CONSTRAINT ... CHECK action. expr must bind no values.
func (AlterTableBuilder) AddColumn ¶
func (b AlterTableBuilder) AddColumn(c ColumnDef) AlterTableBuilder
AddColumn appends an ADD COLUMN action.
func (AlterTableBuilder) AddForeignKey ¶
func (b AlterTableBuilder) AddForeignKey(fk ForeignKeyConstraint) AlterTableBuilder
AddForeignKey appends an ADD CONSTRAINT ... FOREIGN KEY action.
func (AlterTableBuilder) AddPrimaryKey ¶
func (b AlterTableBuilder) AddPrimaryKey(columns ...string) AlterTableBuilder
AddPrimaryKey appends an ADD PRIMARY KEY action over the columns.
func (AlterTableBuilder) AddUnique ¶
func (b AlterTableBuilder) AddUnique(name string, columns ...string) AlterTableBuilder
AddUnique appends an ADD CONSTRAINT ... UNIQUE action over the columns. name is optional (pass "" for an unnamed constraint).
func (AlterTableBuilder) AlterColumnType ¶
func (b AlterTableBuilder) AlterColumnType(name string, t ColumnType) AlterTableBuilder
AlterColumnType appends an action that changes a column's type (PostgreSQL).
func (AlterTableBuilder) DropColumn ¶
func (b AlterTableBuilder) DropColumn(name string) AlterTableBuilder
DropColumn appends a DROP COLUMN action.
func (AlterTableBuilder) DropConstraint ¶
func (b AlterTableBuilder) DropConstraint(name string) AlterTableBuilder
DropConstraint appends a DROP CONSTRAINT action (for CHECK / UNIQUE / primary-key constraints; use DropForeignKey for foreign keys, which differ by dialect).
func (AlterTableBuilder) DropDefault ¶
func (b AlterTableBuilder) DropDefault(name string) AlterTableBuilder
DropDefault appends an action dropping a column's default (PostgreSQL).
func (AlterTableBuilder) DropNotNull ¶
func (b AlterTableBuilder) DropNotNull(name string) AlterTableBuilder
DropNotNull appends an action dropping a column's NOT NULL constraint (PostgreSQL).
func (AlterTableBuilder) DropPrimaryKey ¶
func (b AlterTableBuilder) DropPrimaryKey() AlterTableBuilder
DropPrimaryKey appends a DROP PRIMARY KEY action. MySQL spells it "DROP PRIMARY KEY"; PostgreSQL drops the constraint by its conventional "<table>_pkey" name.
func (AlterTableBuilder) RenameColumn ¶
func (b AlterTableBuilder) RenameColumn(from, to string) AlterTableBuilder
RenameColumn appends a RENAME COLUMN action.
func (AlterTableBuilder) RenameTo ¶
func (b AlterTableBuilder) RenameTo(name string) AlterTableBuilder
RenameTo appends a RENAME TO action (rename the table).
func (AlterTableBuilder) RestateColumn ¶
func (b AlterTableBuilder) RestateColumn(c ColumnDef) AlterTableBuilder
RestateColumn appends an action that restates a column's full definition (type, NOT NULL, DEFAULT). It renders the dialect's spelling at compile time: MySQL's single MODIFY COLUMN, or PostgreSQL's separate ALTER COLUMN TYPE / SET|DROP NOT NULL / SET|DROP DEFAULT actions. It is the dialect-agnostic way a migration changes a column's properties at once.
func (AlterTableBuilder) SetDefault ¶
func (b AlterTableBuilder) SetDefault(name string, expr Expression) AlterTableBuilder
SetDefault appends an action setting a column's default (PostgreSQL). expr must bind no values.
func (AlterTableBuilder) SetNotNull ¶
func (b AlterTableBuilder) SetNotNull(name string) AlterTableBuilder
SetNotNull appends an action adding a NOT NULL constraint to a column (PostgreSQL).
func (AlterTableBuilder) Stmt ¶
func (b AlterTableBuilder) Stmt() AlterTableStmt
Stmt returns the built ALTER TABLE statement.
type AlterTableStmt ¶
type AlterTableStmt struct {
Table Table
Alterations []Alteration
// contains filtered or unexported fields
}
AlterTableStmt is the AST for an ALTER TABLE statement carrying one or more ordered alterations, rendered as a single comma-separated statement.
type AlterTypeAddValueBuilder ¶
type AlterTypeAddValueBuilder struct {
// contains filtered or unexported fields
}
AlterTypeAddValueBuilder is the fluent constructor for an AlterTypeAddValueStmt.
func AlterTypeAddValue ¶
func AlterTypeAddValue(name, value string) AlterTypeAddValueBuilder
AlterTypeAddValue starts a builder that adds value to an enum type.
func (AlterTypeAddValueBuilder) After ¶
func (b AlterTypeAddValueBuilder) After(neighbor string) AlterTypeAddValueBuilder
After places the new value after an existing one.
func (AlterTypeAddValueBuilder) Before ¶
func (b AlterTypeAddValueBuilder) Before(neighbor string) AlterTypeAddValueBuilder
Before places the new value before an existing one.
func (AlterTypeAddValueBuilder) IfNotExists ¶
func (b AlterTypeAddValueBuilder) IfNotExists() AlterTypeAddValueBuilder
IfNotExists adds IF NOT EXISTS, skipping the value if it already exists.
func (AlterTypeAddValueBuilder) Stmt ¶
func (b AlterTypeAddValueBuilder) Stmt() AlterTypeAddValueStmt
Stmt returns the built ALTER TYPE ... ADD VALUE statement.
type AlterTypeAddValueStmt ¶
type AlterTypeAddValueStmt struct {
Name Ident
Value string
IfNotExists bool
Before string
After string
// contains filtered or unexported fields
}
AlterTypeAddValueStmt is the AST for an ALTER TYPE ... ADD VALUE statement, adding a label to an enum type (PostgreSQL). At most one of Before/After is set. It is a DDL Statement.
type AlterTypeRenameValueStmt ¶
type AlterTypeRenameValueStmt struct {
Name Ident
OldValue string
NewValue string
// contains filtered or unexported fields
}
AlterTypeRenameValueStmt is the AST for an ALTER TYPE ... RENAME VALUE statement. It has no options, so it is constructed directly.
func AlterTypeRenameValue ¶
func AlterTypeRenameValue(name, oldValue, newValue string) AlterTypeRenameValueStmt
AlterTypeRenameValue builds a statement that renames an enum label.
type Alteration ¶
type Alteration struct {
Kind AlterationKind
Name Ident // column or constraint name; rename's old column name
NewName Ident // rename target (column or table)
Columns []Ident // AddUnique / AddPrimaryKey columns
Column *ColumnDef // AddColumn / RestateColumn
Type ColumnType // AlterColumnType
Expression Expression // AddCheck / SetDefault
ForeignKey *ForeignKeyConstraint // AddForeignKey
NotNull bool // SetNotNull (true) / DropNotNull (false)
// contains filtered or unexported fields
}
Alteration is one ALTER TABLE action. Kind selects which fields are meaningful (see each AlterationKind). It is both the AST value carried by AlterTableStmt and the unit the AlterTableBuilder methods append.
type AlterationKind ¶
type AlterationKind int
AlterationKind identifies which ALTER TABLE action an Alteration describes.
const ( // AlterAddColumn is ADD COLUMN; Column is set. AlterAddColumn AlterationKind = iota // AlterDropColumn is DROP COLUMN; Name is the column. AlterDropColumn // AlterAddForeignKey is ADD CONSTRAINT ... FOREIGN KEY; ForeignKey is set. AlterAddForeignKey // AlterAddCheck is ADD CONSTRAINT ... CHECK; Name and Expression are set. AlterAddCheck // AlterAddUnique is ADD CONSTRAINT ... UNIQUE; Name (optional) and Columns are set. AlterAddUnique // AlterDropConstraint is DROP CONSTRAINT; Name is the constraint. AlterDropConstraint // AlterColumnType changes a column's type; Name and Type are set. AlterColumnType // AlterSetNotNull adds NOT NULL; Name is the column and NotNull is true. AlterSetNotNull // AlterDropNotNull drops NOT NULL; Name is the column and NotNull is false. AlterDropNotNull // AlterSetDefault sets a column default; Name and Expression are set. AlterSetDefault // AlterDropDefault drops a column default; Name is the column. AlterDropDefault // AlterRenameColumn renames a column; Name is the old name and NewName the new. AlterRenameColumn // AlterRenameTable renames the table; NewName is the new table name. AlterRenameTable // AlterRestateColumn restates a column's full definition; Column is set. AlterRestateColumn // AlterAddPrimaryKey adds a primary key; Columns are the key columns. AlterAddPrimaryKey // AlterDropPrimaryKey drops the primary key. AlterDropPrimaryKey )
type ArrayDialect ¶
type ArrayDialect interface {
// ArrayConstructor renders an ARRAY[...] literal from already-compiled
// element fragments.
ArrayConstructor(elements []string) string
}
ArrayDialect is an optional capability for dialects with a first-class array type and the ARRAY[...] constructor / "op ANY(array)" comparison (PostgreSQL). MySQL has no array type and rejects array expressions (ArrayExpression, QuantifiedArrayExpression) at compile time. The compiler detects it with a type assertion, so it is not a breaking change to Dialect.
type ArrayExpression ¶
type ArrayExpression struct {
Elements []Expression
// contains filtered or unexported fields
}
ArrayExpression is an ARRAY[...] constructor. Arrays are non-portable — PostgreSQL has a first-class array type, MySQL does not — so it renders through an ArrayDialect and a dialect without that capability rejects it at compile time.
func Array ¶
func Array(elements ...any) ArrayExpression
Array creates an ARRAY[...] constructor. Non-expression elements become bind values.
func (ArrayExpression) Pos ¶
func (p ArrayExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ArrayExpression) SQLExpression ¶
func (ArrayExpression) SQLExpression()
func (ArrayExpression) SQLSelection ¶
func (ArrayExpression) SQLSelection()
type Assignment ¶
type Assignment struct {
Column Ident
Target Expression
Value Expression
// contains filtered or unexported fields
}
Assignment is one SET clause item in UPDATE, or a column/value pair in INSERT. Target, when non-nil, is the assignment's left-hand side (e.g. a subscripted column col[i]); otherwise Column names the assigned column.
func Set ¶
func Set(column string, value any) Assignment
Set creates an assignment. A non-expression value becomes a bind value.
func SetAt ¶
func SetAt(target Expression, value any) Assignment
SetAt creates an assignment to a subscripted (or otherwise indirected) target, such as an array element or jsonb key: SetAt(Subscript(Col("data"), 1), v) renders "data"[1] = v.
type AutoIncrementColumnType ¶
type AutoIncrementColumnType interface {
ColumnType
RenderAutoIncrement(d Dialect) (string, bool)
}
AutoIncrementColumnType is an optional capability of a ColumnType: rendering an auto-incrementing integer clause (serial / AUTO_INCREMENT) for a dialect. A ColumnDef with AutoIncrement set uses it when its Type implements it, otherwise the column falls back to its plain type. EngineType implements it, as does the deferred type the meta package builds from a schema, so schema tables can render their serial primary keys.
type BetweenExpression ¶
type BetweenExpression struct {
Operand Expression
Low Expression
High Expression
Negate bool
// contains filtered or unexported fields
}
BetweenExpression tests whether an operand falls within an inclusive range.
func Between ¶
func Between(operand, low, high any) BetweenExpression
Between creates an "operand BETWEEN low AND high" expression (inclusive). Non-expression bounds become bind values.
func NotBetween ¶
func NotBetween(operand, low, high any) BetweenExpression
NotBetween creates an "operand NOT BETWEEN low AND high" expression.
func (BetweenExpression) Pos ¶
func (p BetweenExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (BetweenExpression) SQLExpression ¶
func (BetweenExpression) SQLExpression()
type BinaryExpression ¶
type BinaryExpression struct {
Left Expression
Operator string
Right Expression
// contains filtered or unexported fields
}
BinaryExpression combines two expressions with an operator.
func Add ¶
func Add(left, right any) BinaryExpression
Add creates an "a + b" arithmetic expression. Non-expression operands become bind values.
func Eq ¶
func Eq(left, right any) BinaryExpression
Eq creates an equality expression. Non-expression operands are converted to bind values so callers can write Eq(Col("id"), 123).
func Ge ¶
func Ge(left, right any) BinaryExpression
Ge creates a "greater than or equal" expression.
func NotLike ¶
func NotLike(left, pattern any) BinaryExpression
NotLike creates a NOT LIKE expression.
func (BinaryExpression) Pos ¶
func (p BinaryExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (BinaryExpression) SQLExpression ¶
func (BinaryExpression) SQLExpression()
func (BinaryExpression) SQLSelection ¶
func (BinaryExpression) SQLSelection()
type BindParamLimiter ¶
type BindParamLimiter interface {
MaxBindParams() int
}
BindParamLimiter is an optional capability a Dialect implements to report the maximum number of bind parameters a single statement may carry. Both PostgreSQL and MySQL cap this at 65535, because the parameter count is a 16-bit field in their wire protocols. sqlkit reads it (through a Database configured to auto-detect) to split bulk INSERTs and chunk large IN lists so a statement never exceeds the limit; the compiler does not need it, so adding it is not a breaking change to Dialect.
type CTE ¶
type CTE struct {
// contains filtered or unexported fields
}
CTE is a named common table expression built from a query with Query.CTE. A CTE doubles as a FROM/JOIN source and a handle for referencing its output columns (Col). Attach it to a statement with WithCTE, which emits a leading WITH clause:
active := Select(Col("id")).From(users).Where(...).CTE("active")
Select(active.Col("id")).From(active).WithCTE(active)
func (CTE) Col ¶
func (c CTE) Col(name string) ColumnExpression
Col references one of the CTE's output columns, qualified by the CTE name.
func (CTE) IsRecursive ¶
IsRecursive reports whether the CTE was declared recursive.
func (CTE) OutputColumns ¶
OutputColumns returns the CTE's explicit output column list, or nil when none was declared.
func (CTE) Pos ¶
func (p CTE) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (CTE) SQLSource ¶
func (c CTE) SQLSource() SourceExpression
SQLSource lets a CTE be used as a FROM/JOIN source, referenced by name.
type CTEOption ¶
type CTEOption func(*cteOptions)
CTEOption configures a CTE created with Query.CTE.
func Columns ¶
Columns declares an explicit output column list for the CTE, e.g. q.CTE("totals", Columns("org_id", "n")).
func Recursive ¶
func Recursive() CTEOption
Recursive marks the CTE as recursive. A WITH block containing any recursive CTE is emitted as WITH RECURSIVE. Build the recursive term by combining the base query with Union/UnionAll before calling CTE, referencing the CTE by its name (a plain Table/Col reference).
type CaseExpression ¶
type CaseExpression struct {
Operand Expression
Whens []WhenClause
ElseValue Expression
// contains filtered or unexported fields
}
CaseExpression is a CASE expression in either form. With Operand nil it is a searched CASE — CASE WHEN cond THEN result [...] [ELSE result] END — whose When arms hold boolean conditions. With Operand set it is a simple CASE — CASE operand WHEN value THEN result [...] [ELSE result] END — whose When arms hold values compared for equality against the operand.
func Case ¶
func Case() CaseExpression
Case starts a searched CASE expression; chain When and Else to build it.
func CaseOf ¶
func CaseOf(operand any) CaseExpression
CaseOf starts a simple CASE expression that compares operand for equality against each When value: CASE operand WHEN value THEN result ... END. A non-expression operand becomes a bind value.
func If ¶
func If(condition, then, els any) CaseExpression
If creates the two-armed CASE expression CASE WHEN condition THEN then ELSE els END, like SQL IF().
func (CaseExpression) Else ¶
func (e CaseExpression) Else(result any) CaseExpression
Else sets the ELSE result.
func (CaseExpression) Pos ¶
func (p CaseExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (CaseExpression) SQLExpression ¶
func (CaseExpression) SQLExpression()
func (CaseExpression) SQLSelection ¶
func (CaseExpression) SQLSelection()
func (CaseExpression) When ¶
func (e CaseExpression) When(condition, result any) CaseExpression
When appends a WHEN condition THEN result arm. In a simple CASE (CaseOf) the condition is the value compared against the operand.
type CaseInsensitiveLiker ¶
CaseInsensitiveLiker is an optional capability a Dialect implements to render a case-insensitive LIKE (ILikeExpression) with a native operator. The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it falls back to LOWER(left) LIKE LOWER(pattern). left and pattern are already-compiled SQL fragments.
type CastExpression ¶
type CastExpression struct {
Operand Expression
Type string
// contains filtered or unexported fields
}
CastExpression converts an operand to another SQL type. It renders as the standard CAST(operand AS type), which both PostgreSQL and MySQL accept; the target type spelling is the caller's responsibility (e.g. "integer", "text", "numeric(10, 2)").
func Cast ¶
func Cast(operand any, sqlType string) CastExpression
Cast creates a CAST(operand AS sqlType) expression. A non-expression operand becomes a bind value.
func (CastExpression) Pos ¶
func (p CastExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (CastExpression) SQLExpression ¶
func (CastExpression) SQLExpression()
func (CastExpression) SQLSelection ¶
func (CastExpression) SQLSelection()
type CollateExpression ¶
type CollateExpression struct {
Operand Expression
Collation Ident
// contains filtered or unexported fields
}
CollateExpression applies a collation to an operand (operand COLLATE "name").
func Collate ¶
func Collate(operand Expression, collation string) CollateExpression
Collate builds a COLLATE expression operand COLLATE collation.
func (CollateExpression) Pos ¶
func (p CollateExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (CollateExpression) SQLExpression ¶
func (CollateExpression) SQLExpression()
func (CollateExpression) SQLSelection ¶
func (CollateExpression) SQLSelection()
type ColumnDef ¶
type ColumnDef struct {
Name Ident
Type ColumnType
NotNull bool
Default Expression
AutoIncrement bool
Comment string
Unique bool
References *ColumnReference
Generated *GeneratedColumn
Identity IdentityKind
// Collate is an optional column collation rendered as COLLATE <name> after
// the type (empty for none).
Collate Ident
// OnUpdate is an optional MySQL ON UPDATE clause (e.g. CURRENT_TIMESTAMP) for
// timestamp/datetime columns; it must bind no values. MySQL only.
OnUpdate Expression
// contains filtered or unexported fields
}
ColumnDef is a column definition used by CREATE TABLE and ALTER TABLE ADD COLUMN. Default carries a static expression (no bind values); set AutoIncrement for an integer primary key that should render as a serial/AUTO_INCREMENT column.
The remaining fields are inline column constraints: Unique adds a column-level UNIQUE, References a column-level FOREIGN KEY (REFERENCES other(col)), Generated a computed column (GENERATED ALWAYS AS (expr)), and Identity a standard identity column (GENERATED ... AS IDENTITY). Generated, Identity, Default, and AutoIncrement are mutually exclusive ways to populate a column.
type ColumnExpression ¶
type ColumnExpression struct {
Name Ident
// contains filtered or unexported fields
}
ColumnExpression references a column name.
func (ColumnExpression) Pos ¶
func (p ColumnExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ColumnExpression) Reference ¶
func (e ColumnExpression) Reference() string
Reference returns the SQL column reference.
func (ColumnExpression) SQLExpression ¶
func (ColumnExpression) SQLExpression()
func (ColumnExpression) SQLSelection ¶
func (ColumnExpression) SQLSelection()
type ColumnReference ¶
type ColumnReference struct {
Schema Ident
Table Ident
Column Ident
OnDelete string
OnUpdate string
// contains filtered or unexported fields
}
ColumnReference is a column-level foreign key: REFERENCES <schema.table> (column) with optional referential actions. Schema is optional.
type ColumnType ¶
ColumnType yields the rendered DDL type clause (e.g. "varchar(255)") for a dialect. It is the seam that lets meta hand a dialect-resolved engine type to the DDL compiler without the sql package depending on meta.
type CommentOnColumnStmt ¶
type CommentOnColumnStmt struct {
Table Table
Column Ident
Comment string
// contains filtered or unexported fields
}
CommentOnColumnStmt is the AST for a standalone column comment (PostgreSQL COMMENT ON COLUMN). It renders to "" on dialects that comment inline (MySQL). It has no options, so it is constructed directly.
func CommentOnColumn ¶
func CommentOnColumn(table Table, column, comment string) CommentOnColumnStmt
CommentOnColumn builds a standalone column comment.
type CommentOnTableStmt ¶
type CommentOnTableStmt struct {
Table Table
Comment string
// contains filtered or unexported fields
}
CommentOnTableStmt is the AST for a standalone table comment (PostgreSQL COMMENT ON TABLE). It renders to "" on dialects that comment inline (MySQL). It has no options, so it is constructed directly.
func CommentOnTable ¶
func CommentOnTable(table Table, comment string) CommentOnTableStmt
CommentOnTable builds a standalone table comment.
type Compiler ¶
type Compiler struct {
Dialect Dialect
// contains filtered or unexported fields
}
Compiler turns SQL expressions and queries into SQL text plus arguments. A single compiler instance is shared across a statement and its subqueries so that bind placeholder numbering stays consistent.
func NewCompiler ¶
NewCompiler creates a compiler for the supplied dialect.
func (*Compiler) CompileAlterTable ¶
func (c *Compiler) CompileAlterTable(s AlterTableStmt) (string, error)
CompileAlterTable renders an ALTER TABLE statement as a single comma-separated list of actions.
func (*Compiler) CompileCommentOnColumn ¶
func (c *Compiler) CompileCommentOnColumn(s CommentOnColumnStmt) (string, error)
CompileCommentOnColumn renders a standalone column comment ("" when the dialect comments inline).
func (*Compiler) CompileCommentOnTable ¶
func (c *Compiler) CompileCommentOnTable(s CommentOnTableStmt) (string, error)
CompileCommentOnTable renders a standalone table comment ("" when the dialect comments inline).
func (*Compiler) CompileCompound ¶
func (c *Compiler) CompileCompound(q CompoundStmt) (string, []any, error)
CompileCompound compiles a set-operation query.
func (*Compiler) CompileCreateFunction ¶
func (c *Compiler) CompileCreateFunction(s CreateFunctionStmt) (string, error)
CompileCreateFunction compiles a CREATE FUNCTION statement.
func (*Compiler) CompileCreateIndex ¶
func (c *Compiler) CompileCreateIndex(s CreateIndexStmt) (string, error)
CompileCreateIndex renders a CREATE INDEX statement.
func (*Compiler) CompileCreateSchema ¶
func (c *Compiler) CompileCreateSchema(s CreateSchemaStmt) (string, error)
CompileCreateSchema renders a CREATE SCHEMA statement. PostgreSQL and MySQL share the syntax (on MySQL a schema is a database and CREATE SCHEMA is its synonym), so it renders directly through QuoteName.
func (*Compiler) CompileCreateTable ¶
func (c *Compiler) CompileCreateTable(s CreateTableStmt) (string, error)
CompileCreateTable renders a CREATE TABLE statement.
func (*Compiler) CompileCreateView ¶
func (c *Compiler) CompileCreateView(s CreateViewStmt) (string, error)
CompileCreateView renders a CREATE VIEW statement. The view body compiles to plain SQL text; a body that binds values is rejected, since a DDL statement carries no bind arguments (inline literals with Raw).
func (*Compiler) CompileDelete ¶
func (c *Compiler) CompileDelete(q DeleteStmt) (string, []any, error)
CompileDelete compiles a DELETE statement. A multi-table DELETE (Using/Join) renders as MySQL's DELETE t FROM t JOIN j ON ... and as PostgreSQL's DELETE FROM t USING j WHERE ..., where join ON predicates fold into the WHERE.
func (*Compiler) CompileDropForeignKey ¶
func (c *Compiler) CompileDropForeignKey(s DropForeignKeyStmt) (string, error)
CompileDropForeignKey renders the drop-foreign-key statement via the dialect.
func (*Compiler) CompileDropFunction ¶
func (c *Compiler) CompileDropFunction(s DropFunctionStmt) (string, error)
CompileDropFunction compiles a DROP FUNCTION statement.
func (*Compiler) CompileDropIndex ¶
func (c *Compiler) CompileDropIndex(s DropIndexStmt) (string, error)
CompileDropIndex renders a DROP INDEX statement via the dialect.
func (*Compiler) CompileDropSchema ¶
func (c *Compiler) CompileDropSchema(s DropSchemaStmt) (string, error)
CompileDropSchema renders a DROP SCHEMA statement (shared syntax; CASCADE is PostgreSQL-only, as MySQL's DROP SCHEMA always drops the database's contents).
func (*Compiler) CompileDropTable ¶
func (c *Compiler) CompileDropTable(s DropTableStmt) (string, error)
CompileDropTable renders a DROP TABLE statement over one or more tables.
func (*Compiler) CompileDropView ¶
func (c *Compiler) CompileDropView(s DropViewStmt) (string, error)
CompileDropView renders a DROP VIEW statement (CASCADE is PostgreSQL/standard only; MySQL has no CASCADE clause for DROP VIEW).
func (*Compiler) CompileExpression ¶
func (c *Compiler) CompileExpression(expr Expression) (string, []any, error)
CompileExpression compiles an expression fragment.
func (*Compiler) CompileGrant ¶
CompileGrant compiles a GRANT statement.
func (*Compiler) CompileInsert ¶
func (c *Compiler) CompileInsert(q InsertStmt) (string, []any, error)
CompileInsert compiles an INSERT statement.
func (*Compiler) CompileJoin ¶
func (c *Compiler) CompileJoin(join JoinClause) (string, []any, error)
CompileJoin compiles a JOIN clause. A join's condition is mutually exclusive: NATURAL (no ON/USING), USING (a column list), or ON (a predicate).
func (*Compiler) CompileMerge ¶
CompileMerge compiles a MERGE statement. The dialect must implement MergeDialect (PostgreSQL and the standard target do); others error.
func (*Compiler) CompileRevoke ¶
func (c *Compiler) CompileRevoke(s RevokeStmt) (string, error)
CompileRevoke compiles a REVOKE statement.
func (*Compiler) CompileSelect ¶
func (c *Compiler) CompileSelect(q SelectStmt) (string, []any, error)
CompileSelect compiles a SELECT statement.
func (*Compiler) CompileSelection ¶
CompileSelection compiles a SELECT-list item.
func (*Compiler) CompileSource ¶
CompileSource compiles a FROM/JOIN source.
func (*Compiler) CompileTruncate ¶
func (c *Compiler) CompileTruncate(s TruncateStmt) (string, error)
CompileTruncate renders a TRUNCATE TABLE statement. RESTART IDENTITY and CASCADE, and truncating more than one table, are PostgreSQL features. The unsupported combinations are rejected rather than silently mis-rendered.
func (*Compiler) CompileUpdate ¶
func (c *Compiler) CompileUpdate(q UpdateStmt) (string, []any, error)
CompileUpdate compiles an UPDATE statement. A multi-table UPDATE (From/Join) renders inline after the target on MySQL (UPDATE t JOIN j ON ... SET ...) and as a trailing FROM list on PostgreSQL (UPDATE t SET ... FROM j WHERE ...), where join ON predicates fold into the WHERE since FROM has no ON.
func (*Compiler) CompileValues ¶
func (c *Compiler) CompileValues(q ValuesQuery) (string, []any, error)
CompileValues compiles a standalone VALUES query.
type CompoundBuilder ¶
type CompoundBuilder struct {
// contains filtered or unexported fields
}
CompoundBuilder is the fluent constructor for a CompoundStmt, separate from the AST data for the same reason as SelectBuilder.
func (CompoundBuilder) As ¶
func (b CompoundBuilder) As(alias string) DerivedTable
As wraps this set-operation query as an aliased subquery named alias.
func (CompoundBuilder) CTE ¶
func (b CompoundBuilder) CTE(name string, opts ...CTEOption) CTE
CTE wraps this set-operation query as a common table expression. Use it for recursive CTEs, whose body is a UNION of the base and recursive terms.
func (CompoundBuilder) Except ¶
func (b CompoundBuilder) Except(other Query) CompoundBuilder
Except appends another EXCEPT operand.
func (CompoundBuilder) ExceptAll ¶
func (b CompoundBuilder) ExceptAll(other Query) CompoundBuilder
ExceptAll appends another EXCEPT ALL operand.
func (CompoundBuilder) Intersect ¶
func (b CompoundBuilder) Intersect(other Query) CompoundBuilder
Intersect appends another INTERSECT operand.
func (CompoundBuilder) IntersectAll ¶
func (b CompoundBuilder) IntersectAll(other Query) CompoundBuilder
IntersectAll appends another INTERSECT ALL operand.
func (CompoundBuilder) Limit ¶
func (b CompoundBuilder) Limit(n int) CompoundBuilder
Limit sets the LIMIT clause of the combined result.
func (CompoundBuilder) Offset ¶
func (b CompoundBuilder) Offset(n int) CompoundBuilder
Offset sets the OFFSET clause of the combined result.
func (CompoundBuilder) OrderBy ¶
func (b CompoundBuilder) OrderBy(terms ...OrderTerm) CompoundBuilder
OrderBy adds ORDER BY terms applied to the combined result.
func (CompoundBuilder) SQLSource ¶
func (b CompoundBuilder) SQLSource() SourceExpression
SQLSource marks the building compound query as a subquery source.
func (CompoundBuilder) Stmt ¶
func (b CompoundBuilder) Stmt() CompoundStmt
Stmt returns the built set-operation statement — the pure AST value.
func (CompoundBuilder) ToSQL ¶
func (b CompoundBuilder) ToSQL(dialect Dialect) (string, []any, error)
ToSQL compiles the building compound statement.
func (CompoundBuilder) Union ¶
func (b CompoundBuilder) Union(other Query) CompoundBuilder
Union appends another UNION operand.
func (CompoundBuilder) UnionAll ¶
func (b CompoundBuilder) UnionAll(other Query) CompoundBuilder
UnionAll appends another UNION ALL operand.
type CompoundStmt ¶
type CompoundStmt struct {
Left Query
Operator string
Right Query
OrderBy []OrderTerm
Limit int
HasLimit bool
Offset int
HasOffset bool
// contains filtered or unexported fields
}
CompoundStmt is the immutable AST for a set operation (UNION/INTERSECT/EXCEPT) combining two query operands. Operands are parenthesized as needed, and ORDER BY / LIMIT / OFFSET apply to the combined result. Build one with a SelectBuilder/CompoundBuilder set-operation method.
func (CompoundStmt) Pos ¶
func (p CompoundStmt) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (CompoundStmt) SQLSource ¶
func (q CompoundStmt) SQLSource() SourceExpression
SQLSource marks CompoundStmt as a subquery source.
type ConcatExpression ¶
type ConcatExpression struct {
Operands []Expression
// contains filtered or unexported fields
}
ConcatExpression concatenates strings. It renders per dialect: the standard || operator on PostgreSQL, and CONCAT(...) on MySQL, whose || means logical OR instead.
func Concat ¶
func Concat(operands ...any) ConcatExpression
Concat creates a string concatenation expression. Non-expression operands become bind values.
func (ConcatExpression) Pos ¶
func (p ConcatExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ConcatExpression) SQLExpression ¶
func (ConcatExpression) SQLExpression()
func (ConcatExpression) SQLSelection ¶
func (ConcatExpression) SQLSelection()
type Concatenator ¶
Concatenator is an optional capability for dialects whose string concatenation is not the standard || operator (MySQL, where || is logical OR and CONCAT(...) concatenates). The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it falls back to the || operator. operands are already-compiled SQL fragments.
type ConflictClause ¶
type ConflictClause struct {
Target []Ident
TargetExprs []Expression
TargetConstraint Ident
DoUpdate bool
Sets []Assignment
Where Expression
// contains filtered or unexported fields
}
ConflictClause is the INSERT upsert action (ON CONFLICT / ON DUPLICATE KEY) carried by InsertStmt.Conflict. At most one of Target, TargetExprs, or TargetConstraint is set. DoUpdate distinguishes DO UPDATE (with Sets and an optional Where) from DO NOTHING.
type CountExpression ¶
type CountExpression struct {
Target Selection
All bool
Distinct bool
// contains filtered or unexported fields
}
CountExpression represents COUNT(expr), COUNT(*), or COUNT(DISTINCT expr).
func Count ¶
func Count(target Selection) CountExpression
Count creates a COUNT(selection) aggregate.
func CountDistinct ¶
func CountDistinct(target Selection) CountExpression
CountDistinct creates a COUNT(DISTINCT selection) aggregate, counting the distinct non-NULL values of selection.
func (CountExpression) Over ¶
func (e CountExpression) Over() WindowExpression
Over turns the aggregate into a window expression.
func (CountExpression) Pos ¶
func (p CountExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (CountExpression) SQLExpression ¶
func (CountExpression) SQLExpression()
func (CountExpression) SQLSelection ¶
func (CountExpression) SQLSelection()
type CreateEnumStmt ¶
CreateEnumStmt is the AST for a CREATE TYPE ... AS ENUM statement (PostgreSQL). It has no options, so it is constructed directly with CreateEnum.
func CreateEnum ¶
func CreateEnum(name string, values ...string) CreateEnumStmt
CreateEnum builds a CREATE TYPE name AS ENUM (values...) statement. The name may be schema-qualified.
type CreateExtensionBuilder ¶
type CreateExtensionBuilder struct {
// contains filtered or unexported fields
}
CreateExtensionBuilder is the fluent constructor for a CreateExtensionStmt.
func CreateExtension ¶
func CreateExtension(name string) CreateExtensionBuilder
CreateExtension starts a CREATE EXTENSION builder for an extension name.
func (CreateExtensionBuilder) IfNotExists ¶
func (b CreateExtensionBuilder) IfNotExists() CreateExtensionBuilder
IfNotExists adds IF NOT EXISTS.
func (CreateExtensionBuilder) Schema ¶
func (b CreateExtensionBuilder) Schema(schema string) CreateExtensionBuilder
Schema installs the extension into a specific schema (WITH SCHEMA name).
func (CreateExtensionBuilder) Stmt ¶
func (b CreateExtensionBuilder) Stmt() CreateExtensionStmt
Stmt returns the built CREATE EXTENSION statement.
type CreateExtensionStmt ¶
type CreateExtensionStmt struct {
Name Ident
IfNotExists bool
Schema Ident
// contains filtered or unexported fields
}
CreateExtensionStmt is the AST for a CREATE EXTENSION statement (PostgreSQL). It is a DDL Statement.
type CreateFunctionBuilder ¶
type CreateFunctionBuilder struct {
// contains filtered or unexported fields
}
CreateFunctionBuilder is the fluent constructor for a CreateFunctionStmt.
func CreateFunction ¶
func CreateFunction(name string) CreateFunctionBuilder
CreateFunction starts a CREATE FUNCTION builder for a (optionally schema-qualified) function name.
func (CreateFunctionBuilder) Arg ¶
func (b CreateFunctionBuilder) Arg(name, typ string) CreateFunctionBuilder
Arg appends a plain IN parameter with the given name and type.
func (CreateFunctionBuilder) Args ¶
func (b CreateFunctionBuilder) Args(args ...FunctionArg) CreateFunctionBuilder
Args appends fully specified parameters.
func (CreateFunctionBuilder) Body ¶
func (b CreateFunctionBuilder) Body(body string) CreateFunctionBuilder
Body sets the function body, emitted dollar-quoted (AS $$ body $$).
func (CreateFunctionBuilder) Language ¶
func (b CreateFunctionBuilder) Language(language string) CreateFunctionBuilder
Language sets the implementation language (e.g. "sql", "plpgsql").
func (CreateFunctionBuilder) Option ¶
func (b CreateFunctionBuilder) Option(options ...string) CreateFunctionBuilder
Option appends routine option keywords rendered before AS (e.g. "IMMUTABLE", "STRICT", "SECURITY DEFINER").
func (CreateFunctionBuilder) OrReplace ¶
func (b CreateFunctionBuilder) OrReplace() CreateFunctionBuilder
OrReplace makes it CREATE OR REPLACE FUNCTION.
func (CreateFunctionBuilder) Returns ¶
func (b CreateFunctionBuilder) Returns(returnType string) CreateFunctionBuilder
Returns sets the return type clause (e.g. "integer", "SETOF users", "trigger").
func (CreateFunctionBuilder) Stmt ¶
func (b CreateFunctionBuilder) Stmt() CreateFunctionStmt
Stmt returns the built CREATE FUNCTION statement.
type CreateFunctionStmt ¶
type CreateFunctionStmt struct {
Name Ident
OrReplace bool
Args []FunctionArg
Returns string
Language string
Options []string
Body string
// contains filtered or unexported fields
}
CreateFunctionStmt is the AST for a CREATE FUNCTION statement. The argument types, return type, language, options, and body are rendered verbatim, so they must already be valid for the target engine. It is a DDL Statement.
type CreateIndexBuilder ¶
type CreateIndexBuilder struct {
// contains filtered or unexported fields
}
CreateIndexBuilder is the fluent constructor for a CreateIndexStmt.
func CreateIndex ¶
func CreateIndex(name string, table Table, columns ...string) CreateIndexBuilder
CreateIndex starts a CREATE INDEX builder for an index over columns of a table.
func (CreateIndexBuilder) IfNotExists ¶
func (b CreateIndexBuilder) IfNotExists() CreateIndexBuilder
IfNotExists adds IF NOT EXISTS.
func (CreateIndexBuilder) Stmt ¶
func (b CreateIndexBuilder) Stmt() CreateIndexStmt
Stmt returns the built CREATE INDEX statement.
func (CreateIndexBuilder) ToSQL ¶
func (b CreateIndexBuilder) ToSQL(d Dialect) (string, []any, error)
ToSQL compiles the building CREATE INDEX statement.
func (CreateIndexBuilder) Unique ¶
func (b CreateIndexBuilder) Unique() CreateIndexBuilder
Unique makes it a CREATE UNIQUE INDEX.
type CreateIndexStmt ¶
type CreateIndexStmt struct {
Name Ident
Table Table
Columns []Ident
Unique bool
IfNotExists bool
// contains filtered or unexported fields
}
CreateIndexStmt is the AST for a CREATE INDEX statement.
type CreateMaterializedViewBuilder ¶
type CreateMaterializedViewBuilder struct {
// contains filtered or unexported fields
}
CreateMaterializedViewBuilder is the fluent constructor for a CreateMaterializedViewStmt.
func CreateMaterializedView ¶
func CreateMaterializedView(table Table, query Query) CreateMaterializedViewBuilder
CreateMaterializedView starts a builder for a materialized view defined by query.
func (CreateMaterializedViewBuilder) Columns ¶
func (b CreateMaterializedViewBuilder) Columns(columns ...string) CreateMaterializedViewBuilder
Columns sets explicit column names.
func (CreateMaterializedViewBuilder) IfNotExists ¶
func (b CreateMaterializedViewBuilder) IfNotExists() CreateMaterializedViewBuilder
IfNotExists adds IF NOT EXISTS.
func (CreateMaterializedViewBuilder) Stmt ¶
func (b CreateMaterializedViewBuilder) Stmt() CreateMaterializedViewStmt
Stmt returns the built CREATE MATERIALIZED VIEW statement.
func (CreateMaterializedViewBuilder) ToSQL ¶
func (b CreateMaterializedViewBuilder) ToSQL(d Dialect) (string, []any, error)
ToSQL compiles the building CREATE MATERIALIZED VIEW statement.
func (CreateMaterializedViewBuilder) WithNoData ¶
func (b CreateMaterializedViewBuilder) WithNoData() CreateMaterializedViewBuilder
WithNoData adds WITH NO DATA, creating the view unpopulated.
type CreateMaterializedViewStmt ¶
type CreateMaterializedViewStmt struct {
Table Table
Query Query
Columns []Ident
IfNotExists bool
WithNoData bool
// contains filtered or unexported fields
}
CreateMaterializedViewStmt is the AST for a CREATE MATERIALIZED VIEW statement (PostgreSQL). Like a view its body must compile to plain SQL with no bind values; inline literals with Raw. It is a DDL Statement.
type CreateSchemaBuilder ¶
type CreateSchemaBuilder struct {
// contains filtered or unexported fields
}
CreateSchemaBuilder is the fluent constructor for a CreateSchemaStmt.
func CreateSchema ¶
func CreateSchema(name string) CreateSchemaBuilder
CreateSchema starts a CREATE SCHEMA builder for a schema name.
func (CreateSchemaBuilder) IfNotExists ¶
func (b CreateSchemaBuilder) IfNotExists() CreateSchemaBuilder
IfNotExists adds IF NOT EXISTS, making the statement idempotent (it leaves an already-existing schema, and whatever it contains, untouched).
func (CreateSchemaBuilder) Stmt ¶
func (b CreateSchemaBuilder) Stmt() CreateSchemaStmt
Stmt returns the built CREATE SCHEMA statement.
type CreateSchemaStmt ¶
type CreateSchemaStmt struct {
Name Ident
IfNotExists bool
// contains filtered or unexported fields
}
CreateSchemaStmt is the AST for a CREATE SCHEMA statement. On MySQL, where a schema is a database, CREATE SCHEMA is the engine's own synonym for CREATE DATABASE, so the same node renders for both dialects.
type CreateSequenceBuilder ¶
type CreateSequenceBuilder struct {
// contains filtered or unexported fields
}
CreateSequenceBuilder is the fluent constructor for a CreateSequenceStmt.
func CreateSequence ¶
func CreateSequence(sequence Table) CreateSequenceBuilder
CreateSequence starts a CREATE SEQUENCE builder for a sequence.
func (CreateSequenceBuilder) Cache ¶
func (b CreateSequenceBuilder) Cache(n int64) CreateSequenceBuilder
Cache sets CACHE.
func (CreateSequenceBuilder) Cycle ¶
func (b CreateSequenceBuilder) Cycle() CreateSequenceBuilder
Cycle sets CYCLE.
func (CreateSequenceBuilder) IfNotExists ¶
func (b CreateSequenceBuilder) IfNotExists() CreateSequenceBuilder
IfNotExists adds IF NOT EXISTS.
func (CreateSequenceBuilder) Increment ¶
func (b CreateSequenceBuilder) Increment(n int64) CreateSequenceBuilder
Increment sets INCREMENT BY.
func (CreateSequenceBuilder) MaxValue ¶
func (b CreateSequenceBuilder) MaxValue(n int64) CreateSequenceBuilder
MaxValue sets MAXVALUE.
func (CreateSequenceBuilder) MinValue ¶
func (b CreateSequenceBuilder) MinValue(n int64) CreateSequenceBuilder
MinValue sets MINVALUE.
func (CreateSequenceBuilder) NoCycle ¶
func (b CreateSequenceBuilder) NoCycle() CreateSequenceBuilder
NoCycle sets NO CYCLE.
func (CreateSequenceBuilder) NoMaxValue ¶
func (b CreateSequenceBuilder) NoMaxValue() CreateSequenceBuilder
NoMaxValue sets NO MAXVALUE.
func (CreateSequenceBuilder) NoMinValue ¶
func (b CreateSequenceBuilder) NoMinValue() CreateSequenceBuilder
NoMinValue sets NO MINVALUE.
func (CreateSequenceBuilder) OwnedBy ¶
func (b CreateSequenceBuilder) OwnedBy(column string) CreateSequenceBuilder
OwnedBy sets OWNED BY a "table.column", or "NONE" to detach the sequence.
func (CreateSequenceBuilder) Start ¶
func (b CreateSequenceBuilder) Start(n int64) CreateSequenceBuilder
Start sets START WITH.
func (CreateSequenceBuilder) Stmt ¶
func (b CreateSequenceBuilder) Stmt() CreateSequenceStmt
Stmt returns the built CREATE SEQUENCE statement.
type CreateSequenceStmt ¶
type CreateSequenceStmt struct {
Sequence Table
IfNotExists bool
Increment *int64
MinValue *int64
NoMinValue bool
MaxValue *int64
NoMaxValue bool
Start *int64
Cache *int64
Cycle *bool
OwnedBy Ident
// contains filtered or unexported fields
}
CreateSequenceStmt is the AST for a CREATE SEQUENCE statement (PostgreSQL). It is a DDL Statement. A nil numeric pointer means the option is absent (the engine default); Cycle is nil when neither CYCLE nor NO CYCLE was set. OwnedBy is "", "NONE", or "table.column".
type CreateTableBuilder ¶
type CreateTableBuilder struct {
// contains filtered or unexported fields
}
CreateTableBuilder is the fluent constructor for a CreateTableStmt.
func CreateTable ¶
func CreateTable(table Table) CreateTableBuilder
CreateTable starts a CREATE TABLE builder for a table.
func (CreateTableBuilder) Check ¶
func (b CreateTableBuilder) Check(name string, expr Expression) CreateTableBuilder
Check appends a named CHECK constraint. expr must bind no values.
func (CreateTableBuilder) Column ¶
func (b CreateTableBuilder) Column(c ColumnDef) CreateTableBuilder
Column appends a column definition.
func (CreateTableBuilder) Comment ¶
func (b CreateTableBuilder) Comment(text string) CreateTableBuilder
Comment sets the table comment (rendered inline on dialects that support it, e.g. MySQL; use CommentOnTable for the standalone PostgreSQL form).
func (CreateTableBuilder) ForeignKey ¶
func (b CreateTableBuilder) ForeignKey(fk ForeignKeyConstraint) CreateTableBuilder
ForeignKey appends a table-level FOREIGN KEY constraint.
func (CreateTableBuilder) IfNotExists ¶
func (b CreateTableBuilder) IfNotExists() CreateTableBuilder
IfNotExists adds IF NOT EXISTS.
func (CreateTableBuilder) Index ¶
func (b CreateTableBuilder) Index(name string, columns ...string) CreateTableBuilder
Index appends an inline non-unique secondary index (MySQL KEY/INDEX). name is optional. Inline indexes render only on MySQL; other dialects reject them in favor of a separate CreateIndex statement.
func (CreateTableBuilder) PrimaryKey ¶
func (b CreateTableBuilder) PrimaryKey(columns ...string) CreateTableBuilder
PrimaryKey sets the primary-key columns. Call once with all key columns.
func (CreateTableBuilder) Stmt ¶
func (b CreateTableBuilder) Stmt() CreateTableStmt
Stmt returns the built CREATE TABLE statement.
func (CreateTableBuilder) Temporary ¶
func (b CreateTableBuilder) Temporary() CreateTableBuilder
Temporary makes it a CREATE TEMPORARY TABLE: a session-scoped table that the engine drops at the end of the session (PostgreSQL/MySQL both spell it TEMPORARY). A temporary table usually lives in a session-private namespace, so the table is best referenced unqualified (an explicit schema is the engine's to reject).
func (CreateTableBuilder) ToSQL ¶
func (b CreateTableBuilder) ToSQL(d Dialect) (string, []any, error)
ToSQL compiles the building CREATE TABLE statement.
func (CreateTableBuilder) Unique ¶
func (b CreateTableBuilder) Unique(name string, columns ...string) CreateTableBuilder
Unique appends a table-level UNIQUE constraint over the columns. name is optional (pass "" for an unnamed constraint).
type CreateTableStmt ¶
type CreateTableStmt struct {
Table Table
Columns []ColumnDef
PrimaryKey []Ident
Checks []TableCheck
Uniques []TableUnique
ForeignKeys []ForeignKeyConstraint
Indexes []TableIndex
Comment string
IfNotExists bool
Temporary bool
// contains filtered or unexported fields
}
CreateTableStmt is the AST for a CREATE TABLE statement.
type CreateViewBuilder ¶
type CreateViewBuilder struct {
// contains filtered or unexported fields
}
CreateViewBuilder is the fluent constructor for a CreateViewStmt.
func CreateView ¶
func CreateView(table Table, query Query) CreateViewBuilder
CreateView starts a CREATE VIEW builder for a view defined by query.
func (CreateViewBuilder) Columns ¶
func (b CreateViewBuilder) Columns(columns ...string) CreateViewBuilder
Columns sets explicit view column names (CREATE VIEW v (a, b) AS ...), overriding the names the body's select list would otherwise supply.
func (CreateViewBuilder) OrReplace ¶
func (b CreateViewBuilder) OrReplace() CreateViewBuilder
OrReplace makes it CREATE OR REPLACE VIEW, redefining an existing view in place (PostgreSQL/MySQL).
func (CreateViewBuilder) Stmt ¶
func (b CreateViewBuilder) Stmt() CreateViewStmt
Stmt returns the built CREATE VIEW statement.
type CreateViewStmt ¶
type CreateViewStmt struct {
Table Table
Query Query
Columns []Ident
OrReplace bool
// contains filtered or unexported fields
}
CreateViewStmt is the AST for a CREATE VIEW statement whose body is a query (a SELECT builder, or any Query). Like the other DDL nodes a view binds no values, so the body must compile to plain SQL text — inline any literals with Raw rather than as bound parameters.
type DeleteBuilder ¶
type DeleteBuilder struct {
// contains filtered or unexported fields
}
DeleteBuilder is the fluent constructor for a DeleteStmt.
func DeleteFrom ¶
func DeleteFrom(table Table) DeleteBuilder
DeleteFrom creates a DELETE query builder for a table.
func (DeleteBuilder) Join ¶
func (b DeleteBuilder) Join(source Source, on Expression) DeleteBuilder
Join adds an inner join to the DELETE's source list.
func (DeleteBuilder) LeftJoin ¶
func (b DeleteBuilder) LeftJoin(source Source, on Expression) DeleteBuilder
LeftJoin adds a left join to the DELETE's source list.
func (DeleteBuilder) Limit ¶
func (b DeleteBuilder) Limit(n int) DeleteBuilder
Limit caps the number of rows a DELETE removes (DELETE ... LIMIT n). MySQL only; other dialects reject it.
func (DeleteBuilder) OrderBy ¶
func (b DeleteBuilder) OrderBy(terms ...OrderTerm) DeleteBuilder
OrderBy adds ORDER BY terms that bound which rows a DELETE removes (DELETE ... ORDER BY ... LIMIT). MySQL only; other dialects reject it.
func (DeleteBuilder) Returning ¶
func (b DeleteBuilder) Returning(selections ...Selection) DeleteBuilder
Returning adds a RETURNING clause.
func (DeleteBuilder) Stmt ¶
func (b DeleteBuilder) Stmt() DeleteStmt
Stmt returns the built DELETE statement — the pure AST value.
func (DeleteBuilder) ToSQL ¶
func (b DeleteBuilder) ToSQL(dialect Dialect) (string, []any, error)
ToSQL compiles the building DELETE statement.
func (DeleteBuilder) Using ¶
func (b DeleteBuilder) Using(sources ...Source) DeleteBuilder
Using adds correlated sources to the DELETE (PostgreSQL DELETE ... USING / MySQL multi-table DELETE). Combine with Where to correlate rows.
func (DeleteBuilder) Where ¶
func (b DeleteBuilder) Where(expr Expression) DeleteBuilder
Where adds a WHERE predicate, combined with AND when called repeatedly.
func (DeleteBuilder) WithCTE ¶
func (b DeleteBuilder) WithCTE(ctes ...CTE) DeleteBuilder
WithCTE prepends common table expressions to the DELETE.
type DeleteStmt ¶
type DeleteStmt struct {
With []CTE
Table Table
Using []Source
Joins []JoinClause
Where Expression
OrderBy []OrderTerm
Limit int
HasLimit bool
Returning []Selection
// contains filtered or unexported fields
}
DeleteStmt is the immutable AST for a DELETE statement.
type DerivedTable ¶
type DerivedTable struct {
// contains filtered or unexported fields
}
DerivedTable is an aliased subquery built from a query with Query.As. Like a CTE, it doubles as a FROM/JOIN source and a handle for referencing its output columns (Col), but it is inlined as a parenthesized query at its use site rather than declared in a leading WITH clause:
sub := Select(Col("id")).From(users).Where(...).As("sub")
Select(sub.Col("id")).From(sub)
emits SELECT "sub"."id" FROM (SELECT "id" FROM "users" WHERE ...) AS "sub".
func (DerivedTable) Alias ¶
func (d DerivedTable) Alias() string
Alias returns the derived table's alias.
func (DerivedTable) Col ¶
func (d DerivedTable) Col(name string) ColumnExpression
Col references one of the derived table's output columns, qualified by its alias.
func (DerivedTable) Pos ¶
func (p DerivedTable) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (DerivedTable) SQLSource ¶
func (d DerivedTable) SQLSource() SourceExpression
SQLSource lets a DerivedTable be used as a FROM/JOIN source, emitting the parenthesized query followed by AS alias.
type DerivedValuesUnionDialect ¶
type DerivedValuesUnionDialect interface {
// UsesValuesUnion reports the UNION-ALL-of-SELECTs rendering for a VALUES
// derived table.
UsesValuesUnion() bool
}
DerivedValuesUnionDialect is an optional capability for dialects that cannot alias the columns of a VALUES row constructor used as a derived table. MySQL names VALUES columns column_0, column_1, … with no way to override them, so a VALUES source (ValuesSource) must be rendered as a UNION ALL of SELECTs whose first arm supplies the column names. The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect that does not implement it uses the standard (VALUES ...) AS alias(cols) form (PostgreSQL).
type Dialect ¶
type Dialect interface {
// Name identifies the dialect, e.g. "postgres" or "mysql".
Name() string
// QuoteIdent quotes a possibly dot-qualified identifier, quoting each
// dot-separated part (e.g. a "schema.table" reference from the compiler).
QuoteIdent(identifier string) string
// QuoteName quotes a single identifier as one unit, without splitting on
// dots. DDL uses it for schema/table/column/constraint names, which already
// arrive as separate parts and may legitimately contain a literal dot.
QuoteName(name string) string
// Placeholder renders the bind placeholder for the 1-based position.
Placeholder(position int) string
// SupportsReturning reports whether INSERT/UPDATE/DELETE may carry a
// RETURNING clause. Dialects without it reject Returning at compile time.
SupportsReturning() bool
// ColumnType renders a column's engine type for DDL: the type name plus any
// length/precision modifiers the dialect attaches (e.g. varchar(255),
// numeric(10, 2)). length, precision and scale are 0 when not applicable.
ColumnType(name string, length, precision, scale int) string
// AutoIncrementColumn renders the full type clause for an auto-incrementing
// integer primary key (PostgreSQL serial, MySQL ... AUTO_INCREMENT), or
// reports false when name is not an integer type the dialect auto-increments.
AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
// InlineColumnComment renders the suffix that carries a column comment within
// the CREATE TABLE statement (MySQL), or "" when the dialect uses standalone
// comment statements.
InlineColumnComment(comment string) string
// InlineTableComment renders the suffix that carries a table comment after
// the closing parenthesis (MySQL), or "" when the dialect uses standalone
// comment statements.
InlineTableComment(comment string) string
// TableCommentStatement renders a standalone table comment statement
// (PostgreSQL COMMENT ON TABLE) for the already-quoted table reference, or ""
// when comment is empty or the dialect comments inline.
TableCommentStatement(quotedTable, comment string) string
// ColumnCommentStatement renders a standalone column comment statement
// (PostgreSQL COMMENT ON COLUMN) for the already-quoted table and column, or
// "" when comment is empty or the dialect comments inline.
ColumnCommentStatement(quotedTable, quotedColumn, comment string) string
// DropForeignKey renders the statement that drops a foreign-key constraint
// (PostgreSQL ALTER TABLE ... DROP CONSTRAINT, MySQL ... DROP FOREIGN KEY)
// for the already-quoted table and constraint name.
DropForeignKey(qualifiedTable, quotedConstraint string) string
// DropIndex renders the DROP INDEX statement. PostgreSQL drops the
// schema-qualified index (qualifiedIndex); MySQL drops the bare index
// (quotedIndex) from its table (qualifiedTable).
DropIndex(qualifiedIndex, quotedIndex, qualifiedTable string) string
}
Dialect captures SQL syntax details that vary by database engine. It is the single point where engine differences are resolved: the query builders compile through it, and the schema model renders DDL through it. Adding an engine means implementing this interface; PostgreSQL is the default and the most exercised.
func DialectByName ¶
DialectByName returns the Dialect for a name: "postgres"/"postgresql" (or empty, the default), "mysql", or "standard"/"ansi"/"sql" (the SQL standard / ANSI text target). It errors on an unknown name.
type DistinctOnDialect ¶
type DistinctOnDialect interface {
SupportsDistinctOn() bool
}
DistinctOnDialect is an optional capability a Dialect implements to report support for SELECT DISTINCT ON (exprs) (SelectBuilder.DistinctOn), a PostgreSQL extension with no portable equivalent. The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect that does not implement it (or returns false) rejects DISTINCT ON at compile time.
type DistinctPredicate ¶
type DistinctPredicate struct {
Left Expression
Right Expression
Negate bool // true selects IS NOT DISTINCT FROM
// contains filtered or unexported fields
}
DistinctPredicate compares two operands with IS DISTINCT FROM / IS NOT DISTINCT FROM, the null-safe counterparts of <> and =: two NULLs are not distinct, and a NULL is distinct from any non-NULL value, so the result is never itself NULL. It renders per dialect: the SQL-standard IS [NOT] DISTINCT FROM (PostgreSQL, the standard target) and, through a NullSafeEqualityDialect, MySQL's null-safe equality operator <=> (a <=> b for IS NOT DISTINCT FROM, NOT (a <=> b) for IS DISTINCT FROM).
func IsDistinctFrom ¶
func IsDistinctFrom(left, right any) DistinctPredicate
IsDistinctFrom creates "left IS DISTINCT FROM right", a null-safe inequality. Non-expression operands become bind values.
func IsNotDistinctFrom ¶
func IsNotDistinctFrom(left, right any) DistinctPredicate
IsNotDistinctFrom creates "left IS NOT DISTINCT FROM right", a null-safe equality. Non-expression operands become bind values.
func (DistinctPredicate) Pos ¶
func (p DistinctPredicate) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (DistinctPredicate) SQLExpression ¶
func (DistinctPredicate) SQLExpression()
type DropExtensionBuilder ¶
type DropExtensionBuilder struct {
// contains filtered or unexported fields
}
DropExtensionBuilder is the fluent constructor for a DropExtensionStmt.
func DropExtension ¶
func DropExtension(names ...string) DropExtensionBuilder
DropExtension starts a DROP EXTENSION builder for one or more extensions.
func (DropExtensionBuilder) Cascade ¶
func (b DropExtensionBuilder) Cascade() DropExtensionBuilder
Cascade adds CASCADE.
func (DropExtensionBuilder) IfExists ¶
func (b DropExtensionBuilder) IfExists() DropExtensionBuilder
IfExists adds IF EXISTS.
func (DropExtensionBuilder) Stmt ¶
func (b DropExtensionBuilder) Stmt() DropExtensionStmt
Stmt returns the built DROP EXTENSION statement.
type DropExtensionStmt ¶
type DropExtensionStmt struct {
Names []Ident
IfExists bool
Cascade bool
// contains filtered or unexported fields
}
DropExtensionStmt is the AST for a DROP EXTENSION statement.
type DropForeignKeyStmt ¶
DropForeignKeyStmt is the AST for the statement that drops a foreign-key constraint, using the dialect's syntax (PostgreSQL DROP CONSTRAINT, MySQL DROP FOREIGN KEY). It has no options, so it is constructed directly.
func DropForeignKey ¶
func DropForeignKey(table Table, name string) DropForeignKeyStmt
DropForeignKey builds the statement that drops the named foreign-key constraint from a table.
type DropFunctionBuilder ¶
type DropFunctionBuilder struct {
// contains filtered or unexported fields
}
DropFunctionBuilder is the fluent constructor for a DropFunctionStmt.
func DropFunction ¶
func DropFunction(name string) DropFunctionBuilder
DropFunction starts a DROP FUNCTION builder for a function name.
func (DropFunctionBuilder) ArgTypes ¶
func (b DropFunctionBuilder) ArgTypes(types ...string) DropFunctionBuilder
ArgTypes pins the argument-type list that identifies an overload (DROP FUNCTION f(int, text)). Call with no types for an empty "()" list.
func (DropFunctionBuilder) Cascade ¶
func (b DropFunctionBuilder) Cascade() DropFunctionBuilder
Cascade adds CASCADE, also dropping dependent objects.
func (DropFunctionBuilder) IfExists ¶
func (b DropFunctionBuilder) IfExists() DropFunctionBuilder
IfExists adds IF EXISTS.
func (DropFunctionBuilder) Restrict ¶
func (b DropFunctionBuilder) Restrict() DropFunctionBuilder
Restrict adds RESTRICT, refusing to drop when dependents exist.
func (DropFunctionBuilder) Stmt ¶
func (b DropFunctionBuilder) Stmt() DropFunctionStmt
Stmt returns the built DROP FUNCTION statement.
type DropFunctionStmt ¶
type DropFunctionStmt struct {
Name Ident
IfExists bool
ArgTypes []string
HasArgs bool
Behavior string
// contains filtered or unexported fields
}
DropFunctionStmt is the AST for a DROP FUNCTION statement. Argument types disambiguate an overloaded function; they are rendered verbatim. HasArgs reports whether an argument-type list was given (an empty list still renders "()"). Behavior is "", "CASCADE", or "RESTRICT". It is a DDL Statement.
type DropIndexStmt ¶
DropIndexStmt is the AST for a DROP INDEX statement. It has no options, so it is constructed directly with DropIndex.
func DropIndex ¶
func DropIndex(name string, table Table) DropIndexStmt
DropIndex builds a DROP INDEX statement. The table is needed because MySQL drops an index from its table.
type DropMaterializedViewBuilder ¶
type DropMaterializedViewBuilder struct {
// contains filtered or unexported fields
}
DropMaterializedViewBuilder is the fluent constructor for a DropMaterializedViewStmt.
func DropMaterializedView ¶
func DropMaterializedView(table Table) DropMaterializedViewBuilder
DropMaterializedView starts a DROP MATERIALIZED VIEW builder.
func (DropMaterializedViewBuilder) Cascade ¶
func (b DropMaterializedViewBuilder) Cascade() DropMaterializedViewBuilder
Cascade adds CASCADE.
func (DropMaterializedViewBuilder) IfExists ¶
func (b DropMaterializedViewBuilder) IfExists() DropMaterializedViewBuilder
IfExists adds IF EXISTS.
func (DropMaterializedViewBuilder) Stmt ¶
func (b DropMaterializedViewBuilder) Stmt() DropMaterializedViewStmt
Stmt returns the built DROP MATERIALIZED VIEW statement.
type DropMaterializedViewStmt ¶
type DropMaterializedViewStmt struct {
Table Table
IfExists bool
Cascade bool
// contains filtered or unexported fields
}
DropMaterializedViewStmt is the AST for a DROP MATERIALIZED VIEW statement.
type DropSchemaBuilder ¶
type DropSchemaBuilder struct {
// contains filtered or unexported fields
}
DropSchemaBuilder is the fluent constructor for a DropSchemaStmt.
func DropSchema ¶
func DropSchema(name string) DropSchemaBuilder
DropSchema starts a DROP SCHEMA builder for a schema name.
func (DropSchemaBuilder) Cascade ¶
func (b DropSchemaBuilder) Cascade() DropSchemaBuilder
Cascade adds CASCADE, dropping objects the schema still contains. It renders only on PostgreSQL; MySQL has no CASCADE clause (DROP SCHEMA there always drops the database's contents), so the flag is ignored.
func (DropSchemaBuilder) IfExists ¶
func (b DropSchemaBuilder) IfExists() DropSchemaBuilder
IfExists adds IF EXISTS.
func (DropSchemaBuilder) Stmt ¶
func (b DropSchemaBuilder) Stmt() DropSchemaStmt
Stmt returns the built DROP SCHEMA statement.
type DropSchemaStmt ¶
type DropSchemaStmt struct {
Name Ident
IfExists bool
Cascade bool
// contains filtered or unexported fields
}
DropSchemaStmt is the AST for a DROP SCHEMA statement. On MySQL, where a schema is a database, this drops the database and everything left in it; on PostgreSQL a non-empty schema needs the tables dropped first (or Cascade).
type DropSequenceBuilder ¶
type DropSequenceBuilder struct {
// contains filtered or unexported fields
}
DropSequenceBuilder is the fluent constructor for a DropSequenceStmt.
func DropSequence ¶
func DropSequence(names ...string) DropSequenceBuilder
DropSequence starts a DROP SEQUENCE builder for one or more (possibly schema-qualified) sequence names.
func (DropSequenceBuilder) Cascade ¶
func (b DropSequenceBuilder) Cascade() DropSequenceBuilder
Cascade adds CASCADE.
func (DropSequenceBuilder) IfExists ¶
func (b DropSequenceBuilder) IfExists() DropSequenceBuilder
IfExists adds IF EXISTS.
func (DropSequenceBuilder) Stmt ¶
func (b DropSequenceBuilder) Stmt() DropSequenceStmt
Stmt returns the built DROP SEQUENCE statement.
type DropSequenceStmt ¶
type DropSequenceStmt struct {
Names []Ident
IfExists bool
Cascade bool
// contains filtered or unexported fields
}
DropSequenceStmt is the AST for a DROP SEQUENCE statement.
type DropTableBuilder ¶
type DropTableBuilder struct {
// contains filtered or unexported fields
}
DropTableBuilder is the fluent constructor for a DropTableStmt.
func DropTable ¶
func DropTable(tables ...Table) DropTableBuilder
DropTable starts a DROP TABLE builder for one or more tables, dropped in a single "DROP TABLE a, b" statement.
func (DropTableBuilder) IfExists ¶
func (b DropTableBuilder) IfExists() DropTableBuilder
IfExists adds IF EXISTS.
func (DropTableBuilder) Stmt ¶
func (b DropTableBuilder) Stmt() DropTableStmt
Stmt returns the built DROP TABLE statement.
type DropTableStmt ¶
type DropTableStmt struct {
Tables []Table
IfExists bool
// contains filtered or unexported fields
}
DropTableStmt is the AST for a DROP TABLE statement over one or more tables.
type DropTypeBuilder ¶
type DropTypeBuilder struct {
// contains filtered or unexported fields
}
DropTypeBuilder is the fluent constructor for a DropTypeStmt.
func DropType ¶
func DropType(names ...string) DropTypeBuilder
DropType starts a DROP TYPE builder for one or more (possibly schema-qualified) type names.
func (DropTypeBuilder) Cascade ¶
func (b DropTypeBuilder) Cascade() DropTypeBuilder
Cascade adds CASCADE.
func (DropTypeBuilder) IfExists ¶
func (b DropTypeBuilder) IfExists() DropTypeBuilder
IfExists adds IF EXISTS.
func (DropTypeBuilder) Stmt ¶
func (b DropTypeBuilder) Stmt() DropTypeStmt
Stmt returns the built DROP TYPE statement.
type DropTypeStmt ¶
type DropTypeStmt struct {
Names []Ident
IfExists bool
Cascade bool
// contains filtered or unexported fields
}
DropTypeStmt is the AST for a DROP TYPE statement (PostgreSQL).
type DropViewBuilder ¶
type DropViewBuilder struct {
// contains filtered or unexported fields
}
DropViewBuilder is the fluent constructor for a DropViewStmt.
func DropView ¶
func DropView(table Table) DropViewBuilder
DropView starts a DROP VIEW builder for a view.
func (DropViewBuilder) Cascade ¶
func (b DropViewBuilder) Cascade() DropViewBuilder
Cascade adds CASCADE, dropping objects that depend on the view (PostgreSQL / standard SQL). MySQL has no CASCADE clause for DROP VIEW, so the flag is ignored there.
func (DropViewBuilder) IfExists ¶
func (b DropViewBuilder) IfExists() DropViewBuilder
IfExists adds IF EXISTS.
func (DropViewBuilder) Stmt ¶
func (b DropViewBuilder) Stmt() DropViewStmt
Stmt returns the built DROP VIEW statement.
type DropViewStmt ¶
type DropViewStmt struct {
Table Table
IfExists bool
Cascade bool
// contains filtered or unexported fields
}
DropViewStmt is the AST for a DROP VIEW statement.
type EngineType ¶
EngineType is a dialect-resolved column type: an engine type name plus its length/precision modifiers. The meta package builds these from meta.Engine. It renders through Dialect.ColumnType (and Dialect.AutoIncrementColumn when a column is auto-incrementing).
func (EngineType) RenderAutoIncrement ¶
func (t EngineType) RenderAutoIncrement(d Dialect) (string, bool)
RenderAutoIncrement renders the auto-incrementing clause for the engine type, or reports false when the dialect does not auto-increment it.
func (EngineType) RenderType ¶
func (t EngineType) RenderType(d Dialect) (string, error)
RenderType renders the engine type for the dialect.
type ExcludedExpression ¶
type ExcludedExpression struct {
Column Ident
// contains filtered or unexported fields
}
ExcludedExpression refers, inside an upsert's DO UPDATE assignments, to the value the conflicting INSERT proposed for a column. It renders per dialect: PostgreSQL's excluded.<col> and MySQL's VALUES(<col>).
func Excluded ¶
func Excluded(column string) ExcludedExpression
Excluded references the proposed value for column in an OnConflict DoUpdate assignment, e.g. Set("name", Excluded("name")) to overwrite with the new row.
func (ExcludedExpression) Pos ¶
func (p ExcludedExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ExcludedExpression) SQLExpression ¶
func (ExcludedExpression) SQLExpression()
type ExcludedRenderer ¶
ExcludedRenderer is an optional capability for dialects whose reference to an upsert's proposed row value is not PostgreSQL's excluded.<col> (MySQL uses VALUES(<col>)). The compiler detects it with a type assertion; without it the excluded.<col> form is used. column is the bare column name.
type ExistsExpression ¶
ExistsExpression tests whether a subquery returns any rows.
func Exists ¶
func Exists(query Query) ExistsExpression
Exists creates an "EXISTS (subquery)" expression.
func NotExists ¶
func NotExists(query Query) ExistsExpression
NotExists creates a "NOT EXISTS (subquery)" expression.
func (ExistsExpression) Pos ¶
func (p ExistsExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ExistsExpression) SQLExpression ¶
func (ExistsExpression) SQLExpression()
type Expression ¶
type Expression interface {
SQLExpression()
}
Expression is a composable SQL AST node.
func And ¶
func And(operands ...Expression) Expression
And combines predicates with AND. With a single operand it is the identity.
func Or ¶
func Or(operands ...Expression) Expression
Or combines predicates with OR. With a single operand it is the identity.
type ExtractExpression ¶
type ExtractExpression struct {
Field string
Operand Expression
// contains filtered or unexported fields
}
ExtractExpression pulls a date/time field (year, month, day, hour, ...) out of a date/time operand. It renders as the SQL standard EXTRACT(field FROM operand), which PostgreSQL and MySQL both accept. Field is emitted verbatim as a keyword (not quoted, not bound), so pass a bare field name such as "year".
func Extract ¶
func Extract(field string, operand any) ExtractExpression
Extract creates EXTRACT(field FROM operand), e.g. Extract("year", Col("created_at")). A non-expression operand becomes a bind value.
func (ExtractExpression) Pos ¶
func (p ExtractExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ExtractExpression) SQLExpression ¶
func (ExtractExpression) SQLExpression()
func (ExtractExpression) SQLSelection ¶
func (ExtractExpression) SQLSelection()
type FTSMode ¶
type FTSMode int
FTSMode selects how a full-text search query string is interpreted: natural-language (the default) or boolean (the engine's operator syntax — PostgreSQL's websearch_to_tsquery, MySQL's IN BOOLEAN MODE).
type FieldExpression ¶
type FieldExpression struct {
Operand Expression
Field Ident
// contains filtered or unexported fields
}
FieldExpression selects a field of a composite-typed operand, rendered parenthesized as (operand).field.
func Field ¶
func Field(operand Expression, field string) FieldExpression
Field builds a composite field access (operand).field.
func (FieldExpression) Pos ¶
func (p FieldExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (FieldExpression) SQLExpression ¶
func (FieldExpression) SQLExpression()
func (FieldExpression) SQLSelection ¶
func (FieldExpression) SQLSelection()
type ForeignKeyConstraint ¶
type ForeignKeyConstraint struct {
Name Ident
Columns []Ident
RefSchema Ident
RefTable Ident
RefColumns []Ident
OnDelete string
OnUpdate string
// contains filtered or unexported fields
}
ForeignKeyConstraint describes a foreign-key constraint added with AlterTable.AddForeignKey: the local Columns reference RefColumns of RefTable (in RefSchema). OnDelete/OnUpdate are the referential-action clauses (e.g. "CASCADE", "SET NULL"); an empty string renders nothing (the engine default).
type FullTextSearcher ¶
type FullTextSearcher interface {
Match(columns []string, query string, boolean bool, config string) (string, error)
}
FullTextSearcher is an optional capability a Dialect implements to render a portable full-text search (MatchExpression). Full-text search is genuinely non-portable — PostgreSQL spells it to_tsvector(...) @@ to_tsquery(...) and MySQL MATCH(...) AGAINST(...) — so it renders through this capability and a dialect without it (the standard target) rejects it at compile time (the compiler detects the capability with a type assertion, so adding it is not a breaking change to Dialect). columns and query are already-compiled SQL fragments; boolean selects the engine's boolean query syntax over plain natural-language text, and config is PostgreSQL's text-search configuration (a regconfig name), ignored by engines without an equivalent.
type FuncExpression ¶
type FuncExpression struct {
Name string
Args []Expression
Distinct bool
// contains filtered or unexported fields
}
FuncExpression is a function call such as COALESCE(a, b) or SUM(x). With Distinct set it renders an aggregate over distinct values, name(DISTINCT args...), as in SUM(DISTINCT x); DISTINCT is meaningful only for aggregates.
func DistinctFunc ¶
func DistinctFunc(name string, args ...any) FuncExpression
DistinctFunc creates name(DISTINCT args...), an aggregate over distinct values, as in DistinctFunc("SUM", Col("x")) for SUM(DISTINCT x). Non-expression arguments become bind values.
func Func ¶
func Func(name string, args ...any) FuncExpression
Func creates a function call expression. Non-expression arguments become bind values.
func (FuncExpression) Over ¶
func (f FuncExpression) Over() WindowExpression
Over turns the function into a window expression, e.g. RowNumber().Over().PartitionBy(col).OrderBy(Desc(other)).
func (FuncExpression) Pos ¶
func (p FuncExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (FuncExpression) SQLExpression ¶
func (FuncExpression) SQLExpression()
func (FuncExpression) SQLSelection ¶
func (FuncExpression) SQLSelection()
type FuncRenderer ¶
FuncRenderer is an optional capability a Dialect implements to remap a small set of canonical function names to its native spelling or form (e.g. NOW vs CURRENT_TIMESTAMP, CHAR_LENGTH vs LENGTH). The compiler detects it with a type assertion, so it is not a breaking change to Dialect. name is matched case- insensitively and args are already-compiled argument fragments. It returns (rendered, true) to override the default name(args...) rendering, or ("", false) to fall through unchanged, so a function the dialect does not remap (including any raw Func) passes through verbatim.
type FunctionArg ¶
FunctionArg is one parameter of a CREATE FUNCTION signature: a type (required) with an optional name, mode (IN/OUT/INOUT/VARIADIC), and DEFAULT expression text. Type and Default are rendered verbatim.
type GeneratedColumn ¶
type GeneratedColumn struct {
Expression Expression
Stored bool
// contains filtered or unexported fields
}
GeneratedColumn is a computed column whose value is derived from an expression (which must bind no values), rendered as GENERATED ALWAYS AS (expr) STORED, or VIRTUAL when Stored is false. PostgreSQL supports only stored generated columns (before version 17); MySQL supports both.
type GrantBuilder ¶
type GrantBuilder struct {
// contains filtered or unexported fields
}
GrantBuilder is the fluent constructor for a GrantStmt.
func Grant ¶
func Grant(privileges ...string) GrantBuilder
Grant starts a GRANT builder for the given privilege keywords (e.g. "SELECT", "INSERT"). Pass none for ALL PRIVILEGES.
func (GrantBuilder) On ¶
func (b GrantBuilder) On(objects ...string) GrantBuilder
On sets the objects the privileges apply to, with the default object type TABLE (GRANT ... ON TABLE objects ...).
func (GrantBuilder) OnType ¶
func (b GrantBuilder) OnType(objectType string, objects ...string) GrantBuilder
OnType sets the object type keyword (e.g. "SCHEMA", "SEQUENCE", "DATABASE") and the objects the privileges apply to.
func (GrantBuilder) Stmt ¶
func (b GrantBuilder) Stmt() GrantStmt
Stmt returns the built GRANT statement.
func (GrantBuilder) To ¶
func (b GrantBuilder) To(grantees ...string) GrantBuilder
To sets the grantee roles. Use "PUBLIC" for the PUBLIC pseudo-role.
func (GrantBuilder) ToSQL ¶
func (b GrantBuilder) ToSQL(d Dialect) (string, []any, error)
ToSQL compiles the building GRANT statement.
func (GrantBuilder) WithGrantOption ¶
func (b GrantBuilder) WithGrantOption() GrantBuilder
WithGrantOption adds WITH GRANT OPTION, letting grantees grant the privileges onward.
type GrantStmt ¶
type GrantStmt struct {
Privileges []string
ObjectType string
Objects []Ident
Grantees []Ident
WithGrantOption bool
// contains filtered or unexported fields
}
GrantStmt is the AST for a GRANT statement granting privileges on database objects to roles. An empty privilege list means ALL PRIVILEGES; an empty object type defaults to TABLE. It is a DDL Statement, so it compiles with no bind values.
type GroupingExpression ¶
type GroupingExpression struct {
Kind string
Elements []Expression
// contains filtered or unexported fields
}
GroupingExpression is a ROLLUP or CUBE grouping element in a GROUP BY clause, e.g. ROLLUP (a, b). Kind is "ROLLUP" or "CUBE".
func Cube ¶
func Cube(elements ...Expression) GroupingExpression
Cube builds a CUBE (elements...) grouping element.
func Rollup ¶
func Rollup(elements ...Expression) GroupingExpression
Rollup builds a ROLLUP (elements...) grouping element.
func (GroupingExpression) Pos ¶
func (p GroupingExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (GroupingExpression) SQLExpression ¶
func (GroupingExpression) SQLExpression()
type GroupingSetsExpression ¶
type GroupingSetsExpression struct {
Sets [][]Expression
// contains filtered or unexported fields
}
GroupingSetsExpression is a GROUPING SETS (...) grouping element. Each set is a list of expressions; an empty (nil) set renders as (), the grand total. At least one set is required: zero sets would render the invalid GROUPING SETS ().
func GroupingSets ¶
func GroupingSets(sets ...[]Expression) GroupingSetsExpression
GroupingSets builds a GROUPING SETS element from the given sets.
func (GroupingSetsExpression) Pos ¶
func (p GroupingSetsExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (GroupingSetsExpression) SQLExpression ¶
func (GroupingSetsExpression) SQLExpression()
type ILikeExpression ¶
type ILikeExpression struct {
Left Expression
Pattern Expression
// contains filtered or unexported fields
}
ILikeExpression is a case-insensitive LIKE. It renders per dialect: native ILIKE on PostgreSQL, and the portable LOWER(left) LIKE LOWER(pattern) on engines without an ILIKE operator (MySQL).
func ILike ¶
func ILike(left, pattern any) ILikeExpression
ILike creates a case-insensitive LIKE expression. Non-expression operands become bind values.
func (ILikeExpression) Pos ¶
func (p ILikeExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ILikeExpression) SQLExpression ¶
func (ILikeExpression) SQLExpression()
type Ident ¶
type Ident struct {
Name string
// contains filtered or unexported fields
}
Ident is a SQL identifier — a table, column, schema, or alias name — as written in a statement, together with the source position it was parsed from. The SQL standard (and PostgreSQL) fold unquoted identifiers case-insensitively, so two idents that differ only in case or surrounding space name the same thing: compare with Equal, or canonicalize with Fold, rather than with ==. Equality with == additionally distinguishes positions, so it is never the right test for identifier identity.
Ident is the atom the analysis layer builds its references from — a qualified column reference is an Ident qualifier plus an Ident name. It carries a position (embedded posField) so a parsed identifier reports where it came from in the SQL text; a builder-constructed ident has NoPos. The name itself is a plain string, reachable through Name or String for a lookup at a string boundary (an external metadata lookup, or a policy implemented over plain names).
func Idents ¶
Idents converts names into unpositioned Idents — the helper a parser or builder uses to turn a column/name list taken as plain strings into the AST's Ident slices.
func NewIdent ¶
NewIdent returns an unpositioned Ident for name — the form the builders produce. Its Pos is NoPos; a parser attaches a position with NewIdentAt or by setting NodePos.
func NewIdentAt ¶
NewIdentAt returns an Ident for name positioned at the 0-based byte offset pos in the source SQL. It is the seam a parser uses to record where an identifier was written.
func (Ident) Equal ¶
Equal reports whether id and other name the same identifier, folding case. It ignores position, so two occurrences of the same name compare equal.
func (Ident) Fold ¶
Fold returns id in its canonical case-folded form — trimmed and lower-cased — the form in which case-insensitive idents compare equal, keeping id's position.
func (Ident) IsZero ¶
IsZero reports whether id carries no name — the empty identifier the AST uses for an absent schema, alias, or qualifier.
type IdentityKind ¶
type IdentityKind string
IdentityKind selects a SQL-standard identity column: GENERATED ALWAYS AS IDENTITY (always system-generated) or GENERATED BY DEFAULT AS IDENTITY (a user-supplied value overrides). It is supported on PostgreSQL (10+) and the standard target; MySQL has no IDENTITY (use AutoIncrement).
const ( // IdentityAlways renders GENERATED ALWAYS AS IDENTITY. IdentityAlways IdentityKind = "ALWAYS" // IdentityByDefault renders GENERATED BY DEFAULT AS IDENTITY. IdentityByDefault IdentityKind = "BY DEFAULT" )
type InExpression ¶
type InExpression struct {
Left Expression
Items []Expression
Subquery Query
Negate bool
// contains filtered or unexported fields
}
InExpression tests membership in a list of expressions or, when Subquery is set, in the rows a subquery returns.
func In ¶
func In(left any, items ...any) InExpression
In creates an IN expression. Non-expression items become bind values.
func InQuery ¶
func InQuery(left any, subquery Query) InExpression
InQuery creates a "left IN (subquery)" expression. The subquery must project a single column.
func NotInQuery ¶
func NotInQuery(left any, subquery Query) InExpression
NotInQuery creates a "left NOT IN (subquery)" expression.
func (InExpression) Pos ¶
func (p InExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (InExpression) SQLExpression ¶
func (InExpression) SQLExpression()
type InsertBuilder ¶
type InsertBuilder struct {
// contains filtered or unexported fields
}
InsertBuilder is the fluent constructor for an InsertStmt. Construction lives here and the data on InsertStmt; each method copies the in-progress statement and returns a new builder, so a builder value can be branched and reused.
func InsertInto ¶
func InsertInto(table Table) InsertBuilder
InsertInto creates an INSERT query builder for a table.
func ReplaceInto ¶
func ReplaceInto(table Table) InsertBuilder
ReplaceInto creates a REPLACE query builder for a table — MySQL's delete-then-insert upsert. It shares InsertBuilder's Columns/Values/FromSelect methods but rejects ON CONFLICT and RETURNING, and compiles only on MySQL.
func (InsertBuilder) ColumnCount ¶
func (b InsertBuilder) ColumnCount() int
ColumnCount reports the per-row bind-parameter count; see InsertStmt.ColumnCount.
func (InsertBuilder) Columns ¶
func (b InsertBuilder) Columns(columns ...string) InsertBuilder
Columns sets the column list for the INSERT statement.
func (InsertBuilder) DoNothing ¶
func (b InsertBuilder) DoNothing() InsertBuilder
DoNothing makes the upsert skip conflicting rows (DO NOTHING). PostgreSQL only — MySQL has no DO NOTHING form.
func (InsertBuilder) DoUpdate ¶
func (b InsertBuilder) DoUpdate(assignments ...Assignment) InsertBuilder
DoUpdate makes the upsert update conflicting rows with the given assignments (DO UPDATE SET ...). Reference the proposed row's values with Excluded. Refine it with Where.
func (InsertBuilder) FromSelect ¶
func (b InsertBuilder) FromSelect(query Query) InsertBuilder
FromSelect makes this an INSERT ... SELECT, inserting the rows produced by the query. It is mutually exclusive with Values; the column list is optional (SQL then assigns the query's columns in table order).
func (InsertBuilder) OnConflict ¶
func (b InsertBuilder) OnConflict(columns ...string) InsertBuilder
OnConflict starts an upsert clause targeting a column list — PostgreSQL's ON CONFLICT (cols) — and is followed by an action, DoNothing or DoUpdate:
InsertInto(t).Columns("email", "name").Values("a@x", "Alice").
OnConflict("email").DoUpdate(Set("name", Excluded("name")))
Call it with no columns for MySQL's ON DUPLICATE KEY UPDATE, which has no conflict target. Without a following action the clause is DO NOTHING.
func (InsertBuilder) OnConflictConstraint ¶
func (b InsertBuilder) OnConflictConstraint(name string) InsertBuilder
OnConflictConstraint starts an upsert clause targeting a named constraint (PostgreSQL ON CONFLICT ON CONSTRAINT). PostgreSQL only.
func (InsertBuilder) OnConflictExpr ¶
func (b InsertBuilder) OnConflictExpr(exprs ...Expression) InsertBuilder
OnConflictExpr starts an upsert clause targeting an expression unique index (PostgreSQL ON CONFLICT ((lower(email)))).
func (InsertBuilder) Returning ¶
func (b InsertBuilder) Returning(selections ...Selection) InsertBuilder
Returning adds a RETURNING clause.
func (InsertBuilder) SplitRows ¶
func (b InsertBuilder) SplitRows(n int) []InsertBuilder
SplitRows partitions a VALUES insert into copies of at most n rows each, every copy keeping the same column list, conflict, and returning clauses. It lets a large insert run as several statements without re-deriving the column set per chunk — the columns are already fixed on b. n <= 0, or a query with n or fewer VALUES rows, yields b unchanged as a single element.
func (InsertBuilder) Stmt ¶
func (b InsertBuilder) Stmt() InsertStmt
Stmt returns the built INSERT statement — the pure AST value.
func (InsertBuilder) ToSQL ¶
func (b InsertBuilder) ToSQL(dialect Dialect) (string, []any, error)
ToSQL compiles the building INSERT statement.
func (InsertBuilder) Values ¶
func (b InsertBuilder) Values(values ...any) InsertBuilder
Values appends one row of values. Non-expression values become bind values.
func (InsertBuilder) Where ¶
func (b InsertBuilder) Where(predicate Expression) InsertBuilder
Where adds a predicate to the upsert's DO UPDATE action (PostgreSQL ON CONFLICT ... DO UPDATE ... WHERE) — the only WHERE an INSERT carries. Repeated calls AND together. It is ignored by DO NOTHING.
type InsertStmt ¶
type InsertStmt struct {
Table Table
Columns []Ident
Rows [][]Expression
Select Query
Conflict *ConflictClause
Returning []Selection
// Replace marks a MySQL REPLACE INTO (delete-then-insert) rather than a plain
// INSERT.
Replace bool
// contains filtered or unexported fields
}
InsertStmt is the immutable AST for an INSERT statement (INSERT ... VALUES or INSERT ... SELECT). Exactly one of Rows or Select carries the inserted data; Conflict holds an optional upsert action and Returning an optional RETURNING. Build one with InsertInto; read its exported fields directly to introspection.
func (InsertStmt) ColumnCount ¶
func (q InsertStmt) ColumnCount() int
ColumnCount reports the number of columns each VALUES row binds, the per-row bind-parameter count used to size batches against a parameter limit. It is the explicit Columns list when set, else the width of the first row, else 0.
type JSONAccessExpression ¶
type JSONAccessExpression struct {
Operand Expression
Path []any
AsText bool
// contains filtered or unexported fields
}
JSONAccessExpression extracts the value at a path from a JSON operand. Path steps are object keys (string) or array indices (int) and are rendered as static path literals, not bind parameters. AsText selects the text-returning form. The path is portable: each dialect (a JSONAccessor) renders it in its native syntax (PostgreSQL -> / ->>, MySQL JSON_EXTRACT / JSON_UNQUOTE).
func JSONGet ¶
func JSONGet(operand any, path ...any) JSONAccessExpression
JSONGet extracts the JSON value at path from a JSON operand, e.g. JSONGet(Col("data"), "address", "city") or JSONGet(Col("tags"), 0). Path steps are object keys (string) or array indices (int).
func JSONGetText ¶
func JSONGetText(operand any, path ...any) JSONAccessExpression
JSONGetText is JSONGet returning the extracted value as text (PostgreSQL ->>, MySQL JSON_UNQUOTE(JSON_EXTRACT(...))), so it compares against string values.
func (JSONAccessExpression) Pos ¶
func (p JSONAccessExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (JSONAccessExpression) SQLExpression ¶
func (JSONAccessExpression) SQLExpression()
func (JSONAccessExpression) SQLSelection ¶
func (JSONAccessExpression) SQLSelection()
type JSONAccessor ¶
JSONAccessor is an optional capability a Dialect implements to render JSON path extraction (JSONAccessExpression) in its native syntax. The compiler detects it with a type assertion, so adding it is not a breaking change to Dialect; a dialect that does not implement it rejects JSON access at compile time. operand is the already-compiled JSON expression, path steps are object keys (string) or array indices (int), and asText selects the text form.
type JSONObjectExpression ¶
type JSONObjectExpression struct {
Pairs []Expression
Agg bool
// contains filtered or unexported fields
}
JSONObjectExpression builds a JSON object from key/value pairs. Its argument syntax diverges by engine — MySQL takes a flat JSON_OBJECT(key, value, ...) list, while the SQL/JSON standard (PostgreSQL 16+) requires a key VALUE value separator — so it renders per dialect rather than through Func. Agg selects the JSON_OBJECTAGG aggregate, which takes a single key/value pair.
func JSONObject ¶
func JSONObject(args ...any) JSONObjectExpression
JSONObject creates a JSON_OBJECT expression. Arguments alternate keys and values: JSONObject("id", col, "name", other). Non-expression arguments become bind values.
func JSONObjectAgg ¶
func JSONObjectAgg(key, value any) JSONObjectExpression
JSONObjectAgg creates a JSON_OBJECTAGG(key, value) aggregate that collects the grouped key/value pairs into a JSON object.
func (JSONObjectExpression) Pos ¶
func (p JSONObjectExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (JSONObjectExpression) SQLExpression ¶
func (JSONObjectExpression) SQLExpression()
func (JSONObjectExpression) SQLSelection ¶
func (JSONObjectExpression) SQLSelection()
type JSONObjectRenderer ¶
JSONObjectRenderer is an optional capability for dialects whose JSON object constructor does not use the SQL/JSON standard "key VALUE value" separator (MySQL takes a flat JSON_OBJECT(key, value, ...) list). The compiler detects it with a type assertion, so it is not a breaking change to Dialect; without it the standard VALUE form is used. funcName is JSON_OBJECT or JSON_OBJECTAGG, and pairs are already-compiled {key, value} fragments.
type JoinClause ¶
type JoinClause struct {
Kind string
Source Source
On Expression
Using []Ident
Natural bool
// contains filtered or unexported fields
}
JoinClause represents a JOIN clause. Its condition is given in exactly one way: On for a JOIN ... ON predicate, Using for a JOIN ... USING (columns) on equally named columns, or Natural for a NATURAL JOIN that matches every equally named column implicitly (in which case On and Using are empty). A CROSS JOIN carries none of them.
type JoinedUpdateDeleter ¶
type JoinedUpdateDeleter interface {
// UsesInlineJoins reports the MySQL-style inline-join layout.
UsesInlineJoins() bool
}
JoinedUpdateDeleter is an optional capability for dialects whose multi-table UPDATE/DELETE syntax differs from the SQL-standard FROM/USING form. MySQL puts the joined sources inline (UPDATE t JOIN j ON ... SET ...) and names the delete targets after DELETE (DELETE t FROM t JOIN ...), whereas PostgreSQL appends them after SET / the target with FROM / USING. The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect that does not implement it uses the standard FROM/USING layout.
type LockOption ¶
type LockOption func(*lockClause)
LockOption refines a SELECT row-locking clause (ForUpdate / ForShare / …): SkipLocked, NoWait, and LockOf.
func LockOf ¶
func LockOf(tables ...string) LockOption
LockOf restricts the lock to rows from the named tables/aliases (FOR UPDATE OF t), for a join that should lock only some of its inputs.
func NoWait ¶
func NoWait() LockOption
NoWait adds NOWAIT, erroring immediately instead of waiting when a selected row is already locked.
func SkipLocked ¶
func SkipLocked() LockOption
SkipLocked adds SKIP LOCKED, skipping rows another transaction has already locked rather than waiting (the queue-worker pattern).
type LockTablesStmt ¶
type LockTablesStmt struct {
Locks []TableLock
// contains filtered or unexported fields
}
LockTablesStmt acquires session table locks (MySQL LOCK TABLES t READ, u WRITE). It is a MySQL utility statement.
func LockTables ¶
func LockTables(locks ...TableLock) LockTablesStmt
LockTables builds a LOCK TABLES statement over the given table locks.
type LogicalExpression ¶
type LogicalExpression struct {
Operator string
Operands []Expression
// contains filtered or unexported fields
}
LogicalExpression combines predicates with AND or OR.
func (LogicalExpression) Pos ¶
func (p LogicalExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (LogicalExpression) SQLExpression ¶
func (LogicalExpression) SQLExpression()
type MatchBuilder ¶
type MatchBuilder struct {
// contains filtered or unexported fields
}
MatchBuilder collects the columns of a full-text search; complete it with Against to bind the query.
func Match ¶
func Match(columns ...Expression) MatchBuilder
Match begins a portable full-text search over one or more columns. Complete it with Against:
sql.Match(sql.Col("title"), sql.Col("body")).Against("quick fox")
On PostgreSQL the columns form the searched document (concatenated with a space when there is more than one); on MySQL they are the MATCH column list and must be covered by a FULLTEXT index.
func (MatchBuilder) Against ¶
func (m MatchBuilder) Against(query any) MatchExpression
Against binds the search query, finishing the match. A non-expression query becomes a bind value.
type MatchExpression ¶
type MatchExpression struct {
Columns []Expression
Query Expression
Mode FTSMode
Config string
}
MatchExpression is a portable full-text search predicate over one or more columns. It renders through a FullTextSearcher dialect, so the same builder compiles to PostgreSQL's to_tsvector(...) @@ to_tsquery(...) and MySQL's MATCH(...) AGAINST(...); a dialect without that capability (the standard target) rejects it at compile time. Config is PostgreSQL's text-search configuration (a regconfig name such as "english") and is ignored by engines that have no equivalent.
func (MatchExpression) Boolean ¶
func (e MatchExpression) Boolean() MatchExpression
Boolean interprets the query with the engine's boolean operator syntax (PostgreSQL websearch_to_tsquery, MySQL IN BOOLEAN MODE) instead of as plain natural-language text.
func (MatchExpression) SQLExpression ¶
func (MatchExpression) SQLExpression()
func (MatchExpression) WithConfig ¶
func (e MatchExpression) WithConfig(name string) MatchExpression
WithConfig sets PostgreSQL's text-search configuration (a regconfig name such as "english"). It is ignored by engines that have no equivalent (MySQL).
type MergeBuilder ¶
type MergeBuilder struct {
// contains filtered or unexported fields
}
MergeBuilder is the fluent constructor for a MergeStmt.
func MergeInto ¶
func MergeInto(target Table) MergeBuilder
MergeInto creates a MERGE query builder for a target table.
func (MergeBuilder) As ¶
func (b MergeBuilder) As(alias string) MergeBuilder
As sets an alias for the target table (MERGE INTO target AS alias).
func (MergeBuilder) On ¶
func (b MergeBuilder) On(condition Expression) MergeBuilder
On sets the join condition that pairs source rows with target rows.
func (MergeBuilder) Returning ¶
func (b MergeBuilder) Returning(selections ...Selection) MergeBuilder
Returning adds a RETURNING clause (PostgreSQL 17+).
func (MergeBuilder) Stmt ¶
func (b MergeBuilder) Stmt() MergeStmt
Stmt returns the built MERGE statement — the pure AST value.
func (MergeBuilder) ToSQL ¶
func (b MergeBuilder) ToSQL(dialect Dialect) (string, []any, error)
ToSQL compiles the building MERGE statement.
func (MergeBuilder) Using ¶
func (b MergeBuilder) Using(source Source) MergeBuilder
Using sets the data source matched against the target — a table or subquery, optionally aliased with SourceAlias/Alias.
func (MergeBuilder) When ¶
func (b MergeBuilder) When(whens ...MergeWhen) MergeBuilder
When appends WHEN clauses, evaluated in order for each row.
func (MergeBuilder) WithCTE ¶
func (b MergeBuilder) WithCTE(ctes ...CTE) MergeBuilder
WithCTE prepends common table expressions (WITH ...).
type MergeDialect ¶
type MergeDialect interface {
SupportsMerge() bool
}
MergeDialect is an optional capability a Dialect implements to report support for the MERGE statement (SQL:2003). The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it (or returning false) rejects MERGE at compile time. PostgreSQL (15+) and the standard target support it; MySQL does not.
type MergeStmt ¶
type MergeStmt struct {
With []CTE
Target Table
TargetAlias Ident
Using Source
On Expression
When []MergeWhenClause
Returning []Selection
// contains filtered or unexported fields
}
MergeStmt is the immutable AST for a MERGE statement (SQL:2003, PostgreSQL 15+): it matches rows of a target table against a USING data source on an ON condition and applies a list of WHEN clauses. Build it with MergeInto; read its exported fields directly to introspection.
type MergeWhen ¶
type MergeWhen struct {
// contains filtered or unexported fields
}
MergeWhen is the fluent builder for one WHEN clause of a MERGE: a match kind, an optional AND condition, and the action to perform. Build it with WhenMatched, WhenNotMatched, or WhenNotMatchedBySource, then chain And and a Then* action; pass the result to MergeBuilder.When, which records it as the MergeWhenClause carried by MergeStmt.
func WhenMatched ¶
func WhenMatched() MergeWhen
WhenMatched starts a WHEN MATCHED clause, applied to rows present in both the target and the source. Its action is ThenUpdate, ThenDelete, or ThenDoNothing.
func WhenNotMatched ¶
func WhenNotMatched() MergeWhen
WhenNotMatched starts a WHEN NOT MATCHED [BY TARGET] clause, applied to source rows with no target match. Its action is ThenInsert or ThenDoNothing.
func WhenNotMatchedBySource ¶
func WhenNotMatchedBySource() MergeWhen
WhenNotMatchedBySource starts a WHEN NOT MATCHED BY SOURCE clause, applied to target rows with no source match. Its action is ThenUpdate, ThenDelete, or ThenDoNothing.
func (MergeWhen) And ¶
func (w MergeWhen) And(condition Expression) MergeWhen
And adds an extra condition to the clause (WHEN ... AND condition THEN ...), narrowing the rows it applies to.
func (MergeWhen) ThenDelete ¶
ThenDelete makes the clause DELETE the matched row.
func (MergeWhen) ThenDoNothing ¶
ThenDoNothing makes the clause take no action (DO NOTHING) for the rows it matches, skipping them.
func (MergeWhen) ThenInsert ¶
ThenInsert makes the clause INSERT a row. Non-expression values become bind values; pass no columns and no values for INSERT DEFAULT VALUES.
func (MergeWhen) ThenUpdate ¶
func (w MergeWhen) ThenUpdate(assignments ...Assignment) MergeWhen
ThenUpdate makes the clause UPDATE SET the given assignments.
type MergeWhenClause ¶
type MergeWhenClause struct {
Match string
Condition Expression
Action string
Sets []Assignment
InsertColumns []Ident
InsertValues []Expression
InsertDefault bool
// contains filtered or unexported fields
}
MergeWhenClause is one MERGE WHEN clause as carried by MergeStmt.When. Match is "MATCHED", "NOT MATCHED", or "NOT MATCHED BY SOURCE"; Action is "UPDATE", "DELETE", "INSERT", "DO NOTHING", or "" when none was set. Sets applies to UPDATE; InsertColumns/InsertValues (or InsertDefault) to INSERT.
type MySQLDialect ¶
type MySQLDialect struct{}
MySQLDialect implements MySQL identifier quoting, placeholders, and DDL rendering. The query builders compile against it; RETURNING is rejected at compile time (MySQL has no RETURNING — read generated keys via Result.LastInsertId). sqlkit's schema loading is PostgreSQL-only for now.
func (MySQLDialect) AutoIncrementColumn ¶
func (d MySQLDialect) AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
func (MySQLDialect) ColumnCommentStatement ¶
func (MySQLDialect) ColumnCommentStatement(string, string, string) string
func (MySQLDialect) ColumnType ¶
func (MySQLDialect) ColumnType(name string, length, precision, scale int) string
func (MySQLDialect) Concat ¶
func (MySQLDialect) Concat(operands []string) string
Concat renders MySQL string concatenation, whose || operator means logical OR.
func (MySQLDialect) DropForeignKey ¶
func (MySQLDialect) DropForeignKey(qualifiedTable, quotedConstraint string) string
func (MySQLDialect) DropIndex ¶
func (MySQLDialect) DropIndex(_, quotedIndex, qualifiedTable string) string
func (MySQLDialect) Excluded ¶
func (d MySQLDialect) Excluded(column string) string
Excluded renders MySQL's reference to the proposed row value, VALUES(col).
func (MySQLDialect) InlineColumnComment ¶
func (MySQLDialect) InlineColumnComment(comment string) string
func (MySQLDialect) InlineTableComment ¶
func (MySQLDialect) InlineTableComment(comment string) string
func (MySQLDialect) IsDistinctFrom ¶
func (MySQLDialect) IsDistinctFrom(left, right string, negate bool) string
IsDistinctFrom renders MySQL's null-safe comparison with the <=> operator, which MySQL provides in place of the SQL-standard IS [NOT] DISTINCT FROM. The operator is itself IS NOT DISTINCT FROM (null-safe equality); IS DISTINCT FROM is its negation.
func (MySQLDialect) JSONAccess ¶
JSONAccess builds a JSON path string ($.a[0].b) and wraps the operand in JSON_EXTRACT, adding JSON_UNQUOTE for the text form.
func (MySQLDialect) JSONObject ¶
func (MySQLDialect) JSONObject(funcName string, pairs [][2]string) string
JSONObject renders MySQL's flat JSON_OBJECT(key, value, ...) form, which does not use the SQL/JSON standard VALUE separator.
func (MySQLDialect) LockClause ¶
func (MySQLDialect) LockClause(strength, of, wait string) (string, error)
LockClause renders MySQL's row-locking clause (8.0+). MySQL has only FOR UPDATE and FOR SHARE; the PostgreSQL-only NO KEY UPDATE / KEY SHARE strengths are rejected.
func (MySQLDialect) Match ¶
Match renders full-text search as MATCH(columns) AGAINST(query). A boolean query uses IN BOOLEAN MODE, a natural-language query IN NATURAL LANGUAGE MODE. The columns must be covered by a FULLTEXT index. config has no MySQL equivalent and is ignored.
func (MySQLDialect) MaxBindParams ¶
func (MySQLDialect) MaxBindParams() int
MaxBindParams reports MySQL's per-statement placeholder cap (65535), the limit of the 16-bit parameter count in the client/server protocol.
func (MySQLDialect) Placeholder ¶
func (MySQLDialect) Placeholder(int) string
func (MySQLDialect) QuoteIdent ¶
func (d MySQLDialect) QuoteIdent(identifier string) string
func (MySQLDialect) QuoteName ¶
func (MySQLDialect) QuoteName(name string) string
func (MySQLDialect) Regexp ¶
func (MySQLDialect) Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
Regexp renders MySQL's REGEXP / NOT REGEXP match. MySQL has no inline case-insensitivity flag (it follows the column/expression collation), so a case-insensitive match is rejected rather than silently rendered case- sensitive.
func (MySQLDialect) StringAgg ¶
func (MySQLDialect) StringAgg(arg, delimiter string) string
StringAgg renders MySQL's GROUP_CONCAT, whose SEPARATOR keyword takes the delimiter literal in place of the standard STRING_AGG second argument.
func (MySQLDialect) SupportsReturning ¶
func (MySQLDialect) SupportsReturning() bool
SupportsReturning reports RETURNING support (MySQL lacks it).
func (MySQLDialect) TableCommentStatement ¶
func (MySQLDialect) TableCommentStatement(string, string) string
func (MySQLDialect) Upsert ¶
func (MySQLDialect) Upsert(cl UpsertClause) (string, error)
Upsert renders MySQL's ON DUPLICATE KEY UPDATE clause. MySQL infers the conflicting key, so the target is ignored; it has no DO NOTHING form and no per-action WHERE, both of which are reported as errors.
func (MySQLDialect) UsesInlineJoins ¶
func (MySQLDialect) UsesInlineJoins() bool
UsesInlineJoins selects MySQL's inline multi-table UPDATE/DELETE layout.
func (MySQLDialect) UsesValuesUnion ¶
func (MySQLDialect) UsesValuesUnion() bool
UsesValuesUnion selects MySQL's UNION-ALL-of-SELECTs rendering for a VALUES derived table, since MySQL cannot alias VALUES columns.
type NamedWindow ¶
type NamedWindow struct {
Name Ident
Partitions []Expression
OrderByTerms []OrderTerm
FrameClause string
// contains filtered or unexported fields
}
NamedWindow defines a reusable window in a SELECT's WINDOW clause, referenced from an OVER clause by name (WindowExpression.Named). It renders as "name AS (PARTITION BY ... ORDER BY ... frame)".
func WindowDef ¶
func WindowDef(name string) NamedWindow
WindowDef starts a named window definition for a SELECT's WINDOW clause; chain PartitionBy / OrderBy / Frame to build it.
func (NamedWindow) Frame ¶
func (w NamedWindow) Frame(frame string) NamedWindow
Frame sets a raw frame clause such as "ROWS BETWEEN 1 PRECEDING AND CURRENT ROW".
func (NamedWindow) OrderBy ¶
func (w NamedWindow) OrderBy(terms ...OrderTerm) NamedWindow
OrderBy adds ORDER BY terms to the window definition.
func (NamedWindow) PartitionBy ¶
func (w NamedWindow) PartitionBy(exprs ...Expression) NamedWindow
PartitionBy adds PARTITION BY expressions to the window definition.
type Node ¶
type Node interface{ Pos() int }
Node is an AST node that can report where it was parsed from: the 0-based byte offset of its start in the source SQL, or NoPos when it was built with the query builders rather than parsed. The compiler ignores positions; they are metadata, so two queries that differ only in their nodes' offsets compile identically.
Only the byte offset is kept. A line and column are derived from the original SQL text downstream (a linter, a diagnostic) by scanning to the offset, so a node need not carry them.
type NotExpression ¶
type NotExpression struct {
Operand Expression
// contains filtered or unexported fields
}
NotExpression negates a predicate.
func (NotExpression) Pos ¶
func (p NotExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (NotExpression) SQLExpression ¶
func (NotExpression) SQLExpression()
type NullPredicate ¶
type NullPredicate struct {
Operand Expression
Negate bool
// contains filtered or unexported fields
}
NullPredicate tests an expression for IS NULL / IS NOT NULL.
func IsNotNull ¶
func IsNotNull(operand any) NullPredicate
IsNotNull creates an IS NOT NULL predicate.
func (NullPredicate) Pos ¶
func (p NullPredicate) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (NullPredicate) SQLExpression ¶
func (NullPredicate) SQLExpression()
type NullSafeEqualityDialect ¶
NullSafeEqualityDialect is an optional capability for dialects that spell the null-safe comparison (DistinctPredicate, IS [NOT] DISTINCT FROM) differently from the SQL standard. MySQL has no IS DISTINCT FROM and uses the null-safe equality operator <=> instead. The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it renders the standard IS [NOT] DISTINCT FROM (PostgreSQL, the standard target). left and right are already-compiled SQL fragments; negate selects IS NOT DISTINCT FROM (the null-safe equality).
type NullsOrderingDialect ¶
type NullsOrderingDialect interface {
SupportsNullsOrdering() bool
}
NullsOrderingDialect is an optional capability a Dialect implements to allow NULLS FIRST / NULLS LAST modifiers on ORDER BY terms. PostgreSQL and standard SQL support them; MySQL does not, so the compiler rejects the modifier there rather than emit SQL MySQL cannot parse.
type OrderTerm ¶
type OrderTerm struct {
Expr Expression
Desc bool
Nulls string // "", "FIRST", or "LAST" (PostgreSQL NULLS ordering)
// contains filtered or unexported fields
}
OrderTerm is one ORDER BY term.
func (OrderTerm) NullsFirst ¶
NullsFirst orders NULLs before non-NULLs (PostgreSQL NULLS FIRST). It is a PostgreSQL extension; MySQL does not accept the NULLS clause.
type PositionExpression ¶
type PositionExpression struct {
Substring Expression
String Expression
// contains filtered or unexported fields
}
PositionExpression finds the 1-based index of the first occurrence of a substring within a string, or 0 when it does not occur. It renders as the SQL standard POSITION(substring IN string), which PostgreSQL and MySQL both accept (the comma forms STRPOS / LOCATE diverge, so this is the portable spelling).
func Position ¶
func Position(substring, str any) PositionExpression
Position creates POSITION(substring IN str). Non-expression operands become bind values, as in Position("@", Col("email")).
func (PositionExpression) Pos ¶
func (p PositionExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (PositionExpression) SQLExpression ¶
func (PositionExpression) SQLExpression()
func (PositionExpression) SQLSelection ¶
func (PositionExpression) SQLSelection()
type PostgreSQLDialect ¶
type PostgreSQLDialect struct{}
PostgreSQLDialect implements PostgreSQL identifier quoting, placeholders, and DDL rendering.
func (PostgreSQLDialect) ArrayConstructor ¶
func (PostgreSQLDialect) ArrayConstructor(elements []string) string
ArrayConstructor renders PostgreSQL's ARRAY[...] literal.
func (PostgreSQLDialect) AutoIncrementColumn ¶
func (PostgreSQLDialect) AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
func (PostgreSQLDialect) ColumnCommentStatement ¶
func (p PostgreSQLDialect) ColumnCommentStatement(quotedTable, quotedColumn, comment string) string
func (PostgreSQLDialect) ColumnType ¶
func (PostgreSQLDialect) ColumnType(name string, length, precision, scale int) string
func (PostgreSQLDialect) DropForeignKey ¶
func (PostgreSQLDialect) DropForeignKey(qualifiedTable, quotedConstraint string) string
func (PostgreSQLDialect) DropIndex ¶
func (PostgreSQLDialect) DropIndex(qualifiedIndex, _, _ string) string
func (PostgreSQLDialect) ILike ¶
func (PostgreSQLDialect) ILike(left, pattern string) string
ILike renders PostgreSQL's native case-insensitive ILIKE operator.
func (PostgreSQLDialect) InlineColumnComment ¶
func (PostgreSQLDialect) InlineColumnComment(string) string
func (PostgreSQLDialect) InlineTableComment ¶
func (PostgreSQLDialect) InlineTableComment(string) string
func (PostgreSQLDialect) JSONAccess ¶
JSONAccess chains the -> / ->> operators, one per path step (the last uses ->> when asText), e.g. (("data" -> 'a') -> 0) ->> 'b'.
func (PostgreSQLDialect) LockClause ¶
func (PostgreSQLDialect) LockClause(strength, of, wait string) (string, error)
LockClause renders PostgreSQL's row-locking clause; it supports all four lock strengths (UPDATE, NO KEY UPDATE, SHARE, KEY SHARE).
func (PostgreSQLDialect) Match ¶
func (PostgreSQLDialect) Match(columns []string, query string, boolean bool, config string) (string, error)
Match renders full-text search as to_tsvector(...) @@ to_tsquery(...). The columns form the searched document (concatenated null-safely with a space when there is more than one); a boolean query uses websearch_to_tsquery and a natural-language query plainto_tsquery. config, when set, is passed as the regconfig to both to_tsvector and the query function.
func (PostgreSQLDialect) MaxBindParams ¶
func (PostgreSQLDialect) MaxBindParams() int
MaxBindParams reports PostgreSQL's per-statement bind-parameter cap (65535), the limit of the 16-bit parameter count in the wire protocol.
func (PostgreSQLDialect) Placeholder ¶
func (PostgreSQLDialect) Placeholder(position int) string
func (PostgreSQLDialect) QuoteIdent ¶
func (d PostgreSQLDialect) QuoteIdent(identifier string) string
func (PostgreSQLDialect) QuoteName ¶
func (PostgreSQLDialect) QuoteName(name string) string
func (PostgreSQLDialect) Regexp ¶
func (PostgreSQLDialect) Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
Regexp renders PostgreSQL's POSIX regular-expression match operators: ~ / ~* for match (case-sensitive / insensitive) and !~ / !~* for the negations.
func (PostgreSQLDialect) SimilarTo ¶
func (PostgreSQLDialect) SimilarTo(left, pattern string, negate bool) string
SimilarTo renders PostgreSQL's SIMILAR TO / NOT SIMILAR TO operator.
func (PostgreSQLDialect) SupportsDistinctOn ¶
func (PostgreSQLDialect) SupportsDistinctOn() bool
SupportsDistinctOn reports PostgreSQL's support for SELECT DISTINCT ON.
func (PostgreSQLDialect) SupportsMerge ¶
func (PostgreSQLDialect) SupportsMerge() bool
SupportsMerge reports MERGE support (PostgreSQL 15+ has it).
func (PostgreSQLDialect) SupportsNullsOrdering ¶
func (PostgreSQLDialect) SupportsNullsOrdering() bool
SupportsNullsOrdering reports PostgreSQL's support for NULLS FIRST/LAST.
func (PostgreSQLDialect) SupportsReturning ¶
func (PostgreSQLDialect) SupportsReturning() bool
SupportsReturning reports RETURNING support (PostgreSQL has it).
func (PostgreSQLDialect) TableCommentStatement ¶
func (p PostgreSQLDialect) TableCommentStatement(quotedTable, comment string) string
func (PostgreSQLDialect) Upsert ¶
func (PostgreSQLDialect) Upsert(cl UpsertClause) (string, error)
Upsert renders PostgreSQL's ON CONFLICT clause.
func (PostgreSQLDialect) ValuesCastType ¶
func (d PostgreSQLDialect) ValuesCastType(value any) (string, bool)
ValuesCastType maps a Go value to the PostgreSQL type a VALUES column should be cast to so the server does not default the parameter to text. It dereferences pointers (nullable fields) and reports ok = false for nil or an unrecognized type, leaving the value uncast.
type QuantifiedArrayExpression ¶
type QuantifiedArrayExpression struct {
Left Expression
Operator string // comparison operator, e.g. "=", ">", "<>"
Quantifier string // "ANY" or "ALL"
Array Expression
// contains filtered or unexported fields
}
QuantifiedArrayExpression compares an operand against the elements of an array with a quantifier — ANY (a synonym for SOME) or ALL — as in "x = ANY(array)". Unlike QuantifiedExpression, which quantifies over a subquery's rows, this quantifies over an array value: an ARRAY[...] constructor or a single bound array parameter. "x = ANY($1)" is the idiomatic PostgreSQL form of "x IN (...)" that binds the whole list as one parameter, and "x <> ALL($1)" of "x NOT IN (...)". Arrays are non-portable, so it is gated by ArrayDialect.
func AllArray ¶
func AllArray(left any, operator string, array Expression) QuantifiedArrayExpression
AllArray creates a "left <operator> ALL(array)" expression: true when the comparison holds for every array element (and, vacuously, for an empty array).
func AnyArray ¶
func AnyArray(left any, operator string, array Expression) QuantifiedArrayExpression
AnyArray creates a "left <operator> ANY(array)" expression: true when the comparison holds for at least one array element. A non-expression left operand becomes a bind value; array is an ArrayExpression or a bound array value.
func (QuantifiedArrayExpression) Pos ¶
func (p QuantifiedArrayExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (QuantifiedArrayExpression) SQLExpression ¶
func (QuantifiedArrayExpression) SQLExpression()
type QuantifiedExpression ¶
type QuantifiedExpression struct {
Left Expression
Operator string // comparison operator, e.g. "=", ">", "<>"
Quantifier string // "ANY" or "ALL"
Query Query
// contains filtered or unexported fields
}
QuantifiedExpression compares an operand against the rows of a subquery with a quantifier — ANY (a synonym for SOME) or ALL — as in "x > ALL (subquery)". It generalizes IN/NOT IN, which are "= ANY"/"<> ALL", to the ordering operators.
func All ¶
func All(left any, operator string, query Query) QuantifiedExpression
All creates a "left <operator> ALL (subquery)" expression: true when the comparison holds for every row the subquery returns (and, vacuously, when it returns none). A non-expression left operand becomes a bind value.
func Any ¶
func Any(left any, operator string, query Query) QuantifiedExpression
Any creates a "left <operator> ANY (subquery)" expression: true when the comparison holds for at least one row the subquery returns. A non-expression left operand becomes a bind value.
func (QuantifiedExpression) Pos ¶
func (p QuantifiedExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (QuantifiedExpression) SQLExpression ¶
func (QuantifiedExpression) SQLExpression()
type Query ¶
Query is implemented by SQL statements that can be compiled.
func SetPos ¶
SetPos records pos as the source position of q's top-level statement node and returns q. It is the seam a parser uses to attach a statement's offset: PostgreSQL records that offset on the RawStmt wrapper, not on the statement node, and the builders keep their statement in an unexported field, so it cannot be set from outside the package. A query kind that carries no position (a raw passthrough) is returned unchanged.
type Quoter ¶
type Quoter interface {
SQLQuoted() bool
}
Quoter lets a value opt into being rendered as a single-quoted string literal by the inline compile mode (see CompileInline), so a string-wrapping type (a SecureString, say) whose Go type is not a plain string is quoted without an explicit Quote call. Val consults it when constructing a ValueExpression.
type RawExpression ¶
type RawExpression string
RawExpression is an escape hatch for static SQL fragments.
func CurrentDate ¶
func CurrentDate() RawExpression
CurrentDate creates CURRENT_DATE, the current date. It is a niladic keyword rather than a function call: the SQL standard and PostgreSQL reject the empty parentheses NOW() would render, so it is emitted without them.
func CurrentTime ¶
func CurrentTime() RawExpression
CurrentTime creates CURRENT_TIME, the current time of day. Like CurrentDate it is rendered without parentheses.
func CurrentTimestamp ¶
func CurrentTimestamp() RawExpression
CurrentTimestamp creates CURRENT_TIMESTAMP, the current date and time. Like CurrentDate it is rendered without parentheses.
func (RawExpression) Pos ¶
func (RawExpression) Pos() int
Pos reports NoPos: a raw fragment is a bare string, so unlike the other expression nodes it embeds no posField and carries no parsed position.
func (RawExpression) SQLExpression ¶
func (RawExpression) SQLExpression()
func (RawExpression) SQLSelection ¶
func (RawExpression) SQLSelection()
type RawQuery ¶
type RawQuery struct {
// contains filtered or unexported fields
}
RawQuery is a whole SQL statement kept as verbatim text plus optional bind arguments — the statement-level counterpart to RawExpression. It is an escape hatch for statements the typed builders do not model: it compiles to its text unchanged on every dialect, so the SQL must already be valid for the target.
The sqlparse frontends use it to round-trip statements they cannot yet map to a typed query, deparsing the parse tree back to SQL so that every statement a frontend's grammar accepts still yields a usable Query.
func RawSQL ¶
RawSQL builds a RawQuery from verbatim SQL text and optional bind arguments. The text is emitted as-is, so any placeholders it contains must already match the target dialect's spelling.
type RawType ¶
type RawType string
RawType is a verbatim type clause for hand-written DDL, e.g. RawType("bigserial") or RawType("varchar(64)"). It ignores the dialect.
type RefreshMaterializedViewBuilder ¶
type RefreshMaterializedViewBuilder struct {
// contains filtered or unexported fields
}
RefreshMaterializedViewBuilder is the fluent constructor for a RefreshMaterializedViewStmt.
func RefreshMaterializedView ¶
func RefreshMaterializedView(table Table) RefreshMaterializedViewBuilder
RefreshMaterializedView starts a REFRESH MATERIALIZED VIEW builder.
func (RefreshMaterializedViewBuilder) Concurrently ¶
func (b RefreshMaterializedViewBuilder) Concurrently() RefreshMaterializedViewBuilder
Concurrently adds CONCURRENTLY.
func (RefreshMaterializedViewBuilder) Stmt ¶
func (b RefreshMaterializedViewBuilder) Stmt() RefreshMaterializedViewStmt
Stmt returns the built REFRESH MATERIALIZED VIEW statement.
func (RefreshMaterializedViewBuilder) ToSQL ¶
func (b RefreshMaterializedViewBuilder) ToSQL(d Dialect) (string, []any, error)
ToSQL compiles the building REFRESH MATERIALIZED VIEW statement.
func (RefreshMaterializedViewBuilder) WithNoData ¶
func (b RefreshMaterializedViewBuilder) WithNoData() RefreshMaterializedViewBuilder
WithNoData adds WITH NO DATA, leaving the view unpopulated.
type RefreshMaterializedViewStmt ¶
type RefreshMaterializedViewStmt struct {
Table Table
Concurrently bool
WithNoData bool
// contains filtered or unexported fields
}
RefreshMaterializedViewStmt is the AST for a REFRESH MATERIALIZED VIEW statement.
type RegexpExpression ¶
type RegexpExpression struct {
Left Expression
Pattern Expression
Negate bool
CaseInsensitive bool
// contains filtered or unexported fields
}
RegexpExpression is a regular-expression match. Regex syntax and operators are genuinely non-portable, so it renders per dialect through a RegexpMatcher (PostgreSQL ~ / ~* / !~ / !~*, MySQL REGEXP / NOT REGEXP, the SQL standard LIKE_REGEX [FLAG 'i']); a dialect without that capability rejects it at compile time. CaseInsensitive selects a case-insensitive match where the dialect can express one inline (it errors on dialects that cannot).
func IRegexp ¶
func IRegexp(left, pattern any) RegexpExpression
IRegexp creates a case-insensitive regular-expression match.
func NotIRegexp ¶
func NotIRegexp(left, pattern any) RegexpExpression
NotIRegexp creates a negated case-insensitive regular-expression match.
func NotRegexp ¶
func NotRegexp(left, pattern any) RegexpExpression
NotRegexp creates a negated regular-expression match.
func Regexp ¶
func Regexp(left, pattern any) RegexpExpression
Regexp creates a "left ~ pattern" regular-expression match. Non-expression operands become bind values.
func (RegexpExpression) Pos ¶
func (p RegexpExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (RegexpExpression) SQLExpression ¶
func (RegexpExpression) SQLExpression()
type RegexpMatcher ¶
type RegexpMatcher interface {
Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
}
RegexpMatcher is an optional capability a Dialect implements to render a regular-expression match (RegexpExpression) in its native syntax (PostgreSQL ~ / ~*, MySQL REGEXP, the SQL standard LIKE_REGEX). The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it rejects regex at compile time, because regex syntax is genuinely non-portable. left and pattern are already-compiled SQL fragments; caseInsensitive requests a case-insensitive match, which a dialect that cannot express one inline reports as an error.
type RenameColumnStmt ¶
type RenameColumnStmt struct {
Table Table
OldName Ident
NewName Ident
// contains filtered or unexported fields
}
RenameColumnStmt is the AST for an ALTER TABLE ... RENAME COLUMN ... TO statement. It has no options, so it is constructed directly.
func RenameColumn ¶
func RenameColumn(table Table, oldName, newName string) RenameColumnStmt
RenameColumn builds a statement that renames a column of a table.
type RenameTableStmt ¶
RenameTableStmt is the AST for an ALTER TABLE ... RENAME TO statement. It has no options, so it is constructed directly with RenameTable.
func RenameTable ¶
func RenameTable(table Table, newName string) RenameTableStmt
RenameTable builds a statement that renames a table to newName.
type RevokeBuilder ¶
type RevokeBuilder struct {
// contains filtered or unexported fields
}
RevokeBuilder is the fluent constructor for a RevokeStmt.
func Revoke ¶
func Revoke(privileges ...string) RevokeBuilder
Revoke starts a REVOKE builder for the given privilege keywords. Pass none for ALL PRIVILEGES.
func (RevokeBuilder) Cascade ¶
func (b RevokeBuilder) Cascade() RevokeBuilder
Cascade adds CASCADE, also revoking dependent privileges.
func (RevokeBuilder) From ¶
func (b RevokeBuilder) From(grantees ...string) RevokeBuilder
From sets the roles to revoke from. Use "PUBLIC" for the PUBLIC pseudo-role.
func (RevokeBuilder) GrantOptionFor ¶
func (b RevokeBuilder) GrantOptionFor() RevokeBuilder
GrantOptionFor revokes only the grant option (REVOKE GRANT OPTION FOR ...), leaving the privileges themselves.
func (RevokeBuilder) On ¶
func (b RevokeBuilder) On(objects ...string) RevokeBuilder
On sets the objects to revoke from, with the default object type TABLE.
func (RevokeBuilder) OnType ¶
func (b RevokeBuilder) OnType(objectType string, objects ...string) RevokeBuilder
OnType sets the object type keyword and the objects to revoke from.
func (RevokeBuilder) Restrict ¶
func (b RevokeBuilder) Restrict() RevokeBuilder
Restrict adds RESTRICT, refusing to revoke when dependent privileges exist.
func (RevokeBuilder) Stmt ¶
func (b RevokeBuilder) Stmt() RevokeStmt
Stmt returns the built REVOKE statement.
type RevokeStmt ¶
type RevokeStmt struct {
GrantOptionFor bool
Privileges []string
ObjectType string
Objects []Ident
Grantees []Ident
Behavior string
// contains filtered or unexported fields
}
RevokeStmt is the AST for a REVOKE statement removing privileges on database objects from roles. It mirrors GrantStmt and is likewise a DDL Statement. Behavior is "", "CASCADE", or "RESTRICT".
type RowExpression ¶
type RowExpression struct {
Elements []Expression
// contains filtered or unexported fields
}
RowExpression is a row value constructor: a parenthesized list of expressions such as (a, b). It backs row-wise comparisons ((a, b) = (c, d)) and row-wise membership ((a, b) IN ((1, 2), (3, 4))), where it can stand on either side of the operator and as each IN item.
func Row ¶
func Row(elements ...any) RowExpression
Row creates a row value constructor (a, b, ...). Non-expression elements become bind values.
func (RowExpression) Pos ¶
func (p RowExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (RowExpression) SQLExpression ¶
func (RowExpression) SQLExpression()
type RowLocker ¶
RowLocker is an optional capability a Dialect implements to render a SELECT row-locking clause (SelectBuilder.ForUpdate / ForShare / …). PostgreSQL and MySQL (8.0+) support it; the standard target does not, and rejects it at compile time. The compiler detects it with a type assertion, so it is not a breaking change to Dialect. strength is "UPDATE", "SHARE", "NO KEY UPDATE", or "KEY SHARE"; of is the already-quoted, comma-joined OF table list ("" when none); wait is "", "NOWAIT", or "SKIP LOCKED". It returns the leading-space " FOR ..." fragment, or an error when the dialect cannot express the lock.
type ScalarSubqueryExpression ¶
type ScalarSubqueryExpression struct {
Query Query
// contains filtered or unexported fields
}
ScalarSubqueryExpression wraps a subquery so it can stand in for a single value — in a SELECT-list projection, a comparison, or anywhere else an Expression is expected. The subquery must project a single column and return at most one row; it may be correlated, referencing columns of the enclosing query. It renders as the parenthesized subquery and shares the outer statement's bind placeholder numbering.
func ScalarSubquery ¶
func ScalarSubquery(query Query) ScalarSubqueryExpression
ScalarSubquery wraps a subquery as a scalar expression, the form behind a correlated scalar subquery such as SELECT u.id, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) FROM users u.
func (ScalarSubqueryExpression) Pos ¶
func (p ScalarSubqueryExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ScalarSubqueryExpression) SQLExpression ¶
func (ScalarSubqueryExpression) SQLExpression()
func (ScalarSubqueryExpression) SQLSelection ¶
func (ScalarSubqueryExpression) SQLSelection()
type SelectBuilder ¶
type SelectBuilder struct {
// contains filtered or unexported fields
}
SelectBuilder is the fluent constructor for a SelectStmt. It is a separate type from the AST because the exported field SelectStmt.Where and a same-named builder method cannot coexist in Go; construction lives here and the data on SelectStmt. Each method copies the in-progress statement and returns a new builder, so a builder value can be branched and reused. Build (or any terminal such as ToSQL) yields the finished SelectStmt.
func Select ¶
func Select(columns ...Selection) SelectBuilder
Select creates a SELECT query builder.
func (SelectBuilder) As ¶
func (b SelectBuilder) As(alias string) DerivedTable
As wraps this SELECT as an aliased subquery (derived table) named alias.
func (SelectBuilder) CTE ¶
func (b SelectBuilder) CTE(name string, opts ...CTEOption) CTE
CTE wraps this SELECT as a common table expression named name.
func (SelectBuilder) CrossJoin ¶
func (b SelectBuilder) CrossJoin(source Source) SelectBuilder
CrossJoin adds a CROSS JOIN clause. A cross join has no ON condition; it produces the Cartesian product of its inputs.
func (SelectBuilder) Distinct ¶
func (b SelectBuilder) Distinct() SelectBuilder
Distinct marks the query as SELECT DISTINCT.
func (SelectBuilder) DistinctOn ¶
func (b SelectBuilder) DistinctOn(exprs ...Expression) SelectBuilder
DistinctOn marks the query as SELECT DISTINCT ON (exprs...), keeping the first row of each group of rows equal on the given expressions (PostgreSQL). It is a PostgreSQL extension: dialects without it reject the query at compile time. Pair it with an ORDER BY that begins with the same expressions to make "first" deterministic.
func (SelectBuilder) Except ¶
func (b SelectBuilder) Except(other Query) CompoundBuilder
Except combines this query with another using EXCEPT.
func (SelectBuilder) ExceptAll ¶
func (b SelectBuilder) ExceptAll(other Query) CompoundBuilder
ExceptAll combines this query with another using EXCEPT ALL, the multiset difference: a row in the left result is dropped once per matching right row rather than entirely.
func (SelectBuilder) ForKeyShare ¶
func (b SelectBuilder) ForKeyShare(opts ...LockOption) SelectBuilder
ForKeyShare adds a FOR KEY SHARE clause, the weakest lock, blocking only changes to the key columns (PostgreSQL only).
func (SelectBuilder) ForNoKeyUpdate ¶
func (b SelectBuilder) ForNoKeyUpdate(opts ...LockOption) SelectBuilder
ForNoKeyUpdate adds a FOR NO KEY UPDATE clause, a weaker FOR UPDATE that does not block concurrent inserts of referencing rows (PostgreSQL only).
func (SelectBuilder) ForShare ¶
func (b SelectBuilder) ForShare(opts ...LockOption) SelectBuilder
ForShare adds a FOR SHARE row-locking clause, a shared lock that blocks concurrent writes but not other shared locks.
func (SelectBuilder) ForUpdate ¶
func (b SelectBuilder) ForUpdate(opts ...LockOption) SelectBuilder
ForUpdate adds a FOR UPDATE row-locking clause, locking the selected rows against concurrent updates and deletes until the transaction ends. Refine it with the SkipLocked / NoWait / LockOf options. Row locking is PostgreSQL/MySQL (8.0+) only; other dialects reject it at compile time.
func (SelectBuilder) From ¶
func (b SelectBuilder) From(source Source) SelectBuilder
From sets the table or subquery for the SELECT query.
func (SelectBuilder) FullJoin ¶
func (b SelectBuilder) FullJoin(source Source, on Expression) SelectBuilder
FullJoin adds a FULL OUTER JOIN clause.
func (SelectBuilder) GroupBy ¶
func (b SelectBuilder) GroupBy(exprs ...Expression) SelectBuilder
GroupBy adds GROUP BY expressions.
func (SelectBuilder) Having ¶
func (b SelectBuilder) Having(expr Expression) SelectBuilder
Having sets the HAVING predicate.
func (SelectBuilder) Intersect ¶
func (b SelectBuilder) Intersect(other Query) CompoundBuilder
Intersect combines this query with another using INTERSECT.
func (SelectBuilder) IntersectAll ¶
func (b SelectBuilder) IntersectAll(other Query) CompoundBuilder
IntersectAll combines this query with another using INTERSECT ALL, which keeps duplicate rows (the multiset intersection) rather than collapsing them.
func (SelectBuilder) Join ¶
func (b SelectBuilder) Join(source Source, on Expression) SelectBuilder
Join adds an INNER JOIN clause.
func (SelectBuilder) JoinUsing ¶
func (b SelectBuilder) JoinUsing(source Source, columns ...string) SelectBuilder
JoinUsing adds an INNER JOIN ... USING (columns) clause, matching rows on the equally named columns (which collapse to a single output column each).
func (SelectBuilder) LeftJoin ¶
func (b SelectBuilder) LeftJoin(source Source, on Expression) SelectBuilder
LeftJoin adds a LEFT JOIN clause.
func (SelectBuilder) LeftJoinUsing ¶
func (b SelectBuilder) LeftJoinUsing(source Source, columns ...string) SelectBuilder
LeftJoinUsing adds a LEFT JOIN ... USING (columns) clause.
func (SelectBuilder) Limit ¶
func (b SelectBuilder) Limit(n int) SelectBuilder
Limit sets the LIMIT clause.
func (SelectBuilder) NaturalJoin ¶
func (b SelectBuilder) NaturalJoin(source Source) SelectBuilder
NaturalJoin adds a NATURAL JOIN clause, an inner join on every column the two sources share by name. It takes no condition.
func (SelectBuilder) NaturalLeftJoin ¶
func (b SelectBuilder) NaturalLeftJoin(source Source) SelectBuilder
NaturalLeftJoin adds a NATURAL LEFT JOIN clause.
func (SelectBuilder) Offset ¶
func (b SelectBuilder) Offset(n int) SelectBuilder
Offset sets the OFFSET clause.
func (SelectBuilder) OrderBy ¶
func (b SelectBuilder) OrderBy(terms ...OrderTerm) SelectBuilder
OrderBy adds ORDER BY terms.
func (SelectBuilder) RightJoin ¶
func (b SelectBuilder) RightJoin(source Source, on Expression) SelectBuilder
RightJoin adds a RIGHT JOIN clause.
func (SelectBuilder) SQLSource ¶
func (b SelectBuilder) SQLSource() SourceExpression
SQLSource marks the building SELECT as a subquery source, so a builder can be dropped straight into a FROM/JOIN position.
func (SelectBuilder) Stmt ¶
func (b SelectBuilder) Stmt() SelectStmt
Stmt returns the built SELECT statement — the pure AST value.
func (SelectBuilder) ToSQL ¶
func (b SelectBuilder) ToSQL(dialect Dialect) (string, []any, error)
ToSQL compiles the building SELECT statement.
func (SelectBuilder) Union ¶
func (b SelectBuilder) Union(other Query) CompoundBuilder
Union combines this query with another using UNION.
func (SelectBuilder) UnionAll ¶
func (b SelectBuilder) UnionAll(other Query) CompoundBuilder
UnionAll combines this query with another using UNION ALL.
func (SelectBuilder) Where ¶
func (b SelectBuilder) Where(expr Expression) SelectBuilder
Where adds a WHERE predicate, combined with AND when called repeatedly.
func (SelectBuilder) Window ¶
func (b SelectBuilder) Window(defs ...NamedWindow) SelectBuilder
Window adds named window definitions to the SELECT's WINDOW clause, referenced from an OVER clause with WindowExpression.Named, e.g. Window(WindowDef("w").PartitionBy(Col("team")).OrderBy(Desc(Col("score")))).
func (SelectBuilder) WithCTE ¶
func (b SelectBuilder) WithCTE(ctes ...CTE) SelectBuilder
WithCTE prepends common table expressions to the SELECT, in the given order. Repeated calls append. List a CTE before any CTE whose body references it.
type SelectStmt ¶
type SelectStmt struct {
With []CTE
From Source
Columns []Selection
Joins []JoinClause
Where Expression
GroupBy []Expression
Having Expression
OrderBy []OrderTerm
Limit int
HasLimit bool
Offset int
HasOffset bool
Distinct bool
DistinctOn []Expression
Windows []NamedWindow
Lock *lockClause
// contains filtered or unexported fields
}
SelectStmt is the immutable AST for a SELECT statement. Every field is exported: this struct is the package's read-only public contract, traversed and compiled directly with no Parts() snapshot. Build one with the fluent SelectBuilder (sql.Select) or, from a parser, as a struct literal. A nil Where/Having/From or an empty slice means the clause is absent; HasLimit / HasOffset distinguish a zero LIMIT/OFFSET from none.
func (SelectStmt) Pos ¶
func (p SelectStmt) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (SelectStmt) SQLSource ¶
func (q SelectStmt) SQLSource() SourceExpression
SQLSource marks SelectStmt as a subquery source.
type Selection ¶
type Selection interface {
SQLSelection()
}
Selection is a SELECT-list item such as a column or aggregate expression.
type SetStmt ¶
type SetStmt struct {
Vars []SetVar
// contains filtered or unexported fields
}
SetStmt assigns one or more variables (SET ...). It is produced by the MySQL frontend for the system/user-variable forms; SET NAMES and other special forms are not modeled here.
func SetVariables ¶
SetVariables builds a SET statement over the given variable assignments.
type SetVar ¶
type SetVar struct {
Name string
Value Expression
Scope string
User bool
// contains filtered or unexported fields
}
SetVar is one assignment in a SET statement. Value must bind no values (it is rendered inline). Scope is "", "GLOBAL", or "SESSION" for a system variable; User marks a user variable (@name).
type SimilarToExpression ¶
type SimilarToExpression struct {
Left Expression
Pattern Expression
Negate bool
// contains filtered or unexported fields
}
SimilarToExpression matches a string against a SQL regular expression with the SQL-standard SIMILAR TO operator, whose pattern language is LIKE's (% and _) extended with the regex metacharacters | * + ? () [] {}. It is genuinely non-portable — PostgreSQL and the SQL standard have it, MySQL does not — so it renders through a SimilarToMatcher and a dialect without that capability rejects it at compile time.
func NotSimilarTo ¶
func NotSimilarTo(left, pattern any) SimilarToExpression
NotSimilarTo creates a negated "left NOT SIMILAR TO pattern" match.
func SimilarTo ¶
func SimilarTo(left, pattern any) SimilarToExpression
SimilarTo creates a "left SIMILAR TO pattern" match. Non-expression operands become bind values.
func (SimilarToExpression) Pos ¶
func (p SimilarToExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (SimilarToExpression) SQLExpression ¶
func (SimilarToExpression) SQLExpression()
type SimilarToMatcher ¶
SimilarToMatcher is an optional capability a Dialect implements to render a SQL-standard SIMILAR TO match (SimilarToExpression). PostgreSQL and the SQL standard support it; MySQL does not, and rejects it at compile time (the compiler detects the capability with a type assertion, so adding it is not a breaking change to Dialect). left and pattern are already-compiled SQL fragments; negate selects NOT SIMILAR TO.
type Source ¶
type Source interface {
SQLSource() SourceExpression
}
Source is a table, subquery, or other FROM/JOIN source.
type SourceExpression ¶
type SourceExpression struct {
Name Ident
Query Query
Values *ValuesClause
Alias Ident
Lateral bool
// contains filtered or unexported fields
}
SourceExpression is the compiled representation of a FROM/JOIN source.
func Alias ¶
func Alias(query Query, alias string) SourceExpression
Alias creates a subquery source from a query and alias.
func Lateral ¶
func Lateral(source Source) SourceExpression
Lateral marks a source as LATERAL, so a joined subquery may reference columns of the sources to its left (PostgreSQL LATERAL). Combine with Alias to name the derived table, e.g. Lateral(Alias(subquery, "recent")).
func SourceAlias ¶
func SourceAlias(source Source, alias string) SourceExpression
SourceAlias applies an alias to a table or other source.
func Subquery ¶
func Subquery(query Query, alias string) SourceExpression
Subquery creates a FROM/JOIN source from a query and alias. Deprecated: use Query.As(alias) for a reusable handle with a Col accessor, Alias(query, alias) for an ad-hoc aliased source, or pass query directly when no alias is needed.
func ValuesSource ¶
func ValuesSource(rows [][]Expression, alias string, columns ...string) SourceExpression
ValuesSource builds a derived-table FROM/JOIN source from inline VALUES rows, rendered as (VALUES (...),(...)) AS alias(columns) — or, on dialects that cannot alias VALUES columns (MySQL, via DerivedValuesUnionDialect), an equivalent UNION ALL of SELECTs whose first arm names the columns. Each row must hold one value per column. It backs bulk UPDATE ... FROM (VALUES ...).
func (SourceExpression) Pos ¶
func (p SourceExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (SourceExpression) SQLSource ¶
func (s SourceExpression) SQLSource() SourceExpression
SQLSource marks SourceExpression as a Source.
type StandardSQLDialect ¶
type StandardSQLDialect struct{}
StandardSQLDialect renders portable ANSI/SQL-standard text. It is a text target with no bundled driver: identifiers are double-quoted, placeholders are positional "?", and features the standard lacks (RETURNING, upsert) are rejected at compile time. JSON access uses the SQL/JSON standard JSON_VALUE / JSON_QUERY functions, JSON objects use the standard "key VALUE value" form, and regex uses the standard LIKE_REGEX predicate (an optional feature, F841, not implemented by every engine).
func (StandardSQLDialect) AutoIncrementColumn ¶
func (d StandardSQLDialect) AutoIncrementColumn(name string, length, precision, scale int) (string, bool)
AutoIncrementColumn renders the SQL-standard identity column clause.
func (StandardSQLDialect) ColumnCommentStatement ¶
func (StandardSQLDialect) ColumnCommentStatement(string, string, string) string
func (StandardSQLDialect) ColumnType ¶
func (StandardSQLDialect) ColumnType(name string, length, precision, scale int) string
func (StandardSQLDialect) DropForeignKey ¶
func (StandardSQLDialect) DropForeignKey(qualifiedTable, quotedConstraint string) string
func (StandardSQLDialect) DropIndex ¶
func (StandardSQLDialect) DropIndex(qualifiedIndex, _, _ string) string
func (StandardSQLDialect) InlineColumnComment ¶
func (StandardSQLDialect) InlineColumnComment(string) string
InlineColumnComment and the sibling comment methods return empty: the SQL standard has no COMMENT syntax.
func (StandardSQLDialect) InlineTableComment ¶
func (StandardSQLDialect) InlineTableComment(string) string
func (StandardSQLDialect) JSONAccess ¶
JSONAccess renders SQL/JSON standard JSON_VALUE (text) / JSON_QUERY (JSON).
func (StandardSQLDialect) Name ¶
func (StandardSQLDialect) Name() string
Name identifies the dialect.
func (StandardSQLDialect) Placeholder ¶
func (StandardSQLDialect) Placeholder(int) string
func (StandardSQLDialect) QuoteIdent ¶
func (d StandardSQLDialect) QuoteIdent(identifier string) string
func (StandardSQLDialect) QuoteName ¶
func (StandardSQLDialect) QuoteName(name string) string
func (StandardSQLDialect) Regexp ¶
func (StandardSQLDialect) Regexp(left, pattern string, negate, caseInsensitive bool) (string, error)
Regexp renders the SQL-standard LIKE_REGEX predicate (F841), with FLAG 'i' for a case-insensitive match.
func (StandardSQLDialect) RenderFunc ¶
func (StandardSQLDialect) RenderFunc(name string, args []string) (string, bool)
RenderFunc remaps canonical function names to their SQL-standard spelling.
func (StandardSQLDialect) SimilarTo ¶
func (StandardSQLDialect) SimilarTo(left, pattern string, negate bool) string
SimilarTo renders the SQL-standard SIMILAR TO / NOT SIMILAR TO predicate.
func (StandardSQLDialect) SupportsMerge ¶
func (StandardSQLDialect) SupportsMerge() bool
SupportsMerge reports MERGE support (the SQL standard defines MERGE).
func (StandardSQLDialect) SupportsNullsOrdering ¶
func (StandardSQLDialect) SupportsNullsOrdering() bool
SupportsNullsOrdering reports support for NULLS FIRST/LAST (standard SQL).
func (StandardSQLDialect) SupportsReturning ¶
func (StandardSQLDialect) SupportsReturning() bool
SupportsReturning reports RETURNING support (the SQL standard has none).
func (StandardSQLDialect) TableCommentStatement ¶
func (StandardSQLDialect) TableCommentStatement(string, string) string
type StarSelection ¶
type StarSelection struct {
Qualifier Ident
// contains filtered or unexported fields
}
StarSelection is a "*" select-list item, optionally qualified by a table name or alias to project every column of one source ("users.*"). Unlike a column reference the qualifier is quoted but the "*" is emitted raw, so it never becomes "users"."*". It is only a Selection, not an Expression: a "*" stands alone in the select list and is not a value operand.
func Star ¶
func Star() StarSelection
Star creates an unqualified "*" select-list item, projecting every column of the query's sources.
func StarOf ¶
func StarOf(qualifier string) StarSelection
StarOf creates a qualified "qualifier.*" select-list item, projecting every column of the table or alias named by qualifier — for selecting one source whole alongside individual columns of others (SELECT users.*, profiles.bio).
func (StarSelection) Pos ¶
func (p StarSelection) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (StarSelection) SQLSelection ¶
func (StarSelection) SQLSelection()
type Statement ¶
type Statement interface {
Query
// contains filtered or unexported methods
}
Statement is a DDL statement that compiles to a single SQL statement. It is a Query (it compiles with ToSQL, with no bind arguments) so it runs through the same execution path as the query builders — sqlkit's Database.Exec / Session.Exec — rather than a bespoke one. The ddlStatement marker keeps DDL and DML separable at the type level (a migration is a list of Statement).
type Statements ¶
type Statements []Statement
Statements is an ordered list of DDL statements.
func (Statements) Render ¶
func (ss Statements) Render(dialect Dialect) (string, error)
Render compiles each statement and joins them with blank lines, the form a migration or schema script is written out in. Each statement already ends with ";"; statements that render empty (e.g. an inline-comment dialect's CommentOnTable) are skipped.
type StringAggExpression ¶
type StringAggExpression struct {
Arg Expression
Delimiter string
// contains filtered or unexported fields
}
StringAggExpression concatenates the grouped string values of an aggregate into one delimited string. Its spelling diverges by engine — PostgreSQL uses the SQL standard STRING_AGG(expr, 'delim') while MySQL uses GROUP_CONCAT(expr SEPARATOR 'delim') — so it renders per dialect rather than through Func. The delimiter is emitted as a static SQL string literal (MySQL's SEPARATOR does not accept a bind placeholder), so it must be a constant.
func StringAgg ¶
func StringAgg(arg any, delimiter string) StringAggExpression
StringAgg creates a STRING_AGG(arg, delimiter) aggregate (GROUP_CONCAT on MySQL). A non-expression arg becomes a bind value; delimiter is a constant string literal.
func (StringAggExpression) Pos ¶
func (p StringAggExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (StringAggExpression) SQLExpression ¶
func (StringAggExpression) SQLExpression()
func (StringAggExpression) SQLSelection ¶
func (StringAggExpression) SQLSelection()
type StringAggregator ¶
StringAggregator is an optional capability for dialects whose ordered string aggregation is not the SQL standard STRING_AGG(expr, 'delim') (MySQL spells it GROUP_CONCAT(expr SEPARATOR 'delim')). The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it uses the standard STRING_AGG form. arg is the already-compiled expression and delimiter is an already-quoted SQL string literal.
type SubscriptExpression ¶
type SubscriptExpression struct {
Operand Expression
Indices []SubscriptIndex
// contains filtered or unexported fields
}
SubscriptExpression is an array subscript or slice applied to an operand, e.g. a[1], a[1:3], or a chain a[1][2]. Each SubscriptIndex is one [...] step.
func Slice ¶
func Slice(operand Expression, lower, upper Expression) SubscriptExpression
Slice builds an array-slice expression operand[lower:upper]; pass nil for an open bound.
func Subscript ¶
func Subscript(operand Expression, index any) SubscriptExpression
Subscript builds a single array-index expression operand[index].
func (SubscriptExpression) Pos ¶
func (p SubscriptExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (SubscriptExpression) SQLExpression ¶
func (SubscriptExpression) SQLExpression()
func (SubscriptExpression) SQLSelection ¶
func (SubscriptExpression) SQLSelection()
type SubscriptIndex ¶
type SubscriptIndex struct {
Slice bool
Lower Expression
Upper Expression
}
SubscriptIndex is one subscript step. A non-slice index uses Upper as the single index (a[Upper]); a slice uses Lower:Upper (a[Lower:Upper]), either of which may be nil for an open bound.
type Table ¶
Table is a table reference usable in FROM/JOIN clauses.
func Tbl ¶
Tbl creates a FROM/JOIN source that refers to a table or CTE by name, the source-side counterpart to Col. It is shorthand for Table{Name: NewIdent(name)} — handy for referencing a recursive CTE by name from its own body, e.g. Join(Tbl("tree"), Eq(Col("nodes.parent_id"), Col("tree.id"))).
func (Table) Pos ¶
func (p Table) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (Table) QualifiedName ¶
QualifiedName returns the table name with an optional schema prefix.
func (Table) SQLSource ¶
func (t Table) SQLSource() SourceExpression
SQLSource marks Table as a Source.
type TableCheck ¶
type TableCheck struct {
Name Ident
Expression Expression
// contains filtered or unexported fields
}
TableCheck is a named CHECK constraint within a CREATE TABLE statement.
type TableDef ¶
TableDef describes a table's shape for row-oriented statement generation: the columns in scan order, the primary key, and the columns with database-side defaults. It is the single place that turns row values into statements; the typed builders only supply values.
func (TableDef) ColumnRef ¶
func (d TableDef) ColumnRef(name string) ColumnExpression
ColumnRef returns the qualified reference for one of the table's columns.
func (TableDef) InsertRows ¶
func (d TableDef) InsertRows(rows [][]any) (InsertBuilder, error)
InsertRows creates an INSERT for rows of values given in Columns order. Columns with a database-side default are omitted when their value is the zero value in every row, letting the database fill them in.
func (TableDef) SelectRows ¶
func (d TableDef) SelectRows() SelectBuilder
SelectRows creates a SELECT of all columns from the table.
func (TableDef) Selections ¶
Selections returns all columns as qualified SELECT-list items in Columns order.
type TableIndex ¶
TableIndex is a non-unique secondary index declared inline in a CREATE TABLE statement (MySQL's KEY/INDEX). Name is optional. Inline indexes are a MySQL feature; other dialects declare indexes with a separate CREATE INDEX.
type TableLock ¶
type TableLock struct {
Table Table
Mode TableLockMode
// contains filtered or unexported fields
}
TableLock pairs a table with the mode to lock it in within a LockTablesStmt.
type TableLockMode ¶
type TableLockMode string
TableLockMode is the lock a LOCK TABLES entry requests.
const ( // LockRead requests a READ lock (shared). LockRead TableLockMode = "READ" // LockWrite requests a WRITE lock (exclusive). LockWrite TableLockMode = "WRITE" )
type TableUnique ¶
TableUnique is a table-level UNIQUE constraint within a CREATE TABLE statement. Name is optional (an unnamed UNIQUE (cols) constraint when empty).
type TransactionStmt ¶
type TransactionStmt struct {
Kind string
Savepoint Ident
// contains filtered or unexported fields
}
TransactionStmt is a transaction-control statement: BEGIN, COMMIT, ROLLBACK, or the savepoint forms (SAVEPOINT, RELEASE SAVEPOINT, ROLLBACK TO SAVEPOINT). It binds no values and compiles the same on every dialect. Build one with Begin, Commit, Rollback, Savepoint, ReleaseSavepoint, or RollbackTo.
func ReleaseSavepoint ¶
func ReleaseSavepoint(name string) TransactionStmt
ReleaseSavepoint destroys a named savepoint (RELEASE SAVEPOINT name).
func RollbackTo ¶
func RollbackTo(name string) TransactionStmt
RollbackTo rolls back to a named savepoint (ROLLBACK TO SAVEPOINT name).
func Savepoint ¶
func Savepoint(name string) TransactionStmt
Savepoint establishes a named savepoint (SAVEPOINT name).
type TruncateBuilder ¶
type TruncateBuilder struct {
// contains filtered or unexported fields
}
TruncateBuilder is the fluent constructor for a TruncateStmt.
func Truncate ¶
func Truncate(tables ...Table) TruncateBuilder
Truncate starts a TRUNCATE TABLE builder for one or more tables (multiple tables are PostgreSQL-only).
func (TruncateBuilder) Cascade ¶
func (b TruncateBuilder) Cascade() TruncateBuilder
Cascade adds CASCADE, also truncating tables with foreign keys referencing the truncated ones (PostgreSQL only).
func (TruncateBuilder) RestartIdentity ¶
func (b TruncateBuilder) RestartIdentity() TruncateBuilder
RestartIdentity adds RESTART IDENTITY, resetting owned identity/serial sequences (PostgreSQL and the standard target; implicit on MySQL).
func (TruncateBuilder) Stmt ¶
func (b TruncateBuilder) Stmt() TruncateStmt
Stmt returns the built TRUNCATE statement.
type TruncateStmt ¶
type TruncateStmt struct {
Tables []Table
RestartIdentity bool
Cascade bool
// contains filtered or unexported fields
}
TruncateStmt is the AST for a TRUNCATE TABLE statement, which empties one or more tables far faster than a DELETE. It binds no values and runs through Exec like the other statements. The options diverge by engine: RESTART IDENTITY and CASCADE are PostgreSQL features (MySQL always resets AUTO_INCREMENT and has no CASCADE), and truncating several tables at once is PostgreSQL-only — these are reported as errors at compile time.
type UnaryExpression ¶
type UnaryExpression struct {
Operator string
Operand Expression
// contains filtered or unexported fields
}
UnaryExpression applies a prefix unary operator to an operand, such as the arithmetic negation -x or unary plus +x. It renders as the operator immediately followed by the parenthesized operand, e.g. (-"x").
func Neg ¶
func Neg(operand any) UnaryExpression
Neg creates a "-operand" arithmetic negation. A non-expression operand becomes a bind value.
func Pos ¶
func Pos(operand any) UnaryExpression
Pos creates a "+operand" unary plus. A non-expression operand becomes a bind value.
func Unary ¶
func Unary(operator string, operand any) UnaryExpression
Unary creates a prefix unary operator expression. A non-expression operand becomes a bind value.
func (UnaryExpression) Pos ¶
func (p UnaryExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (UnaryExpression) SQLExpression ¶
func (UnaryExpression) SQLExpression()
func (UnaryExpression) SQLSelection ¶
func (UnaryExpression) SQLSelection()
type UnlockTablesStmt ¶
type UnlockTablesStmt struct {
// contains filtered or unexported fields
}
UnlockTablesStmt releases all of the session's table locks (UNLOCK TABLES).
func UnlockTables ¶
func UnlockTables() UnlockTablesStmt
UnlockTables builds an UNLOCK TABLES statement.
type UpdateBuilder ¶
type UpdateBuilder struct {
// contains filtered or unexported fields
}
UpdateBuilder is the fluent constructor for an UpdateStmt.
func Update ¶
func Update(table Table) UpdateBuilder
Update creates an UPDATE query builder for a table.
func (UpdateBuilder) From ¶
func (b UpdateBuilder) From(sources ...Source) UpdateBuilder
From adds correlated sources to the UPDATE (PostgreSQL UPDATE ... FROM / MySQL multi-table UPDATE). Combine with Where to correlate rows.
func (UpdateBuilder) Join ¶
func (b UpdateBuilder) Join(source Source, on Expression) UpdateBuilder
Join adds an inner join to the UPDATE's source list.
func (UpdateBuilder) LeftJoin ¶
func (b UpdateBuilder) LeftJoin(source Source, on Expression) UpdateBuilder
LeftJoin adds a left join to the UPDATE's source list.
func (UpdateBuilder) Limit ¶
func (b UpdateBuilder) Limit(n int) UpdateBuilder
Limit caps the number of rows an UPDATE touches (UPDATE ... LIMIT n). MySQL only; other dialects reject it.
func (UpdateBuilder) OrderBy ¶
func (b UpdateBuilder) OrderBy(terms ...OrderTerm) UpdateBuilder
OrderBy adds ORDER BY terms that bound which rows an UPDATE touches (UPDATE ... ORDER BY ... LIMIT). MySQL only; other dialects reject it.
func (UpdateBuilder) Returning ¶
func (b UpdateBuilder) Returning(selections ...Selection) UpdateBuilder
Returning adds a RETURNING clause.
func (UpdateBuilder) Set ¶
func (b UpdateBuilder) Set(assignments ...Assignment) UpdateBuilder
Set appends SET assignments.
func (UpdateBuilder) Stmt ¶
func (b UpdateBuilder) Stmt() UpdateStmt
Stmt returns the built UPDATE statement — the pure AST value.
func (UpdateBuilder) ToSQL ¶
func (b UpdateBuilder) ToSQL(dialect Dialect) (string, []any, error)
ToSQL compiles the building UPDATE statement.
func (UpdateBuilder) Where ¶
func (b UpdateBuilder) Where(expr Expression) UpdateBuilder
Where adds a WHERE predicate, combined with AND when called repeatedly.
func (UpdateBuilder) WithCTE ¶
func (b UpdateBuilder) WithCTE(ctes ...CTE) UpdateBuilder
WithCTE prepends common table expressions to the UPDATE.
type UpdateStmt ¶
type UpdateStmt struct {
With []CTE
Table Table
Sets []Assignment
From []Source
Joins []JoinClause
Where Expression
OrderBy []OrderTerm
Limit int
HasLimit bool
Returning []Selection
// contains filtered or unexported fields
}
UpdateStmt is the immutable AST for an UPDATE statement.
type UpsertClause ¶
type UpsertClause struct {
Target []string
TargetConstraint string
DoUpdate bool
Assignments []string
WhereSQL string
}
UpsertClause carries the already-compiled pieces of an upsert for a dialect to assemble into its native syntax. Target holds the already-quoted conflict columns, or TargetConstraint the already-quoted name of a conflict constraint (PostgreSQL ON CONSTRAINT) — at most one is set; DoUpdate distinguishes DO UPDATE from DO NOTHING; Assignments are the already-compiled "col = expr" fragments; WhereSQL is an optional already-compiled predicate ("" when none).
type UpsertRenderer ¶
type UpsertRenderer interface {
Upsert(clause UpsertClause) (string, error)
}
UpsertRenderer is an optional capability a Dialect implements to render an INSERT conflict clause (PostgreSQL ON CONFLICT, MySQL ON DUPLICATE KEY UPDATE). The compiler detects it with a type assertion, so it is not a breaking change to Dialect; a dialect without it rejects upserts at compile time. The returned fragment is appended to the INSERT, leading space included.
type UseStmt ¶
type UseStmt struct {
DB Ident
// contains filtered or unexported fields
}
UseStmt selects the session's default database (USE db). It is produced by the MySQL frontend; the same text is valid on MariaDB.
type ValueExpression ¶
ValueExpression binds a value as a SQL argument. Quoted records whether the value should render as a single-quoted string literal in the inline compile mode (see CompileInline); it does not affect the normal placeholder-binding compile. Val sets it for a plain string or a Quoter; for any other string-wrapping type, mark it with Quote.
func Val ¶
func Val(value any) ValueExpression
Val creates a bind parameter expression, marking it Quoted when value is a plain string or a Quoter that reports true. A non-string type that does not implement Quoter can still be marked with Quote.
func (ValueExpression) Pos ¶
func (p ValueExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ValueExpression) Quote ¶
func (e ValueExpression) Quote() ValueExpression
Quote marks the value to render as a single-quoted string literal in the inline compile mode, for a value whose Go type is not a plain string and does not implement Quoter — a string-wrapping type from another package, say. It does not affect the placeholder-binding compile.
func (ValueExpression) SQLExpression ¶
func (ValueExpression) SQLExpression()
type ValuesCaster ¶
ValuesCaster is an optional capability for dialects that need the columns of a VALUES derived table (ValuesSource) typed explicitly. PostgreSQL infers a bare VALUES parameter as text, so a join or assignment against a non-text column (e.g. a bigint primary key in a bulk UPDATE ... FROM (VALUES ...)) fails with "operator does not exist: bigint = text". The compiler casts the first row's values to the type this returns so the server infers each column's type; ok = false leaves a value uncast. A dialect that does not implement it (MySQL, which types VALUES columns from the bound parameters) gets no casts.
type ValuesClause ¶
type ValuesClause struct {
Rows [][]Expression
Columns []Ident
// contains filtered or unexported fields
}
ValuesClause is an inline VALUES row constructor — a list of value rows with an optional column-name list — used as a derived-table source via ValuesSource.
type ValuesQuery ¶
type ValuesQuery struct {
// contains filtered or unexported fields
}
ValuesQuery is a standalone VALUES row constructor used as a query: VALUES (1, 'a'), (2, 'b'). Being a Query it can stand on its own, serve as a derived-table source (wrap it with Alias to name it and its columns), feed INSERT ... SELECT (InsertQuery.FromSelect), or back a CTE. Every row must hold the same number of values.
It differs from ValuesSource, which is the (VALUES ...) AS alias(cols) form built specifically as a FROM/JOIN source, and from InsertQuery.Values, which is the VALUES list of an INSERT.
func Values ¶
func Values(rows ...[]Expression) ValuesQuery
Values creates a VALUES query from rows of expressions. Append further rows ergonomically with Row.
func (ValuesQuery) Pos ¶
func (p ValuesQuery) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (ValuesQuery) Row ¶
func (q ValuesQuery) Row(values ...any) ValuesQuery
Row appends one row of values. Non-expression values become bind values.
func (ValuesQuery) SQLSource ¶
func (q ValuesQuery) SQLSource() SourceExpression
SQLSource marks ValuesQuery as a subquery source, so it renders as (VALUES ...) and can be aliased into a FROM/JOIN clause.
type Visitor ¶
Visitor is invoked by Walk for each node it encounters. Visit returns the visitor w used to walk node's children: a non-nil w descends into the children and, once they are exhausted, Walk calls w.Visit(nil); a nil w prunes the subtree rooted at node. It mirrors the contract of go/ast.Visitor.
type WhenClause ¶
type WhenClause struct {
Condition Expression
Result Expression
// contains filtered or unexported fields
}
WhenClause is one WHEN ... THEN ... arm of a CASE expression.
type WindowExpression ¶
type WindowExpression struct {
Fn Expression
Name Ident
Partitions []Expression
OrderByTerms []OrderTerm
FrameClause string
// contains filtered or unexported fields
}
WindowExpression applies a window (OVER clause) to a function or aggregate. With Name set it references a window defined in the SELECT's WINDOW clause: "fn OVER name" when it adds no clauses of its own, or "fn OVER (name ...)" when it extends that base window with further ORDER BY / frame clauses.
func Over ¶
func Over(fn Expression) WindowExpression
Over creates a window expression over a function or aggregate.
func (WindowExpression) Frame ¶
func (e WindowExpression) Frame(frame string) WindowExpression
Frame sets a raw frame clause such as "ROWS BETWEEN 1 PRECEDING AND CURRENT ROW".
func (WindowExpression) Named ¶
func (e WindowExpression) Named(name string) WindowExpression
Named references a window defined in the SELECT's WINDOW clause by name, as in Sum(Col("x")).Over().Named("w") for "SUM(x) OVER w". Adding PartitionBy / OrderBy / Frame on top extends that base window (PostgreSQL "OVER (w ...)").
func (WindowExpression) OrderBy ¶
func (e WindowExpression) OrderBy(terms ...OrderTerm) WindowExpression
OrderBy adds ORDER BY terms to the window.
func (WindowExpression) PartitionBy ¶
func (e WindowExpression) PartitionBy(exprs ...Expression) WindowExpression
PartitionBy adds PARTITION BY expressions to the window.
func (WindowExpression) Pos ¶
func (p WindowExpression) Pos() int
Pos returns the node's 0-based byte offset in the source SQL, or NoPos when it was built rather than parsed.
func (WindowExpression) SQLExpression ¶
func (WindowExpression) SQLExpression()
func (WindowExpression) SQLSelection ¶
func (WindowExpression) SQLSelection()
Source Files
¶
- admin.go
- compiler.go
- cte.go
- ddl.go
- ddl_compile.go
- dialect.go
- enum.go
- expression.go
- extension.go
- fulltext.go
- func.go
- function.go
- grant.go
- grouping.go
- ident.go
- indirection.go
- inline.go
- insert.go
- inspect.go
- matview.go
- merge.go
- pos.go
- raw.go
- rename.go
- select.go
- sequence.go
- source.go
- subquery.go
- tabledef.go
- transaction.go
- union.go
- values.go
- walk.go