sqlbuilder

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package sqlbuilder provides a fluent, type-safe SQL query builder for PostgreSQL, MySQL, and SQLite.

By default it uses PostgreSQL $1, $2, ... numbered placeholders. Set a dialect to target MySQL or SQLite (? positional placeholders) via .SetDialect() or the SelectWith/InsertWith/UpdateWith/DeleteWith constructors.

It integrates with the request package's Pagination, SortField, and Filter types for API-driven queries.

Quick Start

sql, args := sqlbuilder.Select("id", "name", "email").
    From("users").
    Where("active = $1", true).
    OrderBy("name ASC").
    Limit(20).
    Build()
// sql:  "SELECT id, name, email FROM users WHERE active = $1 ORDER BY name ASC LIMIT 20"
// args: [true]

Placeholder Rebasing

Each Where call uses $1-relative placeholders. At Build time they are automatically rebased to globally correct positions:

sql, args := sqlbuilder.Select("id").From("users").
    Where("status = $1", "active").
    Where("age > $1", 18).
    Build()
// sql:  "SELECT id FROM users WHERE status = $1 AND age > $2"
// args: ["active", 18]

Integration with request Package

pg, _ := request.Paginate(r)
sorts, _ := request.ParseSort(r, sortCfg)
filters, _ := request.ParseFilters(r, filterCfg)

cols := map[string]string{"name": "u.name", "created_at": "u.created_at"}

sql, args := sqlbuilder.Select("u.id", "u.name").
    From("users u").
    Where("u.active = $1", true).
    ApplyFilters(filters, cols).
    ApplySort(sorts, cols).
    ApplyPagination(pg).
    Build()

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Or

func Or(sql string, args ...any) condition

Or creates a condition that is used inside WhereOr to combine multiple conditions with OR logic.

Select("id").From("users").
    WhereOr(
        sqlbuilder.Or("status = $1", "active"),
        sqlbuilder.Or("role = $1", "admin"),
    ).Build()
// WHERE (status = $1 OR role = $2)

Types

type CaseBuilder added in v0.10.0

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

CaseBuilder builds SQL CASE expressions.

func Case added in v0.10.0

func Case(operand ...string) *CaseBuilder

Case creates a new CaseBuilder. If an operand is provided, it becomes a simple CASE (CASE operand WHEN ...); otherwise it's a searched CASE.

func (*CaseBuilder) Else added in v0.10.0

func (cb *CaseBuilder) Else(result string) *CaseBuilder

Else sets the ELSE clause with a literal SQL string.

func (*CaseBuilder) ElseExpr added in v0.10.0

func (cb *CaseBuilder) ElseExpr(result string, args ...any) *CaseBuilder

ElseExpr sets the ELSE clause with a parameterized expression.

func (*CaseBuilder) End added in v0.10.0

func (cb *CaseBuilder) End() Expr

End builds the CASE expression and returns it as an Expr.

func (*CaseBuilder) When added in v0.10.0

func (cb *CaseBuilder) When(cond, result string) *CaseBuilder

When adds a WHEN/THEN pair with literal SQL.

func (*CaseBuilder) WhenExpr added in v0.10.0

func (cb *CaseBuilder) WhenExpr(condSQL string, condArgs []any, thenSQL string, thenArgs []any) *CaseBuilder

WhenExpr adds a parameterized WHEN/THEN pair.

type DeleteBuilder

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

DeleteBuilder builds DELETE queries.

func Delete

func Delete(table string) *DeleteBuilder

Delete creates a new DeleteBuilder for the given table.

sqlbuilder.Delete("users").Where("id = $1", 1)
Example
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Delete("users").
		Where("id = $1", 1).
		Returning("id", "name").
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

DELETE FROM users WHERE id = $1 RETURNING id, name
[1]

func DeleteWith

func DeleteWith(d Dialect, table string) *DeleteBuilder

DeleteWith creates a new DeleteBuilder with the given dialect and table.

func (*DeleteBuilder) Build

func (b *DeleteBuilder) Build() (string, []any)

Build assembles the SQL string and arguments.

func (*DeleteBuilder) Clone

func (b *DeleteBuilder) Clone() *DeleteBuilder

Clone creates a deep copy of the builder.

func (*DeleteBuilder) MustBuild

func (b *DeleteBuilder) MustBuild() (string, []any)

MustBuild calls Build and panics if the builder is in an invalid state.

func (*DeleteBuilder) Query

func (b *DeleteBuilder) Query() Query

Query builds and returns a Query struct.

func (*DeleteBuilder) Returning

func (b *DeleteBuilder) Returning(cols ...string) *DeleteBuilder

Returning adds a RETURNING clause.

func (*DeleteBuilder) ReturningExpr added in v0.10.0

func (b *DeleteBuilder) ReturningExpr(exprs ...Expr) *DeleteBuilder

ReturningExpr adds expression columns to the RETURNING clause.

func (*DeleteBuilder) SetDialect

func (b *DeleteBuilder) SetDialect(d Dialect) *DeleteBuilder

SetDialect sets the SQL dialect for placeholder conversion at Build time.

func (*DeleteBuilder) String

func (b *DeleteBuilder) String() string

String returns the SQL string only, for debugging.

func (*DeleteBuilder) Using

func (b *DeleteBuilder) Using(tables ...string) *DeleteBuilder

Using adds tables for multi-table DELETE (PostgreSQL USING clause).

func (*DeleteBuilder) When

func (b *DeleteBuilder) When(cond bool, fn func(*DeleteBuilder)) *DeleteBuilder

When conditionally applies a function to the builder.

func (*DeleteBuilder) Where

func (b *DeleteBuilder) Where(sql string, args ...any) *DeleteBuilder

Where adds a WHERE condition.

func (*DeleteBuilder) WhereBetween

func (b *DeleteBuilder) WhereBetween(col string, low, high any) *DeleteBuilder

WhereBetween adds a "col BETWEEN low AND high" condition.

func (*DeleteBuilder) WhereColumn added in v0.10.0

func (b *DeleteBuilder) WhereColumn(col1, op, col2 string) *DeleteBuilder

WhereColumn adds a column-to-column comparison condition (e.g., "a.id = b.id").

func (*DeleteBuilder) WhereEq

func (b *DeleteBuilder) WhereEq(col string, val any) *DeleteBuilder

WhereEq adds a "col = val" condition.

func (*DeleteBuilder) WhereExists

func (b *DeleteBuilder) WhereExists(sub *SelectBuilder) *DeleteBuilder

WhereExists adds a "EXISTS (subquery)" condition.

func (*DeleteBuilder) WhereGt

func (b *DeleteBuilder) WhereGt(col string, val any) *DeleteBuilder

WhereGt adds a "col > val" condition.

func (*DeleteBuilder) WhereGte

func (b *DeleteBuilder) WhereGte(col string, val any) *DeleteBuilder

WhereGte adds a "col >= val" condition.

func (*DeleteBuilder) WhereILike

func (b *DeleteBuilder) WhereILike(col string, val any) *DeleteBuilder

WhereILike adds a "col ILIKE val" condition (case-insensitive LIKE, PostgreSQL).

func (*DeleteBuilder) WhereIn

func (b *DeleteBuilder) WhereIn(col string, vals ...any) *DeleteBuilder

WhereIn adds a "col IN (...)" condition.

func (*DeleteBuilder) WhereInSubquery

func (b *DeleteBuilder) WhereInSubquery(col string, sub *SelectBuilder) *DeleteBuilder

WhereInSubquery adds a "col IN (subquery)" condition.

func (*DeleteBuilder) WhereLike

func (b *DeleteBuilder) WhereLike(col string, val any) *DeleteBuilder

WhereLike adds a "col LIKE val" condition.

func (*DeleteBuilder) WhereLt

func (b *DeleteBuilder) WhereLt(col string, val any) *DeleteBuilder

WhereLt adds a "col < val" condition.

func (*DeleteBuilder) WhereLte

func (b *DeleteBuilder) WhereLte(col string, val any) *DeleteBuilder

WhereLte adds a "col <= val" condition.

func (*DeleteBuilder) WhereNeq

func (b *DeleteBuilder) WhereNeq(col string, val any) *DeleteBuilder

WhereNeq adds a "col != val" condition.

func (*DeleteBuilder) WhereNotExists

func (b *DeleteBuilder) WhereNotExists(sub *SelectBuilder) *DeleteBuilder

WhereNotExists adds a "NOT EXISTS (subquery)" condition.

func (*DeleteBuilder) WhereNotIn

func (b *DeleteBuilder) WhereNotIn(col string, vals ...any) *DeleteBuilder

WhereNotIn adds a "col NOT IN (...)" condition.

func (*DeleteBuilder) WhereNotInSubquery

func (b *DeleteBuilder) WhereNotInSubquery(col string, sub *SelectBuilder) *DeleteBuilder

WhereNotInSubquery adds a "col NOT IN (subquery)" condition.

func (*DeleteBuilder) WhereNotNull

func (b *DeleteBuilder) WhereNotNull(col string) *DeleteBuilder

WhereNotNull adds a "col IS NOT NULL" condition.

func (*DeleteBuilder) WhereNull

func (b *DeleteBuilder) WhereNull(col string) *DeleteBuilder

WhereNull adds a "col IS NULL" condition.

func (*DeleteBuilder) WhereOr

func (b *DeleteBuilder) WhereOr(conditions ...condition) *DeleteBuilder

WhereOr adds a group of OR conditions wrapped in parentheses.

func (*DeleteBuilder) With

func (b *DeleteBuilder) With(name string, q Query) *DeleteBuilder

With adds a CTE (Common Table Expression).

func (*DeleteBuilder) WithSelect

func (b *DeleteBuilder) WithSelect(name string, sub *SelectBuilder) *DeleteBuilder

WithSelect adds a CTE from a SelectBuilder. This is dialect-safe: the subquery is always built with Postgres placeholders internally.

type Dialect

type Dialect int

Dialect represents the target SQL database dialect. The zero value is Postgres.

const (
	// Postgres uses $1, $2, ... numbered placeholders.
	Postgres Dialect = iota
	// MySQL uses ? positional placeholders.
	MySQL
	// SQLite uses ? positional placeholders.
	SQLite
)

type Expr

type Expr struct {
	SQL  string
	Args []any
}

Expr represents a raw SQL expression with optional arguments. Use it where a plain string column would not suffice, such as function calls or computed expressions.

func Avg

func Avg(col string) Expr

Avg creates an AVG(col) expression.

func Cast added in v0.10.0

func Cast(expr, typeName string) Expr

Cast creates a CAST(expr AS type) expression with a literal expression.

func CastExpr added in v0.10.0

func CastExpr(expr Expr, typeName string) Expr

CastExpr creates a CAST expression from a parameterized Expr.

func Coalesce added in v0.10.0

func Coalesce(exprs ...string) Expr

Coalesce creates a COALESCE(a, b, c) expression with literal arguments.

func CoalesceExpr added in v0.10.0

func CoalesceExpr(exprs ...Expr) Expr

