Documentation
¶
Index ¶
- Constants
- Variables
- func AddJoin(joins ...JoinClause) def.QueryOption
- func AddUnion(query *SQLStmt) def.QueryOption
- func AddUnionAll(query *SQLStmt) def.QueryOption
- func Alias(name, alias string) def.FromClause
- func AliasExpression(flavor Flavor, expr, alias string) string
- func AsDelete() def.QueryOption
- func AsInsert() def.QueryOption
- func AsReplace() def.QueryOption
- func AsSelect() def.QueryOption
- func AsUpdate() def.QueryOption
- func BETWEEN(column string, values ...any) *def.BetweenCondition
- func BeforeBuild(callback func(*SQLStmt) error) def.QueryOption
- func BuildNamed(sql string, args []interface{}) (string, map[string]any)
- func BuildNamedWithFlavor(sql string, args []interface{}, flavor Flavor) (string, map[string]any)
- func C(v any, isColumn ...bool) def.Expression
- func Col(name string) *def.ColumnExpr
- func ColS(schema, table, column string) *def.ColumnExpr
- func ColT(table, column string) *def.ColumnExpr
- func Columns(cols ...any) def.QueryOption
- func CrossJoin(target any, alias ...string) def.QueryOption
- func Delete(table any) def.QueryOption
- func DeleteFrom(tables ...TableRef) def.QueryOption
- func DeleteFromTable(name string) def.QueryOption
- func Distinct() def.QueryOption
- func Expr(sql string) *def.RawExpr
- func ForShare() def.QueryOption
- func ForUpdate() def.QueryOption
- func From(table any, alias ...string) def.QueryOption
- func FromTable(name string, alias ...string) def.QueryOption
- func FullJoin(target any, args ...any) def.QueryOption
- func GroupBy(args ...any) def.QueryOption
- func Having(cond any) def.QueryOption
- func IN(column string, values ...any) *def.InCondition
- func ISNOTNULL(column string) *def.NullCondition
- func ISNULL(column string) *def.NullCondition
- func InnerJoin(target any, args ...any) def.QueryOption
- func Insert(table any) def.QueryOption
- func InsertCols(names ...any) def.QueryOption
- func InsertColumns(columns ...Expression) def.QueryOption
- func InsertConflictColumns(cols ...Expression) def.QueryOption
- func InsertInto(table any, cols ...any) def.QueryOption
- func InsertIntoTable(name string) def.QueryOption
- func InsertRows(rows ...[]Expression) def.QueryOption
- func InsertSubQuery(subquery def.SQLStmt) def.QueryOption
- func InsertSubquery(subquery def.SQLStmt) def.QueryOption
- func InsertVals(vals ...any) def.QueryOption
- func InsertValues(values ...Expression) def.QueryOption
- func Join(target any, args ...any) def.QueryOption
- func JoinOn(tableWithAlias string, on string) def.QueryOption
- func JoinUsing(table TableRef, columns ...string) def.QueryOption
- func LIKE(column string, pattern ...string) *def.ComparisonCondition
- func LeftJoin(target any, args ...any) def.QueryOption
- func LeftJoinOn(tableWithAlias string, on string) def.QueryOption
- func LeftJoinUsing(table TableRef, columns ...string) def.QueryOption
- func Limit(limit int) def.QueryOption
- func LimitExpr(limit Expression) def.QueryOption
- func LimitOffset(limit, offset int) def.QueryOption
- func Lit(value any) *def.LiteralExpr
- func NOTBETWEEN(column string, values ...any) *def.BetweenCondition
- func NOTIN(column string, values ...any) *def.InCondition
- func NOTLIKE(column string, pattern ...string) *def.ComparisonCondition
- func NamedArg(name string) interface{}
- func NaturalJoin(table TableRef) def.QueryOption
- func NaturalLeftJoin(table TableRef) def.QueryOption
- func Offset(offset int) def.QueryOption
- func OffsetExpr(offset Expression) def.QueryOption
- func OnConflict(assignments ...Assignment) def.QueryOption
- func OnConflictExpr(exprs map[string]string) def.QueryOption
- func OrderBy(args ...any) def.QueryOption
- func OrderByAsc(args ...any) def.QueryOption
- func Page(page, pageSize int) def.QueryOption
- func Param(name string) *def.ParameterExpr
- func Parameter(name string, position int) def.QueryOption
- func Parameters(bindings ...ParameterBinding) def.QueryOption
- func QualifyIdentifier(flavor Flavor, parts ...string) string
- func QuoteIdentifier(flavor Flavor, ident string) string
- func Raw(sql string) *def.RawExpr
- func RawCond(sql string) *def.RawCondition
- func RawSQL(sql string) def.QueryOption
- func Returning(columns ...any) def.QueryOption
- func RightJoin(target any, args ...any) def.QueryOption
- func RightJoinOn(tableWithAlias string, on string) def.QueryOption
- func Select(args ...any) def.QueryOption
- func SelectColumns(items ...Expression) def.QueryOption
- func SelectIfEmpty(args ...any) def.QueryOption
- func SelectItems(items ...*SelectItem) def.QueryOption
- func Set(assignments ...Assignment) def.QueryOption
- func SetCol(columnName string, value Expression) def.QueryOption
- func SetDefaultFlavor(flavor Flavor)
- func SetDistinct(distinct bool) def.QueryOption
- func SetParam(columnName, paramName string) def.QueryOption
- func Star() *def.WildcardExpr
- func StarS(schema, table string) *def.WildcardExpr
- func StarT(table string) *def.WildcardExpr
- func Union(query *SQLStmt) def.QueryOption
- func UnionAll(query *SQLStmt) def.QueryOption
- func Update(table any) def.QueryOption
- func UpdateTableName(name string) def.QueryOption
- func UpdateTarget(table TableRef) def.QueryOption
- func Where(conds ...any) def.QueryOption
- func WhereAll(conds ...any) def.QueryOption
- func WhereAny(conds ...any) def.QueryOption
- func WhereBetween(column string, start, end any) def.QueryOption
- func WhereOr(conds ...any) def.QueryOption
- func With(ctes ...*CommonTableExpr) def.QueryOption
- type Args
- type Assignment
- type BetweenCondition
- type BinaryExpr
- type BooleanCondition
- type BuildOptions
- type Builder
- func (b *Builder) Args() *Args
- func (b *Builder) CTE() *CTEBuilder
- func (b *Builder) CTEQuery() *CTEQueryBuilder
- func (b *Builder) Clone() *Builder
- func (b *Builder) CreateTable() *CreateTableBuilder
- func (b *Builder) Delete() *DeleteBuilder
- func (b *Builder) Flavor() Flavor
- func (b *Builder) Insert() *InsertBuilder
- func (b *Builder) Select() *SelectBuilder
- func (b *Builder) Struct(model any) *StructModel
- func (b *Builder) Union() *UnionBuilder
- func (b *Builder) Update() *UpdateBuilder
- func (b *Builder) WithDatabase(dbType string, fallback ...Flavor) *Builder
- func (b *Builder) WithFlavor(flavor Flavor) *Builder
- type BuilderOption
- type CTEBuilder
- type CTEQueryBuilder
- type CaseExpr
- type CastExpr
- type ColumnExpr
- type CommonTableExpr
- type ComparisonCondition
- func CONTAINS(column, value string) *ComparisonCondition
- func ColEQ(left, right string) *ComparisonCondition
- func ColGT(left, right string) *ComparisonCondition
- func ColGTE(left, right string) *ComparisonCondition
- func ColLT(left, right string) *ComparisonCondition
- func ColLTE(left, right string) *ComparisonCondition
- func ColNE(left, right string) *ComparisonCondition
- func ENDSWITH(column, value string) *ComparisonCondition
- func Eq(left, right Expression) *ComparisonCondition
- func Gt(left, right Expression) *ComparisonCondition
- func Gte(left, right Expression) *ComparisonCondition
- func Like(left, right Expression) *ComparisonCondition
- func Lt(left, right Expression) *ComparisonCondition
- func Lte(left, right Expression) *ComparisonCondition
- func NOTCONTAINS(column, value string) *ComparisonCondition
- func Ne(left, right Expression) *ComparisonCondition
- func NotLike(left, right Expression) *ComparisonCondition
- func STARTSWITH(column, value string) *ComparisonCondition
- type Condition
- func EQ(column any, value ...any) Condition
- func GT(column any, value ...any) Condition
- func GTE(column any, value ...any) Condition
- func LT(column any, value ...any) Condition
- func LTE(column any, value ...any) Condition
- func NE(column any, value ...any) Condition
- func TupleEQ(cols []string, vals ...any) Condition
- func TupleGT(cols []string, vals ...any) Condition
- func TupleGTE(cols []string, vals ...any) Condition
- func TupleIN(cols []string, valsList [][]any) Condition
- func TupleLT(cols []string, vals ...any) Condition
- func TupleLTE(cols []string, vals ...any) Condition
- func TupleNE(cols []string, vals ...any) Condition
- func TupleNOTIN(cols []string, valsList [][]any) Condition
- type CreateTableBuilder
- type DBExecutor
- type DeleteBuilder
- type DeleteClause
- type ExecOption
- type ExistsCondition
- type Expression
- type Flavor
- type FromClause
- type FunctionExpr
- func Avg(expr Expression) *FunctionExpr
- func AvgCol(name string) *FunctionExpr
- func Coalesce(args ...Expression) *FunctionExpr
- func Concat(args ...Expression) *FunctionExpr
- func Count(expr Expression) *FunctionExpr
- func CountAll() *FunctionExpr
- func CountCol(name string) *FunctionExpr
- func CountDistinct(expr Expression) *FunctionExpr
- func CurrentDate() *FunctionExpr
- func CurrentTimestamp() *FunctionExpr
- func DenseRank() *FunctionExpr
- func FirstValue(expr Expression) *FunctionExpr
- func Func(name string, args ...Expression) *FunctionExpr
- func FuncCols(name string, args ...string) *FunctionExpr
- func FuncDistinct(name string, args ...Expression) *FunctionExpr
- func IfNull(expr, defaultVal Expression) *FunctionExpr
- func Lag(expr Expression, offset int, defaultVal ...Expression) *FunctionExpr
- func LastValue(expr Expression) *FunctionExpr
- func Lead(expr Expression, offset int, defaultVal ...Expression) *FunctionExpr
- func Length(expr Expression) *FunctionExpr
- func Lower(expr Expression) *FunctionExpr
- func Max(expr Expression) *FunctionExpr
- func Min(expr Expression) *FunctionExpr
- func NTile(n int) *FunctionExpr
- func Now() *FunctionExpr
- func Rank() *FunctionExpr
- func RowNumber() *FunctionExpr
- func Substring(expr Expression, start, length Expression) *FunctionExpr
- func Sum(expr Expression) *FunctionExpr
- func SumCol(name string) *FunctionExpr
- func Trim(expr Expression) *FunctionExpr
- func Upper(expr Expression) *FunctionExpr
- type InCondition
- func In(target Expression, values ...Expression) *InCondition
- func InSub(column string, subquery def.SQLStmt) *InCondition
- func InSubquery(target Expression, subquery def.SQLStmt) *InCondition
- func NotIn(target Expression, values ...Expression) *InCondition
- func NotInSub(column string, subquery def.SQLStmt) *InCondition
- func NotInSubquery(target Expression, subquery def.SQLStmt) *InCondition
- type InsertBuilder
- type InsertClause
- func (ic *InsertClause) ColumnCount() int
- func (ic *InsertClause) ColumnsList() []string
- func (ic *InsertClause) GetConflictValue(name string) (def.Expression, bool)
- func (ic *InsertClause) GetTargetName() string
- func (ic *InsertClause) GetValue(name string) (def.Expression, bool)
- func (ic *InsertClause) HasColumn(name string) bool
- func (ic *InsertClause) HasConflictAssignment(name string) bool
- func (ic *InsertClause) RowCount() int
- type InsertMode
- type JoinClause
- func NewCrossJoin(table TableRef) JoinClause
- func NewFullJoin(table TableRef, on Condition) JoinClause
- func NewInnerJoin(table TableRef, on Condition) JoinClause
- func NewJoin(joinType JoinType, table TableRef, on Condition) JoinClause
- func NewJoinUsing(joinType JoinType, table TableRef, columns ...string) JoinClause
- func NewLeftJoin(table TableRef, on Condition) JoinClause
- func NewNaturalJoin(joinType JoinType, table TableRef) JoinClause
- func NewRightJoin(table TableRef, on Condition) JoinClause
- type JoinType
- type LikePatternExpr
- type LimitClause
- type LiteralExpr
- type LockClause
- type LockMode
- type NamedParam
- type NullCondition
- type OrderClause
- type ParameterBinding
- type ParameterExpr
- type QueryOption
- type QueryType
- type RawCondition
- type RawExpr
- type SQLBuilder
- type SQLStmt
- func (q *SQLStmt) Apply(opts ...QueryOption) def.SQLStmt
- func (q *SQLStmt) Avg(executor DBExecutor, target any, opts ...ExecOption) (float64, error)
- func (q *SQLStmt) Build(flavor def.Flavor) (string, []interface{}, error)
- func (q *SQLStmt) BuildMySQL() (string, []interface{}, error)
- func (q *SQLStmt) BuildNamedSQL(opts BuildOptions) (string, map[string]any, error)
- func (q *SQLStmt) BuildPostgreSQL() (string, []interface{}, error)
- func (q *SQLStmt) BuildSQL(opts BuildOptions) (string, []interface{}, error)
- func (q *SQLStmt) BuildSQLite() (string, []interface{}, error)
- func (q *SQLStmt) BuildWhereNamedSQL(opts BuildOptions) (string, map[string]any, error)
- func (q *SQLStmt) BuildWhereSQL(opts BuildOptions) (string, []interface{}, error)
- func (q *SQLStmt) Clone() def.SQLStmt
- func (q *SQLStmt) Columns(cols ...any) def.SQLStmt
- func (q *SQLStmt) ColumnsIfNotSet(cols ...any) def.SQLStmt
- func (q *SQLStmt) Count(executor DBExecutor, target any, opts ...ExecOption) (int64, error)
- func (q *SQLStmt) CrossJoin(target any, alias ...string) def.SQLStmt
- func (q *SQLStmt) Delete(table string) def.SQLStmt
- func (q *SQLStmt) Distinct() def.SQLStmt
- func (q *SQLStmt) Exec(executor DBExecutor, opts ...ExecOption) (int64, error)
- func (q *SQLStmt) ForShare() def.SQLStmt
- func (q *SQLStmt) ForUpdate() def.SQLStmt
- func (q *SQLStmt) From(table any, alias ...string) def.SQLStmt
- func (q *SQLStmt) FullJoin(target any, args ...any) def.SQLStmt
- func (q *SQLStmt) GetCTEs() []*def.CommonTableExpr
- func (q *SQLStmt) GetFromClause() def.FromClause
- func (q *SQLStmt) GetGroupByItems() []def.Expression
- func (q *SQLStmt) GetHavingCond() def.Condition
- func (q *SQLStmt) GetInsertClause() def.InsertClause
- func (q *SQLStmt) GetLimitClause() *def.LimitClause
- func (q *SQLStmt) GetOrderByItems() []def.OrderClause
- func (q *SQLStmt) GetSelectClause() def.SelectClause
- func (stmt *SQLStmt) GetSetFields() []string
- func (stmt *SQLStmt) GetSetValue(name string) (def.Expression, bool)
- func (stmt *SQLStmt) GetTableName() string
- func (q *SQLStmt) GetType() def.QueryType
- func (q *SQLStmt) GetUnions() []def.UnionClause
- func (q *SQLStmt) GetUpdateClause() def.UpdateClause
- func (q *SQLStmt) GetWhere() def.Condition
- func (q *SQLStmt) GetWhereCond() def.Condition
- func (q *SQLStmt) GroupBy(args ...any) def.SQLStmt
- func (q *SQLStmt) HasColumns() bool
- func (stmt *SQLStmt) HasSetField(name string) bool
- func (stmt *SQLStmt) HasWhere() bool
- func (q *SQLStmt) Having(cond any) def.SQLStmt
- func (q *SQLStmt) Insert(table any) def.SQLStmt
- func (q *SQLStmt) InsertAndGetID(executor DBExecutor, opts ...ExecOption) (int64, error)
- func (q *SQLStmt) InsertInto(table any, cols ...any) def.SQLStmt
- func (q *SQLStmt) Join(target any, args ...any) def.SQLStmt
- func (q *SQLStmt) JoinOn(tableWithAlias string, on string) def.SQLStmt
- func (q *SQLStmt) LeftJoin(target any, args ...any) def.SQLStmt
- func (q *SQLStmt) LeftJoinOn(tableWithAlias string, on string) def.SQLStmt
- func (q *SQLStmt) Limit(n int) def.SQLStmt
- func (q *SQLStmt) Offset(n int) def.SQLStmt
- func (q *SQLStmt) OnConflict(args ...any) def.SQLStmt
- func (q *SQLStmt) OnConflictUpdate(col string, value any) def.SQLStmt
- func (q *SQLStmt) OrderBy(args ...any) def.SQLStmt
- func (q *SQLStmt) OrderByAsc(cols ...any) def.SQLStmt
- func (q *SQLStmt) OrderByDesc(cols ...any) def.SQLStmt
- func (q *SQLStmt) Page(page, pageSize int) def.SQLStmt
- func (q *SQLStmt) Query(executor DBExecutor, dest any, opts ...ExecOption) error
- func (q *SQLStmt) QueryAsResult(executor DBExecutor, opts ...ExecOption) def.QueryResult
- func (q *SQLStmt) QueryForEach(executor DBExecutor, fn func(def.RowData) error, opts ...ExecOption) error
- func (q *SQLStmt) QueryOneRow(executor DBExecutor, opts ...ExecOption) ([]any, []string, error)
- func (q *SQLStmt) QueryPagedResult(executor DBExecutor, opts ...ExecOption) def.QueryResult
- func (q *SQLStmt) RightJoin(target any, args ...any) def.SQLStmt
- func (q *SQLStmt) RightJoinOn(tableWithAlias string, on string) def.SQLStmt
- func (q *SQLStmt) Select(args ...any) def.SQLStmt
- func (q *SQLStmt) SelectIfEmpty(args ...any) def.SQLStmt
- func (q *SQLStmt) Set(args ...any) def.SQLStmt
- func (q *SQLStmt) SetColumn(col string, value any) def.SQLStmt
- func (q *SQLStmt) SetLimitClause(c *def.LimitClause)
- func (q *SQLStmt) SetOrderByItems(items []def.OrderClause)
- func (q *SQLStmt) SetValue(col string, value any) def.SQLStmt
- func (q *SQLStmt) Sum(executor DBExecutor, target any, opts ...ExecOption) (float64, error)
- func (q *SQLStmt) Union(query def.SQLStmt) def.SQLStmt
- func (q *SQLStmt) UnionAll(query def.SQLStmt) def.SQLStmt
- func (q *SQLStmt) Update(table string) def.SQLStmt
- func (q *SQLStmt) Values(values ...any) def.SQLStmt
- func (q *SQLStmt) Where(conds ...any) def.SQLStmt
- func (q *SQLStmt) WhereAll(conds ...any) def.SQLStmt
- func (q *SQLStmt) WhereAny(conds ...any) def.SQLStmt
- func (q *SQLStmt) WhereBetween(column string, start, end any) def.SQLStmt
- func (q *SQLStmt) WhereNotBetween(column string, start, end any) def.SQLStmt
- func (q *SQLStmt) WhereOr(conds ...any) def.SQLStmt
- func (q *SQLStmt) WhereTupleEQ(cols []string, vals ...any) def.SQLStmt
- func (q *SQLStmt) WhereTupleGT(cols []string, vals ...any) def.SQLStmt
- func (q *SQLStmt) WhereTupleIN(cols []string, valsList [][]any) def.SQLStmt
- func (q *SQLStmt) With(args ...any) def.SQLStmt
- type SelectBuilder
- type SelectClause
- type SelectItem
- type SortDirection
- type StructModel
- type SubQueryExpr
- type TableRef
- type TableRefKind
- type TupleCondition
- type TupleExpr
- type TupleInCondition
- type UnaryExpr
- type UnionBuilder
- type UnionClause
- type UpdateBuilder
- type UpdateClause
- type WhenThen
- type WildcardExpr
- type WindowExpr
- type WindowFrame
Constants ¶
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 )
const ( QueryTypeUnknown = def.QueryTypeUnknown QueryTypeSelect = def.QueryTypeSelect QueryTypeInsert = def.QueryTypeInsert QueryTypeUpdate = def.QueryTypeUpdate QueryTypeDelete = def.QueryTypeDelete )
Variables ¶
var WhereAnd = Where
WhereAnd is an alias for Where.
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 Alias ¶
func Alias(name, alias string) def.FromClause
Alias creates a base table reference with alias.
Example:
Alias("users", "u")
func AliasExpression ¶
AliasExpression appends an AS alias to the given expression when alias is non-empty.
func AsReplace ¶
func AsReplace() def.QueryOption
AsReplace uses REPLACE semantics (MySQL/SQLite native; others emulate).
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 ¶
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 ¶
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 Expr ¶
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 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 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 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 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 ¶
QualifyIdentifier joins identifier segments (schema/table/column) with dot separators.
func QuoteIdentifier ¶
QuoteIdentifier applies flavor-specific quoting to a single identifier segment.
func Raw ¶
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 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 StarS ¶
func StarS(schema, table string) *def.WildcardExpr
StarS creates schema.table.* wildcard.
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"))
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 New ¶
func New(opts ...BuilderOption) *Builder
New creates a Builder with optional configuration.
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) 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) 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 ¶
WithDatabase maps a database type string (e.g. mysql/postgres) to flavor.
func (*Builder) WithFlavor ¶
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 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 ¶
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 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 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 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 Aliases for convenience and backward compatibility
func EQ ¶
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 TupleEQ ¶
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 ¶
TupleGT creates (cols...) > (vals...), useful for keyset pagination. Auto-degrades to simple comparison for single column.
func TupleIN ¶
TupleIN creates (cols...) IN ((v1...), (v2...), ...), for multiple composite keys.
Example:
TupleIN([]string{"order_id", "product_id"}, [][]any{{1, 2}, {3, 4}})
func TupleNOTIN ¶
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 ¶
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 AvgCol ¶
func AvgCol(name string) *FunctionExpr
func Count ¶
func Count(expr Expression) *FunctionExpr
Count creates COUNT(expr).
Example:
Count(Col("id"))
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 CurrentTimestamp ¶
func CurrentTimestamp() *FunctionExpr
CurrentTimestamp creates CURRENT_TIMESTAMP.
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 Lead ¶
func Lead(expr Expression, offset int, defaultVal ...Expression) *FunctionExpr
Lead creates LEAD(expr, offset, default?).
func Substring ¶
func Substring(expr Expression, start, length Expression) *FunctionExpr
Substring creates SUBSTRING(expr, start, length).
func SumCol ¶
func SumCol(name string) *FunctionExpr
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 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 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 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.
type OrderClause ¶
type OrderClause = def.OrderClause
Clauses
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 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 ¶
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 RawCondition ¶
type RawCondition = def.RawCondition
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 ¶
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 ¶
Build is a convenience wrapper for BuildSQL using just a flavor. It satisfies the def.SQLStmt interface.
func (*SQLStmt) BuildMySQL ¶
BuildMySQL compiles the query for MySQL.
func (*SQLStmt) BuildNamedSQL ¶
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 ¶
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 ¶
BuildSQLite compiles the query for SQLite.
func (*SQLStmt) BuildWhereNamedSQL ¶
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) Columns ¶
Columns sets the columns for INSERT. @Deprecated: Use InsertInto with column parameters instead. Will be removed in v2.0
func (*SQLStmt) ColumnsIfNotSet ¶
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) 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) From ¶
From sets the FROM clause. table can be: - string: table name - *SQLStmt: subquery - TableRef: explicit table reference alias is optional.
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 (*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 ¶
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 ¶
GetTableName returns the name of the primary table being operated on.
func (*SQLStmt) GetUnions ¶
func (q *SQLStmt) GetUnions() []def.UnionClause
func (*SQLStmt) GetUpdateClause ¶
func (q *SQLStmt) GetUpdateClause() def.UpdateClause
func (*SQLStmt) GetWhere ¶
GetWhere returns the WHERE clause condition from the SQLStmt. Returns nil if no WHERE clause is set.
func (*SQLStmt) GetWhereCond ¶
func (*SQLStmt) GroupBy ¶
GroupBy sets the GROUP BY clause. Supports strings (column names) and Expression objects.
func (*SQLStmt) HasColumns ¶
func (*SQLStmt) HasSetField ¶
HasSetField checks if a field is being set (in INSERT columns or UPDATE assignments).
func (*SQLStmt) Insert ¶
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) Join ¶
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) LeftJoinOn ¶
LeftJoinOn adds a LEFT JOIN using string tableWithAlias and ON condition.
func (*SQLStmt) OnConflictUpdate ¶
OnConflictUpdate adds an UPSERT ON CONFLICT DO UPDATE with a single column/value.
func (*SQLStmt) OrderBy ¶
OrderBy adds ORDER BY clause. Supports strings (implies ASC) and OrderClause objects (Asc/Desc).
func (*SQLStmt) OrderByAsc ¶
OrderByAsc adds ORDER BY ... ASC for string columns. @Deprecated: Use OrderBy instead (defaults to ASC). Will be removed in v2.0
func (*SQLStmt) OrderByDesc ¶
OrderByDesc adds ORDER BY ... DESC for string columns.
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) RightJoinOn ¶
RightJoinOn adds a RIGHT JOIN using string tableWithAlias and ON condition.
func (*SQLStmt) Select ¶
Select adds columns or expressions to the SELECT clause. Supports strings (column names) and Expression objects.
func (*SQLStmt) SelectIfEmpty ¶
SelectIfEmpty adds SELECT items only when current SELECT clause is empty. Keeps existing SELECT items unchanged otherwise.
func (*SQLStmt) Set ¶
Set adds SET assignments. Can accept Assignment objects or (column, value) pairs if extended in future. Currently accepts assignments.
func (*SQLStmt) SetLimitClause ¶
func (q *SQLStmt) SetLimitClause(c *def.LimitClause)
func (*SQLStmt) SetOrderByItems ¶
func (q *SQLStmt) SetOrderByItems(items []def.OrderClause)
func (*SQLStmt) SetValue ¶
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) WhereAll ¶
WhereAll combines conditions with AND. @Deprecated: Use Where instead (defaults to AND). Will be removed in v2.0
func (*SQLStmt) WhereBetween ¶
WhereBetween adds a BETWEEN condition for a column.
func (*SQLStmt) WhereNotBetween ¶
WhereNotBetween adds a NOT BETWEEN condition for a column.
func (*SQLStmt) WhereTupleEQ ¶
func (*SQLStmt) WhereTupleGT ¶
func (*SQLStmt) WhereTupleIN ¶
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
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 SubqueryTable ¶
SubqueryTable creates derived table from subquery.
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 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 ¶
TupleCols creates a tuple from column names.
Example:
TupleCols("order_id", "product_id")
func TupleParams ¶
TupleParams creates a tuple from named parameters.
Example:
TupleParams("order_id", "product_id") // (:order_id, :product_id)
type TupleInCondition ¶
type TupleInCondition = def.TupleInCondition
Type Aliases for convenience and backward compatibility
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 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