db

package
v0.0.0-...-ab31a86 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2024 License: MIT Imports: 14 Imported by: 6

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	IgnoreDefault           = sqldb.IgnoreDefault
	IgnorePrimaryKey        = sqldb.IgnorePrimaryKey
	IgnoreReadOnly          = sqldb.IgnoreReadOnly
	IgnoreNull              = sqldb.IgnoreNull
	IgnoreNullOrZero        = sqldb.IgnoreNullOrZero
	IgnoreNullOrZeroDefault = sqldb.IgnoreNullOrZeroDefault
)
View Source
var (
	// Number of retries used for a SerializedTransaction
	// before it fails
	SerializedTransactionRetries = 10
)

Functions

func Conn

func Conn(ctx context.Context) sqldb.Connection

Conn returns a non nil sqldb.Connection from ctx or the global connection set with SetConn. The returned connection will use the passed context. See sqldb.Connection.WithContext

func ConnDefault

func ConnDefault(ctx context.Context, defaultConn sqldb.Connection) sqldb.Connection

ConnDefault returns a non nil sqldb.Connection from ctx or the passed defaultConn. The returned connection will use the passed context. See sqldb.Connection.WithContext

func ContextWithConn

func ContextWithConn(ctx context.Context, conn sqldb.Connection) context.Context

ContextWithConn returns a new context with the passed sqldb.Connection added as value so it can be retrieved again using Conn(ctx). Passing a nil connection causes Conn(ctx) to return the global connection set with SetConn.

func DebugNoTransaction

func DebugNoTransaction(ctx context.Context, nonTxFunc func(context.Context) error) error

DebugNoTransaction executes nonTxFunc without a database transaction. Useful to temporarely replace Transaction to debug the same code without using a transaction.

func DebugPrintConn

func DebugPrintConn(ctx context.Context, args ...any)

DebugPrintConn prints a line to stderr using the passed args and appending the transaction state of the connection and the current time of the database using `select now()` or an error if the time could not be queried.

func Exec

func Exec(ctx context.Context, query string, args ...any) error

Exec executes a query with optional args.

func FprintTable

func FprintTable(w io.Writer, rows [][]string, columnDelimiter string) error

FprintTable prints a string table to an io.Writer padding the table with spaces and using the passed columnDelimiter between columns.

func GetRow

func GetRow[S any](ctx context.Context, pkValue any, pkValues ...any) (row *S, err error)

GetRow uses the passed pkValue+pkValues to query a table row and scan it into a struct of type S that must have tagged fields with primary key flags to identify the primary key column names for the passed pkValue+pkValues and a table name.

func GetRowOrNil

func GetRowOrNil[S any](ctx context.Context, pkValue any, pkValues ...any) (row *S, err error)

GetRowOrNil uses the passed pkValue+pkValues to query a table row and scan it into a struct of type S that must have tagged fields with primary key flags to identify the primary key column names for the passed pkValue+pkValues and a table name. Returns nil as row and error if no row could be found with the passed pkValue+pkValues.

func IgnoreColumns

func IgnoreColumns(names ...string) sqldb.ColumnFilter

func IgnoreStructFields

func IgnoreStructFields(names ...string) sqldb.ColumnFilter

func InsertStruct

func InsertStruct(ctx context.Context, table string, rowStruct any, ignoreColumns ...sqldb.ColumnFilter) error

InsertStruct inserts a new row into table using the connection's StructFieldMapper to map struct fields to column names. Optional ColumnFilter can be passed to ignore mapped columns.

func IsOtherThanErrNoRows

func IsOtherThanErrNoRows(err error) bool

IsOtherThanErrNoRows returns true if the passed error is not nil and does not unwrap to, or is sql.ErrNoRows.

func IsTransaction

func IsTransaction(ctx context.Context) bool

IsTransaction indicates if the connection from the context, or the default connection if the context has none, is a transaction.

func IsolatedTransaction

func IsolatedTransaction(ctx context.Context, txFunc func(context.Context) error) error

IsolatedTransaction executes txFunc within a database transaction that is passed in to txFunc as tx Connection. IsolatedTransaction returns all errors from txFunc or transaction commit errors happening after txFunc. If parentConn is already a transaction, a brand new transaction will begin on the parent's connection. Errors and panics from txFunc will rollback the transaction. Recovered panics are re-paniced and rollback errors after a panic are logged with ErrLogger.

