printtup.c 16.3 KB
Newer Older
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
 *
P
 
PostgreSQL Daemon 已提交
8
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
9
 * Portions Copyright (c) 1994, Regents of the University of California
10 11
 *
 * IDENTIFICATION
12
 *	  $PostgreSQL: pgsql/src/backend/access/common/printtup.c,v 1.93 2005/11/03 17:11:30 alvherre Exp $
13 14 15
 *
 *-------------------------------------------------------------------------
 */
16 17 18 19
#include "postgres.h"

#include "access/heapam.h"
#include "access/printtup.h"
20
#include "libpq/libpq.h"
21
#include "libpq/pqformat.h"
22
#include "tcop/pquery.h"
23
#include "utils/lsyscache.h"
24
#include "utils/portal.h"
25

M
Marc G. Fournier 已提交
26

27
static void printtup_startup(DestReceiver *self, int operation,
B
Bruce Momjian 已提交
28
				 TupleDesc typeinfo);
29 30 31
static void printtup(TupleTableSlot *slot, DestReceiver *self);
static void printtup_20(TupleTableSlot *slot, DestReceiver *self);
static void printtup_internal_20(TupleTableSlot *slot, DestReceiver *self);
32 33 34
static void printtup_shutdown(DestReceiver *self);
static void printtup_destroy(DestReceiver *self);

35

36
/* ----------------------------------------------------------------
37
 *		printtup / debugtup support
38 39 40
 * ----------------------------------------------------------------
 */

41 42
/* ----------------
 *		Private state for a printtup destination object
43 44 45
 *
 * NOTE: finfo is the lookup info for either typoutput or typsend, whichever
 * we are using for this column.
46 47
 * ----------------
 */
B
Bruce Momjian 已提交
48 49
typedef struct
{								/* Per-attribute information */
50 51
	Oid			typoutput;		/* Oid for the type's text output fn */
	Oid			typsend;		/* Oid for the type's binary output fn */
52
	bool		typisvarlena;	/* is it varlena (ie possibly toastable)? */
53 54
	int16		format;			/* format code for this column */
	FmgrInfo	finfo;			/* Precomputed call info for output fn */
55
} PrinttupAttrInfo;
56

B
Bruce Momjian 已提交
57 58 59
typedef struct
{
	DestReceiver pub;			/* publicly-known function pointers */
60
	Portal		portal;			/* the Portal we are printing from */
61
	bool		sendDescrip;	/* send RowDescription at startup? */
B
Bruce Momjian 已提交
62 63 64
	TupleDesc	attrinfo;		/* The attr info we are set up for */
	int			nattrs;
	PrinttupAttrInfo *myinfo;	/* Cached info about each attr */
65
} DR_printtup;
66 67 68 69 70

/* ----------------
 *		Initialize: create a DestReceiver for printtup
 * ----------------
 */
B
Bruce Momjian 已提交
71
DestReceiver *
72
printtup_create_DR(CommandDest dest, Portal portal)
73
{
B
Bruce Momjian 已提交
74
	DR_printtup *self = (DR_printtup *) palloc(sizeof(DR_printtup));
75

76
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
77
		self->pub.receiveSlot = printtup;
78
	else
79
	{
80
		/*
B
Bruce Momjian 已提交
81 82 83
		 * In protocol 2.0 the Bind message does not exist, so there is no way
		 * for the columns to have different print formats; it's sufficient to
		 * look at the first one.
84 85
		 */
		if (portal->formats && portal->formats[0] != 0)
86
			self->pub.receiveSlot = printtup_internal_20;
87
		else
88
			self->pub.receiveSlot = printtup_20;
89
	}
90 91 92
	self->pub.rStartup = printtup_startup;
	self->pub.rShutdown = printtup_shutdown;
	self->pub.rDestroy = printtup_destroy;
93
	self->pub.mydest = dest;
94

95 96
	self->portal = portal;

97 98 99 100 101
	/*
	 * Send T message automatically if DestRemote, but not if
	 * DestRemoteExecute
	 */
	self->sendDescrip = (dest == DestRemote);
102

103 104 105 106
	self->attrinfo = NULL;
	self->nattrs = 0;
	self->myinfo = NULL;

B
Bruce Momjian 已提交
107
	return (DestReceiver *) self;
108 109 110
}

