pg

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2025 License: MIT Imports: 7 Imported by: 0

README

PG

pg is a wrapper around the pgx library for PostgreSQL in Go. It simplifies the process of connecting to a PostgreSQL database, managing migrations, and other. This library provides a clean interface for database operations while leveraging the performance and features of pgx.

Installation

go get github.com/gosuit/pg

Features

• Connection Management: Easily establish connections to PostgreSQL databases using configurable parameters.

• Migration Support: Automatically run database migrations using the goose migration tool.

• Other: Register custom PostgreSQL types with your database connection.

• Mocking: You can create mock client with mock pgx pool

Usage

package main

import (
    "context"
    "log"

    "github.com/gosuit/pg"
)

func main() {
    ctx := context.Background()

    cfg := &pg.Config{
        Host:           "localhost",
        Port:           5432,
        DBName:         "your_database",
        Username:       "your_username",
        Password:       "your_password",
        SSLMode:        "disable",
        MigrationsRun:  true,
        MigrationsPath: "./migrations",
    }

    client, err := pg.New(ctx, cfg)
    if err != nil {
        log.Fatalf("failed to create client: %v", err)
    }

    err = client.RegisterTypes([]string{"custom_type"})
    if err != nil {
        log.Fatalf("failed to register types: %v", err)
    }

    // Use client for database operations...

    // Access underlying pgxpool
    pool := client.ToPgx()
    // Use pool...
}

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue for any enhancements or bug fixes.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTxCommitRollback = pgx.ErrTxCommitRollback
	ErrTooManyRows      = pgx.ErrTooManyRows
	ErrTxClosed         = pgx.ErrTxClosed
	ErrNoRows           = pgx.ErrNoRows
)

Functions

This section is empty.

Types

type Batch

type Batch = pgx.Batch

type BatchResults

type BatchResults = pgx.BatchResults

type Client

type Client interface {
	// Registers custom types with the database connection.
	RegisterTypes(types []string) error

	// Returns the underlying pgxpool.Pool instance.
	ToPgx() *pgxpool.Pool

	// Embeds the Pool interface for pool functionalities.
	Pool
}

Client is interface for communication with postgres database.

func New

func New(ctx context.Context, cfg *Config) (Client, error)

New creates a new Client instance and establishes a connection to the database. It parses the provided configuration and runs migrations if specified.

func NewWithMock

func NewWithMock(pool Pool) Client

NewWithMock creates a new instance of Client with the provided Mock Pool.

func NewWithPool

func NewWithPool(ctx context.Context, pool *pgxpool.Pool) (Client, error)

NewWithPool creates a new Client instance using an existing pgxpool.Pool.

type Config

type Config struct {
	Host           string `confy:"host"     yaml:"host"     json:"host"     toml:"host"     env:"PG_HOST" env-default:"localhost"`
	Port           int    `confy:"port"     yaml:"port"     json:"port"     toml:"port"     env:"PG_PORT" env-default:"5432"`
	DBName         string `confy:"dbname"   yaml:"dbname"   json:"dbname"   toml:"dbname"   env:"PG_NAME" env-default:"postgres"`
	Username       string `confy:"username" yaml:"username" json:"username" toml:"username" env:"PG_USER"`
	Password       string `confy:"password" env:"POSTGRES_PASSWORD"`
	SSLMode        string `` /* 139-byte string literal not displayed */
	MigrationsRun  bool   `` /* 137-byte string literal not displayed */
	MigrationsPath string `` /* 144-byte string literal not displayed */
}

Config is type for database connection.

type Conn

type Conn = pgx.Conn

type CopyFromSource

type CopyFromSource = pgx.CopyFromSource

type Identifier

type Identifier = pgx.Identifier

type Pool

type Pool interface {
	// Acquire returns a connection (*pgxpool.Conn) from the Pool
	Acquire(ctx context.Context) (c *pgxpool.Conn, err error)

	// AcquireFunc acquires a *pgxpool.Conn and calls f with that *pgxpool.Conn. ctx will only affect the Acquire. It has no effect on the
	// call of f. The return value is either an error acquiring the *pgxpool.Conn or the return value of f. The *pgxpool.Conn is
	// automatically released after the call of f.
	AcquireFunc(ctx context.Context, f func(*pgxpool.Conn) error) error

	// Exec acquires a connection from the Pool and executes the given SQL.
	// SQL can be either a prepared statement name or an SQL string.
	// Arguments should be referenced positionally from the SQL string as $1, $2, etc.
	// The acquired connection is returned to the pool when the Exec function returns.
	Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)

	// AcquireAllIdle atomically acquires all currently idle connections. Its intended use is for health check and
	// keep-alive functionality. It does not update pool statistics.
	AcquireAllIdle(ctx context.Context) []*pgxpool.Conn

	// QueryRow acquires a connection and executes a query that is expected
	// to return at most one row (pgx.Row). Errors are deferred until pgx.Row's
	// Scan method is called. If the query selects no rows, pgx.Row's Scan will
	// return ErrNoRows. Otherwise, pgx.Row's Scan scans the first selected row
	// and discards the rest. The acquired connection is returned to the Pool when
	// pgx.Row's Scan method is called.
	//
	// Arguments should be referenced positionally from the SQL string as $1, $2, etc.
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row

	// SendBatch sends a batch of queries to the database and returns the results.
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults

	// Query acquires a connection and executes a query that returns pgx.Rows.
	// Arguments should be referenced positionally from the SQL string as $1, $2, etc.
	// See pgx.Rows documentation to close the returned Rows and return the acquired connection to the Pool.
	//
	// If there is an error, the returned pgx.Rows will be returned in an error state.
	// If preferred, ignore the error returned from Query and handle errors using the returned pgx.Rows.
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

	// BeginTx acquires a connection from the Pool and starts a transaction with pgx.TxOptions determining the transaction mode.
	// Unlike database/sql, the context only affects the begin command. i.e. there is no auto-rollback on context cancellation.
	// *pgxpool.Tx is returned, which implements the pgx.Tx interface.
	// Commit or Rollback must be called on the returned transaction to finalize the transaction block.
	BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)

	// CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and an error.
	CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)

	// Ping acquires a connection from the Pool and executes an empty sql statement against it.
	// If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned.
	Ping(ctx context.Context) error

	// Begin acquires a connection from the Pool and starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no
	// auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see BeginTx with TxOptions if transaction mode is required).
	// *pgxpool.Tx is returned, which implements the pgx.Tx interface.
	// Commit or Rollback must be called on the returned transaction to finalize the transaction block.
	Begin(ctx context.Context) (pgx.Tx, error)

	// Stat returns a pgxpool.Stat struct with a snapshot of Pool statistics.
	Stat() *pgxpool.Stat

	// Config returns a copy of config that was used to initialize this pool.
	Config() *pgxpool.Config

	// Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would
	// disrupt all connections (such as a network interruption or a server state change).
	//
	// It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned
	// to the pool.
	Reset()

	// Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned
	// to pool and closed.
	Close()
}

Pool interface defines methods for managing a pool of database connections.

type Row

type Row = pgx.Row

type Rows

type Rows = pgx.Rows

type Stat

type Stat = pgxpool.Stat

type Tx

type Tx = pgx.Tx

type TxOptions

type TxOptions = pgx.TxOptions

Jump to

Keyboard shortcuts

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