database

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2022 License: MIT Imports: 13 Imported by: 2

README

Database

GoDoc Go Report Card

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
	CertPath     string
	Type         DBType
	ReadTimeout  string
	WriteTimeout string
}

func (*Config) DSN added in v0.3.0

func (cfg *Config) DSN() (connStr string)

type DB

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

func New

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

func (*DB) BeginTxx added in v0.6.0

func (db *DB) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, 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) Beginx added in v0.6.0

func (db *DB) Beginx() (*sqlx.Tx, error)

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

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

func (*DB) ExecContext added in v0.6.0

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

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

func (*DB) 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{}) (sql.Result, 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{}) (*sqlx.Rows, 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) (*sqlx.NamedStmt, error)

PrepareNamedContext returns an sqlx.NamedStmt.

func (*DB) PreparexContext added in v0.6.0

func (db *DB) PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, 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{}) (*sqlx.Rows, error)

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

func (*DB) RunTxx

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

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 Option

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

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

Jump to

Keyboard shortcuts

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