mssqlx

package module
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2022 License: MIT Imports: 15 Imported by: 30

README

mssqlx

Go Report Card Coverage Status godoc

Embeddable, high availability, performance and lightweight database client library. Support go 1.9 or newer.

Features and concepts are:

  • Builtin layer/extension to sqlx.
  • Auto proxy for any master-slave, master-master databases. Compatible with Wsrep, Galera Cluster and others.
  • Auto and lightweight round-robin balancer for queries.
  • Builtin error handling for Wsrep, Galera and some database drivers. Auto retry select/get/query queries when detected bad connection causing by DBMS's timeout policy which auto-closes non interactive/timeout connection.
  • Auto health checking.

For more detail of api, please refer to godoc

Install

go get -u github.com/linxGnu/mssqlx

Connecting to Databases

mssqlx is compatible to all kind of databases which database/sql supports. Below code is mysql usage:

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/linxGnu/mssqlx"
)

dsn := "root:123@(%s:3306)/test?charset=utf8&collation=utf8_general_ci&parseTime=true"
masterDSNs := []string{
    fmt.Sprintf(dsn, "172.31.25.233"), // address of master 1
    fmt.Sprintf(dsn, "172.31.24.233"), // address of master 2 if have
    fmt.Sprintf(dsn, "172.31.23.233"), // address of master 3 if have
}
slaveDSNs := []string{
    fmt.Sprintf(dsn, "172.31.25.234"), // address of slave 1
    fmt.Sprintf(dsn, "172.31.25.235"), // address of slave 2
    fmt.Sprintf(dsn, "172.31.25.236"), // address of slave 3
}

db, _ := mssqlx.ConnectMasterSlaves("mysql", masterDSNs, slaveDSNs)

Connecting to Galera Cluster

Recommended to set flag as following:

db, _ := mssqlx.ConnectMasterSlaves("mysql", masterDSNs, slaveDSNs, mssqlx.WithWsrep())

Connecting to Databases with custom read-query source

Read-queries will be distributed among both masters and slaves:

db, _ := mssqlx.ConnectMasterSlaves("mysql", masterDSNs, slaveDSNs, mssqlx.WithReadQuerySource(mssqlx.ReadQuerySourceAll))

Configuration

It's highly recommended to setup configuration before querying.

db.SetMaxIdleConns(20) // set max idle connections to all nodes
// db.SetMasterMaxIdleConns(20) // set max idle connections to master nodes
// db.SetSlaveMaxIdleConns(20) // set max idle connections to slave nodes

db.SetMaxOpenConns(50) // set max open connections to all nodes
// db.SetMasterMaxOpenConns(50) 
// db.SetSlaveMaxOpenConns(50)
    
// if nodes fail, checking healthy in a period (in milliseconds) for auto reconnect. Default is 500.
db.SetHealthCheckPeriod(1000) 
// db.SetMasterHealthCheckPeriod(1000)
// db.SetSlaveHealthCheckPeriod(1000)

Select

type Person struct {
    FirstName string `db:"first_name"`
    LastName  string `db:"last_name"`
    Email     string
    Data      []byte
}

var people []Person
db.Select(&people, "SELECT * FROM person WHERE id > ? and id < ? ORDER BY first_name ASC", 1, 1000)

Get

var person Person
db.Get(&person, "SELECT * FROM person WHERE id = ?", 1)

Queryx

// Loop through rows using only one struct
var person Person

rows, err := db.Queryx("SELECT * FROM person") // or db.QueryxOnMaster(...)
for rows.Next() {
    if err := rows.StructScan(&person); err != nil {
        log.Fatalln(err)
    } 
    fmt.Printf("%#v\n", person)
}

Named query

// Loop through rows using only one struct
var person Person

rows, err := db.NamedQuery(`SELECT * FROM person WHERE first_name = :fn`, map[string]interface{}{"fn": "Bin"}) // or db.NamedQueryOnMaster(...)
for rows.Next() {
    if err := rows.StructScan(&person); err != nil {
        log.Fatalln(err)
    } 
    fmt.Printf("%#v\n", person)
}

