postgres

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

README

go-postgres

A library that simplifies access to PostgreSQL databases.

Some considerations
  1. Despite go-postgres uses Jack Christensen's PGX library internally, it aims to act as a generic database driver like database/sql and avoid the developer to use specific PGX types and routines.
  2. Most of the commonly used types in Postgres can be mapped to standard Golang types including time.Time for timestamps (except Postgres' time with tz which is not supported)
  3. When reading JSON/JSONB fields, the code will try to unmarshall it into the destination variable. In order to just retrieve the json value as a string, add the ::text suffix to the field in the SELECT query.
  4. To avoid overflows on high uint64 values, you can store them in NUMERIC(24,0) fields.
  5. When reading time-only fields, the date part of the time.Time variable is set to January 1, 2000.

Usage with example

package main

import (
	"context"

	"github.com/randlabs/go-postgres"
)

type Data struct {
	Id   int
	Name string
}

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

	// Create database driver
	db, err := postgres.New(ctx, postgres.Options{
		Host:     "127.0.0.1",
		Port:     5432,
		User:     "postgres",
		Password: "1234",
		Name:     "sampledb",
	})
	if err != nil {
		// ....
	}
	defer db.Close()

	// Insert some data
	data := Data{
		Id:   1,
		Name: "example",
	}

	_, err = db.Exec(ctx, `INSERT INTO test_table (id, name) VALUES ($1, $2)`, data.Id, data.Name)
	if err != nil {
		// ....
	}

	// Read it
	var name string
	err = db.QueryRow(ctx, `SELECT name FROM test_table WHERE id = $1)`, 1).Scan(&name)
	if err != nil {
		// ....
		if postgres.IsNoRowsError(err) {
			// This should not happen. We cannot find the record we just inserted.
		}
	}

	// ....
}

LICENSE

See LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsDatabaseError

func IsDatabaseError(err error) bool

IsDatabaseError returns true if the given error object is a database error.

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError returns true if the error is related to a network issue.

func IsNoRowsError

func IsNoRowsError(err error) bool

IsNoRowsError returns true if the given error is the result of returning an empty result set.

func IsPostgresURL added in v1.3.0

func IsPostgresURL(rawUrl string) bool

IsPostgresURL returns true if the url schema is postgres

Types

type Conn added in v1.3.0

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

Conn encloses a single connection object.

func (*Conn) Copy added in v1.3.0

func (c *Conn) Copy(ctx context.Context, tableName string, columnNames []string, callback CopyCallback) (int64, error)

Copy executes a SQL copy query within the single connection.

func (*Conn) DB added in v1.3.0

func (c *Conn) DB() *Database

DB returns the underlying database driver.

func (*Conn) Exec added in v1.3.0

func (c *Conn) Exec(ctx context.Context, sql string, args ...interface{}) (int64, error)

Exec executes an SQL statement within the single connection.

func (*Conn) QueryRow added in v1.3.0

func (c *Conn) QueryRow(ctx context.Context, sql string, args ...interface{}) Row

QueryRow executes a SQL query within the single connection.

func (*Conn) QueryRows added in v1.3.0

func (c *Conn) QueryRows(ctx context.Context, sql string, args ...interface{}) Rows

QueryRows executes a SQL query within the single connection.

func (*Conn) WithinTx added in v1.3.0

func (c *Conn) WithinTx(ctx context.Context, cb WithinTxCallback) error

WithinTx executes a callback function within the context of a single connection.

type CopyCallback

type CopyCallback func(ctx context.Context, idx int) ([]interface{}, error)

CopyCallback defines a callback that is called for each record being copied to the database

type Database

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

Database represents a PostgreSQL database accessor.

func New

func New(ctx context.Context, opts Options) (*Database, error)

New creates a new postgresql database driver.

func NewFromURL added in v1.2.0

func NewFromURL(ctx context.Context, rawUrl string) (*Database, error)

NewFromURL creates a new postgresql database driver from an URL

func (*Database) Close

func (db *Database) Close()

Close shutdown the connection pool

func (*Database) Copy

func (db *Database) Copy(ctx context.Context, tableName string, columnNames []string, callback CopyCallback) (int64, error)

Copy executes a SQL copy query within the transaction.

func (*Database) Exec

func (db *Database) Exec(ctx context.Context, sql string, args ...interface{}) (int64, error)

Exec executes an SQL statement on a new connection

func (*Database) QueryRow

func (db *Database) QueryRow(ctx context.Context, sql string, args ...interface{}) Row

QueryRow executes a SQL query on a new connection

NOTES: ~~~~~

  1. Most of the commonly used types in Postgres can be mapped to standard Golang type including time.Time for timestamps (except time with tz which is not supported)
  2. When reading JSON/JSONB fields, the underlying library (PGX) tries to unmarshall it into the destination variable. In order to just retrieve the json string, add the `::text` suffix to the field in the query.
  3. To avoid overflows on high uint64 values, store them in NUMERIC(24,0) fields.
  4. For time-only fields, date is set to Jan 1, 2000 by PGX in time.Time variables.

func (*Database) QueryRows

