From 007f401d33e0658c372ca42a45121c4b8676f40d Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Fri, 27 Oct 2023 12:30:05 +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 incomming connections. This is risky, however, and i hope i do not have to regret it. --- pkg/database/types.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/pkg/database/types.go b/pkg/database/types.go index a24998e..baaf6cc 100644 --- a/pkg/database/types.go +++ b/pkg/database/types.go @@ -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