CoalesceExpr creates a COALESCE expression from parameterized Exprs. Placeholders in each Expr are rebased so they chain correctly.

func Count

func Count(col string) Expr

Count creates a COUNT(col) expression.

func CountDistinct

func CountDistinct(col string) Expr

CountDistinct creates a COUNT(DISTINCT col) expression.

func DenseRank added in v0.10.0

func DenseRank() Expr

DenseRank creates a DENSE_RANK() expression.

func Lag added in v0.10.0

func Lag(col string) Expr

Lag creates a LAG(col) expression.

func Lead added in v0.10.0

func Lead(col string) Expr

Lead creates a LEAD(col) expression.

func Max

func Max(col string) Expr

Max creates a MAX(col) expression.

func Min

func Min(col string) Expr

Min creates a MIN(col) expression.

func Ntile added in v0.10.0

func Ntile(n int) Expr

Ntile creates an NTILE(n) expression.

func NullIf added in v0.10.0

func NullIf(expr1, expr2 string) Expr

NullIf creates a NULLIF(a, b) expression with literal arguments.

func NullIfExpr added in v0.10.0

func NullIfExpr(expr1, expr2 Expr) Expr

NullIfExpr creates a NULLIF expression from parameterized Exprs.

func Rank added in v0.10.0

func Rank() Expr

Rank creates a RANK() expression.

func Raw

func Raw(sql string) Expr

Raw creates an Expr with no arguments, for use with SQL literals like NOW(), DEFAULT, or column references.

sqlbuilder.Raw("NOW()")
sqlbuilder.Raw("DEFAULT")

func RawExpr

func RawExpr(sql string, args ...any) Expr

RawExpr creates an Expr with arguments, for parameterized expressions.

sqlbuilder.RawExpr("COUNT(*) FILTER (WHERE status = $1)", "active")
sqlbuilder.RawExpr("COALESCE($1, $2)", fallback1, fallback2)

func RowNumber added in v0.10.0

func RowNumber() Expr

RowNumber creates a ROW_NUMBER() expression.

func Sum

func Sum(col string) Expr

Sum creates a SUM(col) expression.

func (Expr) As

func (e Expr) As(alias string) Expr

As appends an alias to the expression.

Count("*").As("total") → Expr{SQL: "COUNT(*) AS total"}

func (Expr) Over added in v0.10.0

func (e Expr) Over(w *WindowBuilder) Expr

Over appends an OVER clause from a WindowBuilder to the expression.

RowNumber().Over(Window().PartitionBy("dept").OrderBy("salary DESC"))

func (Expr) OverRaw added in v0.10.0

func (e Expr) OverRaw(clause string) Expr

OverRaw appends an OVER clause with a raw string to the expression.

Count("*").OverRaw("ORDER BY created_at")

type InsertBuilder

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

InsertBuilder builds INSERT queries.

func Insert

func Insert(table string) *InsertBuilder

Insert creates a new InsertBuilder for the given table.

sqlbuilder.Insert("users").Columns("name", "email").Values("Alice", "alice@example.com")
Example
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Insert("users").
		Columns("name", "email").
		Values("Alice", "alice@example.com").
		Returning("id").
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id
[Alice alice@example.com]
Example (Batch)
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Insert("users").
		Columns("name", "email").
		Values("Alice", "alice@example.com").
		Values("Bob", "bob@example.com").
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

INSERT INTO users (name, email) VALUES ($1, $2), ($3, $4)
[Alice alice@example.com Bob bob@example.com]
Example (Upsert)
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Insert("users").
		Columns("email", "name").
		Values("alice@example.com", "Alice").
		OnConflictUpdate(
			[]string{"email"},
			map[string]any{"name": "Alice Updated"},
		).
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

INSERT INTO users (email, name) VALUES ($1, $2) ON CONFLICT (email) DO UPDATE SET name = $3
[alice@example.com Alice Alice Updated]

func InsertWith

func InsertWith(d Dialect, table string) *InsertBuilder

InsertWith creates a new InsertBuilder with the given dialect and table.

func (*InsertBuilder) BatchValues

func (b *InsertBuilder) BatchValues(rows [][]any) *InsertBuilder

BatchValues adds multiple rows at once.

func (*InsertBuilder) Build

func (b *InsertBuilder) Build() (string, []any)

Build assembles the SQL string and arguments.

func (*InsertBuilder) Clone

func (b *InsertBuilder) Clone() *InsertBuilder

Clone creates a deep copy of the builder.

func (*InsertBuilder) Columns

func (b *InsertBuilder) Columns(cols ...string) *InsertBuilder

Columns sets the column names for the INSERT.

func (*InsertBuilder) FromSelect

func (b *InsertBuilder) FromSelect(sel *SelectBuilder) *InsertBuilder

FromSelect sets the INSERT to use a SELECT as the data source.

Insert("archive").Columns("id", "name").FromSelect(
    Select("id", "name").From("users").Where("archived = $1", true),
)

func (*InsertBuilder) MustBuild

func (b *InsertBuilder) MustBuild() (string, []any)

MustBuild calls Build and panics if the builder is in an invalid state.

func (*InsertBuilder) OnConflictDoNothing

func (b *InsertBuilder) OnConflictDoNothing(target ...string) *InsertBuilder

OnConflictDoNothing adds ON CONFLICT DO NOTHING. target is optional conflict target columns (e.g., "id" or "email").

func (*InsertBuilder) OnConflictUpdate

func (b *InsertBuilder) OnConflictUpdate(target []string, updates map[string]any) *InsertBuilder