Exec (insert/update/delete/etc...)

result, err := db.Exec("DELETE FROM person WHERE id < ?", 100)

Transaction

// Recommended write transaction this way
tx, e := db.Begin()
if e != nil {
	return e
}
    
shouldAutoRollBack := true
defer func() {
	if e := recover(); e != nil {
		err = fmt.Errorf("%v", e)
		tx.Rollback()
	} else if err != nil && shouldAutoRollBack {
		tx.Rollback()
	}
}()
			
if _, err = tx.Exec("INSERT INTO person(first_name, last_name, email, data) VALUES (?,?,?,?)", "Jon", "Dow", "jon@gmail", []byte{1, 2}); err != nil {
        return
}
    
if _, err = tx.Exec("INSERT INTO person(first_name, last_name, email, data) VALUES (?,?,?,?)", "Jon", "Snow", "snow@gmail", []byte{1}); err != nil {
    return
}
			
if err = tx.Commit(); err != nil {
    shouldAutoRollBack = false
}

Notices

  • APIs supports executing query on master-only or slave-only (or boths). Function name for querying on master-only has suffix OnMaster, querying on slaves-only has suffix OnSlave.
  • Default select/show queries are balanced on slaves.

Documentation

Index

Constants

View Source
const (
	// DefaultHealthCheckPeriodInMilli default period in millisecond mssqlx should do a health check of failed database
	DefaultHealthCheckPeriodInMilli = 40
)

Variables

View Source
var (
	// ErrNoConnection there is no connection to db
	ErrNoConnection = errors.New("no connection available")

	// ErrNoConnectionOrWsrep there is no connection to db or Wsrep is not ready
	ErrNoConnectionOrWsrep = errors.New("no connection available or Wsrep is not ready")
)

Functions

func IsDeadlock added in v1.1.0

func IsDeadlock(err error) bool

IsDeadlock ERROR 1213: Deadlock found when trying to get lock

func IsWsrepNotReady added in v1.1.0

func IsWsrepNotReady(err error) bool

IsWsrepNotReady ERROR 1047: WSREP has not yet prepared node for application use

Types

type DBs

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

DBs sqlx wrapper supports querying master-slave database connections for HA and scalability, auto-balancer integrated.

func ConnectMasterSlaves

func ConnectMasterSlaves(driverName string, masterDSNs []string, slaveDSNs []string, options ...Option) (*DBs, []error)

ConnectMasterSlaves to master-slave databases, healthchecks will ensure they are working driverName: mysql, postgres, etc. masterDSNs: data source names of Masters. slaveDSNs: data source names of ReadQuerySourceSlaves.

func (*DBs) Begin

func (dbs *DBs) Begin() (*Tx, error)

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

Transaction is bound to one of master connections.

func (*DBs) BeginTx

func (dbs *DBs) BeginTx(ctx context.Context, opts *sql.TxOptions) (res *Tx, err 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.

Transaction is bound to one of master connections.

func (*DBs) BeginTxx

func (dbs *DBs) BeginTxx(ctx context.Context, opts *sql.TxOptions) (res *Txx, err error)

BeginTxx begins 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 BeginxContext is canceled.

Transaction is bound to one of master connections.

func (*DBs) Beginx

func (dbs *DBs) Beginx() (res *Txx, err error)

Beginx begins a transaction.

Transaction is bound to one of master connections.

func (*DBs) BindNamed

func (dbs *DBs) BindNamed(query string, arg interface{}) (string, []interface{}, error)

BindNamed binds a query using the DB driver's bindvar type.

func (*DBs) Destroy

func (dbs *DBs) Destroy() []error

Destroy closes all database connections, releasing any open resources.

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

func (*DBs) DestroyMaster

func (dbs *DBs) DestroyMaster() []error

DestroyMaster closes all master database connections, releasing any open resources.

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

func (*DBs) DestroySlave

func (dbs *DBs) DestroySlave() []error

DestroySlave closes all master database connections, releasing any open resources.

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

func (*DBs) DriverName

func (dbs *DBs) DriverName() string

DriverName returns the driverName passed to the Open function for this DB.

func (*DBs) Exec

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

Exec do exec on masters.

func (*DBs) ExecContext

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

ExecContext do exec on masters with context

func (*DBs) ExecContextOnSlave

func (dbs *DBs) ExecContextOnSlave(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

ExecContextOnSlave do exec on slaves with context

func (*DBs) ExecOnSlave

func (dbs *DBs) ExecOnSlave(query string, args ...interface{}) (sql.Result, error)

ExecOnSlave do exec on slaves.

func (*DBs) Get

func (dbs *DBs) Get(dest interface{}, query string, args ...interface{}) (err error)

Get on slaves. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DBs) GetAllMasters

func (dbs *DBs) GetAllMasters() ([]*sqlx.DB, int)

GetAllMasters get all master database connections, included failing one.

func (*DBs) GetAllSlaves

func (dbs *DBs) GetAllSlaves() ([]*sqlx.DB, int)

GetAllSlaves get all slave database connections, included failing one.

func (*DBs) GetContext

func (dbs *DBs) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) (err error)

