postgres_pgx

package module
v0.0.0-...-fa9bc59 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

Postgres PGX Plugin

A Go plugin for PostgreSQL database management using PGX driver with support for connection pooling, migrations, and test containers.

Features

  • Connection pooling with PGX
  • Database migrations support
  • Test containers integration
  • Health checks (readiness and liveness probes)
  • Configurable connection parameters
  • Automatic database creation for tests

Installation

go get github.com/lastbackend/toolkit-plugins/postgres_pgx

Usage

Basic Usage
import "github.com/lastbackend/toolkit-plugins/postgres_pgx"

func main() {
    // Initialize runtime (from your toolkit)
    rt := runtime.New()

    // Create plugin
    pg := postgres_pgx.NewPlugin(rt, &postgres_pgx.Options{
        Name: "my-postgres",
    })

    // Get database connection pool
    db := pg.DB()

    // Use the database
    // ...
}
Configuration

Configuration can be provided via environment variables:

PSQL_DSN=postgresql://user:pass@localhost:5432/dbname
# or individual parameters
PSQL_HOST=localhost
PSQL_PORT=5432
PSQL_DATABASE=dbname
PSQL_USERNAME=user
PSQL_PASSWORD=pass
PSQL_SSLMODE=disable
PSQL_MAX_POOL_SIZE=2
PSQL_CONN_ATTEMPTS=10
PSQL_CONN_TIMEOUT=15s
PSQL_MIGRATIONS_DIR=/path/to/migrations
Running Migrations
if err := pg.RunMigration(); err != nil {
    log.Fatal(err)
}
Testing with Containers
ctx := context.Background()

pg, err := postgres_pgx.NewTestPlugin(ctx, postgres_pgx.TestConfig{
    Config: postgres_pgx.Config{
        Database: "testdb",
    },
    RunContainer: true,
    // Optional container configuration
    ContainerImage: "postgres:15.2",
    ContainerName:  "my-test-postgres",
    MacConnections: 100,
})
if err != nil {
    log.Fatal(err)
}
// Use pg for testing

Configuration Options

Plugin Options
Option Description
Name Plugin name prefix for configuration
Database Config
Parameter Environment Variable Default Description
DSN PSQL_DSN "" Complete connection string
Host PSQL_HOST "127.0.0.1" Database host
Port PSQL_PORT 5432 Database port
Database PSQL_DATABASE "postgres" Database name
Username PSQL_USERNAME "postgres" Database user
Password PSQL_PASSWORD "" Database password
SSLMode PSQL_SSLMODE "disable" SSL mode
MaxPoolSize PSQL_MAX_POOL_SIZE 2 Connection pool size
ConnAttempts PSQL_CONN_ATTEMPTS 10 Connection retry attempts
ConnTimeout PSQL_CONN_TIMEOUT "15s" Connection timeout
MigrationsDir PSQL_MIGRATIONS_DIR "" Migrations directory path
Test Config
Parameter Description
RunContainer Whether to run a test container
ContainerImage Custom PostgreSQL image
ContainerName Custom container name
MacConnections Max connections limit

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PostgresPingChecker

func PostgresPingChecker(pool *pgxpool.Pool, timeout time.Duration) probes.HandleFunc

PostgresPingChecker creates a health check function for the database

Types

type Config

type Config struct {
	DSN               string        `` /* 142-byte string literal not displayed */
	Host              string        `env:"HOST" envDefault:"127.0.0.1" comment:"The host to connect to"`
	Port              int32         `env:"PORT" envDefault:"5432" comment:"The port to connect to"`
	Database          string        `env:"DATABASE" envDefault:"postgres" comment:"Database name"`
	Username          string        `env:"USERNAME" envDefault:"postgres" comment:"The username to connect with"`
	Password          string        `env:"PASSWORD" envDefault:"" comment:"The password to connect with"`
	SSLMode           string        `env:"SSLMODE" envDefault:"disable" comment:"SSL mode (disable, allow, prefer, require, verify-ca, verify-full)"`
	MaxPoolSize       int           `env:"MAX_POOL_SIZE" envDefault:"50" comment:"Max pool size"`
	MinPoolSize       int           `env:"MIN_POOL_SIZE" envDefault:"10" comment:"Min pool size"`
	MaxConnLifetime   time.Duration `env:"MAX_CONN_LIFETIME" envDefault:"1h" comment:"Maximum connection lifetime"`
	MaxConnIdleTime   time.Duration `env:"MAX_CONN_IDLE_TIME" envDefault:"30m" comment:"Maximum connection idle time"`
	HealthCheckPeriod time.Duration `env:"HEALTH_CHECK_PERIOD" envDefault:"1m" comment:"Health check period"`
	ConnAttempts      int           `env:"CONN_ATTEMPTS" envDefault:"3" comment:"Connection attempts"`
	ConnTimeout       time.Duration `env:"CONN_TIMEOUT" envDefault:"5s" comment:"Connection timeout"`
	MigrationsDir     string        `env:"MIGRATIONS_DIR" comment:"Migrations directory"`
}

Config defines the database configuration parameters

type Options

type Options struct {
	// Name is the prefix used for configuration variables
	Name string
}

Options contains plugin initialization options

type Plugin

type Plugin interface {
	// DB returns the database connection pool
	DB() *pgxpool.Pool
	// RunMigration executes database migrations from the configured directory
	RunMigration() error
}

Plugin represents a PostgreSQL database plugin interface

func NewPlugin

func NewPlugin(runtime runtime.Runtime, opts *Options) Plugin

NewPlugin creates a new instance of the PostgreSQL plugin

func NewTestPlugin

func NewTestPlugin(ctx context.Context, cfg TestConfig) (Plugin, error)

NewTestPlugin creates a plugin instance configured for testing

type PostgresContainer

type PostgresContainer interface {
	GetDSN(ctx context.Context) (string, error)
	Close(ctx context.Context) error
}

PostgresContainer defines interface for database container management

type TestConfig

type TestConfig struct {
	Config

	// RunContainer indicates whether to start a test container
	RunContainer bool
	// ContainerImage specifies custom PostgreSQL image for test container
	ContainerImage string
	// ContainerName sets custom name for test container
	ContainerName string
	// MacConnections limits maximum number of connections
	MacConnections int
}

TestConfig extends Config with additional testing-specific options

Jump to

Keyboard shortcuts

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