printtup.c 13.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * printtup.c
4 5 6
 *	  Routines to print out tuples to the destination (both frontend
 *	  clients and interactive backends are supported here).
 *
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.69 2003/05/06 00:20:31 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_setup(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
static void printtup_cleanup(DestReceiver *self);
30

31
/* ----------------------------------------------------------------
32
 *		printtup / debugtup support
33 34 35
 * ----------------------------------------------------------------
 */

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

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

/* ----------------
 *		Initialize: create a DestReceiver for printtup
 * ----------------
 */
B
Bruce Momjian 已提交
61
DestReceiver *
62
printtup_create_DR(bool isBinary, bool sendDescrip)
63
{
B
Bruce Momjian 已提交
64
	DR_printtup *self = (DR_printtup *) palloc(sizeof(DR_printtup));
65

66
	self->pub.receiveTuple = isBinary ? printtup_internal : printtup;
67 68 69
	self->pub.setup = printtup_setup;
	self->pub.cleanup = printtup_cleanup;

70 71
	self->sendDescrip = sendDescrip;

72 73 74 75
	self->attrinfo = NULL;
	self->nattrs = 0;
	self->myinfo = NULL;

B
Bruce Momjian 已提交
76
	return (DestReceiver *) self;
77 78 79
}

static void
80
printtup_setup(DestReceiver *self, int operation,
81
			   const char *portalName, TupleDesc typeinfo, List *targetlist)
82
{
83 84
	DR_printtup *myState = (DR_printtup *) self;

85 86 87 88 89 90 91 92 93 94 95 96
	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);
	}
97 98

	/*
99 100
	 * If this is a retrieve, and we are supposed to emit row descriptions,
	 * then we send back the tuple descriptor of the tuples.  
101
	 */
102
	if (operation == CMD_SELECT && myState->sendDescrip)
103
		SendRowDescriptionMessage(typeinfo, targetlist);
104

105 106
	/* ----------------
	 * We could set up the derived attr info at this time, but we postpone it
107
	 * until the first call of printtup, for 2 reasons:
108
	 * 1. We don't waste time (compared to the old way) if there are no
B
Bruce Momjian 已提交
109
	 *	  tuples at all to output.
110
	 * 2. Checking in printtup allows us to handle the case that the tuples
B
Bruce Momjian 已提交
111 112
	 *	  change type midway through (although this probably can't happen in
	 *	  the current executor).
113 114 115 116
	 * ----------------
	 */
}

117 118
/*
 * SendRowDescriptionMessage --- send a RowDescription message to the frontend
119 120 121 122 123 124
 *
 * 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.
125 126
 */
void
127
SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
{
	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)
		{
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
			/* 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);
			}
162 163 164 165 166 167 168 169 170 171 172 173 174
		}
		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);
}

175
static void
176
printtup_prepare_info(DR_printtup *myState, TupleDesc typeinfo, int numAttrs)
177
{
B
Bruce Momjian 已提交
178
	int			i;
179 180

	if (myState->myinfo)
B
Bruce Momjian 已提交
181
		pfree(myState->myinfo); /* get rid of any old data */
182 183 184 185 186
	myState->myinfo = NULL;
	myState->attrinfo = typeinfo;
	myState->nattrs = numAttrs;
	if (numAttrs <= 0)
		return;
B
Bruce Momjian 已提交
187
	myState->myinfo = (PrinttupAttrInfo *)
188 189 190
		palloc(numAttrs * sizeof(PrinttupAttrInfo));
	for (i = 0; i < numAttrs; i++)
	{
B
Bruce Momjian 已提交
191 192
		PrinttupAttrInfo *thisState = myState->myinfo + i;

193 194 195
		if (getTypeOutputInfo(typeinfo->attrs[i]->atttypid,
							  &thisState->typoutput, &thisState->typelem,
							  &thisState->typisvarlena))
196
			fmgr_info(thisState->typoutput, &thisState->finfo);
197 198 199
	}
}

200
/* ----------------
201
 *		printtup
202 203
 * ----------------
 */
