Add a documentation badge
Add more documentation
Add BeginTx function
Nestable transaction-like contexts for Go database/sql
database connections. Primarily made for writing integration tests - run each test inside a TxContext
, and have the application code start/rollback/commit subcontexts when it would usually use transactions.
SavepointContext
in a TxContext
at any given time. The contexts should
make up a stack, and there should only be one context at any given level in
the stack.
First, install the library
go get git.sr.ht/~pmc/dbcontext
Then, use it. Check out the tests for some more examples. Here's a psuedocode example:
// In your tests:
func TestMyApp(t *testing.T) {
db, err := sql.Open("mysql", "")
require.NoError(t, err)
dbcontext.WithTxContext(db, func(context *dbcontext.TxContext) (*any, error) {
httpRequest(db, "POST", "/user/{user_id}", myUserData)
// Do whatever testing you need here
// WithTxContext will automatically rollback the transaction if it hasn't already been rolled back or committed
return nil, nil
})
}
// In your application
func PostUserHandler(db dbcontext.SqlContext, req HttpRequest) (*HttpResponse, error) {
return dbcontext.WithSubcontext(db, func(tx dbcontext.SqlContext) (*HttpResponse, error) {
var user User
row := tx.QueryRow("SELECT * FROM users WHERE user_id = ?", req.UserID)
if row.Err() != nil {
return nil, row.Err()
}
err := row.Scan(&user)
if err != nil {
return nil, err
}
return &HttpResponse{
User: user,
}, nil
})
}
Version 1.0.0
This license gives everyone as much permission to work with this software as possible, while protecting contributors from liability.
In order to receive this license, you must agree to its rules. The rules of this license are both obligations under that agreement and conditions to your license. You must not do anything with this software that triggers a rule that you cannot or will not follow.
Each contributor licenses you to do everything with this software that would otherwise infringe that contributor's copyright in it.
You must ensure that everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license or a link to https://blueoakcouncil.org/license/1.0.0.
If anyone notifies you in writing that you have not complied with Notices, you can keep your license by taking all practical steps to comply within 30 days after the notice. If you do not do so, your license ends immediately.
Each contributor licenses you to do everything with this software that would otherwise infringe any patent claims they can license or become able to license.
No contributor can revoke this license.
As far as the law allows, this software comes as is, without any warranty or condition, and no contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim.