sqlkit

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 33 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

sqlkit

Go Reference Go Report Card CI

sqlkit is a small, batteries-included layer over sqlx for PostgreSQL, SQLite and ClickHouse. It covers what most services rewrite in every project: connecting from config, transactions carried in context.Context, offset and cursor pagination, embedded migrations, read replicas and portable error handling.

conn, _ := sqlkit.ConnectFromConfig(sqlkit.Config{Driver: "sqlite", DSN: "app.db"})
db, tr := sqlkit.NewDB(conn), sqlkit.NewTransactor(conn)

err := sqlkit.WithTx(ctx, tr, func(ctx context.Context) error {
    _, err := db.ExecContext(ctx, "INSERT INTO users (email) VALUES (?)", email)
    return err // rollback on error or panic, commit otherwise
})
if sqlkit.IsDuplicate(err) { /* 409 Conflict */ }

Features

  • Four drivers, one API: postgres (lib/pq), pgx (jackc/pgx), sqlite (modernc.org/sqlite, pure Go, no cgo) and clickhouse. Rebind and Placeholder keep queries portable.
  • SQLite done right: WAL, foreign_keys=on, busy_timeout, IMMEDIATE write transactions and sortable time values out of the box; in-memory databases get a single pinned connection.
  • Transactions in context: WithTx / BeginTx with ReadOnly(), Isolation(level) and Join(); every query method picks the transaction up from ctx, so repositories stay tx-agnostic.
  • Pagination: offset and keyset (cursor) pagers with opaque, versioned page tokens, generic PageOf, and a go-sqlbuilder adapter (sqlbpager).
  • Migrations: golang-migrate from a directory or an embed.FS, for PostgreSQL and SQLite.
  • Error classification: unique, foreign key, not-null and check violations of PostgreSQL and SQLite map to the same sentinel errors; DuplicateFields names the offending columns.
  • Read replicas: Cluster routes reads to healthy replicas by replication lag with hysteresis, PreferReplica / RequireReplica / ForcePrimary hints and pluggable balancers.
  • Sharding: a shard client with a context-based selector, EachShard and EachShardAsync.

Install

go get github.com/boostgo/sqlkit

Requires Go 1.24 or newer.

Quick start

SQLite
package main

import (
    "context"
    "embed"
    "log"

    "github.com/boostgo/sqlkit"
)

//go:embed migrations/*.sql
var migrations embed.FS

func main() {
    ctx := context.Background()

    conn, err := sqlkit.ConnectFromConfig(sqlkit.Config{
        Driver: sqlkit.SQLiteDriver,
        DSN:    "app.db", // or ":memory:", or a "file:" URI
    })
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    if err = sqlkit.NewMigrator(ctx, conn, "app").WithFS(migrations, "migrations").MigrateContext(ctx); err != nil {
        log.Fatal(err)
    }

    db := sqlkit.NewDB(conn)

    var n int
    if err = db.GetContext(ctx, &n, "SELECT count(*) FROM users WHERE active = ?", true); err != nil {
        log.Fatal(err)
    }
}
PostgreSQL
conn, err := sqlkit.ConnectFromConfig(sqlkit.Config{
    Driver:   sqlkit.PgxDriver, // or sqlkit.PqDriver (default)
    Host:     "localhost",
    Port:     5432,
    Username: "app",
    Password: "secret",
    Database: "app",
    SSLMode:  "require",
    TimeoutMs: 5000,
})
// or: sqlkit.Config{Driver: "pgx", DSN: "postgres://app:secret@localhost:5432/app"}

db := sqlkit.NewDB(conn)
err = db.GetContext(ctx, &n, "SELECT count(*) FROM users WHERE active = $1", true)

Config has JSON and YAML tags, so it can be embedded in your application config as is:

database:
  driver: sqlite
  dsn: /var/lib/app/app.db
  sqlite:
    busyTimeoutMs: 10000
    pragmas: "cache_size(-20000); temp_store(MEMORY)"

Runnable programs live in examples/: sqlite (runs as is: go run ./examples/sqlite), postgres and cluster.

