funq

package module
v0.0.0-...-cb5b6c1 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 17 Imported by: 0

README

Funq

Funq is a schema-first ORM for Go and PostgreSQL. Declare your entities as ordinary Go types, generate a plain model and typed database client, then review the desired PostgreSQL schema as a migration.

Funq keeps the important boundaries explicit:

  • schema declarations are the source of truth for models, names, relations, and constraints;
  • generated column handles and builders keep query values entity- and type-safe at compile time;
  • every database operation ends at an explicit terminal call;
  • migration generation produces Goose-compatible files for review and never changes production schema as an application side effect;
  • raw SQL remains available for reports and database features that do not fit the generated query surface.

The project is under active development. Start with the getting started guide, then use the user documentation for task-oriented guidance. The technical documentation records implementation contracts and design rationale.

Build your first client

This is the path for an application using Funq, not a checkout of the Funq repository.

1. Install Funq

In an existing Go module:

go get codeberg.org/dajooo/funq@latest
go get codeberg.org/dajooo/funq/driver/pgxdriver@latest
go install codeberg.org/dajooo/funq/cmd/funq@latest

The runtime is a normal Go dependency. The funq executable is used during development to generate application code and migration files. The PostgreSQL pgxdriver adapter is a separate module and is only needed by applications using pgx.

2. Scaffold the project
funq init

This writes funq.yaml and an example db/schema package:

schema: ./db/schema
out: ./db/store
migrations: ./db/migrations
dev: env:FUNQ_DEV_DATABASE_URL

Every other command reads this file instead of taking path flags, and finds it by walking up from the working directory the same way go.mod is found. Edit the paths if your project's layout differs; dev is either a literal database URL or an env:VAR reference to a disposable development database.

3. Declare a schema

Edit db/schema/user.go:

package dbschema

import (
	"codeberg.org/dajooo/funq/schema"
	"codeberg.org/dajooo/funq/schema/field"
	"codeberg.org/dajooo/funq/schema/mixin"
)

type User struct{ schema.Schema }

func (User) Fields() schema.Fields {
	return schema.Fields{
		field.Text("name"),
	}
}

func (User) Mixins() schema.Mixins {
	return schema.Mixins{mixin.ULID, mixin.Timestamps}
}

Funq discovers every exported concrete type implementing schema.Interface in the schema package. There is no registry to maintain.

4. Generate the client
funq generate

The generated package contains models, entity clients, typed query handles, mutation builders, edge loaders, a manifest, and the resolved schema cache at db/store/schema.json. Never edit generated files by hand.

5. Connect and use the client
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
	return err
}
defer pool.Close()

db := store.NewClient(pgxdriver.Open(pool))

user, err := db.User.Create().
	SetName("Ada").
	Save(ctx)
if err != nil {
	return err
}

users, err := db.User.Query().
	Where(userq.Name.ContainsFold("ad")).
	Order(userq.Name.Asc()).
	All(ctx)

Query builders do not perform I/O while they are being built. All, One, First, Paginate, Count, Exec, and the other terminal methods execute the operation with the caller's context.

6. Create and review a migration

Render the desired DDL, or create a migration by diffing the dev database set in funq.yaml:

funq sql

funq migrate new initial

Review and apply the generated Goose-compatible migration with the migration runner used by your application. In CI, check that the database matches the declared schema:

funq migrate status

The dev database must be disposable. Funq replays the existing migrations in an isolated scratch schema before it introspects and diffs the result.

Continue with the guides

You want to… Read
Set up a standalone application Getting started
Declare fields, relations, indexes, and mixins Defining a schema
Build typed queries and pagination Querying
Create, update, delete, and transact data Mutations and transactions
Bind HTTP input safely Binding external input
Generate and review PostgreSQL migrations Migrations

For a complete consumer module, see example/. It contains a blog schema, checked-in generated client, Goose migration, and an integration walkthrough using PostgreSQL.

Compatibility

Funq v1 targets Go 1.25 and 1.26 and PostgreSQL 15 through 18. See RELEASE.md for compatibility and release policy and SECURITY.md for vulnerability reporting and deployment guidance.

Repository development

Repository contributors can use the Taskfile commands below:

task fmt
task lint
task test
task test:race
task test:integration
task gen:check
task build

Integration tests use an isolated PostgreSQL database or start a disposable test container. See the tooling contract for the full workflow.

Documentation

Overview

Package funq provides the runtime kernel and public generic types used by Funq-generated clients.

Index

Constants

View Source
const (
	ConstraintUnique     = dialect.ConstraintUnique
	ConstraintForeignKey = dialect.ConstraintForeignKey
	ConstraintCheck      = dialect.ConstraintCheck
	ConstraintNotNull    = dialect.ConstraintNotNull
)

Re-export constraint kind constants.

Variables

View Source
var (
	// ErrNotFound is returned when a query expects a row but none is found.
	ErrNotFound = errors.New("funq: row not found")

	// ErrTooManyRows is returned when a query expects at most one row but finds more.
	ErrTooManyRows = errors.New("funq: too many rows returned")

	// Binding errors are re-exported for callers that do not need to import the
	// neutral bind package just to classify generated-binder failures.
	ErrUnknownField = bind.ErrUnknownField
	ErrBadOperator  = bind.ErrBadOperator
	ErrBadValue     = bind.ErrBadValue

	// ErrConflict is returned when optimistic locking observes no matching
	// version, or when an explicitly conflict-sensitive mutation cannot
	// determine a winner.
	ErrConflict = errors.New("funq: optimistic locking conflict")

	// ErrTransactionRequired is returned before I/O for operations whose SQL
	// semantics require a transaction, such as row locks and relation changes.
	ErrTransactionRequired = errors.New("funq: transaction required")

	// ErrReadOnly is returned when a write or lock-bearing operation is sent to
	// a read-only transaction or replica.
	ErrReadOnly = errors.New("funq: read-only driver")
)
View Source
var ErrInvalidCursor = errors.New("funq: invalid cursor")

ErrInvalidCursor reports a malformed, stale, or tampered cursor.

Functions

func ContextConstraintLookup

func ContextConstraintLookup(ctx context.Context) (dialect.ConstraintLookup, bool)

ContextConstraintLookup retrieves the ConstraintLookup from context if present.

func ContextSensitivePositions

func ContextSensitivePositions(ctx context.Context) ([]int, bool)

ContextSensitivePositions retrieves the sensitive argument positions from context.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether err is a normalized serialization or deadlock failure. Conflict errors are intentionally not retryable.

func NamedExec

func NamedExec(ctx context.Context, drv Driver, sql string, args []any, options NamedQueryOptions) (int64, error)

NamedExec executes command SQL and returns its affected-row count.

func NamedFirst

func NamedFirst[T any](ctx context.Context, drv Driver, sql string, args []any, options NamedQueryOptions) (*T, error)

NamedFirst executes a named SQL operation and returns its first row.

func NamedIterate

func NamedIterate[T any](ctx context.Context, drv Driver, sql string, args []any, fn func(T) error, options NamedQueryOptions) error

NamedIterate streams a named SQL result through the standard scanner.

func NamedOne

func NamedOne[T any](ctx context.Context, drv Driver, sql string, args []any, options NamedQueryOptions) (*T, error)

NamedOne executes a named SQL operation and requires exactly one row.

func NamedQuery

func NamedQuery[T any](ctx context.Context, drv Driver, sql string, args []any, options NamedQueryOptions) ([]T, error)

NamedQuery executes a named SQL operation and scans all rows using the standard scanner and observer path.

func Observe

func Observe(ctx context.Context, sql string, args []any, err error, dur time.Duration)

Observe checks if there is a QueryObserver in the context, and if so, triggers it after redacting sensitive arguments.

func RedactArgs

func RedactArgs(args []any, sensitivePos []int) []any

RedactArgs returns a copy of args with sensitive positions redacted.

func RunInSavepoint

func RunInSavepoint(ctx context.Context, tx TxDriver, fn func(TxDriver) error, options ...SavepointOptions) (err error)

RunInSavepoint executes fn inside a deterministic savepoint. Callback errors roll back to the savepoint and release it; successful callbacks only release it. Drivers without savepoints fail before fn is invoked.

func RunInTx

func RunInTx(ctx context.Context, d Driver, opts TxOptions, fn func(TxDriver) error) (err error)

RunInTx runs a callback function within a transaction. If driver is already a TxDriver (i.e. we are already in an active transaction), it invokes the callback immediately without starting a nested transaction. Otherwise, it starts a new transaction, runs the callback, and commits if the callback returns nil, or rolls back if the callback returns an error or panics.

If the rollback fails, the error is joined with the callback error or reported to the observer in case of a panic.

func RunInTxRetry

