From ef215f1e6e2ec88b5054f88a7409f04480284c27 Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Fri, 27 Oct 2023 12:44:24 +0200 Subject: [PATCH] Add a cache of OID in database to register types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- pkg/pgtypes.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/pkg/pgtypes.go b/pkg/pgtypes.go index 25326a5..6b02fbd 100644 --- a/pkg/pgtypes.go +++ b/pkg/pgtypes.go @@ -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