database

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2022 License: MIT Imports: 15 Imported by: 2

README

Database

GoDoc Go Report Card Coverage Status

Database is wrapper for sqlx with clear interface, retry func and hooks.
Compatible databases: PostgreSQL, Clickhouse, CockroachDB, SQLite.

Install

go get github.com/loghole/database

Usage

package main

import (
	"context"
	"log"

	"github.com/loghole/database"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	// Make connection config
	cfg := &database.Config{
		Database: ":memory:",
		Type:     database.SQLiteDatabase,
	}

	// Connect to Database with hooks
	db, err := database.New(cfg, database.WithSimplerrHook(), database.WithRetryFunc(retry))
	if err != nil {
		panic(err)
	}

	defer db.Close()

	ctx := context.Background()

	// Queries
	db.ExecContext(ctx, "CREATE TABLE t (id INTEGER PRIMARY KEY, text VARCHAR(5))")
	db.ExecContext(ctx, "INSERT into t (id, text) VALUES(?, ?)", 1, "foo")
	// Try 3 times and return error
	if _, err := db.ExecContext(ctx, "INSERT into t (id, text) VALUES(?, ?)", 1, "bar"); err != nil {
		log.Println(err)
	}
}

func retry(retryCount int, err error) bool {
	if retryCount > 3 {
		return false
	}

	log.Println(retryCount, err)

	return true
}

Custom hooks

You can write custom hooks with dbhook and use options database.WithCustomHook(hook)

Documentation

Index

Constants

View Source
const DefaultRetryAttempts = 10

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Addr         string
	User         string
	Database     string
	Type         DBType
	ReadTimeout  string
	WriteTimeout string
	Params       map[string]string

	// Deprecated: use Params for sets certs.
	CertPath string
}

func (*Config) DSN added in v0.3.0

func (cfg *Config) DSN() string

type DB

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

func New

func New(cfg *Config, opts ...Option) (db *DB, err error)

func (*DB) BeginTxx added in v0.6.0

func (db *DB) BeginTxx(ctx context.Context, opts *sql.TxOptions) (tx *sqlx.Tx, err error)

BeginTxx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.

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

func (*DB) BindNamed added in v0.6.0

func (db *DB) BindNamed(query string, arg interface{}) (bound string, arglist []interface{}, err error)

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

func (*DB) Close added in v0.6.0

func (db *DB) Close() error

Close closes the database and prevents new queries from starting. Close then waits for all queries that have started processing on the server to finish.

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

func (*DB) ExecContext added in v0.6.0

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

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

func (*DB) GetContext added in v0.6.0

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

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

func (*DB) NamedExecContext added in v0.6.0

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

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

func (*DB) NamedQueryContext added in v0.6.0

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

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

func (*DB) PrepareNamedContext added in v0.6.0

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

PrepareNamedContext returns an sqlx.NamedStmt.

func (*DB) PreparexContext added in v0.6.0

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

PreparexContext returns an sqlx.Stmt instead of a sqlx.Stmt.

func (*DB) QueryxContext added in v0.6.0

func (db *DB) QueryxContext(ctx context.Context, query string, args ...interface{}) (rows *sqlx.Rows, err error)

QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*DB) RunReadTxx added in v0.6.1

func (db *DB) RunReadTxx(ctx context.Context, fn TransactionFunc) error

RunReadTxx runs transaction callback func with read only `sql.TxOptions`. If an error occurs, the transaction will be retried if it allows `RetryFunc`.

func (*DB) RunTxx

func (db *DB) RunTxx(ctx context.Context, fn TransactionFunc) error

RunTxx runs transaction callback func with default `sql.TxOptions`. If an error occurs, the transaction will be retried if it allows `RetryFunc`.

Example:

err := db.RunTxx(ctx, func(ctx context.Context, tx *sqlx.Tx) error {
	var val time.Time

	if err := tx.GetContext(ctx, &val, "SELECT now()"); err != nil {
		return err
	}

	return nil
})
if err != nil {
	return err
}

func (*DB) RunTxxWithOptions added in v0.6.1

func (db *DB) RunTxxWithOptions(ctx context.Context, opts *sql.TxOptions, fn TransactionFunc) error

