aboutsummaryrefslogtreecommitdiff
path: root/src/database/sql/sql_test.go
diff options
context:
space:
mode:
authorEmmanuel T Odeke <emmanuel@orijtech.com>2021-01-18 16:18:11 -0800
committerDmitri Shuralyov <dmitshur@golang.org>2021-03-30 21:41:42 +0000
commitc77418f4cac41c42566ca90921a1f928995cfba2 (patch)
treeb91ee6f7e76ec9217db99abe94cf73e4a0564d76 /src/database/sql/sql_test.go
parent6df5d3a581380a85183c591d1fd9063a5e8e4b23 (diff)
downloadgo-c77418f4cac41c42566ca90921a1f928995cfba2.tar.gz
go-c77418f4cac41c42566ca90921a1f928995cfba2.zip
[release-branch.go1.15] database/sql: fix tx stmt deadlock when rollback
Tx acquires tx.closemu W-lock and then acquires stmt.closemu.W-lock to fully close the transaction and associated prepared statement. Stmt query and execution run in reverse ways - acquires stmt.closemu.R-lock and then acquires tx.closemu.R-lock to grab tx connection, which may cause deadlock. Prevent the lock is held around tx.closePrepared to ensure no deadlock happens. Includes a test fix from CL 266097. Fixes #42884 Updates #40985 Updates #42259 Change-Id: Id52737660ada3cebdfff6efc23366cdc3224b8e8 Reviewed-on: https://go-review.googlesource.com/c/go/+/250178 Run-TryBot: Emmanuel Odeke <emmanuel@orijtech.com> TryBot-Result: Go Bot <gobot@golang.org> Reviewed-by: Daniel Theophanes <kardianos@gmail.com> Trust: Emmanuel Odeke <emmanuel@orijtech.com> (cherry picked from commit d4c1ad882973e407ff85b977f4ce5b9435451190) Reviewed-on: https://go-review.googlesource.com/c/go/+/284513 Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Diffstat (limited to 'src/database/sql/sql_test.go')
-rw-r--r--src/database/sql/sql_test.go28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/database/sql/sql_test.go b/src/database/sql/sql_test.go
index 5727f0d8aa..d7d4642608 100644
--- a/src/database/sql/sql_test.go
+++ b/src/database/sql/sql_test.go
@@ -2810,6 +2810,34 @@ func TestTxCannotCommitAfterRollback(t *testing.T) {
}
}
+// Issue 40985 transaction statement deadlock while context cancel.
+func TestTxStmtDeadlock(t *testing.T) {
+ db := newTestDB(t, "people")
+ defer closeDB(t, db)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
+ defer cancel()
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ stmt, err := tx.Prepare("SELECT|people|name,age|age=?")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Run number of stmt queries to reproduce deadlock from context cancel
+ for i := 0; i < 1e3; i++ {
+ // Encounter any close related errors (e.g.. ErrTxDone, stmt is closed)
+ // is expected due to context cancel.
+ _, err = stmt.Query(1)
+ if err != nil {
+ break
+ }
+ }
+ _ = tx.Rollback()
+}
+
// Issue32530 encounters an issue where a connection may
// expire right after it comes out of a used connection pool
// even when a new connection is requested.