Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/awcodify/tx

Simple example to database transaction with golang
https://github.com/awcodify/tx

commit go golang rollback sql transaction

Last synced: 24 days ago
JSON representation

Simple example to database transaction with golang

Awesome Lists containing this project

README

        

# Tx
Transactions enforce the integrity of the database and guard the data against program errors or database break-downs [[=>]](https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html).

## How to use
Wrap your transaction inside `Wrap` function. It determine between `Rollback()` and `Commit()` . See example below:
```go
package main

func main() {
// ... some codes
tx : tx.NewTx(db)
err := tx.Wrap(createUserAndRole)
if err != nil {
log.Fatal(err)
}
// ... some codes
}

// This our needs
func createUserAndRole(t Transaction) (err error) {
res, err := t.Exec("INSERT INTO users(name,email) VALUES(?,?)", "example", "[email protected]")
if err != nil {
return
}

userId, err := res.LastInsertId()
if err != nil {
return
}

res, err = t.Exec("INSERT INTO role(user_id,privileges) VALUES(?,?)", userId, "SELECT,INSERT")
if err != nil {
return
}

return
}
```