From 1a69268856845d793d639d685ca0030272a2478b Mon Sep 17 00:00:00 2001 From: Shinya Kato Date: Tue, 1 Dec 2026 10:41:41 +0900 Subject: [PATCH v2 3/4] Add SendFunctionCallInto() to append a send function's output to a buffer Callers of a send function copied its result into a buffer of their own, as a length word followed by the data: printtup and EXPLAIN SERIALIZE into the DataRow message, COPY TO into its row buffer, logical replication into its message, and the container types into their own output. The bytea that each send function allocated, 1 kB by default, was thrown away right after the copy. Add SendFunctionCallInto(), which appends a value to a caller's buffer in that format. It passes the buffer to the send function through a new SendBufferContext node in fcinfo->context. A send function that starts with the new pq_begintypsend_fcinfo() and finishes with pq_endtypsend_fcinfo() appends to that buffer and fills in the length word, so the value is neither allocated separately nor copied. When called any other way, the same send function builds a bytea as before. Send functions that still use pq_begintypsend() keep working, and their result is copied into the buffer. SendFunctionCallInto() frees a copied result, as array_send() always did for its elements, so a send function must return palloc'd memory. That was already required for any type that can be an array element. This commit converts the callers. The send functions are converted separately. Author: Andres Freund Author: Shinya Kato Discussion: https://postgr.es/m/20240218015955.rmw5mcmobt5hbene@awork3.anarazel.de Discussion: https://postgr.es/m/CAOzEurReWaX8i72CBbBzYZzNSP=XRQdp1=cB+rYhir1CB9DUUg@mail.gmail.com --- src/backend/access/common/printtup.c | 7 +-- src/backend/commands/copyto.c | 11 +---- src/backend/commands/explain_dr.c | 7 +-- src/backend/libpq/pqformat.c | 66 +++++++++++++++++++++++++ src/backend/replication/logical/proto.c | 10 ++-- src/backend/utils/adt/array_userfuncs.c | 8 +-- src/backend/utils/adt/arrayfuncs.c | 10 +--- src/backend/utils/adt/multirangetypes.c | 6 +-- src/backend/utils/adt/rangetypes.c | 18 +------ src/backend/utils/adt/rowtypes.c | 6 +-- src/backend/utils/fmgr/fmgr.c | 48 ++++++++++++++++++ src/include/fmgr.h | 1 + src/include/libpq/pqformat.h | 3 ++ src/include/nodes/miscnodes.h | 18 +++++++ src/tools/pgindent/typedefs.list | 1 + 15 files changed, 150 insertions(+), 70 deletions(-) diff --git a/src/backend/access/common/printtup.c b/src/backend/access/common/printtup.c index 06d56cf2f20..a0fb0fd9c0e 100644 --- a/src/backend/access/common/printtup.c +++ b/src/backend/access/common/printtup.c @@ -363,12 +363,7 @@ printtup(TupleTableSlot *slot, DestReceiver *self) else { /* Binary output */ - bytea *outputbytes; - - outputbytes = SendFunctionCall(&thisState->finfo, attr); - pq_sendint32(buf, VARSIZE(outputbytes) - VARHDRSZ); - pq_sendbytes(buf, VARDATA(outputbytes), - VARSIZE(outputbytes) - VARHDRSZ); + SendFunctionCallInto(&thisState->finfo, attr, buf); } } diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c index 9ca06ed3e18..16d1b108d26 100644 --- a/src/backend/commands/copyto.c +++ b/src/backend/commands/copyto.c @@ -520,15 +520,8 @@ CopyToBinaryOneRow(CopyToState cstate, TupleTableSlot *slot) CopySendInt32(cstate, -1); } else - { - bytea *outputbytes; - - outputbytes = SendFunctionCall(&out_functions[attnum - 1], - value); - CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ); - CopySendData(cstate, VARDATA(outputbytes), - VARSIZE(outputbytes) - VARHDRSZ); - } + SendFunctionCallInto(&out_functions[attnum - 1], value, + cstate->fe_msgbuf); } CopySendEndOfRow(cstate); diff --git a/src/backend/commands/explain_dr.c b/src/backend/commands/explain_dr.c index 97166f9c06c..486ce45bd80 100644 --- a/src/backend/commands/explain_dr.c +++ b/src/backend/commands/explain_dr.c @@ -165,12 +165,7 @@ serializeAnalyzeReceive(TupleTableSlot *slot, DestReceiver *self) else { /* Binary output */ - bytea *outputbytes; - - outputbytes = SendFunctionCall(finfo, attr); - pq_sendint32(buf, VARSIZE(outputbytes) - VARHDRSZ); - pq_sendbytes(buf, VARDATA(outputbytes), - VARSIZE(outputbytes) - VARHDRSZ); + SendFunctionCallInto(finfo, attr, buf); } } diff --git a/src/backend/libpq/pqformat.c b/src/backend/libpq/pqformat.c index c16e8365fcc..cf699ccab9d 100644 --- a/src/backend/libpq/pqformat.c +++ b/src/backend/libpq/pqformat.c @@ -50,6 +50,8 @@ * typsend support (construct a bytea value containing external binary data): * pq_begintypsend - initialize StringInfo buffer * pq_endtypsend - return the completed string as a "bytea*" + * pq_begintypsend_fcinfo - like pq_begintypsend, but may use caller's buffer + * pq_endtypsend_fcinfo - finish pq_begintypsend_fcinfo output * * Special-case message output: * pq_puttextmessage - generate a character set-converted message in one step @@ -76,6 +78,7 @@ #include "libpq/libpq.h" #include "libpq/pqformat.h" #include "mb/pg_wchar.h" +#include "nodes/miscnodes.h" #include "port/pg_bswap.h" #include "varatt.h" @@ -358,6 +361,69 @@ pq_endtypsend(StringInfo buf) return result; } +/* -------------------------------- + * pq_begintypsend_fcinfo - start the output of a send function + * + * If the send function was called by SendFunctionCallInto(), returns the + * caller's buffer with the length word reserved, so that the value is + * written into it directly. Otherwise this is the same as pq_begintypsend() + * on a newly allocated StringInfo. Either way, finish the output with + * pq_endtypsend_fcinfo(). + * -------------------------------- + */ +StringInfo +pq_begintypsend_fcinfo(FunctionCallInfo fcinfo) +{ + SendBufferContext *sendctx = (SendBufferContext *) fcinfo->context; + StringInfo buf; + + if (sendctx == NULL || !IsA(sendctx, SendBufferContext)) + { + buf = palloc_object(StringInfoData); + pq_begintypsend(buf); + return buf; + } + + Assert(sendctx->lenpos < 0); + buf = sendctx->buf; + sendctx->lenpos = buf->len; + pq_sendint32(buf, 0); + + return buf; +} + +/* -------------------------------- + * pq_endtypsend_fcinfo - finish the output of a send function + * + * Returns the completed bytea, or NULL if the value went into the caller's + * buffer. The send function returns that as its result. + * -------------------------------- + */ +bytea * +pq_endtypsend_fcinfo(FunctionCallInfo fcinfo, StringInfo buf) +{ + SendBufferContext *sendctx = (SendBufferContext *) fcinfo->context; + uint32 len; + + if (sendctx == NULL || !IsA(sendctx, SendBufferContext)) + { + bytea *result = pq_endtypsend(buf); + + pfree(buf); + return result; + } + + Assert(buf == sendctx->buf); + Assert(sendctx->lenpos >= 0 && !sendctx->done); + + /* The caller wants the length word in network byte order */ + len = pg_hton32(buf->len - sendctx->lenpos - sizeof(uint32)); + memcpy(buf->data + sendctx->lenpos, &len, sizeof(uint32)); + sendctx->done = true; + + return NULL; +} + /* -------------------------------- * pq_puttextmessage - generate a character set-converted message in one step diff --git a/src/backend/replication/logical/proto.c b/src/backend/replication/logical/proto.c index 86ad97cd937..bd2343ef49a 100644 --- a/src/backend/replication/logical/proto.c +++ b/src/backend/replication/logical/proto.c @@ -833,15 +833,11 @@ logicalrep_write_tuple(StringInfo out, Relation rel, TupleTableSlot *slot, */ if (binary && OidIsValid(typclass->typsend)) { - bytea *outputbytes; - int len; + FmgrInfo flinfo; pq_sendbyte(out, LOGICALREP_COLUMN_BINARY); - outputbytes = OidSendFunctionCall(typclass->typsend, values[i]); - len = VARSIZE(outputbytes) - VARHDRSZ; - pq_sendint(out, len, 4); /* length */ - pq_sendbytes(out, VARDATA(outputbytes), len); /* data */ - pfree(outputbytes); + fmgr_info(typclass->typsend, &flinfo); + SendFunctionCallInto(&flinfo, values[i], out); } else { diff --git a/src/backend/utils/adt/array_userfuncs.c b/src/backend/utils/adt/array_userfuncs.c index ae2cde19c43..ae67f571db3 100644 --- a/src/backend/utils/adt/array_userfuncs.c +++ b/src/backend/utils/adt/array_userfuncs.c @@ -771,15 +771,9 @@ array_agg_serialize(PG_FUNCTION_ARGS) for (i = 0; i < state->nelems; i++) { - bytea *outputbytes; - if (state->dnulls[i]) continue; - outputbytes = SendFunctionCall(&iodata->typsend, - state->dvalues[i]); - pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ); - pq_sendbytes(&buf, VARDATA(outputbytes), - VARSIZE(outputbytes) - VARHDRSZ); + SendFunctionCallInto(&iodata->typsend, state->dvalues[i], &buf); } } diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index c9c2689e77f..3c25a9b5da7 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -1629,15 +1629,7 @@ array_send(PG_FUNCTION_ARGS) pq_sendint32(&buf, -1); } else - { - bytea *outputbytes; - - outputbytes = SendFunctionCall(&my_extra->proc, itemvalue); - pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ); - pq_sendbytes(&buf, VARDATA(outputbytes), - VARSIZE(outputbytes) - VARHDRSZ); - pfree(outputbytes); - } + SendFunctionCallInto(&my_extra->proc, itemvalue, &buf); } PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); diff --git a/src/backend/utils/adt/multirangetypes.c b/src/backend/utils/adt/multirangetypes.c index efd50d16693..d2b31aec0b7 100644 --- a/src/backend/utils/adt/multirangetypes.c +++ b/src/backend/utils/adt/multirangetypes.c @@ -394,13 +394,9 @@ multirange_send(PG_FUNCTION_ARGS) for (int i = 0; i < range_count; i++) { Datum range; - bytea *outputbytes; range = RangeTypePGetDatum(ranges[i]); - outputbytes = SendFunctionCall(&cache->typioproc, range); - - pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ); - pq_sendbytes(&buf, VARDATA(outputbytes), VARSIZE(outputbytes) - VARHDRSZ); + SendFunctionCallInto(&cache->typioproc, range, &buf); } PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); diff --git a/src/backend/utils/adt/rangetypes.c b/src/backend/utils/adt/rangetypes.c index 0ee29ddb056..4629d935c62 100644 --- a/src/backend/utils/adt/rangetypes.c +++ b/src/backend/utils/adt/rangetypes.c @@ -290,24 +290,10 @@ range_send(PG_FUNCTION_ARGS) pq_sendbyte(&buf, flags); if (RANGE_HAS_LBOUND(flags)) - { - bytea *bound = SendFunctionCall(&cache->typioproc, lower.val); - uint32 bound_len = VARSIZE(bound) - VARHDRSZ; - char *bound_data = VARDATA(bound); - - pq_sendint32(&buf, bound_len); - pq_sendbytes(&buf, bound_data, bound_len); - } + SendFunctionCallInto(&cache->typioproc, lower.val, &buf); if (RANGE_HAS_UBOUND(flags)) - { - bytea *bound = SendFunctionCall(&cache->typioproc, upper.val); - uint32 bound_len = VARSIZE(bound) - VARHDRSZ; - char *bound_data = VARDATA(bound); - - pq_sendint32(&buf, bound_len); - pq_sendbytes(&buf, bound_data, bound_len); - } + SendFunctionCallInto(&cache->typioproc, upper.val, &buf); PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } diff --git a/src/backend/utils/adt/rowtypes.c b/src/backend/utils/adt/rowtypes.c index abe2246c47e..e7ca05a3d57 100644 --- a/src/backend/utils/adt/rowtypes.c +++ b/src/backend/utils/adt/rowtypes.c @@ -765,7 +765,6 @@ record_send(PG_FUNCTION_ARGS) ColumnIOData *column_info = &my_extra->columns[i]; Oid column_type = att->atttypid; Datum attr; - bytea *outputbytes; /* Ignore dropped columns in datatype */ if (att->attisdropped) @@ -794,10 +793,7 @@ record_send(PG_FUNCTION_ARGS) } attr = values[i]; - outputbytes = SendFunctionCall(&column_info->proc, attr); - pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ); - pq_sendbytes(&buf, VARDATA(outputbytes), - VARSIZE(outputbytes) - VARHDRSZ); + SendFunctionCallInto(&column_info->proc, attr, &buf); } pfree(values); diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c index b2fd6dbb73d..edbf511aeb3 100644 --- a/src/backend/utils/fmgr/fmgr.c +++ b/src/backend/utils/fmgr/fmgr.c @@ -22,6 +22,7 @@ #include "catalog/pg_type.h" #include "executor/functions.h" #include "lib/stringinfo.h" +#include "libpq/pqformat.h" #include "miscadmin.h" #include "nodes/makefuncs.h" #include "nodes/miscnodes.h" @@ -1747,6 +1748,53 @@ SendFunctionCall(FmgrInfo *flinfo, Datum val) return DatumGetByteaP(FunctionCall1(flinfo, val)); } +/* + * Call a previously-looked-up datatype binary-output function, appending the + * value to buf as a length word in network byte order followed by the data. + * + * A send function that uses pq_begintypsend_fcinfo() writes the value into + * buf directly. The result of any other send function is copied there. + * + * Do not call this on NULL datums. + */ +void +SendFunctionCallInto(FmgrInfo *flinfo, Datum val, StringInfo buf) +{ + LOCAL_FCINFO(fcinfo, 1); + SendBufferContext sendctx; + Datum result; + bytea *outputbytes; + + sendctx.type = T_SendBufferContext; + sendctx.buf = buf; + sendctx.lenpos = -1; + sendctx.done = false; + + InitFunctionCallInfoData(*fcinfo, flinfo, 1, InvalidOid, + (Node *) &sendctx, NULL); + + fcinfo->args[0].value = val; + fcinfo->args[0].isnull = false; + + result = FunctionCallInvoke(fcinfo); + + if (sendctx.lenpos >= 0) + { + if (!sendctx.done) + elog(ERROR, "send function %u did not finish its output", + flinfo->fn_oid); + return; + } + + if (fcinfo->isnull) + elog(ERROR, "function %u returned NULL", flinfo->fn_oid); + + outputbytes = DatumGetByteaP(result); + pq_sendint32(buf, VARSIZE(outputbytes) - VARHDRSZ); + pq_sendbytes(buf, VARDATA(outputbytes), VARSIZE(outputbytes) - VARHDRSZ); + pfree(outputbytes); +} + /* * As above, for I/O functions identified by OID. These are only to be used * in seldom-executed code paths. They are not only slow but leak memory. diff --git a/src/include/fmgr.h b/src/include/fmgr.h index b5a95e7507a..49cc7f83220 100644 --- a/src/include/fmgr.h +++ b/src/include/fmgr.h @@ -784,6 +784,7 @@ extern Datum ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf, extern Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod); extern bytea *SendFunctionCall(FmgrInfo *flinfo, Datum val); +extern void SendFunctionCallInto(FmgrInfo *flinfo, Datum val, StringInfo buf); extern bytea *OidSendFunctionCall(Oid functionId, Datum val); diff --git a/src/include/libpq/pqformat.h b/src/include/libpq/pqformat.h index bc4ab1381a9..b6be44a8174 100644 --- a/src/include/libpq/pqformat.h +++ b/src/include/libpq/pqformat.h @@ -13,6 +13,7 @@ #ifndef PQFORMAT_H #define PQFORMAT_H +#include "fmgr.h" #include "lib/stringinfo.h" #include "mb/pg_wchar.h" #include "port/pg_bswap.h" @@ -190,6 +191,8 @@ pq_sendint(StringInfo buf, uint32 i, int b) extern void pq_begintypsend(StringInfo buf); extern bytea *pq_endtypsend(StringInfo buf); +extern StringInfo pq_begintypsend_fcinfo(FunctionCallInfo fcinfo); +extern bytea *pq_endtypsend_fcinfo(FunctionCallInfo fcinfo, StringInfo buf); extern void pq_puttextmessage(char msgtype, const char *str); extern void pq_putemptymessage(char msgtype); diff --git a/src/include/nodes/miscnodes.h b/src/include/nodes/miscnodes.h index ec833001ab0..6f62463d69c 100644 --- a/src/include/nodes/miscnodes.h +++ b/src/include/nodes/miscnodes.h @@ -54,4 +54,22 @@ typedef struct ErrorSaveContext ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \ ((ErrorSaveContext *) (escontext))->error_occurred) +/* + * SendBufferContext - + * function call context node for sending a value into a caller's buffer + * + * SendFunctionCallInto() passes one of these to a datatype's send function + * via the FunctionCallInfo.context field. A send function that starts its + * output with pq_begintypsend_fcinfo() then writes into buf directly instead + * of returning a separately allocated bytea. + */ +typedef struct SendBufferContext +{ + NodeTag type; + struct StringInfoData *buf; /* buffer to append the value to */ + int lenpos; /* offset of the value's length word in buf, + * or -1 if the send function has not used buf */ + bool done; /* has pq_endtypsend_fcinfo() been called? */ +} SendBufferContext; + #endif /* MISCNODES_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb469266..6e7873a6a10 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2806,6 +2806,7 @@ Selectivity SelfJoinCandidate SemTPadded SemiAntiJoinFactors +SendBufferContext SeqScan SeqScanInstrumentation SeqScanState -- 2.47.3