From c841a6a56f93e5936d2de7e34c1bc3ed8ca544db Mon Sep 17 00:00:00 2001 From: Tony Holdstock-Brown Date: Mon, 23 Mar 2015 11:06:54 -0400 Subject: [PATCH] Add WrapTx method for assimilating *sqlx.Transaction within DbMap This allows you to mix *sqlx.Tx transactions within Modl --- dbmap.go | 6 ++++++ modl_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/dbmap.go b/dbmap.go index 438a35d..5d54f5a 100644 --- a/dbmap.go +++ b/dbmap.go @@ -373,6 +373,12 @@ func (m *DbMap) Begin() (*Transaction, error) { return &Transaction{m, tx}, nil } +// Wraps an already existing sqlx Transaction granting the ability to use +// modl query methods within the same transaction +func (m *DbMap) WrapTx(tx *sqlx.Tx) *Transaction { + return &Transaction{m, tx} +} + // FIXME: This is a poor interface. Checking for nils is un-go-like, and this // function should be TableFor(i interface{}) (*TableMap, error) // FIXME: rewrite this in terms of sqlx's reflect helpers diff --git a/modl_test.go b/modl_test.go index e533c42..1555ee4 100644 --- a/modl_test.go +++ b/modl_test.go @@ -470,6 +470,45 @@ func TestTransaction(t *testing.T) { } } +// Ensures that calling transactin methods with an outside +// *sqlx.Tx works as expected +func TestWrapTransaction(t *testing.T) { + dbmap := initDbMap() + defer dbmap.Cleanup() + + inv1 := &Invoice{0, 100, 200, "t1", 0, true} + inv2 := &Invoice{0, 100, 200, "t2", 0, false} + + tx, err := dbmap.Dbx.Beginx() + if err != nil { + panic(err) + } + + trans := dbmap.WrapTx(tx) + trans.Insert(inv1, inv2) + + // Commit on our standard *sqlx.Tx struct + if err = tx.Commit(); err != nil { + panic(err) + } + + obj := &Invoice{} + err = dbmap.Get(obj, inv1.ID) + if err != nil { + panic(err) + } + if !reflect.DeepEqual(inv1, obj) { + t.Errorf("%v != %v", inv1, obj) + } + err = dbmap.Get(obj, inv2.ID) + if err != nil { + panic(err) + } + if !reflect.DeepEqual(inv2, obj) { + t.Errorf("%v != %v", inv2, obj) + } +} + func TestMultiple(t *testing.T) { dbmap := initDbMap() defer dbmap.Cleanup()