postgres

package
v0.0.0-...-7827b3b Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SQLStateUniqueViolation     = "23505"
	SQLStateForeignKeyViolation = "23503"
	SQLStateNotNullViolation    = "23502"
)

SQLSTATE коды (нужные минимум)

Variables

This section is empty.

Functions

func IsForeignKeyViolation

func IsForeignKeyViolation(err error) bool

func IsUniqueViolation

func IsUniqueViolation(err error) bool

Узкие хелперы

Types

type Client

type Client struct {
	Pool *pgxpool.Pool
}

func Open

func Open(ctx context.Context, cfg Config) (*Client, error)

Открыть по высокоуровневому Config (URL + pool options).

func OpenWithDBConfig

func OpenWithDBConfig(ctx context.Context, dbCfg DBConfig) (*Client, error)

Открыть по структурному DBConfig (host/port/user/...). Собирает URL внутри и переносит пул-настройки из DBConfig.

func (*Client) Close

func (c *Client) Close()

func (*Client) RunnerFromPool

func (c *Client) RunnerFromPool() Runner

RunnerFromPool — получить Runner для пула (вне транзакции).

func (*Client) WithSavepoint

func (c *Client) WithSavepoint(ctx context.Context, run Runner, fn func(run Runner) error) error

WithSavepoint — если уже внутри транзакции, создаёт SAVEPOINT; иначе откроет обычную TX.

func (*Client) WithSerializable

func (c *Client) WithSerializable(ctx context.Context, maxRetries int, fn func(run Runner) error) error

WithSerializable — SERIALIZABLE + авто-ретраи на 40001 (serialization_failure), учитывает ctx.

func (*Client) WithSerializableRO

func (c *Client) WithSerializableRO(ctx context.Context, deferrable bool, fn func(run Runner) error) error

Удобный хелпер: SERIALIZABLE + ReadOnly + (опц.) DEFERRABLE

func (*Client) WithTx

func (c *Client) WithTx(ctx context.Context, fn func(run Runner) error) (err error)

WithTx — безопасная (panic-safe) транзакция с дефолтными опциями (ReadCommitted, RW).

func (*Client) WithTxOpts

func (c *Client) WithTxOpts(ctx context.Context, cfg TxConfig, fn func(run Runner) error) (err error)

WithTxOpts — транзакция с опциями + panic-safe commit/rollback + локальные SET LOCAL таймауты.

func (*Client) WithTxRO

func (c *Client) WithTxRO(ctx context.Context, fn func(run Runner) error) error

WithTxRO — Read-Only транзакция (для консистентных чтений в несколько запросов).

type Config

type Config struct {
	URL    string            // postgres://user:pass@host:port/dbname?sslmode=disable
	Params map[string]string // доп.параметры для URL (перезаписывают query)

	// Параметры пула
	MaxConns          int32
	MinConns          int32
	MaxConnLifetime   time.Duration
	MaxConnIdleTime   time.Duration
	HealthCheckPeriod time.Duration
}

Высокоуровневый конфиг — через готовый URL. Оставляем для кейсов со сложными DSN и обратной совместимости.

type ConstraintInfo

type ConstraintInfo struct {
	Code     string // SQLSTATE (e.g. 23505)
	Name     string // constraint name from PG
	Schema   string // optional: pgErr.SchemaName
	Table    string // optional: pgErr.TableName
	Detail   string // optional: pgErr.Detail
	IsUnique bool
}

func Constraint

func Constraint(err error) (ConstraintInfo, bool)

type DBConfig

type DBConfig struct {
	Host            string
	Port            string
	User            string
	Password        string
	DBName          string
	SSLMode         string
	MaxOpenConns    int           // максимум коннекций в пуле
	MaxIdleConns    int           // минимум (минимальный размер пула)
	ConnMaxLifetime time.Duration // переоткрывать коннект не реже чем
	ConnMaxIdleTime time.Duration // держать idle не дольше чем
}

Низкоуровневый конфиг подключения (host/port/...). Удобен в приложениях: читаем ENV → передаём сюда → остальное сделает библиотека.

type Runner

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

Runner — единый интерфейс для пула и транзакции.

type TxConfig

type TxConfig struct {
	Iso        pgx.TxIsoLevel // default: ReadCommitted
	ReadOnly   bool           // default: false
	Deferrable bool           // работает только с SERIALIZABLE (в PG имеет смысл для read-only)

	// Локальные таймауты (SET LOCAL ...), если нужны на время TX
	StatementTimeout         time.Duration // общий timeout каждого стейтмента
	IdleInTransactionTimeout time.Duration // idle_in_transaction_session_timeout
}

TxConfig — дополнительные настройки транзакции.

Jump to

Keyboard shortcuts

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