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 beginTxOnce() context cancel #64

Merged
merged 2 commits into from
May 23, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions db_go18.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,13 @@ func (c *conn) beginTxOnce(ctx context.Context, done <-chan struct{}) (*sql.Tx,
go func() {
select {
case <-ctx.Done():
// operation was interrupted by context cancel, so we cancel parent as well
c.cancel()
select {
case <-done:
// the operation successfully finished at the "same time" as context cancellation, so we won't close ctx on tx
default:
// operation was interrupted by context cancel, so we cancel parent as well
c.cancel()
}
case <-done:
// operation was successfully finished, so we don't close ctx on tx
case <-c.ctx.Done():
Expand Down
35 changes: 35 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -808,3 +808,38 @@ func TestIssue49(t *testing.T) {
}
})
}

func TestShouldRunWithHeavyWork(t *testing.T) {
t.Parallel()

testFn := func(t *testing.T, db *sql.DB) {
t.Helper()

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
row, err := db.QueryContext(ctx, "SELECT 1 from HeavyWork")
if err != nil {
t.Fatalf("failed to query users: %s", err)
}
if err := row.Close(); err != nil {
t.Fatalf("failed to close rows: %s", err)
}
}

txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "HeavyWork")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()

_, err = db.Exec("CREATE TABLE IF NOT EXISTS HeavyWork (id INT, name VARCHAR(255))")
if err != nil {
t.Fatalf("failed to create table: %s", err)
}

for i := 0; i < 10000; i++ {
testFn(t, db)
}
})
}