sqldatabase

package
v6.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2022 License: Apache-2.0 Imports: 6 Imported by: 0

README

SQL Database

This package provides interfaces to abstract working with the Go "database/sql" standard library. This allows services you build to unit test SQL interactions.

This README won't go into the details of each interface, as their concrete types are well documented in the Go standard library.

  • ColumnType
  • DB
  • Row
  • Rows
  • Scanner (this is not in the sdtlib. If abstracts the concent of *sql.Row and *sql.Rows for scanning rows)
  • Stmt
  • Tx

Examples

Connect to Database
var (
	err error
	db sqldatabase.DB
)

if db, err = sqldatabase.Open("mysql", "localhost:3306"); err != nil {
	panic(err)
}
Query
func getData() ([]DataStruct, error) {
	var (
		err error
		ctx context.Context
		cancel context.CancelFunc
		rows sqldatabase.Rows
		row DataStruct
	)

	result := make([]DataStruct, 0, 100)
	ctx, cancel = context.WithTimeout(context.Background, time.Second*30)
	defer cancel()

	if rows, err = db.Query("SELECT * FROM stuff"); err != nil {
		return result, err
	}

	for rows.Next() {
		if row, err = convertToStruct(rows); err != nil {
			return result, err
		}

		result = append(result, row)
	}

	return result, nil
}

func convertToStruct(row sqldatabase.Scanner) (DataStruct, error) {
	var (
		err error
		value1 string
		value2 int
		result DataStruct
	)

	if err = row.Scan(&value1, &value2); err != nil {
		return result, err
	}

	result = DataStruct{
		Value1: value1,
		Value2: value2,
	}

	return result, nil
}

DDL

func update() error {
	var (
		err error
		ctx context.Context
		cancel context.CancelFunc
	)

	ctx, cancel = context.WithTimeout(context.Background(), time.Second*30)
	defer cancel()

	if _, err = db.ExecContext(ctx, "UPDATE stuff set a=?", 2); err != nil {
		return err
	}

	return nil
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	KindString         reflect.Kind = reflect.String
	KindInt            reflect.Kind = reflect.Int64
	KindBool           reflect.Kind = reflect.Bool
	KindFloat32        reflect.Kind = reflect.Float32
	KindFloat64        reflect.Kind = reflect.Float64
	KindTime           reflect.Kind = reflect.TypeOf(time.Time{}).Kind()
	KindSqlNullString  reflect.Kind = reflect.TypeOf(sql.NullString{}).Kind()
	KindSqlNullInt32   reflect.Kind = reflect.TypeOf(sql.NullInt32{}).Kind()
	KindSqlNullInt64   reflect.Kind = reflect.TypeOf(sql.NullInt64{}).Kind()
	KindSqlNullTime    reflect.Kind = reflect.TypeOf(sql.NullTime{}).Kind()
	KindSqlNullFloat64 reflect.Kind = reflect.TypeOf(sql.NullFloat64{}).Kind()
)

Functions

func AssignScanValue

func AssignScanValue(mappings ScanMapping, rowIndex, colIndex int, dest interface{})

AssignScanValue reads the mapping at a row and column index, determines the type of value, and assigns it to the provided destination variable.

func GetDBContext

func GetDBContext(timeout int) (context.Context, context.CancelFunc)

GetDBContext returns a context with the timeout set to the value configured in the application config. Timeouts are in seconds

func LimitAndOffset

func LimitAndOffset(page, pageSize int) string

LimitAndOffset returns a string used in a SQL query to limit the number of records and set the initial offet

func NullBool

func NullBool(value sql.NullBool) bool

NullBool returns the bool value from a SQL bool. If the SQL value is null false is returned.

func NullDate

func NullDate(value sql.NullString) time.Time

NullDate parses a string date in the format of 2006-01-02 to time.Time. If that format doesn't work then 2006-01-02T15:04:05Z is used.

func NullDateWithFormat

func NullDateWithFormat(value sql.NullString, format string) time.Time

NullDateWithFormat parses a string date in the format provided. If the provided SQL value is null then an empty time struct is returned

func NullFloat

