pgrepo

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2023 License: Apache-2.0 Imports: 23 Imported by: 1

README

pgrepo

pgrepo exposes tools to create, drop and connect to a Postgres database, with configurable settings.

The database abstraction used is github.com/jmoiron/sqlx which extends the standard sql library.

Settings

Settings

Default DB

Documentation

Overview

Package pgrepo provides a configurable postgres pool.

It builds a connection pool to a postgres database, with an instrumented driver for tracing.

Index

Constants

View Source
const (
	// DefaultURL points to a local test DB with user postgres.
	//
	// It is defined for a simple, workable demo setup.
	DefaultURL = "postgresql://postgres@localhost:5432/testdb?sslmode=disable"

	// DefaultDBAlias is the default configuration alias for your DB.
	//
	// This is suited for most single-DB configurations.
	DefaultDBAlias = "default"

	// DefaultLogLevel is the default log level for the database driver.
	//
	// The default is set to warn, as the pgx driver is pretty verbose in "info" mode.
	DefaultLogLevel = "warn"
)

Variables

View Source
var (
	ErrDBNotInitialized = errors.New("db not initialized")
	ErrInvalidConfig    = errors.New("invalid config")
	ErrPGAuth           = errors.New("postgres authentication error")
	ErrInvalidPGURL     = errors.New("DB URL is invalid")
)

Functions

func CreateDB

func CreateDB(parentCtx context.Context, dbName string, opts ...Option) (bool, error)

CreateDB creates a database "dbName".

NOTE: credentials to connect to the database must be sufficient to create the database.

func DefaultSettings

func DefaultSettings() *viper.Viper

DefaultSettings returns all defaults for this package as a viper registry.

This is primarily intended for documentation & help purpose.

The configuration is hierarchized like so:

databases:

postgres:
  default:
    url: postgres://localhost:5432/test
    user: $PG_USER
    password: $PG_PASSWORD
    pgconfig: # pool settings for this database
      maxIdleConns: 25
      maxOpenConns: 50
      connMaxLifetime: 5m
      pingTimeout: 10s
      log:
        level: warn
      trace:
        enabled: false
  otherDB:
    url: postgres://user:password@localhost:5433/other
    config:  # pool settings for a postgres databases
      maxIdleConns: 55
pgconfig: # pool settings for this database
  maxIdleConns: 2
  maxOpenConns: 0

func DropDB

func DropDB(parentCtx context.Context, dbName string, opts ...Option) (bool, error)

DropDB drops the database "dbName".

NOTE: credentials to connect to the database must be sufficient to drop the database.

func EnsureDB

func EnsureDB(ctx context.Context, dbName string, opts ...Option) (db *sqlx.DB, created bool, err error)

EnsureDB ensures that database "dbName" is created and returns a connection pool.

The "created" flag indicates if the database had to be freshly created or not.

NOTE: credentials to connect to the database must be sufficient to create the database.

func SetDefaults

func SetDefaults(opts ...Option)

SetDefaults sets the package-level defauts

Types

type DBOption

type DBOption func(*databaseSettings)

Option controls database settings

func WithPassword

func WithPassword(password string) DBOption

func WithPoolSettings

func WithPoolSettings(opts ...PoolOption) DBOption

func WithURL

func WithURL(url string) DBOption

func WithUser

func WithUser(user string) DBOption

type Option

type Option func(*settings)

Option controls settings for a set of databases, as well as a default pool configuration

func SettingsFromViper

func SettingsFromViper(cfg *viper.Viper, opts ...Option) (Option, error)

SettingsFromViper builds settings from a *viper.Viper configuration registry.

Extra options (e.g. WithLogger, ...) can be added.

It returns an error if the configuration cannot be unmarshalled into settings.

func WithDatabaseSettings

func WithDatabaseSettings(alias string, opts ...DBOption) Option

func WithDefaultPoolOptions

func WithDefaultPoolOptions(opts ...PoolOption) Option

func WithLogger

func WithLogger(lg *zap.Logger) Option

WithLogger injects a parent logger for logging the pgx driver and tracing operations.

func WithName

func WithName(app string) Option

WithName declares a name for the app using the DB, so the pgx logger is named.

func WithViper

func WithViper(cfg *viper.Viper) Option

WithViper is the same as SettingsFromViper, but it doesn't check for errors.

type PoolOption

type PoolOption func(*poolSettings)

PoolOption controls pool settings for a database

func WithConnMaxIdleTime

func WithConnMaxIdleTime(connMaxIdleTime time.Duration) PoolOption

func WithConnMaxLifeTime

func WithConnMaxLifeTime(connMaxLifeTime time.Duration) PoolOption

func WithLogLevel

func WithLogLevel(level string) PoolOption

func WithMaxIdleConns

func WithMaxIdleConns(maxIdleConns int) PoolOption

func WithMaxOpenConns

func WithMaxOpenConns(maxOpenConns int) PoolOption

func WithPingTimeout

func WithPingTimeout(timeout time.Duration) PoolOption

func WithSetClause

func WithSetClause(param, value string) PoolOption

func WithTracing

func WithTracing(enabled bool) PoolOption

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository knows how to handle a postgres backend database.

The database driver is instrumented for tracing.

func New

func New(dbAlias string, opts ...Option) *Repository

Newcreates a new postgres repository for one DB alias declared in the settings.

The new repository needs to be started wih Start() in order to create the connection pool.

func (Repository) ConnConfig

func (r Repository) ConnConfig(u string, lg log.Factory, app string) *pgx.ConnConfig

ConnConfig builds a pgx configuration from the URL and additional settings.

Under the hood, pgx merges standard pg parameters such as env variables and pgpass file.

func (*Repository) DB

func (r *Repository) DB() *sqlx.DB

DB master instance

func (Repository) DBURL

func (r Repository) DBURL() string

func (*Repository) HealthCheck

func (r *Repository) HealthCheck() error

HealthCheck pings the database

func (Repository) LogLevel

func (r Repository) LogLevel() tracelog.LogLevel

LogLevel returns a pgx log level from config

func (Repository) Logger

func (r Repository) Logger() log.Factory

Logger returns a logger factory

func (Repository) RedactedURL

func (r Repository) RedactedURL() string

func (Repository) SetPool

func (r Repository) SetPool(db *sql.DB)

SetPool sets the connection pool parameters from config

func (*Repository) Start

func (r *Repository) Start() error

Start a connection pool to a database, plus possibly another one to the read-only version of it

func (*Repository) Stop

func (r *Repository) Stop() error

Stop the repository and close all connection pools.

Stop may be called safely even if the database connection failed to start properly.

func (*Repository) SwitchDB added in v0.0.5

func (r *Repository) SwitchDB(dbName string) error

func (Repository) TraceOptions

func (r Repository) TraceOptions(u string) []ocsql.TraceOption

TraceOptions returns the trace options for the opencensus driver wrapper

func (Repository) Validate

func (r Repository) Validate() error

Validate the configuration

Jump to

Keyboard shortcuts

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