- Notifications
You must be signed in to change notification settings - Fork24
Nested transactions for sqlx
License
NotificationsYou must be signed in to change notification settings
heetch/sqalx
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
sqalx (pronounced 'scale-x') is a library built on top ofsqlx that allows to seamlessly create nested transactions and to avoid thinking about whether or not a function is called within a transaction.With sqalx you can easily create reusable and composable functions that can be called within or out of transactions and that can create transactions themselves.
$ go get github.com/heetch/sqalx
import"github.com/heetch/sqalx"
package mainimport ("log""github.com/heetch/sqalx""github.com/jmoiron/sqlx"_"github.com/lib/pq")funcmain() {// Connect to PostgreSQL with sqlx.db,err:=sqlx.Connect("postgres","user=foo dbname=bar sslmode=disable")iferr!=nil {log.Fatal(err)}deferdb.Close()// Pass the db to sqalx.// It returns a sqalx.Node. A Node is a wrapper around sqlx.DB or sqlx.Tx.node,err:=sqalx.New(db)iferr!=nil {log.Fatal(err)}err=createUser(node)iferr!=nil {log.Fatal(err)}}funccreateUser(node sqalx.Node)error {// Exec a query_,_=node.Exec("INSERT INTO ....")// you can use a node as if it were a *sqlx.DB or a *sqlx.Tx// Let's create a transaction.// A transaction is also a sqalx.Node.tx,err:=node.Beginx()iferr!=nil {returnerr}defertx.Rollback()_,_=tx.Exec("UPDATE ...")// Now we call another function and pass it the transaction.err=updateGroups(tx)iferr!=nil {returnnil}returntx.Commit()}funcupdateGroups(node sqlax.Node)error {// Notice we are creating a new transaction.// This would normally cause a dead lock without sqalx.tx,err:=node.Beginx()iferr!=nil {returnerr}defertx.Rollback()_,_=tx.Exec("INSERT ...")_,_=tx.Exec("UPDATE ...")_,_=tx.Exec("DELETE ...")returntx.Commit()}
When using the PostgreSQL driver, an option can be passed toNew
to enable the use of PostgreSQLSavepoints for nested transactions.
node,err:=sqalx.New(db,sqalx.SavePoint(true))
Please open an issue if you encounter any problem.
The library is released under the MIT license. SeeLICENSE file.
About
Nested transactions for sqlx
Topics
Resources
License
Stars
Watchers
Forks
Packages0
No packages published