Skip to content

Commit

Permalink
simplify duplicate pgx registration guard
Browse files Browse the repository at this point in the history
The binary search is overkill here.
Readability first.
  • Loading branch information
prochac authored and jackc committed Feb 14, 2023
1 parent 1e68b39 commit 7fed69b
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions stdlib/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ import (
"math"
"math/rand"
"reflect"
"sort"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -86,9 +85,9 @@ func init() {
}
fakeTxConns = make(map[*pgx.Conn]*sql.Tx)

drivers := sql.Drivers()
// if pgx driver was already registered by different pgx major version then we skip registration under the default name.
if i := sort.SearchStrings(sql.Drivers(), "pgx"); len(drivers) >= i || drivers[i] != "pgx" {
// if pgx driver was already registered by different pgx major version then we
// skip registration under the default name.
if !contains(sql.Drivers(), "pgx") {
sql.Register("pgx", pgxDriver)
}
sql.Register("pgx/v4", pgxDriver)
Expand All @@ -110,6 +109,17 @@ func init() {
}
}

// TODO replace by slices.Contains when experimental package will be merged to stdlib
// https://pkg.go.dev/golang.org/x/exp/slices#Contains
func contains(list []string, y string) bool {
for _, x := range list {
if x == y {
return true
}
}
return false
}

var (
fakeTxMutex sync.Mutex
fakeTxConns map[*pgx.Conn]*sql.Tx
Expand Down

0 comments on commit 7fed69b

Please sign in to comment.