Documentation
¶
Overview ¶
Package tsq provides a typed SQL query builder and execution helpers.
Index ¶
- Constants
- func ChunkedDelete[T Table](ctx context.Context, tx SQLExecutor, items []T, options ...*ChunkedOptions) error
- func ChunkedDeleteByPKs[O Table, T any](ctx context.Context, tx SQLExecutor, pkField TypedColumn[O, T], pks []T, ...) error
- func ChunkedInsert[T Table](ctx context.Context, tx SQLExecutor, items []T, ...) error
- func ChunkedUpdate[T Table](ctx context.Context, tx SQLExecutor, items []T, options ...*ChunkedOptions) error
- func Delete[T Table](ctx context.Context, tx SQLExecutor, item T) error
- func Insert[T Table](ctx context.Context, tx SQLExecutor, item T) error
- func IsCommonTransactionRetryableError(err error) bool
- func IsOptimisticLockError(err error) bool
- func IsRetryableNetworkError(err error) bool
- func IsRetryableTransactionConflictError(err error) bool
- func Update[T Table](ctx context.Context, tx SQLExecutor, item T) error
- func WithTx1[T any](r *Runtime, ctx context.Context, options *TxOptions, ...) (T, error)
- func WithTx2[T1, T2 any](r *Runtime, ctx context.Context, options *TxOptions, ...) (T1, T2, error)
- type BoundColumn
- type CaseStage
- type ChunkedInsertOptions
- type ChunkedOptions
- type Column
- type CompoundStage
- type Condition
- type ErrAmbiguousSortField
- type ErrIndexMissing
- type ErrOptimisticLockConflict
- type ErrOrderCountMismatch
- type ErrTableMissing
- type ErrUnknownSortField
- type Expression
- type FilteredStage
- type FromStage
- type GroupedStage
- type HavingStage
- type IndexInitMode
- type LockedStage
- type Logger
- type Order
- type OrderBy
- type Owner
- type PageRequest
- type PageResponse
- type Query
- func (q *Query[O]) Count(ctx context.Context, tx SQLExecutor, args ...any) (int, error)
- func (q *Query[O]) Count64(ctx context.Context, tx SQLExecutor, args ...any) (int64, error)
- func (q *Query[O]) CountSQL() string
- func (q *Query[O]) Exists(ctx context.Context, tx SQLExecutor, args ...any) (bool, error)
- func (q *Query[O]) Get(ctx context.Context, tx SQLExecutor, args ...any) (*O, error)
- func (q *Query[O]) GetOrErr(ctx context.Context, tx SQLExecutor, args ...any) (*O, error)
- func (q *Query[O]) KeywordCountSQL() string
- func (q *Query[O]) KeywordListSQL() string
- func (q *Query[O]) List(ctx context.Context, tx SQLExecutor, args ...any) ([]*O, error)
- func (q *Query[O]) ListSQL() string
- func (q *Query[O]) Load(ctx context.Context, tx SQLExecutor, holder *O, args ...any) error
- func (q *Query[O]) Page(ctx context.Context, tx SQLExecutor, page *PageRequest, args ...any) (*PageResponse[O], error)
- func (q *Query[O]) QueryFloat(ctx context.Context, tx SQLExecutor, args ...any) (float64, error)
- func (q *Query[O]) QueryInt(ctx context.Context, tx SQLExecutor, args ...any) (int64, error)
- func (q *Query[O]) QueryString(ctx context.Context, tx SQLExecutor, args ...any) (string, error)
- type QueryStage
- type RHS
- type RegistrationError
- type RegistrationErrorType
- type Result
- type ResultColumn
- type Runtime
- func (r *Runtime) DB() *sql.DB
- func (r *Runtime) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (r *Runtime) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (r *Runtime) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (r *Runtime) SQLDialect() tsqdialect.Dialect
- func (r *Runtime) ValidateIdentifiersForDialect() error
- func (r *Runtime) WithTx(ctx context.Context, options *TxOptions, ...) error
- type RuntimeOptions
- type SQLColumn
- type SQLExecutor
- type SchemaPolicy
- type SearchColumn
- type SearchStage
- type SelectStage
- type Subquery
- type Table
- type TableColumn
- type TableIndex
- type TableRegistration
- type Tracer
- type TxOptions
- type TxRetryConfig
- type TxRetryPredicate
- type TypedColumn
- type ValueColumn
- type WhereStage
Constants ¶
const ( // IndexInitSkip is deprecated; use SchemaPolicyManual. IndexInitSkip = SchemaPolicyManual // IndexInitValidate is deprecated; use SchemaPolicyValidate. IndexInitValidate = SchemaPolicyValidate // IndexInitUpsert is deprecated; use SchemaPolicyCreateMissing. IndexInitUpsert = SchemaPolicyCreateMissing )
Variables ¶
This section is empty.
Functions ¶
func ChunkedDelete ¶
func ChunkedDelete[T Table]( ctx context.Context, tx SQLExecutor, items []T, options ...*ChunkedOptions, ) error
ChunkedDelete deletes items in chunks using the provided executor.
Transaction boundaries are intentionally caller-controlled. Passing a plain *sql.DB or non-transactional executor allows partial progress across chunks; passing a *sql.Tx makes the whole chunked operation participate in that transaction. TSQ does not open an implicit outer transaction for this helper.
func ChunkedDeleteByPKs ¶ added in v4.1.14
func ChunkedDeleteByPKs[O Table, T any]( ctx context.Context, tx SQLExecutor, pkField TypedColumn[O, T], pks []T, options ...*ChunkedOptions, ) error
ChunkedDeleteByPKs deletes rows by primary-key values in chunks.
Transaction boundaries are intentionally caller-controlled. Passing a plain *sql.DB or non-transactional executor allows partial progress across chunks; passing a *sql.Tx makes the whole chunked operation participate in that transaction. TSQ does not open an implicit outer transaction for this helper.
func ChunkedInsert ¶
func ChunkedInsert[T Table]( ctx context.Context, tx SQLExecutor, items []T, options ...*ChunkedInsertOptions, ) error
ChunkedInsert inserts items in chunks using the provided executor.
Transaction boundaries are intentionally caller-controlled. Passing a plain *sql.DB or non-transactional executor allows partial progress across chunks; passing a *sql.Tx makes the whole chunked operation participate in that transaction. TSQ does not open an implicit outer transaction for this helper.
func ChunkedUpdate ¶
func ChunkedUpdate[T Table]( ctx context.Context, tx SQLExecutor, items []T, options ...*ChunkedOptions, ) error
ChunkedUpdate updates items in chunks using the provided executor.
Transaction boundaries are intentionally caller-controlled. Passing a plain *sql.DB or non-transactional executor allows partial progress across chunks; passing a *sql.Tx makes the whole chunked operation participate in that transaction. TSQ does not open an implicit outer transaction for this helper.
func Delete ¶
func Delete[T Table]( ctx context.Context, tx SQLExecutor, item T, ) error
Delete deletes item using the table metadata on T.
func Insert ¶
func Insert[T Table]( ctx context.Context, tx SQLExecutor, item T, ) error
Insert inserts item using the table metadata on T.
func IsCommonTransactionRetryableError ¶ added in v4.1.9
IsCommonTransactionRetryableError reports whether err matches any built-in transaction retry helper.
func IsOptimisticLockError ¶ added in v4.1.9
IsOptimisticLockError reports whether err is an ErrOptimisticLockConflict.
func IsRetryableNetworkError ¶ added in v4.1.9
IsRetryableNetworkError reports whether err looks like a transient connection failure.
func IsRetryableTransactionConflictError ¶ added in v4.1.9
IsRetryableTransactionConflictError reports whether err looks like a transient database concurrency failure.
func Update ¶
func Update[T Table]( ctx context.Context, tx SQLExecutor, item T, ) error
Update updates item using the table metadata on T.
func WithTx1 ¶ added in v4.1.9
func WithTx1[T any]( r *Runtime, ctx context.Context, options *TxOptions, fn func(context.Context, SQLExecutor) (T, error), ) (T, error)
WithTx1 runs fn in a transaction and returns one result value plus an error. The runtime is an explicit parameter because Go does not support generic methods on Runtime.
func WithTx2 ¶ added in v4.1.9
func WithTx2[T1, T2 any]( r *Runtime, ctx context.Context, options *TxOptions, fn func(context.Context, SQLExecutor) (T1, T2, error), ) (T1, T2, error)
WithTx2 runs fn in a transaction and returns two result values plus an error. The runtime is an explicit parameter because Go does not support generic methods on Runtime.
Types ¶
type BoundColumn ¶
BoundColumn is a selectable expression bound to a specific owner type.
type CaseStage ¶ added in v4.1.1
type CaseStage[T any] interface { When(cond Condition, result any) CaseStage[T] Else(result any) CaseStage[T] End() ValueColumn[T] }
CaseStage builds a searched CASE expression.
type ChunkedInsertOptions ¶
type ChunkedInsertOptions struct {
ChunkSize int // 每块处理的数量,默认 1000
IgnoreErrors bool // 是否忽略重复键插入错误并继续处理后续数据
}
ChunkedInsertOptions 分块插入配置选项。
func DefaultChunkedInsertOptions ¶
func DefaultChunkedInsertOptions() *ChunkedInsertOptions
DefaultChunkedInsertOptions 返回默认的分块插入配置。
type ChunkedOptions ¶
type ChunkedOptions struct {
ChunkSize int // 每块处理的数量,默认 1000
}
ChunkedOptions 分块执行通用配置选项。
func DefaultChunkedOptions ¶
func DefaultChunkedOptions() *ChunkedOptions
DefaultChunkedOptions 返回默认的分块执行配置。
type Column ¶ added in v4.1.0
type Column[O Owner, T any] interface { // TypedColumn exposes the common SQL expression metadata and typed value marker. TypedColumn[O, T] // RHS lets typed expressions flow into comparison predicates on another column. RHS[T] // SearchColumn marks the expression as usable in keyword search expansion. SearchColumn // WithTable returns a copy of the column rebound to a different table source. WithTable(table Table) Column[O, T] // As returns a copy of the column that targets an aliased table reference. As(alias string) Column[O, T] // IsNull checks whether the column value is NULL. IsNull() Condition // IsNotNull checks whether the column value is not NULL. IsNotNull() Condition // EQ compares the column to rhs with =. EQ(rhs RHS[T]) Condition // NE compares the column to rhs with <>. NE(rhs RHS[T]) Condition // GT compares the column to rhs with >. GT(rhs RHS[T]) Condition // GTE compares the column to rhs with >=. GTE(rhs RHS[T]) Condition // LT compares the column to rhs with <. LT(rhs RHS[T]) Condition // LTE compares the column to rhs with <=. LTE(rhs RHS[T]) Condition // Like compares the column to rhs with LIKE. Like(rhs RHS[T]) Condition // NLike compares the column to rhs with NOT LIKE. NLike(rhs RHS[T]) Condition // Between compares the column to an inclusive RHS range. Between(start, end RHS[T]) Condition // NBetween compares the column to values outside an inclusive RHS range. NBetween(start, end RHS[T]) Condition // In compares the column to a typed membership subquery with IN. In(rhs Subquery[T]) Condition // NIn compares the column to a typed membership subquery with NOT IN. NIn(rhs Subquery[T]) Condition // EQVal compares the column to arg with =. EQVal(arg T) Condition // NEVal compares the column to arg with <>. NEVal(arg T) Condition // GTVal compares the column to arg with >. GTVal(arg T) Condition // GTEVal compares the column to arg with >=. GTEVal(arg T) Condition // LTVal compares the column to arg with <. LTVal(arg T) Condition // LTEVal compares the column to arg with <=. LTEVal(arg T) Condition // LikeVal compares the column to arg with LIKE. LikeVal(arg T) Condition // NLikeVal compares the column to arg with NOT LIKE. NLikeVal(arg T) Condition // BetweenVal compares the column to an inclusive literal range. BetweenVal(start, end T) Condition // NBetweenVal compares the column to values outside an inclusive literal range. NBetweenVal(start, end T) Condition // InVal compares the column to an explicit list of bound values. InVal(args ...T) Condition // NInVal compares the column to a negated list of bound values. NInVal(args ...T) Condition // StartsWithVal compares the column to a bound prefix pattern. StartsWithVal(str string) Condition // NStartsWithVal compares the column to a negated bound prefix pattern. NStartsWithVal(str string) Condition // EndsWithVal compares the column to a bound suffix pattern. EndsWithVal(str string) Condition // NEndsWithVal compares the column to a negated bound suffix pattern. NEndsWithVal(str string) Condition // ContainsVal compares the column to a bound contains pattern. ContainsVal(str string) Condition // NContainsVal compares the column to a negated bound contains pattern. NContainsVal(str string) Condition // EQVar compares the column to a runtime-bound value with =. EQVar() Condition // NEVar compares the column to a runtime-bound value with <>. NEVar() Condition // GTVar compares the column to a runtime-bound value with >. GTVar() Condition // GTEVar compares the column to a runtime-bound value with >=. GTEVar() Condition // LTVar compares the column to a runtime-bound value with <. LTVar() Condition // LTEVar compares the column to a runtime-bound value with <=. LTEVar() Condition // LikeVar compares the column to a runtime-bound pattern with LIKE. LikeVar() Condition // NLikeVar compares the column to a runtime-bound pattern with NOT LIKE. NLikeVar() Condition // BetweenVar compares the column to two runtime-bound values with BETWEEN. BetweenVar() Condition // NBetweenVar compares the column to two runtime-bound values with NOT BETWEEN. NBetweenVar() Condition // InVar binds a slice at execution time for IN predicates. InVar() Condition // NInVar binds a slice at execution time for NOT IN predicates. NInVar() Condition // StartsWithVar compares the column to a runtime-bound prefix pattern. StartsWithVar() Condition // NStartsWithVar compares the column to a negated runtime-bound prefix pattern. NStartsWithVar() Condition // EndsWithVar compares the column to a runtime-bound suffix pattern. EndsWithVar() Condition // NEndsWithVar compares the column to a negated runtime-bound suffix pattern. NEndsWithVar() Condition // ContainsVar compares the column to a runtime-bound contains pattern. ContainsVar() Condition // NContainsVar compares the column to a negated runtime-bound contains pattern. NContainsVar() Condition // ExistsSub returns an EXISTS predicate for the supplied subquery. ExistsSub(sq rawSubquery) Condition // NExistsSub returns a NOT EXISTS predicate for the supplied subquery. NExistsSub(sq rawSubquery) Condition // Unique returns a deferred portability error because UNIQUE subquery predicates are not supported. Unique(sq rawSubquery) Condition // NUnique returns a deferred portability error because NOT UNIQUE subquery predicates are not supported. NUnique(sq rawSubquery) Condition // Pred formats a custom predicate template around the receiver column. // The format must contain one %s placeholder for the receiver column plus // one %s placeholder for each extra argument. // // Extra arguments may be: // - another SQL expression such as a Column // - an Expression such as Bind(...) // - a plain Go value, which TSQ turns into a bound parameter // // Raw subqueries are rejected; use typed RHS values such as a Column or // typed Subquery via EQ/NE/GT/GTE/LT/LTE/Like/Between, or use In/ExistsSub // style helpers instead. // // Example: // // users.Name.Pred("LOWER(%s) = LOWER(%s)", tsq.Bind("alice")) Pred(format string, args ...any) Condition // Expr formats the receiver column into a custom SQL expression template. // The format must contain exactly one %s placeholder, which receives the // receiver column expression. // // This is an escape hatch for expression wrappers that TSQ does not model // directly, such as CAST(%s AS TEXT) or (%s COLLATE NOCASE). // // Example: // // users.Name.Expr("LOWER(%s)") Expr(format string) Column[O, T] // Exprf formats the receiver column plus extra SQL expressions into a custom // SQL expression template. The first %s placeholder receives the receiver // column; each additional %s placeholder receives the corresponding argument // expression. // // Extra arguments may be Columns, Expressions, or plain Go values. // // Example: // // users.Name.Exprf("COALESCE(%s, %s)", orgs.Name) Exprf(format string, args ...any) Column[O, T] // Count wraps the column in COUNT and marks it as an aggregate expression. Count() Column[O, int64] // Sum wraps the column in SUM and marks it as an aggregate expression. Sum() Column[O, T] // Avg wraps the column in AVG and marks it as an aggregate expression. Avg() Column[O, float64] // Max wraps the column in MAX and marks it as an aggregate expression. Max() Column[O, T] // Min wraps the column in MIN and marks it as an aggregate expression. Min() Column[O, T] // Distinct wraps the column in DISTINCT and marks it as a distinct expression. Distinct() Column[O, T] // Upper wraps the column in UPPER. Upper() Column[O, T] // Lower wraps the column in LOWER. Lower() Column[O, T] // Substring wraps the column in SUBSTRING using start and length. Substring(start, length int) Column[O, T] // Length wraps the column in LENGTH. Length() Column[O, T] // Trim wraps the column in TRIM. Trim() Column[O, T] // Concat appends str to the column expression with CONCAT. Concat(str string) Column[O, T] // Now returns a NOW expression. Now() Column[O, T] // Date wraps the column in DATE. Date() Column[O, T] // Year wraps the column in YEAR. Year() Column[O, T] // Month wraps the column in MONTH. Month() Column[O, T] // Day wraps the column in DAY. Day() Column[O, T] // Round wraps the column in ROUND with precision. Round(precision int) Column[O, T] // Ceil wraps the column in CEIL. Ceil() Column[O, T] // Floor wraps the column in FLOOR. Floor() Column[O, T] // Abs wraps the column in ABS. Abs() Column[O, T] // Coalesce wraps the column in COALESCE with a fallback value. Coalesce(value any) Column[O, T] // NullIf wraps the column in NULLIF with value. NullIf(value any) Column[O, T] // Asc creates an ascending ORDER BY clause for this column. Asc() OrderBy // Desc creates a descending ORDER BY clause for this column. Desc() OrderBy }
Column is the user-facing typed SQL expression API that preserves fluent chaining without exposing the concrete implementation.
type CompoundStage ¶ added in v4.1.1
type CompoundStage[O Owner] interface { QueryStage[O] ForUpdate() LockedStage[O] Union(other QueryStage[O]) CompoundStage[O] UnionAll(other QueryStage[O]) CompoundStage[O] Intersect(other QueryStage[O]) CompoundStage[O] IntersectAll(other QueryStage[O]) CompoundStage[O] Except(other QueryStage[O]) CompoundStage[O] ExceptAll(other QueryStage[O]) CompoundStage[O] }
CompoundStage is the query state after one or more set operations.
type Condition ¶
type Condition interface {
Tables() map[string]Table // Tables returns the tables referenced by the predicate.
Clause() string // Clause returns the predicate SQL in canonical form.
Args() []any // Args returns the bind arguments captured by the predicate.
}
Condition is the runtime view of a rendered SQL predicate.
type ErrAmbiguousSortField ¶
type ErrAmbiguousSortField struct {
// contains filtered or unexported fields
}
ErrAmbiguousSortField reports that a sort field matches multiple selected columns.
func (*ErrAmbiguousSortField) Error ¶
func (e *ErrAmbiguousSortField) Error() string
Error implements error.
func (*ErrAmbiguousSortField) Is ¶
func (e *ErrAmbiguousSortField) Is(target error) bool
Is reports whether target is an *ErrAmbiguousSortField for the same field. An *ErrAmbiguousSortField with an empty field matches any ErrAmbiguousSortField, enabling both type-level and value-level errors.Is checks.
type ErrIndexMissing ¶
type ErrIndexMissing struct {
Table string // Table is the table that should contain the index.
Name string // Name is the expected index name.
Fields []string // Fields is the expected indexed column order.
Unique bool // Unique reports whether the missing index should be unique.
}
ErrIndexMissing reports that an expected index was not found.
type ErrOptimisticLockConflict ¶ added in v4.0.2
type ErrOptimisticLockConflict struct {
// contains filtered or unexported fields
}
ErrOptimisticLockConflict reports that a version-guarded mutation matched fewer rows than expected.
func (*ErrOptimisticLockConflict) Error ¶ added in v4.0.2
func (e *ErrOptimisticLockConflict) Error() string
Error implements error.
func (*ErrOptimisticLockConflict) Is ¶ added in v4.0.2
func (e *ErrOptimisticLockConflict) Is(target error) bool
Is reports whether target is an optimistic lock conflict.
type ErrOrderCountMismatch ¶
type ErrOrderCountMismatch struct {
// contains filtered or unexported fields
}
ErrOrderCountMismatch reports that the ORDER BY field and direction counts differ.
func (*ErrOrderCountMismatch) Error ¶
func (e *ErrOrderCountMismatch) Error() string
Error implements error.
func (*ErrOrderCountMismatch) Is ¶
func (e *ErrOrderCountMismatch) Is(target error) bool
Is reports whether target is an *ErrOrderCountMismatch with the same counts. An *ErrOrderCountMismatch with zero orderBys and zero orders matches any ErrOrderCountMismatch, enabling type-level errors.Is checks.
type ErrTableMissing ¶ added in v4.1.19
type ErrTableMissing struct {
Name string // Name is the expected physical table name.
}
ErrTableMissing reports that an expected table was not found.
func (*ErrTableMissing) Error ¶ added in v4.1.19
func (e *ErrTableMissing) Error() string
Error implements error.
type ErrUnknownSortField ¶
type ErrUnknownSortField struct {
// contains filtered or unexported fields
}
ErrUnknownSortField reports that a requested sort field is unknown.
func (*ErrUnknownSortField) Error ¶
func (e *ErrUnknownSortField) Error() string
Error implements error.
func (*ErrUnknownSortField) Is ¶
func (e *ErrUnknownSortField) Is(target error) bool
Is reports whether target is an *ErrUnknownSortField for the same field. An *ErrUnknownSortField with an empty field matches any ErrUnknownSortField, enabling both type-level and value-level errors.Is checks.
type Expression ¶
type Expression interface {
Expr() string // Expr returns the SQL fragment text.
Args() []any // Args returns the bind arguments referenced by Expr.
}
Expression represents a SQL fragment plus the args needed to render it safely.
func BindSlice ¶
func BindSlice(values any) Expression
BindSlice returns a comma-separated placeholder list for a slice value.
type FilteredStage ¶ added in v4.1.1
type FilteredStage[O Owner] interface { QueryStage[O] GroupBy(cols ...SQLColumn) GroupedStage[O] ForUpdate() LockedStage[O] Union(other QueryStage[O]) CompoundStage[O] UnionAll(other QueryStage[O]) CompoundStage[O] Intersect(other QueryStage[O]) CompoundStage[O] IntersectAll(other QueryStage[O]) CompoundStage[O] Except(other QueryStage[O]) CompoundStage[O] ExceptAll(other QueryStage[O]) CompoundStage[O] }
FilteredStage is the query state after both Where(...) and Search(...).
type FromStage ¶ added in v4.1.1
type FromStage[O Owner] interface { Select(cols ...BoundColumn[O]) *queryBuilder[O] }
FromStage is the result of From(...) before Select(...) is attached.
type GroupedStage ¶ added in v4.1.1
type GroupedStage[O Owner] interface { QueryStage[O] Having(conds ...Condition) HavingStage[O] ForUpdate() LockedStage[O] Union(other QueryStage[O]) CompoundStage[O] UnionAll(other QueryStage[O]) CompoundStage[O] Intersect(other QueryStage[O]) CompoundStage[O] IntersectAll(other QueryStage[O]) CompoundStage[O] Except(other QueryStage[O]) CompoundStage[O] ExceptAll(other QueryStage[O]) CompoundStage[O] }
GroupedStage is the query state after GroupBy(...).
type HavingStage ¶ added in v4.1.1
type HavingStage[O Owner] interface { QueryStage[O] ForUpdate() LockedStage[O] Union(other QueryStage[O]) CompoundStage[O] UnionAll(other QueryStage[O]) CompoundStage[O] Intersect(other QueryStage[O]) CompoundStage[O] IntersectAll(other QueryStage[O]) CompoundStage[O] Except(other QueryStage[O]) CompoundStage[O] ExceptAll(other QueryStage[O]) CompoundStage[O] }
HavingStage is the query state after Having(...).
type IndexInitMode ¶
type IndexInitMode = SchemaPolicy
IndexInitMode is kept as a deprecated alias for SchemaPolicy during the policy rename.
type LockedStage ¶ added in v4.1.1
type LockedStage[O Owner] interface { QueryStage[O] NoWait() LockedStage[O] SkipLocked() LockedStage[O] }
LockedStage is the query state after ForUpdate()/ForShare().
type Logger ¶ added in v4.1.19
type Logger interface {
Enabled(ctx context.Context, level slog.Level) bool
LogAttrs(ctx context.Context, level slog.Level, msg string, attrs ...slog.Attr)
}
Logger is the subset of slog.Logger used by runtime bootstrap.
type Order ¶
type Order string
Order represents a SQL ORDER BY direction.
func ReverseOrder ¶
ReverseOrder returns the opposite sort direction.
type OrderBy ¶
type OrderBy struct {
// contains filtered or unexported fields
}
OrderBy represents an ORDER BY clause with its column and direction.
type Owner ¶
type Owner interface {
// TSQOwner marks a type as a valid tsq scan owner.
TSQOwner()
}
Owner marks any Go type that tsq can scan selected fields into. Table and Result are the two specialized owner kinds built on top of it.
type PageRequest ¶ added in v4.0.6
type PageRequest struct {
Size int `json:"size" query:"size"` // Size is the requested page size.
Page int `json:"page" query:"page"` // Page is the 1-based page number.
OrderBy string `json:"order_by" query:"order_by"` // OrderBy lists sortable field names separated by commas.
Order string `json:"order" query:"order"` // Order lists sort directions aligned with OrderBy.
Keyword string `json:"keyword" query:"keyword"` // Keyword carries the optional free-text search term.
}
PageRequest captures a page request, sort instructions, and optional keyword search.
func NewPageRequest ¶ added in v4.0.6
func NewPageRequest(params url.Values) *PageRequest
NewPageRequest creates *PageRequest from query parameters(e.g. page=1&size=20&order_by=id&order=DESC).
func (*PageRequest) Normalize ¶ added in v4.0.6
func (r *PageRequest) Normalize() error
Normalize applies default page values and clamps the requested page size.
func (*PageRequest) Offset ¶ added in v4.0.6
func (r *PageRequest) Offset() int
Offset calculates the offset value for SQL LIMIT clause. Returns 0 if calculation would overflow; guaranteed safe for use in SQL.
func (*PageRequest) ToQuery ¶ added in v4.0.6
func (r *PageRequest) ToQuery() url.Values
ToQuery serializes the request back into URL query parameters.
func (*PageRequest) Validate ¶ added in v4.0.6
func (r *PageRequest) Validate() error
Validate reports invalid paging or sorting input without mutating r.
type PageResponse ¶ added in v4.0.6
type PageResponse[T any] struct { PageRequest Total int64 `json:"total"` // Total is the full number of matching rows. TotalPage int64 `json:"total_page"` // TotalPage is the number of available pages after rounding up. Data []*T `json:"data"` // Data contains the rows for the current page. }
PageResponse wraps paginated data with request and count metadata.
func NewPageResponse ¶ added in v4.0.6
func NewPageResponse[T any](r *PageRequest, total int64, data []*T) *PageResponse[T]
NewPageResponse creates a PageResponse from the request, total count, and data.
func (*PageResponse[T]) HasNext ¶ added in v4.0.6
func (r *PageResponse[T]) HasNext() bool
HasNext reports whether another page exists after the current one.
func (*PageResponse[T]) HasPrev ¶ added in v4.0.6
func (r *PageResponse[T]) HasPrev() bool
HasPrev reports whether a page exists before the current one.
func (*PageResponse[T]) IsEmpty ¶ added in v4.0.6
func (r *PageResponse[T]) IsEmpty() bool
IsEmpty reports whether the current page contains any rows.
type Query ¶
type Query[O Owner] struct { // contains filtered or unexported fields }
Query is a compiled SQL query with count, list, and keyword-search variants. Query is the immutable, concurrency-safe result of Build, separating query definition from execution.
func (*Query[O]) Count ¶
Count executes the count query and returns the number of matching records. The result is truncated to int; use Count64 when an int64 is required.
func (*Query[O]) Count64 ¶
Count64 executes the count query and returns the number of matching records as int64. This avoids truncation on large result sets or 32-bit platforms.
func (*Query[O]) Get ¶ added in v4.1.23
Get executes q and returns one row or nil when no row matches.
func (*Query[O]) GetOrErr ¶ added in v4.1.23
GetOrErr executes q and returns one row or sql.ErrNoRows.
func (*Query[O]) KeywordCountSQL ¶ added in v4.0.2
KeywordCountSQL returns the keyword-search COUNT query SQL statement.
func (*Query[O]) KeywordListSQL ¶ added in v4.0.2
KeywordListSQL returns the keyword-search SELECT query SQL statement.
func (*Query[O]) Page ¶ added in v4.1.23
func (q *Query[O]) Page( ctx context.Context, tx SQLExecutor, page *PageRequest, args ...any, ) (*PageResponse[O], error)
Page executes a paginated query with the provided page parameters.
func (*Query[O]) QueryFloat ¶
QueryFloat executes the query and returns a single float result.
func (*Query[O]) QueryString ¶ added in v4.0.2
QueryString executes the query and returns a single string result.
type QueryStage ¶ added in v4.1.1
type QueryStage[O Owner] interface { Build() (*Query[O], error) MustBuild() *Query[O] Get(ctx context.Context, tx SQLExecutor, args ...any) (*O, error) GetOrErr(ctx context.Context, tx SQLExecutor, args ...any) (*O, error) Load(ctx context.Context, tx SQLExecutor, holder *O, args ...any) error Exists(ctx context.Context, tx SQLExecutor, args ...any) (bool, error) Count(ctx context.Context, tx SQLExecutor, args ...any) (int, error) List(ctx context.Context, tx SQLExecutor, args ...any) ([]*O, error) Page(ctx context.Context, tx SQLExecutor, page *PageRequest, args ...any) (*PageResponse[O], error) }
QueryStage is a buildable query state that can participate in CTEs and set operations.
type RHS ¶ added in v4.1.15
type RHS[T any] interface { // contains filtered or unexported methods }
RHS is a typed right-hand-side operand for scalar predicates such as EQ/NE/GT/GTE/LT/LTE/Like/NLike.
Supported RHS values are TSQ typed columns/expressions and typed Subquery handles built with BuildSubquery or AsSubquery. Plain Go values intentionally use the dedicated EQVal/NEVal/GTVal/GTEVal/LTVal/LTEVal helpers, while runtime-bound placeholders continue to use EQVar/NEVar/GTVar/GTEVar/LTVar/LTEVar.
type RegistrationError ¶
type RegistrationError struct {
Type RegistrationErrorType // Type classifies the registration failure.
TableName string // TableName identifies the conflicting or invalid table entry.
Message string // Message contains the user-facing error text.
}
RegistrationError reports a table-registration failure.
func (*RegistrationError) Error ¶
func (e *RegistrationError) Error() string
Error implements error.
type RegistrationErrorType ¶
type RegistrationErrorType string
RegistrationErrorType identifies a table-registration failure category.
const ( // RegistrationErrorNilTable means RegisterTable received a nil table. RegistrationErrorNilTable RegistrationErrorType = "nil_table" // RegistrationErrorInvalidIndex means RegisterTable received invalid index metadata. RegistrationErrorInvalidIndex RegistrationErrorType = "invalid_index" // RegistrationErrorDuplicate means the same table key was registered twice. RegistrationErrorDuplicate RegistrationErrorType = "duplicate" )
type Result ¶
type Result interface {
Owner
// TSQResult marks a scan owner as projection-only.
TSQResult()
}
Result marks a projection-only owner. It participates in typed SELECT flows but is not a physical mutation target.
type ResultColumn ¶ added in v4.1.0
type ResultColumn[O Owner, T any] interface { TypedColumn[O, T] }
ResultColumn is the user-facing typed projection API returned by MapInto. It keeps result bindings inspectable without exposing the concrete projection implementation.
func MapInto ¶ added in v4.0.2
func MapInto[Target Owner, T any]( source ValueColumn[T], fieldPointer func(*Target) *T, jsonFieldName string, ) ResultColumn[Target, T]
MapInto creates a result-owned projection column from another typed expression.
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime owns the initialized TSQ process state used for execution, index setup, identifier validation, and tracing.
func NewRuntime ¶
func NewRuntime( driverName string, dsn string, tables []TableRegistration, options ...*RuntimeOptions, ) (*Runtime, error)
NewRuntime opens a database connection, resolves the SQL dialect from driverName, and constructs an initialized runtime for the provided table metadata.
func (*Runtime) ExecContext ¶ added in v4.1.9
ExecContext executes a statement against the runtime database.
func (*Runtime) QueryContext ¶ added in v4.1.9
QueryContext executes a query against the runtime database.
func (*Runtime) QueryRowContext ¶ added in v4.1.9
QueryRowContext executes a query expected to return at most one row.
func (*Runtime) SQLDialect ¶ added in v4.1.4
func (r *Runtime) SQLDialect() tsqdialect.Dialect
SQLDialect returns the concrete SQL dialect bound to this runtime.
func (*Runtime) ValidateIdentifiersForDialect ¶
ValidateIdentifiersForDialect validates all configured table and column identifiers against the current database dialect.
func (*Runtime) WithTx ¶ added in v4.1.9
func (r *Runtime) WithTx( ctx context.Context, options *TxOptions, fn func(context.Context, SQLExecutor) error, ) error
WithTx starts a transaction on the runtime database and passes a dialect-aware executor to fn. It manages BeginTx, Commit, and Rollback automatically.
type RuntimeOptions ¶ added in v4.1.18
type RuntimeOptions struct {
TablePolicy SchemaPolicy // TablePolicy chooses how TSQ manages declared tables and columns during NewRuntime.
IndexPolicy SchemaPolicy // IndexPolicy chooses how TSQ manages declared indexes during NewRuntime.
Tracers []Tracer // Tracers configures the runtime's tracer chain during NewRuntime.
Logger Logger // Logger receives schema bootstrap decisions and executed DDL.
// IdentifierValidationMode controls how to handle identifier length violations:
// "strict" = fail if any identifier exceeds dialect limits (default for most dialects)
// "warn" = log warnings but allow (for permissive databases)
// "skip" = no validation (useful for dynamic schemas)
IdentifierValidationMode string
}
RuntimeOptions controls runtime initialization behavior.
type SQLColumn ¶
type SQLColumn interface {
SQLExpr() string // SQLExpr returns the rendered expression, such as "users.name".
OutputName() string // OutputName returns the default scan alias for the expression.
JSONFieldName() string // JSONFieldName returns the stable field name used by JSON-facing helpers.
Table() Table // Table returns the primary table that owns the expression.
Name() string // Name returns the physical column name when the expression comes from a table column.
QualifiedName() string // QualifiedName returns the expression with its table qualifier or transformation applied.
// contains filtered or unexported methods
}
SQLColumn is the runtime view of a selectable SQL expression.
func AliasColumns ¶
AliasColumns rebinds each column onto table while preserving order.
func RebindColumn ¶
RebindColumn returns col rebound to table when the column supports rebinding.
func SQLColumns ¶
func SQLColumns[O Owner](cols ...BoundColumn[O]) []SQLColumn
SQLColumns converts typed columns into a runtime slice of SQLColumn values.
type SQLExecutor ¶ added in v4.0.2
type SQLExecutor interface {
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
SQLExecutor defines the shared query execution surface implemented by database/sql entry points such as *sql.DB and *sql.Tx. The standard library does not provide this exact interface, so tsq defines the minimal Context-based method set it needs.
func WrapExecutor ¶
func WrapExecutor(exec SQLExecutor, sqlDialect dialect.Dialect) SQLExecutor
WrapExecutor wraps a SQLExecutor with dialect information.
type SchemaPolicy ¶ added in v4.1.19
type SchemaPolicy string
SchemaPolicy controls how TSQ manages declared schema objects during runtime bootstrap.
const ( // SchemaPolicyManual leaves declared objects untouched and only logs a reminder. SchemaPolicyManual SchemaPolicy = "manual" // SchemaPolicyValidate fails when a declared object is missing or mismatched. SchemaPolicyValidate SchemaPolicy = "validate" // SchemaPolicyCreateMissing creates missing declared objects but still fails on mismatches. SchemaPolicyCreateMissing SchemaPolicy = "create_missing" // SchemaPolicyReconcile creates missing declared objects and reconciles mismatches. SchemaPolicyReconcile SchemaPolicy = "reconcile" // SchemaPolicyManaged reconciles declared objects and removes TSQ-managed extras. SchemaPolicyManaged SchemaPolicy = "managed" )
type SearchColumn ¶
type SearchColumn interface {
SQLColumn
// contains filtered or unexported methods
}
SearchColumn marks expressions that may participate in keyword search expansion.
type SearchStage ¶ added in v4.1.1
type SearchStage[O Owner] interface { QueryStage[O] Where(conds ...Condition) FilteredStage[O] GroupBy(cols ...SQLColumn) GroupedStage[O] ForUpdate() LockedStage[O] Union(other QueryStage[O]) CompoundStage[O] UnionAll(other QueryStage[O]) CompoundStage[O] Intersect(other QueryStage[O]) CompoundStage[O] IntersectAll(other QueryStage[O]) CompoundStage[O] Except(other QueryStage[O]) CompoundStage[O] ExceptAll(other QueryStage[O]) CompoundStage[O] }
SearchStage is the query state after Search(...).
type SelectStage ¶ added in v4.1.1
SelectStage is the result of Select(...) before From(...) is attached.
func Select ¶
func Select[O Owner](cols ...BoundColumn[O]) SelectStage[O]
Select creates a new state-machine builder with the specified columns.
type Subquery ¶ added in v4.1.15
Subquery is an opaque typed handle for a built single-column subquery. Construct it with BuildSubquery or AsSubquery.
func AsSubquery ¶ added in v4.1.15
AsSubquery validates that query is a built single-column query whose selected column matches selected, then returns a typed subquery handle suitable for RHS comparisons such as EQ/NE/GT/GTE/LT/LTE/Like/Between and for In/NIn.
func BuildSubquery ¶ added in v4.1.15
func BuildSubquery[O Owner, T any](qb QueryStage[O], selected TypedColumn[O, T]) (Subquery[T], error)
BuildSubquery builds qb and validates that it returns exactly one column with the same typed expression metadata as selected.
type Table ¶
type Table interface {
Owner
Cols() []SQLColumn // Cols returns the physical columns exposed by the table.
Table() string // Table returns the SQL identifier used in rendered queries.
SearchColumns() []SearchColumn // SearchColumns returns columns eligible for keyword-search helpers.
PrimaryKeys() []string // PrimaryKeys returns the primary-key column names in declaration order.
AutoIncrement() bool // AutoIncrement reports whether inserts rely on generated primary keys.
VersionColumn() string // VersionColumn returns the optimistic-lock column name, if any.
}
Table defines a physical SQL table source. Unlike Result, a Table is both a scan owner and a mutation target, and it exposes stable column and primary-key metadata for metadata-driven execution.
func AliasTable ¶
AliasTable returns table wrapped with the provided SQL alias.
type TableColumn ¶
type TableColumn[O Table] interface { BoundColumn[O] SearchColumn // contains filtered or unexported methods }
TableColumn is a physical source column that belongs to a table owner.
type TableIndex ¶ added in v4.1.4
type TableIndex struct {
Name string // Name is the stable physical index name.
Fields []string // Fields preserves the indexed column order.
Unique bool // Unique reports whether the index enforces uniqueness.
}
TableIndex declares one physical index owned by a registered table.
type TableRegistration ¶ added in v4.1.11
type TableRegistration struct {
Table Table // Table is the physical table metadata.
Columns []tsqdialect.DDLColumnSpec // Columns declares the physical column schema owned by Table.
Indexes []TableIndex // Indexes declares the indexes owned by Table.
}
TableRegistration describes one table plus its declared indexes for runtime bootstrap.
type Tracer ¶
Tracer wraps a function call with tracing behavior. Configure tracers via RuntimeOptions.Tracers when constructing a Runtime.
type TxOptions ¶ added in v4.1.9
type TxOptions struct {
// SQL passes through to database/sql BeginTx.
SQL *sql.TxOptions
// Retry decides whether a failed transaction attempt should be retried.
// When set, RetryConfig defaults are applied automatically unless overridden.
Retry TxRetryPredicate
// RetryConfig customizes retry timing and attempt limits when Retry is set.
RetryConfig *TxRetryConfig
}
TxOptions configures Runtime.WithTx.
type TxRetryConfig ¶ added in v4.1.9
type TxRetryConfig struct {
// MaxAttempts is the total number of attempts, including the first try.
MaxAttempts int
// InitialBackoff is the delay after the first retryable failure.
InitialBackoff time.Duration
// MaxBackoff caps exponential backoff. Zero means no cap.
MaxBackoff time.Duration
// BackoffMultiplier grows the delay after each retryable failure.
BackoffMultiplier float64
}
TxRetryConfig configures retry timing and attempt limits for Runtime.WithTx.
func DefaultTxRetryConfig ¶ added in v4.1.9
func DefaultTxRetryConfig() *TxRetryConfig
DefaultTxRetryConfig returns the default retry timing used when Retry is set.
type TxRetryPredicate ¶ added in v4.1.9
TxRetryPredicate reports whether err should retry the whole transaction callback.
type TypedColumn ¶
type TypedColumn[O Owner, T any] interface { BoundColumn[O] // contains filtered or unexported methods }
TypedColumn is a selectable expression that also carries the scanned Go value type.
type ValueColumn ¶ added in v4.1.1
ValueColumn is a selectable expression that carries a scanned Go value type without exposing its owner in the API surface.
type WhereStage ¶ added in v4.1.1
type WhereStage[O Owner] interface { QueryStage[O] Search(cols ...SearchColumn) FilteredStage[O] GroupBy(cols ...SQLColumn) GroupedStage[O] ForUpdate() LockedStage[O] Union(other QueryStage[O]) CompoundStage[O] UnionAll(other QueryStage[O]) CompoundStage[O] Intersect(other QueryStage[O]) CompoundStage[O] IntersectAll(other QueryStage[O]) CompoundStage[O] Except(other QueryStage[O]) CompoundStage[O] ExceptAll(other QueryStage[O]) CompoundStage[O] }
WhereStage is the query state after Where(...).
Source Files
¶
- case.go
- column.go
- column_impl.go
- column_projection.go
- condition.go
- cte.go
- dialect_validation.go
- doc.go
- executor.go
- executor_mutation.go
- executor_mutation_meta.go
- executor_wrap.go
- expression.go
- function.go
- order.go
- owner.go
- paging.go
- predicate_column.go
- predicate_subquery.go
- query.go
- query_args.go
- query_chunked.go
- query_load.go
- query_plan.go
- query_plan_cte.go
- query_plan_sql.go
- query_plan_tables.go
- query_plan_validate.go
- query_scalar.go
- query_scan.go
- query_validation.go
- querybuilder.go
- querybuilder_core.go
- querybuilder_exec.go
- querybuilder_lock.go
- querybuilder_setops.go
- querybuilder_stages.go
- rhs.go
- runtime.go
- runtime_schema.go
- sql_executor.go
- sql_render.go
- sqlite_errors.go
- subquery.go
- table.go
- table_alias.go
- table_index.go
- table_registry.go
- trace.go
- tx.go
- validation.go