From 3c4cd9c7517d22353d083f87474cae37bb5bf876 Mon Sep 17 00:00:00 2001 From: Mitar Date: Sun, 12 May 2024 22:17:43 +0200 Subject: [PATCH] Use pgtype.PreallocBytes in LargeObject's Read. Fixes #1876. --- large_objects.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/large_objects.go b/large_objects.go index a3028b638..9d21afdce 100644 --- a/large_objects.go +++ b/large_objects.go @@ -4,6 +4,8 @@ import ( "context" "errors" "io" + + "github.com/jackc/pgx/v5/pgtype" ) // The PostgreSQL wire protocol has a limit of 1 GB - 1 per message. See definition of @@ -115,9 +117,10 @@ func (o *LargeObject) Read(p []byte) (int, error) { expected = maxLargeObjectMessageLength } - var res []byte + res := pgtype.PreallocBytes(p[nTotal:]) err := o.tx.QueryRow(o.ctx, "select loread($1, $2)", o.fd, expected).Scan(&res) - copy(p[nTotal:], res) + // We compute expected so that it always fits into p, so it should never happen + // that PreallocBytes's ScanBytes had to allocate a new slice. nTotal += len(res) if err != nil { return nTotal, err