Documentation
¶
Overview ¶
Package sqlkit is a thin, batteries-included layer over github.com/jmoiron/sqlx for PostgreSQL, SQLite and ClickHouse.
It provides:
- Connections from a Config (JSON/YAML friendly) or a Connector builder, with sane pool defaults. Drivers: "postgres" (lib/pq, default), "pgx" (jackc/pgx), "sqlite" (modernc.org/sqlite, pure Go, no cgo) and "clickhouse" (mailru/go-clickhouse).
- A DB interface implemented by a single client (NewDB), a shard client (NewShardDB) and a primary/replica Cluster with replication lag tracking (NewCluster, ConnectCluster).
- Context-propagated transactions: Transactor, WithTx, BeginTx with ReadOnly, Isolation and Join. Every DB method runs in the transaction carried by ctx, so repositories need no tx parameter.
- Offset and keyset (cursor) pagination with opaque page tokens: OffsetPager, CursorPager, NewPager, PageOf; a go-sqlbuilder adapter lives in the sqlbpager subpackage.
- golang-migrate migrations from a directory or an embed.FS for PostgreSQL and SQLite: Migrator.
- Driver-independent error classification: Classify, IsDuplicate, IsForeignKey, IsNotNull, IsCheckViolation, DuplicateFields.
SQLite ¶
A Config with Driver "sqlite" uses DSN as the database file path (or ":memory:", or a "file:" URI) and adds connection pragmas: WAL journal, synchronous=NORMAL, foreign_keys=on, busy_timeout=5000 and IMMEDIATE write transactions (see SQLiteOptions and SQLiteDSN):
conn, err := sqlkit.ConnectFromConfig(sqlkit.Config{Driver: sqlkit.SQLiteDriver, DSN: "app.db"})
SQLite uses "?" placeholders. Queries written with "?" can be rebound for any driver with Rebind, and Placeholder returns the placeholder func of a driver for Pager.Where. "$N" placeholders work with SQLite too, so Arguments and Dollar can be shared with PostgreSQL code.
Transactions ¶
A Transactor stores the transaction in the context; the clients pick it up automatically:
err := sqlkit.WithTx(ctx, tr, func(ctx context.Context) error {
_, err := db.ExecContext(ctx, "UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1)
return err
})
Without Join, a nested WithTx opens a second transaction on another connection; pass Join() to reuse the transaction already in ctx.
Example (Sqlite) ¶
Example_sqlite opens a SQLite database from a config, applies embedded migrations, writes in a transaction and reads the rows page by page with a cursor.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"testing/fstest"
"github.com/boostgo/sqlkit"
)
func main() {
dir, _ := os.MkdirTemp("", "sqlkit-example")
defer os.RemoveAll(dir)
conn, err := sqlkit.ConnectFromConfig(sqlkit.Config{
Driver: sqlkit.SQLiteDriver,
DSN: filepath.Join(dir, "app.db"), // WAL, foreign_keys=on, busy_timeout=5000 by default
})
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
ctx := context.Background()
// usually a //go:embed migrations/*.sql embed.FS
migrations := fstest.MapFS{
"migrations/0001_notes.up.sql": {Data: []byte(
"CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL UNIQUE)")},
}
if err = sqlkit.NewMigrator(ctx, conn, "app").WithFS(migrations, "migrations").MigrateContext(ctx); err != nil {
fmt.Println(err)
return
}
db := sqlkit.NewDBWithOptions(conn, sqlkit.WithPaging(sqlkit.PagingCursor))
tr := sqlkit.NewTransactor(conn)
err = sqlkit.WithTx(ctx, tr, func(ctx context.Context) error {
for _, title := range []string{"alpha", "beta", "gamma"} {
if _, err := db.ExecContext(ctx, "INSERT INTO notes (title) VALUES (?)", title); err != nil {
return err
}
}
return nil
})
fmt.Println("insert:", err)
_, err = db.ExecContext(ctx, "INSERT INTO notes (title) VALUES (?)", "alpha")
fmt.Println("duplicate:", sqlkit.IsDuplicate(err))
type note struct {
ID int64 `db:"id"`
Title string `db:"title"`
}
cursor := ""
for {
p := sqlkit.NewPager(db, sqlkit.PageRequest{Size: 2, Cursor: cursor}, sqlkit.Asc("id"))
query := "SELECT id, title FROM notes"
where, args := p.Where(sqlkit.Placeholder(sqlkit.DriverName(db), 1))
if where != "" {
query += " WHERE " + where
}
var rows []note
if err = db.SelectContext(ctx, &rows, query+" "+p.OrderBy()+" "+p.LimitOffset(), args...); err != nil {
fmt.Println(err)
return
}
page := sqlkit.PageOf(rows, p, func(n note) []any { return []any{n.ID} })
fmt.Println(page.Items, page.HasMore)
if !page.HasMore {
break
}
cursor = *page.NextCursor
}
}
Output: insert: <nil> duplicate: true [{1 alpha} {2 beta}] true [{3 gamma}] false
Index ¶
- Constants
- Variables
- func Atomic(ctx context.Context, conn *sqlx.DB, fn func(ctx context.Context) error) errordeprecated
- func BeginTx(ctx context.Context, tr Transactor, opts ...TxOption) (context.Context, error)
- func Classify(err error) error
- func Connect(driverName, connectionString string, timeout time.Duration, ...) (*sqlx.DB, error)
- func ConnectFromConfig(cfg Config, opts ...func(connection *sqlx.DB)) (*sqlx.DB, error)
- func ConnectionString(host string, port int, username, password string, database string, ...) string
- func Dollar(start int) func(v any) string
- func DriverName(db DB) string
- func Duplicate(err error) (bool, string)deprecated
- func DuplicateFields(err error) (fields []string, ok bool)
- func EachShard(conn DB, fn func(conn DB) error) (err error)
- func EachShardAsync(conn DB, fn func(conn DB) error, limit ...int) (err error)
- func ForcePrimary(ctx context.Context) context.Context
- func GetTx(ctx context.Context) (*sqlx.Tx, bool)
- func HandleError(err error) errordeprecated
- func IsCheckViolation(err error) bool
- func IsDuplicate(err error) bool
- func IsForeignKey(err error) bool
- func IsNoRows(err error) bool
- func IsNotNull(err error) bool
- func MaxConnectionsOption(open, idle int) func(conn *sqlx.DB)
- func MaxTimeOption(lifetime, idle time.Duration) func(conn *sqlx.DB)
- func Page(pageSize int64, page int) (offset int, limit int)
- func Placeholder(driverName string, start int) func(v any) string
- func PreferReplica(ctx context.Context) context.Context
- func Question() func(v any) string
- func Rebind(db DB, query string) string
- func RegisterDriver(driverName string, driver driver.Driver)
- func ReplicaPreferred(ctx context.Context) bool
- func ReplicaRequired(ctx context.Context) bool
- func RequireReplica(ctx context.Context) context.Context
- func RewriteTx(key string, original context.Context, toCopy context.Context) context.Context
- func RunTransaction(conn *sqlx.DB, transactionActions func(tx *sqlx.Tx) error) errordeprecated
- func RunTransactionContext(ctx context.Context, conn *sqlx.DB, transactionActions func(tx *sqlx.Tx) error) (err error)
- func SQLiteDSN(path string, opts SQLiteOptions) string
- func SetTx(ctx context.Context, tx *sqlx.Tx) context.Context
- func WithConnMaxIdleTime(d time.Duration) func(*sqlx.DB)
- func WithConnMaxLifetime(d time.Duration) func(*sqlx.DB)
- func WithMaxIdle(n int) func(*sqlx.DB)
- func WithMaxOpen(n int) func(*sqlx.DB)
- func WithTx(ctx context.Context, tr Transactor, fn func(ctx context.Context) error, ...) (err error)
- type Arguments
- type Cluster
- func (c *Cluster) Close() error
- func (c *Cluster) Connection() *sqlx.DB
- func (c *Cluster) DriverName() string
- func (c *Cluster) EachShard(_ func(conn DB) error) error
- func (c *Cluster) EachShardAsync(_ func(conn DB) error, _ ...int) error
- func (c *Cluster) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
- func (c *Cluster) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
- func (c *Cluster) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
- func (c *Cluster) NamedQueryRowxContext(ctx context.Context, query string, arg any) (*sqlx.Row, error)
- func (c *Cluster) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
- func (c *Cluster) PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)
- func (c *Cluster) Primary() DB
- func (c *Cluster) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
- func (c *Cluster) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row
- func (c *Cluster) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)
- func (c *Cluster) Replica(ctx context.Context) DB
- func (c *Cluster) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
- func (c *Cluster) State() ReplicaState
- func (c *Cluster) States() []ReplicaState
- type ClusterConfig
- type ClusterOption
- func WithLagCheckInterval(d time.Duration) ClusterOption
- func WithMaxLag(d time.Duration) ClusterOption
- func WithNamedReplica(name string, db *sqlx.DB) ClusterOption
- func WithRecoveryConflictRetry(on bool) ClusterOption
- func WithReplica(replica *sqlx.DB) ClusterOption
- func WithReplicaBalancer(b ReplicaBalancer) ClusterOption
- func WithStateHook(fn func(ReplicaState)) ClusterOption
- type Config
- type ConnectionSelector
- type Connections
- type Connector
- func (connector *Connector) BinaryParameters(binaryParameters bool) *Connector
- func (connector *Connector) Build() string
- func (connector *Connector) BuildClickhouse() string
- func (connector *Connector) BuildMigration() string
- func (connector *Connector) ClickhouseScheme(scheme string) *Connector
- func (connector *Connector) Connect(driverName string, options ...func(connection *sqlx.DB)) (*sqlx.DB, error)
- func (connector *Connector) ConnectMigration(driverName string, options ...func(connection *sqlx.DB)) (*sqlx.DB, error)
- func (connector *Connector) ConnectionMaxLifetime(connectionMaxLifetime time.Duration) *Connector
- func (connector *Connector) Database(database string) *Connector
- func (connector *Connector) Host(host string) *Connector
- func (connector *Connector) MaxIdleConnections(maxIdleConnections int) *Connector
- func (connector *Connector) MaxIdleTime(maxIdleTime time.Duration) *Connector
- func (connector *Connector) MaxOpenConnections(maxOpenConnections int) *Connector
- func (connector *Connector) MigrationDatabase(database string) *Connector
- func (connector *Connector) MigrationHost(host string) *Connector
- func (connector *Connector) MigrationPassword(password string) *Connector
- func (connector *Connector) MigrationPort(port int) *Connector
- func (connector *Connector) MigrationUsername(username string) *Connector
- func (connector *Connector) Password(password string) *Connector
- func (connector *Connector) Port(port int) *Connector
- func (connector *Connector) ReadTimeout(readTimeout int) *Connector
- func (connector *Connector) SSLMode(mode string) *Connector
- func (connector *Connector) Schema(schema string) *Connector
- func (connector *Connector) String() string
- func (connector *Connector) Timeout(timeout time.Duration) *Connector
- func (connector *Connector) Username(username string) *Connector
- func (connector *Connector) WriteTimeout(writeTimeout int) *Connector
- type DB
- type DBOption
- type GetContext
- type Migrator
- type NamedExecContext
- type NamedQueryRowxContext
- type PageRequest
- type PageResult
- type Pager
- func (p *Pager) Err() error
- func (p *Pager) Limit() int
- func (p *Pager) LimitOffset() string
- func (p *Pager) Offset() int
- func (p *Pager) OrderBy() string
- func (p *Pager) OrderByColumns() []string
- func (p *Pager) Page() int
- func (p *Pager) Size() int
- func (p *Pager) Where(ph func(v any) string) (string, []any)
- type PagerOption
- type PagingMode
- type PrepareContext
- type ReplicaBalancer
- type ReplicaConfig
- type ReplicaState
- type SQLiteOptions
- type SelectContext
- type ShardConnect
- type ShardConnectString
- type Transactiondeprecated
- type Transactor
- type TransactorConnectionProvider
- type TxBeginner
- type TxOption
Examples ¶
Constants ¶
const ( ReasonOK = "ok" ReasonNoReplica = "no_replica" ReasonNotChecked = "not_checked" ReasonLagExceeded = "lag_exceeded" ReasonCheckFailed = "check_failed" ReasonReplayUnknown = "replay_unknown" )
Reasons of ReplicaState.
const ( // PqDriver is the github.com/lib/pq PostgreSQL driver. It is the default when no driver is given. PqDriver = "postgres" // PgxDriver is the github.com/jackc/pgx/v5 PostgreSQL driver (database/sql adapter). PgxDriver = "pgx" // ChDriver is the github.com/mailru/go-clickhouse ClickHouse driver (HTTP protocol). ChDriver = "clickhouse" // SQLiteDriver is the pure-Go modernc.org/sqlite driver (no cgo). SQLiteDriver = "sqlite" )
Driver names understood by the package.
const ( DefaultSQLiteJournalMode = "WAL" DefaultSQLiteSynchronous = "NORMAL" DefaultSQLiteBusyTimeoutMs = 5000 DefaultSQLiteTxLock = "immediate" )
SQLite defaults applied by SQLiteDSN for zero SQLiteOptions fields.
const DefaultMigrationsDirectory = "./migrations"
DefaultMigrationsDirectory is the directory read by a Migrator without WithMigrationsDirectory/WithFS.
Variables ¶
var ( // ErrOpenConnect wraps an error of sql.Open. ErrOpenConnect = errors.New("sqlkit.open_connect") // ErrPing wraps an error of the initial ping of Connect; the pool is closed. ErrPing = errors.New("sqlkit.ping") // ErrConnectionStringEmpty is returned by ConnectShards for a shard without a connection string. ErrConnectionStringEmpty = errors.New("sqlkit.connection_string_empty") // ErrConnectionStringDuplicate is returned by ConnectShards for a repeated shard key. ErrConnectionStringDuplicate = errors.New("sqlkit.connection_string_duplicate") // ErrConnectionIsNotShard is returned by EachShard/EachShardAsync for a DB that is not a shard client. ErrConnectionIsNotShard = errors.New("sqlkit.connection_is_not_shard") // ErrConnectionKeyEmpty is returned by ConnectShards for a shard without a key. ErrConnectionKeyEmpty = errors.New("sqlkit.connection_key_empty") // ErrConnNotSelected is returned by the shard client when its ConnectionSelector returns nil. ErrConnNotSelected = errors.New("sqlkit.connection.not_selected") // ErrMethodNotSupportedInSingle is returned by the shard-only methods of the single client and Cluster. ErrMethodNotSupportedInSingle = errors.New("sqlkit.method_not_supported_in_single") )
Connection errors.
var ( // ErrConfigNoHost means Config.Host is empty. ErrConfigNoHost = errors.New("sqlkit.config.no_host") // ErrConfigNoPort means Config.Port is 0. ErrConfigNoPort = errors.New("sqlkit.config.no_port") // ErrConfigNoDatabase means Config.Database is empty. ErrConfigNoDatabase = errors.New("sqlkit.config.no_database") // ErrConfigNoUsername means Config.Username is empty. ErrConfigNoUsername = errors.New("sqlkit.config.no_username") // ErrConfigNoPassword means Config.Password is empty. ErrConfigNoPassword = errors.New("sqlkit.config.no_password") // ErrConfigNoDSN means Config.DSN is empty for a driver that needs it (SQLite). ErrConfigNoDSN = errors.New("sqlkit.config.no_dsn") )
Config errors returned by Config.Validate.
var ( // ErrMigrateOpenConn means a connection for the migration could not be taken from the pool. ErrMigrateOpenConn = errors.New("sqlkit.migrate.open_conn") // ErrMigrateGetDriver wraps an error of the golang-migrate database driver. ErrMigrateGetDriver = errors.New("sqlkit.migrate.get_driver") // ErrMigrateLock means the PostgreSQL lock_timeout could not be set. ErrMigrateLock = errors.New("sqlkit.migrate.lock") // ErrMigrateReadMigrationsDir means the migrations could not be read. ErrMigrateReadMigrationsDir = errors.New("sqlkit.migrate.read_migrations_dir") // ErrMigrateUp wraps an error of applying the migrations. ErrMigrateUp = errors.New("sqlkit.migrate.up") // ErrMigrateUnsupportedDriver means the driver of the connection has no migration support (ClickHouse). ErrMigrateUnsupportedDriver = errors.New("sqlkit.migrate.unsupported_driver") )
Migration errors returned by Migrator.
var ( // ErrTransactorBegin wraps an error of beginning a transaction. ErrTransactorBegin = errors.New("sqlkit.transactor.begin") // ErrTransactorCommit wraps an error of Commit. ErrTransactorCommit = errors.New("sqlkit.transactor.commit") // ErrTransactorRollback wraps an error of Rollback. ErrTransactorRollback = errors.New("sqlkit.transactor.rollback") // ErrTxOptionNotSupported is returned by BeginTx/WithTx if tx options are given to a Transactor that // can not honor them. ErrTxOptionNotSupported = errors.New("sqlkit.transactor.option_not_supported") )
Transaction errors.
var ( // ErrStatementPrepare wraps an error of preparing a statement. ErrStatementPrepare = errors.New("sqlkit.statement.prepare") // ErrStatementExecuteQuery wraps an error of executing a prepared statement. ErrStatementExecuteQuery = errors.New("sqlkit.statement.execute_query") )
Statement errors, reserved for prepared statement helpers.
var ( // ErrInvalidCursor is a broken page token: a client error (e.g. HTTP 400). ErrInvalidCursor = errors.New("sqlkit.pager.invalid_cursor") // ErrInvalidPager is a Pager configuration error in code: a server error (e.g. HTTP 500). ErrInvalidPager = errors.New("sqlkit.pager.invalid") )
Pagination errors returned by Pager.Err.
var ( // ErrDuplicate is a unique or primary key violation. ErrDuplicate = errors.New("sqlkit.duplicate") // ErrForeignKeyViolation is a foreign key violation. ErrForeignKeyViolation = errors.New("sqlkit.foreign_key_violation") // ErrNotNull is a NOT NULL violation. ErrNotNull = errors.New("sqlkit.not_null") // ErrCheckViolation is a CHECK constraint violation. ErrCheckViolation = errors.New("sqlkit.check_violation") )
Constraint violations returned by Classify (PostgreSQL and SQLite).
var ( // ErrClusterNoPrimary is returned by NewCluster if the primary connection is nil. ErrClusterNoPrimary = errors.New("sqlkit.cluster.no_primary") // ErrClusterOption is returned by NewCluster and ConnectCluster for an invalid option or config. ErrClusterOption = errors.New("sqlkit.cluster.option") // no replica is usable. ErrReplicaUnavailable = errors.New("sqlkit.cluster.replica_unavailable") )
Cluster errors.
var ( // ErrNamedQueryRowxContext wraps errors of NamedQueryRowxContext. ErrNamedQueryRowxContext = errors.New("sqlkit.NamedQueryRowxContext") // ErrPrepareNamedContext wraps errors of PrepareNamedContext. ErrPrepareNamedContext = errors.New("sqlkit.PrepareNamedContext") // ErrGetContext wraps errors of GetContext. ErrGetContext = errors.New("sqlkit.GetContext") // ErrSelectContext wraps errors of SelectContext. ErrSelectContext = errors.New("sqlkit.SelectContext") // ErrNamedExecContext wraps errors of NamedExecContext. ErrNamedExecContext = errors.New("sqlkit.NamedExecContext") // ErrPrepareContext wraps errors of PrepareContext. ErrPrepareContext = errors.New("sqlkit.PrepareContext") // ErrQueryxContext wraps errors of QueryxContext. ErrQueryxContext = errors.New("sqlkit.QueryxContext") // ErrQueryContext wraps errors of QueryContext. ErrQueryContext = errors.New("sqlkit.QueryContext") // ErrQueryRowxContext wraps errors of QueryRowxContext (carried by the returned row). ErrQueryRowxContext = errors.New("sqlkit.QueryRowxContext") // ErrExecContext wraps errors of ExecContext. ErrExecContext = errors.New("sqlkit.ExecContext") )
Method errors: every error of a DB method is wrapped with the sentinel of that method, so errors.Is(err, ErrExecContext) tells where it happened and errors.As still finds the driver error.
Functions ¶
func Atomic
deprecated
Atomic runs fn in a transaction. If ctx already holds a transaction, fn joins it.
The transaction is rolled back if fn returns an error or panics (the panic is re-raised); otherwise it is committed and the Commit error is returned.
Deprecated: use WithTx with Join().
func BeginTx ¶
BeginTx begins a transaction on tr with options.
If tr implements TxBeginner (the transactor of this library) it is used with opts. Otherwise, without opts, tr.Begin is called; with opts a foreign Transactor (e.g. a mock) can not honor them and ErrTxOptionNotSupported is returned.
func Classify ¶
Classify maps a constraint violation of PostgreSQL (lib/pq or pgx) or SQLite (modernc.org/sqlite) to ErrDuplicate, ErrForeignKeyViolation, ErrNotNull or ErrCheckViolation, keeping the original error in the chain (errors.As still finds *pq.Error, *pgconn.PgError or *sqlite.Error).
PostgreSQL 23505, SQLite UNIQUE / PRIMARY KEY -> ErrDuplicate PostgreSQL 23503, SQLite FOREIGN KEY -> ErrForeignKeyViolation PostgreSQL 23502, SQLite NOT NULL -> ErrNotNull PostgreSQL 23514, SQLite CHECK -> ErrCheckViolation
Any other error is returned as is (never nil for a non-nil err); Classify(nil) is nil.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/boostgo/sqlkit"
)
func main() {
conn, err := sqlkit.ConnectFromConfig(sqlkit.Config{Driver: sqlkit.SQLiteDriver, DSN: ":memory:"})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ctx := context.Background()
db := sqlkit.NewDB(conn)
_, _ = db.ExecContext(ctx, "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE)")
_, _ = db.ExecContext(ctx, "INSERT INTO users (email) VALUES (?)", "a@example.com")
_, err = db.ExecContext(ctx, "INSERT INTO users (email) VALUES (?)", "a@example.com")
err = sqlkit.Classify(err)
fields, _ := sqlkit.DuplicateFields(err)
fmt.Println(errors.Is(err, sqlkit.ErrDuplicate), fields)
}
Output: true [email]
func Connect ¶
func Connect( driverName, connectionString string, timeout time.Duration, options ...func(connection *sqlx.DB), ) (*sqlx.DB, error)
Connect to the database.
"options" can override default settings
func ConnectFromConfig ¶
ConnectFromConfig connects with the driver and connection string of cfg (see Config.ConnectionString) and pings the database, with a timeout of cfg.TimeoutMs if it is set.
Pool settings are applied in order: the defaults, the non-zero pool fields of cfg, then opts. An in-memory SQLite database always gets a single, never expiring connection.
func ConnectionString ¶
func ConnectionString( host string, port int, username, password string, database string, binaryParameters bool, ) string
ConnectionString returns built connection string by provided params for sqlx lib
func Dollar ¶
Dollar returns a placeholder func for Pager.Where: "$start", "$start+1", ... It ignores the values.
func DriverName ¶
DriverName returns the database/sql driver name used by db ("postgres", "pgx", "clickhouse", "sqlite", ...). For a shard client it is the driver of the shards; for a Cluster the driver of the primary. It returns "" if the driver can not be determined (e.g. a mock DB).
func DuplicateFields ¶
DuplicateFields returns the columns of a unique violation.
For PostgreSQL (*pq.Error and *pgconn.PgError, SQLSTATE 23505) the columns are taken from the error Detail; for SQLite (*sqlite.Error) from the message "UNIQUE constraint failed: t.a, t.b" (the table prefix is removed). If err is not a unique violation or the columns can not be parsed, it returns nil, false.
func EachShardAsync ¶
EachShardAsync do the same as EachShard but in parallel every shard.
If provide "limit", count of goroutines will be limited
func ForcePrimary ¶
ForcePrimary marks ctx: Cluster sends everything to primary. It overrides PreferReplica and RequireReplica.
func GetTx ¶
GetTx returns the transaction carried by ctx, if any.
The typed key of SetTx is checked first, then the string key "sqlkit:tx" (Transactor.Key).
func HandleError
deprecated
func IsCheckViolation ¶
IsCheckViolation reports whether err is a CHECK constraint violation.
func IsDuplicate ¶
IsDuplicate reports whether err is a unique (or primary key) violation.
func IsForeignKey ¶
IsForeignKey reports whether err is a foreign key violation.
func MaxConnectionsOption ¶
MaxConnectionsOption sets max open & idle connections
func MaxTimeOption ¶
MaxTimeOption sets connection max lifetime & max idle time settings
func Placeholder ¶
Placeholder returns a placeholder func for Pager.Where that matches the bind style of driverName: Dollar(start) for PostgreSQL and unknown drivers, Question() for SQLite and ClickHouse (start is ignored for "?" placeholders: the arguments are positional).
func PreferReplica ¶
PreferReplica marks ctx: read methods of Cluster may go to a replica (if one is usable and ctx has no tx).
func Rebind ¶
Rebind converts a query written with "?" placeholders to the placeholder style of the driver of db: "$1, $2, ..." for PostgreSQL (and unknown drivers), "?" for SQLite and ClickHouse.
It lets a repository keep one query text for every supported database.
Example ¶
package main
import (
"fmt"
"github.com/jmoiron/sqlx"
"github.com/boostgo/sqlkit"
)
func main() {
query := "SELECT * FROM users WHERE tenant_id = ? AND email = ?"
pg := sqlkit.NewDB(sqlx.NewDb(nil, sqlkit.PgxDriver))
lite := sqlkit.NewDB(sqlx.NewDb(nil, sqlkit.SQLiteDriver))
fmt.Println(sqlkit.Rebind(pg, query))
fmt.Println(sqlkit.Rebind(lite, query))
}
Output: SELECT * FROM users WHERE tenant_id = $1 AND email = $2 SELECT * FROM users WHERE tenant_id = ? AND email = ?
func RegisterDriver ¶
RegisterDriver registers driver under driverName via sql.Register, unless a driver with that name is already registered (sql.Register would panic).
func ReplicaPreferred ¶
ReplicaPreferred reports whether ctx has PreferReplica and has no ForcePrimary.
func ReplicaRequired ¶
ReplicaRequired reports whether ctx has RequireReplica and has no ForcePrimary.
func RequireReplica ¶
RequireReplica marks ctx: read methods of Cluster go to a usable replica only; if there is none they fail with ErrReplicaUnavailable and never touch primary (outside a transaction, which always uses its own connection). ForcePrimary overrides it; it takes precedence over PreferReplica.
func RewriteTx ¶
RewriteTx take transaction key from original context and copy key to toCopy context.
For the default key "sqlkit:tx" the transaction is copied via GetTx/SetTx.
func RunTransaction
deprecated
func RunTransactionContext ¶
func RunTransactionContext(ctx context.Context, conn *sqlx.DB, transactionActions func(tx *sqlx.Tx) error) (err error)
RunTransactionContext runs transactionActions in a transaction begun with ctx.
The transaction is rolled back if transactionActions returns an error or panics (the panic is re-raised); otherwise it is committed and the Commit error is returned.
func SQLiteDSN ¶
func SQLiteDSN(path string, opts SQLiteOptions) string
SQLiteDSN builds a modernc.org/sqlite connection string for path with the pragmas of opts.
path is a file path ("app.db", "/var/lib/app/data.db"), ":memory:" or a "file:" URI. Query parameters already present in path are kept; the pragmas of opts are added after them. Time values are written in the SQLite format ("_time_format=sqlite"), which sorts correctly as text and keeps cursor pagination over time columns stable.
Example ¶
package main
import (
"fmt"
"github.com/boostgo/sqlkit"
)
func main() {
fmt.Println(sqlkit.SQLiteDSN("app.db", sqlkit.SQLiteOptions{BusyTimeoutMs: 1000}))
}
Output: app.db?_pragma=busy_timeout%281000%29&_pragma=journal_mode%28WAL%29&_pragma=synchronous%28NORMAL%29&_pragma=foreign_keys%281%29&_time_format=sqlite&_txlock=immediate
func SetTx ¶
SetTx returns a copy of ctx that carries tx. The clients of this package run their queries in tx when they get such a context.
func WithConnMaxIdleTime ¶
WithConnMaxIdleTime sets the max connection idle time as is (<= 0 means no limit).
func WithConnMaxLifetime ¶
WithConnMaxLifetime sets the max connection lifetime as is (<= 0 means no limit).
func WithMaxIdle ¶
WithMaxIdle sets the max number of idle connections as is (<= 0 means no idle connections).
func WithMaxOpen ¶
WithMaxOpen sets the max number of open connections as is (database/sql semantics: <= 0 means no limit).
func WithTx ¶
func WithTx(ctx context.Context, tr Transactor, fn func(ctx context.Context) error, opts ...TxOption) (err error)
WithTx runs fn in a transaction: it commits if fn returns nil, rolls back if fn returns an error or panics (the panic is re-raised with the original value).
WARNING: without Join(), a nested WithTx/Begin inside an open transaction opens a SECOND transaction on another connection: it does not see the uncommitted data of the first one and can deadlock on its rows. Pass Join() to reuse the transaction already in ctx; then the nested call does not commit or roll back, the outer level does.
Example ¶
package main
import (
"context"
"fmt"
"github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
"github.com/boostgo/sqlkit"
)
func main() {
raw, mock, _ := sqlmock.New()
defer raw.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE").WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
conn := sqlx.NewDb(raw, "postgres")
db := sqlkit.NewDB(conn)
tr := sqlkit.NewTransactor(conn)
err := sqlkit.WithTx(context.Background(), tr, func(ctx context.Context) error {
_, err := db.ExecContext(ctx, "UPDATE t SET a = 1")
return err
})
fmt.Println(err)
}
Output: <nil>
Types ¶
type Arguments ¶
type Arguments struct {
// contains filtered or unexported fields
}
Arguments Helps manage query arguments count & their values
func NewArguments ¶
NewArguments created instance of Arguments object
func (*Arguments) Add ¶
Add new argument and increment count.
After adding argument use Number method to get "$number" string
type Cluster ¶
type Cluster struct {
// contains filtered or unexported fields
}
Cluster is a DB over a primary and any number of read replicas of PostgreSQL.
Everything goes to primary except read methods called with PreferReplica(ctx) or RequireReplica(ctx), outside of a transaction, while a replica is usable (its replication lag is within WithMaxLag). The replica is chosen among the usable ones by the ReplicaBalancer (RoundRobin by default).
func ConnectCluster ¶
func ConnectCluster(cfg ClusterConfig, opts ...ClusterOption) (*Cluster, error)
ConnectCluster connects to the primary (with ping) and, if cfg.ReplicasEnabled, opens the replicas without ping: an unavailable replica does not stop the start, it stays in "check_failed" and starts serving after a successful lag check. A zero field of a replica config is taken from cfg.Primary: Port, Username, Password, Database, Driver, SSLMode, TimeoutMs, BinaryParameters, MaxOpenConnections, MaxIdleConnections, MaxLifetime, MaxIdleTime, ReadTimeout, WriteTimeout. Migration* and ClickhouseScheme are not inherited.
Options from cfg are applied first, then opts (they win). The returned Cluster owns the connections: Close stops the lag check and closes the replicas and the primary.
Example ¶
ExampleConnectCluster shows the config of a service: a replica takes the zero fields from primary.
package main
import (
"context"
"errors"
"log"
"github.com/boostgo/sqlkit"
)
func main() {
cfg := sqlkit.ClusterConfig{
Primary: sqlkit.Config{
Host: "db-primary", Port: 5432, Username: "app", Password: "secret", Database: "app",
MaxOpenConnections: 20,
},
ReplicasEnabled: true,
Replicas: []sqlkit.ReplicaConfig{
{Name: "ro1", Config: sqlkit.Config{Host: "db-ro1"}},
{Name: "ro2", Config: sqlkit.Config{Host: "db-ro2", MaxOpenConnections: 50}},
},
MaxLagSeconds: 30,
LagCheckIntervalSeconds: 5,
}
cluster, err := sqlkit.ConnectCluster(cfg,
sqlkit.WithReplicaBalancer(sqlkit.LeastLag()),
sqlkit.WithStateHook(func(s sqlkit.ReplicaState) { log.Printf("replica %s: %s", s.Name, s.Reason) }),
)
if err != nil {
log.Print(err) // the primary is unavailable; an unavailable replica does not fail the start
return
}
defer cluster.Close() // stops the lag check, closes the replicas and the primary
var ids []int
err = cluster.SelectContext(sqlkit.RequireReplica(context.Background()), &ids, "SELECT id FROM items")
if errors.Is(err, sqlkit.ErrReplicaUnavailable) {
log.Print("no usable replica")
}
}
Output:
func NewCluster ¶
func NewCluster(primary *sqlx.DB, opts ...ClusterOption) (*Cluster, error)
NewCluster creates a Cluster over primary. With replicas it starts a background lag check; call Close to stop it. Close does not close the given *sqlx.DB: their owner does.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
"github.com/boostgo/sqlkit"
)
func main() {
rawPrimary, primaryMock, _ := sqlmock.New()
defer rawPrimary.Close()
rawA, mockA, _ := sqlmock.New()
defer rawA.Close()
rawB, mockB, _ := sqlmock.New()
defer rawB.Close()
// lag check on start: the LSN of primary once, then both replicas
primaryMock.ExpectQuery("pg_current_wal_lsn").
WillReturnRows(sqlmock.NewRows([]string{"lsn"}).AddRow("0/1"))
for _, m := range []sqlmock.Sqlmock{mockA, mockB} {
m.ExpectQuery("pg_is_in_recovery").
WillReturnRows(sqlmock.NewRows([]string{"rec", "lsn", "caught", "lag"}).AddRow(true, "0/1", true, 0.0))
}
cluster, err := sqlkit.NewCluster(sqlx.NewDb(rawPrimary, "postgres"),
sqlkit.WithNamedReplica("a", sqlx.NewDb(rawA, "postgres")),
sqlkit.WithNamedReplica("b", sqlx.NewDb(rawB, "postgres")),
sqlkit.WithReplicaBalancer(sqlkit.RoundRobin()),
sqlkit.WithMaxLag(30*time.Second),
)
if err != nil {
fmt.Println(err)
return
}
defer cluster.Close() // does not close primary and replicas: the owner does
// a real service does not wait: until the first check everything goes to primary
for st := cluster.States(); !st[0].Usable || !st[1].Usable; st = cluster.States() {
time.Sleep(time.Millisecond)
}
// a heavy list may be read from a replica, and may NOT fall back to primary: RequireReplica
mockA.ExpectQuery("SELECT").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
ctx := sqlkit.RequireReplica(context.Background())
var ids []int
err = cluster.SelectContext(ctx, &ids, "SELECT id FROM items")
fmt.Println(ids, err)
}
Output: [1] <nil>
func (*Cluster) Close ¶
Close stops the lag check and waits for it. A cluster made by ConnectCluster then closes its replicas and primary (errors are joined); a cluster made by NewCluster does NOT close the *sqlx.DB: their owner does. Repeated Close is a no-op and returns nil.
func (*Cluster) Connection ¶
Connection returns the connection of the primary.
func (*Cluster) DriverName ¶
DriverName returns the driver name of the primary.
func (*Cluster) EachShardAsync ¶
EachShardAsync is not supported by Cluster.
func (*Cluster) ExecContext ¶
func (c *Cluster) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
ExecContext always runs on the primary.
func (*Cluster) GetContext ¶
func (c *Cluster) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
GetContext is a read method: it is routed like SelectContext.
func (*Cluster) NamedExecContext ¶
func (c *Cluster) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
NamedExecContext always runs on the primary.
func (*Cluster) NamedQueryRowxContext ¶
func (c *Cluster) NamedQueryRowxContext(ctx context.Context, query string, arg any) (*sqlx.Row, error)
NamedQueryRowxContext is a read method: it is routed like SelectContext.
func (*Cluster) PrepareContext ¶
PrepareContext always runs on the primary.
func (*Cluster) PrepareNamedContext ¶
PrepareNamedContext always runs on the primary.
func (*Cluster) QueryContext ¶
func (c *Cluster) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryContext retries only an error of the call itself; an error from rows.Next/rows.Err is returned as is.
func (*Cluster) QueryRowxContext ¶
func (c *Cluster) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row
QueryRowxContext retries by row.Err() before the row is returned. If a replica is required but none is usable, the returned row carries ErrReplicaUnavailable (row.Err(), row.Scan).
func (*Cluster) QueryxContext ¶
func (c *Cluster) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)
QueryxContext retries only an error of the call itself; an error from rows.Next/rows.Err is returned as is.
func (*Cluster) Replica ¶
Replica returns the client of a usable replica chosen by the balancer, or the primary if no replica is usable now or ctx has a tx.
func (*Cluster) SelectContext ¶
func (c *Cluster) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
SelectContext is a read method: it is routed to a replica or the primary by the hints of ctx (see Cluster) and retried once on a recovery conflict.
func (*Cluster) State ¶
func (c *Cluster) State() ReplicaState
State returns the summary state: without replicas {Reason: "no_replica"}; with a usable replica {Usable, the minimal Lag among usable, "ok"}; otherwise the Lag and Reason of the first replica.
func (*Cluster) States ¶
func (c *Cluster) States() []ReplicaState
States returns a copy of the states of all replicas in the order of the options; empty without replicas.
type ClusterConfig ¶
type ClusterConfig struct {
Primary Config `json:"primary" yaml:"primary"`
// ReplicasEnabled is the switch of the replicas: false means they are not even opened.
ReplicasEnabled bool `json:"replicas_enabled" yaml:"replicasEnabled"`
Replicas []ReplicaConfig `json:"replicas" yaml:"replicas"`
// MaxLagSeconds is WithMaxLag in seconds; 0 means the default (30s).
MaxLagSeconds int `json:"max_lag_seconds" yaml:"maxLagSeconds"`
// LagCheckIntervalSeconds is WithLagCheckInterval in seconds; 0 means the default (5s).
LagCheckIntervalSeconds int `json:"lag_check_interval_seconds" yaml:"lagCheckIntervalSeconds"`
}
ClusterConfig is the config of ConnectCluster: a primary and optional replicas of PostgreSQL.
type ClusterOption ¶
type ClusterOption func(*clusterConfig) error
ClusterOption configures NewCluster.
func WithLagCheckInterval ¶
func WithLagCheckInterval(d time.Duration) ClusterOption
WithLagCheckInterval sets the lag check period (default 5s). d must be > 0. The timeout of one check is min(d, 2s).
func WithMaxLag ¶
func WithMaxLag(d time.Duration) ClusterOption
WithMaxLag sets the replication lag above which a replica is not used (default 30s). d must be > 0. A replica becomes usable again when its lag is back to maxLag/2 or less.
func WithNamedReplica ¶
func WithNamedReplica(name string, db *sqlx.DB) ClusterOption
WithNamedReplica adds a replica. It can be repeated; the order of the options is the order of States(). db == nil is skipped. An empty or already used name gives ErrClusterOption.
func WithRecoveryConflictRetry ¶
func WithRecoveryConflictRetry(on bool) ClusterOption
WithRecoveryConflictRetry enables one retry of a read that failed on a replica with SQLSTATE 40001 "conflict with recovery" (default true): on primary after PreferReplica, on another usable replica after RequireReplica.
func WithReplica ¶
func WithReplica(replica *sqlx.DB) ClusterOption
WithReplica sets the replica named "default". A repeated call replaces it (the last one wins); nil removes it. nil means a cluster without this replica.
func WithReplicaBalancer ¶
func WithReplicaBalancer(b ReplicaBalancer) ClusterOption
WithReplicaBalancer sets how a replica is chosen among the usable ones (default RoundRobin). b must not be nil.
func WithStateHook ¶
func WithStateHook(fn func(ReplicaState)) ClusterOption
WithStateHook sets fn called with the state of one replica (State.Name is set) when its Usable or Reason changes (not on every check). fn is called from the lag check goroutine, one call at a time: keep it fast and do not call Cluster.Close from it.
type Config ¶
type Config struct {
// Host is the database host.
Host string `json:"host" yaml:"host"`
// Port is the database port.
Port int `json:"port" yaml:"port"`
// Username is the database user.
Username string `json:"username" yaml:"username"`
// Password is the password of the database user.
Password string `json:"password" yaml:"password"`
// Database is the database name.
Database string `json:"database" yaml:"database"`
// TimeoutMs is the timeout of the initial ping in milliseconds; 0 means no timeout.
TimeoutMs int `json:"timeout_ms" yaml:"timeoutMs"`
// DSN is a ready connection string used as is instead of Host/Port/... For Driver "sqlite" it is
// the database file path, ":memory:" or a "file:" URI, and the pragmas of SQLite are added to it.
DSN string `json:"dsn" yaml:"dsn"`
// MigrationHost overrides Host for migrations; empty means Host.
MigrationHost string `json:"migration_host" yaml:"migrationHost"`
// MigrationPort overrides Port for migrations; 0 means Port.
MigrationPort int `json:"migration_port" yaml:"migrationPort"`
// MigrationUsername overrides Username for migrations; empty means Username.
MigrationUsername string `json:"migration_username" yaml:"migrationUsername"`
// MigrationPassword overrides Password for migrations; empty means Password.
MigrationPassword string `json:"migration_password" yaml:"migrationPassword"`
// MigrationDatabase overrides Database for migrations; empty means Database.
MigrationDatabase string `json:"migration_database" yaml:"migrationDatabase"`
// BinaryParameters adds binary_parameters=yes to a lib/pq connection string.
BinaryParameters bool `json:"binary_parameters" yaml:"binaryParameters"`
// MaxOpenConnections is the pool size; 0 means the default (10).
MaxOpenConnections int `json:"max_open_connections" yaml:"maxOpenConnections"`
// MaxIdleConnections is the number of idle connections kept; 0 means the default (10).
MaxIdleConnections int `json:"max_idle_connections" yaml:"maxIdleConnections"`
// MaxLifetime is the max connection lifetime in seconds; 0 means the default (30m).
MaxLifetime int `json:"max_lifetime" yaml:"maxLifetime"`
// MaxIdleTime is the max connection idle time in seconds; 0 means the default (5m).
MaxIdleTime int `json:"max_idle_time" yaml:"maxIdleTime"`
// ReadTimeout is the ClickHouse read timeout in seconds; 0 means the driver default.
ReadTimeout int `json:"read_timeout" yaml:"readTimeout"`
// WriteTimeout is the ClickHouse write timeout in seconds; 0 means the driver default.
WriteTimeout int `json:"write_timeout" yaml:"writeTimeout"`
// Driver is "postgres" (default), "pgx", "clickhouse" or "sqlite".
Driver string `json:"driver" yaml:"driver"`
// SSLMode is the sslmode of the connection string; empty means "disable".
SSLMode string `json:"ssl_mode" yaml:"sslMode"`
// ClickhouseScheme is "http" or "https"; empty means "http" if env LOCAL=true, otherwise "https".
ClickhouseScheme string `json:"clickhouse_scheme" yaml:"clickhouseScheme"`
// SQLite holds the pragmas of a SQLite connection (Driver "sqlite" only).
SQLite SQLiteOptions `json:"sqlite" yaml:"sqlite"`
}
Config describes one database connection. It can be loaded from JSON or YAML.
PostgreSQL and ClickHouse use Host, Port, Username, Password and Database (or DSN). SQLite (Driver "sqlite") uses DSN as the file path, ":memory:" or a "file:" URI plus the SQLite options.
func (*Config) ConnectionString ¶
ConnectionString returns the connection string of the config for its driver: DSN as is (with the pragmas for SQLite), a ClickHouse URL or a libpq key=value string.
func (*Config) MigrationConnectionString ¶
MigrationConnectionString is ConnectionString with the Migration* overrides applied.
type ConnectionSelector ¶
type ConnectionSelector func(ctx context.Context, connections []ShardConnect) ShardConnect
ConnectionSelector chooses the shard for a query, typically by a key stored in ctx. Returning nil makes the query fail with ErrConnNotSelected.
type Connections ¶
type Connections struct {
// contains filtered or unexported fields
}
Connections contain all connections for shard client and selector for choosing connection
func ConnectShards ¶
func ConnectShards( driverName string, connectionStrings []ShardConnectString, selector ConnectionSelector, timeout time.Duration, options ...func(connection *sqlx.DB), ) (*Connections, error)
ConnectShards connect all provided connections and create Connections object
func (*Connections) BeginTxx ¶
BeginTxx method for TransactorConnectionProvider implementation by choosing connection by selector
func (*Connections) Connections ¶
func (c *Connections) Connections() []ShardConnect
Connections return all shard connections
func (*Connections) Get ¶
func (c *Connections) Get(ctx context.Context) (ShardConnect, error)
Get returns shard connect by using selector
func (*Connections) RawConnections ¶
func (c *Connections) RawConnections() []*sqlx.DB
RawConnections returns all connections as []*sqlx.DB
type Connector ¶
type Connector struct {
// contains filtered or unexported fields
}
Connector builder for creating connection
func (*Connector) BinaryParameters ¶
BinaryParameters set binary_parameters=yes param
func (*Connector) BuildClickhouse ¶
BuildClickhouse builds a ClickHouse URL. Login and password are escaped via url.UserPassword.
func (*Connector) BuildMigration ¶
BuildMigration connection string
func (*Connector) ClickhouseScheme ¶
ClickhouseScheme sets the URL scheme for ClickHouse ("http"/"https").
Empty means "http" if the environment variable LOCAL=true, otherwise "https".
func (*Connector) Connect ¶
func (connector *Connector) Connect( driverName string, options ...func(connection *sqlx.DB), ) (*sqlx.DB, error)
Connect calls Build method and call Connect function
func (*Connector) ConnectMigration ¶
func (connector *Connector) ConnectMigration( driverName string, options ...func(connection *sqlx.DB), ) (*sqlx.DB, error)
ConnectMigration calls BuildMigration method and call Connect function
func (*Connector) ConnectionMaxLifetime ¶
ConnectionMaxLifetime set max connection lifetime option for connection setting
func (*Connector) MaxIdleConnections ¶
MaxIdleConnections set max idle connections option for connection setting
func (*Connector) MaxIdleTime ¶
MaxIdleTime set max idle time option for connection setting
func (*Connector) MaxOpenConnections ¶
MaxOpenConnections set max open connections option for connection setting
func (*Connector) MigrationDatabase ¶
MigrationDatabase set database name for migration
func (*Connector) MigrationHost ¶
MigrationHost set host of database for migration
func (*Connector) MigrationPassword ¶
MigrationPassword set password of database user for migration
func (*Connector) MigrationPort ¶
MigrationPort set port of database for migration
func (*Connector) MigrationUsername ¶
MigrationUsername set username of database user for migration
func (*Connector) SSLMode ¶
SSLMode sets the sslmode of the connection string (empty means "disable").
func (*Connector) Timeout ¶
Timeout set timeout for connect & ping (via context.Context)
type DB ¶
type DB interface {
Connection() *sqlx.DB
sqlx.ExecerContext
sqlx.QueryerContext
sqlx.PreparerContext
GetContext
NamedExecContext
SelectContext
PrepareContext
NamedQueryRowxContext
EachShard(fn func(conn DB) error) error
EachShardAsync(fn func(conn DB) error, limit ...int) error
}
DB is the database client of the package: the context-aware query methods of sqlx plus shard helpers.
It is implemented by the single client (NewDB, NewDBWithOptions), the shard client (NewShardDB) and Cluster. Every query method runs in the transaction carried by ctx (see SetTx, Transactor), if any.
func NewDBWithOptions ¶
NewDBWithOptions creates DB implementation by single client with options.
func NewShardDB ¶
func NewShardDB(connections *Connections) DB
NewShardDB creates DB implementation as shard client.
Need to provide Connections object which contains multiple connections for sharding
type DBOption ¶
type DBOption func(*clientSingle)
DBOption configures a client created by NewDBWithOptions.
func WithPaging ¶
func WithPaging(mode PagingMode) DBOption
WithPaging sets the default pagination approach used by NewPager (default: PagingOffset).
type GetContext ¶
type GetContext interface {
GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
}
GetContext is the GetContext method of sqlx.
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator applies golang-migrate "up" migrations (files like 0001_init.up.sql) to a PostgreSQL (drivers "postgres", "pgx") or SQLite (driver "sqlite") database. The migrations are read from a directory on disk (default "./migrations") or from an fs.FS such as an embed.FS (WithFS).
func NewMigrator ¶
NewMigrator creates a Migrator for conn. database is the name of the database reported by golang-migrate (used in its logs and errors). ctx is used only by the deprecated Migrate; MigrateContext takes its own.
func (*Migrator) MigrateContext ¶
MigrateContext applies all pending up migrations. No pending migrations is not an error.
The driver is chosen by the driver name of the connection: "sqlite" uses the SQLite driver of golang-migrate on the pool itself; anything else is treated as PostgreSQL and runs on one dedicated connection with lock_timeout = 60s. ClickHouse is not supported.
func (*Migrator) WithFS ¶
WithFS reads the migrations from dir of fsys, typically an embed.FS:
//go:embed migrations/*.sql var migrations embed.FS sqlkit.NewMigrator(ctx, conn, "app").WithFS(migrations, "migrations")
func (*Migrator) WithMigrationsDirectory ¶
WithMigrationsDirectory reads the migrations from directory on disk.
func (*Migrator) WithMigrationsTable ¶
WithMigrationsTable sets the name of the table where golang-migrate stores the schema version (default "schema_migrations").
type NamedExecContext ¶
type NamedExecContext interface {
NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
}
NamedExecContext is the NamedExecContext method of sqlx.
type NamedQueryRowxContext ¶
type NamedQueryRowxContext interface {
NamedQueryRowxContext(ctx context.Context, query string, arg any) (*sqlx.Row, error)
}
NamedQueryRowxContext runs a query with named arguments (":name") and returns one row. The placeholders are converted to the bind style of the driver ("$N" or "?").
type PageRequest ¶
type PageRequest struct {
Page int // 1-based page number (offset approach only)
Size int // page size; <= 0 means 20
Cursor string // token returned as PageResult.NextCursor
}
PageRequest is the pagination input of a request. Zero values mean defaults.
type PageResult ¶
PageResult is a parsed page. NextCursor is nil on the last page.
func PageOf ¶
func PageOf[T any](rows []T, p *Pager, key func(T) []any) PageResult[T]
PageOf trims the rows fetched with LimitOffset (size+1) to a page.
For a cursor pager key must return the sort key values of a row, in key order; a nil key or a wrong number of values panics (programmer error). A key that does not fit into a 256 byte token (long string keys) also panics: a token the decoder would reject is never returned. For an offset pager key is not called. AllPager returns all rows.
Example ¶
package main
import (
"fmt"
"github.com/boostgo/sqlkit"
)
func main() {
p := sqlkit.OffsetPager(sqlkit.PageRequest{Size: 2}, sqlkit.Asc("id"))
rows := []int{1, 2, 3} // size+1 rows were fetched
res := sqlkit.PageOf(rows, p, nil)
fmt.Println(res.Items, res.HasMore, res.NextCursor != nil)
}
Output: [1 2] true true
type Pager ¶
type Pager struct {
// contains filtered or unexported fields
}
Pager describes one page as SQL fragments and arguments and parses an already fetched slice (PageOf). It never executes SQL. Build it with NewPager, OffsetPager, CursorPager or AllPager.
On Err() != nil all fragments describe the first page, so ignoring the error is safe.
func AllPager ¶
func AllPager(opts ...PagerOption) *Pager
AllPager returns a pager without LIMIT: for internal snapshots only, never for user input. Size and MaxSize are ignored; sort keys are optional.
func CursorPager ¶
func CursorPager(req PageRequest, opts ...PagerOption) *Pager
CursorPager builds a keyset pager. req.Page is ignored; without a cursor it is the first page.
All keys must have the same direction, the last key must be unique and all keys NOT NULL. A token of the offset approach or of another sort order means the first page (never "all").
Example ¶
package main
import (
"fmt"
"time"
"github.com/boostgo/sqlkit"
)
func main() {
type row struct {
ID int64
CreatedAt time.Time
}
ts := time.Date(2026, 11, 11, 10, 0, 0, 0, time.UTC)
opts := []sqlkit.PagerOption{sqlkit.Desc("created_at"), sqlkit.Desc("id")}
// first page returned one extra row, so there is a next page
first := sqlkit.CursorPager(sqlkit.PageRequest{Size: 1}, opts...)
res := sqlkit.PageOf([]row{{2, ts}, {1, ts}}, first, func(r row) []any { return []any{r.CreatedAt, r.ID} })
// second page request
next := sqlkit.CursorPager(sqlkit.PageRequest{Size: 1, Cursor: *res.NextCursor}, opts...)
where, args := next.Where(sqlkit.Dollar(1))
fmt.Println(where)
fmt.Println(args[1])
fmt.Println(next.OrderBy(), next.LimitOffset())
}
Output: (created_at, id) < ($1, $2) 2 ORDER BY created_at DESC, id DESC LIMIT 2
func NewPager ¶
func NewPager(db DB, req PageRequest, opts ...PagerOption) *Pager
NewPager builds an OffsetPager or a CursorPager depending on the default mode of db (see WithPaging). A db that does not know its mode (shard client, service mocks) means offset.
func OffsetPager ¶
func OffsetPager(req PageRequest, opts ...PagerOption) *Pager
OffsetPager builds an offset (LIMIT/OFFSET) pager.
A non-empty req.Cursor wins over req.Page; a token of the cursor approach or of another sort order means the first page. A broken token gives ErrInvalidCursor.
Example ¶
package main
import (
"fmt"
"github.com/boostgo/sqlkit"
)
func main() {
p := sqlkit.OffsetPager(sqlkit.PageRequest{Page: 3, Size: 20}, sqlkit.Desc("created_at"), sqlkit.Desc("id"))
fmt.Println(p.OrderBy())
fmt.Println(p.LimitOffset())
}
Output: ORDER BY created_at DESC, id DESC LIMIT 21 OFFSET 40
func (*Pager) Err ¶
Err returns ErrInvalidCursor (broken token: a client error, e.g. HTTP 400) or ErrInvalidPager (programmer error, e.g. HTTP 500).
func (*Pager) LimitOffset ¶
LimitOffset returns "LIMIT 51" or "LIMIT 51 OFFSET 100": the limit is size+1 so PageOf can tell whether there is a next page; OFFSET is omitted at 0. AllPager returns "".
func (*Pager) OrderByColumns ¶
OrderByColumns returns ["created_at DESC", "id DESC"]; nil if the config is invalid.
func (*Pager) Page ¶
Page is the 1-based page number of the offset approach, for Total/MaxPages that the service counts with a separate COUNT query. It is always 1 for cursor and AllPager.
func (*Pager) Where ¶
Where returns the keyset condition and its arguments, e.g. "(created_at, id) < ($3, $4)". ph is called once per value, in order, and returns its placeholder; if ph registers the values itself (sb.Var, Arguments), the returned args can be ignored.
For offset and for the first page of a cursor pager it returns "", nil.
type PagerOption ¶
type PagerOption func(*pagerConfig)
PagerOption is Asc, Desc or MaxSize.
func Asc ¶
func Asc(column string) PagerOption
Asc adds an ascending sort key. The order of options is the order of sorting.
The last key must be unique (e.g. id): the library can not check it. Column is "name" or "table.name"; anything else makes Pager.Err return ErrInvalidPager. Keys of CursorPager must be NOT NULL: a tuple comparison with NULL yields an empty page.
func Desc ¶
func Desc(column string) PagerOption
Desc adds a descending sort key; see Asc for the rules.
func MaxSize ¶
func MaxSize(n int) PagerOption
MaxSize sets the maximum page size (n > 0; default 1000). Ignored by AllPager.
type PagingMode ¶
type PagingMode int
PagingMode is the default pagination approach of a client, see WithPaging.
const ( // PagingOffset is the default approach: LIMIT/OFFSET. PagingOffset PagingMode = iota // PagingCursor is keyset pagination. PagingCursor )
type PrepareContext ¶
type PrepareContext interface {
PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)
}
PrepareContext is the PrepareNamedContext method of sqlx.
type ReplicaBalancer ¶
type ReplicaBalancer func(usable []ReplicaState) int
ReplicaBalancer chooses a replica among the usable ones and returns its index in usable. It is called only with a non-empty usable; an index outside [0, len(usable)) means usable[0].
func LeastLag ¶
func LeastLag() ReplicaBalancer
LeastLag chooses the usable replica with the minimal Lag; on a tie the first one in the order of the options.
func RoundRobin ¶
func RoundRobin() ReplicaBalancer
RoundRobin cycles through the usable replicas. It is safe for concurrent use.
type ReplicaConfig ¶
type ReplicaConfig struct {
Name string `json:"name" yaml:"name"`
Config `yaml:",inline"` // json: embedded without a tag, the fields are flat
}
ReplicaConfig is the config of one replica. Its zero fields are taken from ClusterConfig.Primary (see ConnectCluster), Host and Name are required.
type ReplicaState ¶
type ReplicaState struct {
// Name is the name of the replica; empty only in the summary State() and in the "no_replica" state.
Name string
Usable bool
Lag time.Duration
// Reason is "ok" | "no_replica" | "not_checked" | "lag_exceeded" | "check_failed" | "replay_unknown".
Reason string
}
ReplicaState is the current applicability of a replica.
func (ReplicaState) String ¶
func (s ReplicaState) String() string
type SQLiteOptions ¶
type SQLiteOptions struct {
// JournalMode is PRAGMA journal_mode; empty means "WAL".
JournalMode string `json:"journal_mode" yaml:"journalMode"`
// Synchronous is PRAGMA synchronous; empty means "NORMAL" (safe with WAL).
Synchronous string `json:"synchronous" yaml:"synchronous"`
// BusyTimeoutMs is PRAGMA busy_timeout in milliseconds; 0 means 5000, a negative value disables it.
BusyTimeoutMs int `json:"busy_timeout_ms" yaml:"busyTimeoutMs"`
// DisableForeignKeys turns PRAGMA foreign_keys off (it is on by default).
DisableForeignKeys bool `json:"disable_foreign_keys" yaml:"disableForeignKeys"`
// TxLock is the BEGIN mode of read-write transactions: "deferred", "immediate" or "exclusive";
// empty means "immediate", which avoids SQLITE_BUSY when a read transaction upgrades to a write.
// Read-only transactions (ReadOnly()) always use a plain deferred BEGIN.
TxLock string `json:"tx_lock" yaml:"txLock"`
// Pragmas are extra pragmas applied to every connection, separated by ";" and written without
// the PRAGMA keyword, e.g. "cache_size(-20000); temp_store(MEMORY)". A string (not a slice)
// keeps Config comparable.
Pragmas string `json:"pragmas" yaml:"pragmas"`
}
SQLiteOptions are the per-connection settings of a SQLite database (driver "sqlite", modernc.org/sqlite). Zero values mean the defaults, which suit an application database: WAL journal, synchronous=NORMAL, foreign keys on, a 5s busy timeout and IMMEDIATE write transactions.
type SelectContext ¶
type SelectContext interface {
SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
}
SelectContext is the SelectContext method of sqlx.
type ShardConnect ¶
ShardConnect contain connection & it's key for shard client
type ShardConnectString ¶
type ShardConnectString struct {
// Key identifies the shard; it must be unique and not empty.
Key string
// ConnectionString is passed to Connect.
ConnectionString string
}
ShardConnectString is the connection string of one shard and its unique key.
type Transactor ¶
type Transactor interface {
Key() string
IsTx(ctx context.Context) bool
Begin(ctx context.Context) (context.Context, error)
Commit(ctx context.Context) error
Rollback(ctx context.Context) error
Rewrite(original, toCopy context.Context) context.Context
}
Transactor is common representation of transactions for any type of database.
Reason to use this: hide from usecase/service layer of using "sql" or "mongo" database
func NewTransactor ¶
func NewTransactor(provider TransactorConnectionProvider) Transactor
NewTransactor creates SQL multipleTransactor
type TransactorConnectionProvider ¶
type TransactorConnectionProvider interface {
BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error)
}
TransactorConnectionProvider sql multipleTransaction interface
type TxBeginner ¶
type TxBeginner interface {
BeginTx(ctx context.Context, opts ...TxOption) (context.Context, error)
}
TxBeginner is implemented by the transactor of this library (NewTransactor). Other Transactor implementations (e.g. mocks) are not required to implement it.
type TxOption ¶
type TxOption func(*txConfig)
TxOption configures a transaction. See ReadOnly, Isolation and Join.
func Isolation ¶
func Isolation(level sql.IsolationLevel) TxOption
Isolation sets the isolation level of the transaction (default: sql.LevelReadCommitted).
func Join ¶
func Join() TxOption
Join makes BeginTx / WithTx reuse the transaction already stored in ctx instead of opening a second one.
Commit and Rollback of the joined level are no-ops: the outer level commits or rolls back. Without a transaction in ctx, Join has no effect and a new transaction is opened.
Source Files
¶
- arguments.go
- client.go
- client_shard.go
- client_single.go
- cluster.go
- cluster_connect.go
- cluster_ctx.go
- cluster_lag.go
- cluster_options.go
- config.go
- connection_shard.go
- connection_single.go
- connector.go
- doc.go
- driver.go
- errors.go
- errors_classify.go
- errors_handle.go
- migrate.go
- pager.go
- pager_token.go
- row_error.go
- sql_transaction.go
- sql_transactor.go
- sqlite.go
- transactor.go
- tx.go
- tx_options.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package duplicate parses PostgreSQL unique violation errors (SQLSTATE 23505) of lib/pq.
|
Package duplicate parses PostgreSQL unique violation errors (SQLSTATE 23505) of lib/pq. |
|
examples
|
|
|
cluster
command
Command cluster shows a PostgreSQL primary with read replicas: reads marked with PreferReplica go to a replica whose replication lag is within the limit, everything else goes to the primary.
|
Command cluster shows a PostgreSQL primary with read replicas: reads marked with PreferReplica go to a replica whose replication lag is within the limit, everything else goes to the primary. |
|
postgres
command
Command postgres shows sqlkit with PostgreSQL: config, embedded migrations, a transaction, error classification and offset pagination.
|
Command postgres shows sqlkit with PostgreSQL: config, embedded migrations, a transaction, error classification and offset pagination. |
|
sqlite
command
Command sqlite shows sqlkit with a local SQLite database: config, embedded migrations, a repository that uses the transactor, error classification and cursor pagination.
|
Command sqlite shows sqlkit with a local SQLite database: config, embedded migrations, a repository that uses the transactor, error classification and cursor pagination. |
|
Package sqlbpager applies a sqlkit.Pager to a go-sqlbuilder SelectBuilder.
|
Package sqlbpager applies a sqlkit.Pager to a go-sqlbuilder SelectBuilder. |