record

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2020 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrModelEmptyQueryBuilder indicates the model's query builder is empty. To fix
	// the error, simply call:
	//
	// - All
	// - Count
	// - Create
	// - Delete
	// - Find
	// - Update
	// - Scan
	ErrModelEmptyQueryBuilder = errors.New("model's query builder is empty")

	// ErrModelMissingMasterDB indicates the model is missing master database.
	ErrModelMissingMasterDB = errors.New("model is missing master database")

	// ErrModelMissingReplicaDB indicates the model is missing replica database.
	ErrModelMissingReplicaDB = errors.New("model is missing replica database")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// Adapter indicates the database adapter to use. The value is parsed from
	// "DB_URI_<DB_NAME>".
	Adapter string

	// ConnMaxLifetime indicates 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.
	ConnMaxLifetime time.Duration

	// Database indicates the database schema to connect. The value is parsed
	// from "DB_URI_<DB_NAME>".
	Database string

	// Host indicates the host to use for connecting to the database. The value
	// is parsed from "DB_URI_<DB_NAME>".
	Host string

	// MaxIdleConns indicates the maximum number of connections in the idle
	// connection pool. By default, it is 25. Otherwise, the value is parsed
	// from "DB_MAX_IDLE_CONNS_<DB_NAME>".
	//
	// Note: MaxIdleConns will automatically be updated to use the same value
	// as MaxOpenConns if  MaxIdleConns is greater than MaxOpenConns.
	MaxIdleConns int

	// MaxOpenConns indicates the maximum number of open connections to the
	// database. By default, it is 25. Otherwise, the value is parsed
	// from "DB_MAX_OPEN_CONNS_<DB_NAME>".
	MaxOpenConns int

	// Password indicates the password to use for connecting to the database.
	// The value is parsed from "DB_URI_<DB_NAME>".
	Password string

	// Port indicates the port to use for connecting to the database. The value
	// is parsed from "DB_URI_<DB_NAME>".
	Port string

	// Replica indicates if the database is a read replica. By default, it is
	// false. Otherwise, the value is parsed from "DB_REPLICA_<DB_NAME>".
	Replica bool

	// SchemaSearchPath indicates the schema search path which is only used with
	// "postgres" adapter.
	//
	// By default, it is "public". Otherwise, the value is parsed from
	// "DB_SCHEMA_SEARCH_PATH_<DB_NAME>".
	SchemaSearchPath string

	// SchemaMigrationsTable indicates the table name for storing the schema
	// migration versions.
	//
	// By default, it is "schema_migrations". Otherwise, the value is parsed from
	// "DB_SCHEMA_MIGRATIONS_TABLE_<DB_NAME>".
	SchemaMigrationsTable string

	// URI indicates the database connection string to connect.
	//
	// URI connection string documentation:
	//   - mysql: https://dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html#connecting-using-uri
	//   - postgres: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
	URI string

	// Username indicates the username to use for connecting to the database. The
	// value is parsed from "DB_URI_<DB_NAME>".
	Username string
}

Config contains database connection configuration.

type DB

type DB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

DB manages the database config/connection/migrations.

func (*DB) Begin

func (db *DB) Begin() (Txer, error)

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

func (*DB) BeginContext

func (db *DB) BeginContext(ctx context.Context, opts *sql.TxOptions) (Txer, error)

BeginContext 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 BeginContext 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) Config

func (db *DB) Config() *Config

Config returns the database config.

func (*DB) Connect

func (db *DB) Connect() error

Connect establishes a connection to the database specified in URI and assign the database handler which is safe for concurrent use by multiple goroutines and maintains its own connection pool.

func (*DB) ConnectDefaultDB

func (db *DB) ConnectDefaultDB() error

ConnectDefaultDB connects to the default database.

func (*DB) CreateDB

func (db *DB) CreateDB(database string) error

CreateDB creates the database.

func (*DB) DropDB

