pgquery

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package pgquery provides PostgreSQL helpers: SQL query building (Builder) and generic PG SQLSTATE wire-error classification (IsUniqueViolation / IsForeignKeyViolation). Business-specific classification (e.g. last-admin trigger sentinel) belongs in the cell-internal adapter package that owns the corresponding migration.

Index

Constants

View Source
const (
	// SQLStateUniqueViolation is class 23 / 23505 (unique constraint).
	// pgconn.PgError.Code carries this value verbatim.
	SQLStateUniqueViolation = "23505"
	// SQLStateForeignKeyViolation is class 23 / 23503.
	SQLStateForeignKeyViolation = "23503"
	// SQLStateRaiseException is the catch-all class P0001 used by
	// PL/pgSQL `RAISE EXCEPTION`.
	SQLStateRaiseException = "P0001"
)

PG SQLSTATE codes used by repo error classifiers. PG codes are stable identifiers and are not language-dependent, so ad-hoc string compares are the idiomatic Go convention.

ref: https://www.postgresql.org/docs/current/errcodes-appendix.html

Variables

This section is empty.

Functions

func AppendKeyset

func AppendKeyset(b *Builder, params query.ListParams) error

AppendKeyset appends keyset pagination clauses (WHERE + ORDER BY + LIMIT) to a Builder. It integrates with any existing WHERE conditions via AND.

When CursorValues is nil (first page), only ORDER BY and LIMIT are appended. When CursorValues is set, a keyset WHERE clause is generated:

  • Same direction columns: tuple comparison (col1, col2) > ($1, $2)
  • Mixed direction columns: compound OR

LIMIT is set to params.FetchLimit() (Limit+1) for N+1 hasMore detection.

Callers should ensure a composite index exists on the sort columns in the specified directions (e.g. CREATE INDEX idx ON table (col1 DESC, col2 ASC)) for efficient keyset pagination. Without such an index, the database will perform a full table sort on every page request.

func AsRaiseException

func AsRaiseException(err error) (*pgconn.PgError, bool)

AsRaiseException returns the unwrapped *pgconn.PgError if err (or any error in its Unwrap chain) is a PL/pgSQL RAISE EXCEPTION (SQLSTATE P0001), so callers that need both the SQLSTATE classification AND the trigger Message attribution can do so in a single Unwrap walk. ok=false when err is nil, not a pgconn.PgError, or carries a different SQLSTATE.

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

IsForeignKeyViolation reports whether err (or any error in its Unwrap chain) is a PG foreign-key violation (SQLSTATE 23503). Used by role_assignments to classify a delete that would orphan downstream rows.

func IsRaiseException

func IsRaiseException(err error) bool

IsRaiseException reports whether err (or any error in its Unwrap chain) is a PL/pgSQL RAISE EXCEPTION (SQLSTATE P0001). P0001 is the generic class used by any RAISE EXCEPTION site, so a true result only tells the caller the error originated from a trigger/function RAISE — callers that need to attribute it to a specific trigger must additionally inspect pgconn.PgError.Message (e.g. accesscore isLastAdminProtected matches the trigger message prefix). Keeping the SQLSTATE classification here keeps pkg/pgquery the single source for PG error-code knowledge.

func IsUniqueViolation

func IsUniqueViolation(err error) bool

IsUniqueViolation reports whether err (or any error in its Unwrap chain) is a PG unique-constraint violation (SQLSTATE 23505). Repo callers wrap the result as a domain ErrAuth*Duplicate to keep the wire-level errcode stable across mem and PG backends.

Types

type Builder

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

Builder assists in constructing parameterized PostgreSQL queries. It tracks positional parameters ($1, $2, ...) and their values.

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates an empty Builder.

func (*Builder) Append

func (b *Builder) Append(sql string) *Builder

Append adds a raw SQL fragment to the query.

func (*Builder) AppendIf

func (b *Builder) AppendIf(condition bool, sqlPrefix string, value any) *Builder

AppendIf conditionally appends a parameterized clause. This is useful for optional WHERE conditions.

func (*Builder) AppendParam

func (b *Builder) AppendParam(sqlPrefix string, value any) *Builder

AppendParam adds a SQL fragment containing a single positional parameter and its value. The placeholder $N is inserted automatically.

func (*Builder) Args

func (b *Builder) Args() []any

Args returns a copy of the current argument slice. The returned slice is safe to hold across Reset() calls.

func (*Builder) Build

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

Build returns the assembled SQL string and a copy of the argument slice. The returned args are safe to hold across Reset() calls.

func (*Builder) NextParam

func (b *Builder) NextParam(value any) string

NextParam registers value as the next positional argument and returns its placeholder string (e.g. "$3"). Useful when building complex clauses where AppendParam's single-prefix pattern is insufficient.

func (*Builder) Reset

func (b *Builder) Reset() *Builder

Reset clears the builder for reuse.

func (*Builder) SQL

func (b *Builder) SQL() string

SQL returns the current query string without arguments.

Jump to

Keyboard shortcuts

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