Usage

Repositories and portable queries

Write queries with ? and let Rebind convert them to $1, $2, ... for PostgreSQL:

type Repository struct {
    db sqlkit.DB
    tr sqlkit.Transactor
}

func (r *Repository) Create(ctx context.Context, email string) (int64, error) {
    var id int64
    err := r.db.GetContext(ctx, &id,
        sqlkit.Rebind(r.db, "INSERT INTO users (email) VALUES (?) RETURNING id"), email)
    return id, sqlkit.Classify(err)
}

NamedExecContext and NamedQueryRowxContext (:name arguments) choose the right bind style automatically. $N placeholders also work with SQLite, so Arguments and Dollar can be shared.

Transactions
tr := sqlkit.NewTransactor(conn)

err := sqlkit.WithTx(ctx, tr, func(ctx context.Context) error {
    if err := repo.Debit(ctx, from, amount); err != nil {
        return err // rolled back
    }
    return repo.Credit(ctx, to, amount) // committed if nil
}, sqlkit.Isolation(sql.LevelSerializable))
  • The transaction travels in ctx; db.ExecContext(ctx, ...) and friends use it automatically.
  • WithTx commits on nil, rolls back on error and on panic (the panic is re-raised).
  • Join() reuses a transaction already in ctx; inner commits/rollbacks become no-ops. Without Join() a nested WithTx opens a second transaction on another connection.
  • ReadOnly() and Isolation(level) are passed to the driver. SQLite ignores the isolation level (it is always serializable) and starts read-only transactions with a plain deferred BEGIN.
  • Manual control: ctx, err := tr.Begin(ctx) then tr.Commit(ctx) / tr.Rollback(ctx).
Pagination
func (r *Repository) List(ctx context.Context, req sqlkit.PageRequest) (sqlkit.PageResult[User], error) {
    p := sqlkit.CursorPager(req, sqlkit.Desc("created_at"), sqlkit.Desc("id"))
    if err := p.Err(); err != nil {
        return sqlkit.PageResult[User]{}, err // ErrInvalidCursor -> 400, ErrInvalidPager -> 500
    }

    q, args := "SELECT * FROM users WHERE tenant_id = ?", []any{tenantID}
    if where, wargs := p.Where(sqlkit.Placeholder(sqlkit.DriverName(r.db), len(args)+1)); where != "" {
        q += " AND " + where
        args = append(args, wargs...)
    }

    var rows []User
    if err := r.db.SelectContext(ctx, &rows, sqlkit.Rebind(r.db, q)+" "+p.OrderBy()+" "+p.LimitOffset(), args...); err != nil {
        return sqlkit.PageResult[User]{}, err
    }

    return sqlkit.PageOf(rows, p, func(u User) []any { return []any{u.CreatedAt, u.ID} }), nil
}
Pager Use it for
OffsetPager(req, keys...) numbered pages (req.Page), when a total count is shown
CursorPager(req, keys...) feeds and large tables: stable under inserts, no OFFSET scan
NewPager(db, req, keys...) the client default: NewDBWithOptions(conn, WithPaging(PagingCursor))
AllPager(keys...) internal snapshots without a limit; never for user input

Rules: Size defaults to 20 and is capped at 1000 (MaxSize(n)); the last key must be unique (usually id); cursor keys must be NOT NULL and share one direction. Page tokens are base64url JSON with a fingerprint of the sort order; a token from another sort order or approach restarts at page one. Store times in UTC: with SQLite they are compared as text.

With go-sqlbuilder: sqlbpager.Apply(sb, p) adds the condition, ORDER BY, LIMIT and OFFSET.

Migrations
//go:embed migrations/*.sql
var migrations embed.FS

err := sqlkit.NewMigrator(ctx, conn, "app").
    WithFS(migrations, "migrations"). // or WithMigrationsDirectory("./migrations")
    WithMigrationsTable("schema_migrations").
    MigrateContext(ctx)

