query

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package query provides a fluent, driver-aware SQL builder. It is used by the ORM but is fully usable on its own — it returns *sql.Rows where the caller wants raw access.

Chaining methods (Where, OrderBy, Limit, ...) mutate and return the receiver, so a Builder is single-use: build it, execute once, discard. The terminal aggregate helpers (Count, Exists, Sum, ...) are the exception — they operate on an internal clone so they never disturb the receiver's clause state and may be called mid-chain.

Index

Constants

View Source
const (
	OpEq         = "="
	OpNe         = "<>"
	OpLt         = "<"
	OpLte        = "<="
	OpGt         = ">"
	OpGte        = ">="
	OpLike       = "like"
	OpILike      = "ilike"
	OpIn         = "in"
	OpNotIn      = "not in"
	OpBetween    = "between"
	OpNotBetween = "not between"
	OpIsNull     = "is null"
	OpNotNull    = "is not null"
)

Op enumerates supported comparison operators.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

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

Builder builds SQL statements.

func New

func New(conn *database.Connection, table string) *Builder

New returns a fresh Builder for the given connection/table.

func (*Builder) Avg

func (b *Builder) Avg(ctx context.Context, col string) (float64, error)

Avg returns the average of a column.

func (*Builder) Clone added in v0.20.0

func (b *Builder) Clone() *Builder

Clone returns a deep copy of the builder. Callers that want to branch a query (e.g. run First() and then Get() off the same base) use this to avoid the receiver's single-use mutation semantics leaking across calls.

func (*Builder) Connection

func (b *Builder) Connection() *database.Connection

Connection returns the underlying connection.

func (*Builder) Count

func (b *Builder) Count(ctx context.Context) (int64, error)

Count returns the COUNT(*) for the current WHERE/JOIN state. When the query has a GROUP BY, a plain COUNT(*) would return only the first group's count; in that case the grouped query is wrapped in a subquery so the result is the number of groups.

func (*Builder) Delete

func (b *Builder) Delete(ctx context.Context) (int64, error)

Delete deletes rows matching the WHERE clauses. Returns rows affected.

func (*Builder) Distinct

func (b *Builder) Distinct() *Builder

Distinct toggles DISTINCT.

func (*Builder) Exists

func (b *Builder) Exists(ctx context.Context) (bool, error)

Exists returns true if at least one row matches. It operates on a clone so the receiver's state is not mutated.

func (*Builder) From

func (b *Builder) From(table string) *Builder

From sets the table.

func (*Builder) Get

func (b *Builder) Get(ctx context.Context) (*sql.Rows, error)

Get executes the SELECT and returns the rows.

func (*Builder) GroupBy

func (b *Builder) GroupBy(cols ...string) *Builder

GroupBy adds GROUP BY columns.

func (*Builder) Having

func (b *Builder) Having(col, op string, value any) *Builder

Having adds an AND HAVING. The operator is whitelisted (see normalizeOp); an unsupported operator panics rather than being concatenated into the SQL.

func (*Builder) Insert

func (b *Builder) Insert(ctx context.Context, values map[string]any) (sql.Result, error)

Insert inserts a single row. Returns the *sql.Result.

func (*Builder) InsertBatch

func (b *Builder) InsertBatch(ctx context.Context, rows []map[string]any) (sql.Result, error)

InsertBatch performs a multi-row insert.

func (*Builder) InsertGetID

func (b *Builder) InsertGetID(ctx context.Context, values map[string]any, pk string) (int64, error)

InsertGetID inserts and returns the auto-incremented ID. For Postgres this appends RETURNING <pk>.

func (*Builder) Join

func (b *Builder) Join(table, on string, args ...any) *Builder

Join adds an INNER JOIN.

func (*Builder) Latest

func (b *Builder) Latest(col ...string) *Builder

Latest orders by the column descending. Default column is "created_at".

func (*Builder) LeftJoin

