printtup.c 14.2 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
 *
B
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
9
 * Portions Copyright (c) 1994, Regents of the University of California
10 11
 *
 * IDENTIFICATION
12
 *	  $Header: /cvsroot/pgsql/src/backend/access/common/printtup.c,v 1.70 2003/05/06 20:26:26 tgl 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 23
#include "utils/lsyscache.h"

M
Marc G. Fournier 已提交
24

25
static void printtup_startup(DestReceiver *self, int operation,
26
			   const char *portalName, TupleDesc typeinfo, List *targetlist);
27
static void printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self);
28
static void printtup_internal(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self);
29 30 31
static void printtup_shutdown(DestReceiver *self);
static void printtup_destroy(DestReceiver *self);

32

33
/* ----------------------------------------------------------------
34
 *		printtup / debugtup support
35 36 37
 * ----------------------------------------------------------------
 */

38 39 40 41
/* ----------------
 *		Private state for a printtup destination object
 * ----------------
 */
B
Bruce Momjian 已提交
42 43
typedef struct
{								/* Per-attribute information */
44 45
	Oid			typoutput;		/* Oid for the attribute's type output fn */
	Oid			typelem;		/* typelem value to pass to the output fn */
46
	bool		typisvarlena;	/* is it varlena (ie possibly toastable)? */
47
	FmgrInfo	finfo;			/* Precomputed call info for typoutput */
48
} PrinttupAttrInfo;
49

B
Bruce Momjian 已提交
50 51 52
typedef struct
{
	DestReceiver pub;			/* publicly-known function pointers */
53
	bool		sendDescrip;	/* send RowDescription at startup? */
B
Bruce Momjian 已提交
54 55 56
	TupleDesc	attrinfo;		/* The attr info we are set up for */
	int			nattrs;
	PrinttupAttrInfo *myinfo;	/* Cached info about each attr */
57
} DR_printtup;
58 59 60 61 62

/* ----------------
 *		Initialize: create a DestReceiver for printtup
 * ----------------
 */
