postgres

package module
v0.9.0 Latest Latest
Warning

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

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

Documentation

Overview

Package postgres provides PostgreSQL utilities wrapping pgx/v5.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromEnv

func FromEnv(ctx context.Context) (*pgxpool.Pool, error)

FromEnv opens a PostgreSQL pool using DATABASE_URL environment variable.

Example:

// Reads DATABASE_URL from environment
pool, err := postgres.FromEnv(ctx)

func Open

func Open(ctx context.Context, url string) (*pgxpool.Pool, error)

Open opens a PostgreSQL connection pool with default settings.

Example:

pool, err := postgres.Open(ctx, "postgres://user:pass@localhost:5432/mydb")
if err != nil {
    log.Fatal(err)
}
defer pool.Close()

var name string
err = pool.QueryRow(ctx, "SELECT name FROM users WHERE id = $1", 1).Scan(&name)

func OpenWithConfig

func OpenWithConfig(ctx context.Context, cfg Config) (*pgxpool.Pool, error)

OpenWithConfig opens a PostgreSQL connection pool with custom settings.

Example:

pool, err := postgres.OpenWithConfig(ctx, postgres.Config{
    URL:      "postgres://user:pass@localhost:5432/mydb",
    MaxConns: 50,
    MinConns: 10,
})

func Transaction

func Transaction(ctx context.Context, pool *pgxpool.Pool, fn func(tx pgx.Tx) error) error

Transaction executes a function within a PostgreSQL transaction. Automatically commits on success, rolls back on error or panic.

Example:

err := postgres.Transaction(ctx, pool, func(tx pgx.Tx) error {
    _, err := tx.Exec(ctx, "INSERT INTO users (name) VALUES ($1)", "John")
    if err != nil {
        return err
    }
    _, err = tx.Exec(ctx, "UPDATE accounts SET balance = balance - $1 WHERE user_id = $2", 100, 1)
    return err
})

Types

type Config

type Config struct {
	// URL is the connection string (required).
	// Format: postgres://user:password@host:port/database?sslmode=disable
	URL string

	// MaxConns is the maximum number of connections in the pool.
	// Default: 25
	MaxConns int32

	// MinConns is the minimum number of connections to keep open.
	// Default: 5
	MinConns int32

	// MaxConnLifetime is how long a connection can be reused.
	// Default: 1 hour
	MaxConnLifetime time.Duration

	// MaxConnIdleTime is how long a connection can be idle before closing.
	// Default: 30 minutes
	MaxConnIdleTime time.Duration

	// HealthCheckPeriod is how often to check connection health.
	// Default: 1 minute
	HealthCheckPeriod time.Duration
}

Config configures PostgreSQL connection pooling.

func DefaultConfig

func DefaultConfig(url string) Config

DefaultConfig returns production-ready defaults.

Jump to

Keyboard shortcuts

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