sqltx

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2021 License: MIT Imports: 3 Imported by: 1

README

Golang SQL transaction

Helper for sql transactions

Install

go get -u github.com/andrdru/sqltx

Usage

see examples

// add helper to repo

User interface {
  sqltx.Tx

  TX(action func(txRepo User) error) error
}

// TX simplify DoTransaction call for User interface
func (m *user) TX(action func(txRepo User) error) error {
  return m.DoTransaction(
    func(tx sqltx.QueryExecutor) sqltx.Tx { return NewUser(tx) },
    func(txRepo sqltx.Tx) error { return action(txRepo.(User)) },
  )
}

// call

err = userRepo.TX(func(txRepo repo.User) (err error) {
  err = txRepo.CreateUser(ctx, 1, "Vasya")
  if err != nil {
    return err
  }
  
  return nil
}

if err != nil {
  log.Fatalf("transaction rollback: %s", err)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDatabaseTypeInvalid throws when QueryExecutor not *sql.DB
	// are you try to run transaction in transaction?
	ErrDatabaseTypeInvalid = errors.New("wrong database struct type")
)

Functions

This section is empty.

Types

type QueryExecutor

type QueryExecutor interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
}

QueryExecutor is execution interface of sql.Tx and sql.DB

type Tx

type Tx interface {
	DoTransaction(construct func(tx QueryExecutor) Tx, action func(txRepo Tx) error) (err error)
	DB() (db QueryExecutor)
}

Tx repo tx helper

func NewTx

func NewTx(db QueryExecutor) Tx

Directories

Path Synopsis
examples
sql2repos Module

Jump to

Keyboard shortcuts

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