dbrx

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2021 License: MIT Imports: 11 Imported by: 1

README

dbrx - Transaction wrapped dbr

This is a little utility package used to wrap dbr sessions with a global transaction. The idea is to simplify the development of microservices, releasing the developer from the need of repeating the code necessary to create transactions, and deal with commit or rollback, for all requests.

Instalation

Use go get

go get github.com/stefanomozart/dbrx

Usage

You just need to use dbr connect to the database and create a regular session , then use the Wrap(sess *dbr.Session) function to wrap the session with a global transaction.

import (
    "github.com/gocraft/dbr"
    "github.com/stefanomozart/dbrx"
)

func handleRequest() {
    // connect to the database
    conn, err := dbr.Open("pgx", dsn, nil)
    if err != nil {
        panic(err)
    }

    // wrap the session 
    wrappedSession :=  dbrx.Wrap(conn.NewSession(nil))

    // then pass on the wrapped session to your service endpoint

}

The package also provides the utility function SetupConn(dsn string) that will receive a dns string and perform the connection, create the session and return the wrapped connection:

import (
    "github.com/gocraft/dbr"
    "github.com/stefanomozart/dbrx"
)

func handleRequest() {
    dsn := "string with host, port, user, password and dbname"
    // Use dbrx to connect, start the session and wrap it on a transaction
    wrappedSession :=  dbrx.SetupConn(dsn)

    // then pass on the wrapped session to your service endpoint
}

If you provide and empty string as the parameter to the SetupConn function, it will atempt to create a dsn using environment variables, as follows:

dsn = fmt.Sprintf(
    "host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
    GetEnv("DB_HOST", "localhost"),
    GetEnv("DB_PORT", "5432"),
    GetEnv("DB_USER", "postgres"),
    GetEnv("DB_PASSWD", ""),
    GetEnv("DB_DBNAME", "postgres"),
)

Supported database divres

This package was written especifically to be used with the postgres or the pgx database drivers. It can was be used with the SQLite3 driver for testing.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound           = errors.New("dbr: not found")
	ErrNotSupported       = errors.New("dbr: not supported")
	ErrTableNotSpecified  = errors.New("dbr: table not specified")
	ErrColumnNotSpecified = errors.New("dbr: column not specified")
	ErrInvalidPointer     = errors.New("dbr: attempt to load into an invalid pointer")
	ErrPlaceholderCount   = errors.New("dbr: wrong placeholder count")
	ErrInvalidSliceLength = errors.New("dbr: length of slice is 0. length must be >= 1")
	ErrCantConvertToTime  = errors.New("dbr: can't convert to time.Time")
	ErrInvalidTimestring  = errors.New("dbr: invalid time string")
	ErrInvalidValue       = errors.New("dbrx: invalid value")
)

package errors

Functions

func GetEnv

func GetEnv(varName, defaultVal string) string

GetEnv returns the environment variable, if it is set, or the provided default value

func Greatest

func Greatest(d dbr.Dialect, value ...interface{}) dbr.Builder

func Parens

func Parens(b dbr.Builder) dbr.Builder

func RunInTransaction

func RunInTransaction(dml DML, f func(tx TX) error) error

RunInTransaction calls f inside a transaction and rollbacks if it returns an error

func Translate

func Translate(d dbr.Dialect, text, regex, replace string) dbr.Builder

func TranslateString

func TranslateString(d dbr.Dialect, text, regex, replace string) string

Types

type AfterCommitEventReceiver

type AfterCommitEventReceiver struct {
	*dbr.NullEventReceiver
	// contains filtered or unexported fields
}

func (*AfterCommitEventReceiver) Add

func (er *AfterCommitEventReceiver) Add(f func())

func (*AfterCommitEventReceiver) Event

func (er *AfterCommitEventReceiver) Event(eventName string)

type DML

type DML interface {
	Select(...string) *SelectStmt
	InsertInto(string) *InsertStmt
	Update(string) *UpdateStmt
	DeleteFrom(string) *dbr.DeleteStmt
	Begin() (TX, error)
	Exec(sql string, args ...interface{}) (sql.Result, error)
	With(name string, builder dbr.Builder) DML
	Greatest(value ...interface{}) dbr.Builder
	Union(builders ...dbr.Builder) *UnionStmt
	RunAfterCommit(func()) error
	UpdateBySql(sql string) *dbr.UpdateBuilder
	SelectBySql(sql string, value ...interface{}) *dbr.SelectBuilder
	InsertBySql(sql string, value ...interface{}) *dbr.InsertStmt
	TranslateString(text, regex, replace string) string
	Translate(text, regex, replace string) dbr.Builder
}

DML is the data manipulation language interface for dbr

func SetupConn

func SetupConn(dsn string) DML

SetupConn abre conexão de banco

func Wrap

func Wrap(s *dbr.Session) DML

Wrap a *dbr.Session

type DoUpdateBuilder

type DoUpdateBuilder struct {
	Value     map[string]interface{}
	WhereCond []dbr.Builder
}

func DoUpdate

func DoUpdate() *DoUpdateBuilder

func (*DoUpdateBuilder) Build

func (b *DoUpdateBuilder) Build(d dbr.Dialect, buf dbr.Buffer) error

func (*DoUpdateBuilder) Set

func (b *DoUpdateBuilder) Set(column string, expr interface{}) *DoUpdateBuilder

func (*DoUpdateBuilder) Where

func (b *DoUpdateBuilder) Where(query interface{}, value ...interface{}) *DoUpdateBuilder