func (db *Database) QueryRows(ctx context.Context, sql string, args ...interface{}) Rows

QueryRows executes a SQL query on a new connection

func (*Database) RunMigrations added in v1.3.0

func (db *Database) RunMigrations(ctx context.Context, tableName string, cb MigrationStepCallback) error

func (*Database) SetEventHandler

func (db *Database) SetEventHandler(handler ErrorHandler)

SetEventHandler sets a new error handler callback

func (*Database) WithinConn added in v1.3.0

func (db *Database) WithinConn(ctx context.Context, cb WithinConnCallback) error

WithinConn executes a callback function within the context of a single connection

func (*Database) WithinTx

func (db *Database) WithinTx(ctx context.Context, cb WithinTxCallback) error

WithinTx executes a callback function within the context of a transaction

type Error

type Error struct {
	Details *ErrorDetails
	// contains filtered or unexported fields
}

Error is the error type usually returned by us.

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type ErrorDetails added in v1.1.0

type ErrorDetails struct {
	Severity       string
	Code           string
	Message        string
	Detail         string
	Hint           string
	Position       int32
	Where          string
	SchemaName     string
	TableName      string
	ColumnName     string
	DataTypeName   string
	ConstraintName string
	File           string
	Line           int32
	Routine        string
}

type ErrorHandler

type ErrorHandler func(err error)

ErrorHandler defines a custom error handler.

type MigrationStep added in v1.3.0

type MigrationStep struct {
	// Name is a user defined name for this migration step. I.e.: "v1->v2"
	Name string

	// The index of the SQL sentence within a named block.
	SequenceNo int

	// Actual SQL sentence to execute in this migration step.
	Sql string
}

MigrationStep contains details about the SQL sentence to execute in this step. Pass an empty struct to indicate the end.

func CreateMigrationStepsFromSqlContent added in v1.3.0

func CreateMigrationStepsFromSqlContent(content string) ([]MigrationStep, error)

CreateMigrationStepsFromSqlContent creates an array of migration steps based on the provided content

The expected format is the following: # a comment with the step name (starting and ending spaces and dashes will be removed) A single SQL sentence (extra comment/sql sentence pairs)

type MigrationStepCallback added in v1.3.0

type MigrationStepCallback func(ctx context.Context, stepIdx int) (MigrationStep, error)

MigrationStepCallback is called to get the migration step details at stepIdx position (starting from 1)

type NoRowsError

type NoRowsError struct {
}

NoRowsError is the error we return if the query does not return any row.

func (*NoRowsError) Error

func (e *NoRowsError) Error() string

type Options

type Options struct {
	Host             string `json:"host"`
	Port             uint16 `json:"port"`
	User             string `json:"user"`
	Password         string `json:"password"`
	Name             string `json:"name"`
	MaxConns         int32  `json:"maxConns"`
	SSLMode          SSLMode
	ExtendedSettings map[string]string `json:"extendedSettings"`
}

Options defines the database connection options.

type Row

type Row interface {
	// Scan saves the content of the current row in the destination variables.
	Scan(dest ...interface{}) error
}

Row defines a returned record.

type Rows

type Rows interface {
	// Do calls the provided callback for each row returned by the executed query.
	Do(callback ScanRowsCallback) error
}

Rows defines a set of returned records.

type SSLMode

type SSLMode int

SSLMode states if secure communication with the server is optional or mandatory.

const (
	SSLModeAllow SSLMode = iota
	SSLModeRequired
	SSLModeDisable
)

type ScanRowsCallback

type ScanRowsCallback = func(ctx context.Context, row Row) (bool, error)

ScanRowsCallback defines a callback that is called on each row returned by the executed query.

type Tx

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

Tx encloses a transaction object.

func (*Tx) Copy

func (tx *Tx) Copy(ctx context.Context, tableName string, columnNames []string, callback CopyCallback) (int64, error)

Copy executes a SQL copy query within the transaction.

func (*Tx) DB

func (tx *Tx) DB() *Database

DB returns the underlying database driver.

func (*Tx) Exec

func (tx *Tx) Exec(ctx context.Context, sql string, args ...interface{}) (int64, error)

Exec executes an SQL statement within the transaction.

func (*Tx) QueryRow

func (tx *Tx) QueryRow(ctx context.Context, sql string, args ...interface{}) Row

QueryRow executes a SQL query within the transaction.

func (*Tx) QueryRows

func (tx *Tx) QueryRows(ctx context.Context, sql string, args ...interface{}) Rows

QueryRows executes a SQL query within the transaction.

func (*Tx) WithinTx added in v1.3.0

func (tx *Tx) WithinTx(ctx context.Context, cb WithinTxCallback) error

WithinTx executes a callback function within the context of a nested transaction.

type WithinConnCallback added in v1.3.0

type WithinConnCallback = func(ctx context.Context, conn Conn) error

WithinConnCallback defines a callback called in the context of a single connection.

type WithinTxCallback

type WithinTxCallback = func(ctx context.Context, tx Tx) error

WithinTxCallback defines a callback called in the context of the initiated transaction.

Jump to

Keyboard shortcuts

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