func RunInTxRetry(ctx context.Context, d Driver, txOptions TxOptions, retry RetryOptions, fn func(TxDriver) error) error

RunInTxRetry retries a complete transaction only for normalized serialization/deadlock errors. Each attempt receives a fresh transaction.

func RunInTxWithRetry

func RunInTxWithRetry(ctx context.Context, d Driver, txOptions TxOptions, retry RetryOptions, fn func(TxDriver) error) error

RunInTxWithRetry is a descriptive alias for RunInTxRetry.

func Scan

func Scan[T any, Q scanQuery](ctx context.Context, q Q) ([]T, error)

Scan executes a typed query and scans its projection into destination T. The query's source entity and destination type are intentionally separate; this is what permits aggregate and arbitrary projection results.

func ScanRows

func ScanRows[T any](rows Rows, strict bool) ([]T, error)

ScanRows scans all rows into a slice of type T.

func WithConstraintLookup

func WithConstraintLookup(ctx context.Context, lookup dialect.ConstraintLookup) context.Context

WithConstraintLookup returns a context holding the given ConstraintLookup.

func WithContextObserver

func WithContextObserver(ctx context.Context, obs QueryObserver) context.Context

WithContextObserver returns a context holding the given QueryObserver.

func WithNamedQueryMetadata

func WithNamedQueryMetadata(ctx context.Context, entity string, op Operation, readOnly bool, expectedColumns []string) context.Context

WithNamedQueryMetadata records the complete metadata contract for a named SQL operation before it reaches the driver and observer.

func WithQueryMetadata

func WithQueryMetadata(ctx context.Context, entity string, op Operation) context.Context

WithQueryMetadata returns a context holding query metadata.

func WithSensitivePositions

func WithSensitivePositions(ctx context.Context, positions []int) context.Context

WithSensitivePositions returns a context holding the 1-based sensitive argument positions.

Types

type Annotation

type Annotation struct {
	Namespace string          `json:"namespace"`
	Payload   json.RawMessage `json:"payload,omitempty"`
}

Annotation is opaque metadata attached to a named SQL declaration. Generators preserve annotations but do not interpret them.

type ArrayCol

type ArrayCol[T any, E any] struct {
	// contains filtered or unexported fields
}

ArrayCol is a typed array column handle.

func NewArrayCol

func NewArrayCol[T any, E any](table, column string, sensitive ...bool) ArrayCol[T, E]

func (ArrayCol) As

