pgxapi

package
v0.52.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2020 License: BSD-2-Clause Imports: 19 Imported by: 1

Documentation

Overview

Package sqlapi contains a small API for a tool (sqlgen2) that generates SQL functions for specified struct types.

Lighter than a full-blown ORM and simpler than hand-written code, the output makes it easy to write flexible yet reliable and high-performance database code.

See the README for further details: https://github.com/rickb777/sqlapi/blob/master/README.md

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListTables added in v0.50.0

func ListTables(ex Execer, re *regexp.Regexp) (collection.StringList, error)

ListTables gets all the table names in the database/schema. The regular expression supplies a filter: only names that match are returned. If the regular expression is nil, all table names are returned.

func Named

func Named(name string, value interface{}) sql.NamedArg

Named creates NamedArg values; it is synonymous with sql.Named().

func NamedArgString

func NamedArgString(arg sql.NamedArg) string

NamedArgString converts the argument to a string of the form "name=value".

func ParseEnvConfig added in v0.44.0

func ParseEnvConfig() pgx.ConnPoolConfig

ParseEnvConfig creates connection pool config information based on environment variables: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGCONNECT_TIMEOUT, PGSSLMODE, PGSSLKEY, PGSSLCERT, PGSSLROOTCERT. Also available are DB_MAX_CONNECTIONS, DB_CONNECT_DELAY and DB_CONNECT_TIMEOUT.

Types

type Batcher

type Batcher interface {
	// BeginBatch exposes the pgx batch operations.
	BeginBatch() *pgx.Batch
}

Batcher provides additional methods for Postgresql batch operations.

type CanPostGet

type CanPostGet interface {
	PostGet() error
}

CanPostGet is implemented by value types that need a hook to run just after their data is fetched from the database.

type CanPreInsert

type CanPreInsert interface {
	PreInsert() error
}

CanPreInsert is implemented by value types that need a hook to run just before their data is inserted into the database.

type CanPreUpdate

type CanPreUpdate interface {
	PreUpdate() error
}

CanPreUpdate is implemented by value types that need a hook to run just before their data is updated in the database.

type CoreTable added in v0.51.0

type CoreTable struct {
	Nm TableName
	Ex Execer
}

CoreTable implements a Table.

func (CoreTable) Ctx added in v0.51.0

func (tbl CoreTable) Ctx() context.Context

func (CoreTable) DB added in v0.51.0

func (tbl CoreTable) DB() SqlDB

func (CoreTable) Dialect added in v0.51.0

func (tbl CoreTable) Dialect() dialect.Dialect

func (CoreTable) Execer added in v0.51.0

func (tbl CoreTable) Execer() Execer

func (CoreTable) IsTx added in v0.51.0

func (tbl CoreTable) IsTx() bool

func (CoreTable) Logger added in v0.51.0

func (tbl CoreTable) Logger() Logger

func (CoreTable) Name added in v0.51.0

func (tbl CoreTable) Name() TableName

func (CoreTable) Tx added in v0.51.0

func (tbl CoreTable) Tx() SqlTx

type DBStats

type DBStats = sql.DBStats

type Execer

type Execer interface {
	Getter
	Batcher

	// ExecContext executes a query without returning any rows.
	// The arguments are for any placeholder parameters in the query.
	ExecContext(ctx context.Context, sql string, arguments ...interface{}) (int64, error)

	// InsertContext executes a query and returns the insertion ID.
	// The primary key column, pk, is used for some dialects, notably PostgreSQL.
	// The arguments are for any placeholder parameters in the query.
	InsertContext(ctx context.Context, pk, query string, arguments ...interface{}) (int64, error)

	// PrepareContext creates a prepared statement for later queries or executions.
	// Multiple queries or executions may be run concurrently from the
	// returned statement.
	// The caller must call the statement's Close method
	// when the statement is no longer needed.
	//
	// The provided context is used for the preparation of the statement, not for the
	// execution of the statement.
	PrepareContext(ctx context.Context, name, sql string) (*pgx.PreparedStatement, error)

	IsTx() bool

	// Logger gets the trace logger. Note that you can use this to rotate the output writer
	// via its SetOutput method. Also, it can even disable it completely (via ioutil.Discard).
	Logger() Logger

	// Dialect gets the database dialect.
	Dialect() dialect.Dialect
}

