From 0d163ce1c95d03a173eba246de6d45db69e678ac Mon Sep 17 00:00:00 2001 From: Daniel Theophanes Date: Fri, 28 Oct 2016 10:10:46 -0700 Subject: database/sql: do not bypass the driver locks with Context methods When context methods were initially added it was attempted to unify behavior between drivers without Context methods and those with Context methods to always return right away when the Context expired. However in doing so the driver call could be executed outside of the scope of the driver connection lock and thus bypassing thread safety. The new behavior waits until the driver operation is complete. It then checks to see if the context has expired and if so returns that error. Change-Id: I4a5c7c3263420c57778f36a5ed6fa0ef8cb32b20 Reviewed-on: https://go-review.googlesource.com/32422 Reviewed-by: Brad Fitzpatrick Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- src/database/sql/fakedb_test.go | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) (limited to 'src/database/sql/fakedb_test.go') diff --git a/src/database/sql/fakedb_test.go b/src/database/sql/fakedb_test.go index c42f23208f..9de9289644 100644 --- a/src/database/sql/fakedb_test.go +++ b/src/database/sql/fakedb_test.go @@ -39,6 +39,9 @@ var _ = log.Printf // Any of these can be preceded by PANIC||, to cause the // named method on fakeStmt to panic. // +// Any of these can be proceeded by WAIT||, to cause the +// named method on fakeStmt to sleep for the specified duration. +// // Multiple of these can be combined when separated with a semicolon. // // When opening a fakeDriver's database, it starts empty with no @@ -119,6 +122,7 @@ type fakeStmt struct { cmd string table string panic string + wait time.Duration next *fakeStmt // used for returning multiple results. @@ -526,14 +530,28 @@ func (c *fakeConn) Prepare(query string) (driver.Stmt, error) { if firstStmt == nil { firstStmt = stmt } - if len(parts) >= 3 && parts[0] == "PANIC" { - stmt.panic = parts[1] - parts = parts[2:] + if len(parts) >= 3 { + switch parts[0] { + case "PANIC": + stmt.panic = parts[1] + parts = parts[2:] + case "WAIT": + wait, err := time.ParseDuration(parts[1]) + if err != nil { + return nil, errf("expected section after WAIT to be a duration, got %q %v", parts[1], err) + } + parts = parts[2:] + stmt.wait = wait + } } cmd := parts[0] stmt.cmd = cmd parts = parts[1:] + if stmt.wait > 0 { + time.Sleep(stmt.wait) + } + c.incrStat(&c.stmtsMade) var err error switch cmd { @@ -619,6 +637,16 @@ func (s *fakeStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (d return nil, err } + if s.wait > 0 { + time.Sleep(s.wait) + } + + select { + default: + case <-ctx.Done(): + return nil, ctx.Err() + } + db := s.c.db switch s.cmd { case "WIPE": -- cgit v1.3-5-g9baa