dotpgx

package module
v0.0.0-...-e18090d Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2019 License: MIT Imports: 16 Imported by: 0

README

GoDoc Build Status Coverage Status Go Report Card

dotpgx

A Go library for parsing, mapping and executing .sql files or blobs. Inspired by projects such as dotsql, yesql and anosql.

Documentation

Overview

Package dotpgx creates a connection pool, parses and executes queries.

Index

Constants

This section is empty.

Variables

View Source
var Default = Config{
	Name:           "dotpgx_test",
	Host:           "/run/postgresql",
	Port:           5432,
	User:           "postgres",
	MaxConnections: 5,
	RunTime: dbRuntime{
		AppName: "dotpgx connection lib",
	},
}

Default config for database

Functions

This section is empty.

Types

type Batch

type Batch struct {
	// Pgx provides direct access to the pgx batch object
	Pgx *pgx.Batch
	// contains filtered or unexported fields
}

Batch represents a pgx btach and the loaded query map. Support is still primitive and limited for our own use in migrations.

func (*Batch) Close

func (b *Batch) Close() error

Close the batch operation

func (*Batch) ExecResults

func (b *Batch) ExecResults() (pgx.CommandTag, error)

ExecResults reads the results from the next query in the batch as if the query has been sent with Exec.

func (*Batch) QueryResults

func (b *Batch) QueryResults() (*pgx.Rows, error)

QueryResults reads the results from the next query in the batch as if the query has been sent with Query.

func (*Batch) QueryRowResults

func (b *Batch) QueryRowResults() *pgx.Row

QueryRowResults reads the results from the next query in the batch as if the query has been sent with QueryRow.

func (*Batch) Queue

func (b *Batch) Queue(name string, arguments []interface{}, parameterOIDs []pgtype.OID, resultFormatCodes []int16) (err error)

Queue a query by name

func (*Batch) QueueAll

func (b *Batch) QueueAll()

QueueAll the registered queries, sorted by name.

func (*Batch) Send

func (b *Batch) Send() error

Send the batch

type Config

type Config struct {
	Name           string `usage:"PostgreSQL database name"`
	Host           string `usage:"PostgreSQL host"`
	Port           uint   `usage:"Postgresql port number"`
	TLS            bool   `usage:"Enable TLS communication with database server"`
	User           string `usage:"PostgreSQL username"`
	Password       string `usage:"PostgreSQL password"`
	MaxConnections int    `usage:"Maximum DB connection pool size"`
	RunTime        dbRuntime
}

Config for database

func (Config) ConnPoolConfig

func (c Config) ConnPoolConfig() pgx.ConnPoolConfig

ConnPoolConfig parses the Config into a pgx.ConnPoolConfig

type DB

type DB struct {
	// Pool allows direct access to the underlying *pgx.ConnPool
	Pool *pgx.ConnPool
	// contains filtered or unexported fields
}

DB represents the database connection pool and parsed queries.

func InitDB

func InitDB(c Config, path string) (db *DB, err error)

InitDB is a wrapper for New() and ParsePath(). Config is the dotpgx config, which will be parsed into a pgx.ConnPoolConfig. Path is where sql queries will be parsed from.

func New

func New(conf pgx.ConnPoolConfig) (db *DB, err error)

New configures and creates a database connection pool It returns a pointer to the Database object. It returns an error only when the connection pool cannot be set-up.

An example config object would look like:

conf := pgx.ConnPoolConfig{
	ConnConfig: pgx.ConnConfig{
		Host:     pgHost,
		User:     pgUser,
		Database: pgDatabase,
		Logger:   logger,
	},
	MaxConnections: 50,
	AfterConnect:   sqlPrepare,
}

Most arguments are optional. If no logger is specified, one will get apointed automatically.

func (*DB) Begin

func (db *DB) Begin() (tx *Tx, err error)

Begin a transaction

func (*DB) BeginBatch

func (db *DB) BeginBatch() *Batch

BeginBatch starts a new pgx batch.

func (*DB) ClearMap

func (db *DB) ClearMap() (err error)

ClearMap clears the query map and sets the internal incremental counter to 0. Use this before you want to load a fresh set of queries, keeping the connection pool open. An error is only returned if one or more prepared statements failed to deallocate. It does not abbort on error and continues to (attempt) the clear the remaining queries.