func (db *DB) DropDB(database string) error

DropDB drops the database.

func (*DB) DumpSchema

func (db *DB) DumpSchema(dbname string) error

DumpSchema dumps the database schema into "db/migrate/<dbname>/schema.go".

func (*DB) Exec

func (db *DB) Exec(query string, args ...interface{}) (sql.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{}) (sql.Result, error)

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

func (*DB) GenerateMigration

func (db *DB) GenerateMigration(name, target string, tx bool) error

GenerateMigration generates the migration file for the target database.

func (*DB) Get

func (db *DB) Get(dest interface{}, query string, args ...interface{}) error

Get using this DB. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DB) GetContext

func (db *DB) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

GetContext using this DB. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DB) Migrate

func (db *DB) Migrate() error

Migrate runs migrations for the current environment that have not run yet.

func (*DB) MigrateStatus

func (db *DB) MigrateStatus() ([][]string, error)

MigrateStatus returns the migration status for the current environment.

func (*DB) NamedExec

func (db *DB) NamedExec(query string, arg interface{}) (sql.Result, error)

NamedExec using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) NamedExecContext

func (db *DB) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContext using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) NamedQuery

func (db *DB) NamedQuery(query string, arg interface{}) (*Rows, error)

NamedQuery using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) NamedQueryContext

func (db *DB) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*Rows, error)

NamedQueryContext using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) Prepare

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

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

func (db *DB) PrepareNamed(query string) (*NamedStmt, error)

PrepareNamed returns a NamedStmt.

func (*DB) PrepareNamedContext

func (db *DB) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error)

PrepareNamedContext returns NamedStmt.

func (*DB) Query

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

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

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

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

func (db *DB) RegisterMigration(up func(DBer) error, down func(DBer) error, args ...string) error

RegisterMigration registers the up/down migrations that won't be executed in transaction.

func (*DB) RegisterMigrationTx

func (db *DB) RegisterMigrationTx(upTx func(Txer) error, downTx func(Txer) error, args ...string) error

RegisterMigrationTx registers the up/down migrations that will be executed in transaction.

func (*DB) RegisterSeedTx

func (db *DB) RegisterSeedTx(seed func(Txer) error)

RegisterSeedTx registers the seeding that will be executed in transaction.

func (*DB) Rollback

func (db *DB) Rollback() error

Rollback rolls back the last migration for the current environment.

func (*DB) Schema

func (db *DB) Schema() string

Schema returns the database schema.

func (*DB) Seed

func (db *DB) Seed() error

Seed runs the seeding for the current environment.

func (*DB) Select

func (db *DB) Select(dest interface{}, query string, args ...interface{}) error

Select using this DB. Any placeholder parameters are replaced with supplied args.

func (*DB) SelectContext

func (db *DB) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext using this DB. Any placeholder parameters are replaced with supplied args.

func (*DB) SetSchema

func (db *DB) SetSchema(schema string)

SetSchema sets the database schema.

type DBer

type DBer interface {
	Begin() (Txer, error)
	BeginContext(ctx context.Context, opts *sql.TxOptions) (Txer, error)
	Close() error
	Config() *Config
	Conn(ctx context.Context) (*sql.Conn, error)
	Connect() error
	ConnectDefaultDB() error
	CreateDB(database string) error
	Driver() driver.Driver
	DriverName() string
	DropDB(database string) error
	DumpSchema(database string) error
	Exec(query string, args ...interface{}) (sql.Result, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	GenerateMigration(name, target string, tx bool) error
	Get(dest interface{}, query string, args ...interface{}) error
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	Migrate() error
	MigrateStatus() ([][]string, error)
	NamedExec(query string, arg interface{}) (sql.Result, error)
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
	NamedQuery(query string, arg interface{}) (*Rows, error)
	NamedQueryContext(ctx context.Context, query string, arg interface{}) (*Rows, error)
	Ping() error
	PingContext(ctx context.Context) error
	Prepare(query string) (*Stmt, error)
	PrepareContext(ctx context.Context, query string) (*Stmt, error)
	PrepareNamed(query string) (*NamedStmt, error)
	PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error)
	Query(query string, args ...interface{}) (*Rows, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)
	QueryRow(query string, args ...interface{}) *Row
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row
	Rebind(query string) string
	RegisterMigration(up func(DBer) error, down func(DBer) error, args ...string) error
	RegisterMigrationTx(upTx func(Txer) error, downTx func(Txer) error, args ...string) error
	RegisterSeedTx(seed func(Txer) error)
	Rollback() error
	Schema() string
	Seed() error
	Select(dest interface{}, query string, args ...interface{}) error
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	SetConnMaxLifetime(d time.Duration)
	SetMaxIdleConns(n int)
	SetMaxOpenConns(n int)
	SetSchema(schema string)
	Stats() sql.DBStats
}

