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 incomming connections. This is risky, however, and i hope i do not have to regret it.
This commit is contained in:
parent
62b54961f4
commit
007f401d33
|
@ -17,6 +17,10 @@ const (
|
|||
RedsysSignedRequestTypeName = "redsys_signed_request"
|
||||
)
|
||||
|
||||
var (
|
||||
oidCache = make(map[string]uint32)
|
||||
)
|
||||
|
||||
func registerTypes(ctx context.Context, conn *pgx.Conn) error {
|
||||
uriOID, err := registerType(ctx, conn, &pgtype.Text{}, "uri")
|
||||
if err != nil {
|
||||
|
@ -65,8 +69,12 @@ func registerTypes(ctx context.Context, conn *pgx.Conn) error {
|
|||
}
|
||||
|
||||
func registerType(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