Help us shape the future of Go! Take the 2026 Go Developer Survey

postgres

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidUpdatePayload = errors.New("invalid update payload: must be a struct or pointer to struct")
View Source
var ErrNoFieldsToUpdate = errors.New("no fields to update")
View Source
var ErrNoRowsAffected = errors.New("no rows affected")

Functions

func GetColumns

func GetColumns(cols []string) string

func GetColumnsWithPrefix

func GetColumnsWithPrefix(prefix string, cols []string) string

func IsUniqueConstraintError

func IsUniqueConstraintError(err error) bool

func IsUpdatePayloadEmpty

func IsUpdatePayloadEmpty(payload any) bool

IsUpdatePayloadEmpty checks if the given payload has any fields set for update.

func Open

func Open(ctx context.Context, host, port, user, password, dbname, sslmode string) (*sqlx.DB, error)

func SliceToIdsSlice

func SliceToIdsSlice[T any](items []*T, extractor func(*T) int) []int

SliceToIdsMap transforms a slice of pointers to T into a slice of ints using an extractor function. This helps with preparing the IDs for SQL ANY clauses used for child relations instead of multiple joins. Postgres filters using the ANY clause, so duplicated IDs are not an issue, but we still want to avoid unnecessary duplicates for better readibility during debugging, so we use a map to ensure uniqueness.

func SliceToIndexMap

func SliceToIndexMap[T any, K comparable](items []*T, keyExtractor func(*T) K) map[K]*T

SliceToIndexMap converts a slice of pointers to a map of pointers. It's helpful for quickly accessing items by their ID without iterating through the slice and it's primarily used in database query results merging, like associating child records with their parents.

func SliceToOptionalIdsSlice

func SliceToOptionalIdsSlice[T any](items []*T, extractor func(*T) *int) []int

SliceToOptionalIdsMap works like SliceToIdsMap but handles optional IDs (pointers to int). Sometimes we have relations that are optional, so the foreign key can be null. This function extracts only the non-nil IDs and returns them as a slice of ints.

func SliceToResponseMap

func SliceToResponseMap[T any, R any, K comparable](items []*T, extractor func(*T) (K, R)) map[K]R

SliceToResponseMap transforms a slice of pointers to T into a map of R using keyExtractor and extractor functions. It's useful in a final stage of data processing, where we take database models and convert them into response models (DTO), while also organizing them in a map for quick access by a specific key. Then at the end, the parent will use this map to associate the child records efficiently.

func SliceToStringSlice

func SliceToStringSlice[T any](items []*T, extractor func(*T) string) []string

SliceToStringSlice transforms a slice of pointers to T into a slice of strings using an extractor function. This helps with preparing the strings for SQL ANY clauses used for child relations instead of multiple joins. Postgres filters using the ANY clause, so duplicated strings are not an issue, but we still want to avoid unnecessary duplicates for better readibility during debugging, so we use a map to ensure uniqueness.

Types

type BuildWhereClausePaginationParams

type BuildWhereClausePaginationParams struct {
	// Specify the table prefix and column for time filtering, e.g.
	// "teams.created_at"
	TimeColumn string
	// Pagination parsed data
	Parsed *pagination.Parsed
}

type BuildWhereClauseParams

type BuildWhereClauseParams struct {
	// Optional, pagination related parameters
	Pagination *BuildWhereClausePaginationParams
}

type Queries

type Queries struct {
	SQLExecutor
}

func NewQueries

func NewQueries(ex SQLExecutor) *Queries

func (*Queries) BuildUpdateQuery

func (q *Queries) BuildUpdateQuery(tableName string, payload any, conditions []WhereCondition) (string, []any, error)

BuildUpdateQuery constructs an UPDATE SQL query string and its corresponding arguments based on the provided table name, payload struct, and conditions.

The payload struct should have fields tagged with `db` to indicate the corresponding database columns. Only fields that implement the UpdateItem interface and are set will be included in the SET clause of the query.

func (*Queries) BuildWhereClause

func (q *Queries) BuildWhereClause(conditions []WhereCondition, params BuildWhereClauseParams) (string, []any)

BuildWhereClause takes a slice of WhereCondition and returns a WHERE clause string and a slice of arguments. It also takes optional pagination parameters to include in the WHERE clause.

Note: The returned query should be passed through the rebind function before executing it to ensure that the placeholders are correctly formatted.

func (*Queries) Delete

func (q *Queries) Delete(query string, args ...any) error

func (*Queries) Insert added in v0.3.1

func (q *Queries) Insert(query string, args ...any) error

func (*Queries) InsertWithDest

func (q *Queries) InsertWithDest(dest any, returningColumns string, query string, args ...any) error

func (*Queries) Update added in v0.3.1

func (q *Queries) Update(query string, args ...any) error

func (*Queries) UpdateWithDest

func (q *Queries) UpdateWithDest(dest any, returningColumns string, query string, args ...any) error

type SQLExecutor

type SQLExecutor interface {
	Queryx(query string, args ...any) (*sqlx.Rows, error)
	QueryRowx(query string, args ...any) *sqlx.Row
	Exec(query string, args ...any) (sql.Result, error)
	Get(dest any, query string, args ...any) error
	Select(dest any, query string, args ...any) error
	NamedExec(query string, arg any) (sql.Result, error)
	Rebind(query string) string
}

type UpdateField

type UpdateField[T any] struct {
	// Value is the new value to set for the field. If nil, the field will be
	// set to null. If not provided, the field will remain unchanged.
	Value *T
	// False means undefined, omitted, or unchanged.
	Set bool
}

UpdateField represents a 3-state update field that can be set to a value, set to null, or left unchanged.

func (UpdateField[T]) Get

func (uf UpdateField[T]) Get() any

func (UpdateField[T]) IsSet

func (uf UpdateField[T]) IsSet() bool

type UpdateItem

type UpdateItem interface {
	IsSet() bool
	Get() any
}

type WhereCondition

type WhereCondition struct {
	// Clause can be a simple condition like "id = ?" or a complex one like
	// "name = ? OR age > ?" Use placeholders (?) for arguments instead of
	// numbers (e.g., $1, $2) as it will be handled by the rebind function.
	Clause string
	Args   []any
}

Where clause builder helps with managing WHERE clauses where e.g. pagination is involved with other filters like soft delete and query specific filters.

Jump to

Keyboard shortcuts

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