Files follow the golang-migrate naming: 0001_create_users.up.sql, 0001_create_users.down.sql. The driver is picked from the connection: PostgreSQL migrations run on a dedicated connection with lock_timeout = 60s; SQLite migrations run on the pool, which stays open afterwards. "No change" is not an error. ClickHouse returns ErrMigrateUnsupportedDriver.

Read replicas (PostgreSQL)
cluster, err := sqlkit.ConnectCluster(sqlkit.ClusterConfig{
    Primary:         sqlkit.Config{Host: "db-primary", Port: 5432, Username: "app", Password: "secret", Database: "app"},
    ReplicasEnabled: true,
    Replicas: []sqlkit.ReplicaConfig{
        {Name: "ro1", Config: sqlkit.Config{Host: "db-ro1"}}, // zero fields are inherited from the primary
        {Name: "ro2", Config: sqlkit.Config{Host: "db-ro2"}},
    },
}, sqlkit.WithReplicaBalancer(sqlkit.LeastLag()))
defer cluster.Close()

err = cluster.SelectContext(sqlkit.PreferReplica(ctx), &rows, q)  // replica if healthy, else primary
err = cluster.SelectContext(sqlkit.RequireReplica(ctx), &rows, q) // replica or ErrReplicaUnavailable
err = cluster.SelectContext(sqlkit.ForcePrimary(ctx), &rows, q)   // always primary

Writes, prepares and anything inside a transaction always go to the primary. Replication lag is checked in the background (pg_last_wal_replay_lsn); a replica is dropped above WithMaxLag and comes back at half of it. A read that hits a recovery conflict (SQLSTATE 40001) on a replica is retried once. Cluster implements DB, so repositories do not change.

Error handling
_, err := db.ExecContext(ctx, query, args...)
switch {
case sqlkit.IsDuplicate(err):
    fields, _ := sqlkit.DuplicateFields(err) // e.g. ["email"]
case sqlkit.IsForeignKey(err), sqlkit.IsNotNull(err), sqlkit.IsCheckViolation(err):
case sqlkit.IsNoRows(err):
case errors.Is(err, sqlkit.ErrExecContext): // any other failure of ExecContext
}
Sentinel PostgreSQL SQLite
ErrDuplicate 23505 unique_violation SQLITE_CONSTRAINT_UNIQUE, _PRIMARYKEY
ErrForeignKeyViolation 23503 SQLITE_CONSTRAINT_FOREIGNKEY
ErrNotNull 23502 SQLITE_CONSTRAINT_NOTNULL
ErrCheckViolation 23514 SQLITE_CONSTRAINT_CHECK

Classify(err) wraps the driver error with the sentinel and keeps it in the chain, so errors.As(err, &pgErr) still works. Every DB method wraps its errors with its own sentinel (ErrExecContext, ErrSelectContext, ...).

Sharding
conns, err := sqlkit.ConnectShards(sqlkit.PgxDriver, []sqlkit.ShardConnectString{
    {Key: "eu", ConnectionString: euDSN},
    {Key: "us", ConnectionString: usDSN},
}, selectByRegion, 5*time.Second)
db := sqlkit.NewShardDB(conns)

err = db.EachShardAsync(func(shard sqlkit.DB) error { /* ... */ return nil }, 4)

Options reference