Execer is a precis of *pgx.ConnPool and *pgx.Tx.

type Getter

type Getter interface {
	// QueryContext executes a query that returns rows, typically a SELECT.
	// The arguments are for any placeholder parameters in the query.
	// Placeholders in the SQL are automatically replaced with numbered placeholders.
	QueryContext(ctx context.Context, sql string, arguments ...interface{}) (SqlRows, error)

	// QueryExRaw directly accesses the pgx.QueryEx connection pool method, exposing
	// the query options. The placeholders will not be automatically replaced.
	QueryExRaw(ctx context.Context, sql string, options *pgx.QueryExOptions, arguments ...interface{}) (SqlRows, error)

	// QueryRowContext executes a query that is expected to return at most one row.
	// QueryRowContext always returns a non-nil value. Errors are deferred until
	// Row's Scan method is called.
	// If the query selects no rows, the *Row's Scan will return ErrNoRows.
	// Otherwise, the *Row's Scan scans the first selected row and discards
	// the rest.
	//
	// Placeholders in the SQL are automatically replaced with numbered placeholders.
	QueryRowContext(ctx context.Context, query string, arguments ...interface{}) SqlRow

	// QueryRowExRaw directly accesses the pgx.QueryRowEx connection pool method, exposing
	// the query options. The placeholders will not be automatically replaced.
	QueryRowExRaw(ctx context.Context, query string, options *pgx.QueryExOptions, arguments ...interface{}) SqlRow
}

Getter provides the core methods for reading information from databases.

type Logger

type Logger interface {
	pgx.Logger
	LogT(level pgx.LogLevel, msg string, startTime *time.Time, data ...interface{})
	LogQuery(query string, args ...interface{})
	LogIfError(err error) error
	LogError(err error) error
	TraceLogging(on bool)
}

Logger provides the specialised logging operations within this API.

func NewLogger added in v0.27.0

func NewLogger(lgr pgx.Logger) Logger

type NamedArgList

type NamedArgList []sql.NamedArg

NamedArgList holds a slice of NamedArgs

func (NamedArgList) Assignments

func (list NamedArgList) Assignments(q quote.Quoter, from int) []string

Assignments gets the assignment expressions.

func (NamedArgList) Contains

func (list NamedArgList) Contains(name string) bool

Contains tests whether anything in the list has a certain name.

func (NamedArgList) Exists

func (list NamedArgList) Exists(fn func(sql.NamedArg) bool) bool

Exists verifies that one or more elements of NamedArgList return true for the passed func.

func (NamedArgList) Find

func (list NamedArgList) Find(fn func(sql.NamedArg) bool) (sql.NamedArg, bool)

Find returns the first sql.NamedArg that returns true for some function. False is returned if none match.

func (NamedArgList) FindByName

func (list NamedArgList) FindByName(name string) (sql.NamedArg, bool)

FindByName finds the first item with a particular name.

func (NamedArgList) MkString

func (list NamedArgList) MkString(sep string) string

MkString produces a string ontainin all the values separated by sep.

func (NamedArgList) Names

func (list NamedArgList) Names() []string

Names gets all the names.

func (NamedArgList) String

func (list NamedArgList) String() string

String produces a string ontainin all the values separated by comma.

func (NamedArgList) Values

func (list NamedArgList) Values() []interface{}

Values gets all the valules

type RowData

type RowData struct {
	Fields []pgx.FieldDescription
	Data   collection.StringAnyMap
}

RowData holds a single row result from the database.

type Rows

type Rows struct {
	Rows SqlRows
	// contains filtered or unexported fields
}

Rows provides a tool for scanning result *sql.Rows of arbitrary or varying length. The internal *sql.Rows field is exported and is usable as per normal via its Next and Scan methods, or the Next and ScanToMap methods can be used instead.

func WrapRows

func WrapRows(rows SqlRows) (*Rows, error)

