PostgreSQL Source Code  git master
printtup.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * printtup.c
4  * Routines to print out tuples to the destination (both frontend
5  * clients and standalone backends are supported here).
6  *
7  *
8  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
9  * Portions Copyright (c) 1994, Regents of the University of California
10  *
11  * IDENTIFICATION
12  * src/backend/access/common/printtup.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17 
18 #include "access/printtup.h"
19 #include "libpq/pqformat.h"
20 #include "tcop/pquery.h"
21 #include "utils/lsyscache.h"
22 #include "utils/memdebug.h"
23 #include "utils/memutils.h"
24 
25 
26 static void printtup_startup(DestReceiver *self, int operation,
27  TupleDesc typeinfo);
28 static bool printtup(TupleTableSlot *slot, DestReceiver *self);
29 static void printtup_shutdown(DestReceiver *self);
30 static void printtup_destroy(DestReceiver *self);
31 
32 /* ----------------------------------------------------------------
33  * printtup / debugtup support
34  * ----------------------------------------------------------------
35  */
36 
37 /* ----------------
38  * Private state for a printtup destination object
39  *
40  * NOTE: finfo is the lookup info for either typoutput or typsend, whichever
41  * we are using for this column.
42  * ----------------
43  */
44 typedef struct
45 { /* Per-attribute information */
46  Oid typoutput; /* Oid for the type's text output fn */
47  Oid typsend; /* Oid for the type's binary output fn */
48  bool typisvarlena; /* is it varlena (ie possibly toastable)? */
49  int16 format; /* format code for this column */
50  FmgrInfo finfo; /* Precomputed call info for output fn */
52 
53 typedef struct
54 {
55  DestReceiver pub; /* publicly-known function pointers */
56  Portal portal; /* the Portal we are printing from */
57  bool sendDescrip; /* send RowDescription at startup? */
58  TupleDesc attrinfo; /* The attr info we are set up for */
59  int nattrs;
60  PrinttupAttrInfo *myinfo; /* Cached info about each attr */
61  StringInfoData buf; /* output buffer (*not* in tmpcontext) */
62  MemoryContext tmpcontext; /* Memory context for per-row workspace */
63 } DR_printtup;
64 
65 /* ----------------
66  * Initialize: create a DestReceiver for printtup
67  * ----------------
68  */
71 {
72  DR_printtup *self = (DR_printtup *) palloc0(sizeof(DR_printtup));
73 
74  self->pub.receiveSlot = printtup; /* might get changed later */
75  self->pub.rStartup = printtup_startup;
76  self->pub.rShutdown = printtup_shutdown;
77  self->pub.rDestroy = printtup_destroy;
78  self->pub.mydest = dest;
79 
80  /*
81  * Send T message automatically if DestRemote, but not if
82  * DestRemoteExecute
83  */
84  self->sendDescrip = (dest == DestRemote);
85 
86  self->attrinfo = NULL;
87  self->nattrs = 0;
88  self->myinfo = NULL;
89  self->buf.data = NULL;
90  self->tmpcontext = NULL;
91 
92  return (DestReceiver *) self;
93 }
94 
95 /*
96  * Set parameters for a DestRemote (or DestRemoteExecute) receiver
97  */
98 void
100 {
101  DR_printtup *myState = (DR_printtup *) self;
102 
103  Assert(myState->pub.mydest == DestRemote ||
104  myState->pub.mydest == DestRemoteExecute);
105 
106  myState->portal = portal;
107 }
108 
109 static void
110 printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
111 {
112  DR_printtup *myState = (DR_printtup *) self;
113  Portal portal = myState->portal;
114 
115  /*
116  * Create I/O buffer to be used for all messages. This cannot be inside
117  * tmpcontext, since we want to re-use it across rows.
118  */
119  initStringInfo(&myState->buf);
120 
121  /*
122  * Create a temporary memory context that we can reset once per row to
123  * recover palloc'd memory. This avoids any problems with leaks inside
124  * datatype output routines, and should be faster than retail pfree's
125  * anyway.
126  */
128  "printtup",
130 
131  /*
132  * If we are supposed to emit row descriptions, then send the tuple
133  * descriptor of the tuples.
134  */
135  if (myState->sendDescrip)
136  SendRowDescriptionMessage(&myState->buf,
137  typeinfo,
138  FetchPortalTargetList(portal),
139  portal->formats);
140 
141  /* ----------------
142  * We could set up the derived attr info at this time, but we postpone it
143  * until the first call of printtup, for 2 reasons:
144  * 1. We don't waste time (compared to the old way) if there are no
145  * tuples at all to output.
146  * 2. Checking in printtup allows us to handle the case that the tuples
147  * change type midway through (although this probably can't happen in
148  * the current executor).
149  * ----------------
150  */
151 }
152 
153 /*
154  * SendRowDescriptionMessage --- send a RowDescription message to the frontend
155  *
156  * Notes: the TupleDesc has typically been manufactured by ExecTypeFromTL()
157  * or some similar function; it does not contain a full set of fields.
158  * The targetlist will be NIL when executing a utility function that does
159  * not have a plan. If the targetlist isn't NIL then it is a Query node's
160  * targetlist; it is up to us to ignore resjunk columns in it. The formats[]
161  * array pointer might be NULL (if we are doing Describe on a prepared stmt);
162  * send zeroes for the format codes in that case.
163  */
164 void
166  List *targetlist, int16 *formats)
167 {
168  int natts = typeinfo->natts;
169  int i;
170  ListCell *tlist_item = list_head(targetlist);
171 
172  /* tuple descriptor message type */
174  /* # of attrs in tuples */
175  pq_sendint16(buf, natts);
176 
177  /*
178  * Preallocate memory for the entire message to be sent. That allows to
179  * use the significantly faster inline pqformat.h functions and to avoid
180  * reallocations.
181  *
182  * Have to overestimate the size of the column-names, to account for
183  * character set overhead.
184  */
186  + sizeof(Oid) /* resorigtbl */
187  + sizeof(AttrNumber) /* resorigcol */
188  + sizeof(Oid) /* atttypid */
189  + sizeof(int16) /* attlen */
190  + sizeof(int32) /* attypmod */
191  + sizeof(int16) /* format */
192  ) * natts);
193 
194  for (i = 0; i < natts; ++i)
195  {
196  Form_pg_attribute att = TupleDescAttr(typeinfo, i);
197  Oid atttypid = att->atttypid;
198  int32 atttypmod = att->atttypmod;
199  Oid resorigtbl;
200  AttrNumber resorigcol;
201  int16 format;
202 
203  /*
204  * If column is a domain, send the base type and typmod instead.
205  * Lookup before sending any ints, for efficiency.
206  */
207  atttypid = getBaseTypeAndTypmod(atttypid, &atttypmod);
208 
209  /* Do we have a non-resjunk tlist item? */
210  while (tlist_item &&
211  ((TargetEntry *) lfirst(tlist_item))->resjunk)
212  tlist_item = lnext(targetlist, tlist_item);
213  if (tlist_item)
214  {
215  TargetEntry *tle = (TargetEntry *) lfirst(tlist_item);
216 
217  resorigtbl = tle->resorigtbl;
218  resorigcol = tle->resorigcol;
219  tlist_item = lnext(targetlist, tlist_item);
220  }
221  else
222  {
223  /* No info available, so send zeroes */
224  resorigtbl = 0;
225  resorigcol = 0;
226  }
227 
228  if (formats)
229  format = formats[i];
230  else
231  format = 0;
232 
233  pq_writestring(buf, NameStr(att->attname));
234  pq_writeint32(buf, resorigtbl);
235  pq_writeint16(buf, resorigcol);
236  pq_writeint32(buf, atttypid);
237  pq_writeint16(buf, att->attlen);
238  pq_writeint32(buf, atttypmod);
240  }
241 
243 }
244 
245 /*
246  * Get the lookup info that printtup() needs
247  */
248 static void
249 printtup_prepare_info(DR_printtup *myState, TupleDesc typeinfo, int numAttrs)
250 {
251  int16 *formats = myState->portal->formats;
252  int i;
253 
254  /* get rid of any old data */
255  if (myState->myinfo)
256  pfree(myState->myinfo);
257  myState->myinfo = NULL;
258 
259  myState->attrinfo = typeinfo;
260  myState->nattrs = numAttrs;
261  if (numAttrs <= 0)
262  return;
263 
264  myState->myinfo = (PrinttupAttrInfo *)
265  palloc0(numAttrs * sizeof(PrinttupAttrInfo));
266 
267  for (i = 0; i < numAttrs; i++)
268  {
269  PrinttupAttrInfo *thisState = myState->myinfo + i;
270  int16 format = (formats ? formats[i] : 0);
271  Form_pg_attribute attr = TupleDescAttr(typeinfo, i);
272 
273  thisState->format = format;
274  if (format == 0)
275  {
276  getTypeOutputInfo(attr->atttypid,
277  &thisState->typoutput,
278  &thisState->typisvarlena);
279  fmgr_info(thisState->typoutput, &thisState->finfo);
280  }
281  else if (format == 1)
282  {
283  getTypeBinaryOutputInfo(attr->atttypid,
284  &thisState->typsend,
285  &thisState->typisvarlena);
286  fmgr_info(thisState->typsend, &thisState->finfo);
287  }
288  else
289  ereport(ERROR,
290  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
291  errmsg("unsupported format code: %d", format)));
292  }
293 }
294 
295 /* ----------------
296  * printtup --- send a tuple to the client
297  *
298  * Note: if you change this function, see also serializeAnalyzeReceive
299  * in explain.c, which is meant to replicate the computations done here.
300  * ----------------
301  */
302 static bool
304 {
305  TupleDesc typeinfo = slot->tts_tupleDescriptor;
306  DR_printtup *myState = (DR_printtup *) self;
307  MemoryContext oldcontext;
308  StringInfo buf = &myState->buf;
309  int natts = typeinfo->natts;
310  int i;
311 
312  /* Set or update my derived attribute info, if needed */
313  if (myState->attrinfo != typeinfo || myState->nattrs != natts)
314  printtup_prepare_info(myState, typeinfo, natts);
315 
316  /* Make sure the tuple is fully deconstructed */
317  slot_getallattrs(slot);
318 
319  /* Switch into per-row context so we can recover memory below */
320  oldcontext = MemoryContextSwitchTo(myState->tmpcontext);
321 
322  /*
323  * Prepare a DataRow message (note buffer is in per-query context)
324  */
326 
327  pq_sendint16(buf, natts);
328 
329  /*
330  * send the attributes of this tuple
331  */
332  for (i = 0; i < natts; ++i)
333  {
334  PrinttupAttrInfo *thisState = myState->myinfo + i;
335  Datum attr = slot->tts_values[i];
336 
337  if (slot->tts_isnull[i])
338  {
339  pq_sendint32(buf, -1);
340  continue;
341  }
342 
343  /*
344  * Here we catch undefined bytes in datums that are returned to the
345  * client without hitting disk; see comments at the related check in
346  * PageAddItem(). This test is most useful for uncompressed,
347  * non-external datums, but we're quite likely to see such here when
348  * testing new C functions.
349  */
350  if (thisState->typisvarlena)
352  VARSIZE_ANY(attr));
353 
354  if (thisState->format == 0)
355  {
356  /* Text output */
357  char *outputstr;
358 
359  outputstr = OutputFunctionCall(&thisState->finfo, attr);
360  pq_sendcountedtext(buf, outputstr, strlen(outputstr));
361  }
362  else
363  {
364  /* Binary output */
365  bytea *outputbytes;
366 
367  outputbytes = SendFunctionCall(&thisState->finfo, attr);
368  pq_sendint32(buf, VARSIZE(outputbytes) - VARHDRSZ);
369  pq_sendbytes(buf, VARDATA(outputbytes),
370  VARSIZE(outputbytes) - VARHDRSZ);
371  }
372  }
373 
375 
376  /* Return to caller's context, and flush row's temporary memory */
377  MemoryContextSwitchTo(oldcontext);
378  MemoryContextReset(myState->tmpcontext);
379 
380  return true;
381 }
382 
383 /* ----------------
384  * printtup_shutdown
385  * ----------------
386  */
387 static void
389 {
390  DR_printtup *myState = (DR_printtup *) self;
391 
392  if (myState->myinfo)
393  pfree(myState->myinfo);
394  myState->myinfo = NULL;
395 
396  myState->attrinfo = NULL;
397 
398  if (myState->buf.data)
399  pfree(myState->buf.data);
400  myState->buf.data = NULL;
401 
402  if (myState->tmpcontext)
404  myState->tmpcontext = NULL;
405 }
406 
407 /* ----------------
408  * printtup_destroy
409  * ----------------
410  */
411 static void
413 {
414  pfree(self);
415 }
416 
417 /* ----------------
418  * printatt
419  * ----------------
420  */
421 static void
422 printatt(unsigned attributeId,
423  Form_pg_attribute attributeP,
424  char *value)
425 {
426  printf("\t%2d: %s%s%s%s\t(typeid = %u, len = %d, typmod = %d, byval = %c)\n",
427  attributeId,
428  NameStr(attributeP->attname),
429  value != NULL ? " = \"" : "",
430  value != NULL ? value : "",
431  value != NULL ? "\"" : "",
432  (unsigned int) (attributeP->atttypid),
433  attributeP->attlen,
434  attributeP->atttypmod,
435  attributeP->attbyval ? 't' : 'f');
436 }
437 
438 /* ----------------
439  * debugStartup - prepare to print tuples for an interactive backend
440  * ----------------
441  */
442 void
443 debugStartup(DestReceiver *self, int operation, TupleDesc typeinfo)
444 {
445  int natts = typeinfo->natts;
446  int i;
447 
448  /*
449  * show the return type of the tuples
450  */
451  for (i = 0; i < natts; ++i)
452  printatt((unsigned) i + 1, TupleDescAttr(typeinfo, i), NULL);
453  printf("\t----\n");
454 }
455 
456 /* ----------------
457  * debugtup - print one tuple for an interactive backend
458  * ----------------
459  */
460 bool
462 {
463  TupleDesc typeinfo = slot->tts_tupleDescriptor;
464  int natts = typeinfo->natts;
465  int i;
466  Datum attr;
467  char *value;
468  bool isnull;
469  Oid typoutput;
470  bool typisvarlena;
471 
472  for (i = 0; i < natts; ++i)
473  {
474  attr = slot_getattr(slot, i + 1, &isnull);
475  if (isnull)
476  continue;
477  getTypeOutputInfo(TupleDescAttr(typeinfo, i)->atttypid,
478  &typoutput, &typisvarlena);
479 
480  value = OidOutputFunctionCall(typoutput, attr);
481 
482  printatt((unsigned) i + 1, TupleDescAttr(typeinfo, i), value);
483  }
484  printf("\t----\n");
485 
486  return true;
487 }
int16 AttrNumber
Definition: attnum.h:21
#define NameStr(name)
Definition: c.h:746
signed short int16
Definition: c.h:493
signed int int32
Definition: c.h:494
#define VARHDRSZ
Definition: c.h:692
#define Assert(condition)
Definition: c.h:858
CommandDest
Definition: dest.h:86
@ DestRemote
Definition: dest.h:89
@ DestRemoteExecute
Definition: dest.h:90
int errcode(int sqlerrcode)
Definition: elog.c:855
int errmsg(const char *fmt,...)
Definition: elog.c:1068
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1744
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1683
static struct @155 value
int i
Definition: isn.c:73
void getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
Definition: lsyscache.c:2973
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2538
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc0(Size size)
Definition: mcxt.c:1347
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define VALGRIND_CHECK_MEM_IS_DEFINED(addr, size)
Definition: memdebug.h:23
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static char format
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
static char * buf
Definition: pg_test_fsync.c:73
#define MAX_CONVERSION_GROWTH
Definition: pg_wchar.h:302
#define printf(...)
Definition: port.h:244
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
unsigned int Oid
Definition: postgres_ext.h:31
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition: pqformat.c:126
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition: pqformat.c:109
void pq_endmessage_reuse(StringInfo buf)
Definition: pqformat.c:314
void pq_sendcountedtext(StringInfo buf, const char *str, int slen)
Definition: pqformat.c:142
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:144
static void pq_writestring(StringInfoData *pg_restrict buf, const char *pg_restrict str)
Definition: pqformat.h:108
static void pq_writeint32(StringInfoData *pg_restrict buf, uint32 i)
Definition: pqformat.h:74
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:136
static void pq_writeint16(StringInfoData *pg_restrict buf, uint16 i)
Definition: pqformat.h:60
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:326
bool debugtup(TupleTableSlot *slot, DestReceiver *self)
Definition: printtup.c:461
static void printatt(unsigned attributeId, Form_pg_attribute attributeP, char *value)
Definition: printtup.c:422
void debugStartup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: printtup.c:443
static void printtup_prepare_info(DR_printtup *myState, TupleDesc typeinfo, int numAttrs)
Definition: printtup.c:249
static bool printtup(TupleTableSlot *slot, DestReceiver *self)
Definition: printtup.c:303
static void printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: printtup.c:110
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:99
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:165
static void printtup_destroy(DestReceiver *self)
Definition: printtup.c:412
DestReceiver * printtup_create_DR(CommandDest dest)
Definition: printtup.c:70
static void printtup_shutdown(DestReceiver *self)
Definition: printtup.c:388
MemoryContextSwitchTo(old_ctx)
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:289
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
PrinttupAttrInfo * myinfo
Definition: printtup.c:60
StringInfoData buf
Definition: printtup.c:61
int nattrs
Definition: printtup.c:59
DestReceiver pub
Definition: printtup.c:55
bool sendDescrip
Definition: printtup.c:57
Portal portal
Definition: printtup.c:56
MemoryContext tmpcontext
Definition: printtup.c:62
TupleDesc attrinfo
Definition: printtup.c:58
Definition: fmgr.h:57
Definition: pg_list.h:54
int16 * formats
Definition: portal.h:162
bool typisvarlena
Definition: printtup.c:48
FmgrInfo finfo
Definition: printtup.c:50
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
CommandDest mydest
Definition: dest.h:128
Definition: c.h:687
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:395
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:368
#define VARSIZE_ANY(PTR)
Definition: varatt.h:311
#define VARDATA(PTR)
Definition: varatt.h:278
#define VARSIZE(PTR)
Definition: varatt.h:279