Config
Field YAML Default Description
Driver driver postgres postgres, pgx, sqlite, clickhouse
DSN dsn Connection string used as is; for SQLite the file path, :memory: or file: URI (required)
Host, Port, Username, Password, Database host, ... Server connection (PostgreSQL, ClickHouse)
SSLMode sslMode disable PostgreSQL sslmode
TimeoutMs timeoutMs none Timeout of the initial ping
MaxOpenConnections maxOpenConnections 10 Pool size
MaxIdleConnections maxIdleConnections 10 Idle connections kept
MaxLifetime maxLifetime 30m Connection lifetime, seconds
MaxIdleTime maxIdleTime 5m Connection idle time, seconds
Migration* migrationHost, ... main values Separate host/credentials for migrations
BinaryParameters binaryParameters false lib/pq binary_parameters=yes
ClickhouseScheme clickhouseScheme https (http if LOCAL=true) ClickHouse URL scheme
ReadTimeout, WriteTimeout readTimeout, ... driver ClickHouse timeouts, seconds
SQLite sqlite see below SQLite pragmas
SQLiteOptions
Field YAML Default Description
JournalMode journalMode WAL PRAGMA journal_mode
Synchronous synchronous NORMAL PRAGMA synchronous
BusyTimeoutMs busyTimeoutMs 5000 PRAGMA busy_timeout; negative disables
DisableForeignKeys disableForeignKeys false Foreign keys are on unless set
TxLock txLock immediate BEGIN mode of write transactions: deferred, immediate, exclusive
Pragmas pragmas Extra pragmas, ;-separated, e.g. cache_size(-20000); temp_store(MEMORY)
Transactions, pagers and clusters
Option Applies to Description
ReadOnly() WithTx, BeginTx Read-only transaction
Isolation(level) WithTx, BeginTx Isolation level (default ReadCommitted; ignored by SQLite)
Join() WithTx, BeginTx Reuse the transaction in ctx
Asc(col), Desc(col) pagers Sort keys, in order; the last must be unique
MaxSize(n) pagers Page size cap (default 1000)
WithPaging(mode) NewDBWithOptions Default approach of NewPager
WithReplica(db), WithNamedReplica(name, db) NewCluster Add replicas
WithReplicaBalancer(b) clusters RoundRobin() (default) or LeastLag()
WithMaxLag(d) clusters Max replication lag (default 30s)
WithLagCheckInterval(d) clusters Lag check period (default 5s)
WithRecoveryConflictRetry(on) clusters Retry reads on 40001 (default true)
WithStateHook(fn) clusters Called when a replica becomes usable or unusable

Contributing

Issues and pull requests are welcome. Before sending a change:

make vet lint test   # go vet, golangci-lint, go test -race
make cover           # coverage summary

Tests that need a server are skipped unless their DSN is set:

make postgres-up
SQLKIT_TEST_POSTGRES_DSN="postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable" make test
make postgres-down

SQLKIT_TEST_CLICKHOUSE_DSN (e.g. http://default:@localhost:8123/default) enables the ClickHouse test. Please add tests for new behaviour and an entry to CHANGELOG.md.

License

MIT © 2026 boostgo

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

Examples

Constants

View Source
const (
	ReasonOK            = "ok"
	ReasonNoReplica     = "no_replica"
	ReasonNotChecked    = "not_checked"
	ReasonLagExceeded   = "lag_exceeded"
	ReasonCheckFailed   = "check_failed"
	ReasonReplayUnknown = "replay_unknown"
)

Reasons of ReplicaState.

View Source
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.

View Source
const (
	DefaultSQLiteJournalMode   = "WAL"
	DefaultSQLiteSynchronous   = "NORMAL"
	DefaultSQLiteBusyTimeoutMs = 5000
	DefaultSQLiteTxLock        = "immediate"
)

SQLite defaults applied by SQLiteDSN for zero SQLiteOptions fields.

View Source
const DefaultMigrationsDirectory = "./migrations"

DefaultMigrationsDirectory is the directory read by a Migrator without WithMigrationsDirectory/WithFS.

Variables

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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).

View Source
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")
	// ErrReplicaUnavailable is returned by read methods of Cluster called with RequireReplica(ctx) when
	// no replica is usable.
	ErrReplicaUnavailable = errors.New("sqlkit.cluster.replica_unavailable")
)

Cluster errors.

View Source
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

func Atomic(ctx context.Context, conn *sqlx.DB, fn func(ctx context.Context) error) error

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

func BeginTx(ctx context.Context, tr Transactor, opts ...TxOption) (context.Context, error)

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

func Classify(err error) error

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

func ConnectFromConfig(cfg Config, opts ...func(connection *sqlx.DB)) (*sqlx.DB, error)

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

func Dollar(start int) func(v any) string

Dollar returns a placeholder func for Pager.Where: "$start", "$start+1", ... It ignores the values.

func DriverName