GetContext on slaves. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DBs) GetContextOnMaster

func (dbs *DBs) GetContextOnMaster(ctx context.Context, dest interface{}, query string, args ...interface{}) (err error)

GetContextOnMaster on masters. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DBs) GetOnMaster

func (dbs *DBs) GetOnMaster(dest interface{}, query string, args ...interface{}) (err error)

GetOnMaster on masters. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DBs) MapperFunc

func (dbs *DBs) MapperFunc(mf func(string) string)

MapperFunc sets a new mapper for this db using the default sqlx struct tag and the provided mapper function.

func (*DBs) MapperFuncMaster

func (dbs *DBs) MapperFuncMaster(mf func(string) string)

MapperFuncMaster sets a new mapper for this db using the default sqlx struct tag and the provided mapper function.

func (*DBs) MapperFuncSlave

func (dbs *DBs) MapperFuncSlave(mf func(string) string)

MapperFuncSlave sets a new mapper for this db using the default sqlx struct tag and the provided mapper function.

func (*DBs) MustBegin

func (dbs *DBs) MustBegin() *Tx

MustBegin starts a transaction, and panics on error. Transaction is bound to one of master connections.

func (*DBs) MustBeginTx

func (dbs *DBs) MustBeginTx(ctx context.Context, opts *sql.TxOptions) *Txx

MustBeginTx starts a transaction, and panics on error.

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 MustBeginContext is canceled.

Transaction is bound to one of master connections.

func (*DBs) MustBeginx

func (dbs *DBs) MustBeginx() *Txx

MustBeginx starts a transaction, and panics on error.

Transaction is bound to one of master connections.

func (*DBs) MustExec

func (dbs *DBs) MustExec(query string, args ...interface{}) sql.Result

MustExec do exec on masters and panic on error

func (*DBs) MustExecContext

func (dbs *DBs) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result

MustExecContext do exec on masters and panic on error

func (*DBs) MustExecContextOnSlave

func (dbs *DBs) MustExecContextOnSlave(ctx context.Context, query string, args ...interface{}) sql.Result

MustExecContextOnSlave do exec on slave only and panic on error

func (*DBs) MustExecOnSlave

func (dbs *DBs) MustExecOnSlave(query string, args ...interface{}) sql.Result

MustExecOnSlave do exec on slave only and panic on error

func (*DBs) NamedExec

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

NamedExec do named exec. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedExecContext

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

NamedExecContext do named exec with context. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedExecContextOnSlave

func (dbs *DBs) NamedExecContextOnSlave(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContextOnSlave do named exec with context on slave. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedExecOnSlave

func (dbs *DBs) NamedExecOnSlave(query string, arg interface{}) (sql.Result, error)

NamedExecOnSlave do named exec on slave. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedQuery

func (dbs *DBs) NamedQuery(query string, arg interface{}) (*sqlx.Rows, error)

NamedQuery do named query. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedQueryContext

func (dbs *DBs) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error)

NamedQueryContext do named query with context. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedQueryContextOnMaster

func (dbs *DBs) NamedQueryContextOnMaster(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error)

NamedQueryContextOnMaster do named query with context on master. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) NamedQueryOnMaster

func (dbs *DBs) NamedQueryOnMaster(query string, arg interface{}) (*sqlx.Rows, error)

NamedQueryOnMaster do named query on master. Any named placeholder parameters are replaced with fields from arg.

func (*DBs) Ping

func (dbs *DBs) Ping() []error

Ping all master-slave database connections

func (*DBs) PingMaster

func (dbs *DBs) PingMaster() []error

PingMaster all master database connections

func (*DBs) PingSlave

func (dbs *DBs) PingSlave() []error

PingSlave all slave database connections

func (*DBs) Prepare

func (dbs *DBs) Prepare(query string) (db *sqlx.DB, stmt *sql.Stmt, err error)

Prepare creates a prepared statement for later queries or executions on masters. 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 (*DBs) PrepareContext

func (dbs *DBs) PrepareContext(ctx context.Context, query string) (db *sqlx.DB, stmt *sql.Stmt, err error)

PrepareContext creates a prepared statement for later queries or executions on masters. 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 (*DBs) PrepareContextOnSlave

func (dbs *DBs) PrepareContextOnSlave(ctx context.Context, query string) (db *sqlx.DB, stmt *sql.Stmt, err error)

PrepareContextOnSlave creates a prepared statement for later queries or executions on slaves. 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 (*DBs) PrepareNamed

func (dbs *DBs) PrepareNamed(query string) (db *sqlx.DB, stmt *sqlx.NamedStmt, err error)

PrepareNamed returns an sqlx.NamedStmt on masters

func (*DBs) PrepareNamedContext

func (dbs *DBs) PrepareNamedContext(ctx context.Context, query string) (db *sqlx.DB, stmt *sqlx.NamedStmt, err error)

PrepareNamedContext returns an sqlx.NamedStmt on masters

func (*DBs) PrepareNamedContextOnSlave

func (dbs *DBs) PrepareNamedContextOnSlave(ctx context.Context, query string) (db *sqlx.DB, stmt *sqlx.NamedStmt, err error)

PrepareNamedContextOnSlave returns an sqlx.NamedStmt on slaves

func (*DBs) PrepareNamedOnSlave

func (dbs *DBs) PrepareNamedOnSlave(query string) (db *sqlx.DB, stmt *sqlx.NamedStmt, err error)

PrepareNamedOnSlave returns an sqlx.NamedStmt on slaves

func (*DBs) PrepareOnSlave

func (dbs *DBs) PrepareOnSlave(query string) (db *sqlx.DB, stmt *sql.Stmt, err error)

PrepareOnSlave creates a prepared statement for later queries or executions on slaves. 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 (*DBs) Preparex

func (dbs *DBs) Preparex(query string) (db *sqlx.DB, stmt *sqlx.Stmt, err error)

Preparex creates a prepared statement for later queries or executions on masters. But return sqlx.Stmt instead of sql.Stmt. 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 (*DBs) PreparexContext

func (dbs *DBs) PreparexContext(ctx context.Context, query string) (db *sqlx.DB, stmt *sqlx.Stmt, err error)

PreparexContext creates a prepared statement for later queries or executions on masters. But return sqlx.Stmt instead of sql.Stmt. 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 (*DBs) PreparexContextOnSlave

func (dbs *DBs) PreparexContextOnSlave(ctx context.Context, query string) (db *sqlx.DB, stmt *sqlx.Stmt, err error)

PreparexContextOnSlave creates a prepared statement for later queries or executions on slaves. But return sqlx.Stmt instead of sql.Stmt. 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 (*DBs) PreparexOnSlave

func (dbs *DBs) PreparexOnSlave(query string) (db *sqlx.DB, stmt *sqlx.Stmt, err error)

PreparexOnSlave creates a prepared statement for later queries or executions on slaves. But return sqlx.Stmt instead of sql.Stmt. 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 (*DBs) Query

func (dbs *DBs) Query(query string, args ...interface{}) (r *sql.Rows, err error)

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

func (*DBs) QueryContext

func (dbs *DBs) QueryContext(ctx context.Context, query string, args ...interface{}) (r *sql.Rows, err error)

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

func (*DBs) QueryContextOnMaster

func (dbs *DBs) QueryContextOnMaster(ctx context.Context, query string, args ...interface{}) (r *sql.Rows, err error)

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

func (*DBs) QueryOnMaster

func (dbs *DBs) QueryOnMaster(query string, args ...interface{}) (r *sql.Rows, err error)

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

func (*DBs) QueryRow

func (dbs *DBs) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow executes a query on slaves 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.

func (*DBs) QueryRowContext

func (dbs *DBs) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRowContext executes a query on slaves 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.

func (*DBs) QueryRowContextOnMaster

func (dbs *DBs) QueryRowContextOnMaster(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRowContextOnMaster executes a query on masters 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.

func (*DBs) QueryRowOnMaster

func (dbs *DBs) QueryRowOnMaster(query string, args ...interface{}) *sql.Row

QueryRowOnMaster executes a query on masters 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.

func (*DBs) QueryRowx

func (dbs *DBs) QueryRowx(query string, args ...interface{}) *sqlx.Row

QueryRowx executes a query on slaves that is expected to return at most one row. But return sqlx.Row instead of sql.Row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called.

func (*DBs) QueryRowxContext

func (dbs *DBs) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row

QueryRowxContext executes a query on slaves 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.

func (*DBs) QueryRowxContextOnMaster

func (dbs *DBs) QueryRowxContextOnMaster(ctx context.Context, query string, args ...interface{}) *sqlx.Row

QueryRowxContextOnMaster executes a query on masters 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.

func (*DBs) QueryRowxOnMaster

func (dbs *DBs) QueryRowxOnMaster(query string, args ...interface{}) *sqlx.Row

QueryRowxOnMaster executes a query on masters 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.

func (*DBs) Queryx

func (dbs *DBs) Queryx(query string, args ...interface{}) (r *sqlx.Rows, err error)

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

func (*DBs) QueryxContext

func (dbs *DBs) QueryxContext(ctx context.Context, query string, args ...interface{}) (r *sqlx.Rows, err error)

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

func (*DBs) QueryxContextOnMaster

func (dbs *DBs) QueryxContextOnMaster(ctx context.Context, query string, args ...interface{}) (r *sqlx.Rows, err error)

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

func (*DBs) QueryxOnMaster

func (dbs *DBs) QueryxOnMaster(query string, args ...interface{}) (r *sqlx.Rows, err error)

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

func (*DBs) Rebind

func (dbs *DBs) Rebind(query string) string

Rebind transforms a query from QUESTION to the DB driver's bindvar type.

func (*DBs) Select

func (dbs *DBs) Select(dest interface{}, query string, args ...interface{}) (err error)

Select do select on slaves. Any placeholder parameters are replaced with supplied args.

func (*DBs) SelectContext

func (dbs *DBs) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) (err error)

SelectContext do select on slaves with context. Any placeholder parameters are replaced with supplied args.

func (*DBs) SelectContextOnMaster

func (dbs *DBs) SelectContextOnMaster(ctx context.Context, dest interface{}, query string, args ...interface{}) (err error)

SelectContextOnMaster do select on masters with context. Any placeholder parameters are replaced with supplied args.

func (*DBs) SelectOnMaster

func (dbs *DBs) SelectOnMaster(dest interface{}, query string, args ...interface{}) (err error)

SelectOnMaster do select on masters. Any placeholder parameters are replaced with supplied args.

func (*DBs) SetConnMaxLifetime

func (dbs *DBs) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a master-slave connection may be reused.

Expired connections may be closed lazily before reuse.

If d <= 0, connections are reused forever.

