Skip to content

Commit 7c6a1fc

Browse files
author
Jay Mundrawala
committed
Refactor rollback in commit
Rollback cannot be called in Commit as the function that watches the context for cancelation assumes it is only ever called once. Calling it multiple times hangs the goroutine. This is an alternative to #829. Fixes #731 and #848 Replaces #829 Signed-off-by: Jay Mundrawala <[email protected]>
1 parent 2ff3cb3 commit 7c6a1fc

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

conn.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ func (cn *conn) Commit() (err error) {
549549
// would get the same behaviour if you issued a COMMIT in a failed
550550
// transaction, so it's also the least surprising thing to do here.
551551
if cn.txnStatus == txnStatusInFailedTransaction {
552-
if err := cn.Rollback(); err != nil {
552+
if err := cn.rollback(); err != nil {
553553
return err
554554
}
555555
return ErrInFailedTransaction
@@ -576,7 +576,10 @@ func (cn *conn) Rollback() (err error) {
576576
return driver.ErrBadConn
577577
}
578578
defer cn.errRecover(&err)
579+
return cn.rollback()
580+
}
579581

582+
func (cn *conn) rollback() (err error) {
580583
cn.checkIsInTransaction(true)
581584
_, commandTag, err := cn.simpleExec("ROLLBACK")
582585
if err != nil {

go19_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,25 @@ func TestPing(t *testing.T) {
6767
t.Fatalf("expected error %s, instead got %s", driver.ErrBadConn, err)
6868
}
6969
}
70+
71+
func TestCommitInFailedTransactionWithCancelContext(t *testing.T) {
72+
db := openTestConn(t)
73+
defer db.Close()
74+
75+
ctx, cancel := context.WithCancel(context.Background())
76+
defer cancel()
77+
78+
txn, err := db.BeginTx(ctx, nil)
79+
if err != nil {
80+
t.Fatal(err)
81+
}
82+
rows, err := txn.Query("SELECT error")
83+
if err == nil {
84+
rows.Close()
85+
t.Fatal("expected failure")
86+
}
87+
err = txn.Commit()
88+
if err != ErrInFailedTransaction {
89+
t.Fatalf("expected ErrInFailedTransaction; got %#v", err)
90+
}
91+
}

0 commit comments

Comments
 (0)