ss

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// FlavorMySQL maps to sqlbuilder.MySQL.
	FlavorMySQL = sqlbuilder.MySQL
	// FlavorPostgreSQL maps to sqlbuilder.PostgreSQL.
	FlavorPostgreSQL = sqlbuilder.PostgreSQL
	// FlavorSQLite maps to sqlbuilder.SQLite.
	FlavorSQLite = sqlbuilder.SQLite
	// FlavorSQLServer maps to sqlbuilder.SQLServer.
	FlavorSQLServer = sqlbuilder.SQLServer
	// FlavorCQL maps to sqlbuilder.CQL.
	FlavorCQL = sqlbuilder.CQL
	// FlavorClickHouse maps to sqlbuilder.ClickHouse.
	FlavorClickHouse = sqlbuilder.ClickHouse
	// FlavorPresto maps to sqlbuilder.Presto.
	FlavorPresto = sqlbuilder.Presto
	// FlavorOracle maps to sqlbuilder.Oracle.
	FlavorOracle = sqlbuilder.Oracle
	// FlavorInformix maps to sqlbuilder.Informix.
	FlavorInformix = sqlbuilder.Informix
	// FlavorDoris maps to sqlbuilder.Doris.
	FlavorDoris = sqlbuilder.Doris
)
View Source
const (
	QueryTypeUnknown = def.QueryTypeUnknown
	QueryTypeSelect  = def.QueryTypeSelect
	QueryTypeInsert  = def.QueryTypeInsert
	QueryTypeUpdate  = def.QueryTypeUpdate
	QueryTypeDelete  = def.QueryTypeDelete
)

Variables

View Source
var WhereAnd = Where

WhereAnd is an alias for Where.

View Source
var X = C

X is an alias for C, for even shorter code. @Deprecated: Use Col, Lit, or Param instead. Will be removed in v2.0

Functions

func AddJoin

func AddJoin(joins ...JoinClause) def.QueryOption

AddJoin adds one or more JOIN clauses to the current query.

Params:

  • joins: pre-built JoinClause values (e.g. NewInnerJoin(...), NewJoinUsing(...))

Example:

// SELECT * FROM users u INNER JOIN orders o ON u.id = o.user_id
q := Q(
  FromTable("users", "u"),
  AddJoin(NewInnerJoin(TableAs("orders", "o"), EQ("u.id", Col("o.user_id")))),
)

func AddUnion

func AddUnion(query *SQLStmt) def.QueryOption

AddUnion adds UNION.

func AddUnionAll

func AddUnionAll(query *SQLStmt) def.QueryOption

AddUnionAll adds UNION ALL.

func Alias

func Alias(name, alias string) def.FromClause

Alias creates a base table reference with alias.

Example:

Alias("users", "u")

func AliasExpression

func AliasExpression(flavor Flavor, expr, alias string) string

AliasExpression appends an AS alias to the given expression when alias is non-empty.

func AsDelete

func AsDelete() def.QueryOption

AsDelete sets query type to DELETE.

func AsInsert

func AsInsert() def.QueryOption

AsInsert sets query type to INSERT.

func AsReplace

func AsReplace() def.QueryOption

AsReplace uses REPLACE semantics (MySQL/SQLite native; others emulate).

func AsSelect

func AsSelect() def.QueryOption

AsSelect sets query type to SELECT.

func AsUpdate

func AsUpdate() def.QueryOption

AsUpdate sets query type to UPDATE.

func BETWEEN

func BETWEEN(column string, values ...any) *def.BetweenCondition

BETWEEN creates column BETWEEN start AND end.

Example:

BETWEEN("age", 18, 30)

func BeforeBuild

func BeforeBuild(callback func(*SQLStmt) error) def.QueryOption

BeforeBuild registers a callback function that will be invoked before building SQL. This allows you to validate or modify the SQLStmt dynamically, such as: - Checking if required fields are present - Verifying that conditions exist - Adding additional conditions based on runtime logic - Validating the query structure

The callback receives a pointer to the SQLStmt and can modify it in place. If the callback returns an error, the Build operation will fail with that error.

Example:

query := NewQuery(
    Select("id", "name"),
    FromTable("users"),
    BeforeBuild(func(stmt *SQLStmt) error {
        // Ensure WHERE clause exists for safety
        if stmt.WhereCond == nil {
            return errors.New("WHERE clause is required")
        }
        // Or add a default condition
        if stmt.WhereCond == nil {
            stmt.WhereCond = &ComparisonCondition{
                Left: parseColumnExpr("deleted_at"),
                Right: &LiteralExpr{Value: nil},
                Operator: "IS",
            }
        }
        return nil
    }),
)

func BuildNamed

func BuildNamed(sql string, args []interface{}) (string, map[string]any)

BuildNamed converts a SQL with positional placeholders to named placeholders. It takes the SQL and args from a builder's Build() method and returns SQL with :p1, :p2 style placeholders and a map of parameter values.

Example:

sb := cybuilder.Select()
sb.Select("id", "name").From("users").Where(sb.Equal("status", "active"))
sql, args := sb.Build()
namedSQL, params := cybuilder.BuildNamed(sql, args)
// namedSQL: SELECT id, name FROM users WHERE status = :p1
// params: map[p1:active]

func BuildNamedWithFlavor

func BuildNamedWithFlavor(sql string, args []interface{}, flavor Flavor) (string, map[string]any)

BuildNamedWithFlavor converts SQL with positional placeholders to named placeholders using the specified database flavor.

func C

func C(v any, isColumn ...bool) def.Expression

C is a universal expression builder with auto-detection. @Deprecated: Use Col for columns, Lit for literals, or Param for parameters instead. Will be removed in v2.0

Params:

  • v: string/int/float/bool/Expression; string with ":" -> Param, with "." -> ColT
  • isColumn (optional): force treating plain string as column

Examples:

C("u.name")          // → ColT("u","name")
C(":id")             // → Param("id")
C(100)               // → Lit(100)
C("status", true)    // → Col("status")

func Col

func Col(name string) *def.ColumnExpr

Col creates a column expression.

Supports:

  • "col" -> ColumnExpr{Name:"col"}
  • "t.col" -> ColumnExpr{Table:"t", Name:"col"}
  • "s.t.col" -> ColumnExpr{Schema:"s", Table:"t", Name:"col"}

Examples:

Col("id")
Col("u.name").As("user_name")

func ColS

func ColS(schema, table, column string) *def.ColumnExpr

ColS creates a column expression with schema and table qualifiers.

Example:

ColS("public", "users", "id")

func ColT

func ColT(table, column string) *def.ColumnExpr

ColT creates a column expression with explicit table qualifier.

Example:

ColT("u", "id")

func Columns

func Columns(cols ...any) def.QueryOption

func CrossJoin

func CrossJoin(target any, alias ...string) def.QueryOption

CrossJoin is a convenience function for adding a CROSS JOIN.

Params:

  • target: table name, TableRef, or *SQLStmt
  • alias: optional alias if target is string

Example:

CrossJoin("countries c")

func Delete

func Delete(table any) def.QueryOption

Delete sets DELETE target; supports string or TableRef. @Deprecated: Use DeleteFrom instead. Will be removed in v2.0

func DeleteFrom

func DeleteFrom(tables ...TableRef) def.QueryOption

DeleteFrom sets DELETE target tables.

func DeleteFromTable

func DeleteFromTable(name string) def.QueryOption

DeleteFromTable convenience for simple table name. @Deprecated: Use DeleteFrom(Table(name)) instead. Will be removed in v2.0

func Distinct

func Distinct() def.QueryOption

Distinct is shorthand for DISTINCT.

func Expr

func Expr(sql string) *def.RawExpr

Expr creates a raw SQL expression without parsing or quoting. This is useful for complex expressions like CASE WHEN, subqueries, or aggregate functions with DISTINCT that would otherwise be incorrectly parsed.

Example:

Expr("COUNT(DISTINCT CASE WHEN status = 'active' THEN id END)")
Expr("SUM(CASE WHEN type = 'A' THEN amount ELSE 0 END)")

Note: This is an alias for Raw() with clearer intent for SELECT expressions.

func ForShare

func ForShare() def.QueryOption

ForShare sets FOR SHARE locking.

func ForUpdate

func ForUpdate() def.QueryOption

ForUpdate sets FOR UPDATE locking.

func From

func From(table any, alias ...string) def.QueryOption

From sets FROM clause.

