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:
+9
-1
@@ -49,11 +49,15 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/jackc/pgx"
|
||||
)
|
||||
|
||||
var openFromConnPoolCount int
|
||||
var (
|
||||
openFromConnPoolCountMu sync.Mutex
|
||||
openFromConnPoolCount int
|
||||
)
|
||||
|
||||
// oids that map to intrinsic database/sql types. These will be allowed to be
|
||||
// binary, anything else will be forced to text format
|
||||
@@ -115,8 +119,12 @@ func (d *Driver) Open(name string) (driver.Conn, error) {
|
||||
// pool connection size must be at least 2.
|
||||
func OpenFromConnPool(pool *pgx.ConnPool) (*sql.DB, error) {
|
||||
d := &Driver{Pool: pool}
|
||||
|
||||
openFromConnPoolCountMu.Lock()
|
||||
name := fmt.Sprintf("pgx-%d", openFromConnPoolCount)
|
||||
openFromConnPoolCount++
|
||||
openFromConnPoolCountMu.Unlock()
|
||||
|
||||
sql.Register(name, d)
|
||||
db, err := sql.Open(name, "")
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user