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
B
Bruce Momjian 已提交
12
 *	  $PostgreSQL: pgsql/src/backend/access/common/printtup.c,v 1.92 2005/10/15 02:49:08 momjian 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 97 98
	self->portal = portal;

	/* Send T message automatically if Remote, but not if RemoteExecute */
	self->sendDescrip = (dest == Remote);
99

100 101 102 103
	self->attrinfo = NULL;
	self->nattrs = 0;
	self->myinfo = NULL;

B
Bruce Momjian 已提交
104
	return (DestReceiver *) self;
105 106 107
}

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

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

		if (portalName == NULL || portalName[0] == '\0')
123 124 125 126
			portalName = "blank";

		pq_puttextmessage('P', portalName);
	}
127 128

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

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

149 150
/*
 * SendRowDescriptionMessage --- send a RowDescription message to the frontend
151 152 153 154
 *
 * 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
155
 * not have a plan.  If the targetlist isn't NIL then it is a Query node's
B
Bruce Momjian 已提交
156
 * targetlist; it is up to us to ignore resjunk columns in it.	The formats[]
157 158
 * array pointer might be NULL (if we are doing Describe on a prepared stmt);
 * send zeroes for the format codes in that case.
159 160
 */
void
161
SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
162 163 164 165 166 167
{
	Form_pg_attribute *attrs = typeinfo->attrs;
	int			natts = typeinfo->natts;
	int			proto = PG_PROTOCOL_MAJOR(FrontendProtocol);
	int			i;
	StringInfoData buf;
168
	ListCell   *tlist_item = list_head(targetlist);
169

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

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

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

191 192
				pq_sendint(&buf, tle->resorigtbl, 4);
				pq_sendint(&buf, tle->resorigcol, 2);
193
				tlist_item = lnext(tlist_item);
194 195 196 197 198 199 200
			}
			else
			{
				/* No info available, so send zeroes */
				pq_sendint(&buf, 0, 4);
				pq_sendint(&buf, 0, 2);
			}
201
		}
202 203 204 205 206 207 208 209 210
		/* 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));
211 212
		/* typmod appears in protocol 2.0 and up */
		if (proto >= 2)
213
			pq_sendint(&buf, atttypmod, sizeof(atttypmod));
214 215 216 217 218 219 220 221
		/* 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);
		}
222 223 224 225
	}
	pq_endmessage(&buf);
}

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

235
	/* get rid of any old data */
236
	if (myState->myinfo)
237
		pfree(myState->myinfo);
238
	myState->myinfo = NULL;
239

240 241 242 243
	myState->attrinfo = typeinfo;
	myState->nattrs = numAttrs;
	if (numAttrs <= 0)
		return;
244

B
Bruce Momjian 已提交
245
	myState->myinfo = (PrinttupAttrInfo *)
246
		palloc0(numAttrs * sizeof(PrinttupAttrInfo));
247

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

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

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

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

292 293
	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);
294

295 296 297 298 299 300 301 302 303 304 305 306 307
	/*
	 * 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;
308
		Datum		origattr = slot->tts_values[i],
309 310
					attr;

311
		if (slot->tts_isnull[i])
312 313 314 315 316
		{
			pq_sendint(&buf, -1, 4);
			continue;
		}

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

326
		if (thisState->format == 0)
327
		{
328 329 330
			/* Text output */
			char	   *outputstr;

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

341 342
			outputbytes = DatumGetByteaP(FunctionCall1(&thisState->finfo,
													   attr));
343 344 345 346 347
			/* 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);
348
		}
349 350 351 352

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

	pq_endmessage(&buf);
}

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

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

377 378
	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);
379

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

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

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

415
		if (slot->tts_isnull[i])
M
 
Marc G. Fournier 已提交
416
			continue;
417

418 419 420
		Assert(thisState->format == 0);

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

429 430
		outputstr = DatumGetCString(FunctionCall1(&thisState->finfo,
												  attr));
431 432
		pq_sendcountedtext(&buf, outputstr, strlen(outputstr), true);
		pfree(outputstr);
433

434 435 436
		/* Clean up detoasted copy, if any */
		if (attr != origattr)
			pfree(DatumGetPointer(attr));
437
	}
438 439

	pq_endmessage(&buf);
440 441
}

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

451 452
	if (myState->myinfo)
		pfree(myState->myinfo);
453
	myState->myinfo = NULL;
454

455 456 457 458 459 460 461 462 463 464 465
	myState->attrinfo = NULL;
}

/* ----------------
 *		printtup_destroy
 * ----------------
 */
static void
printtup_destroy(DestReceiver *self)
{
	pfree(self);
466 467
}

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

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

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

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

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

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

542 543
		value = DatumGetCString(OidFunctionCall1(typoutput,
												 attr));
544

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

547 548 549 550 551
		pfree(value);

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

/* ----------------
557 558 559 560
 *		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.
561
 *
562
 * This is largely same as printtup_20, except we use binary formatting.
563 564
 * ----------------
 */
565
static void
566
printtup_internal_20(TupleTableSlot *slot, DestReceiver *self)
567
{
B
Bruce Momjian 已提交
568
	TupleDesc	typeinfo = slot->tts_tupleDescriptor;
569
	DR_printtup *myState = (DR_printtup *) self;
570
	StringInfoData buf;
571
	int			natts = typeinfo->natts;
572 573 574
	int			i,
				j,
				k;
575 576 577 578

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

580 581
	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);
582

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

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

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

618
		if (slot->tts_isnull[i])
619
			continue;
620

621
		Assert(thisState->format == 1);
622

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

632 633
		outputbytes = DatumGetByteaP(FunctionCall1(&thisState->finfo,
												   attr));
634 635 636 637 638 639 640 641 642
		/* 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));
643
	}
644 645

	pq_endmessage(&buf);
646
}