sql

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2019 License: MIT Imports: 6 Imported by: 9

README

Canceling MySQL in Go GoDoc Go Report Card

This package will properly implement context cancelation for MySQL. Without this package, context cancelation does not actually cancel a MySQL query.

See Article for details of the behind-the-scenes magic.

The API is designed to resemble the standard library. It is fully compatible with the dbq package which allows for zero boilerplate database operations in Go.

the project to show your appreciation.

Dependencies

Installation

go get -u github.com/rocketlaunchr/mysql-go

QuickStart


import (
   sql "github.com/rocketlaunchr/mysql-go"
)

pool, _ := sql.Open("user:password@tcp(localhost:3306)/db")

Read Query


// Obtain an exclusive connection
conn, err := pool.Conn(ctx)
defer conn.Close() // Return the connection back to the pool

// Perform your read operation.
rows, err := conn.QueryContext(ctx, stmt)
if err != nil {
   return err
}

Write Query


// Obtain an exclusive connection
conn, err := pool.Conn(ctx)
defer conn.Close() // Return the connection back to the pool

// Perform the write operation
tx, err := conn.BeginTx(ctx, nil)

_, err = tx.ExecContext(ctx, stmt)
if err != nil {
   return tx.Rollback()
}

tx.Commit()

Cancel Query

Cancel the context. This will send a KILL signal to MySQL automatically.

It is highly recommended you set a KillerPool when you instantiate the DB object.

The KillerPool is used to call the KILL signal.

Reverse Proxy Support

Checkout the proxy-protection branch if your database is behind a reverse proxy in order to better guarantee that you are killing the correct query.

Other useful packages

  • dataframe-go - Statistics and data manipulation
  • dbq - Zero boilerplate database operations for Go
  • igo - A Go transpiler with cool new syntax such as fordefer (defer for for-loops)
  • react - Build front end applications using Go
  • remember-go - Cache slow database queries

The license is a modified MIT license. Refer to LICENSE file for more details.

© 2018-19 PJ Engineering and Business Solutions Pty. Ltd.

Final Notes

Feel free to enhance features by issuing pull-requests.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Conn

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

Conn represents a single database connection rather than a pool of database connections. Prefer running queries from DB unless there is a specific need for a continuous single database connection.

A Conn must call Close to return the connection to the database pool and may do so concurrently with a running query.

After a call to Close, all operations on the connection fail with ErrConnDone.

func (*Conn) Begin

func (c *Conn) Begin(opts *stdSql.TxOptions) (*Tx, error)

Begin starts a transaction. The default isolation level is dependent on the driver.

func (*Conn) BeginTx

func (c *Conn) BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*Tx, error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

func (*Conn) Close

func (c *Conn) Close() error

Close returns the connection to the connection pool. All operations after a Close will return with ErrConnDone. Close is safe to call concurrently with other operations and will block until all other operations finish. It may be useful to first cancel any used context and then call close directly after.

func (*Conn) Exec

func (c *Conn) Exec(query string, args ...interface{}) (stdSql.Result, error)

Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*Conn) ExecContext

func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{}) (stdSql.Result, error)

ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*Conn) Ping

func (c *Conn) Ping() error

Ping verifies a connection to the database is still alive.

func (*Conn) PingContext

func (c *Conn) PingContext(ctx context.Context) error

PingContext verifies the connection to the database is still alive.

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (*Stmt, 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.

func (*Conn) PrepareContext

func (c *Conn) PrepareContext(ctx context.Context, 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.

func (*Conn) Query

func (c *Conn) Query(query string, args ...interface{}) (*Rows, error)

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*Conn) QueryContext

func (c *Conn) QueryContext(ctx context.Context, 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.

func (*Conn) QueryRow

func (c *Conn) QueryRow(query string, args ...interface{}) *Row

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.

func (*Conn) QueryRowContext

func (c *Conn) QueryRowContext(ctx context.Context, 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.

func (*Conn) Unleak

func (c *Conn) Unleak()

Unleak will release the reference to the killerPool in order to prevent a memory leak.

type DB

type DB struct {

	// DB is the primary connection pool (i.e. *stdSql.DB).
	DB StdSQLDBExtra

	// KillerPool is an optional (but recommended) secondary connection pool (i.e. *stdSql.DB).
	// If provided, it is used to fire KILL signals.
	KillerPool StdSQLDBExtra

	// KillTimeout sets how long to attempt sending the KILL signal.
	// A value of zero is equivalent to no time limit (not recommended).
	KillTimeout time.Duration
}

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 string, dataSourceName ...string) (*DB, error)

Open opens a database specified by its connection information.

You will need to import "github.com/go-sql-driver/mysql".

Open will 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 contains 2 pools. The KillerPool is configured to have only 1 max open connection. It is for internal use only.

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. For the cancelation feature, a Conn needs to be created.

func OpenDB

func OpenDB(c driver.Connector) *DB

OpenDB opens a database using a Connector, allowing drivers to bypass a string based data source name.

You will need to import "github.com/go-sql-driver/mysql".

OpenDB will 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 contains 2 pools. The KillerPool is configured to have only 1 max open connection. It is for internal use only.

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

func (*DB) Begin

func (db *DB) Begin() (*stdSql.Tx, error)

Begin starts a transaction. The default isolation level is dependent on the driver.

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*stdSql.Tx, error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

func (*DB) Close

func (db *DB) Close() 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.

func (*DB) Conn

func (db *DB) Conn(ctx context.Context) (*Conn, error)

Conn returns a single connection by either opening a new connection or returning an existing connection from the connection pool. Conn will block until either a connection is returned or ctx is canceled. Queries run on the same Conn will be run in the same database session.

Every Conn must be returned to the database pool after use by calling Conn.Close.

func (*DB) Driver

func (db *DB) Driver() driver.Driver

Driver returns the database's underlying driver.

func (*DB) Exec

func (db *DB) Exec(query string, args ...interface{}) (stdSql.Result, error)

Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*DB) ExecContext

func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (stdSql.Result, error)

ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*DB) Ping

