db

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2025 License: MIT Imports: 17 Imported by: 0

README

DB Package

Package db provides PostgreSQL database functionality using the pgx driver with built-in connection pooling, transaction management, and query logging capabilities.

Features

  • Transaction management with different isolation levels and access modes
  • Connection pooling via pgxpool
  • Query logging support
  • Tracing and metrics support
  • Large objects support (within transactions)
  • Batch operations for bulk data processing
  • Service-based architecture with start/stop lifecycle management
  • Implementation of the ITransactionInformer and ITransactionBeginner interfaces from the txmgr package

Usage

import (   
    "github.com/n-r-w/pgh/v2/px/db"
)
Creating a DB Instance
db := db.New(
    db.WithName("mydb"),
    db.WithDSN("postgres://user:password@localhost:5432/dbname"),
    db.WithLogPxDBQueries(), // Enable query logging
)

// Start the service
if err := db.Start(context.Background()); err != nil {
    log.Fatal(err)
}
defer db.Stop(context.Background())
Options

The db.New() function accepts various options to configure the database connection:

  • WithName(name string) - Sets service name for logging
  • WithDSN(dsn string) - Sets connection string
  • WithPool(pool *pgxpool.Pool) - Sets existing connection pool
  • WithConfig(cfg *pgxpool.Config) - Sets pool configuration
  • WithLogPxDBQueries() - Enables query logging
  • WithRestartPolicy(policy github.com/cenkalti/backoff/v5) - Sets restart policy on errors. Only works when using https://github.com/n-r-w/bootstrap
  • WithAfterStartFunc(f func(context.Context, *PxDB) error) - Sets function to run after successful start
  • WithLogger(logger ctxlog.ILogger) - Sets custom logger implementation
Transaction Management
err := db.Begin(ctx, func(ctxTr context.Context) error {
        // Use the database within transaction
        connection := db.Connection(ctxTr)
        
        _, err := connection.Exec(ctxTr, "INSERT INTO users (name) VALUES ($1)", "John")
        if err != nil {
            return err // Transaction will be rolled back
        }
        
        return nil // Transaction will be committed
    }, 
    txmgr.Options{}, // default options
)
Query Execution

Implements the IConnection interface from the conn package, which allows executing SQL queries, batch operations, large objects, CopyFrom, and other operations.

Telemetry Package

See the telemetry package for more information.

Support for PostgreSQL client sharding

See the sharded module for more information.

Documentation

Overview

Package db is a generated GoMock package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithoutTransaction

func WithoutTransaction(ctx context.Context) context.Context

WithoutTransaction returns context without transaction.

Types

type IConnectionGetter

type IConnectionGetter interface {
	Connection(ctx context.Context, opt ...conn.ConnectionOption) conn.IConnection
}

IConnectionGetter interface for getting connections. Created for ease of use of this package in other projects.

type IStartStopConnector

type IStartStopConnector interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
	Connection(ctx context.Context, opt ...conn.ConnectionOption) conn.IConnection
}

IStartStopConnector - interface for a service that creates IConnection and can be started and stopped.

type MockIConnectionGetter

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

MockIConnectionGetter is a mock of IConnectionGetter interface.

func NewMockIConnectionGetter

func NewMockIConnectionGetter(ctrl *gomock.Controller) *MockIConnectionGetter

NewMockIConnectionGetter creates a new mock instance.

func (*MockIConnectionGetter) Connection

Connection mocks base method.

func (*MockIConnectionGetter) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

type MockIConnectionGetterMockRecorder

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

MockIConnectionGetterMockRecorder is the mock recorder for MockIConnectionGetter.

func (*MockIConnectionGetterMockRecorder) Connection

func (mr *MockIConnectionGetterMockRecorder) Connection(ctx any, opt ...any) *gomock.Call

Connection indicates an expected call of Connection.

type MockIStartStopConnector

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

MockIStartStopConnector is a mock of IStartStopConnector interface.

func NewMockIStartStopConnector

func NewMockIStartStopConnector(ctrl *gomock.Controller) *MockIStartStopConnector

NewMockIStartStopConnector creates a new mock instance.

func (*MockIStartStopConnector) Connection

Connection mocks base method.

func (*MockIStartStopConnector) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockIStartStopConnector) Start

Start mocks base method.

func (*MockIStartStopConnector) Stop

Stop mocks base method.

type MockIStartStopConnectorMockRecorder

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

MockIStartStopConnectorMockRecorder is the mock recorder for MockIStartStopConnector.

func (*MockIStartStopConnectorMockRecorder) Connection

func (mr *MockIStartStopConnectorMockRecorder) Connection(ctx any, opt ...any) *gomock.Call

Connection indicates an expected call of Connection.

func (*MockIStartStopConnectorMockRecorder) Start

Start indicates an expected call of Start.

func (*MockIStartStopConnectorMockRecorder) Stop

Stop indicates an expected call of Stop.

