Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix checking cancelled connections back into the connection pool #1095

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -107,3 +107,4 @@ Multiplay Ltd.
Percona LLC
Pivotal Inc.
Stripe Inc.
Zendesk Inc.
4 changes: 4 additions & 0 deletions connection.go
Expand Up @@ -489,6 +489,10 @@ func (mc *mysqlConn) Ping(ctx context.Context) (err error) {

// BeginTx implements driver.ConnBeginTx interface
func (mc *mysqlConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
if mc.closed.IsSet() {
return nil, driver.ErrBadConn
}

if err := mc.watchCancel(ctx); err != nil {
return nil, err
}
Expand Down
19 changes: 17 additions & 2 deletions driver_test.go
Expand Up @@ -2608,7 +2608,12 @@ func TestContextCancelBegin(t *testing.T) {
runTests(t, dsn, func(dbt *DBTest) {
dbt.mustExec("CREATE TABLE test (v INTEGER)")
ctx, cancel := context.WithCancel(context.Background())
tx, err := dbt.db.BeginTx(ctx, nil)
conn, err := dbt.db.Conn(ctx)
if err != nil {
dbt.Fatal(err)
}
defer conn.Close()
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
dbt.Fatal(err)
}
Expand Down Expand Up @@ -2638,7 +2643,17 @@ func TestContextCancelBegin(t *testing.T) {
dbt.Errorf("expected sql.ErrTxDone or context.Canceled, got %v", err)
}

// Context is canceled, so cannot begin a transaction.
// The connection is now in an inoperable state - so performing other
// operations should fail with ErrBadConn
// Important to exercise isolation level too - it runs SET TRANSACTION ISOLATION
// LEVEL XXX first, which needs to return ErrBadConn if the connection's context
// is cancelled
_, err = conn.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != driver.ErrBadConn {
dbt.Errorf("expected driver.ErrBadConn, got %v", err)
}

// cannot begin a transaction (on a different conn) with a canceled context
if _, err := dbt.db.BeginTx(ctx, nil); err != context.Canceled {
dbt.Errorf("expected context.Canceled, got %v", err)
}
Expand Down