func (c ArrayCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (ArrayCol) Asc

func (c ArrayCol) Asc() OrderTerm[T]

func (ArrayCol[T, E]) Contains

func (c ArrayCol[T, E]) Contains(v []E) Pred[T]

func (ArrayCol) Desc

func (c ArrayCol) Desc() OrderTerm[T]

func (ArrayCol[T, E]) Eq

func (c ArrayCol[T, E]) Eq(v []E) Pred[T]

func (ArrayCol) Expr

func (c ArrayCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (ArrayCol[T, E]) Has

func (c ArrayCol[T, E]) Has(v E) Pred[T]

func (ArrayCol) IsNull

func (c ArrayCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (ArrayCol) NotNull

func (c ArrayCol) NotNull() Pred[T]

func (ArrayCol[T, E]) Overlaps

func (c ArrayCol[T, E]) Overlaps(v []E) Pred[T]

func (ArrayCol) Ref

func (c ArrayCol) Ref() ColumnRef

type Assignment

type Assignment struct {
	Column     string
	Value      any
	Expression MutationExpr
	Sensitive  bool
}

Assignment is a declaration-order mutation assignment.

func Assign

func Assign(column string, value any) Assignment

func AssignExpr

func AssignExpr(column string, expression MutationExpr) Assignment

func AssignSensitive

func AssignSensitive(column string, value any) Assignment

type BoolCol

type BoolCol[T any] struct {
	// contains filtered or unexported fields
}

BoolCol is a typed boolean column handle.

func NewBoolCol

func NewBoolCol[T any](table, column string, sensitive ...bool) BoolCol[T]

func (BoolCol) As

func (c BoolCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (BoolCol) Asc

func (c BoolCol) Asc() OrderTerm[T]

func (BoolCol) Desc

func (c BoolCol) Desc() OrderTerm[T]

func (BoolCol[T]) Eq

func (c BoolCol[T]) Eq(v bool) Pred[T]

func (BoolCol) Expr

func (c BoolCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (BoolCol[T]) IsFalse

func (c BoolCol[T]) IsFalse() Pred[T]

func (BoolCol) IsNull

func (c BoolCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (BoolCol[T]) IsTrue

func (c BoolCol[T]) IsTrue() Pred[T]

func (BoolCol) NotNull

func (c BoolCol) NotNull() Pred[T]

func (BoolCol) Ref

func (c BoolCol) Ref() ColumnRef

type BulkInsertBuilder

type BulkInsertBuilder[T any] struct {
	// contains filtered or unexported fields
}

func NewBulkInsert

func NewBulkInsert[T any](drv Driver, table string, options ...MutationOption) *BulkInsertBuilder[T]

func (*BulkInsertBuilder[T]) Add

func (b *BulkInsertBuilder[T]) Add(row BulkRow) *BulkInsertBuilder[T]

func (*BulkInsertBuilder[T]) AddRow

func (b *BulkInsertBuilder[T]) AddRow(assignments ...Assignment) *BulkInsertBuilder[T]

func (*BulkInsertBuilder[T]) BatchSize

func (b *BulkInsertBuilder[T]) BatchSize(size int) *BulkInsertBuilder[T]

func (*BulkInsertBuilder[T]) Batches

func (b *BulkInsertBuilder[T]) Batches() ([]MutationBatch, error)

func (*BulkInsertBuilder[T]) Exec

func (b *BulkInsertBuilder[T]) Exec(ctx context.Context) (int64, error)

func (*BulkInsertBuilder[T]) ParameterLimit

func (b *BulkInsertBuilder[T]) ParameterLimit(limit int) *BulkInsertBuilder[T]

type BulkRow

type BulkRow struct{ Assignments []Assignment }

BulkRow holds one insert row. All rows in a batch must have the same column shape; rows with other shapes are grouped separately.

func NewBulkRow

func NewBulkRow(assignments ...Assignment) BulkRow

type CTE

type CTE struct {
	Name          string
	Columns       []string
	Body          Selectable
	Recursive     bool
	RecursiveBody Selectable
}

CTE is a declared common-table expression.

func NewCTE

func NewCTE(name string, body Selectable, columns ...string) CTE

func NewRecursiveCTE

func NewRecursiveCTE(name string, columns []string, anchor, recursive Selectable) CTE

type ColumnRef

type ColumnRef struct {
	Entity   string
	Table    string
	Column   string
	Nullable bool
}

ColumnRef is a typed source-column identity used by joins and correlations. It is an identity, not a raw SQL fragment, and is always quoted on render.

func NewColumnRef

func NewColumnRef(entity, table, column string) ColumnRef

NewColumnRef creates a column identity for composition helpers.

type Config

type Config struct {
	Observer    QueryObserver
	MaxPageSize int
	CursorKey   []byte
	StrictScan  bool
}

Config holds runtime configuration options for the client.

func Configure

func Configure(options ...Option) Config

Configure applies options to a fresh runtime configuration. Generated clients use this helper to keep option handling in the runtime package.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

type ConflictTarget

type ConflictTarget struct {
	Constraint string
	Columns    []ColumnRef
	Predicate  any
}

ConflictTarget identifies a unique conflict target. Exactly one of Constraint or Columns must be supplied. Predicate is accepted as a typed Pred[T] value and is checked against the upsert entity during rendering.

type ConstraintError

type ConstraintError = dialect.ConstraintError

ConstraintError represents a database constraint violation.

type ConstraintKind

type ConstraintKind = dialect.ConstraintKind

ConstraintKind identifies the database constraint type that was violated.

type CopyBuilder

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

CopyBuilder is an opt-in COPY mutation. It requires a CopyDriver and never silently falls back to INSERT.

func NewCopy

func NewCopy(drv Driver, table string, columns []string, source CopySource, options ...MutationOption) *CopyBuilder

func (*CopyBuilder) Exec

func (b *CopyBuilder) Exec(ctx context.Context) (int64, error)

type CopyDriver

type CopyDriver interface {
	Driver
	CopyFrom(ctx context.Context, table string, columns []string, source CopySource) (int64, error)
}

CopyDriver is an optional bulk-write interface. COPY is intentionally not part of Driver because its conflict, returning, and trigger semantics are different from regular INSERT.

type CopySource

type CopySource interface {
	Next() bool
	Values() ([]any, error)
	Err() error
}

CopySource is the neutral row stream consumed by a COPY-capable driver. Values must be returned in the same order as the requested COPY columns.

type CreateBuilder

type CreateBuilder[T any] struct {
	// contains filtered or unexported fields
}

CreateBuilder is an explicit INSERT builder. Generated setters are thin wrappers around Set and therefore retain compile-time field/value typing in the generated package.

func NewCreate

func NewCreate[T any](drv Driver, table string, options ...MutationOption) *CreateBuilder[T]

func NewCreateBuilder

func NewCreateBuilder[T any](drv Driver, table string, options ...MutationOption) *CreateBuilder[T]

NewCreateBuilder is an explicit alias useful to generated code.

func (*CreateBuilder[T]) Clear

func (b *CreateBuilder[T]) Clear(column string) *CreateBuilder[T]

func (*CreateBuilder[T]) ClearSensitive

func (b *CreateBuilder[T]) ClearSensitive(column string) *CreateBuilder[T]

ClearSensitive clears a sensitive create field and keeps it redacted in observer notifications.

func (*CreateBuilder[T]) Require

func (b *CreateBuilder[T]) Require(columns ...string) *CreateBuilder[T]

Require marks fields that must be present and non-nil before SQL rendering.

func (*CreateBuilder[T]) Returning

func (b *CreateBuilder[T]) Returning(exprs ...SelectExpr) *CreateBuilder[T]

Returning selects a typed projection for a create mutation.

func (*CreateBuilder[T]) SQL

func (b *CreateBuilder[T]) SQL() (string, []any, error)

func (*CreateBuilder[T]) Save

func (b *CreateBuilder[T]) Save(ctx context.Context) (*T, error)

func (*CreateBuilder[T]) Set

func (b *CreateBuilder[T]) Set(column string, value any) *CreateBuilder[T]

func (*CreateBuilder[T]) SetExpr

func (b *CreateBuilder[T]) SetExpr(column string, expression MutationExpr) *CreateBuilder[T]

SetExpr assigns an expression without reading the current row first.

func (*CreateBuilder[T]) SetNillable

func (b *CreateBuilder[T]) SetNillable(column string, value any) *CreateBuilder[T]

func (*CreateBuilder[T]) SetNillableSensitive

func (b *CreateBuilder[T]) SetNillableSensitive(column string, value any) *CreateBuilder[T]

SetNillableSensitive is SetNillable with observer redaction enabled.

func (*CreateBuilder[T]) SetSensitive

func (b *CreateBuilder[T]) SetSensitive(column string, value any) *CreateBuilder[T]

SetSensitive marks a create argument as sensitive for observer redaction.

type CursorPage

type CursorPage struct {
	After  string
	Before string
	Size   int
}

CursorPage requests a stable keyset page. After and Before are mutually exclusive opaque cursors.

type DeleteBuilder

type DeleteBuilder[T any] struct {
	// contains filtered or unexported fields
}

DeleteBuilder is an explicit DELETE builder. DeleteOne is represented by the same builder with single=true and reports ErrNotFound for zero rows.

func NewDelete

func NewDelete[T any](drv Driver, table string, options ...MutationOption) *DeleteBuilder[T]

func (*DeleteBuilder[T]) Exec

func (b *DeleteBuilder[T]) Exec(ctx context.Context) (int64, error)

func (*DeleteBuilder[T]) SQL

func (b *DeleteBuilder[T]) SQL() (string, []any, error)

func (*DeleteBuilder[T]) Where

func (b *DeleteBuilder[T]) Where(preds ...Pred[T]) *DeleteBuilder[T]

type DeleteOneBuilder

type DeleteOneBuilder[T any] struct {
	// contains filtered or unexported fields
}

DeleteOneBuilder is the single-row delete variant. Its Exec method returns ErrNotFound when the key does not exist.

func NewDeleteOne

func NewDeleteOne[T any](drv Driver, table, idColumn string, id any, options ...MutationOption) *DeleteOneBuilder[T]

func (*DeleteOneBuilder[T]) Exec

func (b *DeleteOneBuilder[T]) Exec(ctx context.Context) error

func (*DeleteOneBuilder[T]) SQL

func (b *DeleteOneBuilder[T]) SQL() (string, []any, error)

func (*DeleteOneBuilder[T]) Where

func (b *DeleteOneBuilder[T]) Where(preds ...Pred[T]) *DeleteOneBuilder[T]

type Driver

type Driver interface {
	Query(ctx context.Context, sql string, args ...any) (Rows, error)
	Exec(ctx context.Context, sql string, args ...any) (Result, error)
	Begin(ctx context.Context, opts TxOptions) (TxDriver, error)
	Dialect() dialect.Dialect
}

Driver is the core abstraction for database query and execution.

type EagerContext

type EagerContext struct {
	Driver     Driver
	StrictScan bool
	Entity     string
}

EagerContext contains the immutable runtime settings needed by a generated eager loader. Loaders receive the same driver and scan policy as the base query, so eager loading also works inside caller-owned transactions.

type EagerOption

type EagerOption[T any] struct {
	// contains filtered or unexported fields
}

EagerOption describes one generated relationship loader.

func NewEagerOption

func NewEagerOption[T any](name string, load func(context.Context, EagerContext, []T) error) EagerOption[T]

NewEagerOption creates an eager-loading option for a generated edge.

type Edge

type Edge[S, R any] struct {
	Name          string
	SourceTable   string
	TargetTable   string
	SourceColumns []string
	TargetColumns []string
	TargetAlias   string
	SourceEntity  string
	TargetEntity  string
	Nullable      bool
}

Edge is a generated-style declared relationship descriptor. Only an Edge can be passed to Join, so composition cannot invent a column pair from SQL strings at the call site.

func NewEdge

func NewEdge[S, R any](name, sourceTable, targetTable string, sourceColumns, targetColumns []string) Edge[S, R]

NewEdge creates a declared edge descriptor.

func (Edge[S, R]) As

func (e Edge[S, R]) As(alias string) Edge[S, R]

func (Edge[S, R]) Optional

func (e Edge[S, R]) Optional() Edge[S, R]

type EnumCol

type EnumCol[T any, E any] struct {
	// contains filtered or unexported fields
}

EnumCol is a typed string-backed enum column handle.

func NewEnumCol

func NewEnumCol[T any, E any](table, column string, sensitive ...bool) EnumCol[T, E]

func (EnumCol) As

func (c EnumCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (EnumCol) Asc

func (c EnumCol) Asc() OrderTerm[T]

func (EnumCol) Desc

func (c EnumCol) Desc() OrderTerm[T]

func (EnumCol[T, E]) Eq

func (c EnumCol[T, E]) Eq(v E) Pred[T]

func (EnumCol) Expr

func (c EnumCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (EnumCol[T, E]) In

func (c EnumCol[T, E]) In(v ...E) Pred[T]

func (EnumCol) IsNull

func (c EnumCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (EnumCol[T, E]) NEq

func (c EnumCol[T, E]) NEq(v E) Pred[T]

func (EnumCol[T, E]) NotIn

func (c EnumCol[T, E]) NotIn(v ...E) Pred[T]

func (EnumCol) NotNull

func (c EnumCol) NotNull() Pred[T]

func (EnumCol) Ref

func (c EnumCol) Ref() ColumnRef

type ErrUnsupported

type ErrUnsupported struct {
	Dialect    string
	Capability dialect.Capability
	Operation  string
}

ErrUnsupported represents an error when a dialect does not support a specific capability.

func (*ErrUnsupported) Error

func (e *ErrUnsupported) Error() string

type FKCol

type FKCol[T any, R any, K any] struct {
	// contains filtered or unexported fields
}

FKCol is a typed foreign-key column handle. R and K document the related entity and key type and make accidental cross-entity predicates impossible.

func NewFKCol

func NewFKCol[T any, R any, K any](table, column string, sensitive ...bool) FKCol[T, R, K]

func (FKCol) As

func (c FKCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (FKCol) Asc

func (c FKCol) Asc() OrderTerm[T]

func (FKCol) Desc

func (c FKCol) Desc() OrderTerm[T]

func (FKCol[T, R, K]) Eq

func (c FKCol[T, R, K]) Eq(v K) Pred[T]

func (FKCol) Expr

func (c FKCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (FKCol[T, R, K]) In

func (c FKCol[T, R, K]) In(v ...K) Pred[T]

func (FKCol) IsNull

func (c FKCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (FKCol[T, R, K]) NEq

func (c FKCol[T, R, K]) NEq(v K) Pred[T]

func (FKCol[T, R, K]) NotIn

func (c FKCol[T, R, K]) NotIn(v ...K) Pred[T]

func (FKCol) NotNull

func (c FKCol) NotNull() Pred[T]

func (FKCol) Ref

func (c FKCol) Ref() ColumnRef

type IsolationLevel

type IsolationLevel string

IsolationLevel defines the SQL transaction isolation level.

const (
	IsolationDefault         IsolationLevel = ""
	IsolationReadUncommitted IsolationLevel = "read uncommitted"
	IsolationReadCommitted   IsolationLevel = "read committed"
	IsolationRepeatableRead  IsolationLevel = "repeatable read"
	IsolationSerializable    IsolationLevel = "serializable"
)

Standard SQL transaction isolation levels.

type JSONCol

type JSONCol[T any, V any] struct {
	// contains filtered or unexported fields
}

JSONCol is a typed JSON column handle.

func NewJSONCol

func NewJSONCol[T any, V any](table, column string, sensitive ...bool) JSONCol[T, V]

func (JSONCol) As

func (c JSONCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (JSONCol) Asc

func (c JSONCol) Asc() OrderTerm[T]

func (JSONCol[T, V]) ContainedBy

func (c JSONCol[T, V]) ContainedBy(v V) Pred[T]

func (JSONCol[T, V]) Contains

func (c JSONCol[T, V]) Contains(v V) Pred[T]

func (JSONCol) Desc

func (c JSONCol) Desc() OrderTerm[T]

func (JSONCol[T, V]) Eq

func (c JSONCol[T, V]) Eq(v V) Pred[T]

func (JSONCol) Expr

func (c JSONCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (JSONCol[T, V]) HasKey

func (c JSONCol[T, V]) HasKey(v string) Pred[T]

func (JSONCol) IsNull

func (c JSONCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (JSONCol) NotNull

func (c JSONCol) NotNull() Pred[T]

func (JSONCol[T, V]) PathEq

func (c JSONCol[T, V]) PathEq(path []string, v V) Pred[T]

func (JSONCol) Ref

func (c JSONCol) Ref() ColumnRef

type JoinKind

type JoinKind string

JoinKind controls the SQL join operator.

const (
	InnerJoin JoinKind = "JOIN"
	LeftJoin  JoinKind = "LEFT JOIN"
	RightJoin JoinKind = "RIGHT JOIN"
	FullJoin  JoinKind = "FULL JOIN"
)

type LoadedMany

type LoadedMany[T any] struct {
	// contains filtered or unexported fields
}

LoadedMany stores the state of an optionally eager-loaded collection edge.

func (LoadedMany[T]) Get

func (l LoadedMany[T]) Get() ([]T, bool)

Get returns a copy of the loaded values and whether the edge was loaded.

func (*LoadedMany[T]) Set

func (l *LoadedMany[T]) Set(values []T)

Set marks the edge as loaded. The supplied slice is copied.

type LoadedOne

type LoadedOne[T any] struct {
	// contains filtered or unexported fields
}

LoadedOne stores the state of an optionally eager-loaded singular edge. A zero value means that the edge has not been requested or loaded.

func (LoadedOne[T]) Get

func (l LoadedOne[T]) Get() (*T, bool)

Get returns the loaded value and whether the edge has been loaded.

func (*LoadedOne[T]) Set

func (l *LoadedOne[T]) Set(value *T)

Set marks the edge as loaded with value. A nil value represents an empty optional relationship and is different from an edge that was not loaded.

type LockMode

type LockMode string

LockMode is an explicit row-lock clause. Lock-bearing queries are accepted only by transaction-bound drivers at execution time.

const (
	LockNone   LockMode = ""
	LockUpdate LockMode = "FOR UPDATE"
	LockShare  LockMode = "FOR SHARE"
)

type MutationBatch

type MutationBatch struct {
	SQL                string
	Args               []any
	SensitivePositions []int
}

MutationBatch is one deterministic SQL batch emitted by BulkInsertBuilder.

type MutationExpr

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

MutationExpr is a typed mutation expression. Values are bound arguments; column and EXCLUDED references are quoted generated handles.

func Add

func Add(left, right MutationExpr) MutationExpr

func ArrayAppend

func ArrayAppend(array, value MutationExpr) MutationExpr

ArrayAppend emits array_append(array, value).

func Coalesce

func Coalesce(exprs ...MutationExpr) MutationExpr

Coalesce emits COALESCE with deterministic expression order.

func ColumnExpression

func ColumnExpression(expr SelectExpr) MutationExpr

ColumnExpression creates a generated column reference for an expression.

func Div

func Div(left, right MutationExpr) MutationExpr

func Excluded

func Excluded(column string) MutationExpr

Excluded references the PostgreSQL upsert EXCLUDED pseudo-table.

func ExprColumn

func ExprColumn(table, column string) MutationExpr

ExprColumn creates a generated column reference without requiring a query column handle. Generated code generally uses column.Expr() instead.

func ExprSensitiveValue

func ExprSensitiveValue[T any](value T) MutationExpr

ExprSensitiveValue creates a redacted bound mutation value.

func ExprValue

func ExprValue[T any](value T) MutationExpr

ExprValue creates a bound mutation value.

func JSONMerge

func JSONMerge(left, right MutationExpr) MutationExpr

JSONMerge emits the PostgreSQL JSONB merge operator.

func JSONPath

func JSONPath(value MutationExpr, path ...string) MutationExpr

JSONPath emits a PostgreSQL JSONB path extraction expression.

func Mul

func Mul(left, right MutationExpr) MutationExpr

func Sub

func Sub(left, right MutationExpr) MutationExpr

func VersionIncrement

func VersionIncrement(column string) MutationExpr

VersionIncrement emits a single-statement version increment.

type MutationOption

type MutationOption func(*mutationConfig)

MutationOption configures a create, update, or delete builder.

func WithMutationBatchSize

func WithMutationBatchSize(size int) MutationOption

WithMutationBatchSize configures the maximum number of rows in a bulk mutation batch.

func WithMutationConstraintLookup

func WithMutationConstraintLookup(lookup dialect.ConstraintLookup) MutationOption

WithMutationConstraintLookup supplies generated constraint metadata.

func WithMutationEntity

func WithMutationEntity(entity string) MutationOption

func WithMutationObserver

func WithMutationObserver(observer QueryObserver) MutationOption

WithMutationObserver attaches a passive observer to generated mutations.

func WithMutationParameterLimit

func WithMutationParameterLimit(limit int) MutationOption

WithMutationParameterLimit configures the maximum bind parameters per bulk mutation batch.

func WithMutationStrictScan

func WithMutationStrictScan(strict bool) MutationOption

type NamedAnnotation

type NamedAnnotation = Annotation

NamedAnnotation is retained as a descriptive alias for Annotation.

type NamedQueryOptions

type NamedQueryOptions struct {
	Name               string
	Entity             string
	ReadOnly           bool
	SensitivePositions []int
	ExpectedColumns    []string
	ExpectedOrdinals   []int
	ScanColumns        []string
	Partial            bool
	Strict             bool
	ConstraintLookup   dialect.ConstraintLookup
}

NamedQueryOptions carries generated metadata and the explicit result contract for a named SQL operation.

type NumCol

type NumCol[T any, N any] struct {
	// contains filtered or unexported fields
}

NumCol is a typed numeric column handle.

func NewNumCol

func NewNumCol[T any, N any](table, column string, sensitive ...bool) NumCol[T, N]

func (NumCol) As

func (c NumCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (NumCol) Asc

func (c NumCol) Asc() OrderTerm[T]

func (NumCol[T, N]) Between

func (c NumCol[T, N]) Between(lo, hi N) Pred[T]

func (NumCol) Desc

func (c NumCol) Desc() OrderTerm[T]

func (NumCol[T, N]) Eq

func (c NumCol[T, N]) Eq(v N) Pred[T]

func (NumCol) Expr

func (c NumCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (NumCol[T, N]) Gt

func (c NumCol[T, N]) Gt(v N) Pred[T]

func (NumCol[T, N]) Gte

func (c NumCol[T, N]) Gte(v N) Pred[T]

func (NumCol[T, N]) In

func (c NumCol[T, N]) In(v ...N) Pred[T]

func (NumCol) IsNull

func (c NumCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (NumCol[T, N]) Lt

func (c NumCol[T, N]) Lt(v N) Pred[T]

func (NumCol[T, N]) Lte

func (c NumCol[T, N]) Lte(v N) Pred[T]

func (NumCol[T, N]) NEq

func (c NumCol[T, N]) NEq(v N) Pred[T]

func (NumCol[T, N]) NotIn

func (c NumCol[T, N]) NotIn(v ...N) Pred[T]

func (NumCol) NotNull

func (c NumCol) NotNull() Pred[T]

func (NumCol) Ref

func (c NumCol) Ref() ColumnRef

type OffsetPage

type OffsetPage struct {
	Number int
	Size   int
}

OffsetPage requests a one-based page. Size is defaulted and clamped by the query's configured maximum page size.

type Operation

type Operation string

Operation represents the query/execution action type.

func ContextQueryMetadata

func ContextQueryMetadata(ctx context.Context) (entity string, op Operation)

ContextQueryMetadata retrieves the query metadata from context.

type Option

type Option func(*Config)

Option applies a configuration option.

func Lax

func Lax() Option

Lax is an option helper to disable strict scanning (equivalent to WithStrictScan(false)).

func WithCursorKey

func WithCursorKey(key []byte) Option

WithCursorKey configures the secret key used for HMAC signing of keyset cursors.

func WithMaxPageSize

func WithMaxPageSize(size int) Option

WithMaxPageSize sets the maximum limit size allowed for pagination.

func WithObserver

func WithObserver(observer QueryObserver) Option

WithObserver registers a query observer.

func WithStrictScan

func WithStrictScan(strict bool) Option

WithStrictScan enables or disables strict schema mapping during row scanning.

type OrderTerm

type OrderTerm[T any] struct {
	// contains filtered or unexported fields
}

OrderTerm describes an ordered entity column. Order terms are immutable; NullsFirst and NullsLast return modified copies.

func (OrderTerm[T]) NullsFirst

func (o OrderTerm[T]) NullsFirst() OrderTerm[T]

func (OrderTerm[T]) NullsLast

func (o OrderTerm[T]) NullsLast() OrderTerm[T]

type Page

type Page[T any] struct {
	Items    []T
	Total    int64
	Number   int
	Size     int
	Next     string
	Previous string
}

Page is returned by both pagination modes. Offset pages populate Number, Size, and Total; cursor pages populate Next and Previous.

type ParamSpec

type ParamSpec struct {
	Name      string
	Type      TypeRef
	Nullable  bool
	Sensitive bool
}

ParamSpec describes one named SQL argument. Arguments are bound in slice order, independently of the order in which placeholders appear in SQL.

type Pred

type Pred[T any] struct {
	// contains filtered or unexported fields
}

Pred represents a typed query predicate for entity T. It is a value rather than an interface so Go can infer T in expressions such as Not(postq.ID.Eq (id)) and Or(postq.Title.Eq(a), postq.Title.Eq(b)).

func And

func And[T any](preds ...Pred[T]) Pred[T]

And combines predicates using SQL AND. With no arguments it renders TRUE.

func CompareColumns

func CompareColumns[T any](left, right ColumnRef) Pred[T]

CompareColumns compares two typed column identities. It is useful for the equality predicate that connects an inner query to an outer scope.

func EdgePredicate

func EdgePredicate[S any, R any](sourceTable, sourceColumn, targetTable, targetColumn, joinTable, sourceJoinColumn, targetJoinColumn string, predicates ...Pred[R]) Pred[S]

EdgePredicate renders a correlated EXISTS predicate for a declared edge. When joinTable is empty, sourceColumn and targetColumn are compared directly between sourceTable and targetTable. When it is present, the join table is traversed using sourceJoinColumn and targetJoinColumn.

func Exists

func Exists[T, R any](s Subquery[R]) Pred[T]

Exists turns a subquery into a typed EXISTS predicate.

func InSubquery

func InSubquery[T, R any](column ownedSelectExpr[T], s Subquery[R]) Pred[T]

func NewPred

func NewPred[T any](render func(*dialect.Writer, dialect.Dialect) error) Pred[T]

NewPred creates a predicate backed by a custom renderer.

func Not

func Not[T any](pred Pred[T]) Pred[T]

Not negates a predicate.

func NotExists

func NotExists[T, R any](s Subquery[R]) Pred[T]

NotExists turns a subquery into a typed NOT EXISTS predicate.

func Or

func Or[T any](preds ...Pred[T]) Pred[T]

Or combines predicates using SQL OR. With no arguments it renders FALSE.

func RawPred

func RawPred[T any](query string, args ...any) Pred[T]

RawPred creates a raw SQL predicate that can be composed inside typed builders. The query must use the target driver's native placeholder syntax.

func (Pred[T]) Render

func (p Pred[T]) Render(w *dialect.Writer, d dialect.Dialect) error

Render writes the predicate into a shared SQL writer.

type Projection

type Projection []SelectExpr

Projection is the returning projection in a mutation plan.

func NewProjection

func NewProjection(exprs ...SelectExpr) Projection

type ProjectionSlot

type ProjectionSlot struct {
	Alias      string
	SourcePath string
	Column     string
	GoType     string
	Nullable   bool
}

ProjectionSlot is the scanner contract for one selected value.

type Query

type Query[T any] struct {
	// contains filtered or unexported fields
}

Query is an immutable, typed SELECT builder. Every builder method returns a copy, so a base query can safely be used to construct independent branches.

func Join

func Join[S, R any](q *Query[S], edge Edge[S, R], kind JoinKind) *Query[S]

Join adds a declared edge join to q.

func JoinInner

func JoinInner[S, R any](q *Query[S], edge Edge[S, R]) *Query[S]

JoinInner, JoinLeft, JoinRight, and JoinFull are readable aliases for Join.

func JoinLeft

func JoinLeft[S, R any](q *Query[S], edge Edge[S, R]) *Query[S]

func JoinOn

func JoinOn[S, R any](q *Query[S], edge Edge[S, R], kind JoinKind, predicate Pred[R]) *Query[S]

JoinOn adds a declared join and an additional typed predicate on its target entity. The edge predicate is rendered after the generated key predicate.

func JoinRight

func JoinRight[S, R any](q *Query[S], edge Edge[S, R]) *Query[S]

func NewQuery

func NewQuery[T any](drv Driver, table string, options ...QueryOption) *Query[T]

NewQuery creates a typed query for table.

func (*Query[T]) All

func (q *Query[T]) All(ctx context.Context) ([]T, error)

All executes the query and returns all matching rows.

func (*Query[T]) Count

func (q *Query[T]) Count(ctx context.Context) (int64, error)

Count returns the number of rows matching the filters. Ordering and paging are deliberately excluded from the count.

func (*Query[T]) Distinct

func (q *Query[T]) Distinct() *Query[T]

Distinct marks the query as SELECT DISTINCT.

func (*Query[T]) DistinctOn

func (q *Query[T]) DistinctOn(exprs ...SelectExpr) *Query[T]

DistinctOn marks the query as PostgreSQL-style SELECT DISTINCT ON.

func (*Query[T]) EagerManyToManySQL

func (q *Query[T]) EagerManyToManySQL(joinTable, sourceJoinColumn, targetJoinColumn, targetPrimaryKey string, sourceIDs []any) (string, []any, error)

EagerManyToManySQL builds the single batched statement used for a many-to-many eager load. The result contains all target columns plus a private source-key column named _funq_source_id. Query filters and ordering are retained; pagination is intentionally removed by EagerQuery.

func (*Query[T]) EagerQuery

func (q *Query[T]) EagerQuery() (*Query[T], int)

EagerQuery returns a copy suitable for a batched edge query and its requested per-parent limit. Global offset and limit are removed; generated loaders enforce the limit independently for each parent.

func (*Query[T]) Exist

func (q *Query[T]) Exist(ctx context.Context) (bool, error)

Exist reports whether at least one row matches.

func (*Query[T]) First

func (q *Query[T]) First(ctx context.Context) (*T, error)

First returns the first row in query order.

func (*Query[T]) ForShare

func (q *Query[T]) ForShare() *Query[T]

ForShare adds a PostgreSQL FOR SHARE row lock.

func (*Query[T]) ForUpdate

func (q *Query[T]) ForUpdate() *Query[T]

ForUpdate adds a PostgreSQL FOR UPDATE row lock.

func (*Query[T]) GroupBy

func (q *Query[T]) GroupBy(exprs ...SelectExpr) *Query[T]

func (*Query[T]) Having

func (q *Query[T]) Having(preds ...Pred[T]) *Query[T]

func (*Query[T]) IDs

func (q *Query[T]) IDs(ctx context.Context) ([]string, error)

IDs selects the configured primary-key column.

func (*Query[T]) Iterate

func (q *Query[T]) Iterate(ctx context.Context, fn func(T) error) error

Iterate calls fn for each matching entity.

func (*Query[T]) Limit

func (q *Query[T]) Limit(limit int) *Query[T]

func (*Query[T]) Nowait

func (q *Query[T]) Nowait() *Query[T]

Nowait makes the selected row lock fail immediately when a conflicting lock is held. It is valid only after ForUpdate or ForShare.

func (*Query[T]) Offset

func (q *Query[T]) Offset(offset int) *Query[T]

func (*Query[T]) One

func (q *Query[T]) One(ctx context.Context) (*T, error)

One expects exactly one row, returning ErrNotFound or ErrTooManyRows as appropriate.

func (*Query[T]) OnlyDeleted

func (q *Query[T]) OnlyDeleted() *Query[T]

func (*Query[T]) Order

func (q *Query[T]) Order(terms ...OrderTerm[T]) *Query[T]

func (*Query[T]) Paginate

func (q *Query[T]) Paginate(ctx context.Context, request any) (Page[T], error)

Paginate executes either an OffsetPage or CursorPage request.

func (*Query[T]) SQL

func (q *Query[T]) SQL() (string, []any, error)

func (*Query[T]) Select

func (q *Query[T]) Select(exprs ...SelectExpr) *Query[T]

func (*Query[T]) SkipLocked

func (q *Query[T]) SkipLocked() *Query[T]

SkipLocked makes the selected row lock skip conflicting rows. It is valid only after ForUpdate or ForShare.

func (*Query[T]) Subquery

func (q *Query[T]) Subquery() Subquery[T]

Subquery returns q as a selectable node.

func (*Query[T]) Where

func (q *Query[T]) Where(preds ...Pred[T]) *Query[T]

func (*Query[T]) With

func (q *Query[T]) With(options ...EagerOption[T]) *Query[T]

With requests one or more explicit eager-load operations. Options are immutable and are executed only by a terminal operation.

func (*Query[T]) WithCTE

func (q *Query[T]) WithCTE(ctes ...CTE) *Query[T]

WithCTE adds CTE declarations in the order supplied.

func (*Query[T]) WithDeleted

func (q *Query[T]) WithDeleted() *Query[T]

type QueryInfo

type QueryInfo struct {
	SQL             string
	Args            []any
	Duration        time.Duration
	Entity          string
	Operation       Operation
	ReadOnly        bool
	ExpectedColumns []string
	Err             error
}

QueryInfo contains diagnostic information about a completed query.

type QueryObserver

type QueryObserver interface {
	ObserveQuery(ctx context.Context, info QueryInfo)
}

QueryObserver defines the interface for passive post-query monitoring.

func ContextObserver

func ContextObserver(ctx context.Context) (QueryObserver, bool)

ContextObserver retrieves the QueryObserver from context if present.

type QueryOption

type QueryOption func(*queryConfig)

QueryOption configures a typed query created with NewQuery.

func WithQueryConstraintLookup

func WithQueryConstraintLookup(lookup dialect.ConstraintLookup) QueryOption

WithQueryConstraintLookup supplies generated constraint metadata.

func WithQueryCursorKey

func WithQueryCursorKey(key []byte) QueryOption

WithQueryCursorKey configures HMAC signing for keyset cursors.

func WithQueryEntity

func WithQueryEntity(entity string) QueryOption

func WithQueryIDColumn

func WithQueryIDColumn(column string) QueryOption

func WithQueryMaxPageSize

func WithQueryMaxPageSize(size int) QueryOption

func WithQueryObserver

func WithQueryObserver(observer QueryObserver) QueryOption

WithQueryObserver attaches a passive observer to generated query execution.

func WithQuerySoftDelete

func WithQuerySoftDelete(column string) QueryOption

func WithQueryStrictScan

func WithQueryStrictScan(strict bool) QueryOption

type QuerySpec

type QuerySpec struct {
	Name        string
	SQLFile     string
	Args        []ParamSpec
	Result      ResultSpec
	Interface   string
	ReadOnly    bool
	Annotations []NamedAnnotation

	// GoName optionally overrides the generated method and type prefix. SQL
	// operation identity remains Name.
	GoName string `json:"goName,omitempty"`
}

QuerySpec declares one named SQL operation.

type RawExecQuery

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

RawExecQuery represents a raw SQL execution query.

func RawExec

func RawExec(drv Driver, query string, args ...any) *RawExecQuery

RawExec creates a new raw SQL execution query (e.g. for mutations).

func (*RawExecQuery) Exec

func (q *RawExecQuery) Exec(ctx context.Context) (Result, error)

Exec executes the raw SQL statement.

func (*RawExecQuery) SQL

func (q *RawExecQuery) SQL() (string, []any, error)

SQL returns the native statement and its arguments.

type RawQuery

type RawQuery[T any] struct {
	// contains filtered or unexported fields
}

RawQuery represents a typed raw SQL query.

func Raw

func Raw[T any](drv Driver, query string, args ...any) *RawQuery[T]

Raw creates a new typed raw SQL query.

func (*RawQuery[T]) All

func (q *RawQuery[T]) All(ctx context.Context) ([]T, error)

All executes the query and returns all matching rows.

func (*RawQuery[T]) First

func (q *RawQuery[T]) First(ctx context.Context) (*T, error)

First executes the query, fetching at most one row, and returns ErrNotFound if no rows are returned.

func (*RawQuery[T]) Iterate

func (q *RawQuery[T]) Iterate(ctx context.Context, fn func(T) error) error

Iterate executes the query and calls fn for each row.

func (*RawQuery[T]) Lax

func (q *RawQuery[T]) Lax() *RawQuery[T]

Lax disables strict schema mapping during row scanning.

func (*RawQuery[T]) One

func (q *RawQuery[T]) One(ctx context.Context) (*T, error)

One executes the query and expects at most one row. It returns ErrNotFound if no rows are returned, and ErrTooManyRows if more than one row is returned.

func (*RawQuery[T]) SQL

func (q *RawQuery[T]) SQL() (string, []any, error)

SQL returns the native query string and its arguments.

type ReadOnlyDriver

type ReadOnlyDriver interface {
	ReadOnly() bool
}

ReadOnlyDriver marks a driver that routes reads to a replica. Lock-bearing queries reject such drivers before invoking Query.

type RelationMutation

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

RelationMutation performs attach, detach, and replace atomically on a join table. All target keys are validated before a transaction starts.

func NewRelationMutation

func NewRelationMutation(drv Driver, joinTable, parentColumn, targetColumn string, parentKey any) *RelationMutation

func (*RelationMutation) Attach

func (m *RelationMutation) Attach(ctx context.Context, targets ...any) (int64, error)

func (*RelationMutation) AttachRows

func (m *RelationMutation) AttachRows(ctx context.Context, rows ...RelationRow) (int64, error)

func (*RelationMutation) Detach

func (m *RelationMutation) Detach(ctx context.Context, targets ...any) (int64, error)

func (*RelationMutation) Replace

func (m *RelationMutation) Replace(ctx context.Context, targets ...any) (int64, error)

type RelationRow

type RelationRow struct {
	Target  any
	Payload []Assignment
}

RelationRow is one join-table row. It supports through-row payloads while preserving deterministic column order.

type RestoreBuilder

type RestoreBuilder[T any] struct {
	// contains filtered or unexported fields
}

RestoreBuilder clears a declared soft-delete field without changing the query visibility policy.

func NewRestore

func NewRestore[T any](drv Driver, table, deletedColumn string, options ...MutationOption) *RestoreBuilder[T]

func (*RestoreBuilder[T]) Exec

func (b *RestoreBuilder[T]) Exec(ctx context.Context) (int64, error)

func (*RestoreBuilder[T]) SQL

func (b *RestoreBuilder[T]) SQL() (string, []any, error)

func (*RestoreBuilder[T]) Where

func (b *RestoreBuilder[T]) Where(preds ...Pred[T]) *RestoreBuilder[T]

type Result

type Result interface {
	RowsAffected() int64
}

Result is the outcome of a database execution (non-SELECT query).

type ResultFieldSpec

type ResultFieldSpec struct {
	Name     string
	GoName   string
	Column   string
	Ordinal  int
	Type     TypeRef
	Nullable bool
	Scanner  string
}

ResultFieldSpec maps one database result column to a Go field.

type ResultMode

type ResultMode string

ResultMode controls the generated execution method for a named SQL query.

const (
	// ResultRows returns every row as a slice. It is the default mode.
	ResultRows ResultMode = "rows"
	// ResultOne returns exactly one row and reports ErrNotFound or
	// ErrTooManyRows when the cardinality does not match.
	ResultOne ResultMode = "one"
	// ResultFirst returns the first row and reports ErrNotFound for an empty
	// result.
	ResultFirst ResultMode = "first"
	// ResultIterate streams rows to a callback.
	ResultIterate ResultMode = "iterate"
	// ResultExec executes command SQL and returns affected rows.
	ResultExec ResultMode = "exec"
)

type ResultSpec

type ResultSpec struct {
	Mode   ResultMode
	Type   TypeRef
	GoName string
	Fields []ResultFieldSpec

	// Partial permits declared fields to be absent from a result projection.
	// Unknown columns remain errors.
	Partial bool
}

ResultSpec describes the explicit result mapping for a query.

type RetryOptions

type RetryOptions struct {
	MaxAttempts  int
	InitialDelay time.Duration
	MaxDelay     time.Duration
}

RetryOptions makes transaction retries explicit and bounded.

func DefaultRetryOptions

func DefaultRetryOptions() RetryOptions

DefaultRetryOptions returns a conservative bounded retry policy.

type Rows

type Rows interface {
	Next() bool
	Columns() ([]string, error)
	Values() ([]any, error)
	Close()
	Err() error
}

Rows represents the database result rows.

type SavepointDriver

type SavepointDriver interface {
	Savepoint(ctx context.Context, name string) error
	ReleaseSavepoint(ctx context.Context, name string) error
	RollbackToSavepoint(ctx context.Context, name string) error
}

SavepointDriver is implemented by transaction drivers that support nested transaction scopes without opening a second database transaction.

It is deliberately optional: drivers can continue to implement TxDriver while reporting ErrUnsupported for savepoint-dependent operations.

type SavepointOptions

type SavepointOptions struct {
	Prefix string
}

SavepointOptions controls the deterministic name prefix used by nested transaction scopes.

type Scope

type Scope struct{ Aliases []string }

Scope is the set of source aliases visible to a selectable node.

type SelectExpr

type SelectExpr interface {
	As(string) SelectExpr
	// contains filtered or unexported methods
}

SelectExpr is an expression that may appear in a SELECT or GROUP BY list. Column handles implement this interface. Computed expressions are created by the aggregate helpers below.

func As

func As(expr SelectExpr, alias string) SelectExpr

As gives a selected expression a stable SQL alias.

func Avg

func Avg(column SelectExpr) SelectExpr

Avg returns AVG(column) as a selectable expression.

func Count

func Count(column SelectExpr) SelectExpr

Count returns COUNT(column) as a selectable expression.

func CountAll

func CountAll() SelectExpr

CountAll returns COUNT(*) as a selectable expression.

func Max

func Max(column SelectExpr) SelectExpr

Max returns MAX(column) as a selectable expression.

func Min

func Min(column SelectExpr) SelectExpr

Min returns MIN(column) as a selectable expression.

func NestedProjection

func NestedProjection(prefix string, exprs ...SelectExpr) []SelectExpr

NestedProjection gives a group of expressions stable flat aliases suitable for nested destination structs.

func OuterColumn

func OuterColumn(ref ColumnRef) SelectExpr

OuterColumn renders a declared correlation reference.

func Scalar

func Scalar[T any](s Subquery[T]) SelectExpr

Scalar turns a one-column subquery into a SELECT expression.

func Slot

func Slot(expr SelectExpr, alias string, nullable ...bool) SelectExpr

Slot assigns explicit scanner metadata to an expression.

func Sum

func Sum(column SelectExpr) SelectExpr

Sum returns SUM(column) as a selectable expression.

type Selectable

type Selectable interface {
	// contains filtered or unexported methods
}

Selectable is a query node that can be used as a subquery or CTE body. Query and Subquery are the constructors provided by this package; the unexported methods deliberately prevent arbitrary SQL nodes from entering a typed composition tree.

type Shape

type Shape struct {
	Slots []ProjectionSlot
}

Shape describes the values produced by a selectable node.

type Subquery

type Subquery[T any] struct {
	Source     *Query[T]
	Shape      Shape
	Correlated []ColumnRef
	// contains filtered or unexported fields
}

Subquery is a typed selectable node. Correlate must be used to declare every outer reference used by the node.

func AsSubquery

func AsSubquery[T any](q *Query[T]) Subquery[T]

AsSubquery turns a query into a selectable node.

func (Subquery[T]) As

func (s Subquery[T]) As(alias string) Subquery[T]

As assigns the SQL alias used when the subquery is embedded in a FROM or JOIN position.

func (Subquery[T]) Correlate

func (s Subquery[T]) Correlate(refs ...ColumnRef) Subquery[T]

Correlate declares the outer columns visible to this subquery.

type TextCol

type TextCol[T any] struct {
	// contains filtered or unexported fields
}

TextCol is a typed text column handle.

func NewTextCol

func NewTextCol[T any](table, column string, sensitive ...bool) TextCol[T]

func (TextCol) As

func (c TextCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (TextCol) Asc

func (c TextCol) Asc() OrderTerm[T]

func (TextCol[T]) Contains

func (c TextCol[T]) Contains(v string) Pred[T]

func (TextCol[T]) ContainsFold

func (c TextCol[T]) ContainsFold(v string) Pred[T]

func (TextCol) Desc

func (c TextCol) Desc() OrderTerm[T]

func (TextCol[T]) Eq

func (c TextCol[T]) Eq(v string) Pred[T]

func (TextCol) Expr

func (c TextCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (TextCol[T]) HasPrefix

func (c TextCol[T]) HasPrefix(v string) Pred[T]

func (TextCol[T]) HasSuffix

func (c TextCol[T]) HasSuffix(v string) Pred[T]

func (TextCol[T]) ILike

func (c TextCol[T]) ILike(v string) Pred[T]

func (TextCol[T]) In

func (c TextCol[T]) In(v ...string) Pred[T]

func (TextCol) IsNull

func (c TextCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (TextCol[T]) Like

func (c TextCol[T]) Like(v string) Pred[T]

func (TextCol[T]) NEq

func (c TextCol[T]) NEq(v string) Pred[T]

func (TextCol[T]) NotIn

func (c TextCol[T]) NotIn(v ...string) Pred[T]

func (TextCol) NotNull

func (c TextCol) NotNull() Pred[T]

func (TextCol) Ref

func (c TextCol) Ref() ColumnRef

type TimeCol

type TimeCol[T any] struct {
	// contains filtered or unexported fields
}

TimeCol is a typed time column handle.

func NewTimeCol

func NewTimeCol[T any](table, column string, sensitive ...bool) TimeCol[T]

func (TimeCol[T]) After

func (c TimeCol[T]) After(v time.Time) Pred[T]

func (TimeCol) As

func (c TimeCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (TimeCol) Asc

func (c TimeCol) Asc() OrderTerm[T]

func (TimeCol[T]) Before

func (c TimeCol[T]) Before(v time.Time) Pred[T]

func (TimeCol[T]) Between

func (c TimeCol[T]) Between(lo, hi time.Time) Pred[T]

func (TimeCol) Desc

func (c TimeCol) Desc() OrderTerm[T]

func (TimeCol[T]) Eq

func (c TimeCol[T]) Eq(v time.Time) Pred[T]

func (TimeCol) Expr

func (c TimeCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (TimeCol) IsNull

func (c TimeCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (TimeCol) NotNull

func (c TimeCol) NotNull() Pred[T]

func (TimeCol) Ref

func (c TimeCol) Ref() ColumnRef

type TxDriver

type TxDriver interface {
	Driver
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
	Unwrap() any
}

TxDriver is a Driver that runs in the context of a transaction.

type TxOptions

type TxOptions struct {
	Isolation IsolationLevel
	ReadOnly  bool
}

TxOptions holds the options for starting a transaction.

type TypeRef

type TypeRef struct {
	PackagePath string       `json:"packagePath,omitempty"`
	Name        string       `json:"name"`
	Pointer     bool         `json:"pointer,omitempty"`
	Type        reflect.Type `json:"-"`
}

TypeRef describes a Go type used by a named SQL declaration. TypeRef values are normally created with TypeOf so the generator can preserve imports and named types without requiring the declaration package to expose strings.

func TypeOf

func TypeOf[T any]() TypeRef

TypeOf creates a generator-visible reference to T.

func TypeRefFrom

func TypeRefFrom(t reflect.Type) TypeRef

TypeRefFrom creates a generator-visible reference from a reflect type.

type UpdateBuilder

type UpdateBuilder[T any] struct {
	// contains filtered or unexported fields
}

UpdateBuilder is an explicit UPDATE builder. It returns affected rows from Exec and can also use Save to fetch a model through RETURNING *.

func NewUpdate

func NewUpdate[T any](drv Driver, table string, options ...MutationOption) *UpdateBuilder[T]

func NewUpdateOne

func NewUpdateOne[T any](drv Driver, table, idColumn string, id any, options ...MutationOption) *UpdateBuilder[T]

func (*UpdateBuilder[T]) Clear

func (b *UpdateBuilder[T]) Clear(column string) *UpdateBuilder[T]

func (*UpdateBuilder[T]) ClearSensitive

func (b *UpdateBuilder[T]) ClearSensitive(column string) *UpdateBuilder[T]

ClearSensitive clears a sensitive update field and keeps it redacted in observer notifications.

func (*UpdateBuilder[T]) Exec

func (b *UpdateBuilder[T]) Exec(ctx context.Context) (int64, error)

func (*UpdateBuilder[T]) Returning

func (b *UpdateBuilder[T]) Returning(exprs ...SelectExpr) *UpdateBuilder[T]

Returning selects a typed projection for an update mutation.

func (*UpdateBuilder[T]) SQL

func (b *UpdateBuilder[T]) SQL() (string, []any, error)

func (*UpdateBuilder[T]) Save

func (b *UpdateBuilder[T]) Save(ctx context.Context) (*T, error)

func (*UpdateBuilder[T]) Set

func (b *UpdateBuilder[T]) Set(column string, value any) *UpdateBuilder[T]

func (*UpdateBuilder[T]) SetExpr

func (b *UpdateBuilder[T]) SetExpr(column string, expression MutationExpr) *UpdateBuilder[T]

SetExpr assigns an expression without reading the current row first.

func (*UpdateBuilder[T]) SetNillable

func (b *UpdateBuilder[T]) SetNillable(column string, value any) *UpdateBuilder[T]

func (*UpdateBuilder[T]) SetNillableSensitive

func (b *UpdateBuilder[T]) SetNillableSensitive(column string, value any) *UpdateBuilder[T]

SetNillableSensitive is SetNillable with observer redaction enabled.

func (*UpdateBuilder[T]) SetSensitive

func (b *UpdateBuilder[T]) SetSensitive(column string, value any) *UpdateBuilder[T]

SetSensitive marks an update argument as sensitive for observer redaction.

func (*UpdateBuilder[T]) Where

func (b *UpdateBuilder[T]) Where(preds ...Pred[T]) *UpdateBuilder[T]

func (*UpdateBuilder[T]) WithOptimisticLock

func (b *UpdateBuilder[T]) WithOptimisticLock(column string, expected any) *UpdateBuilder[T]

WithOptimisticLock adds version = expected to the predicate and increments the version in the same UPDATE statement. Zero affected rows become ErrConflict and are never retried implicitly.

type UpsertBuilder

type UpsertBuilder[T any] struct {
	// contains filtered or unexported fields
}

UpsertBuilder renders and executes an atomic INSERT ... ON CONFLICT plan.

func NewUpsert

func NewUpsert[T any](drv Driver, table string, options ...MutationOption) *UpsertBuilder[T]

func (*UpsertBuilder[T]) DoNothing

func (b *UpsertBuilder[T]) DoNothing() *UpsertBuilder[T]

func (*UpsertBuilder[T]) Exec

func (b *UpsertBuilder[T]) Exec(ctx context.Context) (int64, error)

func (*UpsertBuilder[T]) OnColumns

func (b *UpsertBuilder[T]) OnColumns(columns ...ColumnRef) *UpsertBuilder[T]

func (*UpsertBuilder[T]) OnConflict

func (b *UpsertBuilder[T]) OnConflict(target ConflictTarget) *UpsertBuilder[T]

func (*UpsertBuilder[T]) OnConstraint

func (b *UpsertBuilder[T]) OnConstraint(name string) *UpsertBuilder[T]

func (*UpsertBuilder[T]) Plan

func (b *UpsertBuilder[T]) Plan() UpsertPlan

func (*UpsertBuilder[T]) Returning

func (b *UpsertBuilder[T]) Returning(exprs ...SelectExpr) *UpsertBuilder[T]

func (*UpsertBuilder[T]) SQL

func (b *UpsertBuilder[T]) SQL() (string, []any, error)

func (*UpsertBuilder[T]) Save

func (b *UpsertBuilder[T]) Save(ctx context.Context) (*T, error)

func (*UpsertBuilder[T]) Set

func (b *UpsertBuilder[T]) Set(column string, value any) *UpsertBuilder[T]

func (*UpsertBuilder[T]) SetExpr

func (b *UpsertBuilder[T]) SetExpr(column string, expression MutationExpr) *UpsertBuilder[T]

func (*UpsertBuilder[T]) SetSensitive

func (b *UpsertBuilder[T]) SetSensitive(column string, value any) *UpsertBuilder[T]

func (*UpsertBuilder[T]) Update

func (b *UpsertBuilder[T]) Update(assignments ...Assignment) *UpsertBuilder[T]

func (*UpsertBuilder[T]) Where

func (b *UpsertBuilder[T]) Where(pred any) *UpsertBuilder[T]

type UpsertPlan

type UpsertPlan struct {
	Insert    []Assignment
	Conflict  ConflictTarget
	Update    []Assignment
	Predicate any
	Returning Projection
}

UpsertPlan is the serializable mutation plan used by UpsertBuilder.

type ValueCol

type ValueCol[T any, V any] struct {
	// contains filtered or unexported fields
}

ValueCol is a generic scalar handle for UUID, byte, and application-defined values whose comparison type is not one of the built-in text/numeric types.

func NewValueCol

func NewValueCol[T any, V any](table, column string, sensitive ...bool) ValueCol[T, V]

NewValueCol creates a generic typed value handle.

func (ValueCol) As

func (c ValueCol) As(alias string) SelectExpr

As gives a column a SELECT alias.

func (ValueCol) Asc

func (c ValueCol) Asc() OrderTerm[T]

func (ValueCol) Desc

func (c ValueCol) Desc() OrderTerm[T]

func (ValueCol[T, V]) Eq

func (c ValueCol[T, V]) Eq(v V) Pred[T]

func (ValueCol) Expr

func (c ValueCol) Expr() MutationExpr

Expr exposes the column as a typed mutation expression. All generated column handles inherit this method through columnBase.

func (ValueCol[T, V]) In

func (c ValueCol[T, V]) In(v ...V) Pred[T]

func (ValueCol) IsNull

func (c ValueCol) IsNull() Pred[T]

IsNull and NotNull are available on every column kind.

func (ValueCol[T, V]) NEq

func (c ValueCol[T, V]) NEq(v V) Pred[T]

func (ValueCol[T, V]) NotIn

func (c ValueCol[T, V]) NotIn(v ...V) Pred[T]

func (ValueCol) NotNull

func (c ValueCol) NotNull() Pred[T]

func (ValueCol) Ref

func (c ValueCol) Ref() ColumnRef

Directories

Path Synopsis
Package bind defines dialect-neutral structures for binding untrusted input.
Package bind defines dialect-neutral structures for binding untrusted input.
dashsort
Package dashsort implements the generated allowlist-based dash-sort codec.
Package dashsort implements the generated allowlist-based dash-sort codec.
rhs
Package rhs implements the generated right-hand-side filter codec.
Package rhs implements the generated right-hand-side filter codec.
Package bindable defines opt-in schema annotations consumed by generated request binders.
Package bindable defines opt-in schema annotations consumed by generated request binders.
cmd
funq command
Command funq provides schema generation and migration tooling.
Command funq provides schema generation and migration tooling.
Package dialect defines database dialect contracts and shared SQL writing.
Package dialect defines database dialect contracts and shared SQL writing.
dialecttest
Package dialecttest provides reusable conformance tests for dialects.
Package dialecttest provides reusable conformance tests for dialects.
postgres
Package postgres implements the PostgreSQL dialect.
Package postgres implements the PostgreSQL dialect.
Package driver contains concrete adapters for Funq's root driver contracts.
Package driver contains concrete adapters for Funq's root driver contracts.
pgxdriver module
gen
Package gen loads schemas and coordinates deterministic code generation.
Package gen loads schemas and coordinates deterministic code generation.
emit
Package emit contains Funq's built-in deterministic source emitters.
Package emit contains Funq's built-in deterministic source emitters.
ir
Package ir defines Funq's stable, resolved, serializable schema graph.
Package ir defines Funq's stable, resolved, serializable schema graph.
internal
cli
Package cli implements the command-line interface while keeping command parsing separate from library behavior.
Package cli implements the command-line interface while keeping command parsing separate from library behavior.
config
Package config loads the funq.yaml project file that anchors schema, generated output, migration, and development-database locations for every CLI command.
Package config loads the funq.yaml project file that anchors schema, generated output, migration, and development-database locations for every CLI command.
testpg
Package testpg provides isolated PostgreSQL schemas for integration tests.
Package testpg provides isolated PostgreSQL schemas for integration tests.
Package migrate provides desired-state DDL, introspection, diffing, and planning.
Package migrate provides desired-state DDL, introspection, diffing, and planning.
Package schema defines declaration-time entity values.
Package schema defines declaration-time entity values.
check
Package check declares application-level SQL check constraints.
Package check declares application-level SQL check constraints.
edge
Package edge defines schema relationship builders.
Package edge defines schema relationship builders.
field
Package field defines typed schema field builders.
Package field defines typed schema field builders.
index
Package index defines schema index builders.
Package index defines schema index builders.
mixin
Package mixin defines reusable groups of schema declarations, including application-side and database-side primary-key generators.
Package mixin defines reusable groups of schema declarations, including application-side and database-side primary-key generators.
Package types defines custom value and scanner extension contracts.
Package types defines custom value and scanner extension contracts.

Jump to

Keyboard shortcuts

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