func Now

func Now(ctx context.Context) (time.Time, error)

Now returns the result of the SQL now() function for the current connection. Useful for getting the timestamp of a SQL transaction for use in Go code.

func OnlyColumns

func OnlyColumns(names ...string) sqldb.ColumnFilter

func OnlyStructFields

func OnlyStructFields(names ...string) sqldb.ColumnFilter

func PrintlnTable

func PrintlnTable(rows [][]string, err error) error

PrintlnTable prints a string table to stdout padding the table with spaces and using '|' as delimiter between columns.

func QueryRow

func QueryRow(ctx context.Context, query string, args ...any) sqldb.RowScanner

QueryRow queries a single row and returns a RowScanner for the results.

func QueryRowStruct

func QueryRowStruct[S any](ctx context.Context, query string, args ...any) (row *S, err error)

QueryRowStruct queries a row and scans it as struct.

func QueryRowStructOrNil

func QueryRowStructOrNil[S any](ctx context.Context, query string, args ...any) (row *S, err error)

QueryRowStructOrNil queries a row and scans it as struct or returns nil in case of sql.ErrNoRows.

func QueryRowStructReplaceErrNoRows

func QueryRowStructReplaceErrNoRows[S any](ctx context.Context, errNoRows func() error, query string, args ...any) (row *S, err error)

QueryRowStructReplaceErrNoRows queries a row and scans it as struct. In case of an sql.ErrNoRows error, errNoRows will be called and its result returned as error together with nil as row.

func QueryRows

func QueryRows(ctx context.Context, query string, args ...any) sqldb.RowsScanner

QueryRows queries multiple rows and returns a RowsScanner for the results.

func QueryStructSlice

func QueryStructSlice[S any](ctx context.Context, query string, args ...any) (rows []S, err error)

QueryStructSlice returns queried rows as slice of the generic type S which must be a struct or a pointer to a struct.

func QueryValue

func QueryValue[T any](ctx context.Context, query string, args ...any) (value T, err error)

QueryValue queries a single value of type T.

func QueryValueOr

func QueryValueOr[T any](ctx context.Context, defaultValue T, query string, args ...any) (value T, err error)

QueryValueOr queries a single value of type T or returns the passed defaultValue in case of sql.ErrNoRows.

func QueryValueReplaceErrNoRows

func QueryValueReplaceErrNoRows[T any](ctx context.Context, errNoRows func() error, query string, args ...any) (value T, err error)

QueryValueReplaceErrNoRows queries a single value of type T. In case of an sql.ErrNoRows error, errNoRows will be called and its result returned together with the default value for T.

func ReplaceErrNoRows

func ReplaceErrNoRows(err, replacement error) error

ReplaceErrNoRows returns the passed replacement error if errors.Is(err, sql.ErrNoRows), else the passed err is returned unchanged.

func SerializedTransaction

func SerializedTransaction(ctx context.Context, txFunc func(context.Context) error) error

SerializedTransaction executes txFunc "serially" within a database transaction that is passed in to txFunc via the context. Use db.Conn(ctx) to get the transaction connection within txFunc. Transaction returns all errors from txFunc or transaction commit errors happening after txFunc. If parentConn is already a transaction, then it is passed through to txFunc unchanged as tx sqldb.Connection and no parentConn.Begin, Commit, or Rollback calls will occour within this Transaction call. Errors and panics from txFunc will rollback the transaction if parentConn was not already a transaction. Recovered panics are re-paniced and rollback errors after a panic are logged with sqldb.ErrLogger.

Serialized transactions are typically necessary when an insert depends on a previous select within the transaction, but that pre-insert select can't lock the table like it's possible with SELECT FOR UPDATE. During transaction execution, the isolation level "Serializable" is set. This does not mean that the transaction will be run in series. On the contrary, it actually means that Postgres will track read/write dependencies and will report an error in case other concurrent transactions have altered the results of the statements within this transaction. If no serialisation is possible, raw Postgres error will be: ``` ERROR: could not serialize access due to read/write dependencies among transactions HINT: The transaction might succeed if retried. ``` or ``` ERROR: could not serialize access due to concurrent update HINT: The transaction might succeed if retried. ``` In this case, retry the whole transaction (as Postgres hints). This works simply because if you run the transaction for the second (or Nth) time, the queries will yield different results therefore altering the end result.

