Documentation
¶
Overview ¶
Package postgres provides PostgreSQL utilities wrapping pgx/v5.
Index ¶
- func FromEnv(ctx context.Context) (*pgxpool.Pool, error)
- func Open(ctx context.Context, url string) (*pgxpool.Pool, error)
- func OpenWithConfig(ctx context.Context, cfg Config) (*pgxpool.Pool, error)
- func Transaction(ctx context.Context, pool *pgxpool.Pool, fn func(tx pgx.Tx) error) error
- type Config
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FromEnv ¶
FromEnv opens a PostgreSQL pool using DATABASE_URL environment variable.
Example:
// Reads DATABASE_URL from environment pool, err := postgres.FromEnv(ctx)
func Open ¶
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 ¶
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 ¶
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 ¶
DefaultConfig returns production-ready defaults.
Click to show internal directories.
Click to hide internal directories.