B
Bruce Momjian 已提交
63
DestReceiver *
64
printtup_create_DR(CommandDest dest)
65
{
B
Bruce Momjian 已提交
66
	DR_printtup *self = (DR_printtup *) palloc(sizeof(DR_printtup));
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	bool	isBinary;
	bool	sendDescrip;

	switch (dest)
	{
		case Remote:
			isBinary = false;
			sendDescrip = true;
			break;
		case RemoteInternal:
			isBinary = true;
			sendDescrip = true;
			break;
		case RemoteExecute:
			isBinary = false;
			sendDescrip = false; /* no T message for Execute */
			break;
		case RemoteExecuteInternal:
			isBinary = true;
			sendDescrip = false; /* no T message for Execute */
			break;

		default:
			elog(ERROR, "printtup_create_DR: unsupported dest");
			return NULL;
	}
93

94
	self->pub.receiveTuple = isBinary ? printtup_internal : printtup;
95 96 97 98
	self->pub.startup = printtup_startup;
	self->pub.shutdown = printtup_shutdown;
	self->pub.destroy = printtup_destroy;
	self->pub.mydest = dest;
99

100 101
	self->sendDescrip = sendDescrip;

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

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

static void
110 111
printtup_startup(DestReceiver *self, int operation,
				 const char *portalName, TupleDesc typeinfo, List *targetlist)
112
{
113 114
	DR_printtup *myState = (DR_printtup *) self;

115 116 117 118 119 120 121 122 123 124 125 126
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
	{
		/*
		 * Send portal name to frontend (obsolete cruft, gone in proto 3.0)
		 *
		 * If portal name not specified, use "blank" portal.
		 */
		if (portalName == NULL)
			portalName = "blank";

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

	/*
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
		SendRowDescriptionMessage(typeinfo, targetlist);
134

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

147 148
/*
 * SendRowDescriptionMessage --- send a RowDescription message to the frontend
149 150 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
 * not have a plan.  If the targetlist isn't NIL then it is a Plan node's
 * targetlist; it is up to us to ignore resjunk columns in it.
155 156
 */
void
157
SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist)
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
{
	Form_pg_attribute *attrs = typeinfo->attrs;
	int			natts = typeinfo->natts;
	int			proto = PG_PROTOCOL_MAJOR(FrontendProtocol);
	int			i;
	StringInfoData buf;

	pq_beginmessage(&buf, 'T');		/* tuple descriptor message type */
	pq_sendint(&buf, natts, 2);		/* # of attrs in tuples */

	for (i = 0; i < natts; ++i)
	{
		pq_sendstring(&buf, NameStr(attrs[i]->attname));
		/* column ID info appears in protocol 3.0 and up */
		if (proto >= 3)
		{
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
			/* Do we have a non-resjunk tlist item? */
			while (targetlist &&
				   ((TargetEntry *) lfirst(targetlist))->resdom->resjunk)
				targetlist = lnext(targetlist);
			if (targetlist)
			{
				Resdom	   *res = ((TargetEntry *) lfirst(targetlist))->resdom;

				pq_sendint(&buf, res->resorigtbl, 4);
				pq_sendint(&buf, res->resorigcol, 2);
				targetlist = lnext(targetlist);
			}
			else
			{
				/* No info available, so send zeroes */
				pq_sendint(&buf, 0, 4);
				pq_sendint(&buf, 0, 2);
			}
192 193 194 195 196 197 198 199 200 201 202 203 204
		}
		pq_sendint(&buf, (int) attrs[i]->atttypid,
				   sizeof(attrs[i]->atttypid));
		pq_sendint(&buf, attrs[i]->attlen,
				   sizeof(attrs[i]->attlen));
		/* typmod appears in protocol 2.0 and up */
		if (proto >= 2)
			pq_sendint(&buf, attrs[i]->atttypmod,
					   sizeof(attrs[i]->atttypmod));
	}
	pq_endmessage(&buf);
}

205
static void
206
printtup_prepare_info(DR_printtup *myState, TupleDesc typeinfo, int numAttrs)
207
{
B
Bruce Momjian 已提交
208
	int			i;
209 210

	if (myState->myinfo)
B
Bruce Momjian 已提交
211
		pfree(myState->myinfo); /* get rid of any old data */
212 213 214 215 216
	myState->myinfo = NULL;
	myState->attrinfo = typeinfo;
	myState->nattrs = numAttrs;
	if (numAttrs <= 0)
		return;
B
Bruce Momjian 已提交
217
	myState->myinfo = (PrinttupAttrInfo *)
218 219 220
		palloc(numAttrs * sizeof(PrinttupAttrInfo));
	for (i = 0; i < numAttrs; i++)
	{
B
Bruce Momjian 已提交
221 222
		PrinttupAttrInfo *thisState = myState->myinfo + i;

223 224 225
		if (getTypeOutputInfo(typeinfo->attrs[i]->atttypid,
							  &thisState->typoutput, &thisState->typelem,
							  &thisState->typisvarlena))
226
			fmgr_info(thisState->typoutput, &thisState->finfo);
227 228 229
	}
}

230
/* ----------------
231
 *		printtup
232 233
 * ----------------
 */
234
static void
235
printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self)
236
{
B
Bruce Momjian 已提交
237
	DR_printtup *myState = (DR_printtup *) self;
238
	StringInfoData buf;
239
	int			natts = tuple->t_data->t_natts;
240 241
	int			i,
				j,
242
				k;
243

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

248 249
	/*
	 * tell the frontend to expect new tuple data (in ASCII style)
250
	 */
251
	pq_beginmessage(&buf, 'D');
252

253 254
	/*
	 * send a bitmap of which attributes are not null
255 256 257
	 */
	j = 0;
	k = 1 << 7;
258
	for (i = 0; i < natts; ++i)
259
	{
B
Bruce Momjian 已提交
260
		if (!heap_attisnull(tuple, i + 1))
261
			j |= k;				/* set bit if not null */
262
		k >>= 1;
263
		if (k == 0)				/* end of byte? */
264
		{
265
			pq_sendint(&buf, j, 1);
266 267 268
			j = 0;
			k = 1 << 7;
		}
269
	}
270
	if (k != (1 << 7))			/* flush last partial byte */
271
		pq_sendint(&buf, j, 1);
272

273 274
	/*
	 * send the attributes of this tuple
275
	 */
276
	for (i = 0; i < natts; ++i)
277
	{
B
Bruce Momjian 已提交
278
		PrinttupAttrInfo *thisState = myState->myinfo + i;
279 280 281 282
		Datum		origattr,
					attr;
		bool		isnull;
		char	   *outputstr;
B
Bruce Momjian 已提交
283

284
		origattr = heap_getattr(tuple, i + 1, typeinfo, &isnull);
M
 
Marc G. Fournier 已提交
285 286
		if (isnull)
			continue;
287
		if (OidIsValid(thisState->typoutput))
288
		{
289
			/*
B
Bruce Momjian 已提交
290 291
			 * If we have a toasted datum, forcibly detoast it here to
			 * avoid memory leakage inside the type's output routine.
292 293 294 295 296 297
			 */
			if (thisState->typisvarlena)
				attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
			else
				attr = origattr;

298
			outputstr = DatumGetCString(FunctionCall3(&thisState->finfo,
B
Bruce Momjian 已提交
299 300 301
													  attr,
									ObjectIdGetDatum(thisState->typelem),
						  Int32GetDatum(typeinfo->attrs[i]->atttypmod)));
302

303
			pq_sendcountedtext(&buf, outputstr, strlen(outputstr));
304 305 306 307

			/* Clean up detoasted copy, if any */
			if (attr != origattr)
				pfree(DatumGetPointer(attr));
308 309
			pfree(outputstr);
		}
M
 
Marc G. Fournier 已提交
310 311 312
		else
		{
			outputstr = "<unprintable>";
313
			pq_sendcountedtext(&buf, outputstr, strlen(outputstr));
314
		}
315
	}
316 317

	pq_endmessage(&buf);
318 319
}

320
/* ----------------
321
 *		printtup_shutdown
322 323 324
 * ----------------
 */
static void
325
printtup_shutdown(DestReceiver *self)
326
{
B
Bruce Momjian 已提交
327 328
	DR_printtup *myState = (DR_printtup *) self;

329 330
	if (myState->myinfo)
		pfree(myState->myinfo);
331 332 333 334 335 336 337 338 339 340 341 342
	myState->myinfo = NULL;
	myState->attrinfo = NULL;
}

/* ----------------
 *		printtup_destroy
 * ----------------
 */
static void
printtup_destroy(DestReceiver *self)
{
	pfree(self);
343 344
}

345
/* ----------------
346
 *		printatt
347 348 349 350
 * ----------------
 */
static void
printatt(unsigned attributeId,
351
		 Form_pg_attribute attributeP,
352
		 char *value)
353
{
B
Bruce Momjian 已提交
354
	printf("\t%2d: %s%s%s%s\t(typeid = %u, len = %d, typmod = %d, byval = %c)\n",
355
		   attributeId,
356
		   NameStr(attributeP->attname),
357 358 359 360 361
		   value != NULL ? " = \"" : "",
		   value != NULL ? value : "",
		   value != NULL ? "\"" : "",
		   (unsigned int) (attributeP->atttypid),
		   attributeP->attlen,
B
Bruce Momjian 已提交
362
		   attributeP->atttypmod,
363
		   attributeP->attbyval ? 't' : 'f');
364 365 366
}

/* ----------------
367
 *		showatts
368 369
 * ----------------
 */
370 371
static void
showatts(const char *name, TupleDesc tupleDesc)
372
{
373
	int			natts = tupleDesc->natts;
374
	Form_pg_attribute *attinfo = tupleDesc->attrs;
375
	int			i;
376

377 378 379 380
	puts(name);
	for (i = 0; i < natts; ++i)
		printatt((unsigned) i + 1, attinfo[i], (char *) NULL);
	printf("\t----\n");
381 382 383
}

/* ----------------
384
 *		debugStartup - prepare to print tuples for an interactive backend
385 386 387
 * ----------------
 */
void
388 389
debugStartup(DestReceiver *self, int operation,
			 const char *portalName, TupleDesc typeinfo, List *targetlist)
390 391 392 393 394 395 396 397 398 399 400 401
{
	/*
	 * show the return type of the tuples
	 */
	if (portalName == NULL)
		portalName = "blank";

	showatts(portalName, typeinfo);
}

/* ----------------
 *		debugtup - print one tuple for an interactive backend
402 403 404
 * ----------------
 */
void
405
debugtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self)
406
{
407
	int			natts = tuple->t_data->t_natts;
408
	int			i;
409 410
	Datum		origattr,
				attr;
411
	char	   *value;
412
	bool		isnull;
413 414
	Oid			typoutput,
				typelem;
415
	bool		typisvarlena;
416

417
	for (i = 0; i < natts; ++i)
418
	{
419
		origattr = heap_getattr(tuple, i + 1, typeinfo, &isnull);
420 421
		if (isnull)
			continue;
422 423
		if (getTypeOutputInfo(typeinfo->attrs[i]->atttypid,
							  &typoutput, &typelem, &typisvarlena))
424
		{
425
			/*
B
Bruce Momjian 已提交
426 427
			 * If we have a toasted datum, forcibly detoast it here to
			 * avoid memory leakage inside the type's output routine.
428 429 430 431 432 433
			 */
			if (typisvarlena)
				attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
			else
				attr = origattr;

434
			value = DatumGetCString(OidFunctionCall3(typoutput,
B
Bruce Momjian 已提交
435 436 437
													 attr,
											   ObjectIdGetDatum(typelem),
						  Int32GetDatum(typeinfo->attrs[i]->atttypmod)));
438

439
			printatt((unsigned) i + 1, typeinfo->attrs[i], value);
440 441 442 443

			/* Clean up detoasted copy, if any */
			if (attr != origattr)
				pfree(DatumGetPointer(attr));
444 445
			pfree(value);
		}
446
	}
447
	printf("\t----\n");
448 449 450
}