DBer implements all DB methods.

func NewDB

func NewDB(config *Config, logger *support.Logger) DBer

NewDB initializes the database handler that is used to connect to the database.

type Engine

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

Engine manages the databases.

func NewEngine

func NewEngine(logger *support.Logger, i18n *support.I18n) *Engine

NewEngine initializes the engine instance to manage the databases.

func (*Engine) DB

func (m *Engine) DB(name string) DBer

DB returns the database handle with the specified name.

func (*Engine) Databases

func (m *Engine) Databases() map[string]DBer

Databases returns the managed databases.

func (*Engine) Errors

func (m *Engine) Errors() []error

Errors returns the engine errors.

func (*Engine) Info

func (m *Engine) Info() string

Info returns the engine info.

type ExecOption

type ExecOption struct {
	// Context can be used to set the query timeout.
	Context context.Context

	// Locale indicates the language translation to use for validation error
	// messages.
	Locale string

	// UseReplica indicates if the query should use replica. Note that there
	// could be replica lag which won't allow recent inserted/updated data to
	// be returned correctly.
	UseReplica bool

	// SkipCallbacks indicates if the Create/Delete/Update callbacks should be
	// skipped.
	SkipCallbacks bool

	// SkipValidate indicates if the validation callbacks should be skipped.
	// By default, it is false.
	SkipValidate bool
	// contains filtered or unexported fields
}

ExecOption indicates how a query should be executed.

type Migration

type Migration struct {
	File    string
	Version string
	Down    func(DBer) error
	DownTx  func(Txer) error
	Up      func(DBer) error
	UpTx    func(Txer) error
}

Migration contains database migration.

type Model

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

Model is the layer that represents business data and logic.

func (*Model) All

func (m *Model) All() Modeler

All returns all records from the model's table. Use an array/slice of the struct to scan all the records. Otherwise, only the 1st record will be scanned into the single struct.

Note that this can cause performance issue if there are too many data rows in the model's table.

func (*Model) AttrByDBColumn

func (m *Model) AttrByDBColumn(dbColumn string) *ModelAttr

AttrByDBColumn returns the model's attribute based on the DB column provided.

func (*Model) Begin

func (m *Model) Begin() error

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

func (*Model) BeginContext

func (m *Model) BeginContext(ctx context.Context, opts *sql.TxOptions) error

BeginContext 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 BeginContext 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 (*Model) Commit

func (m *Model) Commit() []error

Commit commits the transaction.

func (*Model) Count

func (m *Model) Count() Modeler

Count returns the total count of matching records. Note that this can cause performance issue if there are too many data rows in the model's table.

func (*Model) Create

func (m *Model) Create() Modeler

Create inserts the model object(s) into the database.

func (*Model) Delete

func (m *Model) Delete() Modeler

Delete deletes the records from the database.

func (*Model) DeleteAll

func (m *Model) DeleteAll() Modeler

DeleteAll deletes all the records that match where condition.

func (*Model) Exec