func NullFloat(value sql.NullFloat64) float64

NullFloat returns the float value from a SQL float. If the SQL value is null 0.0 is returned

func NullFloatFromString

func NullFloatFromString(value sql.NullString) float64

NullFloatFromString returns the float value from a SQL string. If the the SQL string is null 0.0 is returned.

func NullInt

func NullInt(value sql.NullInt64) int

NullInt returns the int value from a SQL int64. If the SQL value is null then 0 is returned

func NullString

func NullString(value sql.NullString) string

NullString returns the string value from a SQL string. Empty is returned if the SQL value is null

func NullTime

func NullTime(value sql.NullTime) time.Time

NullTime returns the time.Time value of a SQL time. If the SQL time is null, an empty time value is returned

func Scan

func Scan(mappings ScanMapping, rowIndex int, dest ...interface{})

Scan scans values into dest... from the provided mappings and row index. This is most useful in a mock method.

Example:

  data := gosqldatabase.ScanMapping{
    {
		 {gosqldatabase.KindString, "value1"},
		 {gosqldatabase.KindInt, 2},
		 {gosqldatabase.KindSqlNullString, sql.NullString{"value2", true}},
		 {gosqldatabase.KindSqlNullInt64, sql.NullInt64{nil, false}},
    },
  }

  rowIndex := 0

  mock := &gosqldatabase.MockRow{
    ScanFunc: func(dest ...interface{}) error {
      gosqldatabase.Scan(data, rowIndex, dest...)
      return nil
    },
  }

Types

type ColumnType

type ColumnType interface {
	/*
		DatabaseTypeName returns the database system name of the column
		type. If an empty string is returned, then the driver type name
		is not supported. Consult your driver documentation for a list of
		driver data types. Length specifiers are not included. Common type
		names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL",
		"INT", and "BIGINT".
	*/
	DatabaseTypeName() string

	/*
		DecimalSize returns the scale and precision of a decimal type.
		If not applicable or if not supported ok is false.
	*/
	DecimalSize() (precision, scale int64, ok bool)

	/*
		Length returns the column type length for variable length column types
		such as text and binary field types. If the type length is unbounded
		the value will be math.MaxInt64 (any database limits will still apply).
		If the column type is not variable length, such as an int, or if not
		supported by the driver ok is false.
	*/
	Length() (length int64, ok bool)

	/*
		Name returns the name or alias of the column.
	*/
	Name() string

	/*
		Nullable reports whether the column may be null. If a driver does
		not support this property ok will be false.
	*/
	Nullable() (nullable, ok bool)

	/*
		ScanType returns a Go type suitable for scanning into using Rows.Scan.
		If a driver does not support this property ScanType will return the
		type of an empty interface.
	*/
	ScanType() reflect.Type
}

ColumnType contains the name and type of a column.

type DB

type DB interface {
	/*
		Begin starts a transaction. The default isolation level is dependent
		on the driver.
	*/
	Begin() (Tx, error)

	/*
		Close closes the database and prevents new queries from starting.
		Close then waits for all queries that have started processing on
		the server to finish.

		It is rare to Close a DB, as the DB handle is meant to be long-lived
		and shared between many goroutines.
	*/
	Close() error

	/*
		Exec executes a query without returning any rows. The args are for
		any placeholder parameters in the query.
	*/
	Exec(query string, args ...interface{}) (sql.Result, error)

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

	/*
		Ping verifies a connection to the database is still alive,
		establishing a connection if necessary.
	*/
	Ping() error

	/*
		PingContext verifies a connection to the database is still alive,
		establishing a connection if necessary.
	*/
	PingContext(ctx context.Context) error

	/*
		Prepare 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.
	*/
	Prepare(query string) (Stmt, 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, query string) (Stmt, error)

	/*
		Query executes a query that returns rows, typically a SELECT. The args are
		for any placeholder parameters in the query.
	*/
	Query(query string, args ...interface{}) (Rows, error)

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

	/*
		QueryRow executes a query that is expected to return at most one row.
		QueryRow 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.
	*/
	QueryRow(query string, args ...interface{}) Row

	/*
		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, query string, args ...interface{}) Row

	/*
		SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.

		Expired connections may be closed lazily before reuse.

		If d <= 0, connections are not closed due to a connection's idle time.
	*/
	SetConnMaxIdleTime(d time.Duration)

	/*
		SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

		Expired connections may be closed lazily before reuse.

		If d <= 0, connections are not closed due to a connection's age.
	*/
	SetConnMaxLifetime(d time.Duration)

	/*
		SetMaxIdleConns sets the maximum number of connections in the idle connection pool.

		If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new
		MaxIdleConns will be reduced to match the MaxOpenConns limit.

		If n <= 0, no idle connections are retained.

		The default max idle connections is currently 2. This may change in a future release.
	*/
	SetMaxIdleConns(n int)

	/*
		SetMaxOpenConns sets the maximum number of open connections to the database.

		If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
		MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit.

		If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).
	*/
	SetMaxOpenConns(n int)
}

DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.

The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.

func Open

func Open(driverName, dataSourceName string) (DB, error)

Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.

Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

type MockColumnType

type MockColumnType struct {
	DatabaseTypeNameFunc func() string
	DecimalSizeFunc      func() (precision, scale int64, ok bool)
	LengthFunc           func() (length int64, ok bool)
	NameFunc             func() string
	NullableFunc         func() (nullable, ok bool)
	ScanTypeFunc         func() reflect.Type
}

func (*MockColumnType) DatabaseTypeName

func (m *MockColumnType) DatabaseTypeName() string

*******************************************************************

  • MockColumnType ******************************************************************

func (*MockColumnType) DecimalSize

func (m *MockColumnType) DecimalSize() (precision, scale int64, ok bool)

func (*MockColumnType) Length

func (m *MockColumnType) Length() (length int64, ok bool)

func (*MockColumnType) Name

func (m *MockColumnType) Name() string

func (*MockColumnType) Nullable

func (m *MockColumnType) Nullable() (nullable, ok bool)

func (*MockColumnType) ScanType

func (m *MockColumnType) ScanType() reflect.Type

type MockDB

type MockDB struct {
	BeginFunc              func() (Tx, error)
	CloseFunc              func() error
	ExecFunc               func(query string, args ...interface{}) (sql.Result, error)
	ExecContextFunc        func(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	PingFunc               func() error
	PingContextFunc        func(ctx context.Context) error
	PrepareFunc            func(query string) (Stmt, error)
	PrepareContextFunc     func(ctx context.Context, query string) (Stmt, error)
	QueryFunc              func(query string, args ...interface{}) (Rows, error)
	QueryContextFunc       func(ctx context.Context, query string, args ...interface{}) (Rows, error)
	QueryRowFunc           func(query string, args ...interface{}) Row
	QueryRowContextFunc    func(ctx context.Context, query string, args ...interface{}) Row
	SetConnMaxIdleTimeFunc func(d time.Duration)
	SetConnMaxLifetimeFunc func(d time.Duration)
	SetMaxIdleConnsFunc    func(n int)
	SetMaxOpenConnsFunc    func(n int)
}

func (*MockDB) Begin

func (m *MockDB) Begin() (Tx, error)

*******************************************************************

  • MockDB ******************************************************************

func (*MockDB) Close

func (m *MockDB) Close() error

func (*MockDB) Exec

func (m *MockDB) Exec(query string, args ...interface{}) (sql.Result, error)

func (*MockDB) ExecContext

func (m *MockDB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*MockDB) Ping

func (m *MockDB) Ping() error

func (*MockDB) PingContext

func (m *MockDB) PingContext(ctx context.Context) error

func (*MockDB) Prepare

func (m *MockDB) Prepare(query string) (Stmt, error)

func (*MockDB) PrepareContext

func (m *MockDB) PrepareContext(ctx context.Context, query string) (Stmt, error)

func (*MockDB) Query

func (m *MockDB) Query(query string, args ...interface{}) (Rows, error)

func (*MockDB) QueryContext

func (m *MockDB) QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)

func (*MockDB) QueryRow

func (m *MockDB) QueryRow(query string, args ...interface{}) Row