func DriverName(db DB) string

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 Duplicate deprecated

func Duplicate(err error) (bool, string)

Duplicate reports whether err is a unique violation and the guessed field name.

Deprecated: use IsDuplicate and DuplicateFields.

func DuplicateFields

func DuplicateFields(err error) (fields []string, ok bool)

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 EachShard

func EachShard(conn DB, fn func(conn DB) error) (err error)

EachShard runs provided fn function with every shard single connection

func EachShardAsync

func EachShardAsync(conn DB, fn func(conn DB) error, limit ...int) (err error)

EachShardAsync do the same as EachShard but in parallel every shard.

If provide "limit", count of goroutines will be limited

func ForcePrimary

func ForcePrimary(ctx context.Context) context.Context

ForcePrimary marks ctx: Cluster sends everything to primary. It overrides PreferReplica and RequireReplica.

func GetTx

func GetTx(ctx context.Context) (*sqlx.Tx, bool)

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 HandleError(err error) error

HandleError maps constraint violations of lib/pq to sentinel errors; it returns nil for any other non-pq error.

Deprecated: use Classify / Is*.

func IsCheckViolation

func IsCheckViolation(err error) bool

IsCheckViolation reports whether err is a CHECK constraint violation.

func IsDuplicate

func IsDuplicate(err error) bool

IsDuplicate reports whether err is a unique (or primary key) violation.

func IsForeignKey

func IsForeignKey(err error) bool

IsForeignKey reports whether err is a foreign key violation.

func IsNoRows

func IsNoRows(err error) bool

IsNoRows reports whether err is sql.ErrNoRows.

func IsNotNull

func IsNotNull(err error) bool

IsNotNull reports whether err is a not-null violation.

func MaxConnectionsOption

func MaxConnectionsOption(open, idle int) func(conn *sqlx.DB)

MaxConnectionsOption sets max open & idle connections

func MaxTimeOption

func MaxTimeOption(lifetime, idle time.Duration) func(conn *sqlx.DB)

MaxTimeOption sets connection max lifetime & max idle time settings

func Page

func Page(pageSize int64, page int) (offset int, limit int)

Page returns offset & limit by pagination

func Placeholder

func Placeholder(driverName string, start int) func(v any) string

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

func PreferReplica(ctx context.Context) context.Context

PreferReplica marks ctx: read methods of Cluster may go to a replica (if one is usable and ctx has no tx).

func Question

func Question() func(v any) string

Question returns a placeholder func for Pager.Where that always returns "?".

func Rebind

func Rebind(db DB, query string) string

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

func RegisterDriver(driverName string, driver driver.Driver)

RegisterDriver registers driver under driverName via sql.Register, unless a driver with that name is already registered (sql.Register would panic).

func ReplicaPreferred

func ReplicaPreferred(ctx context.Context) bool

ReplicaPreferred reports whether ctx has PreferReplica and has no ForcePrimary.

func ReplicaRequired

func ReplicaRequired(ctx context.Context) bool

ReplicaRequired reports whether ctx has RequireReplica and has no ForcePrimary.

func RequireReplica

func RequireReplica(ctx context.Context) context.Context

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

func RewriteTx(key string, original context.Context, toCopy context.Context) context.Context

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 RunTransaction(conn *sqlx.DB, transactionActions func(tx *sqlx.Tx) error) error

RunTransaction run "actions" by created transaction object.

The transaction is rolled back if transactionActions returns an error or panics (the panic is re-raised).

Deprecated: use RunTransactionContext.

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

func SetTx(ctx context.Context, tx *sqlx.Tx) context.Context

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

func WithConnMaxIdleTime(d time.Duration) func(*sqlx.DB)

WithConnMaxIdleTime sets the max connection idle time as is (<= 0 means no limit).

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) func(*sqlx.DB)

WithConnMaxLifetime sets the max connection lifetime as is (<= 0 means no limit).

func WithMaxIdle

func WithMaxIdle(n int) func(*sqlx.DB)

WithMaxIdle sets the max number of idle connections as is (<= 0 means no idle connections).