OnConflictUpdate adds ON CONFLICT ... DO UPDATE SET for upsert. target specifies the conflict columns, updates maps column names to values.

func (*InsertBuilder) OnConflictUpdateExpr

func (b *InsertBuilder) OnConflictUpdateExpr(target []string, updates map[string]Expr) *InsertBuilder

OnConflictUpdateExpr adds ON CONFLICT ... DO UPDATE SET with expressions.

func (*InsertBuilder) Query

func (b *InsertBuilder) Query() Query

Query builds and returns a Query struct.

func (*InsertBuilder) Returning

func (b *InsertBuilder) Returning(cols ...string) *InsertBuilder

Returning adds a RETURNING clause.

func (*InsertBuilder) ReturningExpr added in v0.10.0

func (b *InsertBuilder) ReturningExpr(exprs ...Expr) *InsertBuilder

ReturningExpr adds expression columns to the RETURNING clause.

func (*InsertBuilder) SetDialect

func (b *InsertBuilder) SetDialect(d Dialect) *InsertBuilder

SetDialect sets the SQL dialect for placeholder conversion at Build time.

func (*InsertBuilder) String

func (b *InsertBuilder) String() string

String returns the SQL string only, for debugging.

func (*InsertBuilder) ValueMap

func (b *InsertBuilder) ValueMap(m map[string]any) *InsertBuilder

ValueMap adds a row from a map. Keys are sorted for deterministic output. If columns are already set (via Columns or a prior ValueMap), values are extracted in column order to ensure correct alignment.

func (*InsertBuilder) Values

func (b *InsertBuilder) Values(vals ...any) *InsertBuilder

Values adds a row of values. Can be called multiple times for batch inserts.

func (*InsertBuilder) When

func (b *InsertBuilder) When(cond bool, fn func(*InsertBuilder)) *InsertBuilder

When conditionally applies a function to the builder.

func (*InsertBuilder) With

func (b *InsertBuilder) With(name string, q Query) *InsertBuilder

With adds a CTE (Common Table Expression).

func (*InsertBuilder) WithSelect

func (b *InsertBuilder) WithSelect(name string, sub *SelectBuilder) *InsertBuilder

WithSelect adds a CTE from a SelectBuilder. This is dialect-safe: the subquery is always built with Postgres placeholders internally.

type Query

type Query struct {
	SQL  string
	Args []any
}

Query holds a built SQL statement and its arguments.

type SelectBuilder

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

SelectBuilder builds SELECT queries.

func ApplyFilters

func ApplyFilters(sb *SelectBuilder, filters []request.Filter, allowedColumns map[string]string) *SelectBuilder

ApplyFilters applies request.Filter slices to a SelectBuilder. This is a standalone function alternative to the method on SelectBuilder.

func ApplyPagination

func ApplyPagination(sb *SelectBuilder, p request.Pagination) *SelectBuilder

ApplyPagination applies request.Pagination to a SelectBuilder. This is a standalone function alternative to the method on SelectBuilder.

func ApplySort

func ApplySort(sb *SelectBuilder, sorts []request.SortField, allowedColumns map[string]string) *SelectBuilder

ApplySort applies request.SortField slices to a SelectBuilder. This is a standalone function alternative to the method on SelectBuilder.

func Select

func Select(columns ...string) *SelectBuilder

Select creates a new SelectBuilder with the given columns.

sqlbuilder.Select("id", "name", "email")
Example
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Select("id", "name", "email").
		From("users").
		Where("active = $1", true).
		OrderBy("name ASC").
		Limit(20).
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

SELECT id, name, email FROM users WHERE active = $1 ORDER BY name ASC LIMIT 20
[true]
Example (Join)
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Select("u.id", "u.name", "p.bio").
		From("users u").
		LeftJoin("profiles p", "p.user_id = u.id").
		Where("u.active = $1", true).
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

SELECT u.id, u.name, p.bio FROM users u LEFT JOIN profiles p ON p.user_id = u.id WHERE u.active = $1
[true]
Example (Pagination)
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/request"
	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	p := request.Pagination{Page: 3, PerPage: 25, Offset: 50}
	sql, _ := sqlbuilder.Select("id", "name").
		From("users").
		ApplyPagination(p).
		Build()
	fmt.Println(sql)
}
Output:

SELECT id, name FROM users LIMIT 25 OFFSET 50
Example (PlaceholderRebasing)
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Select("id").
		From("users").
		Where("status = $1", "active").
		Where("age > $1", 18).
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

SELECT id FROM users WHERE status = $1 AND age > $2
[active 18]

func SelectExpr

func SelectExpr(exprs ...Expr) *SelectBuilder

SelectExpr creates a new SelectBuilder with expression columns.

sqlbuilder.SelectExpr(sqlbuilder.Raw("COUNT(*)"))

func SelectWith

func SelectWith(d Dialect, columns ...string) *SelectBuilder

SelectWith creates a new SelectBuilder with the given dialect and columns.

func (*SelectBuilder) ApplyFilters

func (s *SelectBuilder) ApplyFilters(filters []request.Filter, allowedColumns map[string]string) *SelectBuilder

ApplyFilters applies request.Filter slices as WHERE conditions. allowedColumns maps API field names to SQL column expressions. Unknown fields are silently skipped.

func (*SelectBuilder) ApplyPagination

func (s *SelectBuilder) ApplyPagination(p request.Pagination) *SelectBuilder

ApplyPagination applies request.Pagination as LIMIT and OFFSET.

func (*SelectBuilder) ApplySort

func (s *SelectBuilder) ApplySort(sorts []request.SortField, allowedColumns map[string]string) *SelectBuilder