static void
111
printtup_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
112
{
113
	DR_printtup *myState = (DR_printtup *) self;
B
Bruce Momjian 已提交
114
	Portal		portal = myState->portal;
115

116 117 118
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
	{
		/*
B
Bruce Momjian 已提交
119
		 * Send portal name to frontend (obsolete cruft, gone in proto 3.0)
120 121 122
		 *
		 * If portal name not specified, use "blank" portal.
		 */
123 124 125
		const char *portalName = portal->name;

		if (portalName == NULL || portalName[0] == '\0')
126 127 128 129
			portalName = "blank";

		pq_puttextmessage('P', portalName);
	}
130 131

	/*
B
Bruce Momjian 已提交
132 133
	 * If this is a retrieve, and we are supposed to emit row descriptions,
	 * then we send back the tuple descriptor of the tuples.
134
	 */
135
	if (operation == CMD_SELECT && myState->sendDescrip)
136 137 138
		SendRowDescriptionMessage(typeinfo,
								  FetchPortalTargetList(portal),
								  portal->formats);
139

140 141
	/* ----------------
	 * We could set up the derived attr info at this time, but we postpone it
142
	 * until the first call of printtup, for 2 reasons:
143
	 * 1. We don't waste time (compared to the old way) if there are no
B
Bruce Momjian 已提交
144
	 *	  tuples at all to output.
145
	 * 2. Checking in printtup allows us to handle the case that the tuples
B
Bruce Momjian 已提交
146 147
	 *	  change type midway through (although this probably can't happen in
	 *	  the current executor).
148 149 150 151
	 * ----------------
	 */
}

152 153
/*
 * SendRowDescriptionMessage --- send a RowDescription message to the frontend
154 155 156 157
 *
 * Notes: the TupleDesc has typically been manufactured by ExecTypeFromTL()
 * or some similar function; it does not contain a full set of fields.
 * The targetlist will be NIL when executing a utility function that does
158
 * not have a plan.  If the targetlist isn't NIL then it is a Query node's
B
Bruce Momjian 已提交
159
 * targetlist; it is up to us to ignore resjunk columns in it.	The formats[]
160 161
 * array pointer might be NULL (if we are doing Describe on a prepared stmt);
 * send zeroes for the format codes in that case.
162 163
 */