WrapRows wraps a *sql.Rows result so that its data can be scanned into a series of maps, one for each row.

func (*Rows) Close

func (rams *Rows) Close()

Close closes the Rows, preventing further enumeration. If Next is called and returns false and there are no further result sets, the Rows are closed automatically and it will suffice to check the result of Err. Close is idempotent and does not affect the result of Err.

func (*Rows) Err

func (rams *Rows) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.

func (*Rows) FieldDescriptions

func (rams *Rows) FieldDescriptions() []pgx.FieldDescription

func (*Rows) Next

func (rams *Rows) Next() bool

Next prepares the next result row for reading with the Scan method. It returns true on success, or false if there is no next result row or an error happened while preparing it. Err should be consulted to distinguish between the two cases.

Every call to Scan, even the first one, must be preceded by a call to Next.

func (*Rows) Scan

func (rams *Rows) Scan(dest ...interface{}) error

Scan copies the columns in the current row into the values pointed at by dest. The number of values in dest must be the same as the number of columns in the wrapped Rows.

func (*Rows) ScanToMap

func (rams *Rows) ScanToMap() (RowData, error)

ScanToMap copies all the column data of the current row into a map. The map is keyed by column name.

The result describes a single row from the database, consisting of the column names, types and data.

type SqlDB

type SqlDB interface {
	Execer

	// Transact handles a transaction according to some function. If the function completes
	// without error, the transaction will be committed automatically. If there is an error
	// or a panic, the transaction will be rolled back automatically.
	//
	// The function fn should avoid using the original SqlDB; this is easily achieved by
	// using a named function instead of an anonymous closure.
	Transact(ctx context.Context, txOptions *pgx.TxOptions, fn func(SqlTx) error) error

	// PingContext tests connectivity to the database server.
	PingContext(ctx context.Context) error

	// Stats gets statistics from the database server.
	Stats() DBStats

	// SingleConn takes exclusive use of a connection for use by the supplied function.
	// The connection will be automatically released after the function has terminated.
	SingleConn(ctx context.Context, fn func(ex Execer) error) error

	// Close closes the database connection.
	Close()

	// With returns a modified SqlDB with a user-supplied item.
	With(wrapped interface{}) SqlDB

	// UserItem gets a user-supplied item associated with this DB.
	UserItem() interface{}
}

SqlDB is able to make queries and begin transactions.

func Connect

func Connect(config pgx.ConnPoolConfig, quoter quote.Quoter) (SqlDB, error)

Connect opens a database connection and pings the server.

func ConnectEnv

func ConnectEnv(lgr pgx.Logger, logLevel pgx.LogLevel) (SqlDB, error)

ConnectEnv connects to the PostgreSQL server using environment variables: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGCONNECT_TIMEOUT, PGSSLMODE, PGSSLKEY, PGSSLCERT, PGSSLROOTCERT. Also available are PGQUOTE, DB_MAX_CONNECTIONS, DB_CONNECT_DELAY and DB_CONNECT_TIMEOUT. Use PGQUOTE to set "ansi", "mysql" or "none" as the policy for quoting identifiers (the default is none).

func MustConnect added in v0.29.0

func MustConnect(config pgx.ConnPoolConfig, quoter quote.Quoter) SqlDB

MustConnect is as per Connect but with a fatal termination on error.

func MustConnectEnv added in v0.29.0

func MustConnectEnv(lgr pgx.Logger, logLevel pgx.LogLevel) SqlDB

MustConnectEnv is as per ConnectEnv but with a fatal termination on error.

func WrapDB

func WrapDB(pool *pgx.ConnPool, lgr pgx.Logger, quoter quote.Quoter) SqlDB

WrapDB wraps a *pgx.ConnPool as SqlDB. The logger is optional and can be nil, which disables logging. The quoter is optional and can be nil, defaulting to no quotes.

type SqlRow

type SqlRow interface {
	Scan(dest ...interface{}) error
}

SqlRow is a precis of *sql.Row.

type SqlRows