func (db *DB) Ping() error

Ping verifies a connection to the database is still alive, establishing a connection if necessary.

func (*DB) PingContext

func (db *DB) PingContext(ctx context.Context) error

PingContext verifies a connection to the database is still alive, establishing a connection if necessary.

func (*DB) Prepare

func (db *DB) Prepare(query string) (*stdSql.Stmt, 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.

func (*DB) PrepareContext

func (db *DB) PrepareContext(ctx context.Context, query string) (*stdSql.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.

func (*DB) Query

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

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*stdSql.Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*DB) QueryRow

func (db *DB) QueryRow(query string, args ...interface{}) *stdSql.Row

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.

func (*DB) QueryRowContext

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *stdSql.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.

func (*DB) SetConnMaxLifetime

func (db *DB) SetConnMaxLifetime(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 reused forever.

func (*DB) SetMaxIdleConns

func (db *DB) SetMaxIdleConns(n int)

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.

func (*DB) SetMaxOpenConns

func (db *DB) SetMaxOpenConns(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).

func (*DB) Stats

func (db *DB) Stats() stdSql.DBStats

Stats returns database statistics.

type Row

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

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

func (*Row) Scan

func (r *Row) Scan(dest ...interface{}) 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.

type Rows

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

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.

func (*Rows) Close

func (rs *Rows) Close() error

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) ColumnTypes

func (rs *Rows) ColumnTypes() ([]*stdSql.ColumnType, error)

ColumnTypes returns column information such as column type, length, and nullable. Some information may not be available from some drivers.

func (*Rows) Columns

func (rs *Rows) Columns() ([]string, error)

Columns returns the column names. Columns returns an error if the rows are closed.

func (*Rows) Err

func (rs *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) Next

func (rs *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) NextResultSet

func (rs *Rows) NextResultSet() 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.

func (*Rows) Scan

func (rs *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 Rows.

Scan converts columns read from the database into the following common Go types and special types provided by the sql package:

*string
*[]byte
*int, *int8, *int16, *int32, *int64
*uint, *uint8, *uint16, *uint32, *uint64
*bool
*float32, *float64
*interface{}
*RawBytes
*Rows (cursor value)
any type implementing Scanner (see Scanner docs)

In the most simple case, if the type of the value from the source column is an integer, bool or string type T and dest is of type *T, Scan simply assigns the value through the pointer.

Scan also converts between string and numeric types, as long as no information would be lost. While Scan stringifies all numbers scanned from numeric database columns into *string, scans into numeric types are checked for overflow. For example, a float64 with value 300 or a string with value "300" can scan into a uint16, but not into a uint8, though float64(255) or "255" can scan into a uint8. One exception is that scans of some float64 numbers to strings may lose information when stringifying. In general, scan floating point columns into *float64.

If a dest argument has type *[]byte, Scan saves in that argument a copy of the corresponding data. The copy is owned by the caller and can be modified and held indefinitely. The copy can be avoided by using an argument of type *RawBytes instead; see the documentation for RawBytes for restrictions on its use.

If an argument has type *interface{}, Scan copies the value provided by the underlying driver without conversion. When scanning from a source value of type []byte to *interface{}, a copy of the slice is made and the caller owns the result.

Source values of type time.Time may be scanned into values of type *time.Time, *interface{}, *string, or *[]byte. When converting to the latter two, time.RFC3339Nano is used.

Source values of type bool may be scanned into types *bool, *interface{}, *string, *[]byte, or *RawBytes.

For scanning into *bool, the source may be true, false, 1, 0, or string inputs parseable by strconv.ParseBool.

Scan can also convert a cursor returned from a query, such as "select cursor(select * from my_table) from dual", into a *Rows value that can itself be scanned from. The parent select query will close any cursor *Rows if the parent *Rows is closed.

func (*Rows) Unleak

func (rs *Rows) Unleak()

Unleak will release the reference to the killerPool in order to prevent a memory leak.

type SQLBasic

type SQLBasic interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (stdSql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row
}

SQLBasic is the interface that allows Conn and Stmt to be used.

type SQLConn

type SQLConn interface {
	SQLBasic
	BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*Tx, error)
	Close() error
	PingContext(ctx context.Context) error
	PrepareContext(ctx context.Context, query string) (*Stmt, error)
}

SQLConn is the interface that allows Conn and Stmt to be used.

type SQLTx

type SQLTx interface {
	SQLBasic
	Stmt(stmt *stdSql.Stmt) *Stmt
	StmtContext(ctx context.Context, stmt *stdSql.Stmt) *Stmt
	Commit() error
	Rollback() error
}

SQLTx is the interface that allows Tx to be used.

type StdSQLCommon

type StdSQLCommon interface {
	StdSQLLegacy
	ExecContext(ctx context.Context, query string, args ...interface{}) (stdSql.Result, error)
	PrepareContext(ctx context.Context, query string) (*stdSql.Stmt, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*stdSql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *stdSql.Row
}

StdSQLCommon is the interface that allows query and exec interactions with a database.

type StdSQLDB

type StdSQLDB interface {
	Ping() error
	PingContext(ctx context.Context) error
	StdSQLCommon
	Conn(ctx context.Context) (*stdSql.Conn, error)
	Begin() (*stdSql.Tx, error)
	BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*stdSql.Tx, error)
	Close() error
}

StdSQLDB is the interface that allows a transaction to be created.

type StdSQLDBExtra

type StdSQLDBExtra interface {
	StdSQLDB
	Driver() driver.Driver
	SetConnMaxLifetime(d time.Duration)
	SetMaxIdleConns(n int)
	SetMaxOpenConns(n int)
	Stats() stdSql.DBStats
}

StdSQLDBExtra is the interface that directly maps to a *stdSql.DB.

type StdSQLLegacy

type StdSQLLegacy interface {
	Exec(query string, args ...interface{}) (stdSql.Result, error)
	Prepare(query string) (*stdSql.Stmt, error)
	Query(query string, args ...interface{}) (*stdSql.Rows, error)
	QueryRow(query string, args ...interface{}) *stdSql.Row
}

StdSQLLegacy will potentially be removed in Go 2.

type StdSQLTx

type StdSQLTx interface {
	StdSQLCommon
	Stmt(stmt *stdSql.Stmt) *stdSql.Stmt
	StmtContext(ctx context.Context, stmt *stdSql.Stmt) *stdSql.Stmt
	Commit() error
	Rollback() error
}

StdSQLTx is the interface that allows a transaction to be committed or rolledback.

type Stmt

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

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

func (*Stmt) Close

func (s *Stmt) Close() error

Close closes the statement.

func (*Stmt) Exec

func (s *Stmt) Exec(args ...interface{}) (stdSql.Result, error)

Exec executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.

func (*Stmt) ExecContext

func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (stdSql.Result, error)

ExecContext executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.

func (*Stmt) Query

func (s *Stmt) Query(args ...interface{}) (*Rows, error)

Query executes a prepared query statement with the given arguments and returns the query results as a *Rows.

func (*Stmt) QueryContext

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

QueryContext executes a prepared query statement with the given arguments and returns the query results as a *Rows.

func (*Stmt) QueryRow

func (s *Stmt) QueryRow(args ...interface{}) *Row

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.

Example usage:

var name string
err := nameByUseridStmt.QueryRow(id).Scan(&name)

func (*Stmt) QueryRowContext

func (s *Stmt) QueryRowContext(ctx context.Context, 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.

func (*Stmt) Unleak

func (s *Stmt) Unleak()

Unleak will release the reference to the killerPool in order to prevent a memory leak.

type Tx

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

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.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction.

func (*Tx) Exec

func (tx *Tx) Exec(query string, args ...interface{}) (stdSql.Result, error)

Exec executes a query that doesn't return rows. For example: an INSERT and UPDATE.

func (*Tx) ExecContext

func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (stdSql.Result, error)

ExecContext executes a query that doesn't return rows. For example: an INSERT and UPDATE.

func (*Tx) Prepare

func (tx *Tx) Prepare(query string) (*Stmt, 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.

func (*Tx) PrepareContext

func (tx *Tx) PrepareContext(ctx context.Context, 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.

func (*Tx) Query

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

Query executes a query that returns rows, typically a SELECT.

func (*Tx) QueryContext

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

QueryContext executes a query that returns rows, typically a SELECT.

func (*Tx) QueryRow

func (tx *Tx) QueryRow(query string, args ...interface{}) *Row

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.

func (*Tx) QueryRowContext

func (tx *Tx) QueryRowContext(ctx context.Context, 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.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback aborts the transaction.

func (*Tx) Stmt

func (tx *Tx) Stmt(stmt *stdSql.Stmt) *Stmt

Stmt returns a transaction-specific prepared statement from an existing statement.

Example:

updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)

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

func (*Tx) StmtContext

func (tx *Tx) StmtContext(ctx context.Context, stmt *stdSql.Stmt) *Stmt

StmtContext returns a transaction-specific prepared statement from an existing statement.

Example:

updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)

The provided context is used for the preparation of the statement, not for the execution of the statement.

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

func (*Tx) Unleak

func (tx *Tx) Unleak()

Unleak will release the reference to the killerPool in order to prevent a memory leak.

Jump to

Keyboard shortcuts

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