Add a cache of OID in database to register types
It makes no sense to retrieve the same OIDs each and every connection, because they are not going to change unless the database is reset, something it is very unlikely to happen in production. Thus, it is best to query them the first time the application connects to the database, that it is done at startup to query the available languages, and then reuse the OIDs. I can get away of using an “unprotected” map, instead of sync.Map or a map in tandem with sync.RWMutex, because the application establishes a connection at startup from a single goroutine, and it registers _all_ types we will need to register within the application’s lifespan, hence it there will be no more writes to that map once the web server is listening for incoming connections. This is risky, however, and i hope i do not have to regret it.
This commit is contained in:
parent
2501b7d226
commit
ef215f1e6e
|
@ -7,6 +7,10 @@ import (
|
|||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
var (
|
||||
oidCache = make(map[string]uint32)
|
||||
)
|
||||
|
||||
type CustomerTaxDetails struct {
|
||||
BusinessName string
|
||||
VATIN string
|
||||
|
@ -325,8 +329,12 @@ func registerPgTypes(ctx context.Context, conn *pgx.Conn) error {
|
|||
}
|
||||
|
||||
func registerPgType(ctx context.Context, conn *pgx.Conn, value pgtype.Value, name string) (oid uint32, err error) {
|
||||
if err = conn.QueryRow(ctx, "select $1::regtype::oid", name).Scan(&oid); err != nil {
|
||||
return
|
||||
var found bool
|
||||
if oid, found = oidCache[name]; !found {
|
||||
if err = conn.QueryRow(ctx, "select $1::regtype::oid", name).Scan(&oid); err != nil {
|
||||
return
|
||||
}
|
||||
oidCache[name] = oid
|
||||
}
|
||||
conn.ConnInfo().RegisterDataType(pgtype.DataType{Value: value, Name: name, OID: oid})
|
||||
return
|
||||
|
|
Loading…
Reference in New Issue