func WithMaxOpen

func WithMaxOpen(n int) func(*sqlx.DB)

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

func NewArguments(args ...any) *Arguments

NewArguments created instance of Arguments object

func (*Arguments) Add

func (a *Arguments) Add(arg any) *Arguments

Add new argument and increment count.

After adding argument use Number method to get "$number" string

func (*Arguments) AddMany

func (a *Arguments) AddMany(args ...any) string

AddMany adds new many arguments and return "($1, $2, $3...)" string

func (*Arguments) Args

func (a *Arguments) Args() []any

Args return all provided arguments for executing query

func (*Arguments) Number

func (a *Arguments) Number() string

Number returns current $number value as a 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")
	}
}

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

func (c *Cluster) Close() error

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

func (c *Cluster) Connection() *sqlx.DB

Connection returns the connection of the primary.

func (*Cluster) DriverName

func (c *Cluster) DriverName() string

DriverName returns the driver name of the primary.

func (*Cluster) EachShard

func (c *Cluster) EachShard(_ func(conn DB) error) error

EachShard is not supported by Cluster.

func (*Cluster) EachShardAsync

func (c *Cluster) EachShardAsync(_ func(conn DB) error, _ ...int) error

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

func (c *Cluster) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

PrepareContext always runs on the primary.

func (*Cluster) PrepareNamedContext

func (c *Cluster) PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)

PrepareNamedContext always runs on the primary.

func (*Cluster) Primary

func (c *Cluster) Primary() DB

Primary returns the client of 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

func (c *Cluster) Replica(ctx context.Context) DB

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

func (c *Config) ConnectionString() string

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

func (c *Config) MigrationConnectionString() string

MigrationConnectionString is ConnectionString with the Migration* overrides applied.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that the config has everything needed to connect: DSN for SQLite or when DSN is set, otherwise Host, Port, Database, Username and Password.

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

func (c *Connections) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error)

BeginTxx method for TransactorConnectionProvider implementation by choosing connection by selector

func (*Connections) Close

func (c *Connections) Close() error

Close all connections in parallel

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 NewConnector

func NewConnector() *Connector

NewConnector creates Connector builder

func (*Connector) BinaryParameters

func (connector *Connector) BinaryParameters(binaryParameters bool) *Connector

BinaryParameters set binary_parameters=yes param

func (*Connector) Build

func (connector *Connector) Build() string

Build connection string

func (*Connector) BuildClickhouse

func (connector *Connector) BuildClickhouse() string

BuildClickhouse builds a ClickHouse URL. Login and password are escaped via url.UserPassword.

func (*Connector) BuildMigration

func (connector *Connector) BuildMigration() string

BuildMigration connection string

func (*Connector) ClickhouseScheme

func (connector *Connector) ClickhouseScheme(scheme string) *Connector

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

func (connector *Connector) ConnectionMaxLifetime(connectionMaxLifetime time.Duration) *Connector

ConnectionMaxLifetime set max connection lifetime option for connection setting

func (*Connector) Database

func (connector *Connector) Database(database string) *Connector

Database set database name

func (*Connector) Host

func (connector *Connector) Host(host string) *Connector

Host set host of database

func (*Connector) MaxIdleConnections

func (connector *Connector) MaxIdleConnections(maxIdleConnections int) *Connector

MaxIdleConnections set max idle connections option for connection setting

func (*Connector) MaxIdleTime

func (connector *Connector) MaxIdleTime(maxIdleTime time.Duration) *Connector

MaxIdleTime set max idle time option for connection setting

func (*Connector) MaxOpenConnections

func (connector *Connector) MaxOpenConnections(maxOpenConnections int) *Connector

MaxOpenConnections set max open connections option for connection setting

func (*Connector) MigrationDatabase

func (connector *Connector) MigrationDatabase(database string) *Connector

MigrationDatabase set database name for migration

func (*Connector) MigrationHost

func (connector *Connector) MigrationHost(host string) *Connector

MigrationHost set host of database for migration

func (*Connector) MigrationPassword