ApplySort applies request.SortField slices as ORDER BY clauses. allowedColumns maps API field names to SQL column expressions. Unknown fields are silently skipped.

func (*SelectBuilder) Build

func (s *SelectBuilder) Build() (string, []any)

Build assembles the SQL string and arguments. Order: WITH → SELECT [DISTINCT] → FROM → JOINs → WHERE → GROUP BY → HAVING → set ops → ORDER BY → LIMIT → OFFSET → FOR

func (*SelectBuilder) Clone

func (s *SelectBuilder) Clone() *SelectBuilder

Clone creates a deep copy of the builder.

func (*SelectBuilder) Column

func (s *SelectBuilder) Column(col string) *SelectBuilder

Column adds a column to the SELECT list.

func (*SelectBuilder) ColumnExpr

func (s *SelectBuilder) ColumnExpr(expr Expr) *SelectBuilder

ColumnExpr adds an expression column to the SELECT list.

func (*SelectBuilder) Columns

func (s *SelectBuilder) Columns(cols ...string) *SelectBuilder

Columns adds multiple columns to the SELECT list.

func (*SelectBuilder) CrossJoin

func (s *SelectBuilder) CrossJoin(table string) *SelectBuilder

CrossJoin adds a CROSS JOIN.

func (*SelectBuilder) Distinct

func (s *SelectBuilder) Distinct() *SelectBuilder

Distinct adds DISTINCT to the SELECT.

func (*SelectBuilder) DistinctOn added in v0.10.0

func (s *SelectBuilder) DistinctOn(cols ...string) *SelectBuilder

DistinctOn adds DISTINCT ON (cols) to the SELECT (PostgreSQL).

func (*SelectBuilder) Except

func (s *SelectBuilder) Except(other *SelectBuilder) *SelectBuilder

Except adds an EXCEPT with another SELECT.

func (*SelectBuilder) ForShare

func (s *SelectBuilder) ForShare() *SelectBuilder

ForShare adds FOR SHARE locking.

func (*SelectBuilder) ForUpdate

func (s *SelectBuilder) ForUpdate() *SelectBuilder

ForUpdate adds FOR UPDATE locking.

func (*SelectBuilder) From

func (s *SelectBuilder) From(table string) *SelectBuilder

From sets the FROM table.

func (*SelectBuilder) FromAlias

func (s *SelectBuilder) FromAlias(table, alias string) *SelectBuilder

FromAlias sets the FROM table with an alias.

func (*SelectBuilder) FromSubquery

func (s *SelectBuilder) FromSubquery(sub *SelectBuilder, alias string) *SelectBuilder

FromSubquery sets the FROM clause to a subquery. The subquery is built at Build() time so placeholders are correctly rebased.

func (*SelectBuilder) FullJoin

func (s *SelectBuilder) FullJoin(table, on string, args ...any) *SelectBuilder

FullJoin adds a FULL JOIN.

func (*SelectBuilder) FullJoinSubquery added in v0.10.0

func (s *SelectBuilder) FullJoinSubquery(sub *SelectBuilder, alias, on string, args ...any) *SelectBuilder

FullJoinSubquery adds a FULL JOIN with a subquery.

func (*SelectBuilder) GroupBy

func (s *SelectBuilder) GroupBy(cols ...string) *SelectBuilder

GroupBy adds GROUP BY columns.

func (*SelectBuilder) GroupByExpr added in v0.10.0

func (s *SelectBuilder) GroupByExpr(expr Expr) *SelectBuilder

GroupByExpr adds a GROUP BY expression.

func (*SelectBuilder) Having

func (s *SelectBuilder) Having(sql string, args ...any) *SelectBuilder

Having adds a HAVING condition.

func (*SelectBuilder) HavingBetween added in v0.10.0

func (s *SelectBuilder) HavingBetween(col string, low, high any) *SelectBuilder

HavingBetween adds a "col BETWEEN low AND high" HAVING condition.

func (*SelectBuilder) HavingIn added in v0.10.0

func (s *SelectBuilder) HavingIn(col string, vals ...any) *SelectBuilder

HavingIn adds a "col IN (...)" HAVING condition.

func (*SelectBuilder) Intersect

func (s *SelectBuilder) Intersect(other *SelectBuilder) *SelectBuilder

Intersect adds an INTERSECT with another SELECT.

func (*SelectBuilder) Join

func (s *SelectBuilder) Join(table, on string, args ...any) *SelectBuilder

Join adds an INNER JOIN.

func (*SelectBuilder) JoinSubquery added in v0.10.0

func (s *SelectBuilder) JoinSubquery(sub *SelectBuilder, alias, on string, args ...any) *SelectBuilder

JoinSubquery adds an INNER JOIN with a subquery.

func (*SelectBuilder) LeftJoin

func (s *SelectBuilder) LeftJoin(table, on string, args ...any) *SelectBuilder

LeftJoin adds a LEFT JOIN.

func (*SelectBuilder) LeftJoinSubquery added in v0.10.0

func (s *SelectBuilder) LeftJoinSubquery(sub *SelectBuilder, alias, on string, args ...any) *SelectBuilder

LeftJoinSubquery adds a LEFT JOIN with a subquery.

func (*SelectBuilder) Limit

func (s *SelectBuilder) Limit(n int) *SelectBuilder

Limit sets the LIMIT clause.

func (*SelectBuilder) MustBuild

func (s *SelectBuilder) MustBuild() (string, []any)

MustBuild calls Build and panics if the builder is in an invalid state.

func (*SelectBuilder) NoWait

func (s *SelectBuilder) NoWait() *SelectBuilder

