Documentation
¶
Index ¶
- Constants
- func IsForeignKeyViolation(err error) bool
- func IsUniqueViolation(err error) bool
- type Client
- func (c *Client) Close()
- func (c *Client) RunnerFromPool() Runner
- func (c *Client) WithSavepoint(ctx context.Context, run Runner, fn func(run Runner) error) error
- func (c *Client) WithSerializable(ctx context.Context, maxRetries int, fn func(run Runner) error) error
- func (c *Client) WithSerializableRO(ctx context.Context, deferrable bool, fn func(run Runner) error) error
- func (c *Client) WithTx(ctx context.Context, fn func(run Runner) error) (err error)
- func (c *Client) WithTxOpts(ctx context.Context, cfg TxConfig, fn func(run Runner) error) (err error)
- func (c *Client) WithTxRO(ctx context.Context, fn func(run Runner) error) error
- type Config
- type ConstraintInfo
- type DBConfig
- type Runner
- type TxConfig
Constants ¶
const ( SQLStateUniqueViolation = "23505" SQLStateForeignKeyViolation = "23503" SQLStateNotNullViolation = "23502" )
SQLSTATE коды (нужные минимум)
Variables ¶
This section is empty.
Functions ¶
func IsForeignKeyViolation ¶
Types ¶
type Client ¶
func OpenWithDBConfig ¶
Открыть по структурному DBConfig (host/port/user/...). Собирает URL внутри и переносит пул-настройки из DBConfig.
func (*Client) RunnerFromPool ¶
RunnerFromPool — получить Runner для пула (вне транзакции).
func (*Client) WithSavepoint ¶
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 ¶
WithTx — безопасная (panic-safe) транзакция с дефолтными опциями (ReadCommitted, RW).
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 — дополнительные настройки транзакции.