func (b *Builder) LeftJoin(table, on string, args ...any) *Builder

LeftJoin adds a LEFT JOIN.

func (*Builder) Limit

func (b *Builder) Limit(n int) *Builder

Limit sets the row limit.

func (*Builder) LockForUpdate

func (b *Builder) LockForUpdate() *Builder

LockForUpdate appends FOR UPDATE on supported dialects. SQLite has no row locking syntax, so the clause is a no-op there.

func (*Builder) Max

func (b *Builder) Max(ctx context.Context, col string) (float64, error)

Max returns the maximum value.

func (*Builder) Min

func (b *Builder) Min(ctx context.Context, col string) (float64, error)

Min returns the minimum value.

func (*Builder) Offset

func (b *Builder) Offset(n int) *Builder

Offset sets the row offset.

func (*Builder) Oldest

func (b *Builder) Oldest(col ...string) *Builder

Oldest orders by the column ascending. Default column is "created_at".

func (*Builder) OrWhere

func (b *Builder) OrWhere(args ...any) *Builder

OrWhere appends an OR condition.

func (*Builder) OrderBy

func (b *Builder) OrderBy(col, dir string) *Builder

OrderBy adds an ORDER BY. The direction is whitelisted to ASC/DESC; any other value (e.g. an injection attempt) panics rather than being emitted into the SQL.

func (*Builder) OrderByRaw

func (b *Builder) OrderByRaw(expr string) *Builder

OrderByRaw adds a raw ORDER BY clause.

func (*Builder) Select

func (b *Builder) Select(cols ...string) *Builder

Select replaces the column list.

func (*Builder) SetExecutor

func (b *Builder) SetExecutor(e database.Executor) *Builder

SetExecutor lets a Tx wrap the builder so it runs inside a transaction.

func (*Builder) SharedLock

func (b *Builder) SharedLock() *Builder

SharedLock appends FOR SHARE on supported dialects. SQLite has no row locking syntax, so the clause is a no-op there.

func (*Builder) Sum

func (b *Builder) Sum(ctx context.Context, col string) (float64, error)

Sum returns the sum of a column.

func (*Builder) ToSQL

func (b *Builder) ToSQL() (string, []any, error)

ToSQL compiles the builder into a SELECT statement and its bound args.

func (*Builder) Truncate

func (b *Builder) Truncate(ctx context.Context) error

Truncate empties the table.

func (*Builder) Update

func (b *Builder) Update(ctx context.Context, values map[string]any) (int64, error)

Update performs an UPDATE with the current WHERE clauses.

func (*Builder) Where

func (b *Builder) Where(args ...any) *Builder

Where appends an AND condition.

Where("name", "=", "Ada") | Where("name", "Ada") | Where(func(q *Builder) { ... })

func (*Builder) WhereBetween

func (b *Builder) WhereBetween(col string, lo, hi any) *Builder

WhereBetween appends a BETWEEN constraint.

func (*Builder) WhereIn

func (b *Builder) WhereIn(col string, values any) *Builder

WhereIn appends an IN constraint.

func (*Builder) WhereNotIn

func (b *Builder) WhereNotIn(col string, values any) *Builder

WhereNotIn appends a NOT IN constraint.

func (*Builder) WhereNotNull

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

WhereNotNull appends an IS NOT NULL constraint.

func (*Builder) WhereNull

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

WhereNull appends an IS NULL constraint.

func (*Builder) WhereRaw

func (b *Builder) WhereRaw(expr string, args ...any) *Builder

WhereRaw appends a raw expression.

func (*Builder) WrapWheres added in v0.27.0

func (b *Builder) WrapWheres() *Builder

WrapWheres groups the current WHERE conditions in parentheses when they contain an OR, so conditions appended afterwards (scopes, cursors, key lookups) apply to the whole filter instead of binding only to the last OR branch. Without OR the conditions are left untouched.

Jump to

Keyboard shortcuts

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