Categorygithub.com/andresmijares/sqlxtx
modulepackage
0.0.1
Repository: https://github.com/andresmijares/sqlxtx.git
Documentation: pkg.go.dev

# README

Sqlxtx License: MIT CircleCI Coverage Status

Changes behavior between sqlx.DB and sqlx.Tx in runtime.

Installation

go get -u github.com/andresmijares/sqlxtx

Usage

// domain.go
type User struct {}

func (u *User) Create(username, password string) error {
    _, err := u.Client.NamedExec("INSERT INTO users (first_name, last_name) VALUES (:first_name, :last_name);",
		map[string]interface{}{
			"first_name": "Jhon",
			"last_name":  "Doe",
		})
	if err != nil {
		return err
	}
	return nil
}

type Events struct {}

func (u *Events) Create(name string) error {
    _, err := e.Client.NamedExec(`INSERT INTO events(name) VALUE (:name);`,
		map[string]interface{}{
			"name": name,
		})
	if err != nil {
		return err
	}
    return nil
}

// service.go
// Will manage each operation independently 
func init() {
    
}

func CreateUser () {
    if err := UserDao.Create(); err != nil {
		return err
	}

	if err := EventsDao.Create("userCreated"); err != nil {
		return err
	}

	return nil
}

// Will run a transaction, not need to modify the underline implementation
func CreateUserWithTx () {
    if err := db.WithTx.Exec(func() error {
		if err := UserDao.Create(); err != nil {
			return err
		}

		if err := EventsDao.Create("userCreated"); err != nil {
			return err
		}

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

Test

Sample how to test this can be found in the sample folder.

Limitations

I've mocked only the most commons methods I use, for a more detailed list, please check sqltxmocks

Motivation

Transactions should be implementation details, it should not force developers to re-write code to support between Tx and DB. I couldn't find a solid way to decorate operations in my services, so I created this one.

I lot of motivation were found in this articles.

I only added the methods I use, please, feel free to submit PR's to support more methods.

License

MIT

# Packages

No description provided by the author

# Structs

Config used as configuration object for EnableSqlxTx.
EnableSqlxTx init SqlxTx.
SQLxTx is wrapper around sqlx.Tx, to change behavior in runtime between sqlx.DB and sqlx.Tx.

# Interfaces

SqlxTxInterface exposes a workable interface for SqlxTx.
SqlxWrapperInterface Wraps sqlx interface.
Transactions wraps sqlx Transactions functionality.