func (m *Model) Exec(opts ...ExecOption) (int64, []error)

Exec can execute the query with/without context/replica which will return the affected rows and error if there is any.

func (*Model) Find

func (m *Model) Find() Modeler

Find retrieves the records from the database.

func (*Model) Group

func (m *Model) Group(group string) Modeler

Group indicates how to group rows into subgroups based on values of columns or expressions.

func (*Model) Having

func (m *Model) Having(having string, args ...interface{}) Modeler

Having indicates the filter conditions for a group of rows.

func (*Model) Join

func (m *Model) Join(join string, args ...interface{}) Modeler

Join indicates the join queries

func (*Model) Limit

func (m *Model) Limit(limit int) Modeler

Limit indicates the number limit of records to retrieve from the database.

func (*Model) Offset

func (m *Model) Offset(offset int) Modeler

Offset indicates the number of records to skip before starting to return the records.

func (*Model) Order

func (m *Model) Order(order string) Modeler

Order indicates the specific order to retrieve records from the database.

func (*Model) PrimaryKeys

func (m *Model) PrimaryKeys() []string

PrimaryKeys returns the model's primary keys.

func (*Model) Rollback

func (m *Model) Rollback() []error

Rollback aborts the transaction.

func (*Model) SQL

func (m *Model) SQL() string

SQL returns the SQL string.

func (*Model) Scan

func (m *Model) Scan(dest interface{}) Modeler

Scan allows custom select result being scanned into the specified dest.

func (*Model) Select

func (m *Model) Select(columns string) Modeler

Select selects only a subset of fields from the result set.

func (*Model) Tx

func (m *Model) Tx() Txer

Tx returns the transaction connection.

func (*Model) Update

func (m *Model) Update() Modeler

Update updates the model object(s) into the database.

func (*Model) UpdateAll

func (m *Model) UpdateAll(set string, args ...interface{}) Modeler

UpdateAll updates all the records that match where condition.

func (*Model) Where

func (m *Model) Where(condition string, args ...interface{}) Modeler

Where indicates the condition of which records to return.

type ModelAttr

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

ModelAttr keeps track of the model's attributes.

type ModelOption

type ModelOption struct {
	Tx Txer
}

ModelOption is used to initialise a model with additional configurations.

type Modeler

type Modeler interface {
	All() Modeler
	AttrByDBColumn(dbColumn string) *ModelAttr
	Begin() error
	BeginContext(ctx context.Context, opts *sql.TxOptions) error
	Commit() []error
	Count() Modeler
	Create() Modeler
	Delete() Modeler
	DeleteAll() Modeler
	Exec(opts ...ExecOption) (int64, []error)
	Find() Modeler
	Group(group string) Modeler
	Having(having string, args ...interface{}) Modeler
	Join(join string, args ...interface{}) Modeler
	Limit(limit int) Modeler
	Offset(offset int) Modeler
	Order(order string) Modeler
	PrimaryKeys() []string
	Rollback() []error
	Scan(dest interface{}) Modeler
	Select(columns string) Modeler
	SQL() string
	Tx() Txer
	Update() Modeler
	UpdateAll(set string, args ...interface{}) Modeler
	Where(condition string, args ...interface{}) Modeler
}

Modeler implements all Model methods.

func NewModel

func NewModel(dbManager *Engine, dest interface{}, opts ...ModelOption) Modeler

NewModel initializes a model that represents business data and logic.

type NamedStmt

type NamedStmt struct {
	*sqlx.NamedStmt
}

NamedStmt is a prepared statement that executes named queries. Prepare it like how you would execute a NamedQuery, but pass in a struct or map when executing.

type Row

type Row struct {
	*sqlx.Row
}

Row is a wrapper around sqlx.Row.

type Rows

type Rows struct {
	*sqlx.Rows
}

Rows is a wrapper around sqlx.Rows.

type Stmt