NoWait adds NOWAIT to the lock clause. Mutually exclusive with SkipLocked — setting one clears the other.

func (*SelectBuilder) Offset

func (s *SelectBuilder) Offset(n int64) *SelectBuilder

Offset sets the OFFSET clause.

func (*SelectBuilder) OrderBy

func (s *SelectBuilder) OrderBy(clauses ...string) *SelectBuilder

OrderBy adds ORDER BY clauses (e.g., "name ASC", "created_at DESC").

func (*SelectBuilder) OrderByAsc

func (s *SelectBuilder) OrderByAsc(cols ...string) *SelectBuilder

OrderByAsc adds ORDER BY columns with ASC direction.

func (*SelectBuilder) OrderByDesc

func (s *SelectBuilder) OrderByDesc(cols ...string) *SelectBuilder

OrderByDesc adds ORDER BY columns with DESC direction.

func (*SelectBuilder) OrderByExpr

func (s *SelectBuilder) OrderByExpr(expr Expr) *SelectBuilder

OrderByExpr adds an ORDER BY clause from an expression. Unlike OrderBy, this preserves the expression's Args so parameterized expressions (e.g., RawExpr) are correctly included in the final query.

func (*SelectBuilder) Query

func (s *SelectBuilder) Query() Query

Query builds and returns a Query struct.

func (*SelectBuilder) RightJoin

func (s *SelectBuilder) RightJoin(table, on string, args ...any) *SelectBuilder

RightJoin adds a RIGHT JOIN.

func (*SelectBuilder) RightJoinSubquery added in v0.10.0

func (s *SelectBuilder) RightJoinSubquery(sub *SelectBuilder, alias, on string, args ...any) *SelectBuilder

RightJoinSubquery adds a RIGHT JOIN with a subquery.

func (*SelectBuilder) SetDialect

func (s *SelectBuilder) SetDialect(d Dialect) *SelectBuilder

SetDialect sets the SQL dialect for placeholder conversion at Build time.

func (*SelectBuilder) SkipLocked

func (s *SelectBuilder) SkipLocked() *SelectBuilder

SkipLocked adds SKIP LOCKED to the lock clause. Mutually exclusive with NoWait — setting one clears the other.

func (*SelectBuilder) String

func (s *SelectBuilder) String() string

String returns the SQL string only, for debugging.

func (*SelectBuilder) Union

func (s *SelectBuilder) Union(other *SelectBuilder) *SelectBuilder

Union adds a UNION with another SELECT.

func (*SelectBuilder) UnionAll

func (s *SelectBuilder) UnionAll(other *SelectBuilder) *SelectBuilder

UnionAll adds a UNION ALL with another SELECT.

func (*SelectBuilder) When

func (s *SelectBuilder) When(cond bool, fn func(*SelectBuilder)) *SelectBuilder

When conditionally applies a function to the builder. If cond is true, fn is called with the builder. Always returns the builder for chaining.

func (*SelectBuilder) Where

func (s *SelectBuilder) Where(sql string, args ...any) *SelectBuilder

Where adds a WHERE condition. Placeholders use $1-relative numbering and are rebased at Build time.

func (*SelectBuilder) WhereBetween

func (s *SelectBuilder) WhereBetween(col string, low, high any) *SelectBuilder

WhereBetween adds a "col BETWEEN low AND high" condition.

func (*SelectBuilder) WhereColumn added in v0.10.0

func (s *SelectBuilder) WhereColumn(col1, op, col2 string) *SelectBuilder

WhereColumn adds a column-to-column comparison condition (e.g., "a.id = b.id").

func (*SelectBuilder) WhereEq

func (s *SelectBuilder) WhereEq(col string, val any) *SelectBuilder

WhereEq adds a "col = val" condition.

func (*SelectBuilder) WhereExists

func (s *SelectBuilder) WhereExists(sub *SelectBuilder) *SelectBuilder

WhereExists adds a "EXISTS (subquery)" condition.

func (*SelectBuilder) WhereGt

func (s *SelectBuilder) WhereGt(col string, val any) *SelectBuilder

WhereGt adds a "col > val" condition.

func (*SelectBuilder) WhereGte

func (s *SelectBuilder) WhereGte(col string, val any) *SelectBuilder

WhereGte adds a "col >= val" condition.

func (*SelectBuilder) WhereILike

func (s *SelectBuilder) WhereILike(col string, val any) *SelectBuilder

WhereILike adds a "col ILIKE val" condition (case-insensitive LIKE, PostgreSQL).

func (*SelectBuilder) WhereIn

func (s *SelectBuilder) WhereIn(col string, vals ...any) *SelectBuilder

WhereIn adds a "col IN (...)" condition.

func (*SelectBuilder) WhereInSubquery

func (s *SelectBuilder) WhereInSubquery(col string, sub *SelectBuilder) *SelectBuilder

WhereInSubquery adds a "col IN (subquery)" condition.

func (*SelectBuilder) WhereLike

func (s *SelectBuilder) WhereLike(col string, val any) *SelectBuilder

WhereLike adds a "col LIKE val" condition.

func (*SelectBuilder) WhereLt

func (s *SelectBuilder) WhereLt(col string, val any) *SelectBuilder

WhereLt adds a "col < val" condition.

func (*SelectBuilder) WhereLte

func (s *SelectBuilder) WhereLte(col string, val any) *SelectBuilder

WhereLte adds a "col <= val" condition.

func (*SelectBuilder) WhereNeq

func (s *SelectBuilder) WhereNeq(col string, val any) *SelectBuilder