func (*DBs) SetHealthCheckPeriod

func (dbs *DBs) SetHealthCheckPeriod(period uint64)

SetHealthCheckPeriod sets the period (in millisecond) for checking health of failed nodes for automatic recovery.

Default is 500

func (*DBs) SetMasterConnMaxLifetime

func (dbs *DBs) SetMasterConnMaxLifetime(d time.Duration)

SetMasterConnMaxLifetime sets the maximum amount of time a master connection may be reused.

Expired connections may be closed lazily before reuse.

If d <= 0, connections are reused forever.

func (*DBs) SetMasterHealthCheckPeriod

func (dbs *DBs) SetMasterHealthCheckPeriod(period uint64)

SetMasterHealthCheckPeriod sets the period (in millisecond) for checking health of failed master nodes for automatic recovery.

Default is 500

func (*DBs) SetMasterMaxIdleConns

func (dbs *DBs) SetMasterMaxIdleConns(n int)

SetMasterMaxIdleConns sets the maximum number of connections in the idle connection pool for masters.

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.

func (*DBs) SetMasterMaxOpenConns

func (dbs *DBs) SetMasterMaxOpenConns(n int)

SetMasterMaxOpenConns sets the maximum number of open connections to the master databases.

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 (*DBs) SetMaxIdleConns

func (dbs *DBs) SetMaxIdleConns(n int)

SetMaxIdleConns sets the maximum number of connections in the idle connection pool for all masters-slaves.

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.

func (*DBs) SetMaxOpenConns

func (dbs *DBs) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to all master-slave databases.

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 (*DBs) SetSlaveConnMaxLifetime

func (dbs *DBs) SetSlaveConnMaxLifetime(d time.Duration)

SetSlaveConnMaxLifetime sets the maximum amount of time a slave connection may be reused.

Expired connections may be closed lazily before reuse.

If d <= 0, connections are reused forever.

func (*DBs) SetSlaveHealthCheckPeriod

func (dbs *DBs) SetSlaveHealthCheckPeriod(period uint64)

SetSlaveHealthCheckPeriod sets the period (in millisecond) for checking health of failed slave nodes for automatic recovery.

Default is 500

func (*DBs) SetSlaveMaxIdleConns

func (dbs *DBs) SetSlaveMaxIdleConns(n int)

SetSlaveMaxIdleConns sets the maximum number of connections in the idle connection pool for slaves.

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.

func (*DBs) SetSlaveMaxOpenConns

func (dbs *DBs) SetSlaveMaxOpenConns(n int)

SetSlaveMaxOpenConns sets the maximum number of open connections to the slave databases.

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 (*DBs) Stats

func (dbs *DBs) Stats() (stats []sql.DBStats)

Stats returns database statistics.

func (*DBs) StatsMaster

func (dbs *DBs) StatsMaster() (stats []sql.DBStats)

StatsMaster returns master database statistics.

func (*DBs) StatsSlave

func (dbs *DBs) StatsSlave() (stats []sql.DBStats)

StatsSlave returns slave database statistics.

type Instantiate added in v1.1.2

type Instantiate func(driverName, dsn string) (*sql.DB, error)

Instantiate db.

type Option added in v1.0.8

type Option func(*clusterOptions)

Option setter.

func WithDBInstantiate added in v1.1.2

func WithDBInstantiate(f Instantiate) Option

WithDBInstantiate overwrite instantiate for db conn.

func WithReadQuerySource added in v1.0.8

func WithReadQuerySource(source ReadQuerySource) Option

WithReadQuerySource sets default sources for read-queries.

func WithWsrep added in v1.0.8

func WithWsrep() Option

WithWsrep indicates galera/wsrep cluster

type ReadQuerySource added in v1.0.8

type ReadQuerySource int

ReadQuerySource enums.

const (
	// ReadQuerySourceSlaves setting indicates: read-queries will be distributed only among slaves.
	//
	// Note: there is no option for Master. One could use functions like `QueryMaster`, etc
	// to query from masters only.
	ReadQuerySourceSlaves ReadQuerySource = iota

	// ReadQuerySourceAll setting indicates: read-queries will be distributed among both masters and slaves.
	//
	// Note: this is default setting.
	ReadQuerySourceAll
)