204
static void
205
printtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self)
206
{
B
Bruce Momjian 已提交
207
	DR_printtup *myState = (DR_printtup *) self;
208
	StringInfoData buf;
209
	int			natts = tuple->t_data->t_natts;
210 211
	int			i,
				j,
212
				k;
213

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

218 219
	/*
	 * tell the frontend to expect new tuple data (in ASCII style)
220
	 */
221
	pq_beginmessage(&buf, 'D');
222

223 224
	/*
	 * send a bitmap of which attributes are not null
225 226 227
	 */
	j = 0;
	k = 1 << 7;
228
	for (i = 0; i < natts; ++i)
229
	{
B
Bruce Momjian 已提交
230
		if (!heap_attisnull(tuple, i + 1))
231
			j |= k;				/* set bit if not null */
232
		k >>= 1;
233
		if (k == 0)				/* end of byte? */
234
		{
235
			pq_sendint(&buf, j, 1);
236 237 238
			j = 0;
			k = 1 << 7;
		}
239
	}
240
	if (k != (1 << 7))			/* flush last partial byte */
241
		pq_sendint(&buf, j, 1);
242

243 244
	/*
	 * send the attributes of this tuple
245
	 */
246
	for (i = 0; i < natts; ++i)
247
	{
B
Bruce Momjian 已提交
248
		PrinttupAttrInfo *thisState = myState->myinfo + i;
249 250 251 252
		Datum		origattr,
					attr;
		bool		isnull;
		char	   *outputstr;
B
Bruce Momjian 已提交
253

254
		origattr = heap_getattr(tuple, i + 1, typeinfo, &isnull);
M
 
Marc G. Fournier 已提交
255 256
		if (isnull)
			continue;
257
		if (OidIsValid(thisState->typoutput))
258
		{
259
			/*
B
Bruce Momjian 已提交
260 261
			 * If we have a toasted datum, forcibly detoast it here to
			 * avoid memory leakage inside the type's output routine.
262 263 264 265 266 267
			 */
			if (thisState->typisvarlena)
				attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
			else
				attr = origattr;

268
			outputstr = DatumGetCString(FunctionCall3(&thisState->finfo,
B
Bruce Momjian 已提交
269 270 271
													  attr,
									ObjectIdGetDatum(thisState->typelem),
						  Int32GetDatum(typeinfo->attrs[i]->atttypmod)));
272

273
			pq_sendcountedtext(&buf, outputstr, strlen(outputstr));
274 275 276 277

			/* Clean up detoasted copy, if any */
			if (attr != origattr)
				pfree(DatumGetPointer(attr));
278 279
			pfree(outputstr);
		}
M
 
Marc G. Fournier 已提交
280 281 282
		else
		{
			outputstr = "<unprintable>";
283
			pq_sendcountedtext(&buf, outputstr, strlen(outputstr));
284
		}
285
	}
286 287

	pq_endmessage(&buf);
288 289
}

290 291 292 293 294
/* ----------------
 *		printtup_cleanup
 * ----------------
 */
static void
295
printtup_cleanup(DestReceiver *self)
296
{
B
Bruce Momjian 已提交
297 298
	DR_printtup *myState = (DR_printtup *) self;

299 300 301 302 303
	if (myState->myinfo)
		pfree(myState->myinfo);
	pfree(myState);
}

304
/* ----------------
305
 *		printatt
306 307 308 309
 * ----------------
 */
static void
printatt(unsigned attributeId,
310
		 Form_pg_attribute attributeP,
311
		 char *value)
312
{
B
Bruce Momjian 已提交
313
	printf("\t%2d: %s%s%s%s\t(typeid = %u, len = %d, typmod = %d, byval = %c)\n",
314
		   attributeId,
315
		   NameStr(attributeP->attname),
316 317 318 319 320
		   value != NULL ? " = \"" : "",
		   value != NULL ? value : "",
		   value != NULL ? "\"" : "",
		   (unsigned int) (attributeP->atttypid),
		   attributeP->attlen,
B
Bruce Momjian 已提交
321
		   attributeP->atttypmod,
322
		   attributeP->attbyval ? 't' : 'f');
323 324 325
}

/* ----------------
326
 *		showatts
327 328
 * ----------------
 */
329 330
static void
showatts(const char *name, TupleDesc tupleDesc)
331
{
332
	int			natts = tupleDesc->natts;
333
	Form_pg_attribute *attinfo = tupleDesc->attrs;
334
	int			i;
335

336 337 338 339
	puts(name);
	for (i = 0; i < natts; ++i)
		printatt((unsigned) i + 1, attinfo[i], (char *) NULL);
	printf("\t----\n");
340 341 342
}

/* ----------------
343 344 345 346 347
 *		debugSetup - prepare to print tuples for an interactive backend
 * ----------------
 */
void
debugSetup(DestReceiver *self, int operation,
348
		   const char *portalName, TupleDesc typeinfo, List *targetlist)
349 350 351 352 353 354 355 356 357 358 359 360
{
	/*
	 * show the return type of the tuples
	 */
	if (portalName == NULL)
		portalName = "blank";

	showatts(portalName, typeinfo);
}

/* ----------------
 *		debugtup - print one tuple for an interactive backend
361 362 363
 * ----------------
 */