void
164
SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
165 166 167 168 169 170
{
	Form_pg_attribute *attrs = typeinfo->attrs;
	int			natts = typeinfo->natts;
	int			proto = PG_PROTOCOL_MAJOR(FrontendProtocol);
	int			i;
	StringInfoData buf;
171
	ListCell   *tlist_item = list_head(targetlist);
172

B
Bruce Momjian 已提交
173 174
	pq_beginmessage(&buf, 'T'); /* tuple descriptor message type */
	pq_sendint(&buf, natts, 2); /* # of attrs in tuples */
175 176 177

	for (i = 0; i < natts; ++i)
	{
B
Bruce Momjian 已提交
178 179 180
		Oid			atttypid = attrs[i]->atttypid;
		int32		atttypmod = attrs[i]->atttypmod;
		Oid			basetype;
181

182 183 184 185
		pq_sendstring(&buf, NameStr(attrs[i]->attname));
		/* column ID info appears in protocol 3.0 and up */
		if (proto >= 3)
		{
186
			/* Do we have a non-resjunk tlist item? */
187
			while (tlist_item &&
188
				   ((TargetEntry *) lfirst(tlist_item))->resjunk)
189 190
				tlist_item = lnext(tlist_item);
			if (tlist_item)
191
			{
192
				TargetEntry *tle = (TargetEntry *) lfirst(tlist_item);
193

194 195
				pq_sendint(&buf, tle->resorigtbl, 4);
				pq_sendint(&buf, tle->resorigcol, 2);
196
				tlist_item = lnext(tlist_item);
197 198 199 200 201 202 203
			}
			else
			{
				/* No info available, so send zeroes */
				pq_sendint(&buf, 0, 4);
				pq_sendint(&buf, 0, 2);
			}
204
		}
205 206 207 208 209 210 211 212 213
		/* If column is a domain, send the base type and typmod instead */
		basetype = getBaseType(atttypid);
		if (basetype != atttypid)
		{
			atttypmod = get_typtypmod(atttypid);
			atttypid = basetype;
		}
		pq_sendint(&buf, (int) atttypid, sizeof(atttypid));
		pq_sendint(&buf, attrs[i]->attlen, sizeof(attrs[i]->attlen));
214 215
		/* typmod appears in protocol 2.0 and up */
		if (proto >= 2)
216
			pq_sendint(&buf, atttypmod, sizeof(atttypmod));
217 218 219 220 221 222 223 224
		/* format info appears in protocol 3.0 and up */
		if (proto >= 3)
		{
			if (formats)
				pq_sendint(&buf, formats[i], 2);
			else
				pq_sendint(&buf, 0, 2);
		}
225 226 227 228
	}
	pq_endmessage(&buf);
}

229 230 231
/*
 * Get the lookup info that printtup() needs
 */
232
static void
233
printtup_prepare_info(DR_printtup *myState, TupleDesc typeinfo, int numAttrs)
234
{
235
	int16	   *formats = myState->portal->formats;
B
Bruce Momjian 已提交
236
	int			i;
237

238
	/* get rid of any old data */
239
	if (myState->myinfo)
240
		pfree(myState->myinfo);
241
	myState->myinfo = NULL;
242

243 244 245 246
	myState->attrinfo = typeinfo;
	myState->nattrs = numAttrs;
	if (numAttrs <= 0)
		return;
247

B
Bruce Momjian 已提交
248
	myState->myinfo = (PrinttupAttrInfo *)
249
		palloc0(numAttrs * sizeof(PrinttupAttrInfo));
250

251 252
	for (i = 0; i < numAttrs; i++)
	{
B
Bruce Momjian 已提交
253
		PrinttupAttrInfo *thisState = myState->myinfo + i;
254
		int16		format = (formats ? formats[i] : 0);
B
Bruce Momjian 已提交
255

256 257 258 259 260 261
		thisState->format = format;
		if (format == 0)
		{
			getTypeOutputInfo(typeinfo->attrs[i]->atttypid,
							  &thisState->typoutput,
							  &thisState->typisvarlena);
262
			fmgr_info(thisState->typoutput, &thisState->finfo);
263 264 265 266 267 268 269 270 271
		}
		else if (format == 1)
		{
			getTypeBinaryOutputInfo(typeinfo->attrs[i]->atttypid,
									&thisState->typsend,
									&thisState->typisvarlena);
			fmgr_info(thisState->typsend, &thisState->finfo);
		}
		else
272 273 274
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("unsupported format code: %d", format)));
275 276 277
	}
}

278
/* ----------------
279
 *		printtup --- print a tuple in protocol 3.0
280 281
 * ----------------
 */
282
static void
283
printtup(TupleTableSlot *slot, DestReceiver *self)
284
{
B
Bruce Momjian 已提交
285
	TupleDesc	typeinfo = slot->tts_tupleDescriptor;
286 287
	DR_printtup *myState = (DR_printtup *) self;
	StringInfoData buf;
288
	int			natts = typeinfo->natts;
289 290 291 292 293 294
	int			i;

	/* Set or update my derived attribute info, if needed */
	if (myState->attrinfo != typeinfo || myState->nattrs != natts)
		printtup_prepare_info(myState, typeinfo, natts);

295 296
	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);