type Stmt added in v1.1.0

type Stmt struct {
	*sql.Stmt
}

Stmt wraps over sql.Stmt

func (*Stmt) Exec added in v1.1.0

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

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

func (*Stmt) ExecContext added in v1.1.0

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

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

func (*Stmt) Query added in v1.1.0

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

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

func (*Stmt) QueryContext added in v1.1.0

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

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

type Stmtx added in v1.1.0

type Stmtx struct {
	*sqlx.Stmt
}

Stmtx wraps over sqlx.Stmt

func (*Stmtx) Exec added in v1.1.0

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

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

func (*Stmtx) ExecContext added in v1.1.0

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

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

func (*Stmtx) Query added in v1.1.0

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

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

func (*Stmtx) QueryContext added in v1.1.0

func (s *Stmtx) QueryContext(ctx context.Context, args ...interface{}) (result *sql.Rows, err error)

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

func (*Stmtx) Queryx added in v1.1.0

func (s *Stmtx) Queryx(args ...interface{}) (*sqlx.Rows, error)

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

func (*Stmtx) QueryxContext added in v1.1.0

func (s *Stmtx) QueryxContext(ctx context.Context, args ...interface{}) (result *sqlx.Rows, err error)

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

type Tx added in v1.1.0

type Tx struct {
	*sql.Tx
}

Tx wraps over sql.Tx

func (*Tx) Commit added in v1.1.0

func (t *Tx) Commit() (err error)

Commit commits the transaction.

func (*Tx) Exec added in v1.1.0

func (t *Tx) Exec(query string, args ...interface{}) (result sql.Result, err error)

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

func (*Tx) ExecContext added in v1.1.0

func (t *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error)

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

func (*Tx) Prepare added in v1.1.0

func (t *Tx) Prepare(query string) (*Stmt, error)

Prepare 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.

func (*Tx) PrepareContext added in v1.1.0

func (t *Tx) PrepareContext(ctx context.Context, query string) (result *Stmt, err 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.

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 added in v1.1.0

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

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

func (*Tx) QueryContext added in v1.1.0

func (t *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (result *sql.Rows, err error)

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

type Txx added in v1.1.0

type Txx struct {
	*sqlx.Tx
}

Txx wraps over sqlx.Tx

func (*Txx) Commit added in v1.1.0

func (t *Txx) Commit() (err error)

Commit commits the transaction.

func (*Txx) Exec added in v1.1.0

func (t *Txx) Exec(query string, args ...interface{}) (result sql.Result, err error)

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

func (*Txx) ExecContext added in v1.1.0

func (t *Txx) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error)

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

func (*Txx) Prepare added in v1.1.0

func (t *Txx) Prepare(query string) (*Stmt, error)

Prepare 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.

func (*Txx) PrepareContext added in v1.1.0

func (t *Txx) PrepareContext(ctx context.Context, query string) (result *Stmt, err 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.

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 (*Txx) Preparex added in v1.1.0

func (t *Txx) Preparex(query string) (*Stmtx, error)

Preparex 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.

func (*Txx) PreparexContext added in v1.1.0

func (t *Txx) PreparexContext(ctx context.Context, query string) (result *Stmtx, err error)

PreparexContext 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.

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 (*Txx) Query added in v1.1.0

func (t *Txx) Query(query string, args ...interface{}) (*sql.Rows, error)

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

func (*Txx) QueryContext added in v1.1.0

func (t *Txx) QueryContext(ctx context.Context, query string, args ...interface{}) (result *sql.Rows, err error)

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

func (*Txx) Queryx added in v1.1.0

func (t *Txx) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)

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

func (*Txx) QueryxContext added in v1.1.0

func (t *Txx) QueryxContext(ctx context.Context, query string, args ...interface{}) (result *sqlx.Rows, err error)

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

Jump to

Keyboard shortcuts

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