void
364
debugtup(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self)
365
{
366
	int			natts = tuple->t_data->t_natts;
367
	int			i;
368 369
	Datum		origattr,
				attr;
370
	char	   *value;
371
	bool		isnull;
372 373
	Oid			typoutput,
				typelem;
374
	bool		typisvarlena;
375

376
	for (i = 0; i < natts; ++i)
377
	{
378
		origattr = heap_getattr(tuple, i + 1, typeinfo, &isnull);
379 380
		if (isnull)
			continue;
381 382
		if (getTypeOutputInfo(typeinfo->attrs[i]->atttypid,
							  &typoutput, &typelem, &typisvarlena))
383
		{
384
			/*
B
Bruce Momjian 已提交
385 386
			 * If we have a toasted datum, forcibly detoast it here to
			 * avoid memory leakage inside the type's output routine.
387 388 389 390 391 392
			 */
			if (typisvarlena)
				attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));
			else
				attr = origattr;

393
			value = DatumGetCString(OidFunctionCall3(typoutput,
B
Bruce Momjian 已提交
394 395 396
													 attr,
											   ObjectIdGetDatum(typelem),
						  Int32GetDatum(typeinfo->attrs[i]->atttypmod)));
397

398
			printatt((unsigned) i + 1, typeinfo->attrs[i], value);
399 400 401 402

			/* Clean up detoasted copy, if any */
			if (attr != origattr)
				pfree(DatumGetPointer(attr));
403 404
			pfree(value);
		}
405
	}
406
	printf("\t----\n");
407 408 409
}

/* ----------------
410 411 412
 *		printtup_internal
 *		We use a different data prefix, e.g. 'B' instead of 'D' to
 *		indicate a tuple in internal (binary) form.
413
 *
414
 *		This is largely same as printtup, except we don't use the typout func.
415 416
 * ----------------
 */
417
static void
418
printtup_internal(HeapTuple tuple, TupleDesc typeinfo, DestReceiver *self)
419
{
420
	DR_printtup *myState = (DR_printtup *) self;
421
	StringInfoData buf;
422
	int			natts = tuple->t_data->t_natts;
423 424 425
	int			i,
				j,
				k;
426 427 428 429

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

431 432
	/*
	 * tell the frontend to expect new tuple data (in binary style)
433
	 */
434
	pq_beginmessage(&buf, 'B');
435

436 437
	/*
	 * send a bitmap of which attributes are not null
438 439 440
	 */
	j = 0;
	k = 1 << 7;
441
	for (i = 0; i < natts; ++i)
442
	{
B
Bruce Momjian 已提交
443
		if (!heap_attisnull(tuple, i + 1))
444
			j |= k;				/* set bit if not null */
445
		k >>= 1;
446
		if (k == 0)				/* end of byte? */
447
		{
448
			pq_sendint(&buf, j, 1);
449 450 451
			j = 0;
			k = 1 << 7;
		}
452
	}
453
	if (k != (1 << 7))			/* flush last partial byte */
454
		pq_sendint(&buf, j, 1);
455

456 457
	/*
	 * send the attributes of this tuple
458
	 */
459
#ifdef IPORTAL_DEBUG
460
	fprintf(stderr, "sending tuple with %d atts\n", natts);
461
#endif
462 463

	for (i = 0; i < natts; ++i)
464
	{
465 466 467 468 469
		PrinttupAttrInfo *thisState = myState->myinfo + i;
		Datum		origattr,
					attr;
		bool		isnull;
		int32		len;
470

471 472 473 474 475
		origattr = heap_getattr(tuple, i + 1, typeinfo, &isnull);
		if (isnull)
			continue;
		/* send # of bytes, and opaque data */
		if (thisState->typisvarlena)
476
		{
477 478 479 480 481 482
			/*
			 * If we have a toasted datum, must detoast before sending.
			 */
			attr = PointerGetDatum(PG_DETOAST_DATUM(origattr));

			len = VARSIZE(attr) - VARHDRSZ;
483

484 485
			pq_sendint(&buf, len, VARHDRSZ);
			pq_sendbytes(&buf, VARDATA(attr), len);
486

487
#ifdef IPORTAL_DEBUG
488 489
			{
				char	   *d = VARDATA(attr);
490

491 492
				fprintf(stderr, "length %d data %x %x %x %x\n",
						len, *d, *(d + 1), *(d + 2), *(d + 3));
493
			}
494 495 496 497 498 499 500 501
#endif

			/* Clean up detoasted copy, if any */
			if (attr != origattr)
				pfree(DatumGetPointer(attr));
		}
		else
		{
502
			/* fixed size or cstring */
503 504
			attr = origattr;
			len = typeinfo->attrs[i]->attlen;
505 506 507 508 509 510
			if (len <= 0)
			{
				/* it's a cstring */
				Assert(len == -2 && !typeinfo->attrs[i]->attbyval);
				len = strlen(DatumGetCString(attr)) + 1;
			}
511 512
			pq_sendint(&buf, len, sizeof(int32));
			if (typeinfo->attrs[i]->attbyval)
513
			{
514 515 516 517 518 519 520 521
				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);
522
#ifdef IPORTAL_DEBUG
523 524
				fprintf(stderr, "byval length %d data %ld\n", len,
						(long) attr);
525
#endif
526 527 528 529
			}
			else
			{
				pq_sendbytes(&buf, DatumGetPointer(attr), len);
530
#ifdef IPORTAL_DEBUG
531 532
				fprintf(stderr, "byref length %d data %p\n", len,
						DatumGetPointer(attr));
533
#endif
534
			}
535 536
		}
	}
537 538

	pq_endmessage(&buf);
539
}