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:
jordi fita mas 2023-10-27 12:44:24 +02:00
parent 2501b7d226
commit ef215f1e6e
1 changed files with 10 additions and 2 deletions

View File

@ -7,6 +7,10 @@ import (
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
var (
oidCache = make(map[string]uint32)
)
type CustomerTaxDetails struct { type CustomerTaxDetails struct {
BusinessName string BusinessName string
VATIN string VATIN string
@ -325,9 +329,13 @@ 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) { func registerPgType(ctx context.Context, conn *pgx.Conn, value pgtype.Value, name string) (oid uint32, err error) {
var found bool
if oid, found = oidCache[name]; !found {
if err = conn.QueryRow(ctx, "select $1::regtype::oid", name).Scan(&oid); err != nil { if err = conn.QueryRow(ctx, "select $1::regtype::oid", name).Scan(&oid); err != nil {
return return
} }
oidCache[name] = oid
}
conn.ConnInfo().RegisterDataType(pgtype.DataType{Value: value, Name: name, OID: oid}) conn.ConnInfo().RegisterDataType(pgtype.DataType{Value: value, Name: name, OID: oid})
return return
} }