SerializedTransaction calls can be nested, in which case nested calls just execute the txFunc within the parent's serialized transaction. It's not valid to nest a SerializedTransaction within a normal Transaction function because in this case serialization retries can't be delegated up to the partent transaction that doesn't know anything about serialization.

Because of the retryable nature, please be careful with the size of the transaction and the retry cost.

func SetConn

func SetConn(c sqldb.Connection)

SetConn sets the global connection returned by Conn if there is no other connection in the context passed to Conn.

func Transaction

func Transaction(ctx context.Context, txFunc func(context.Context) error) error

Transaction executes txFunc within a database transaction that is passed in to txFunc via the context. Use db.Conn(ctx) to get the transaction connection within txFunc. Transaction returns all errors from txFunc or transaction commit errors happening after txFunc. If parentConn is already a transaction, then it is passed through to txFunc unchanged as tx sqldb.Connection and no parentConn.Begin, Commit, or Rollback calls will occour within this Transaction call. Errors and panics from txFunc will rollback the transaction if parentConn was not already a transaction. Recovered panics are re-paniced and rollback errors after a panic are logged with sqldb.ErrLogger.

func TransactionOpts

func TransactionOpts(ctx context.Context, opts *sql.TxOptions, txFunc func(context.Context) error) error

TransactionOpts executes txFunc within a database transaction with sql.TxOptions that is passed in to txFunc via the context. Use db.Conn(ctx) to get the transaction connection within txFunc. TransactionOpts returns all errors from txFunc or transaction commit errors happening after txFunc. If parentConn is already a transaction, then it is passed through to txFunc unchanged as tx sqldb.Connection and no parentConn.Begin, Commit, or Rollback calls will occour within this TransactionOpts call. Errors and panics from txFunc will rollback the transaction if parentConn was not already a transaction. Recovered panics are re-paniced and rollback errors after a panic are logged with sqldb.ErrLogger.

func TransactionReadOnly

func TransactionReadOnly(ctx context.Context, txFunc func(context.Context) error) error

TransactionReadOnly executes txFunc within a read-only database transaction that is passed in to txFunc via the context. Use db.Conn(ctx) to get the transaction connection within txFunc. TransactionReadOnly returns all errors from txFunc or transaction commit errors happening after txFunc. If parentConn is already a transaction, then it is passed through to txFunc unchanged as tx sqldb.Connection and no parentConn.Begin, Commit, or Rollback calls will occour within this TransactionReadOnly call. Errors and panics from txFunc will rollback the transaction if parentConn was not already a transaction. Recovered panics are re-paniced and rollback errors after a panic are logged with sqldb.ErrLogger.

func TransactionSavepoint

func TransactionSavepoint(ctx context.Context, txFunc func(context.Context) error) error

TransactionSavepoint executes txFunc within a database transaction or uses savepoints for rollback. If the passed context already has a database transaction connection, then a savepoint with a random name is created before the execution of txFunc. If txFunc returns an error, then the transaction is rolled back to the savepoint but the transaction from the context is not rolled back. If the passed context does not have a database transaction connection, then Transaction(ctx, txFunc) is called without savepoints. Use db.Conn(ctx) to get the transaction connection within txFunc. TransactionSavepoint returns all errors from txFunc, transaction, savepoint, and rollback errors. Panics from txFunc are not recovered to rollback to the savepoint, they should behandled by the parent Transaction function.

func TxOptionsString

func TxOptionsString(opts *sql.TxOptions) string

TxOptionsString returns a string representing the passed TxOptions wich will be empty for the default options.

func ValidateNotWithinTransaction

func ValidateNotWithinTransaction(ctx context.Context) error

ValidateNotWithinTransaction returns sqldb.ErrWithinTransaction if the database connection from the context is a transaction.

func ValidateWithinTransaction

func ValidateWithinTransaction(ctx context.Context) error

ValidateWithinTransaction returns sqldb.ErrNotWithinTransaction if the database connection from the context is not a transaction.

Types

This section is empty.

Jump to

Keyboard shortcuts

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