WhereNeq adds a "col != val" condition.

func (*SelectBuilder) WhereNotExists

func (s *SelectBuilder) WhereNotExists(sub *SelectBuilder) *SelectBuilder

WhereNotExists adds a "NOT EXISTS (subquery)" condition.

func (*SelectBuilder) WhereNotIn

func (s *SelectBuilder) WhereNotIn(col string, vals ...any) *SelectBuilder

WhereNotIn adds a "col NOT IN (...)" condition.

func (*SelectBuilder) WhereNotInSubquery

func (s *SelectBuilder) WhereNotInSubquery(col string, sub *SelectBuilder) *SelectBuilder

WhereNotInSubquery adds a "col NOT IN (subquery)" condition.

func (*SelectBuilder) WhereNotNull

func (s *SelectBuilder) WhereNotNull(col string) *SelectBuilder

WhereNotNull adds a "col IS NOT NULL" condition.

func (*SelectBuilder) WhereNull

func (s *SelectBuilder) WhereNull(col string) *SelectBuilder

WhereNull adds a "col IS NULL" condition.

func (*SelectBuilder) WhereOr

func (s *SelectBuilder) WhereOr(conditions ...condition) *SelectBuilder

WhereOr adds a group of OR conditions wrapped in parentheses.

.WhereOr(
    sqlbuilder.Or("status = $1", "active"),
    sqlbuilder.Or("role = $1", "admin"),
)
// WHERE ... AND (status = $1 OR role = $2)

func (*SelectBuilder) With

func (s *SelectBuilder) With(name string, q Query) *SelectBuilder

With adds a CTE (Common Table Expression).

func (*SelectBuilder) WithRecursive

func (s *SelectBuilder) WithRecursive(name string, q Query) *SelectBuilder

WithRecursive adds a recursive CTE.

func (*SelectBuilder) WithRecursiveSelect

func (s *SelectBuilder) WithRecursiveSelect(name string, sub *SelectBuilder) *SelectBuilder

WithRecursiveSelect adds a recursive CTE from a SelectBuilder.

func (*SelectBuilder) WithSelect

func (s *SelectBuilder) WithSelect(name string, sub *SelectBuilder) *SelectBuilder

WithSelect adds a CTE from a SelectBuilder. This is dialect-safe: the subquery is always built with Postgres placeholders internally, so placeholder rebasing works correctly regardless of the sub's dialect.

type UpdateBuilder

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

UpdateBuilder builds UPDATE queries.

func Update

func Update(table string) *UpdateBuilder

Update creates a new UpdateBuilder for the given table.

sqlbuilder.Update("users").Set("name", "Bob").Where("id = $1", 1)
Example
package main

import (
	"fmt"

	"github.com/KARTIKrocks/apikit/sqlbuilder"
)

func main() {
	sql, args := sqlbuilder.Update("users").
		Set("name", "Bob").
		SetExpr("updated_at", sqlbuilder.Raw("NOW()")).
		Where("id = $1", 1).
		Build()
	fmt.Println(sql)
	fmt.Println(args)
}
Output:

UPDATE users SET name = $1, updated_at = NOW() WHERE id = $2
[Bob 1]

func UpdateWith

func UpdateWith(d Dialect, table string) *UpdateBuilder

UpdateWith creates a new UpdateBuilder with the given dialect and table.

func (*UpdateBuilder) Build

func (b *UpdateBuilder) Build() (string, []any)

Build assembles the SQL string and arguments.

func (*UpdateBuilder) Clone

func (b *UpdateBuilder) Clone() *UpdateBuilder

Clone creates a deep copy of the builder.

func (*UpdateBuilder) Decrement

func (b *UpdateBuilder) Decrement(col string, n any) *UpdateBuilder

Decrement adds a "col = col - n" assignment.

func (*UpdateBuilder) From

func (b *UpdateBuilder) From(tables ...string) *UpdateBuilder

From adds tables for multi-table UPDATE (PostgreSQL FROM clause).

func (*UpdateBuilder) Increment

func (b *UpdateBuilder) Increment(col string, n any) *UpdateBuilder

Increment adds a "col = col + n" assignment.

func (*UpdateBuilder) MustBuild

func (b *UpdateBuilder) MustBuild() (string, []any)

MustBuild calls Build and panics if the builder is in an invalid state.

func (*UpdateBuilder) Query

func (b *UpdateBuilder) Query() Query

Query builds and returns a Query struct.

func (*UpdateBuilder) Returning

func (b *UpdateBuilder) Returning(cols ...string) *UpdateBuilder

Returning adds a RETURNING clause.

func (*UpdateBuilder) ReturningExpr added in v0.10.0

func (b *UpdateBuilder) ReturningExpr(exprs ...Expr) *UpdateBuilder

ReturningExpr adds expression columns to the RETURNING clause.

func (*UpdateBuilder) Set

func (b *UpdateBuilder) Set(col string, val any) *UpdateBuilder

Set adds a column = value assignment.

func (*UpdateBuilder) SetDialect

func (b *UpdateBuilder) SetDialect(d Dialect) *UpdateBuilder

SetDialect sets the SQL dialect for placeholder conversion at Build time.

func (*UpdateBuilder) SetExpr

func (b *UpdateBuilder) SetExpr(col string, expr Expr) *UpdateBuilder

SetExpr adds a column = expression assignment.

.SetExpr("updated_at", sqlbuilder.Raw("NOW()"))

func (*UpdateBuilder) SetMap

func (b *UpdateBuilder) SetMap(m map[string]any) *UpdateBuilder

SetMap adds multiple column = value assignments from a map. Keys are sorted for deterministic output.