func (*DB) Close

func (db *DB) Close()

Close cleans up the mapped queries and closes the pgx connection pool. It is safe to call close multiple times.

func (*DB) DropQuery

func (db *DB) DropQuery(name string) (err error)

DropQuery removes a query form the Map. It calls Pgx Deallocate if the query was a prepared statement. An error is returned only when deallocating fails. Regardless of an error, the query will be dropped from the map.

func (*DB) Exec

func (db *DB) Exec(name string, args ...interface{}) (pgx.CommandTag, error)

Exec runs the sql identified by name. Returns the result of the exec or an error.

func (*DB) HasQueries

func (db *DB) HasQueries() bool

HasQueries returns true if the are queries in the map. False in case of nil map or 0 queries.

func (*DB) List

func (db *DB) List() (index []string)

List of all registered query names, sorted

func (*DB) ParseFileGlob

func (db *DB) ParseFileGlob(glob string) error

ParseFileGlob passes all files that match glob to ParseFiles. Subsequently those files get fed into DB.ParseSql. See filepath.glob for behavior.

func (*DB) ParseFiles

func (db *DB) ParseFiles(files ...string) error

ParseFiles opens one or more files and feeds them to ParseSql

func (*DB) ParsePath

func (db *DB) ParsePath(path string) error

ParsePath is a convenience wrapper. It uses ParseFileGlob to load all files in path, with a .sql suffix.

func (*DB) ParseSQL

func (db *DB) ParseSQL(r io.Reader) error

ParseSQL parses and stores SQL queries from a io.Reader. Queries should end with a semi-colon. It stores queries by their "--name: <name>" tag. If no name tag is specified, an incremental number will be appointed. This might come in handy for sequential execution (like migrations).ParseSql Parsed queries get appended to the current map. If a name tag was already present, it will get overwritten by the new one parsed. The serial value is stored inside the DB object, so it is safe to call this function multiple times.

If the input conains a double dollar sign "$$", the parser will ignore semi-colon untill another occurance of "$$". This makes parsing of functions possible.

func (*DB) Prepare

func (db *DB) Prepare(name string) (*pgx.PreparedStatement, error)

Prepare a sql statement identified by name.

func (*DB) PrepareAll

func (db *DB) PrepareAll() (ps []*pgx.PreparedStatement, err error)

PrepareAll prepares all registered queries. It returns an error when one of the queries failed to prepare. However, it will not abort in such case and attempts to prepare the remaining statements.

func (*DB) Query

func (db *DB) Query(name string, args ...interface{}) (*pgx.Rows, error)

Query runs the sql indentified by name. Return a row set.

func (*DB) QueryRow

func (db *DB) QueryRow(name string, args ...interface{}) (*pgx.Row, error)

QueryRow runs the sql identified by name. It returns a single row. Not that an error is only returned if the query is not defined. A query error is defered untill row.Scan is run. See pgx docs for more info.

type Tx

type Tx struct {
	Ptx *pgx.Tx
	// contains filtered or unexported fields
}

Tx is transaction

func (*Tx) BeginBatch

func (tx *Tx) BeginBatch() *Batch

BeginBatch starts a new pgx batch inside the current transaction

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit the transaction

func (*Tx) Exec

func (tx *Tx) Exec(name string, args ...interface{}) (pgx.CommandTag, error)

Exec runs the sql identified by name. Returns the result of the exec or an error.

func (*Tx) Prepare

func (tx *Tx) Prepare(name string) (*pgx.PreparedStatement, error)

Prepare a sql statement identified by name.

func (*Tx) Query

func (tx *Tx) Query(name string, args ...interface{}) (*pgx.Rows, error)

Query runs the sql indentified by name. Return a row set.

func (*Tx) QueryRow

func (tx *Tx) QueryRow(name string, args ...interface{}) (*pgx.Row, error)

QueryRow runs the sql identified by name. It returns a single row. Not that an error is only returned if the query is not defined. A query error is defered untill row.Scan is run. See pgx docs for more info.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback the transaction

Jump to

Keyboard shortcuts

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