fix(stdlib): lock openFromConnPoolCount while using
Locks the `openFromConnPoolCount` counter while formatting the driver name and incrementing to avoid a data race of multiple goroutines modifying the counter and registering the same name. `sql.Register` panics if a driver name has already been registered.
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"github.com/jackc/pgx"
|
||||
"github.com/jackc/pgx/stdlib"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -163,6 +164,43 @@ func TestOpenFromConnPool(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenFromConnPoolRace(t *testing.T) {
|
||||
wg := &sync.WaitGroup{}
|
||||
connConfig := pgx.ConnConfig{
|
||||
Host: "127.0.0.1",
|
||||
User: "pgx_md5",
|
||||
Password: "secret",
|
||||
Database: "pgx_test",
|
||||
}
|
||||
|
||||
config := pgx.ConnPoolConfig{ConnConfig: connConfig}
|
||||
pool, err := pgx.NewConnPool(config)
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to create connection pool: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
wg.Add(10)
|
||||
for i := 0; i < 10; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
db, err := stdlib.OpenFromConnPool(pool)
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to create connection pool: %v", err)
|
||||
}
|
||||
defer closeDB(t, db)
|
||||
|
||||
// Can get pgx.ConnPool from driver
|
||||
driver := db.Driver().(*stdlib.Driver)
|
||||
if driver.Pool == nil {
|
||||
t.Fatal("Expected driver opened through OpenFromConnPool to have Pool, but it did not")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestStmtExec(t *testing.T) {
|
||||
db := openDB(t)
|
||||
defer closeDB(t, db)
|
||||
|
||||
Reference in New Issue
Block a user