func (*MockDB) QueryRowContext

func (m *MockDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) Row

func (*MockDB) SetConnMaxIdleTime

func (m *MockDB) SetConnMaxIdleTime(d time.Duration)

func (*MockDB) SetConnMaxLifetime

func (m *MockDB) SetConnMaxLifetime(d time.Duration)

func (*MockDB) SetMaxIdleConns

func (m *MockDB) SetMaxIdleConns(n int)

func (*MockDB) SetMaxOpenConns

func (m *MockDB) SetMaxOpenConns(n int)

type MockResult

type MockResult struct {
	LastInsertIdFunc func() (int64, error)
	RowsAffectedFunc func() (int64, error)
}

func (*MockResult) LastInsertId

func (m *MockResult) LastInsertId() (int64, error)

*******************************************************************

  • MockResult ******************************************************************

func (*MockResult) RowsAffected

func (m *MockResult) RowsAffected() (int64, error)

type MockRow

type MockRow struct {
	ErrFunc  func() error
	ScanFunc func(dest ...interface{}) error
}

func (*MockRow) Err

func (m *MockRow) Err() error

*******************************************************************

  • MockRow ******************************************************************

func (*MockRow) Scan

func (m *MockRow) Scan(dest ...interface{}) error

type MockRows

type MockRows struct {
	CloseFunc         func() error
	ColumnTypesFunc   func() ([]ColumnType, error)
	ColumnsFunc       func() ([]string, error)
	ErrFunc           func() error
	NextFunc          func() bool
	NextResultSetFunc func() bool
	ScanFunc          func(dst ...interface{}) error
}

func (*MockRows) Close

func (m *MockRows) Close() error

*******************************************************************

  • MockRows ******************************************************************

func (*MockRows) ColumnTypes

func (m *MockRows) ColumnTypes() ([]ColumnType, error)

func (*MockRows) Columns

func (m *MockRows) Columns() ([]string, error)

func (*MockRows) Err

func (m *MockRows) Err() error

func (*MockRows) Next

func (m *MockRows) Next() bool

func (*MockRows) NextResultSet

func (m *MockRows) NextResultSet() bool

func (*MockRows) Scan

func (m *MockRows) Scan(dst ...interface{}) error

type MockStmt

type MockStmt struct {
	CloseFunc           func() error
	ExecFunc            func(args ...interface{}) (sql.Result, error)
	ExecContextFunc     func(ctx context.Context, args ...interface{}) (sql.Result, error)
	QueryFunc           func(args ...interface{}) (Rows, error)
	QueryContextFunc    func(ctx context.Context, args ...interface{}) (Rows, error)
	QueryRowFunc        func(args ...interface{}) Row
	QueryRowContextFunc func(ctx context.Context, args ...interface{}) Row
}

func (*MockStmt) Close

func (m *MockStmt) Close() error

*******************************************************************

  • MockStmt ******************************************************************

func (*MockStmt) Exec

func (m *MockStmt) Exec(args ...interface{}) (sql.Result, error)

func (*MockStmt) ExecContext

func (m *MockStmt) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)

func (*MockStmt) Query

func (m *MockStmt) Query(args ...interface{}) (Rows, error)

func (*MockStmt) QueryContext

func (m *MockStmt) QueryContext(ctx context.Context, args ...interface{}) (Rows, error)

func (*MockStmt) QueryRow

func (m *MockStmt) QueryRow(args ...interface{}) Row

func (*MockStmt) QueryRowContext

func (m *MockStmt) QueryRowContext(ctx context.Context, args ...interface{}) Row

type MockTx

type MockTx struct {
	CommitFunc          func() error
	ExecFunc            func(query string, args ...interface{}) (sql.Result, error)
	ExecContextFunc     func(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	PrepareFunc         func(query string) (Stmt, error)
	PrepareContextFunc  func(ctx context.Context, query string) (Stmt, error)
	QueryFunc           func(query string, args ...interface{}) (Rows, error)
	QueryContextFunc    func(ctx context.Context, query string, args ...interface{}) (Rows, error)
	QueryRowFunc        func(query string, args ...interface{}) Row
	QueryRowContextFunc func(ctx context.Context, query string, args ...interface{}) Row
	RollbackFunc        func() error
	StmtFunc            func(stmt *sql.Stmt) Stmt
	StmtContextFunc     func(ctx context.Context, stmt *sql.Stmt) Stmt
}

func (*MockTx) Commit

func (m *MockTx) Commit() error

*******************************************************************

  • MockTx ******************************************************************

func (*MockTx) Exec

func (m *MockTx) Exec(query string, args ...interface{}) (sql.Result, error)

func (*MockTx) ExecContext

func (m *MockTx) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*MockTx) Prepare

func (m *MockTx) Prepare(query string) (Stmt, error)

func (*MockTx) PrepareContext

func (m *MockTx) PrepareContext(ctx context.Context, query string) (Stmt, error)

func (*MockTx) Query

func (m *MockTx) Query(query string, args ...interface{}) (Rows, error)

func (*MockTx) QueryContext

func (m *MockTx) QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)

func (*MockTx) QueryRow

func (m *MockTx) QueryRow(query string, args ...interface{}) Row

func (*MockTx) QueryRowContext

func (m *MockTx) QueryRowContext(ctx context.Context, query string, args ...interface{}) Row

func (*MockTx) Rollback

func (m *MockTx) Rollback() error

func (*MockTx) Stmt

func (m *MockTx) Stmt(stmt *sql.Stmt) Stmt

func (*MockTx) StmtContext

func (m *MockTx) StmtContext(ctx context.Context, stmt *sql.Stmt) Stmt

type Row

type Row interface {
	/*
		Err provides a way for wrapping packages to check for query errors
		without calling Scan. Err returns the error, if any, that was
		encountered while running the query. If this error is not nil, this
		error will also be returned from Scan.
	*/
	Err() error

	/*
		Scan copies the columns from the matched row into the values pointed
		at by dest. See the documentation on Rows.Scan for details. If more
		than one row matches the query, Scan uses the first row and discards
		the rest. If no row matches the query, Scan returns ErrNoRows.
	*/
	Scan(dest ...interface{}) error
}

Row is the result of calling QueryRow to select a single row.

type Rows

type Rows interface {
	/*
		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.
	*/
	Close() error

	/*
		ColumnTypes returns column information such as column type, length,
		and nullable. Some information may not be available from some drivers.
	*/
	ColumnTypes() ([]ColumnType, error)

	/*
		Columns returns the column names. Columns returns an error if the
		rows are closed.
	*/
	Columns() ([]string, error)

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

	/*
		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.
	*/
	Next() bool

	/*
		NextResultSet prepares the next result set for reading. It reports
		whether there is further result sets, or false if there is no further
		result set or if there is an error advancing to it. The Err method
		should be consulted to distinguish between the two cases.

		After calling NextResultSet, the Next method should always be called
		before scanning. If there are further result sets they may not have
		rows in the result set.
	*/
	NextResultSet() bool

	/*
		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 Rows.
	*/
	Scan(dst ...interface{}) error
}

Rows is the result of a query. Its cursor starts before the first row of the result set. Use Next to advance from row to row.

type ScanMapping

type ScanMapping [][]ScanMappingItem

ScanMapping is a slice of a slice of ScanMappingItem structs. Think of this as a set of rows containing a set of column definitions.

Example:

  data := gosqldatabase.ScanMapping{
    {
		 {gosqldatabase.KindString, "value1"},
		 {gosqldatabase.KindInt, 2},
		 {gosqldatabase.KindSqlNullString, sql.NullString{"value2", true}},
		 {gosqldatabase.KindSqlNullInt64, sql.NullInt64{nil, false}},
    },
  }

type ScanMappingItem

type ScanMappingItem struct {
	Kind  reflect.Kind
	Value interface{}
}

ScanMappingItem decribes a value and what kind of value it is.

Example 1: A string value

mapping := gosqldatabase.ScanMappingItem{gosqldatabase.KindString, "value"}

Example 2: A sql.NullInt64 value