type InsertStmt

type InsertStmt struct {
	*dbr.InsertStmt
	// contains filtered or unexported fields
}

InsertStmt overcomes dbr.InsertStmt limitations

func (*InsertStmt) Build

func (b *InsertStmt) Build(d dbr.Dialect, buf dbr.Buffer) error

Build calls itself to build SQL.

func (*InsertStmt) Columns

func (b *InsertStmt) Columns(column ...string) *InsertStmt

Columns specifies the columns names

func (*InsertStmt) Exec

func (b *InsertStmt) Exec() (sql.Result, error)

Exec runs the insert statement

func (*InsertStmt) ExecContext

func (b *InsertStmt) ExecContext(ctx context.Context) (sql.Result, error)

ExecContext runs the insert statement

func (*InsertStmt) OnConflict

func (b *InsertStmt) OnConflict(name interface{}, do dbr.Builder) *InsertStmt

OnConflict implements the ON CONFLICT clause

func (*InsertStmt) Returning

func (b *InsertStmt) Returning(column ...string) *InsertStmt

Returning specifies the returning columns for postgres.

func (*InsertStmt) Values

func (b *InsertStmt) Values(value ...interface{}) *InsertStmt

Values adds a tuple to be inserted. The order of the tuple should match Columns.

type MultipleEventReceiver

type MultipleEventReceiver []dbr.EventReceiver

func (MultipleEventReceiver) Add

func (ers MultipleEventReceiver) Add(fn func())

func (MultipleEventReceiver) Event

func (ers MultipleEventReceiver) Event(eventName string)

func (MultipleEventReceiver) EventErr

func (ers MultipleEventReceiver) EventErr(eventName string, err error) error

func (MultipleEventReceiver) EventErrKv

func (ers MultipleEventReceiver) EventErrKv(eventName string, err error, kvs map[string]string) error

func (MultipleEventReceiver) EventKv

func (ers MultipleEventReceiver) EventKv(eventName string, kvs map[string]string)

func (MultipleEventReceiver) Timing

func (ers MultipleEventReceiver) Timing(eventName string, nanoseconds int64)

func (MultipleEventReceiver) TimingKv

func (ers MultipleEventReceiver) TimingKv(eventName string, nanoseconds int64, kvs map[string]string)

type SelectStmt

type SelectStmt struct {
	*dbr.SelectStmt
	// contains filtered or unexported fields
}

SelectStmt overcomes dbr.SelectStmt limitations

func (*SelectStmt) Build

func (b *SelectStmt) Build(d dbr.Dialect, buf dbr.Buffer) error

Build calls itself to build SQL.

func (*SelectStmt) Debug

func (b *SelectStmt) Debug()

Debug prints the select query, without and with the values

func (*SelectStmt) From

func (b *SelectStmt) From(table interface{}) *SelectStmt

func (*SelectStmt) Join

func (b *SelectStmt) Join(table, on interface{}) *SelectStmt

func (*SelectStmt) LeftJoin

func (b *SelectStmt) LeftJoin(table, on interface{}) *SelectStmt

func (*SelectStmt) Load

func (b *SelectStmt) Load(value interface{}) (int, error)

func (*SelectStmt) OrderAsc

func (b *SelectStmt) OrderAsc(col string) *SelectStmt

func (*SelectStmt) OrderBy

func (b *SelectStmt) OrderBy(col string) *SelectStmt

func (*SelectStmt) OrderDesc

func (b *SelectStmt) OrderDesc(col string) *SelectStmt

func (*SelectStmt) Where

func (b *SelectStmt) Where(query interface{}, value ...interface{}) *SelectStmt

type TX

type TX interface {
	DML
	Commit() error
	Rollback() error
	RollbackUnlessCommitted()
}

TX represents a db transaction

type UnionStmt

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

func (*UnionStmt) Load

func (us *UnionStmt) Load(value interface{}) (int, error)

func (*UnionStmt) LoadContext

func (us *UnionStmt) LoadContext(ctx context.Context, value interface{}) (int, error)

type UpdateStmt

type UpdateStmt struct {
	*dbr.UpdateStmt
	// contains filtered or unexported fields
}

UpdateStmt overcomes dbr.UpdateStmt limitations

func (*UpdateStmt) Build

func (b *UpdateStmt) Build(d dbr.Dialect, buf dbr.Buffer) error

Build calls itself to build SQL.

func (*UpdateStmt) Exec

func (b *UpdateStmt) Exec() (sql.Result, error)

Exec runs the update statement

func (*UpdateStmt) ExecContext

func (b *UpdateStmt) ExecContext(ctx context.Context) (sql.Result, error)

ExecContext runs the update statement

func (*UpdateStmt) Returning

func (b *UpdateStmt) Returning(column ...string) *UpdateStmt

Returning specifies the returning columns for postgres.

func (*UpdateStmt) Set

func (b *UpdateStmt) Set(column string, value interface{}) *UpdateStmt

Set updates column with value.

func (*UpdateStmt) Where

func (b *UpdateStmt) Where(query interface{}, value ...interface{}) *UpdateStmt

Where adds a where condition. query can be Builder or string. value is used only if query type is string.

type ValuesExpr

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

func Values

func Values(v ...interface{}) *ValuesExpr

func (*ValuesExpr) Build

func (e *ValuesExpr) Build(d dbr.Dialect, buf dbr.Buffer) error

func (*ValuesExpr) Values

func (e *ValuesExpr) Values(v ...interface{}) *ValuesExpr

Jump to

Keyboard shortcuts

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