func (connector *Connector) MigrationPassword(password string) *Connector

MigrationPassword set password of database user for migration

func (*Connector) MigrationPort

func (connector *Connector) MigrationPort(port int) *Connector

MigrationPort set port of database for migration

func (*Connector) MigrationUsername

func (connector *Connector) MigrationUsername(username string) *Connector

MigrationUsername set username of database user for migration

func (*Connector) Password

func (connector *Connector) Password(password string) *Connector

Password set password of database user

func (*Connector) Port

func (connector *Connector) Port(port int) *Connector

Port set port of database

func (*Connector) ReadTimeout

func (connector *Connector) ReadTimeout(readTimeout int) *Connector

ReadTimeout set readTimeout parameter.

For clickhouse

func (*Connector) SSLMode

func (connector *Connector) SSLMode(mode string) *Connector

SSLMode sets the sslmode of the connection string (empty means "disable").

func (*Connector) Schema

func (connector *Connector) Schema(schema string) *Connector

Schema set schema name

func (*Connector) String

func (connector *Connector) String() string

String calls Build method

func (*Connector) Timeout

func (connector *Connector) Timeout(timeout time.Duration) *Connector

Timeout set timeout for connect & ping (via context.Context)

func (*Connector) Username

func (connector *Connector) Username(username string) *Connector

Username set username of database user

func (*Connector) WriteTimeout

func (connector *Connector) WriteTimeout(writeTimeout int) *Connector

WriteTimeout set writeTimeout parameter.

For clickhouse

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 NewDB

func NewDB(conn *sqlx.DB) DB

NewDB creates DB implementation by single client

func NewDBWithOptions

func NewDBWithOptions(conn *sqlx.DB, opts ...DBOption) DB

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

func NewMigrator(
	ctx context.Context,
	conn *sqlx.DB,
	database string,
) *Migrator

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) Migrate deprecated

func (m *Migrator) Migrate() error

Migrate runs migrations with the ctx given to NewMigrator.

Deprecated: use MigrateContext.

func (*Migrator) MigrateContext

func (m *Migrator) MigrateContext(ctx context.Context) error

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

func (m *Migrator) WithFS(fsys fs.FS, dir string) *Migrator

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

func (m *Migrator) WithMigrationsDirectory(directory string) *Migrator

WithMigrationsDirectory reads the migrations from directory on disk.

func (*Migrator) WithMigrationsTable

func (m *Migrator) WithMigrationsTable(table string) *Migrator

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

type PageResult[T any] struct {
	Items      []T
	HasMore    bool
	NextCursor *string
}

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

func (p *Pager) Err() error

Err returns ErrInvalidCursor (broken token: a client error, e.g. HTTP 400) or ErrInvalidPager (programmer error, e.g. HTTP 500).

func (*Pager) Limit

func (p *Pager) Limit() int

Limit is size+1 (0 for AllPager).

func (*Pager) LimitOffset

func (p *Pager) LimitOffset() string

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

func (p *Pager) Offset() int

Offset is the number of rows to skip (0 for cursor and AllPager).

func (*Pager) OrderBy

func (p *Pager) OrderBy() string

OrderBy returns "ORDER BY created_at DESC, id DESC"; "" without keys.

func (*Pager) OrderByColumns

func (p *Pager) OrderByColumns() []string

OrderByColumns returns ["created_at DESC", "id DESC"]; nil if the config is invalid.

func (*Pager) Page

func (p *Pager) Page() int

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

func (p *Pager) Size() int

Size is the normalized page size (0 for AllPager).

func (*Pager) Where

func (p *Pager) Where(ph func(v any) string) (string, []any)

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

type ShardConnect interface {
	Key() string
	Conn() *sqlx.DB
	Close() error
}

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 Transaction deprecated

type Transaction interface {
	Context() context.Context
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

Transaction interface using by Transactor.

Deprecated: the library does not implement it; use Transactor.

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.

func ReadOnly

func ReadOnly() TxOption

ReadOnly makes the transaction read-only.

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.

Jump to

Keyboard shortcuts

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