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

Tx.Rollback returns ErrBadConn after context is cancelled #1137

Open
emersion opened this issue Aug 16, 2023 · 0 comments
Open

Tx.Rollback returns ErrBadConn after context is cancelled #1137

emersion opened this issue Aug 16, 2023 · 0 comments

Comments

@emersion
Copy link

emersion commented Aug 16, 2023

Sometimes, Tx.Rollback returns ErrBadConn after a context is cancelled. Doesn't happen on context deadline exceeded it seems.

Reproducer with v1.10.9:

package main

import (
	"log"
	"database/sql"
	"context"
	"sync"

	"github.com/lib/pq"
)

var wg sync.WaitGroup

func main() {
	connStr := "dbname=<name> sslmode=disable"
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(5)

	for i := 0; i < 10000; i++ {
		wg.Add(1)
		go run(db)
	}

	wg.Wait()
}

func run(db *sql.DB) {
	ctx := context.Background()

	ctx, cancel := context.WithCancel(ctx)

	tx, err := db.BeginTx(ctx, &sql.TxOptions{
		ReadOnly:  true,
	})
	if err != nil {
		log.Fatal("BeginTx: ", err)
	}

	cancel()

	ids := []int{1}
	_, err1 := tx.ExecContext(ctx, `SELECT * FROM "user" WHERE id = ANY($1)`, pq.Array(ids))

	err2 := tx.Rollback()

	if err2 != nil {
		log.Print("err1 = ", err1)
		log.Print("err2 = ", err2)
	}

	wg.Done()
}

Output is repeated patterns like the following:

2023/08/16 19:59:38 err1 = context canceled
2023/08/16 19:59:38 err2 = driver: bad connection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant