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

pgsql

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

AdvisoryLock implements primitives to use PostgreSQL's advisory locks.

These locks can be used to pipeline concurrent access between multiple database sessions. Keep in mind, both [Lock] and [TryLock] are stackable, can be called multiple times on the same session, requiring the same amount of calls to [Unlock] to free up the lock:

   var l := NewAdvisoryLock(conn, 32)
   l.Lock(context.Background()) // lock does not exist previously in this session, so locks successfully
   l.Lock(context.Background()) // lock already exists, but this increments the lock

   l.Unlock() // lock is not freed yet, as it was locked twice
   l.Unlock() // only here lock is released

See https://www.postgresql.org/docs/current/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS for more details on the specifics

of PostgreSQL advisory locks

Note: since pgxpool is used, the lock will keep a connection from the connection pool for himself; this connection is freed when the number of locked unlocks is achieved

Index

Constants

View Source
const (
	DefaultIdleConns          = 2
	DefaultMaxConns           = 4
	DefaultConnLifeTimeSecond = 3600
	DefaultConnIdleTimeSecond = 1800

	ErrEmptyDSN            = utils.Error("Empty DSN")
	ErrNilConfig           = utils.Error("Config is nil")
	ErrInvalidIdleConns    = utils.Error("Invalid idleConns")
	ErrInvalidMaxConns     = utils.Error("Invalid maxConns")
	ErrInvalidConnLifeTime = utils.Error("connLifeTime must be >= 1")
	ErrInvalidConnIdleTime = utils.Error("connIdleTime must be >= 1")
)
View Source
const (
	EngineSchema         = "public"
	MigrationTable       = "db_migration"
	EngineMigrationTable = EngineSchema + "." + MigrationTable

	MigrationLockId = 2343452349
)
View Source
const (
	// ErrInvalidSettingName is returned by WithTxSession when a setting name
	// is not a custom (dotted) PostgreSQL configuration parameter name.
	ErrInvalidSettingName = utils.Error("pgsql: invalid custom setting name")
	// ErrInvalidRoleName is returned by WithTxSession when role cannot be
	// quoted as a single identifier.
	ErrInvalidRoleName = utils.Error("pgsql: invalid role name")
	// ErrNotPostgres is returned by WithTxSession when the Querier's dialect
	// is not PostgreSQL.
	ErrNotPostgres = utils.Error("pgsql: querier dialect is not PostgreSQL")
)
View Source
const (
	SchemaDefault = "public"

	TblTypeTable        = "BASE TABLE"
	TblTypeView         = "VIEW"
	TblTypeForeignTable = "FOREIGN TABLE"
	TblTypeLocal        = "LOCAL TEMPORARY"
)

Variables

This section is empty.

Functions

func ColumnExists

func ColumnExists(ctx context.Context, client *db.SqlClient, tableName string, columnName string, schema string) (bool, error)

ColumnExists check if a column exists

func DialectOptions

func DialectOptions() *goqu.SQLDialectOptions

func ForeignTableExists

func ForeignTableExists(ctx context.Context, client *db.SqlClient, tableName string, schema string) (bool, error)

ForeignTableExists returns true if specified foreign table exists

func GetServerVersion

func GetServerVersion(db *sqlx.DB, ctx context.Context) (string, error)

GetServerVersion fetch postgresql version

func NewClient

func NewClient(config *ClientConfig) (*db.SqlClient, error)

func NewMigrationManager

func NewMigrationManager(ctx context.Context, client *db.SqlClient, opts ...PgMigrationOption) (migrations.Manager, error)

func TableExists

func TableExists(ctx context.Context, client *db.SqlClient, tableName string, schema string) (bool, error)

TableExists returns true if specified table exists

func ViewExists

func ViewExists(ctx context.Context, client *db.SqlClient, tableName string, schema string) (bool, error)

ViewExists returns true if specified view exists

func WithTxSession added in v0.10.0

func WithTxSession(ctx context.Context, q dbx.Querier, settings map[string]string, role string, fn func(tx dbx.Querier) error) error

WithTxSession runs fn inside a transaction (via dbx.WithTx) after making settings and role transaction-local:

  • each setting is applied with SELECT set_config(name, value, true), in ascending name order, with name and value as bound parameters;
  • if role is not empty, SET LOCAL ROLE switches to it (the name is quoted with the Querier's gohan dialect).

Everything is undone by PostgreSQL when the transaction ends, so nothing leaks to the next user of the pooled connection. Setting names must be custom parameter names (e.g. "app.tenant_id"; see customSettingName), no two of them equal ignoring case (PostgreSQL treats them as one setting), and role must be at most 63 bytes, without a dot, and not "*"; invalid input is rejected before any statement is sent. Setting and role names should be constants: a dotted name also matches extension settings (such as auto_explain.*), which set_config changes too. If q is already a transaction, WithTxSession joins it: the settings and role then last until that outer transaction ends, not just until fn returns.

Types

type AdvisoryLock

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

func NewAdvisoryLock

func NewAdvisoryLock(ctx context.Context, db *sqlx.DB, id int) (*AdvisoryLock, error)

func (*AdvisoryLock) Close

func (l *AdvisoryLock) Close()

func (*AdvisoryLock) Lock

func (l *AdvisoryLock) Lock(ctx context.Context) error

Lock attempts to perform a lock, and waits until it is available

func (*AdvisoryLock) TryLock

func (l *AdvisoryLock) TryLock(ctx context.Context) (bool, error)

TryLock attempts to perform a lock, and returns true if operation was successful

func (*AdvisoryLock) Unlock

func (l *AdvisoryLock) Unlock(ctx context.Context) error

Unlock unlocks a given lock Unlock of a given lock needs to be done with the same connection

type ClientConfig

type ClientConfig struct {
	DSN          string `json:"dsn"`
	MaxOpenConns int    `json:"maxOpenConns"` // MaxOpenConns max number of pool connections
	MaxIdleConns int    `json:"maxIdleConns"` // MaxIdleConns max number of idle pool connections

	// ConnLifeTime is the duration in seconds since creation after which a connection will be automatically closed
	ConnLifetime int `json:"connLifetime"`
	// ConnIdleTime is the duration in seconds after which an idle connection will be automatically closed by the health check
	ConnIdleTime int `json:"connIdleTime"`
}

func NewClientConfig

func NewClientConfig() *ClientConfig

func (ClientConfig) Apply

func (c ClientConfig) Apply(db *sqlx.DB) error

func (ClientConfig) Validate

func (c ClientConfig) Validate() error

type LockConn

type LockConn interface {
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
	Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
}

type PgMigrationOption

type PgMigrationOption func(s *pgMigrationManager) error

func WithModule

func WithModule(module string) PgMigrationOption

Jump to

Keyboard shortcuts

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