Params:

  • table: string/TableRef/*SQLStmt
  • alias: optional alias

Example:

From("users u")
From("users AS u")
From("users as u")
From(SubqueryTable(Q(Select("1")), "t"))

func FromTable

func FromTable(name string, alias ...string) def.QueryOption

FromTable is convenience for base table (optional alias).

func FullJoin

func FullJoin(target any, args ...any) def.QueryOption

FullJoin is a convenience function for adding a FULL OUTER JOIN.

Params mirror InnerJoin.

Example:

FullJoin("audit a", EQ("a.user_id", Col("u.id")))

func GroupBy

func GroupBy(args ...any) def.QueryOption

GroupBy sets GROUP BY columns/expressions.

Example:

GroupBy("dept_id", "role")

func Having

func Having(cond any) def.QueryOption

Having sets HAVING condition (Condition or string).

Example:

Having(GT(CountAll(), Lit(10)))

func IN

func IN(column string, values ...any) *def.InCondition

IN creates column IN (values...).

Params:

  • column: column name
  • values: literals/Expressions; empty -> named param :column

Example:

IN("status", "A", "B")

func ISNOTNULL

func ISNOTNULL(column string) *def.NullCondition

ISNOTNULL creates column IS NOT NULL.

func ISNULL

func ISNULL(column string) *def.NullCondition

ISNULL creates column IS NULL.

func InnerJoin

func InnerJoin(target any, args ...any) def.QueryOption

InnerJoin is a convenience function for adding an INNER JOIN.

Params:

  • target: table name (string), TableRef, or *SQLStmt for subquery
  • args: optional alias string and/or ON condition (Condition or string)

Example:

Q(
  FromTable("users", "u"),
  InnerJoin("orders o", EQ("u.id", Col("o.user_id"))),
)

func Insert

func Insert(table any) def.QueryOption

Insert sets INSERT target table; supports string or TableRef. @Deprecated: Use InsertInto instead. Will be removed in v2.0

Example:

Insert("users")

func InsertCols

func InsertCols(names ...any) def.QueryOption

InsertCols sets INSERT columns by name. @Deprecated: Use InsertInto with column parameters instead. Will be removed in v2.0

func InsertColumns

func InsertColumns(columns ...Expression) def.QueryOption

InsertColumns sets INSERT columns. @Deprecated: Use InsertInto with column parameters instead. Will be removed in v2.0

func InsertConflictColumns

func InsertConflictColumns(cols ...Expression) def.QueryOption

InsertConflictColumns sets conflict target columns for upsert/replace.

func InsertInto

func InsertInto(table any, cols ...any) def.QueryOption

InsertInto sets INSERT target table.

func InsertIntoTable

func InsertIntoTable(name string) def.QueryOption

InsertIntoTable is a convenience for simple table names.

func InsertRows

func InsertRows(rows ...[]Expression) def.QueryOption

InsertRows adds multiple rows for bulk INSERT. @Deprecated: Use multiple InsertValues calls instead. Will be removed in v2.0

func InsertSubQuery

func InsertSubQuery(subquery def.SQLStmt) def.QueryOption

InsertSubQuery sets subquery as source (INSERT ... SELECT ...). @Deprecated: Use InsertSubquery instead. Will be removed in v2.0

func InsertSubquery

func InsertSubquery(subquery def.SQLStmt) def.QueryOption

InsertSubquery sets subquery as source (INSERT ... SELECT ...).

func InsertVals

func InsertVals(vals ...any) def.QueryOption

InsertValuesAny adds one row, auto-converting any -> Expression. @Deprecated: Use InsertValues instead. Will be removed in v2.0

func InsertValues

func InsertValues(values ...Expression) def.QueryOption

InsertValues adds one row of values (expressions) for INSERT.

Example:

InsertValues(Param("name"), Param("age"))

func Join

func Join(target any, args ...any) def.QueryOption

Join is an alias for InnerJoin.

Example:

Join("profiles p", EQ("p.user_id", Col("u.id")))

func JoinOn

func JoinOn(tableWithAlias string, on string) def.QueryOption

JoinOn adds an INNER JOIN with string table+alias and on condition. @Deprecated: Use InnerJoin instead. Will be removed in v2.0

Params:

  • tableWithAlias: "table alias" or "schema.table alias"
  • on: ON condition as raw SQL string

Example:

JoinOn("orders o", "u.id = o.user_id")

func JoinUsing

func JoinUsing(table TableRef, columns ...string) def.QueryOption

JoinUsing is a convenience function for adding a JOIN with USING clause.

Params:

  • table: target TableRef
  • columns: column names used in USING(...)

Example:

JoinUsing(TableAs("orders", "o"), "id")

func LIKE

func LIKE(column string, pattern ...string) *def.ComparisonCondition

LIKE creates column LIKE pattern.

Example:

LIKE("name", "%bob%")

func LeftJoin

func LeftJoin(target any, args ...any) def.QueryOption

LeftJoin is a convenience function for adding a LEFT JOIN.

Params mirror InnerJoin.

Example:

LeftJoin("orders o", EQ("u.id", Col("o.user_id")))

func LeftJoinOn

func LeftJoinOn(tableWithAlias string, on string) def.QueryOption

LeftJoinOn adds a LEFT JOIN with string table+alias and on condition. @Deprecated: Use LeftJoin instead. Will be removed in v2.0

Params mirror JoinOn.

Example:

LeftJoinOn("orders o", "u.id = o.user_id")

func LeftJoinUsing

func LeftJoinUsing(table TableRef, columns ...string) def.QueryOption

LeftJoinUsing is a convenience function for adding a LEFT JOIN with USING clause.

Params mirror JoinUsing.

Example:

LeftJoinUsing(TableAs("orders", "o"), "user_id")

func Limit

func Limit(limit int) def.QueryOption

Limit sets LIMIT with int.

Example: Limit(10)

func LimitExpr

func LimitExpr(limit Expression) def.QueryOption

LimitExpr sets LIMIT with Expression (e.g., Param/Raw).

func LimitOffset

func LimitOffset(limit, offset int) def.QueryOption

LimitOffset sets LIMIT and OFFSET.

func Lit

func Lit(value any) *def.LiteralExpr

Lit creates a literal value expression.

Example:

Lit(123)

func NOTBETWEEN

func NOTBETWEEN(column string, values ...any) *def.BetweenCondition

NOTBETWEEN creates column NOT BETWEEN start AND end.

Example:

NOTBETWEEN("age", 18, 30)

func NOTIN

func NOTIN(column string, values ...any) *def.InCondition

NOTIN creates column NOT IN (values...).

func NOTLIKE

func NOTLIKE(column string, pattern ...string) *def.ComparisonCondition

NOTLIKE creates column NOT LIKE pattern.

func NamedArg

func NamedArg(name string) interface{}

NamedArg is a helper to create a raw named argument string for use with sqlbuilder. It returns a sqlbuilder.Raw value that won't be converted to a placeholder. Usage:

sb.Where(sb.Equal("status", cybuilder.NamedArg("status")))
sql, _ := sb.Build()
// sql: SELECT ... WHERE status = :status

func NaturalJoin

func NaturalJoin(table TableRef) def.QueryOption

NaturalJoin is a convenience function for adding a NATURAL JOIN.

Params:

  • table: target TableRef

Example:

NaturalJoin(Table("departments"))

func NaturalLeftJoin

func NaturalLeftJoin(table TableRef) def.QueryOption

NaturalLeftJoin is a convenience function for adding a NATURAL LEFT JOIN.

Params:

  • table: target TableRef

Example:

NaturalLeftJoin(Table("departments"))

func Offset

func Offset(offset int) def.QueryOption

Offset sets OFFSET with int.

func OffsetExpr

func OffsetExpr(offset Expression) def.QueryOption

OffsetExpr sets OFFSET with Expression.

func OnConflict

func OnConflict(assignments ...Assignment) def.QueryOption

OnConflict sets ON CONFLICT / ON DUPLICATE KEY assignments.

Example:

OnConflict(AssignCol("name", Param("name")))

func OnConflictExpr

func OnConflictExpr(exprs map[string]string) def.QueryOption

OnConflictExpr sets assignments using raw expression strings (not quoted).

Example:

OnConflictExpr(map[string]string{"name": "VALUES(name)"})

func OrderBy

func OrderBy(args ...any) def.QueryOption

OrderBy sets ORDER BY items (string -> Asc(col) by default).

Supported argument types:

  • string: column name, defaults to ASC (or use next arg SortDesc for DESC)
  • []string: multiple column names, defaults to ASC (or use next arg SortDesc for DESC)
  • SortDirection: applies to the preceding string or []string
  • Expression: defaults to ASC
  • OrderClause: used as-is

Example:

OrderBy("created_at", Desc(Col("id")))
OrderBy("created_at", SortDesc)
OrderBy([]string{"created_at", "updated_at"})
OrderBy([]string{"created_at", "updated_at"}, SortDesc)

func OrderByAsc

func OrderByAsc(args ...any) def.QueryOption

OrderByAsc is an alias for OrderBy (defaults to ASC).

func Page

func Page(page, pageSize int) def.QueryOption

Page sets LIMIT/OFFSET for pagination (1-based page).

Example: Page(2, 20) => LIMIT 20 OFFSET 20

func Param

func Param(name string) *def.ParameterExpr

Param creates a named parameter expression.

Example:

Param("user_id")  // :user_id

func Parameter

func Parameter(name string, position int) def.QueryOption

Parameter binds named parameter position.

Example:

Parameter("id", 1)

func Parameters

func Parameters(bindings ...ParameterBinding) def.QueryOption

Parameters adds multiple parameter bindings.

func QualifyIdentifier

func QualifyIdentifier(flavor Flavor, parts ...string) string

QualifyIdentifier joins identifier segments (schema/table/column) with dot separators.

func QuoteIdentifier

func QuoteIdentifier(flavor Flavor, ident string) string

QuoteIdentifier applies flavor-specific quoting to a single identifier segment.

func Raw

func Raw(sql string) *def.RawExpr

Raw creates a raw SQL expression (use with caution).

Example:

Raw("COUNT(*) FILTER (WHERE status='A')")

func RawCond

func RawCond(sql string) *def.RawCondition

RawCond creates a raw SQL condition (use with caution).

Example:

RawCond("deleted_at IS NULL")

func RawSQL

func RawSQL(sql string) def.QueryOption

RawSQL sets the raw SQL fallback.

func Returning

func Returning(columns ...any) def.QueryOption

Returning adds RETURNING clause to INSERT statement.

Example:

Returning("id", "created_at")

func RightJoin

func RightJoin(target any, args ...any) def.QueryOption

RightJoin is a convenience function for adding a RIGHT JOIN.

Params mirror InnerJoin.

Example:

RightJoin("logs l", EQ("l.user_id", Col("u.id")))

func RightJoinOn

func RightJoinOn(tableWithAlias string, on string) def.QueryOption

RightJoinOn adds a RIGHT JOIN with string table+alias and on condition. @Deprecated: Use RightJoin instead. Will be removed in v2.0

Params mirror JoinOn.

Example:

RightJoinOn("logs l", "u.id = l.user_id")

func Select

func Select(args ...any) def.QueryOption

Select sets SELECT items.

Supports string / Expression / *SelectItem. String rules: auto parse "col", "t.col", "col as alias", "FUNC(col) as alias".

Example:

Select("id", "name as n", CountAll().As("c"))

func SelectColumns

func SelectColumns(items ...Expression) def.QueryOption

SelectColumns sets the SELECT clause with the given expressions. Kept for backward compatibility or strict typing.

func SelectIfEmpty

func SelectIfEmpty(args ...any) def.QueryOption

SelectIfEmpty sets SELECT items only when the current SELECT clause is empty. If the statement already has SELECT items, it keeps them unchanged.

func SelectItems

func SelectItems(items ...*SelectItem) def.QueryOption

SelectItems sets SELECT with SelectItem structs.

Example:

SelectItems(SelectAs(Col("id"), "uid"))

func Set

func Set(assignments ...Assignment) def.QueryOption

Set adds assignments to UPDATE clause.

func SetCol

func SetCol(columnName string, value Expression) def.QueryOption

SetCol convenience to set column to value Expression.

func SetDefaultFlavor

func SetDefaultFlavor(flavor Flavor)

SetDefaultFlavor overrides the package level default flavor.

func SetDistinct

func SetDistinct(distinct bool) def.QueryOption

SetDistinct sets DISTINCT on SELECT.

func SetParam

func SetParam(columnName, paramName string) def.QueryOption

SetParam convenience to set column = :param. @Deprecated: Use Set(AssignParam(columnName, paramName)) instead. Will be removed in v2.0

func Star

func Star() *def.WildcardExpr

Star creates wildcard expression (*).

func StarS

func StarS(schema, table string) *def.WildcardExpr

StarS creates schema.table.* wildcard.

func StarT

func StarT(table string) *def.WildcardExpr

StarT creates table.* wildcard.

func Union

func Union(query *SQLStmt) def.QueryOption

Union alias for AddUnion.

func UnionAll

func UnionAll(query *SQLStmt) def.QueryOption

UnionAll alias for AddUnionAll.

func Update

func Update(table any) def.QueryOption

Update sets UPDATE target; supports string or TableRef.

func UpdateTableName

func UpdateTableName(name string) def.QueryOption

UpdateTableName convenience for simple table. @Deprecated: Use Update instead. Will be removed in v2.0

func UpdateTarget

func UpdateTarget(table TableRef) def.QueryOption

UpdateTarget sets UPDATE target table. @Deprecated: Use Update instead. Will be removed in v2.0

func Where

func Where(conds ...any) def.QueryOption

Where sets WHERE condition; accepts Condition or string (auto-parsed).

Params:

  • conds: Condition or SQL-like string (e.g., "age >= 18", "name LIKE '%a%'")

Example:

Where(EQ("status", "A"), GT("age", 18))

func WhereAll

func WhereAll(conds ...any) def.QueryOption

WhereAll combines conditions with AND (overwrites previous).

func WhereAny

func WhereAny(conds ...any) def.QueryOption

WhereAny combines conditions with OR (overwrites previous).

func WhereBetween

func WhereBetween(column string, start, end any) def.QueryOption

WhereBetween sugar for column BETWEEN start AND end.

Example:

WhereBetween("created_at", "2024-01-01", "2024-01-31")

func WhereOr

func WhereOr(conds ...any) def.QueryOption

WhereOr adds OR conditions; if existing WHERE present, wraps with OR.

Example:

WhereOr(EQ("status","A"), EQ("status","B"))

func With

func With(ctes ...*CommonTableExpr) def.QueryOption

With adds CTE definitions.

Example:

With(CTEDef("t", Q(Select("1"))))

Types

type Args

type Args = sqlbuilder.Args

Re-export key builder types and helpers for convenience.

func ArgsHelper

func ArgsHelper() *Args

Args creates a flavor-aware args helper using default builder.

type Assignment

type Assignment struct {
	Column def.Expression
	Value  def.Expression
}

Assignment describes column = expression pairs.

func Assign

func Assign(column Expression, value Expression) Assignment

Assign creates Assignment for UPDATE / ON CONFLICT.

func AssignCol

func AssignCol(columnName string, value Expression) Assignment

AssignCol creates assignment by column name.

func AssignParam

func AssignParam(columnName, paramName string) Assignment

AssignParam creates assignment using named parameter.

type BetweenCondition

type BetweenCondition = def.BetweenCondition

Type Aliases for convenience and backward compatibility

func Between

func Between(expr, start, end Expression) *BetweenCondition

Between creates a BETWEEN condition.

func NotBetween

func NotBetween(expr, start, end Expression) *BetweenCondition

NotBetween creates a NOT BETWEEN condition.

type BinaryExpr

type BinaryExpr = def.BinaryExpr

Type Aliases for convenience and backward compatibility

func Add

func Add(left, right Expression) *BinaryExpr

Add creates left + right.

Example: Add(Col("a"), Col("b"))

func Div

func Div(left, right Expression) *BinaryExpr

Div creates left / right.

func Mod

func Mod(left, right Expression) *BinaryExpr

Mod creates left % right.

func Mul

func Mul(left, right Expression) *BinaryExpr

Mul creates left * right.

func Sub

func Sub(left, right Expression) *BinaryExpr

Sub creates left - right.

type BooleanCondition

type BooleanCondition = def.BooleanCondition

Conditions

func And

func And(conditions ...Condition) *BooleanCondition

And creates an AND condition combining multiple conditions.

func Or

func Or(conditions ...Condition) *BooleanCondition

Or creates an OR condition combining multiple conditions.

type BuildOptions

type BuildOptions = def.BuildOptions

BuildOptions controls how SQLStmt is rendered.

type Builder

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

Builder wraps go-sqlbuilder flavor factories and provides a single entry to create any builder.

func Default

func Default() *Builder

Default returns a cloned copy of the current global builder.

func New

func New(opts ...BuilderOption) *Builder

New creates a Builder with optional configuration.

func (*Builder) Args

func (b *Builder) Args() *Args

Args creates a new Args helper that shares builder flavor.

func (*Builder) CTE

func (b *Builder) CTE() *CTEBuilder

CTE creates a CTEBuilder bound to Builder flavor.

func (*Builder) CTEQuery

func (b *Builder) CTEQuery() *CTEQueryBuilder

CTEQuery creates a CTEQueryBuilder bound to Builder flavor.

func (*Builder) Clone

func (b *Builder) Clone() *Builder

Clone returns a shallow copy of Builder.

func (*Builder) CreateTable

func (b *Builder) CreateTable() *CreateTableBuilder

CreateTable creates a CreateTableBuilder bound to Builder flavor.

func (*Builder) Delete

func (b *Builder) Delete() *DeleteBuilder

Delete creates a DeleteBuilder bound to Builder flavor.

func (*Builder) Flavor

func (b *Builder) Flavor() Flavor

Flavor reports builder flavor.

func (*Builder) Insert

func (b *Builder) Insert() *InsertBuilder

Insert creates an InsertBuilder bound to Builder flavor.

func (*Builder) Select

func (b *Builder) Select() *SelectBuilder

Select creates a SelectBuilder bound to Builder flavor.

func (*Builder) Struct

func (b *Builder) Struct(model any) *StructModel

Struct returns a struct helper configured with builder flavor.

func (*Builder) Union

func (b *Builder) Union() *UnionBuilder

Union creates a UnionBuilder bound to Builder flavor.

func (*Builder) Update

func (b *Builder) Update() *UpdateBuilder

Update creates an UpdateBuilder bound to Builder flavor.

func (*Builder) WithDatabase

func (b *Builder) WithDatabase(dbType string, fallback ...Flavor) *Builder

WithDatabase maps a database type string (e.g. mysql/postgres) to flavor.

func (*Builder) WithFlavor

func (b *Builder) WithFlavor(flavor Flavor) *Builder

WithFlavor returns a cloned builder using provided flavor.

type BuilderOption

type BuilderOption func(*Builder)

BuilderOption configures Builder creation.

func WithBuilderFlavor

func WithBuilderFlavor(flavor Flavor) BuilderOption

WithBuilderFlavor configures Builder flavor.

type CTEBuilder

type CTEBuilder = sqlbuilder.CTEBuilder

Re-export key builder types and helpers for convenience.

func CTEWithFlavor

func CTEWithFlavor(flavor Flavor) *CTEBuilder

CTEWithFlavor creates a CTEBuilder for the given flavor.

func NewCTEBuilder

func NewCTEBuilder() *CTEBuilder

NewCTEBuilder creates a CTEBuilder using the default builder.

type CTEQueryBuilder

type CTEQueryBuilder = sqlbuilder.CTEQueryBuilder

Re-export key builder types and helpers for convenience.

func CTEQueryWithFlavor

func CTEQueryWithFlavor(flavor Flavor) *CTEQueryBuilder

CTEQueryWithFlavor creates a CTEQueryBuilder for the given flavor.

func NewCTEQueryBuilder

func NewCTEQueryBuilder() *CTEQueryBuilder

NewCTEQueryBuilder creates a CTEQueryBuilder using the default builder.

type CaseExpr

type CaseExpr = def.CaseExpr

Type Aliases for convenience and backward compatibility

func Case

func Case(value Expression) *CaseExpr

Case creates CASE value WHEN ... THEN ... END.

Example:

Case(Col("status")).
  When( Lit("A"), Lit("Active") ).
  Else(Lit("Unknown"))

func CaseWhenPairs

func CaseWhenPairs(value any, whens [][2]any, elseVal ...any) *CaseExpr

CaseWhenPairs builds CASE with when/then pairs.

Params:

  • value: base expression
  • whens: [][2]any, each {when, then}
  • elseVal: optional else expression

Example:

CaseWhenPairs("status", [][2]any{{"A","Active"}, {"I","Inactive"}}, "Unknown")

type CastExpr

type CastExpr = def.CastExpr

Type Aliases for convenience and backward compatibility

func Cast

func Cast(expr Expression, typeName string) *CastExpr

Cast creates a CAST(expr AS type) expression.

Example:

Cast(Col("price"), "INTEGER")           // → CAST(price AS INTEGER)
Cast(Col("amount"), "DECIMAL(10,2)")    // → CAST(amount AS DECIMAL(10,2))
Cast(Lit("2024-01-01"), "DATE")         // → CAST('2024-01-01' AS DATE)

type ColumnExpr

type ColumnExpr = def.ColumnExpr

Expressions

type CommonTableExpr

type CommonTableExpr = def.CommonTableExpr

Type Aliases for convenience and backward compatibility

func CTEDef

func CTEDef(name string, query def.SQLStmt, columns ...string) *CommonTableExpr

CTE creates a Common Table Expression.

Example:

CTEDef("t", Q(Select("1")))

func CTERecursive

func CTERecursive(name string, query def.SQLStmt, columns ...string) *CommonTableExpr

CTERecursive creates a recursive Common Table Expression.

type ComparisonCondition

type ComparisonCondition = def.ComparisonCondition

Type Aliases for convenience and backward compatibility

func CONTAINS

func CONTAINS(column, value string) *ComparisonCondition

CONTAINS creates a LIKE condition with %value% pattern. The value is automatically escaped to treat % and _ as literal characters.

Example:

CONTAINS("name", "test")   // → name LIKE '%test%' ESCAPE '\'
CONTAINS("rate", "50%")    // → name LIKE '%50\%%' ESCAPE '\' (50% is literal)

func ColEQ

func ColEQ(left, right string) *ComparisonCondition

ColEQ creates a column = column condition. @Deprecated: Use Eq(Col(left), Col(right)) instead. Will be removed in v2.0

Example:

ColEQ("o.user_id", "u.id")  // → o.user_id = u.id

func ColGT

func ColGT(left, right string) *ComparisonCondition

ColGT creates a column > column condition. @Deprecated: Use Gt(Col(left), Col(right)) instead. Will be removed in v2.0

func ColGTE

func ColGTE(left, right string) *ComparisonCondition

ColGTE creates a column >= column condition. @Deprecated: Use Gte(Col(left), Col(right)) instead. Will be removed in v2.0

func ColLT

func ColLT(left, right string) *ComparisonCondition

ColLT creates a column < column condition. @Deprecated: Use Lt(Col(left), Col(right)) instead. Will be removed in v2.0

func ColLTE

func ColLTE(left, right string) *ComparisonCondition

ColLTE creates a column <= column condition. @Deprecated: Use Lte(Col(left), Col(right)) instead. Will be removed in v2.0

func ColNE

func ColNE(left, right string) *ComparisonCondition

ColNE creates a column <> column condition. @Deprecated: Use Ne(Col(left), Col(right)) instead. Will be removed in v2.0

func ENDSWITH

func ENDSWITH(column, value string) *ComparisonCondition

ENDSWITH creates a LIKE condition with %value pattern. The value is automatically escaped to treat % and _ as literal characters.

Example:

ENDSWITH("name", "test")  // → name LIKE '%test' ESCAPE '\'

func Eq

func Eq(left, right Expression) *ComparisonCondition

Eq creates an equality condition (=).

func Gt

func Gt(left, right Expression) *ComparisonCondition

Gt creates a greater-than condition (>).

func Gte

func Gte(left, right Expression) *ComparisonCondition

Gte creates a greater-than-or-equal condition (>=).

func Like

func Like(left, right Expression) *ComparisonCondition

Like creates a LIKE condition.

func Lt

func Lt(left, right Expression) *ComparisonCondition

Lt creates a less-than condition (<).

func Lte

func Lte(left, right Expression) *ComparisonCondition

Lte creates a less-than-or-equal condition (<=).

func NOTCONTAINS

func NOTCONTAINS(column, value string) *ComparisonCondition

func Ne

func Ne(left, right Expression) *ComparisonCondition

Ne creates a not-equal condition (<>).

func NotLike

func NotLike(left, right Expression) *ComparisonCondition

NotLike creates a NOT LIKE condition.

func STARTSWITH

func STARTSWITH(column, value string) *ComparisonCondition

STARTSWITH creates a LIKE condition with value% pattern. The value is automatically escaped to treat % and _ as literal characters.

Example:

STARTSWITH("name", "test")  // → name LIKE 'test%' ESCAPE '\'

type Condition

type Condition = def.Condition

Type Aliases for convenience and backward compatibility

func EQ

func EQ(column any, value ...any) Condition

EQ creates column = value, with auto-tuple support.

Params:

  • column: column name (string) or columns ([]string) for tuple comparison
  • value (optional): if omitted, uses :col as param; if string with ":" treated as param

Example:

EQ("u.id", 1)                              // u.id = 1
EQ("status")                               // status = :status
EQ([]string{"a", "b"}, 1, 2)               // (a, b) = (1, 2)
EQ([]string{"id"}, 100)                    // id = 100 (auto-degrade)

func GT

func GT(column any, value ...any) Condition

GT creates column > value, with auto-tuple support.

func GTE

func GTE(column any, value ...any) Condition

GTE creates column >= value, with auto-tuple support.

func LT

func LT(column any, value ...any) Condition

LT creates column < value, with auto-tuple support.

func LTE

func LTE(column any, value ...any) Condition

LTE creates column <= value, with auto-tuple support.

func NE

func NE(column any, value ...any) Condition

NE creates column <> value, with auto-tuple support.

func TupleEQ

func TupleEQ(cols []string, vals ...any) Condition

TupleEQ creates (cols...) = (vals...), with auto-degrade for single column.

Example:

TupleEQ([]string{"order_id", "product_id"}, 1, 2)  // (order_id, product_id) = (1, 2)
TupleEQ([]string{"id"}, 100)                        // id = 100 (auto-degrade)
TupleEQ([]string{"a", "b"})                         // (a, b) = (:a, :b) (named params)

func TupleGT

func TupleGT(cols []string, vals ...any) Condition

TupleGT creates (cols...) > (vals...), useful for keyset pagination. Auto-degrades to simple comparison for single column.

func TupleGTE

func TupleGTE(cols []string, vals ...any) Condition

TupleGTE creates (cols...) >= (vals...), with auto-degrade for single column.

func TupleIN

func TupleIN(cols []string, valsList [][]any) Condition

TupleIN creates (cols...) IN ((v1...), (v2...), ...), for multiple composite keys.

Example:

TupleIN([]string{"order_id", "product_id"}, [][]any{{1, 2}, {3, 4}})

func TupleLT

func TupleLT(cols []string, vals ...any) Condition

TupleLT creates (cols...) < (vals...), with auto-degrade for single column.

func TupleLTE

func TupleLTE(cols []string, vals ...any) Condition

TupleLTE creates (cols...) <= (vals...), with auto-degrade for single column.

func TupleNE

func TupleNE(cols []string, vals ...any) Condition

TupleNE creates (cols...) <> (vals...), with auto-degrade for single column.

func TupleNOTIN

func TupleNOTIN(cols []string, valsList [][]any) Condition

TupleNOTIN creates (cols...) NOT IN ((...)).

type CreateTableBuilder

type CreateTableBuilder = sqlbuilder.CreateTableBuilder

Re-export key builder types and helpers for convenience.

func CreateTableWithFlavor

func CreateTableWithFlavor(flavor Flavor) *CreateTableBuilder

CreateTableWithFlavor creates CreateTableBuilder for the given flavor.

func NewCreateTableBuilder

func NewCreateTableBuilder() *CreateTableBuilder

NewCreateTableBuilder creates a CreateTableBuilder using the default builder.

type DBExecutor

type DBExecutor = def.DBExecutor

Re-export types from def to keep signatures aligned with interface.

type DeleteBuilder

type DeleteBuilder = sqlbuilder.DeleteBuilder

Re-export key builder types and helpers for convenience.

func DeleteWithFlavor

func DeleteWithFlavor(flavor Flavor) *DeleteBuilder

DeleteWithFlavor creates a DeleteBuilder for the given flavor.

func NewDeleteBuilder

func NewDeleteBuilder() *DeleteBuilder

NewDeleteBuilder creates a DeleteBuilder using the default builder.

type DeleteClause

type DeleteClause struct {
	Targets []TableRef // MySQL supports multi-table delete
}

DeleteClause captures DELETE statements.

func (*DeleteClause) TargetCount

func (dc *DeleteClause) TargetCount() int

type ExecOption

type ExecOption = def.ExecOption

func WithAutoIncPK

func WithAutoIncPK(pk string) ExecOption

WithAutoIncPK sets the auto-increment primary key for query execution. This is used in InsertAndGetID to specify the column to return.

Example:

query.InsertAndGetID(dbCli, WithAutoIncPK("id"))

func WithExecContext

func WithExecContext(ctx context.Context) ExecOption

WithExecContext sets the context for query execution.

Example:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
query.Exec(dbCli, WithExecContext(ctx))

func WithExecParams

func WithExecParams(params map[string]any) ExecOption

WithExecParams sets named parameters for query execution. These parameters will be merged with any parameters extracted from the query.

Example:

query.Exec(dbCli, WithExecParams(map[string]any{"user_id": 123}))

type ExistsCondition

type ExistsCondition = def.ExistsCondition

Type Aliases for convenience and backward compatibility

func Exists

func Exists(subquery def.SQLStmt) *ExistsCondition

Exists creates an EXISTS condition.

func NotExists

func NotExists(subquery def.SQLStmt) *ExistsCondition

NotExists creates a NOT EXISTS condition.

type Expression

type Expression = def.Expression

Type Aliases for convenience and backward compatibility

func Cols

func Cols(names ...string) []Expression

Cols creates multiple column expressions from names. Supports table-qualified names like "u.name".

Example:

SelectColumns(Cols("id", "name", "u.email")...)

type Flavor

type Flavor = sqlbuilder.Flavor

Flavor re-exports go-sqlbuilder Flavor so callers don't need to import both packages.

func FlavorForDatabase

func FlavorForDatabase(dbType string, fallback ...Flavor) Flavor

FlavorForDatabase converts textual database type to Flavor.

func FlavorFromExecutor

func FlavorFromExecutor(executor def.DBExecutor) Flavor

FlavorFromExecutor returns the Flavor for a DBExecutor based on its database type. This is a shortcut for FlavorForDatabase(executor.DBType()).

Example:

flavor := ss.FlavorFromExecutor(dbCli)
whereSQL, args, _ := query.BuildWhereSQL(ss.BuildOptions{Flavor: flavor})

type FromClause

type FromClause struct {
	Primary TableRef
	Joins   []JoinClause
}

FromClause represents FROM ... including primary table(s) and joins.

func (*FromClause) GetAlias

func (fc *FromClause) GetAlias() string

GetAlias returns the alias of the primary table.

func (*FromClause) GetTableName

func (fc *FromClause) GetTableName() string

GetTableName returns the name of the primary table.

func (*FromClause) JoinCount

func (fc *FromClause) JoinCount() int

type FunctionExpr

type FunctionExpr = def.FunctionExpr

Type Aliases for convenience and backward compatibility

func Avg

func Avg(expr Expression) *FunctionExpr

Avg creates AVG(expr).

func AvgCol

func AvgCol(name string) *FunctionExpr

func Coalesce

func Coalesce(args ...Expression) *FunctionExpr

Coalesce creates COALESCE(args...).

func Concat

func Concat(args ...Expression) *FunctionExpr

Concat creates CONCAT(args...).

func Count

func Count(expr Expression) *FunctionExpr

Count creates COUNT(expr).

Example:

Count(Col("id"))

func CountAll

func CountAll() *FunctionExpr

CountAll creates COUNT(*).

func CountCol

func CountCol(name string) *FunctionExpr

Common aggregate helpers with column name. @Deprecated: Use Count(Col(name)), Sum(Col(name)), Avg(Col(name)) instead. Will be removed in v2.0

func CountDistinct

func CountDistinct(expr Expression) *FunctionExpr

CountDistinct creates COUNT(DISTINCT expr).

func CurrentDate

func CurrentDate() *FunctionExpr

CurrentDate creates CURRENT_DATE.

func CurrentTimestamp

func CurrentTimestamp() *FunctionExpr

CurrentTimestamp creates CURRENT_TIMESTAMP.

func DenseRank

func DenseRank() *FunctionExpr

DenseRank creates DENSE_RANK().

func FirstValue

func FirstValue(expr Expression) *FunctionExpr

FirstValue creates FIRST_VALUE(expr).

func Func

func Func(name string, args ...Expression) *FunctionExpr

Func creates a function call expression.

Params:

  • name: function name
  • args: function arguments as Expression

Example:

Func("ABS", Col("delta"))

func FuncCols

func FuncCols(name string, args ...string) *FunctionExpr

FuncCols creates a function with string column arguments (auto Col).

Example:

FuncCols("COALESCE", "name", "'unknown'")

func FuncDistinct

func FuncDistinct(name string, args ...Expression) *FunctionExpr

FuncDistinct creates DISTINCT function call.

Example:

FuncDistinct("COUNT", Col("user_id"))

func IfNull

func IfNull(expr, defaultVal Expression) *FunctionExpr

IfNull creates IFNULL(expr, default) / NVL equivalent.

func Lag

func Lag(expr Expression, offset int, defaultVal ...Expression) *FunctionExpr

Lag creates LAG(expr, offset, default?).

Example:

Lag(Col("price"), 1, Lit(0))

func LastValue

func LastValue(expr Expression) *FunctionExpr

LastValue creates LAST_VALUE(expr).

func Lead

func Lead(expr Expression, offset int, defaultVal ...Expression) *FunctionExpr

Lead creates LEAD(expr, offset, default?).

func Length

func Length(expr Expression) *FunctionExpr

Length creates LENGTH(expr).

func Lower

func Lower(expr Expression) *FunctionExpr

Lower creates LOWER(expr).

func Max

func Max(expr Expression) *FunctionExpr

Max creates MAX(expr).

func Min

func Min(expr Expression) *FunctionExpr

Min creates MIN(expr).

func NTile

func NTile(n int) *FunctionExpr

NTile creates NTILE(n).

Example:

NTile(4)

func Now

func Now() *FunctionExpr

Now creates NOW().

func Rank

func Rank() *FunctionExpr

Rank creates RANK().

func RowNumber

func RowNumber() *FunctionExpr

RowNumber creates ROW_NUMBER().

func Substring

func Substring(expr Expression, start, length Expression) *FunctionExpr

Substring creates SUBSTRING(expr, start, length).

func Sum

func Sum(expr Expression) *FunctionExpr

Sum creates SUM(expr).

func SumCol

func SumCol(name string) *FunctionExpr

func Trim

func Trim(expr Expression) *FunctionExpr

Trim creates TRIM(expr).

func Upper

func Upper(expr Expression) *FunctionExpr

Upper creates UPPER(expr).

type InCondition

type InCondition = def.InCondition

Type Aliases for convenience and backward compatibility

func In

func In(target Expression, values ...Expression) *InCondition

In creates an IN condition with a list of values.

func InSub

func InSub(column string, subquery def.SQLStmt) *InCondition

INSub creates an IN subquery condition with column name.

func InSubquery

func InSubquery(target Expression, subquery def.SQLStmt) *InCondition

InSubquery creates an IN condition with a subquery.

func NotIn

func NotIn(target Expression, values ...Expression) *InCondition

NotIn creates a NOT IN condition with a list of values.

func NotInSub

func NotInSub(column string, subquery def.SQLStmt) *InCondition

func NotInSubquery

func NotInSubquery(target Expression, subquery def.SQLStmt) *InCondition

NotInSubquery creates a NOT IN condition with a subquery.

type InsertBuilder

type InsertBuilder = sqlbuilder.InsertBuilder

Re-export key builder types and helpers for convenience.

func InsertWithFlavor

func InsertWithFlavor(flavor Flavor) *InsertBuilder

InsertWithFlavor creates an InsertBuilder for the given flavor.

func NewInsertBuilder

func NewInsertBuilder() *InsertBuilder

NewInsertBuilder creates an InsertBuilder using the default builder.

type InsertClause

type InsertClause struct {
	Target     TableRef
	Columns    []def.Expression
	Values     [][]def.Expression // matrix of row values
	SubQuery   def.SQLStmt
	OnConflict []Assignment // upsert/replace semantics
	// ConflictColumns specifies conflict target columns for ON CONFLICT/MERGE.
	ConflictColumns []def.Expression
	// Returning specifies columns to return after insert (PostgreSQL/Oracle/SQLite).
	Returning []def.Expression
	// Mode controls INSERT vs REPLACE semantics.
	Mode InsertMode
}

InsertClause captures INSERT/REPLACE style statements.

func (*InsertClause) ColumnCount

func (ic *InsertClause) ColumnCount() int

func (*InsertClause) ColumnsList

func (ic *InsertClause) ColumnsList() []string

Columns implements InsertClause.

func (*InsertClause) GetConflictValue

func (ic *InsertClause) GetConflictValue(name string) (def.Expression, bool)

GetConflictValue returns the value expression for a field in the ON CONFLICT/DUPLICATE KEY clause.

func (*InsertClause) GetTargetName

func (ic *InsertClause) GetTargetName() string

func (*InsertClause) GetValue

func (ic *InsertClause) GetValue(name string) (def.Expression, bool)

GetValue returns the value expression for a specific column (from the first row).

func (*InsertClause) HasColumn

func (ic *InsertClause) HasColumn(name string) bool

HasColumn checks if the insert clause contains a specific column.

func (*InsertClause) HasConflictAssignment

func (ic *InsertClause) HasConflictAssignment(name string) bool

HasConflictAssignment checks if a field is updated in the ON CONFLICT/DUPLICATE KEY clause.

func (*InsertClause) RowCount

func (ic *InsertClause) RowCount() int

type InsertMode

type InsertMode int

InsertMode indicates insert semantics.

const (
	InsertModeInsert InsertMode = iota
	InsertModeReplace
)

type JoinClause

type JoinClause struct {
	Type    JoinType
	Table   TableRef
	On      def.Condition
	Using   []string
	Natural bool
}

JoinClause describes a JOIN ... ON/USING ...

func NewCrossJoin

func NewCrossJoin(table TableRef) JoinClause

NewCrossJoin creates a CROSS JOIN clause.

func NewFullJoin

func NewFullJoin(table TableRef, on Condition) JoinClause

NewFullJoin creates a FULL JOIN clause.

func NewInnerJoin

func NewInnerJoin(table TableRef, on Condition) JoinClause

NewInnerJoin creates an INNER JOIN clause.

func NewJoin

func NewJoin(joinType JoinType, table TableRef, on Condition) JoinClause

JoinClause creates a JOIN clause.

func NewJoinUsing

func NewJoinUsing(joinType JoinType, table TableRef, columns ...string) JoinClause

NewJoinUsing creates a JOIN clause with USING.

func NewLeftJoin

func NewLeftJoin(table TableRef, on Condition) JoinClause

NewLeftJoin creates a LEFT JOIN clause.

func NewNaturalJoin

func NewNaturalJoin(joinType JoinType, table TableRef) JoinClause

NewNaturalJoin creates a NATURAL JOIN clause.

func NewRightJoin

func NewRightJoin(table TableRef, on Condition) JoinClause

NewRightJoin creates a RIGHT JOIN clause.

type JoinType

type JoinType string

JoinType enumerates supported join flavors.

const (
	JoinInner JoinType = "INNER"
	JoinLeft  JoinType = "LEFT"
	JoinRight JoinType = "RIGHT"
	JoinFull  JoinType = "FULL"
	JoinCross JoinType = "CROSS"
)

type LikePatternExpr

type LikePatternExpr = def.LikePatternExpr

Type Aliases for convenience and backward compatibility

type LimitClause

type LimitClause = def.LimitClause

Type Aliases for convenience and backward compatibility

type LiteralExpr

type LiteralExpr = def.LiteralExpr

Type Aliases for convenience and backward compatibility

type LockClause

type LockClause struct {
	Mode   LockMode
	Tables []string // optional: specific tables to lock
	NoWait bool     // NOWAIT option
	Skip   bool     // SKIP LOCKED option
}

LockClause represents row-level locking (FOR UPDATE / FOR SHARE).

type LockMode

type LockMode string

LockMode represents the type of row locking.

const (
	LockNone      LockMode = ""
	LockForUpdate LockMode = "FOR UPDATE"
	LockForShare  LockMode = "FOR SHARE"
)

type NamedParam

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

NamedParam represents a named parameter placeholder like :name It wraps sqlbuilder.Raw to prevent the value from being converted to a positional placeholder.

func Named

func Named(name string) NamedParam

Named creates a named parameter placeholder that outputs :name directly in SQL. Usage:

sb.Where(sb.Equal("status", cybuilder.Named("status")))
sql, _ := sb.Build()
// sql: SELECT ... WHERE status = :status

The named parameter will NOT be converted to ? or $1, it will appear as :name in the SQL.

func (NamedParam) Name

func (p NamedParam) Name() string

Name returns the parameter name without the colon prefix

func (NamedParam) Raw

func (p NamedParam) Raw() string

Raw returns the raw SQL representation (:name) for use with sqlbuilder. This is used internally by go-sqlbuilder when building SQL.

func (NamedParam) String

func (p NamedParam) String() string

String returns the named parameter in :name format

type NullCondition

type NullCondition = def.NullCondition

Type Aliases for convenience and backward compatibility

func IsNotNull

func IsNotNull(expr Expression) *NullCondition

IsNotNull creates an IS NOT NULL condition.

func IsNull

func IsNull(expr Expression) *NullCondition

IsNull creates an IS NULL condition.

type OrderClause

type OrderClause = def.OrderClause

Clauses

func Asc

func Asc(expr Expression) OrderClause

Asc creates ORDER BY expr ASC.

func AscNullsFirst

func AscNullsFirst(expr Expression) OrderClause

AscNullsFirst creates ASC NULLS FIRST.

func AscNullsLast

func AscNullsLast(expr Expression) OrderClause

AscNullsLast creates ASC NULLS LAST.

func Desc

func Desc(expr Expression) OrderClause

Desc creates ORDER BY expr DESC.

func DescNullsFirst

func DescNullsFirst(expr Expression) OrderClause

DescNullsFirst creates DESC NULLS FIRST.

func DescNullsLast

func DescNullsLast(expr Expression) OrderClause

DescNullsLast creates DESC NULLS LAST.

type ParameterBinding

type ParameterBinding struct {
	Name     string // e.g. ":id" -> "id"
	Position int
}

ParameterBinding keeps parsed placeholder ordering information.

type ParameterExpr

type ParameterExpr = def.ParameterExpr

Type Aliases for convenience and backward compatibility

type QueryOption

type QueryOption = def.QueryOption

def.QueryOption is a function that configures and returns a SQLStmt. This follows the def.QueryOption pattern for flexible query building.

func OrderByDesc

func OrderByDesc(args ...any) QueryOption

OrderByDesc adds ORDER BY ... DESC for all items. Equivalent to OrderBy(args..., SortDesc) but ignores any SortDirection in args.

Example:

OrderByDesc("created_at")
OrderByDesc([]string{"created_at", "updated_at"})

func SetQueryType

func SetQueryType(t QueryType) QueryOption

SetQueryType sets the query type explicitly.

Params:

  • t: QueryTypeSelect/Insert/Update/Delete

Example:

SetQueryType(QueryTypeSelect)

type QueryType

type QueryType = def.QueryType

Type Aliases for convenience and backward compatibility

type RawCondition

type RawCondition = def.RawCondition

Type Aliases for convenience and backward compatibility

type RawExpr

type RawExpr = def.RawExpr

Type Aliases for convenience and backward compatibility

type SQLBuilder

type SQLBuilder = sqlbuilder.Builder

Re-export key builder types and helpers for convenience.

type SQLStmt

type SQLStmt struct {
	Type         def.QueryType
	CTEs         []*def.CommonTableExpr
	SelectClause *SelectClause
	InsertClause *InsertClause
	UpdateClause *UpdateClause
	DeleteClause *DeleteClause
	FromClause   *FromClause
	WhereCond    def.Condition
	GroupByItems []def.Expression
	HavingCond   def.Condition
	OrderByItems []def.OrderClause
	LimitClause  *def.LimitClause
	Unions       []def.UnionClause
	LockClause   *LockClause // FOR UPDATE / FOR SHARE
	Parameters   []ParameterBinding
	RawSQL       string // fallback when certain syntax cannot be structured
	// contains filtered or unexported fields
}

SQLStmt captures a normalized description of a SQL statement that can be rebuilt for arbitrary dialects.

func NewQuery

func NewQuery(opts ...QueryOption) *SQLStmt

NewQuery creates a new SQLStmt with the given options.

func ParseMySQLStructuredV1

func ParseMySQLStructuredV1(sql string) (*SQLStmt, error)

ParseMySQLStructuredV1 parses MySQL SQL using GoSQLX. This implementation currently focuses on validation and parameter extraction, returning RawSQL when a richer AST mapping is unavailable.

func Q

func Q(opts ...QueryOption) *SQLStmt

Q is alias for NewQuery. @Deprecated: Use NewQuery instead. Will be removed in v2.0

func (*SQLStmt) Apply

func (q *SQLStmt) Apply(opts ...QueryOption) def.SQLStmt

Apply applies additional options to an existing query.

func (*SQLStmt) Avg

func (q *SQLStmt) Avg(executor DBExecutor, target any, opts ...ExecOption) (float64, error)

Avg executes AVG(target) based on current query (ignores original SELECT/LIMIT/OFFSET/ORDER BY). target 支持 string(列名或函数字符串)或 Expression。

func (*SQLStmt) Build

func (q *SQLStmt) Build(flavor def.Flavor) (string, []interface{}, error)

Build is a convenience wrapper for BuildSQL using just a flavor. It satisfies the def.SQLStmt interface.

func (*SQLStmt) BuildMySQL

func (q *SQLStmt) BuildMySQL() (string, []interface{}, error)

BuildMySQL compiles the query for MySQL.

func (*SQLStmt) BuildNamedSQL

func (q *SQLStmt) BuildNamedSQL(opts BuildOptions) (string, map[string]any, error)

BuildNamedSQL converts the SQLStmt into SQL text with named parameters (:name style). Returns the SQL string and a map of parameter names to values. Original ParameterExpr (e.g., :user_id) are preserved in the SQL but NOT included in the params map, as their values should be provided by the caller. Literal values are converted to named parameters like :p1, :p2, etc.

Example:

Input query: SELECT * FROM users WHERE id = :user_id AND status = 1
Output SQL:  SELECT * FROM users WHERE id = :user_id AND status = :p1
Output params: map[string]any{"p1": 1}
// :user_id value should be provided by caller and merged with params

func (*SQLStmt) BuildPostgreSQL

func (q *SQLStmt) BuildPostgreSQL() (string, []interface{}, error)

BuildPostgreSQL compiles the query for PostgreSQL.

func (*SQLStmt) BuildSQL

func (q *SQLStmt) BuildSQL(opts BuildOptions) (string, []interface{}, error)

BuildSQL converts the SQLStmt into SQL text using go-sqlbuilder builders and flavor.

func (*SQLStmt) BuildSQLite

func (q *SQLStmt) BuildSQLite() (string, []interface{}, error)

BuildSQLite compiles the query for SQLite.

func (*SQLStmt) BuildWhereNamedSQL

func (q *SQLStmt) BuildWhereNamedSQL(opts BuildOptions) (string, map[string]any, error)

BuildWhereNamedSQL builds only the WHERE clause SQL with named parameters (:name style). Returns the WHERE clause SQL (without "WHERE" keyword) and a map of parameter names to values. If there is no WHERE condition, returns empty string and nil params.

Example:

query := NewQuery(
    Where(And(EQ("status", "active"), GT("age", 18))),
)
whereSQL, params, err := query.BuildWhereNamedSQL(BuildOptions{Flavor: FlavorMySQL})
// whereSQL: "(status = :__cydb_param_1 AND age > :__cydb_param_2)"
// params: map[string]any{"__cydb_param_1": "active", "__cydb_param_2": 18}

func (*SQLStmt) BuildWhereSQL

func (q *SQLStmt) BuildWhereSQL(opts BuildOptions) (string, []interface{}, error)

BuildWhereSQL builds only the WHERE clause SQL and arguments from the query. This is useful when you need just the condition part without table name, SELECT columns, etc. Returns the WHERE clause SQL (without "WHERE" keyword) and the arguments. If there is no WHERE condition, returns empty string and nil args.

Example:

query := NewQuery(
    Where(And(EQ("status", "active"), GT("age", 18))),
)
whereSQL, args, err := query.BuildWhereSQL(BuildOptions{Flavor: FlavorMySQL})
// whereSQL: "(status = ? AND age > ?)"
// args: ["active", 18]

func (*SQLStmt) Clone

func (q *SQLStmt) Clone() def.SQLStmt

Clone creates a shallow copy of the query.

func (*SQLStmt) Columns

func (q *SQLStmt) Columns(cols ...any) def.SQLStmt

Columns sets the columns for INSERT. @Deprecated: Use InsertInto with column parameters instead. Will be removed in v2.0

func (*SQLStmt) ColumnsIfNotSet

func (q *SQLStmt) ColumnsIfNotSet(cols ...any) def.SQLStmt

ColumnsIfNotSet sets the columns for INSERT only if they are not already set. This is useful for providing default columns that can be overridden by explicit calls.

func (*SQLStmt) Count

func (q *SQLStmt) Count(executor DBExecutor, target any, opts ...ExecOption) (int64, error)

Count executes COUNT(target) based on current query (ignores original SELECT/LIMIT/OFFSET/ORDER BY). target 可为:

  • nil 或 "*":COUNT(*)
  • string:自动解析列名(或函数调用字符串,如 "SUM(price)")
  • Expression:直接作为 COUNT 的参数(若已是 COUNT 则直接使用)

func (*SQLStmt) CrossJoin

func (q *SQLStmt) CrossJoin(target any, alias ...string) def.SQLStmt

CrossJoin adds a CROSS JOIN clause.

func (*SQLStmt) Delete

func (q *SQLStmt) Delete(table string) def.SQLStmt

Delete sets the DELETE FROM table.

func (*SQLStmt) Distinct

func (q *SQLStmt) Distinct() def.SQLStmt

Distinct sets DISTINCT on the SELECT clause.

func (*SQLStmt) Exec

func (q *SQLStmt) Exec(executor DBExecutor, opts ...ExecOption) (int64, error)

Exec executes a non-SELECT (INSERT/UPDATE/DELETE) and returns affected rows。 会自动根据 executor.DBType 选择方言,先 BuildNamedSQL 再执行,调用方自行提供 ExecOption(如参数、上下文)。

Example:

query := NewQuery(
	WithUpdateTableName("users"),
	WithSet(SetVal("status", "inactive")),
	WithWhere(EQ("id")), // uses :id parameter
)
affected, err := query.Exec(dbCli, WithExecParams(map[string]any{"id": 123}))

func (*SQLStmt) ForShare

func (q *SQLStmt) ForShare() def.SQLStmt

ForShare adds FOR SHARE locking clause.

func (*SQLStmt) ForUpdate

func (q *SQLStmt) ForUpdate() def.SQLStmt

ForUpdate adds FOR UPDATE locking clause.

func (*SQLStmt) From

func (q *SQLStmt) From(table any, alias ...string) def.SQLStmt

From sets the FROM clause. table can be: - string: table name - *SQLStmt: subquery - TableRef: explicit table reference alias is optional.

func (*SQLStmt) FullJoin

func (q *SQLStmt) FullJoin(target any, args ...any) def.SQLStmt

FullJoin adds a FULL OUTER JOIN clause.

func (*SQLStmt) GetCTEs

func (q *SQLStmt) GetCTEs() []*def.CommonTableExpr

func (*SQLStmt) GetFromClause

func (q *SQLStmt) GetFromClause() def.FromClause

func (*SQLStmt) GetGroupByItems

func (q *SQLStmt) GetGroupByItems() []def.Expression

func (*SQLStmt) GetHavingCond

func (q *SQLStmt) GetHavingCond() def.Condition

func (*SQLStmt) GetInsertClause

func (q *SQLStmt) GetInsertClause() def.InsertClause

func (*SQLStmt) GetLimitClause

func (q *SQLStmt) GetLimitClause() *def.LimitClause

func (*SQLStmt) GetOrderByItems

func (q *SQLStmt) GetOrderByItems() []def.OrderClause

func (*SQLStmt) GetSelectClause

func (q *SQLStmt) GetSelectClause() def.SelectClause

func (*SQLStmt) GetSetFields

func (stmt *SQLStmt) GetSetFields() []string

GetSetFields returns a list of all fields being set (in INSERT or UPDATE).

func (*SQLStmt) GetSetValue

func (stmt *SQLStmt) GetSetValue(name string) (def.Expression, bool)

GetSetValue returns the value assigned to a field (in INSERT or UPDATE). For INSERT, it returns the value from the first row.

func (*SQLStmt) GetTableName

func (stmt *SQLStmt) GetTableName() string

GetTableName returns the name of the primary table being operated on.

func (*SQLStmt) GetType

func (q *SQLStmt) GetType() def.QueryType

func (*SQLStmt) GetUnions

func (q *SQLStmt) GetUnions() []def.UnionClause

func (*SQLStmt) GetUpdateClause

func (q *SQLStmt) GetUpdateClause() def.UpdateClause

func (*SQLStmt) GetWhere

func (q *SQLStmt) GetWhere() def.Condition

GetWhere returns the WHERE clause condition from the SQLStmt. Returns nil if no WHERE clause is set.

func (*SQLStmt) GetWhereCond

func (q *SQLStmt) GetWhereCond() def.Condition

func (*SQLStmt) GroupBy

func (q *SQLStmt) GroupBy(args ...any) def.SQLStmt

GroupBy sets the GROUP BY clause. Supports strings (column names) and Expression objects.

func (*SQLStmt) HasColumns

func (q *SQLStmt) HasColumns() bool

func (*SQLStmt) HasSetField

func (stmt *SQLStmt) HasSetField(name string) bool

HasSetField checks if a field is being set (in INSERT columns or UPDATE assignments).

func (*SQLStmt) HasWhere

func (stmt *SQLStmt) HasWhere() bool

HasWhere checks if the statement has a WHERE condition.

func (*SQLStmt) Having

func (q *SQLStmt) Having(cond any) def.SQLStmt

Having sets the HAVING clause.

func (*SQLStmt) Insert

func (q *SQLStmt) Insert(table any) def.SQLStmt

Insert sets the INSERT INTO table. @Deprecated: Use InsertInto instead. Will be removed in v2.0

func (*SQLStmt) InsertAndGetID

func (q *SQLStmt) InsertAndGetID(executor DBExecutor, opts ...ExecOption) (int64, error)

InsertAndGetID executes INSERT and returns the auto-generated ID. It handles dialect differences: - MySQL/SQLite: uses LastInsertId() - PostgreSQL/Oracle: uses RETURNING clause

func (*SQLStmt) InsertInto

func (q *SQLStmt) InsertInto(table any, cols ...any) def.SQLStmt

func (*SQLStmt) Join

func (q *SQLStmt) Join(target any, args ...any) def.SQLStmt

Join adds an INNER JOIN clause. target can be table name (string), subquery (*SQLStmt), or TableRef. args can include alias (string) and ON condition (Condition).

func (*SQLStmt) JoinOn

func (q *SQLStmt) JoinOn(tableWithAlias string, on string) def.SQLStmt

JoinOn adds an INNER JOIN using string tableWithAlias and ON condition.

func (*SQLStmt) LeftJoin

func (q *SQLStmt) LeftJoin(target any, args ...any) def.SQLStmt

LeftJoin adds a LEFT JOIN clause.

func (*SQLStmt) LeftJoinOn

func (q *SQLStmt) LeftJoinOn(tableWithAlias string, on string) def.SQLStmt

LeftJoinOn adds a LEFT JOIN using string tableWithAlias and ON condition.

func (*SQLStmt) Limit

func (q *SQLStmt) Limit(n int) def.SQLStmt

Limit sets the LIMIT clause.

func (*SQLStmt) Offset

func (q *SQLStmt) Offset(n int) def.SQLStmt

Offset sets the OFFSET clause.

func (*SQLStmt) OnConflict

func (q *SQLStmt) OnConflict(args ...any) def.SQLStmt

func (*SQLStmt) OnConflictUpdate

func (q *SQLStmt) OnConflictUpdate(col string, value any) def.SQLStmt

OnConflictUpdate adds an UPSERT ON CONFLICT DO UPDATE with a single column/value.

func (*SQLStmt) OrderBy

func (q *SQLStmt) OrderBy(args ...any) def.SQLStmt

OrderBy adds ORDER BY clause. Supports strings (implies ASC) and OrderClause objects (Asc/Desc).

func (*SQLStmt) OrderByAsc

func (q *SQLStmt) OrderByAsc(cols ...any) def.SQLStmt

OrderByAsc adds ORDER BY ... ASC for string columns. @Deprecated: Use OrderBy instead (defaults to ASC). Will be removed in v2.0

func (*SQLStmt) OrderByDesc

func (q *SQLStmt) OrderByDesc(cols ...any) def.SQLStmt

OrderByDesc adds ORDER BY ... DESC for string columns.

func (*SQLStmt) Page

func (q *SQLStmt) Page(page, pageSize int) def.SQLStmt

Page sets pagination (1-indexed page number).

func (*SQLStmt) Query

func (q *SQLStmt) Query(executor DBExecutor, dest any, opts ...ExecOption) error

Query 执行 SELECT 并 Scan 到 dest。自动按 executor.DBType 选方言并 BuildNamedSQL,调用方可通过 ExecOption 传递参数/上下文。

Example:

query := NewQuery(
	WithSelect(Star()),
	WithFromTable("users"),
	WithWhere(GT("age")), // uses :age parameter
)
var users []User
err := query.Query(dbCli, &users, WithExecParams(map[string]any{"age": 18}))

func (*SQLStmt) QueryAsResult

func (q *SQLStmt) QueryAsResult(executor DBExecutor, opts ...ExecOption) def.QueryResult

QueryAsResult executes a SELECT and returns the raw cydb.QueryResult. 不会做 Scan,适合调用方自行处理结果或配合分页辅助函数使用。

Example:

res, err := query.QueryAsResult(dbCli, WithExecParams(map[string]any{"age": 18}))
if err != nil { return err }
if res.HasError() { return res.Error }
// 使用 res.ScanInto / res.GetColumn / res.TotalCount 等自行处理

func (*SQLStmt) QueryForEach

func (q *SQLStmt) QueryForEach(executor DBExecutor, fn func(def.RowData) error, opts ...ExecOption) error

func (*SQLStmt) QueryOneRow

func (q *SQLStmt) QueryOneRow(executor DBExecutor, opts ...ExecOption) ([]any, []string, error)

QueryOneRow executes SELECT and returns the first row as []any (LIMIT 1 applied). 若无结果返回空切片和 nil。

func (*SQLStmt) QueryPagedResult

func (q *SQLStmt) QueryPagedResult(executor DBExecutor, opts ...ExecOption) def.QueryResult

QueryPagedResult 执行带分页的 SELECT,返回 cydb.QueryResult 并填充 TotalCount/Page/PageSize。分页信息应提前在 SQLStmt 设置 Limit/Offset; 若未设置分页,则不会额外执行 count,只执行一次查询。

Example:

query := NewQuery(
	WithSelect(Star()),
	WithFromTable("users"),
	WithWhere(GT("age")), // uses :age parameter
	WithLimit(10),
	WithOffset(20),
)
res, err := query.QueryPagedResult(dbCli, WithExecParams(map[string]any{"age": 18}))
if err != nil { return err }
fmt.Println(res.TotalCount, res.Page, res.PageSize)

func (*SQLStmt) RightJoin

func (q *SQLStmt) RightJoin(target any, args ...any) def.SQLStmt

RightJoin adds a RIGHT JOIN clause.

func (*SQLStmt) RightJoinOn

func (q *SQLStmt) RightJoinOn(tableWithAlias string, on string) def.SQLStmt

RightJoinOn adds a RIGHT JOIN using string tableWithAlias and ON condition.

func (*SQLStmt) Select

func (q *SQLStmt) Select(args ...any) def.SQLStmt

Select adds columns or expressions to the SELECT clause. Supports strings (column names) and Expression objects.

func (*SQLStmt) SelectIfEmpty

func (q *SQLStmt) SelectIfEmpty(args ...any) def.SQLStmt

SelectIfEmpty adds SELECT items only when current SELECT clause is empty. Keeps existing SELECT items unchanged otherwise.

func (*SQLStmt) Set

func (q *SQLStmt) Set(args ...any) def.SQLStmt

Set adds SET assignments. Can accept Assignment objects or (column, value) pairs if extended in future. Currently accepts assignments.

func (*SQLStmt) SetColumn

func (q *SQLStmt) SetColumn(col string, value any) def.SQLStmt

SetColumn sets a single column to a value.

func (*SQLStmt) SetLimitClause

func (q *SQLStmt) SetLimitClause(c *def.LimitClause)

func (*SQLStmt) SetOrderByItems

func (q *SQLStmt) SetOrderByItems(items []def.OrderClause)

func (*SQLStmt) SetValue

func (q *SQLStmt) SetValue(col string, value any) def.SQLStmt

SetValue sets a single column to a value. @Deprecated: Use SetColumn instead. Will be removed in v2.0

func (*SQLStmt) Sum

func (q *SQLStmt) Sum(executor DBExecutor, target any, opts ...ExecOption) (float64, error)

Sum executes SUM(target) based on current query (ignores original SELECT/LIMIT/OFFSET/ORDER BY). target 支持 string(列名或函数字符串)或 Expression。

func (*SQLStmt) Union

func (q *SQLStmt) Union(query def.SQLStmt) def.SQLStmt

Union adds a UNION clause.

func (*SQLStmt) UnionAll

func (q *SQLStmt) UnionAll(query def.SQLStmt) def.SQLStmt

UnionAll adds a UNION ALL clause.

func (*SQLStmt) Update

func (q *SQLStmt) Update(table string) def.SQLStmt

Update sets the UPDATE table.

func (*SQLStmt) Values

func (q *SQLStmt) Values(values ...any) def.SQLStmt

Values adds values for INSERT (supports Expression or raw values).

func (*SQLStmt) Where

func (q *SQLStmt) Where(conds ...any) def.SQLStmt

Where adds conditions to the WHERE clause (AND by default).

func (*SQLStmt) WhereAll

func (q *SQLStmt) WhereAll(conds ...any) def.SQLStmt

WhereAll combines conditions with AND. @Deprecated: Use Where instead (defaults to AND). Will be removed in v2.0

func (*SQLStmt) WhereAny

func (q *SQLStmt) WhereAny(conds ...any) def.SQLStmt

WhereAny combines conditions with OR.

func (*SQLStmt) WhereBetween

func (q *SQLStmt) WhereBetween(column string, start, end any) def.SQLStmt

WhereBetween adds a BETWEEN condition for a column.

func (*SQLStmt) WhereNotBetween

func (q *SQLStmt) WhereNotBetween(column string, start, end any) def.SQLStmt

WhereNotBetween adds a NOT BETWEEN condition for a column.

func (*SQLStmt) WhereOr

func (q *SQLStmt) WhereOr(conds ...any) def.SQLStmt

WhereOr adds conditions with OR.

func (*SQLStmt) WhereTupleEQ

func (q *SQLStmt) WhereTupleEQ(cols []string, vals ...any) def.SQLStmt

func (*SQLStmt) WhereTupleGT

func (q *SQLStmt) WhereTupleGT(cols []string, vals ...any) def.SQLStmt

func (*SQLStmt) WhereTupleIN

func (q *SQLStmt) WhereTupleIN(cols []string, valsList [][]any) def.SQLStmt

func (*SQLStmt) With

func (q *SQLStmt) With(args ...any) def.SQLStmt

With adds Common Table Expressions.

type SelectBuilder

type SelectBuilder = sqlbuilder.SelectBuilder

Re-export key builder types and helpers for convenience.

func NewSelectBuilder

func NewSelectBuilder() *SelectBuilder

NewSelectBuilder creates a SelectBuilder using the default builder.

func SelectWithFlavor

func SelectWithFlavor(flavor Flavor) *SelectBuilder

SelectWithFlavor creates a SelectBuilder for the given flavor.

type SelectClause

type SelectClause struct {
	Distinct bool
	Items    []*SelectItem
}

SelectClause models the SELECT projection list.

func (*SelectClause) FieldCount

func (sc *SelectClause) FieldCount() int

func (*SelectClause) HasField

func (sc *SelectClause) HasField(name string) bool

HasField checks if the select clause contains a specific field (by name or alias).

func (*SelectClause) IsDistinct

func (sc *SelectClause) IsDistinct() bool

type SelectItem

type SelectItem struct {
	Expr  def.Expression
	Alias string
}

SelectItem represents one projected expression in SELECT list.

func SelectAs

func SelectAs(expr Expression, alias string) *SelectItem

SelectAs creates SelectItem with alias.

type SortDirection

type SortDirection string

SortDirection represents the sort direction for ORDER BY.

const (
	SortAsc  SortDirection = "ASC"
	SortDesc SortDirection = "DESC"
)

type StructModel

type StructModel = sqlbuilder.Struct

Re-export key builder types and helpers for convenience.

func NewStruct

func NewStruct(model any) *StructModel

NewStruct creates a Struct helper using the default builder.

func StructWithFlavor

func StructWithFlavor(flavor Flavor, model any) *StructModel

StructWithFlavor creates a Struct helper for the given flavor.

type SubQueryExpr

type SubQueryExpr = def.SubQueryExpr

Type Aliases for convenience and backward compatibility

func SubQ

func SubQ(query *SQLStmt) *SubQueryExpr

SubQ creates a subquery expression.

type TableRef

type TableRef struct {
	Kind   TableRefKind
	Schema string
	Name   string
	Alias  string
	Query  *SQLStmt // for subqueries/CTEs
}

TableRef identifies a table-like source.

func CTERef

func CTERef(name, alias string) TableRef

CTERef creates reference to a CTE.

func SubqueryTable

func SubqueryTable(query *SQLStmt, alias string) TableRef

SubqueryTable creates derived table from subquery.

func Table

func Table(name string) TableRef

Table creates a base table reference.

Example:

Table("users")

func TableAs

func TableAs(name, alias string) TableRef

TableAs creates table with alias.

Example:

TableAs("users", "u")

func TableS

func TableS(schema, name string) TableRef

TableS creates table with schema.

Example:

TableS("public", "users")

func TableSAs

func TableSAs(schema, name, alias string) TableRef

TableSAs creates table with schema and alias.

type TableRefKind

type TableRefKind string

TableRefKind differentiates between table sources.

const (
	TableRefBase     TableRefKind = "BASE"     // regular table
	TableRefSubQuery TableRefKind = "SUBQUERY" // derived table
	TableRefCTE      TableRefKind = "CTE"      // reference to WITH entry
)

type TupleCondition

type TupleCondition = def.TupleCondition

Type Aliases for convenience and backward compatibility

type TupleExpr

type TupleExpr = def.TupleExpr

Type Aliases for convenience and backward compatibility

func Tuple

func Tuple(exprs ...Expression) *TupleExpr

Tuple creates a row value expression (expr1, expr2, ...), useful for composite keys.

Example:

Tuple(Col("order_id"), Col("product_id"))  // (order_id, product_id)
Tuple(Lit(1), Lit(2))                      // (1, 2)

func TupleCols

func TupleCols(cols ...string) *TupleExpr

TupleCols creates a tuple from column names.

Example:

TupleCols("order_id", "product_id")

func TupleParams

func TupleParams(cols ...string) *TupleExpr

TupleParams creates a tuple from named parameters.

Example:

TupleParams("order_id", "product_id")  // (:order_id, :product_id)

func TupleVals

func TupleVals(vals ...any) *TupleExpr

TupleVals creates a tuple from literal values.

Example:

TupleVals(1, 2)  // (1, 2)

type TupleInCondition

type TupleInCondition = def.TupleInCondition

Type Aliases for convenience and backward compatibility

type UnaryExpr

type UnaryExpr = def.UnaryExpr

Type Aliases for convenience and backward compatibility

func Neg

func Neg(expr Expression) *UnaryExpr

Neg creates -expr.

type UnionBuilder

type UnionBuilder = sqlbuilder.UnionBuilder

Re-export key builder types and helpers for convenience.

func NewUnionBuilder

func NewUnionBuilder() *UnionBuilder

NewUnionBuilder creates a UnionBuilder using the default builder.

func UnionWithFlavor

func UnionWithFlavor(flavor Flavor) *UnionBuilder

UnionWithFlavor creates a UnionBuilder for the given flavor.

type UnionClause

type UnionClause = def.UnionClause

Type Aliases for convenience and backward compatibility

type UpdateBuilder

type UpdateBuilder = sqlbuilder.UpdateBuilder

Re-export key builder types and helpers for convenience.

func NewUpdateBuilder

func NewUpdateBuilder() *UpdateBuilder

NewUpdateBuilder creates an UpdateBuilder using the default builder.

func UpdateWithFlavor

func UpdateWithFlavor(flavor Flavor) *UpdateBuilder

UpdateWithFlavor creates an UpdateBuilder for the given flavor.

type UpdateClause

type UpdateClause struct {
	Target      TableRef
	Assignments []Assignment
}

UpdateClause captures UPDATE assignments.

func (*UpdateClause) AssignmentCount

func (uc *UpdateClause) AssignmentCount() int

func (*UpdateClause) GetTargetName

func (uc *UpdateClause) GetTargetName() string

func (*UpdateClause) GetValue

func (uc *UpdateClause) GetValue(name string) (def.Expression, bool)

GetValue returns the new value expression assigned to a specific column.

func (*UpdateClause) HasAssignment

func (uc *UpdateClause) HasAssignment(name string) bool

HasAssignment checks if the update clause modifies a specific column.

type WhenThen

type WhenThen = def.WhenThen

Type Aliases for convenience and backward compatibility

type WildcardExpr

type WildcardExpr = def.WildcardExpr

Type Aliases for convenience and backward compatibility

type WindowExpr

type WindowExpr = def.WindowExpr

Type Aliases for convenience and backward compatibility

func Window

func Window(fn *FunctionExpr) *WindowExpr

Window creates a window expression with OVER clause.

Example:

Window(RowNumber()).PartitionBy(Col("dept")).OrderBy(Desc(Col("salary")))

type WindowFrame

type WindowFrame = def.WindowFrame

Type Aliases for convenience and backward compatibility

Jump to

Keyboard shortcuts

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