297

298 299 300 301 302 303 304 305 306 307 308 309 310
	/*
	 * Prepare a DataRow message
	 */
	pq_beginmessage(&buf, 'D');

	pq_sendint(&buf, natts, 2);

	/*
	 * send the attributes of this tuple
	 */
	for (i = 0; i < natts; ++i)
	{
		PrinttupAttrInfo *thisState = myState->myinfo + i;
311
		Datum		origattr = slot->tts_values[i],
312 313
					attr;

314
		if (slot->tts_isnull[i])
315 316 317 318 319
		{
			pq_sendint(&buf, -1, 4);
			continue;
		}

320
		/*
B
Bruce Momjian 已提交
321 322
		 * If we have a toasted datum, forcibly detoast it here to avoid
		 * memory leakage inside the type's output routine.
323 324 325 326 327
		 */
		if (thisState->typisvarlena)
			attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
		else
			attr = origattr;
328

329
		if (thisState->format == 0)
330
		{
331 332 333
			/* Text output */
			char	   *outputstr;

334 335
			outputstr = DatumGetCString(FunctionCall1(&thisState->finfo,
													  attr));
336 337
			pq_sendcountedtext(&buf, outputstr, strlen(outputstr), false);
			pfree(outputstr);
338 339 340
		}
		else
		{
341 342 343
			/* Binary output */
			bytea	   *outputbytes;

344 345
			outputbytes = DatumGetByteaP(FunctionCall1(&thisState->finfo,
													   attr));
346 347 348 349 350
			/* We assume the result will not have been toasted */
			pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4);
			pq_sendbytes(&buf, VARDATA(outputbytes),
						 VARSIZE(outputbytes) - VARHDRSZ);
			pfree(outputbytes);
351
		}
352 353 354 355

		/* Clean up detoasted copy, if any */
		if (attr != origattr)
			pfree(DatumGetPointer(attr));
356 357 358 359 360 361 362 363 364 365
	}

	pq_endmessage(&buf);
}

/* ----------------
 *		printtup_20 --- print a tuple in protocol 2.0
 * ----------------
 */
static void
366
printtup_20(TupleTableSlot *slot, DestReceiver *self)
367
{
B
Bruce Momjian 已提交
368
	TupleDesc	typeinfo = slot->tts_tupleDescriptor;
B
Bruce Momjian 已提交
369
	DR_printtup *myState = (DR_printtup *) self;
370
	StringInfoData buf;
371
	int			natts = typeinfo->natts;
372 373
	int			i,
				j,
374
				k;
375

376
	/* Set or update my derived attribute info, if needed */
377 378
	if (myState->attrinfo != typeinfo || myState->nattrs != natts)
		printtup_prepare_info(myState, typeinfo, natts);
379

380 381
	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);
382

383 384
	/*
	 * tell the frontend to expect new tuple data (in ASCII style)
385
	 */
386
	pq_beginmessage(&buf, 'D');
387

388 389
	/*
	 * send a bitmap of which attributes are not null
390 391 392
	 */
	j = 0;
	k = 1 << 7;
393
	for (i = 0; i < natts; ++i)
394
	{
395
		if (!slot->tts_isnull[i])
396
			j |= k;				/* set bit if not null */
397
		k >>= 1;
398
		if (k == 0)				/* end of byte? */
399
		{
400
			pq_sendint(&buf, j, 1);
401 402 403
			j = 0;
			k = 1 << 7;
		}
404
	}
405
	if (k != (1 << 7))			/* flush last partial byte */
406
		pq_sendint(&buf, j, 1);
407

408 409
	/*
	 * send the attributes of this tuple
410
	 */
411
	for (i = 0; i < natts; ++i)