mapping := gosqldatabase.ScanMappingItem{gosqldatabase.KindSqlNullInt64, sql.NullInt64{25, true}}

type Scanner

type Scanner interface {
	/*
		Scan copies the columns into values pointed at by dest. The number
		of values in dest must be the same as the number of
		columns.
	*/
	Scan(dst ...interface{}) error
}

Scanner describes a strut that can scan columns from a record

type Stmt

type Stmt interface {
	/*
		Close closes the statement.
	*/
	Close() error

	/*
		Exec executes a prepared statement with the given arguments and
		returns a Result summarizing the effect of the statement.
	*/
	Exec(args ...interface{}) (sql.Result, error)

	/*
		ExecContext executes a prepared statement with the given arguments
		and returns a Result summarizing the effect of the statement.
	*/
	ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)

	/*
		Query executes a prepared query statement with the given arguments
		and returns the query results as a *Rows.
	*/
	Query(args ...interface{}) (Rows, error)

	/*
		QueryContext executes a prepared query statement with the given
		arguments and returns the query results as a *Rows.
	*/
	QueryContext(ctx context.Context, args ...interface{}) (Rows, error)

	/*
		QueryRow executes a prepared query statement with the given arguments.
		If an error occurs during the execution of the statement, that error
		will be returned by a call to Scan on the returned *Row, which is always
		non-nil. 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.
	*/
	QueryRow(args ...interface{}) Row

	/*
		QueryRowContext executes a prepared query statement with the given
		arguments. If an error occurs during the execution of the statement,
		that error will be returned by a call to Scan on the returned *Row,
		which is always non-nil. 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, args ...interface{}) Row
}

Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.

If a Stmt is prepared on a Tx or Conn, it will be bound to a single underlying connection forever. If the Tx or Conn closes, the Stmt will become unusable and all operations will return an error. If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically.

type Tx

type Tx interface {
	/*
		Commit commits the transaction.
	*/
	Commit() error

	/*
		Exec executes a query that doesn't return rows. For example: an INSERT
		and UPDATE.
	*/
	Exec(query string, args ...interface{}) (sql.Result, error)

	/*
		ExecContext executes a query that doesn't return rows. For example: an
		INSERT and UPDATE.
	*/
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

	/*
		Prepare creates a prepared statement for use within a transaction.

		The returned statement operates within the transaction and can no
		longer be used once the transaction has been committed or rolled back.

		To use an existing prepared statement on this transaction, see Tx.Stmt.
	*/
	Prepare(query string) (Stmt, error)

	/*
		PrepareContext creates a prepared statement for use within a
		transaction.

		The returned statement operates within the transaction and will
		be closed when the transaction has been committed or rolled back.

		To use an existing prepared statement on this transaction, see Tx.Stmt.

		The provided context will be used for the preparation of the
		context, not for the execution of the returned statement. The
		returned statement will run in the transaction context.
	*/
	PrepareContext(ctx context.Context, query string) (Stmt, error)

	/*
		Query executes a query that returns rows, typically a SELECT.
	*/
	Query(query string, args ...interface{}) (Rows, error)

	/*
		QueryContext executes a query that returns rows, typically a SELECT.
	*/
	QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)

	/*
		QueryRow executes a query that is expected to return at most one row.
		QueryRow 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.
	*/
	QueryRow(query string, args ...interface{}) Row

	/*
		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, query string, args ...interface{}) Row

	/*
		Rollback aborts the transaction.
	*/
	Rollback() error

	/*
		Stmt returns a transaction-specific prepared statement from an existing statement.
	*/
	Stmt(stmt *sql.Stmt) Stmt

	/*
		StmtContext returns a transaction-specific prepared statement from an
		existing statement.
	*/
	StmtContext(ctx context.Context, stmt *sql.Stmt) Stmt
}

Tx is an in-progress database transaction.

A transaction must end with a call to Commit or Rollback.

After a call to Commit or Rollback, all operations on the transaction fail with ErrTxDone.

The statements prepared for a transaction by calling the transaction's Prepare or Stmt methods are closed by the call to Commit or Rollback.

Jump to

Keyboard shortcuts

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