RunTxxWithOptions runs transaction callback func with custom `sql.TxOptions`. If an error occurs, the transaction will be retried if it allows `RetryFunc`.

func (*DB) SelectContext added in v0.6.0

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

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

type DBType

type DBType string
const (
	PostgresDatabase   DBType = "postgres"
	ClickhouseDatabase DBType = "clickhouse"
	SQLiteDatabase     DBType = "sqlite3"
)

func (DBType) String

func (d DBType) String() string

type Database added in v0.7.1

type Database interface {
	// SelectContext using this DB.
	// Any placeholder parameters are replaced with supplied args.
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

	// GetContext using this DB.
	// Any placeholder parameters are replaced with supplied args.
	// An error is returned if the result set is empty.
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

	// BindNamed binds a query using the DB driver's bindvar type.
	BindNamed(query string, arg interface{}) (bound string, arglist []interface{}, err error)

	// BeginTxx begins a transaction and returns an *sqlx.Tx instead of an
	// *sql.Tx.
	//
	// The provided context is used until the transaction is committed or rolled
	// back. If the context is canceled, the sql package will roll back the
	// transaction. Tx.Commit will return an error if the context provided to
	// BeginxContext is canceled.
	BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error)

	// ExecContext executes a query without returning any rows.
	// The args are for any placeholder parameters in the query.
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

	// NamedExecContext using this DB.
	// Any named placeholder parameters are replaced with fields from arg.
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

	// QueryxContext queries the database and returns an *sqlx.Rows.
	// Any placeholder parameters are replaced with supplied args.
	QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)

	// NamedQueryContext using this DB.
	// Any named placeholder parameters are replaced with fields from arg.
	NamedQueryContext(ctx context.Context, query string, arg interface{}) (*sqlx.Rows, error)

	// PreparexContext returns an sqlx.Stmt instead of a sqlx.Stmt.
	PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error)

	// PrepareNamedContext returns an sqlx.NamedStmt.
	PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)

	// RunTxx runs transaction callback func with default `sql.TxOptions`.
	// If an error occurs, the transaction will be retried if it allows `RetryFunc`.
	RunTxx(ctx context.Context, fn TransactionFunc) error

	// RunReadTxx runs transaction callback func with read only `sql.TxOptions`.
	// If an error occurs, the transaction will be retried if it allows `RetryFunc`.
	RunReadTxx(ctx context.Context, fn TransactionFunc) error

	// RunTxxWithOptions runs transaction callback func with custom `sql.TxOptions`.
	// If an error occurs, the transaction will be retried if it allows `RetryFunc`.
	RunTxxWithOptions(ctx context.Context, opts *sql.TxOptions, fn TransactionFunc) error

	// Close closes the database and prevents new queries from starting.
	// Close then waits for all queries that have started processing on the server
	// to finish.
	//
	// It is rare to Close a DB, as the DB handle is meant to be
	// long-lived and shared between many goroutines.
	Close() error
}

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option sets options such as hooks, metrics and retry parameters, etc.

func WithCockroachRetryFunc

func WithCockroachRetryFunc() Option

func WithCustomHook

func WithCustomHook(hook dbhook.Hook) Option

func WithDefaultOptions

func WithDefaultOptions(tracer trace.Tracer) Option

func WithMetricsHook added in v0.5.0

func WithMetricsHook(collector hooks.MetricCollector) Option

func WithPQRetryFunc added in v0.6.0

func WithPQRetryFunc(maxAttempts int) Option

func WithPrometheusMetrics added in v0.5.0

func WithPrometheusMetrics() Option

func WithReconnectHook

func WithReconnectHook() Option

func WithRetryFunc

func WithRetryFunc(f RetryFunc) Option

func WithSimplerrHook

func WithSimplerrHook() Option

func WithTracingHook

func WithTracingHook(tracer trace.Tracer) Option

type QueryFunc added in v0.6.0

type QueryFunc func(ctx context.Context, db *sqlx.DB) error

type RetryFunc

type RetryFunc func(retryCount int, err error) bool

type TransactionFunc

type TransactionFunc func(ctx context.Context, tx *sqlx.Tx) error

Directories

Path Synopsis
examples
sqlite command
internal
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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