412
	{
B
Bruce Momjian 已提交
413
		PrinttupAttrInfo *thisState = myState->myinfo + i;
414
		Datum		origattr = slot->tts_values[i],
415 416
					attr;
		char	   *outputstr;
B
Bruce Momjian 已提交
417

418
		if (slot->tts_isnull[i])
M
 
Marc G. Fournier 已提交
419
			continue;
420

421 422 423
		Assert(thisState->format == 0);

		/*
B
Bruce Momjian 已提交
424 425
		 * If we have a toasted datum, forcibly detoast it here to avoid
		 * memory leakage inside the type's output routine.
426 427 428 429 430 431
		 */
		if (thisState->typisvarlena)
			attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
		else
			attr = origattr;

432 433
		outputstr = DatumGetCString(FunctionCall1(&thisState->finfo,
												  attr));
434 435
		pq_sendcountedtext(&buf, outputstr, strlen(outputstr), true);
		pfree(outputstr);
436

437 438 439
		/* Clean up detoasted copy, if any */
		if (attr != origattr)
			pfree(DatumGetPointer(attr));
440
	}
441 442

	pq_endmessage(&buf);
443 444
}

445
/* ----------------
446
 *		printtup_shutdown
447 448 449
 * ----------------
 */
static void
450
printtup_shutdown(DestReceiver *self)
451
{
B
Bruce Momjian 已提交
452 453
	DR_printtup *myState = (DR_printtup *) self;

454 455
	if (myState->myinfo)
		pfree(myState->myinfo);
456
	myState->myinfo = NULL;
457

458 459 460 461 462 463 464 465 466 467 468
	myState->attrinfo = NULL;
}

/* ----------------
 *		printtup_destroy
 * ----------------
 */
static void
printtup_destroy(DestReceiver *self)
{
	pfree(self);
469 470
}

471
/* ----------------
472
 *		printatt
473 474 475 476
 * ----------------
 */
static void
printatt(unsigned attributeId,
477
		 Form_pg_attribute attributeP,
478
		 char *value)
479
{
B
Bruce Momjian 已提交
480
	printf("\t%2d: %s%s%s%s\t(typeid = %u, len = %d, typmod = %d, byval = %c)\n",
481
		   attributeId,
482
		   NameStr(attributeP->attname),
483 484 485 486 487
		   value != NULL ? " = \"" : "",
		   value != NULL ? value : "",
		   value != NULL ? "\"" : "",
		   (unsigned int) (attributeP->atttypid),
		   attributeP->attlen,
B
Bruce Momjian 已提交
488
		   attributeP->atttypmod,
489
		   attributeP->attbyval ? 't' : 'f');
490 491 492
}

/* ----------------
493
 *		debugStartup - prepare to print tuples for an interactive backend
494 495 496
 * ----------------
 */
void
497
debugStartup(DestReceiver *self, int operation, TupleDesc typeinfo)
498
{
499 500 501 502
	int			natts = typeinfo->natts;
	Form_pg_attribute *attinfo = typeinfo->attrs;
	int			i;

503 504 505
	/*
	 * show the return type of the tuples
	 */
506
	for (i = 0; i < natts; ++i)
507
		printatt((unsigned) i + 1, attinfo[i], NULL);
508
	printf("\t----\n");
509 510 511 512
}

/* ----------------
 *		debugtup - print one tuple for an interactive backend
513 514 515
 * ----------------
 */
void
516
debugtup(TupleTableSlot *slot, DestReceiver *self)
517
{
518
	TupleDesc	typeinfo = slot->tts_tupleDescriptor;
519
	int			natts = typeinfo->natts;
520
	int			i;
521 522
	Datum		origattr,
				attr;
523
	char	   *value;
524
	bool		isnull;
525
	Oid			typoutput;
526
	bool		typisvarlena;
527

528
	for (i = 0; i < natts; ++i)
529
	{
530
		origattr = slot_getattr(slot, i + 1, &isnull);
531 532
		if (isnull)
			continue;
533
		getTypeOutputInfo(typeinfo->attrs[i]->atttypid,
534
						  &typoutput, &typisvarlena);
B
Bruce Momjian 已提交
535

536
		/*
B
Bruce Momjian 已提交
537 538
		 * If we have a toasted datum, forcibly detoast it here to avoid
		 * memory leakage inside the type's output routine.
539 540 541 542 543
		 */
		if (typisvarlena)
			attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
		else
			attr = origattr;
544

545 546
		value = DatumGetCString(OidFunctionCall1(typoutput,
												 attr));
547

548
		printatt((unsigned) i + 1, typeinfo->attrs[i], value);
549

550 551 552 553 554
		pfree(value);

		/* Clean up detoasted copy, if any */
		if (attr != origattr)
			pfree(DatumGetPointer(attr));
555
	}
556
	printf("\t----\n");
557 558 559
}

/* ----------------
560 561 562 563
 *		printtup_internal_20 --- print a binary tuple in protocol 2.0
 *
 * We use a different message type, i.e. 'B' instead of 'D' to
 * indicate a tuple in internal (binary) form.
564
 *
565
 * This is largely same as printtup_20, except we use binary formatting.
566 567
 * ----------------
 */
568
static void
569
printtup_internal_20(TupleTableSlot *slot, DestReceiver *self)
570
{
B
Bruce Momjian 已提交
571
	TupleDesc	typeinfo = slot->tts_tupleDescriptor;
572
	DR_printtup *myState = (DR_printtup *) self;
573
	StringInfoData buf;
574
	int			natts = typeinfo->natts;
575 576 577
	int			i,
				j,
				k;
578 579 580 581

	/* Set or update my derived attribute info, if needed */
	if (myState->attrinfo != typeinfo || myState->nattrs != natts)
		printtup_prepare_info(myState, typeinfo, natts);
582

583 584
	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);
585

586 587
	/*
	 * tell the frontend to expect new tuple data (in binary style)
588
	 */
589
	pq_beginmessage(&buf, 'B');
590

591 592
	/*
	 * send a bitmap of which attributes are not null
593 594 595
	 */
	j = 0;
	k = 1 << 7;
596
	for (i = 0; i < natts; ++i)
597
	{
598
		if (!slot->tts_isnull[i])
599
			j |= k;				/* set bit if not null */
600
		k >>= 1;
601
		if (k == 0)				/* end of byte? */
602
		{
603
			pq_sendint(&buf, j, 1);
604 605 606
			j = 0;
			k = 1 << 7;
		}
607
	}
608
	if (k != (1 << 7))			/* flush last partial byte */
609
		pq_sendint(&buf, j, 1);
610

611 612
	/*
	 * send the attributes of this tuple
613
	 */
614
	for (i = 0; i < natts; ++i)
615
	{
616
		PrinttupAttrInfo *thisState = myState->myinfo + i;
617
		Datum		origattr = slot->tts_values[i],
618
					attr;
619
		bytea	   *outputbytes;
620

621
		if (slot->tts_isnull[i])
622
			continue;
623

624
		Assert(thisState->format == 1);
625

626
		/*
B
Bruce Momjian 已提交
627 628
		 * If we have a toasted datum, forcibly detoast it here to avoid
		 * memory leakage inside the type's output routine.
629 630 631
		 */
		if (thisState->typisvarlena)
			attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
632 633
		else
			attr = origattr;
634

635 636
		outputbytes = DatumGetByteaP(FunctionCall1(&thisState->finfo,
												   attr));
637 638 639 640 641 642 643 644 645
		/* We assume the result will not have been toasted */
		pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4);
		pq_sendbytes(&buf, VARDATA(outputbytes),
					 VARSIZE(outputbytes) - VARHDRSZ);
		pfree(outputbytes);

		/* Clean up detoasted copy, if any */
		if (attr != origattr)
			pfree(DatumGetPointer(attr));
646
	}
647 648

	pq_endmessage(&buf);
649
}