type Option

type Option func(*PxDB)

Option option for PxDB.

func WithAfterStartFunc

func WithAfterStartFunc(f func(context.Context, *PxDB) error) Option

WithAfterStartFunc sets a function that will be called after successful service start.

func WithConfig

func WithConfig(cfg *pgxpool.Config) Option

WithConfig sets connection pool configuration.

func WithDSN

func WithDSN(dsn string) Option

WithDSN sets DSN for database connection. If WithConfig is used, this option is ignored.

func WithLogPxDBQueries

func WithLogPxDBQueries() Option

WithLogPxDBQueries enables query logging at the PxDB service level.

func WithLogger

func WithLogger(logger ctxlog.ILogger) Option

WithLogger sets the logger.

func WithName

func WithName(name string) Option

WithName sets service name.

func WithPool

func WithPool(pool *pgxpool.Pool) Option

WithPool sets connection pool when creating a PxDB instance.

func WithRestartPolicy

func WithRestartPolicy(policy ...backoff.RetryOption) Option

WithRestartPolicy sets service restart policy on error. Only works when using https://github.com/n-r-w/bootstrap

type PxDB

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

PxDB service for working with PostgreSQL database. Implements IService interface.

func New

func New(opt ...Option) *PxDB

New creates a new instance of PxDB.

func (*PxDB) Begin

func (p *PxDB) Begin(ctx context.Context, f func(ctxTr context.Context) error, opts txmgr.Options) (err error)

Begin runs a function within a transaction.

func (*PxDB) BeginTx

func (*PxDB) Connection

func (p *PxDB) Connection(ctx context.Context, opt ...conn.ConnectionOption) conn.IConnection

Connection extracts transaction/pool from context and returns database interface implementation. Use only at repository level. Returns IConnection interface implementation.

func (*PxDB) InTransaction

func (p *PxDB) InTransaction(ctx context.Context) bool

InTransaction returns true if transaction is started.

func (*PxDB) Info

func (p *PxDB) Info() bootstrap.Info

Info returns service information.

func (*PxDB) Start

func (p *PxDB) Start(ctx context.Context) (err error)

Start starts the service.

func (*PxDB) Stop

func (p *PxDB) Stop(_ context.Context) error

Stop stops the service.

func (*PxDB) TransactionOptions

func (p *PxDB) TransactionOptions(ctx context.Context) txmgr.Options

TransactionOptions returns transaction parameters. If transaction is not started, returns false.

func (*PxDB) WithoutTransaction

func (p *PxDB) WithoutTransaction(ctx context.Context) context.Context

WithoutTransaction returns context without transaction.

type Wrapper

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

Wrapper is a wrapper over pgx.

func (*Wrapper) CopyFrom

func (i *Wrapper) CopyFrom(ctx context.Context, tableName pgx.Identifier,
	columnNames []string, rowSrc pgx.CopyFromSource,
) (n int64, err error)

CopyFrom implements bulk data insertion into a table.

func (*Wrapper) Exec

func (i *Wrapper) Exec(ctx context.Context, sql string, args ...any) (tag pgconn.CommandTag, err error)

Exec executes a query without returning data.

func (*Wrapper) InTransaction

func (i *Wrapper) InTransaction() bool

InTransaction returns true if transaction is started.

func (*Wrapper) LargeObjects

func (i *Wrapper) LargeObjects() pgx.LargeObjects

LargeObjects supports working with large objects and is only available within a transaction (PostgreSQL limitation). Outside of a transaction, it will panic.

func (*Wrapper) Query

func (i *Wrapper) Query(ctx context.Context, sql string, args ...any) (rows pgx.Rows, err error)

Query executes a query and returns the result.

func (*Wrapper) QueryRow

func (i *Wrapper) QueryRow(ctx context.Context, sql string, args ...any) (row pgx.Row)

QueryRow gets a connection and executes a query that should return no more than one row. Errors are deferred until the pgx.Row.Scan method is called. If the query doesn't select a row, pgx.Row.Scan will return pgx.ErrNoRows. Otherwise, pgx.Row.Scan scans the first selected row and discards the rest. The obtained connection is returned to the pool when the pgx.Row.Scan method is called.

func (*Wrapper) SendBatch

func (i *Wrapper) SendBatch(ctx context.Context, b *pgx.Batch) (res pgx.BatchResults)

SendBatch sends a set of queries for execution, combining all queries into one package.

func (*Wrapper) TransactionOptions

func (i *Wrapper) TransactionOptions() txmgr.Options

TransactionOptions returns transaction parameters. If transaction is not started, returns false.

func (*Wrapper) WithoutTransaction

func (i *Wrapper) WithoutTransaction(ctx context.Context) context.Context

WithoutTransaction returns context without transaction.

Directories

Path Synopsis
Package conn is a generated GoMock package.
Package conn is a generated GoMock package.
sharded

Jump to

Keyboard shortcuts

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