From dc63b59630cbc7fe1b039757bac0d6f713dfc26d Mon Sep 17 00:00:00 2001 From: Daniel Theophanes Date: Fri, 26 Apr 2019 14:09:07 -0700 Subject: database/sql: add Conn.Raw to expose the driver Conn safely Exposing the underlying driver conn will allow the use of the standard connection pool while still able to run special function directly on the driver. Fixes #29835 Change-Id: Ib6d3b9535e730f008916805ae3bf76e4494c88f9 Reviewed-on: https://go-review.googlesource.com/c/go/+/174182 Run-TryBot: Daniel Theophanes TryBot-Result: Gobot Gobot Reviewed-by: Ian Lance Taylor --- src/database/sql/sql_test.go | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'src/database/sql/sql_test.go') diff --git a/src/database/sql/sql_test.go b/src/database/sql/sql_test.go index 260374d413..a95b70cadb 100644 --- a/src/database/sql/sql_test.go +++ b/src/database/sql/sql_test.go @@ -1339,6 +1339,54 @@ func TestConnQuery(t *testing.T) { } } +func TestConnRaw(t *testing.T) { + db := newTestDB(t, "people") + defer closeDB(t, db) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + conn, err := db.Conn(ctx) + if err != nil { + t.Fatal(err) + } + conn.dc.ci.(*fakeConn).skipDirtySession = true + defer conn.Close() + + sawFunc := false + err = conn.Raw(func(dc interface{}) error { + sawFunc = true + if _, ok := dc.(*fakeConn); !ok { + return fmt.Errorf("got %T want *fakeConn", dc) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if !sawFunc { + t.Fatal("Raw func not called") + } + + func() { + defer func() { + x := recover() + if x == nil { + t.Fatal("expected panic") + } + conn.closemu.Lock() + closed := conn.dc == nil + conn.closemu.Unlock() + if !closed { + t.Fatal("expected connection to be closed after panic") + } + }() + err = conn.Raw(func(dc interface{}) error { + panic("Conn.Raw panic should return an error") + }) + t.Fatal("expected panic from Raw func") + }() +} + func TestCursorFake(t *testing.T) { db := newTestDB(t, "people") defer closeDB(t, db) -- cgit v1.3