type SqlRows interface {
	SqlRow

	// Next prepares the next row for reading. It returns true if there is another
	// row and false if no more rows are available. It automatically closes rows
	// when all rows are read.
	Next() bool

	FieldDescriptions() []pgx.FieldDescription

	// Values returns an array of the row values
	Values() ([]interface{}, error)

	// Close closes the rows, making the connection ready for use again. It is safe
	// to call Close after rows is already closed.
	Close()

	Err() error
}

SqlRows is a precis of *sql.Rows.

type SqlStmt

type SqlStmt interface {
	// ExecContext executes a query without returning any rows.
	// The arguments are for any placeholder parameters in the query.
	ExecContext(ctx context.Context, arguments ...interface{}) (sql.Result, error)

	// QueryContext executes a query that returns rows, typically a SELECT.
	// The arguments are for any placeholder parameters in the query.
	QueryContext(ctx context.Context, arguments ...interface{}) (*pgx.Rows, error)

	// QueryRowContext executes a query that is expected to return at most one row.
	// QueryRowContext always returns a non-nil value. Errors are deferred until
	// Row's Scan method is called.
	// If the query selects no rows, the *Row's Scan will return ErrNoRows.
	// Otherwise, the *Row's Scan scans the first selected row and discards
	// the rest.
	QueryRowContext(ctx context.Context, arguments ...interface{}) *pgx.Row

	Close() error
}

SqlStmt is a precis of *sql.Stmt

type SqlTx

type SqlTx interface {
	Execer
	Commit() error
	Rollback() error
}

SqlTx is a precis of *pgx.Tx

type Table

type Table interface {
	// Name gets the table name. without prefix
	Name() TableName

	// Execer gets the wrapped database or transaction handle.
	Execer() Execer

	// DB gets the wrapped database handle, provided this is not within a transaction.
	// Panics if it is in the wrong state - use IsTx() if necessary.
	DB() SqlDB

	// Tx gets the wrapped transaction handle, provided this is within a transaction.
	// Panics if it is in the wrong state - use IsTx() if necessary.
	Tx() SqlTx

	// IsTx tests whether this is within a transaction.
	IsTx() bool

	// Ctx gets the current request context.
	Ctx() context.Context

	// Dialect gets the database dialect.
	Dialect() dialect.Dialect

	// Logger gets the trace logger.
	Logger() Logger
}

Table provides the generic features of each generated table handler.

type TableCreator

type TableCreator interface {
	Table

	// CreateTable creates the database table.
	CreateTable(ifNotExists bool) (int64, error)

	// DropTable drops the database table.
	DropTable(ifExists bool) (int64, error)

	// Truncate empties the table
	Truncate(force bool) (err error)
}

TableCreator is a table with create/delete/truncate methods.

type TableName

type TableName struct {
	// Prefix on the table name. It can be used as the schema name, in which case
	// it should include the trailing dot. Or it can be any prefix as needed.
	Prefix string

	// The principal name of the table.
	Name string
}

TableName holds a two-part name. The prefix part is optional.

func (TableName) PrefixWithoutDot

func (tn TableName) PrefixWithoutDot() string

PrefixWithoutDot return the prefix; if this ends with a dot, the dot is removed.

func (TableName) String

func (tn TableName) String() string

String gets the full table name.

type TableWithIndexes

type TableWithIndexes interface {
	TableCreator

	// CreateIndexes creates the indexes for the database table.
	CreateIndexes(ifNotExist bool) (err error)

	// DropIndexes executes a query that drops all the indexes on the database table.
	DropIndexes(ifExist bool) (err error)

	// CreateTableWithIndexes creates the database table and its indexes.
	CreateTableWithIndexes(ifNotExist bool) (err error)
}

TableWithIndexes is a table creator with create/delete methods for the indexes.

Directories

Path Synopsis
Package constraint provides types and methods to support foreign-key relationshipd between database tables.
Package constraint provides types and methods to support foreign-key relationshipd between database tables.
Package logadapter provides a logger that writes to a log.Logger log.
Package logadapter provides a logger that writes to a log.Logger log.
Package vanilla provides a re-usable table API.
Package vanilla provides a re-usable table API.

Jump to

Keyboard shortcuts

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