/* ----------------
451 452 453
 *		printtup_internal
 *		We use a different data prefix, e.g. 'B' instead of 'D' to
 *		indicate a tuple in internal (binary) form.
454
 *
455
 *		This is largely same as printtup, except we don't use the typout func.
456 457
 * ----------------
 */
458
static void
459
printtup_internal(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self)
460
{
461
	DR_printtup *myState = (DR_printtup *) self;
462
	StringInfoData buf;
463
	int			natts = tuple->t_data->t_natts;
464 465 466
	int			i,
				j,
				k;
467 468 469 470

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

472 473
	/*
	 * tell the frontend to expect new tuple data (in binary style)
474
	 */
475
	pq_beginmessage(&buf, 'B');
476

477 478
	/*
	 * send a bitmap of which attributes are not null
479 480 481
	 */
	j = 0;
	k = 1 << 7;
482
	for (i = 0; i < natts; ++i)
483
	{
B
Bruce Momjian 已提交
484
		if (!heap_attisnull(tuple, i + 1))
485
			j |= k;				/* set bit if not null */
486
		k >>= 1;
487
		if (k == 0)				/* end of byte? */
488
		{
489
			pq_sendint(&buf, j, 1);
490 491 492
			j = 0;
			k = 1 << 7;
		}
493
	}
494
	if (k != (1 << 7))			/* flush last partial byte */
495
		pq_sendint(&buf, j, 1);
496

497 498
	/*
	 * send the attributes of this tuple
499
	 */
500
#ifdef IPORTAL_DEBUG
501
	fprintf(stderr, "sending tuple with %d atts\n", natts);
502
#endif
503 504

	for (i = 0; i < natts; ++i)
505
	{
506 507 508 509 510
		PrinttupAttrInfo *thisState = myState->myinfo + i;
		Datum		origattr,
					attr;
		bool		isnull;
		int32		len;
511

512 513 514 515 516
		origattr = heap_getattr(tuple, i + 1, typeinfo, &isnull);
		if (isnull)
			continue;
		/* send # of bytes, and opaque data */
		if (thisState->typisvarlena)
517
		{
518 519 520 521 522 523
			/*
			 * If we have a toasted datum, must detoast before sending.
			 */
			attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));

			len = VARSIZE(attr) - VARHDRSZ;
524

525 526
			pq_sendint(&buf, len, VARHDRSZ);
			pq_sendbytes(&buf, VARDATA(attr), len);
527

528
#ifdef IPORTAL_DEBUG
529 530
			{
				char	   *d = VARDATA(attr);
531

532 533
				fprintf(stderr, "length %d data %x %x %x %x\n",
						len, *d, *(d + 1), *(d + 2), *(d + 3));
534
			}
535 536 537 538 539 540 541 542
#endif

			/* Clean up detoasted copy, if any */
			if (attr != origattr)
				pfree(DatumGetPointer(attr));
		}
		else
		{
543
			/* fixed size or cstring */
544 545
			attr = origattr;
			len = typeinfo->attrs[i]->attlen;
546 547 548 549 550 551
			if (len <= 0)
			{
				/* it's a cstring */
				Assert(len == -2 && !typeinfo->attrs[i]->attbyval);
				len = strlen(DatumGetCString(attr)) + 1;
			}
552 553
			pq_sendint(&buf, len, sizeof(int32));
			if (typeinfo->attrs[i]->attbyval)
554
			{
555 556 557 558 559 560 561 562
				Datum		datumBuf;

				/*
				 * We need this horsing around because we don't know how
				 * shorter data values are aligned within a Datum.
				 */
				store_att_byval(&datumBuf, attr, len);
				pq_sendbytes(&buf, (char *) &datumBuf, len);
563
#ifdef IPORTAL_DEBUG
564 565
				fprintf(stderr, "byval length %d data %ld\n", len,
						(long) attr);
566
#endif
567 568 569 570
			}
			else
			{
				pq_sendbytes(&buf, DatumGetPointer(attr), len);
571
#ifdef IPORTAL_DEBUG
572 573
				fprintf(stderr, "byref length %d data %p\n", len,
						DatumGetPointer(attr));
574
#endif
575
			}
576 577
		}
	}
578 579

	pq_endmessage(&buf);
580
}