type Stmt struct {
	*sqlx.Stmt
	// contains filtered or unexported fields
}

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.

func (*Stmt) Close

func (s *Stmt) Close() error

Close closes the statement.

func (*Stmt) Exec

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

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

func (*Stmt) ExecContext

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

ExecContext executes a prepared statement with the given arguments and returns a sql.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 *sql.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 *sql.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 duringthe execution of the statement, that error will be returned by a call to Scan on the returned *sql.Row, which is always non-nil. If the query selects no rows, the *sql.Row's Scan will return sql.ErrNoRows. Otherwise, the *sql.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 *sql.Row, which is always non-nil. If the query selects no rows, the *sql.Row's Scan will return sql.ErrNoRows. Otherwise, the *sql.Row's Scan scans the first selected row and discards the rest.

type Stmter

type Stmter interface {
	Exec(args ...interface{}) (sql.Result, error)
	ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)
	Query(args ...interface{}) (*Rows, error)
	QueryContext(ctx context.Context, args ...interface{}) (*Rows, error)
	QueryRow(args ...interface{}) *Row
	QueryRowContext(ctx context.Context, args ...interface{}) *Row
}

Stmter implements all Stmt methods and is useful for mocking Stmt in unit tests.

type Tx

type Tx struct {
	*sqlx.Tx
	// 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{}) (sql.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{}) (sql.Result, error)

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

func (*Tx) Get

func (tx *Tx) Get(dest interface{}, query string, args ...interface{}) error

Get using this transaction. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*Tx) GetContext

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

GetContext using this transaction. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*Tx) NamedExec

func (tx *Tx) NamedExec(query string, arg interface{}) (sql.Result, error)

NamedExec executes a named query within this transaction. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) NamedExecContext

func (tx *Tx) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContext executes a named query within this transaction with the specified context. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) NamedQuery

func (tx *Tx) NamedQuery(query string, arg interface{}) (*Rows, error)

NamedQuery within this transaction. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) NamedQueryContext

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

NamedQueryContext within this transaction with the specified context. Any named placeholder parameters are replaced with fields from arg.

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

func (tx *Tx) PrepareNamed(query string) (*NamedStmt, error)

PrepareNamed returns an NamedStmt.

func (*Tx) PrepareNamedContext

func (tx *Tx) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error)

PrepareNamedContext returns an NamedStmt.

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 sql.Row's Scan method is called. If the query selects no rows, the *sql.Row's Scan will return sql.ErrNoRows. Otherwise, the *sql.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 sql.Row's Scan method is called. If the query selects no rows, the *sql.Row's Scan will return sql.ErrNoRows. Otherwise, the *sql.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) Select

func (tx *Tx) Select(dest interface{}, query string, args ...interface{}) error

Select using this transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) SelectContext

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

SelectContext using this transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) Stmt

func (tx *Tx) Stmt(stmt *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 *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.

type Txer

type Txer interface {
	Commit() error
	Exec(query string, args ...interface{}) (sql.Result, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	Get(dest interface{}, query string, args ...interface{}) error
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	NamedExec(query string, arg interface{}) (sql.Result, error)
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
	NamedQuery(query string, arg interface{}) (*Rows, error)
	NamedQueryContext(ctx context.Context, query string, arg interface{}) (*Rows, error)
	Prepare(query string) (*Stmt, error)
	PrepareContext(ctx context.Context, query string) (*Stmt, error)
	PrepareNamed(query string) (*NamedStmt, error)
	PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error)
	Query(query string, args ...interface{}) (*Rows, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)
	QueryRow(query string, args ...interface{}) *Row
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row
	Rollback() error
	Select(dest interface{}, query string, args ...interface{}) error
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	Stmt(stmt *Stmt) *Stmt
	StmtContext(ctx context.Context, stmt *Stmt) *Stmt
}

Txer implements all Tx methods and is useful for mocking Tx in unit tests.

Jump to

Keyboard shortcuts

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