pg

package
v0.0.0-...-f0d0f3b Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2025 License: ISC Imports: 23 Imported by: 0

Documentation

Overview

Package pg is a wrapper around the pgx PostgreSQL driver, providing a higher-level client with features for connection pooling, tracing, and metrics.

Index

Constants

View Source
const (

	// BatchSizeKey represents the batch size.
	BatchSizeKey = attribute.Key("db.operation.batch.size")

	// PrepareStmtNameKey represents the prepared statement name.
	PrepareStmtNameKey = attribute.Key("pgx.prepare_stmt.name")

	// RowsAffectedKey represents the number of rows affected.
	RowsAffectedKey = attribute.Key("pgx.rows_affected")

	// SQLStateKey represents PostgreSQL error code,
	// see https://www.postgresql.org/docs/current/errcodes-appendix.html.
	SQLStateKey = attribute.Key("db.response.status_code")
)
View Source
const (
	BaseAdvisoryLockId uint32 = 42
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AdvisoryLock

type AdvisoryLock = uint32

type Client

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

Client provides a PostgreSQL client with a connection pool, logging, tracing, and Prometheus metrics registration.

func NewClient

func NewClient(options ...Option) (*Client, error)

NewClient creates a new database client with customizable options for logging, tracing, TLS, and Prometheus metrics.

Example:

client, err := pg.NewClient(
    pg.WithAddr("db.example.com:5432"),
    pg.WithUser("dbuser"),
    pg.WithPassword("password"),
)
if err != nil {
    panic(err)
}

func (*Client) Close

func (c *Client) Close()

Close closes the client's connection pool, releasing all resources.

func (*Client) RefreshTypes

func (c *Client) RefreshTypes(ctx context.Context) error

func (*Client) WithAdvisoryLock

func (c *Client) WithAdvisoryLock(
	ctx context.Context,
	id AdvisoryLock,
	f func(Conn) error,
) error

func (*Client) WithConn

func (c *Client) WithConn(
	ctx context.Context,
	exec ExecFunc,
) error

WithConn executes the given ExecFunc with a database connection from the pool.

Example:

err := client.WithConn(ctx, func(conn pg.Conn) error {
    _, err := conn.Exec(ctx, "SELECT * FROM users")
    return err
})

If tracing is enabled, this method creates a span named "WithConn" and logs any errors.

func (*Client) WithTx

func (c *Client) WithTx(
	ctx context.Context,
	exec ExecFunc,
) error

WithTx executes the given ExecFunc within a transaction. This method begins a transaction, executing `exec` within it. If `exec` returns an error, the transaction is rolled back; otherwise, it commits.

Example:

err := client.WithTx(ctx, func(tx pg.Conn) error {
    if _, err := tx.Exec(ctx, "DELETE FROM users WHERE id = $1 ", id); err != nil {
        return err
    }
    return nil
})

If tracing is enabled, this method creates a span named "WithTx" and logs any errors.

type Conn

type Conn interface {
	Exec(context.Context, string, ...any) (pgconn.CommandTag, error)

	Query(context.Context, string, ...any) (pgx.Rows, error)
	QueryRow(context.Context, string, ...any) pgx.Row

	CopyFrom(context.Context, pgx.Identifier, []string, pgx.CopyFromSource) (int64, error)
	SendBatch(context.Context, *pgx.Batch) pgx.BatchResults
}

Conn represents a PostgreSQL connection with basic methods for executing SQL commands, querying rows, performing bulk copy operations, and sending batch requests.

type ExecFunc

type ExecFunc func(Conn) error

type Option

type Option func(c *Client)

Option is a function that configures the Client during initialization.

func WithAddr

func WithAddr(addr string) Option

WithAddr specifies the database address in "host:port" format.

func WithDatabase

func WithDatabase(database string) Option

WithDatabase specifies the database to connect to.

func WithLogger

func WithLogger(l *log.Logger) Option

WithLogger sets a custom logger.

func WithPassword

func WithPassword(password string) Option

WithPassword sets the database password.

func WithPoolSize

func WithPoolSize(i int32) Option

func WithRegisterer

func WithRegisterer(r prometheus.Registerer) Option

WithRegisterer sets a custom Prometheus registerer for metrics.

func WithTLS

func WithTLS(cert *x509.Certificate) Option

WithTLS configures TLS using the provided certificate for secure connections.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) Option

WithTracerProvider configures OpenTelemetry tracing with the provided tracer provider.

func WithUser

func WithUser(user string) Option

WithUser sets the database user.

Jump to

Keyboard shortcuts

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