func (*UpdateBuilder) String

func (b *UpdateBuilder) String() string

String returns the SQL string only, for debugging.

func (*UpdateBuilder) When

func (b *UpdateBuilder) When(cond bool, fn func(*UpdateBuilder)) *UpdateBuilder

When conditionally applies a function to the builder.

func (*UpdateBuilder) Where

func (b *UpdateBuilder) Where(sql string, args ...any) *UpdateBuilder

Where adds a WHERE condition.

func (*UpdateBuilder) WhereBetween

func (b *UpdateBuilder) WhereBetween(col string, low, high any) *UpdateBuilder

WhereBetween adds a "col BETWEEN low AND high" condition.

func (*UpdateBuilder) WhereColumn added in v0.10.0

func (b *UpdateBuilder) WhereColumn(col1, op, col2 string) *UpdateBuilder

WhereColumn adds a column-to-column comparison condition (e.g., "a.id = b.id").

func (*UpdateBuilder) WhereEq

func (b *UpdateBuilder) WhereEq(col string, val any) *UpdateBuilder

WhereEq adds a "col = val" condition.

func (*UpdateBuilder) WhereExists

func (b *UpdateBuilder) WhereExists(sub *SelectBuilder) *UpdateBuilder

WhereExists adds a "EXISTS (subquery)" condition.

func (*UpdateBuilder) WhereGt

func (b *UpdateBuilder) WhereGt(col string, val any) *UpdateBuilder

WhereGt adds a "col > val" condition.

func (*UpdateBuilder) WhereGte

func (b *UpdateBuilder) WhereGte(col string, val any) *UpdateBuilder

WhereGte adds a "col >= val" condition.

func (*UpdateBuilder) WhereILike

func (b *UpdateBuilder) WhereILike(col string, val any) *UpdateBuilder

WhereILike adds a "col ILIKE val" condition (case-insensitive LIKE, PostgreSQL).

func (*UpdateBuilder) WhereIn

func (b *UpdateBuilder) WhereIn(col string, vals ...any) *UpdateBuilder

WhereIn adds a "col IN (...)" condition.

func (*UpdateBuilder) WhereInSubquery

func (b *UpdateBuilder) WhereInSubquery(col string, sub *SelectBuilder) *UpdateBuilder

WhereInSubquery adds a "col IN (subquery)" condition.

func (*UpdateBuilder) WhereLike

func (b *UpdateBuilder) WhereLike(col string, val any) *UpdateBuilder

WhereLike adds a "col LIKE val" condition.

func (*UpdateBuilder) WhereLt

func (b *UpdateBuilder) WhereLt(col string, val any) *UpdateBuilder

WhereLt adds a "col < val" condition.

func (*UpdateBuilder) WhereLte

func (b *UpdateBuilder) WhereLte(col string, val any) *UpdateBuilder

WhereLte adds a "col <= val" condition.

func (*UpdateBuilder) WhereNeq

func (b *UpdateBuilder) WhereNeq(col string, val any) *UpdateBuilder

WhereNeq adds a "col != val" condition.

func (*UpdateBuilder) WhereNotExists

func (b *UpdateBuilder) WhereNotExists(sub *SelectBuilder) *UpdateBuilder

WhereNotExists adds a "NOT EXISTS (subquery)" condition.

func (*UpdateBuilder) WhereNotIn

func (b *UpdateBuilder) WhereNotIn(col string, vals ...any) *UpdateBuilder

WhereNotIn adds a "col NOT IN (...)" condition.

func (*UpdateBuilder) WhereNotInSubquery

func (b *UpdateBuilder) WhereNotInSubquery(col string, sub *SelectBuilder) *UpdateBuilder

WhereNotInSubquery adds a "col NOT IN (subquery)" condition.

func (*UpdateBuilder) WhereNotNull

func (b *UpdateBuilder) WhereNotNull(col string) *UpdateBuilder

WhereNotNull adds a "col IS NOT NULL" condition.

func (*UpdateBuilder) WhereNull

func (b *UpdateBuilder) WhereNull(col string) *UpdateBuilder

WhereNull adds a "col IS NULL" condition.

func (*UpdateBuilder) WhereOr

func (b *UpdateBuilder) WhereOr(conditions ...condition) *UpdateBuilder

WhereOr adds a group of OR conditions wrapped in parentheses.

func (*UpdateBuilder) With

func (b *UpdateBuilder) With(name string, q Query) *UpdateBuilder

With adds a CTE (Common Table Expression).

func (*UpdateBuilder) WithSelect

func (b *UpdateBuilder) WithSelect(name string, sub *SelectBuilder) *UpdateBuilder

WithSelect adds a CTE from a SelectBuilder. This is dialect-safe: the subquery is always built with Postgres placeholders internally.

type WindowBuilder added in v0.10.0

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

WindowBuilder builds a window specification for OVER clauses.

func Window added in v0.10.0

func Window() *WindowBuilder

Window creates a new WindowBuilder.

func (*WindowBuilder) Build added in v0.10.0

func (w *WindowBuilder) Build() string

Build renders the window specification as "(PARTITION BY ... ORDER BY ...)".

func (*WindowBuilder) OrderBy added in v0.10.0

func (w *WindowBuilder) OrderBy(clauses ...string) *WindowBuilder

OrderBy sets the ORDER BY clauses.

func (*WindowBuilder) PartitionBy added in v0.10.0

func (w *WindowBuilder) PartitionBy(cols ...string) *WindowBuilder

PartitionBy sets the PARTITION BY columns.

Jump to

Keyboard shortcuts

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