heaptuple.c 50 KB
Newer Older
1
/*-------------------------------------------------------------------------
2
 *
3
 * heaptuple.c
4
 *	  This file contains heap tuple accessor and mutator routines, as well
5
 *	  as various tuple utilities.
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19
 * Some notes about varlenas and this code:
 *
 * Before Postgres 8.3 varlenas always had a 4-byte length header, and
 * therefore always needed 4-byte alignment (at least).  This wasted space
 * for short varlenas, for example CHAR(1) took 5 bytes and could need up to
 * 3 additional padding bytes for alignment.
 *
 * Now, a short varlena (up to 126 data bytes) is reduced to a 1-byte header
 * and we don't align it.  To hide this from datatype-specific functions that
 * don't want to deal with it, such a datum is considered "toasted" and will
 * be expanded back to the normal 4-byte-header format by pg_detoast_datum.
 * (In performance-critical code paths we can use pg_detoast_datum_packed
 * and the appropriate access macros to avoid that overhead.)  Note that this
20 21
 * conversion is performed directly in heap_form_tuple, without invoking
 * tuptoaster.c.
22 23
 *
 * This change will break any code that assumes it needn't detoast values
Bruce Momjian's avatar
Bruce Momjian committed
24
 * that have been put into a tuple but never sent to disk.  Hopefully there
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 * are few such places.
 *
 * Varlenas still have alignment 'i' (or 'd') in pg_type/pg_attribute, since
 * that's the normal requirement for the untoasted format.  But we ignore that
 * for the 1-byte-header format.  This means that the actual start position
 * of a varlena datum may vary depending on which format it has.  To determine
 * what is stored, we have to require that alignment padding bytes be zero.
 * (Postgres actually has always zeroed them, but now it's required!)  Since
 * the first byte of a 1-byte-header varlena can never be zero, we can examine
 * the first byte after the previous datum to tell if it's a pad byte or the
 * start of a 1-byte-header varlena.
 *
 * Note that while formerly we could rely on the first varlena column of a
 * system catalog to be at the offset suggested by the C struct for the
 * catalog, this is now risky: it's only safe if the preceding field is
 * word-aligned, so that there will never be any padding.
 *
 * We don't pack varlenas whose attstorage is 'p', since the data type
 * isn't expecting to have to detoast values.  This is used in particular
 * by oidvector and int2vector, which are used in the system catalogs
 * and we'd like to still refer to them via C struct offsets.
 *
 *
Bruce Momjian's avatar
Bruce Momjian committed
48
 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
49
 * Portions Copyright (c) 1994, Regents of the University of California
50 51 52
 *
 *
 * IDENTIFICATION
53
 *	  src/backend/access/common/heaptuple.c
54 55 56 57
 *
 *-------------------------------------------------------------------------
 */

58
#include "postgres.h"
59

60
#include "access/sysattr.h"
61
#include "access/tupdesc_details.h"
62
#include "access/tuptoaster.h"
63
#include "executor/tuptable.h"
64
#include "utils/expandeddatum.h"
Marc G. Fournier's avatar
Marc G. Fournier committed
65 66


67 68 69 70 71 72 73 74
/* Does att's datatype allow packing into the 1-byte-header varlena format? */
#define ATT_IS_PACKABLE(att) \
	((att)->attlen == -1 && (att)->attstorage != 'p')
/* Use this if it's already known varlena */
#define VARLENA_ATT_IS_PACKABLE(att) \
	((att)->attstorage != 'p')


75
/* ----------------------------------------------------------------
76
 *						misc support routines
77 78 79
 * ----------------------------------------------------------------
 */

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
/*
 * Return the missing value of an attribute, or NULL if there isn't one.
 */
static Datum
getmissingattr(TupleDesc tupleDesc,
			   int attnum, bool *isnull)
{
	Form_pg_attribute att;

	Assert(attnum <= tupleDesc->natts);
	Assert(attnum > 0);

	att = TupleDescAttr(tupleDesc, attnum - 1);

	if (att->atthasmissing)
	{
		AttrMissing *attrmiss;

		Assert(tupleDesc->constr);
		Assert(tupleDesc->constr->missing);

		attrmiss = tupleDesc->constr->missing + (attnum - 1);

		if (attrmiss->ammissingPresent)
		{
			*isnull = false;
			return attrmiss->ammissing;
		}
	}

	*isnull = true;
	return PointerGetDatum(NULL);
}

/*
115 116 117 118 119
 * Fill in missing values for a TupleTableSlot.
 *
 * This is only exposed because it's needed for JIT compiled tuple
 * deforming. That exception aside, there should be no callers outside of this
 * file.
120
 */
121
void
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
slot_getmissingattrs(TupleTableSlot *slot, int startAttNum, int lastAttNum)
{
	AttrMissing *attrmiss = NULL;
	int			missattnum;

	if (slot->tts_tupleDescriptor->constr)
		attrmiss = slot->tts_tupleDescriptor->constr->missing;

	if (!attrmiss)
	{
		/* no missing values array at all, so just fill everything in as NULL */
		memset(slot->tts_values + startAttNum, 0,
			   (lastAttNum - startAttNum) * sizeof(Datum));
		memset(slot->tts_isnull + startAttNum, 1,
			   (lastAttNum - startAttNum) * sizeof(bool));
	}
	else
	{
		/* if there is a missing values array we must process them one by one */
141 142 143
		for (missattnum = startAttNum;
			 missattnum < lastAttNum;
			 missattnum++)
144 145 146 147 148 149 150
		{
			slot->tts_values[missattnum] = attrmiss[missattnum].ammissing;
			slot->tts_isnull[missattnum] =
				!attrmiss[missattnum].ammissingPresent;
		}
	}
}
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
/*
 * heap_compute_data_size
 *		Determine size of the data area of a tuple to be constructed
 */
Size
heap_compute_data_size(TupleDesc tupleDesc,
					   Datum *values,
					   bool *isnull)
{
	Size		data_length = 0;
	int			i;
	int			numberOfAttributes = tupleDesc->natts;

	for (i = 0; i < numberOfAttributes; i++)
	{
Bruce Momjian's avatar
Bruce Momjian committed
167
		Datum		val;
168
		Form_pg_attribute atti;
169

170 171 172
		if (isnull[i])
			continue;

173
		val = values[i];
174
		atti = TupleDescAttr(tupleDesc, i);
175

176
		if (ATT_IS_PACKABLE(atti) &&
177 178 179
			VARATT_CAN_MAKE_SHORT(DatumGetPointer(val)))
		{
			/*
Bruce Momjian's avatar
Bruce Momjian committed
180 181
			 * we're anticipating converting to a short varlena header, so
			 * adjust length and don't count any alignment
182 183 184
			 */
			data_length += VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(val));
		}
185 186 187 188 189 190 191 192 193 194
		else if (atti->attlen == -1 &&
				 VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(val)))
		{
			/*
			 * we want to flatten the expanded value so that the constructed
			 * tuple doesn't depend on it
			 */
			data_length = att_align_nominal(data_length, atti->attalign);
			data_length += EOH_get_flat_size(DatumGetEOHP(val));
		}
195 196
		else
		{
197 198 199
			data_length = att_align_datum(data_length, atti->attalign,
										  atti->attlen, val);
			data_length = att_addlength_datum(data_length, atti->attlen,
200 201
											  val);
		}
202 203 204 205 206
	}

	return data_length;
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
/*
 * Per-attribute helper for heap_fill_tuple and other routines building tuples.
 *
 * Fill in either a data value or a bit in the null bitmask
 */
static inline void
fill_val(Form_pg_attribute att,
		 bits8 **bit,
		 int *bitmask,
		 char **dataP,
		 uint16 *infomask,
		 Datum datum,
		 bool isnull)
{
	Size		data_length;
	char	   *data = *dataP;

	/*
	 * If we're building a null bitmap, set the appropriate bit for the
	 * current column value here.
	 */
	if (bit != NULL)
	{
		if (*bitmask != HIGHBIT)
			*bitmask <<= 1;
		else
		{
			*bit += 1;
			**bit = 0x0;
			*bitmask = 1;
		}

		if (isnull)
		{
			*infomask |= HEAP_HASNULL;
			return;
		}

		**bit |= *bitmask;
	}

	/*
	 * XXX we use the att_align macros on the pointer value itself, not on an
	 * offset.  This is a bit of a hack.
	 */
	if (att->attbyval)
	{
		/* pass-by-value */
		data = (char *) att_align_nominal(data, att->attalign);
		store_att_byval(data, datum, att->attlen);
		data_length = att->attlen;
	}
	else if (att->attlen == -1)
	{
		/* varlena */
		Pointer		val = DatumGetPointer(datum);

		*infomask |= HEAP_HASVARWIDTH;
		if (VARATT_IS_EXTERNAL(val))
		{
			if (VARATT_IS_EXTERNAL_EXPANDED(val))
			{
				/*
				 * we want to flatten the expanded value so that the
				 * constructed tuple doesn't depend on it
				 */
				ExpandedObjectHeader *eoh = DatumGetEOHP(datum);

				data = (char *) att_align_nominal(data,
												  att->attalign);
				data_length = EOH_get_flat_size(eoh);
				EOH_flatten_into(eoh, data, data_length);
			}
			else
			{
				*infomask |= HEAP_HASEXTERNAL;
				/* no alignment, since it's short by definition */
				data_length = VARSIZE_EXTERNAL(val);
				memcpy(data, val, data_length);
			}
		}
		else if (VARATT_IS_SHORT(val))
		{
			/* no alignment for short varlenas */
			data_length = VARSIZE_SHORT(val);
			memcpy(data, val, data_length);
		}
		else if (VARLENA_ATT_IS_PACKABLE(att) &&
				 VARATT_CAN_MAKE_SHORT(val))
		{
			/* convert to short varlena -- no alignment */
			data_length = VARATT_CONVERTED_SHORT_SIZE(val);
			SET_VARSIZE_SHORT(data, data_length);
			memcpy(data + 1, VARDATA(val), data_length - 1);
		}
		else
		{
			/* full 4-byte header varlena */
			data = (char *) att_align_nominal(data,
											  att->attalign);
			data_length = VARSIZE(val);
			memcpy(data, val, data_length);
		}
	}
	else if (att->attlen == -2)
	{
		/* cstring ... never needs alignment */
		*infomask |= HEAP_HASVARWIDTH;
		Assert(att->attalign == 'c');
		data_length = strlen(DatumGetCString(datum)) + 1;
		memcpy(data, DatumGetPointer(datum), data_length);
	}
	else
	{
		/* fixed-length pass-by-reference */
		data = (char *) att_align_nominal(data, att->attalign);
		Assert(att->attlen > 0);
		data_length = att->attlen;
		memcpy(data, DatumGetPointer(datum), data_length);
	}

	data += data_length;
	*dataP = data;
}

332 333 334 335 336 337
/*
 * heap_fill_tuple
 *		Load data portion of a tuple from values/isnull arrays
 *
 * We also fill the null bitmap (if any) and set the infomask bits
 * that reflect the tuple's data contents.
338 339
 *
 * NOTE: it is now REQUIRED that the caller have pre-zeroed the data area.
340 341 342 343
 */
void
heap_fill_tuple(TupleDesc tupleDesc,
				Datum *values, bool *isnull,
344 345
				char *data, Size data_size,
				uint16 *infomask, bits8 *bit)
346 347 348 349 350
{
	bits8	   *bitP;
	int			bitmask;
	int			i;
	int			numberOfAttributes = tupleDesc->natts;
Bruce Momjian's avatar
Bruce Momjian committed
351

352 353 354
#ifdef USE_ASSERT_CHECKING
	char	   *start = data;
#endif
355 356 357 358

	if (bit != NULL)
	{
		bitP = &bit[-1];
359
		bitmask = HIGHBIT;
360 361 362 363 364 365 366 367
	}
	else
	{
		/* just to keep compiler quiet */
		bitP = NULL;
		bitmask = 0;
	}

368
	*infomask &= ~(HEAP_HASNULL | HEAP_HASVARWIDTH | HEAP_HASEXTERNAL);
369 370 371

	for (i = 0; i < numberOfAttributes; i++)
	{
372 373 374 375 376 377 378 379 380
		Form_pg_attribute attr = TupleDescAttr(tupleDesc, i);

		fill_val(attr,
				 bitP ? &bitP : NULL,
				 &bitmask,
				 &data,
				 infomask,
				 values ? values[i] : PointerGetDatum(NULL),
				 isnull ? isnull[i] : true);
381
	}
382 383

	Assert((data - start) == data_size);
384 385
}

386 387

/* ----------------------------------------------------------------
388
 *						heap tuple interface
389 390 391 392
 * ----------------------------------------------------------------
 */

/* ----------------
393
 *		heap_attisnull	- returns true iff tuple attribute is not present
394 395
 * ----------------
 */
396
bool
397
heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
398
{
399 400 401 402 403
	/*
	 * We allow a NULL tupledesc for relations not expected to have missing
	 * values, such as catalog relations and indexes.
	 */
	Assert(!tupleDesc || attnum <= tupleDesc->natts);
404
	if (attnum > (int) HeapTupleHeaderGetNatts(tup->t_data))
405 406 407 408 409 410
	{
		if (tupleDesc && TupleDescAttr(tupleDesc, attnum - 1)->atthasmissing)
			return false;
		else
			return true;
	}
411 412

	if (attnum > 0)
413 414
	{
		if (HeapTupleNoNulls(tup))
415
			return false;
416
		return att_isnull(attnum - 1, tup->t_data->t_bits);
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
	}

	switch (attnum)
	{
		case TableOidAttributeNumber:
		case SelfItemPointerAttributeNumber:
		case ObjectIdAttributeNumber:
		case MinTransactionIdAttributeNumber:
		case MinCommandIdAttributeNumber:
		case MaxTransactionIdAttributeNumber:
		case MaxCommandIdAttributeNumber:
			/* these are never null */
			break;

		default:
			elog(ERROR, "invalid attnum: %d", attnum);
	}
434

435
	return false;
436 437 438
}

/* ----------------
439 440 441 442
 *		nocachegetattr
 *
 *		This only gets called from fastgetattr() macro, in cases where
 *		we can't use a cacheoffset and the value is not null.
443
 *
444
 *		This caches attribute offsets in the attribute descriptor.
445
 *
446
 *		An alternative way to speed things up would be to cache offsets
447 448 449
 *		with the tuple, but that seems more difficult unless you take
 *		the storage hit of actually putting those offsets into the
 *		tuple you send to disk.  Yuck.
450
 *
451
 *		This scheme will be slightly slower than that, but should
452
 *		perform well for queries which hit large #'s of tuples.  After
453 454
 *		you cache the offsets once, examining all the other tuples using
 *		the same attribute descriptor will go much quicker. -cim 5/4/91
455
 *
456
 *		NOTE: if you need to change this code, see also heap_deform_tuple.
457 458
 *		Also see nocache_index_getattr, which is the same code for index
 *		tuples.
459 460
 * ----------------
 */
461
Datum
462
nocachegetattr(HeapTuple tuple,
463
			   int attnum,
464
			   TupleDesc tupleDesc)
465
{
Bruce Momjian's avatar
Bruce Momjian committed
466
	HeapTupleHeader tup = tuple->t_data;
467
	char	   *tp;				/* ptr to data part of tuple */
Tom Lane's avatar
Tom Lane committed
468
	bits8	   *bp = tup->t_bits;	/* ptr to null bitmap in tuple */
469 470
	bool		slow = false;	/* do we have to walk attrs? */
	int			off;			/* current offset within data */
471 472

	/* ----------------
473 474
	 *	 Three cases:
	 *
475 476 477
	 *	 1: No nulls and no variable-width attributes.
	 *	 2: Has a null or a var-width AFTER att.
	 *	 3: Has nulls or var-widths BEFORE att.
478 479
	 * ----------------
	 */
480

481 482
	attnum--;

483
	if (!HeapTupleNoNulls(tuple))
484 485 486
	{
		/*
		 * there's a null somewhere in the tuple
487
		 *
488
		 * check to see if any preceding bits are null...
489
		 */
490
		int			byte = attnum >> 3;
491
		int			finalbit = attnum & 0x07;
492

493 494 495 496
		/* check for nulls "before" final bit of last byte */
		if ((~bp[byte]) & ((1 << finalbit) - 1))
			slow = true;
		else
497
		{
498 499
			/* check for nulls in any "earlier" bytes */
			int			i;
500

501
			for (i = 0; i < byte; i++)
502
			{
503
				if (bp[i] != 0xFF)
504
				{
505 506
					slow = true;
					break;
507
				}
508 509
			}
		}
510
	}
511

512 513
	tp = (char *) tup + tup->t_hoff;

514 515
	if (!slow)
	{
516 517
		Form_pg_attribute att;

518 519 520 521
		/*
		 * If we get here, there are no nulls up to and including the target
		 * attribute.  If we have a cached offset, we can use it.
		 */
522 523 524
		att = TupleDescAttr(tupleDesc, attnum);
		if (att->attcacheoff >= 0)
			return fetchatt(att, tp + att->attcacheoff);
525 526 527

		/*
		 * Otherwise, check for non-fixed-length attrs up to and including
Bruce Momjian's avatar
Bruce Momjian committed
528
		 * target.  If there aren't any, it's safe to cheaply initialize the
Bruce Momjian's avatar
Bruce Momjian committed
529
		 * cached offsets for these attrs.
530 531
		 */
		if (HeapTupleHasVarWidth(tuple))
532
		{
533
			int			j;
Bruce Momjian's avatar
Bruce Momjian committed
534

535 536
			for (j = 0; j <= attnum; j++)
			{
537
				if (TupleDescAttr(tupleDesc, j)->attlen <= 0)
538
				{
539
					slow = true;
540 541 542
					break;
				}
			}
543 544
		}
	}
545 546 547

	if (!slow)
	{
548
		int			natts = tupleDesc->natts;
549
		int			j = 1;
550 551

		/*
552 553 554 555 556 557 558
		 * If we get here, we have a tuple with no nulls or var-widths up to
		 * and including the target attribute, so we can use the cached offset
		 * ... only we don't have it yet, or we'd not have got here.  Since
		 * it's cheap to compute offsets for fixed-width columns, we take the
		 * opportunity to initialize the cached offsets for *all* the leading
		 * fixed-width columns, in hope of avoiding future visits to this
		 * routine.
559
		 */
560
		TupleDescAttr(tupleDesc, 0)->attcacheoff = 0;
561

562
		/* we might have set some offsets in the slow path previously */
563
		while (j < natts && TupleDescAttr(tupleDesc, j)->attcacheoff > 0)
564 565
			j++;

566 567
		off = TupleDescAttr(tupleDesc, j - 1)->attcacheoff +
			TupleDescAttr(tupleDesc, j - 1)->attlen;
568

569
		for (; j < natts; j++)
570
		{
571 572 573
			Form_pg_attribute att = TupleDescAttr(tupleDesc, j);

			if (att->attlen <= 0)
574 575
				break;

576
			off = att_align_nominal(off, att->attalign);
577

578
			att->attcacheoff = off;
579

580
			off += att->attlen;
581
		}
582

583 584
		Assert(j > attnum);

585
		off = TupleDescAttr(tupleDesc, attnum)->attcacheoff;
586
	}
587 588
	else
	{
589 590
		bool		usecache = true;
		int			i;
591 592

		/*
Bruce Momjian's avatar
Bruce Momjian committed
593 594
		 * Now we know that we have to walk the tuple CAREFULLY.  But we still
		 * might be able to cache some offsets for next time.
595
		 *
596 597
		 * Note - This loop is a little tricky.  For each non-null attribute,
		 * we have to first account for alignment padding before the attr,
Bruce Momjian's avatar
Bruce Momjian committed
598
		 * then advance over the attr based on its length.  Nulls have no
599
		 * storage and no alignment padding either.  We can use/set
600
		 * attcacheoff until we reach either a null or a var-width attribute.
601
		 */
602
		off = 0;
Bruce Momjian's avatar
Bruce Momjian committed
603
		for (i = 0;; i++)		/* loop exit is at "break" */
604
		{
605 606
			Form_pg_attribute att = TupleDescAttr(tupleDesc, i);

607
			if (HeapTupleHasNulls(tuple) && att_isnull(i, bp))
608
			{
609
				usecache = false;
Bruce Momjian's avatar
Bruce Momjian committed
610
				continue;		/* this cannot be the target att */
611
			}
612

613
			/* If we know the next offset, we can skip the rest */
614 615 616
			if (usecache && att->attcacheoff >= 0)
				off = att->attcacheoff;
			else if (att->attlen == -1)
617 618
			{
				/*
Bruce Momjian's avatar
Bruce Momjian committed
619 620 621 622
				 * We can only cache the offset for a varlena attribute if the
				 * offset is already suitably aligned, so that there would be
				 * no pad bytes in any case: then the offset will be valid for
				 * either an aligned or unaligned value.
623 624
				 */
				if (usecache &&
625 626
					off == att_align_nominal(off, att->attalign))
					att->attcacheoff = off;
627 628
				else
				{
629
					off = att_align_pointer(off, att->attalign, -1,
630 631 632 633
											tp + off);
					usecache = false;
				}
			}
634 635
			else
			{
636
				/* not varlena, so safe to use att_align_nominal */
637
				off = att_align_nominal(off, att->attalign);
638

639
				if (usecache)
640
					att->attcacheoff = off;
641 642
			}

643 644 645
			if (i == attnum)
				break;

646
			off = att_addlength_pointer(off, att->attlen, tp + off);
647

648
			if (usecache && att->attlen <= 0)
649
				usecache = false;
650
		}
651
	}
652

653
	return fetchatt(TupleDescAttr(tupleDesc, attnum), tp + off);
654 655
}

656 657 658 659 660 661 662 663 664 665
/* ----------------
 *		heap_getsysattr
 *
 *		Fetch the value of a system attribute for a tuple.
 *
 * This is a support routine for the heap_getattr macro.  The macro
 * has already determined that the attnum refers to a system attribute.
 * ----------------
 */
Datum
666
heap_getsysattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
667 668 669 670 671 672
{
	Datum		result;

	Assert(tup);

	/* Currently, no sys attribute ever reads as NULL. */
673
	*isnull = false;
674 675 676 677 678 679 680 681

	switch (attnum)
	{
		case SelfItemPointerAttributeNumber:
			/* pass-by-reference datatype */
			result = PointerGetDatum(&(tup->t_self));
			break;
		case ObjectIdAttributeNumber:
682
			result = ObjectIdGetDatum(HeapTupleGetOid(tup));
683 684
			break;
		case MinTransactionIdAttributeNumber:
685
			result = TransactionIdGetDatum(HeapTupleHeaderGetRawXmin(tup->t_data));
686 687
			break;
		case MaxTransactionIdAttributeNumber:
688
			result = TransactionIdGetDatum(HeapTupleHeaderGetRawXmax(tup->t_data));
689
			break;
690
		case MinCommandIdAttributeNumber:
691
		case MaxCommandIdAttributeNumber:
Bruce Momjian's avatar
Bruce Momjian committed
692

693
			/*
Bruce Momjian's avatar
Bruce Momjian committed
694
			 * cmin and cmax are now both aliases for the same field, which
Bruce Momjian's avatar
Bruce Momjian committed
695
			 * can in fact also be a combo command id.  XXX perhaps we should
Bruce Momjian's avatar
Bruce Momjian committed
696 697
			 * return the "real" cmin or cmax if possible, that is if we are
			 * inside the originating transaction?
698 699
			 */
			result = CommandIdGetDatum(HeapTupleHeaderGetRawCommandId(tup->t_data));
700 701 702 703 704
			break;
		case TableOidAttributeNumber:
			result = ObjectIdGetDatum(tup->t_tableOid);
			break;
		default:
705
			elog(ERROR, "invalid attnum: %d", attnum);
706 707 708 709 710 711
			result = 0;			/* keep compiler quiet */
			break;
	}
	return result;
}

712
/* ----------------
713
 *		heap_copytuple
714
 *
715
 *		returns a copy of an entire tuple
716 717 718
 *
 * The HeapTuple struct, tuple header, and tuple data are all allocated
 * as a single palloc() block.
719 720 721 722 723
 * ----------------
 */
HeapTuple
heap_copytuple(HeapTuple tuple)
{
724
	HeapTuple	newTuple;
725

726
	if (!HeapTupleIsValid(tuple) || tuple->t_data == NULL)
727
		return NULL;
728

729 730 731
	newTuple = (HeapTuple) palloc(HEAPTUPLESIZE + tuple->t_len);
	newTuple->t_len = tuple->t_len;
	newTuple->t_self = tuple->t_self;
732
	newTuple->t_tableOid = tuple->t_tableOid;
733
	newTuple->t_data = (HeapTupleHeader) ((char *) newTuple + HEAPTUPLESIZE);
734
	memcpy((char *) newTuple->t_data, (char *) tuple->t_data, tuple->t_len);
735
	return newTuple;
736 737
}

738 739 740
/* ----------------
 *		heap_copytuple_with_tuple
 *
741
 *		copy a tuple into a caller-supplied HeapTuple management struct
742 743 744
 *
 * Note that after calling this function, the "dest" HeapTuple will not be
 * allocated as a single palloc() block (unlike with heap_copytuple()).
745 746 747 748 749 750 751 752 753 754
 * ----------------
 */
void
heap_copytuple_with_tuple(HeapTuple src, HeapTuple dest)
{
	if (!HeapTupleIsValid(src) || src->t_data == NULL)
	{
		dest->t_data = NULL;
		return;
	}
Bruce Momjian's avatar
Bruce Momjian committed
755

756 757
	dest->t_len = src->t_len;
	dest->t_self = src->t_self;
758
	dest->t_tableOid = src->t_tableOid;
759
	dest->t_data = (HeapTupleHeader) palloc(src->t_len);
760
	memcpy((char *) dest->t_data, (char *) src->t_data, src->t_len);
761 762
}

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
/*
 * Expand a tuple which has less attributes than required. For each attribute
 * not present in the sourceTuple, if there is a missing value that will be
 * used. Otherwise the attribute will be set to NULL.
 *
 * The source tuple must have less attributes than the required number.
 *
 * Only one of targetHeapTuple and targetMinimalTuple may be supplied. The
 * other argument must be NULL.
 */
static void
expand_tuple(HeapTuple *targetHeapTuple,
			 MinimalTuple *targetMinimalTuple,
			 HeapTuple sourceTuple,
			 TupleDesc tupleDesc)
{
	AttrMissing *attrmiss = NULL;
	int			attnum;
	int			firstmissingnum = 0;
	bool		hasNulls = HeapTupleHasNulls(sourceTuple);
	HeapTupleHeader targetTHeader;
	HeapTupleHeader sourceTHeader = sourceTuple->t_data;
	int			sourceNatts = HeapTupleHeaderGetNatts(sourceTHeader);
	int			natts = tupleDesc->natts;
	int			sourceNullLen;
	int			targetNullLen;
	Size		sourceDataLen = sourceTuple->t_len - sourceTHeader->t_hoff;
	Size		targetDataLen;
	Size		len;
	int			hoff;
	bits8	   *nullBits = NULL;
	int			bitMask = 0;
	char	   *targetData;
	uint16	   *infoMask;

	Assert((targetHeapTuple && !targetMinimalTuple)
		   || (!targetHeapTuple && targetMinimalTuple));

	Assert(sourceNatts < natts);

	sourceNullLen = (hasNulls ? BITMAPLEN(sourceNatts) : 0);

	targetDataLen = sourceDataLen;

	if (tupleDesc->constr &&
		tupleDesc->constr->missing)
	{
		/*
		 * If there are missing values we want to put them into the tuple.
		 * Before that we have to compute the extra length for the values
		 * array and the variable length data.
		 */
		attrmiss = tupleDesc->constr->missing;

		/*
		 * Find the first item in attrmiss for which we don't have a value in
		 * the source. We can ignore all the missing entries before that.
		 */
		for (firstmissingnum = sourceNatts;
			 firstmissingnum < natts;
			 firstmissingnum++)
		{
			if (attrmiss[firstmissingnum].ammissingPresent)
				break;
		}

		/*
		 * If there are no more missing values everything else must be NULL
		 */
		if (firstmissingnum >= natts)
		{
			hasNulls = true;
		}
		else
		{

			/*
			 * Now walk the missing attributes. If there is a missing value
			 * make space for it. Otherwise, it's going to be NULL.
			 */
			for (attnum = firstmissingnum;
				 attnum < natts;
				 attnum++)
			{
				if (attrmiss[attnum].ammissingPresent)
				{
					Form_pg_attribute att = TupleDescAttr(tupleDesc, attnum);

					targetDataLen = att_align_datum(targetDataLen,
													att->attalign,
													att->attlen,
													attrmiss[attnum].ammissing);

					targetDataLen = att_addlength_pointer(targetDataLen,
														  att->attlen,
														  attrmiss[attnum].ammissing);
				}
				else
				{
					/* no missing value, so it must be null */
					hasNulls = true;
				}
			}
		}
	}							/* end if have missing values */
	else
	{
		/*
		 * If there are no missing values at all then NULLS must be allowed,
		 * since some of the attributes are known to be absent.
		 */
		hasNulls = true;
	}

	len = 0;

	if (hasNulls)
	{
		targetNullLen = BITMAPLEN(natts);
		len += targetNullLen;
	}
	else
		targetNullLen = 0;

	if (tupleDesc->tdhasoid)
		len += sizeof(Oid);

	/*
	 * Allocate and zero the space needed.  Note that the tuple body and
	 * HeapTupleData management structure are allocated in one chunk.
	 */
	if (targetHeapTuple)
	{
		len += offsetof(HeapTupleHeaderData, t_bits);
		hoff = len = MAXALIGN(len); /* align user data safely */
		len += targetDataLen;

		*targetHeapTuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
		(*targetHeapTuple)->t_data
			= targetTHeader
			= (HeapTupleHeader) ((char *) *targetHeapTuple + HEAPTUPLESIZE);
		(*targetHeapTuple)->t_len = len;
		(*targetHeapTuple)->t_tableOid = sourceTuple->t_tableOid;
		ItemPointerSetInvalid(&((*targetHeapTuple)->t_self));

		targetTHeader->t_infomask = sourceTHeader->t_infomask;
		targetTHeader->t_hoff = hoff;
		HeapTupleHeaderSetNatts(targetTHeader, natts);
		HeapTupleHeaderSetDatumLength(targetTHeader, len);
		HeapTupleHeaderSetTypeId(targetTHeader, tupleDesc->tdtypeid);
		HeapTupleHeaderSetTypMod(targetTHeader, tupleDesc->tdtypmod);
		/* We also make sure that t_ctid is invalid unless explicitly set */
		ItemPointerSetInvalid(&(targetTHeader->t_ctid));
		if (targetNullLen > 0)
			nullBits = (bits8 *) ((char *) (*targetHeapTuple)->t_data
								  + offsetof(HeapTupleHeaderData, t_bits));
		targetData = (char *) (*targetHeapTuple)->t_data + hoff;
		infoMask = &(targetTHeader->t_infomask);
	}
	else
	{
		len += SizeofMinimalTupleHeader;
		hoff = len = MAXALIGN(len); /* align user data safely */
		len += targetDataLen;

		*targetMinimalTuple = (MinimalTuple) palloc0(len);
		(*targetMinimalTuple)->t_len = len;
		(*targetMinimalTuple)->t_hoff = hoff + MINIMAL_TUPLE_OFFSET;
		(*targetMinimalTuple)->t_infomask = sourceTHeader->t_infomask;
		/* Same macro works for MinimalTuples */
		HeapTupleHeaderSetNatts(*targetMinimalTuple, natts);
		if (targetNullLen > 0)
			nullBits = (bits8 *) ((char *) *targetMinimalTuple
								  + offsetof(MinimalTupleData, t_bits));
		targetData = (char *) *targetMinimalTuple + hoff;
		infoMask = &((*targetMinimalTuple)->t_infomask);
	}

	if (targetNullLen > 0)
	{
		if (sourceNullLen > 0)
		{
			/* if bitmap pre-existed copy in - all is set */
			memcpy(nullBits,
				   ((char *) sourceTHeader)
				   + offsetof(HeapTupleHeaderData, t_bits),
				   sourceNullLen);
			nullBits += sourceNullLen - 1;
		}
		else
		{
			sourceNullLen = BITMAPLEN(sourceNatts);
			/* Set NOT NULL for all existing attributes */
			memset(nullBits, 0xff, sourceNullLen);

			nullBits += sourceNullLen - 1;

			if (sourceNatts & 0x07)
			{
				/* build the mask (inverted!) */
				bitMask = 0xff << (sourceNatts & 0x07);
				/* Voila */
				*nullBits = ~bitMask;
			}
		}

		bitMask = (1 << ((sourceNatts - 1) & 0x07));
	}							/* End if have null bitmap */

	memcpy(targetData,
		   ((char *) sourceTuple->t_data) + sourceTHeader->t_hoff,
		   sourceDataLen);

	targetData += sourceDataLen;

	/* Now fill in the missing values */
	for (attnum = sourceNatts; attnum < natts; attnum++)
	{

		Form_pg_attribute attr = TupleDescAttr(tupleDesc, attnum);

984
		if (attrmiss && attrmiss[attnum].ammissingPresent)
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
		{
			fill_val(attr,
					 nullBits ? &nullBits : NULL,
					 &bitMask,
					 &targetData,
					 infoMask,
					 attrmiss[attnum].ammissing,
					 false);
		}
		else
		{
			fill_val(attr,
					 &nullBits,
					 &bitMask,
					 &targetData,
					 infoMask,
					 (Datum) 0,
					 true);
		}
	}							/* end loop over missing attributes */
}

/*
 * Fill in the missing values for a minimal HeapTuple
 */
MinimalTuple
minimal_expand_tuple(HeapTuple sourceTuple, TupleDesc tupleDesc)
{
	MinimalTuple minimalTuple;

	expand_tuple(NULL, &minimalTuple, sourceTuple, tupleDesc);
	return minimalTuple;
}

/*
 * Fill in the missing values for an ordinary HeapTuple
 */
HeapTuple
heap_expand_tuple(HeapTuple sourceTuple, TupleDesc tupleDesc)
{
	HeapTuple	heapTuple;

	expand_tuple(&heapTuple, NULL, sourceTuple, tupleDesc);
	return heapTuple;
}

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
/* ----------------
 *		heap_copy_tuple_as_datum
 *
 *		copy a tuple as a composite-type Datum
 * ----------------
 */
Datum
heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
{
	HeapTupleHeader td;

	/*
	 * If the tuple contains any external TOAST pointers, we have to inline
	 * those fields to meet the conventions for composite-type Datums.
	 */
	if (HeapTupleHasExternal(tuple))
		return toast_flatten_tuple_to_datum(tuple->t_data,
											tuple->t_len,
											tupleDesc);

	/*
	 * Fast path for easy case: just make a palloc'd copy and insert the
	 * correct composite-Datum header fields (since those may not be set if
	 * the given tuple came from disk, rather than from heap_form_tuple).
	 */
	td = (HeapTupleHeader) palloc(tuple->t_len);
	memcpy((char *) td, (char *) tuple->t_data, tuple->t_len);

	HeapTupleHeaderSetDatumLength(td, tuple->t_len);
	HeapTupleHeaderSetTypeId(td, tupleDesc->tdtypeid);
	HeapTupleHeaderSetTypMod(td, tupleDesc->tdtypmod);

	return PointerGetDatum(td);
}

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
/*
 * heap_form_tuple
 *		construct a tuple from the given values[] and isnull[] arrays,
 *		which are of the length indicated by tupleDescriptor->natts
 *
 * The result is allocated in the current memory context.
 */
HeapTuple
heap_form_tuple(TupleDesc tupleDescriptor,
				Datum *values,
				bool *isnull)
{
	HeapTuple	tuple;			/* return tuple */
	HeapTupleHeader td;			/* tuple data */
Bruce Momjian's avatar
Bruce Momjian committed
1080 1081
	Size		len,
				data_len;
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
	int			hoff;
	bool		hasnull = false;
	int			numberOfAttributes = tupleDescriptor->natts;
	int			i;

	if (numberOfAttributes > MaxTupleAttributeNumber)
		ereport(ERROR,
				(errcode(ERRCODE_TOO_MANY_COLUMNS),
				 errmsg("number of columns (%d) exceeds limit (%d)",
						numberOfAttributes, MaxTupleAttributeNumber)));

	/*
1094
	 * Check for nulls
1095 1096 1097 1098 1099
	 */
	for (i = 0; i < numberOfAttributes; i++)
	{
		if (isnull[i])
		{
1100 1101
			hasnull = true;
			break;
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
		}
	}

	/*
	 * Determine total space needed
	 */
	len = offsetof(HeapTupleHeaderData, t_bits);

	if (hasnull)
		len += BITMAPLEN(numberOfAttributes);

	if (tupleDescriptor->tdhasoid)
		len += sizeof(Oid);

	hoff = len = MAXALIGN(len); /* align user data safely */

1118 1119 1120
	data_len = heap_compute_data_size(tupleDescriptor, values, isnull);

	len += data_len;
1121 1122

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1123
	 * Allocate and zero the space needed.  Note that the tuple body and
1124 1125
	 * HeapTupleData management structure are allocated in one chunk.
	 */
1126
	tuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
1127 1128 1129
	tuple->t_data = td = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);

	/*
1130
	 * And fill in the information.  Note we fill the Datum fields even though
1131 1132
	 * this tuple may never become a Datum.  This lets HeapTupleHeaderGetDatum
	 * identify the tuple type if needed.
1133 1134 1135 1136 1137 1138 1139 1140
	 */
	tuple->t_len = len;
	ItemPointerSetInvalid(&(tuple->t_self));
	tuple->t_tableOid = InvalidOid;

	HeapTupleHeaderSetDatumLength(td, len);
	HeapTupleHeaderSetTypeId(td, tupleDescriptor->tdtypeid);
	HeapTupleHeaderSetTypMod(td, tupleDescriptor->tdtypmod);
1141 1142
	/* We also make sure that t_ctid is invalid unless explicitly set */
	ItemPointerSetInvalid(&(td->t_ctid));
1143

1144
	HeapTupleHeaderSetNatts(td, numberOfAttributes);
1145 1146
	td->t_hoff = hoff;

Tom Lane's avatar
Tom Lane committed
1147
	if (tupleDescriptor->tdhasoid)	/* else leave infomask = 0 */
1148 1149 1150 1151 1152 1153
		td->t_infomask = HEAP_HASOID;

	heap_fill_tuple(tupleDescriptor,
					values,
					isnull,
					(char *) td + hoff,
1154
					data_len,
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
					&td->t_infomask,
					(hasnull ? td->t_bits : NULL));

	return tuple;
}

/*
 * heap_modify_tuple
 *		form a new tuple from an old tuple and a set of replacement values.
 *
 * The replValues, replIsnull, and doReplace arrays must be of the length
 * indicated by tupleDesc->natts.  The new tuple is constructed using the data
 * from replValues/replIsnull at columns where doReplace is true, and using
 * the data from the old tuple at columns where doReplace is false.
 *
 * The result is allocated in the current memory context.
 */
HeapTuple
heap_modify_tuple(HeapTuple tuple,
				  TupleDesc tupleDesc,
				  Datum *replValues,
				  bool *replIsnull,
				  bool *doReplace)
{
	int			numberOfAttributes = tupleDesc->natts;
	int			attoff;
	Datum	   *values;
	bool	   *isnull;
	HeapTuple	newTuple;

	/*
1186 1187
	 * allocate and fill values and isnull arrays from either the tuple or the
	 * repl information, as appropriate.
1188 1189
	 *
	 * NOTE: it's debatable whether to use heap_deform_tuple() here or just
Heikki Linnakangas's avatar
Heikki Linnakangas committed
1190
	 * heap_getattr() only the non-replaced columns.  The latter could win if
1191 1192 1193 1194
	 * there are many replaced columns and few non-replaced ones. However,
	 * heap_deform_tuple costs only O(N) while the heap_getattr way would cost
	 * O(N^2) if there are many non-replaced columns, so it seems better to
	 * err on the side of linear cost.
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
	 */
	values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
	isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));

	heap_deform_tuple(tuple, tupleDesc, values, isnull);

	for (attoff = 0; attoff < numberOfAttributes; attoff++)
	{
		if (doReplace[attoff])
		{
			values[attoff] = replValues[attoff];
			isnull[attoff] = replIsnull[attoff];
		}
	}

	/*
	 * create a new tuple from the values and isnull arrays
	 */
	newTuple = heap_form_tuple(tupleDesc, values, isnull);

	pfree(values);
	pfree(isnull);

	/*
1219 1220
	 * copy the identification info of the old tuple: t_ctid, t_self, and OID
	 * (if any)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
	 */
	newTuple->t_data->t_ctid = tuple->t_data->t_ctid;
	newTuple->t_self = tuple->t_self;
	newTuple->t_tableOid = tuple->t_tableOid;
	if (tupleDesc->tdhasoid)
		HeapTupleSetOid(newTuple, HeapTupleGetOid(tuple));

	return newTuple;
}

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
/*
 * heap_modify_tuple_by_cols
 *		form a new tuple from an old tuple and a set of replacement values.
 *
 * This is like heap_modify_tuple, except that instead of specifying which
 * column(s) to replace by a boolean map, an array of target column numbers
 * is used.  This is often more convenient when a fixed number of columns
 * are to be replaced.  The replCols, replValues, and replIsnull arrays must
 * be of length nCols.  Target column numbers are indexed from 1.
 *
 * The result is allocated in the current memory context.
 */
HeapTuple
heap_modify_tuple_by_cols(HeapTuple tuple,
						  TupleDesc tupleDesc,
						  int nCols,
						  int *replCols,
						  Datum *replValues,
						  bool *replIsnull)
{
	int			numberOfAttributes = tupleDesc->natts;
	Datum	   *values;
	bool	   *isnull;
	HeapTuple	newTuple;
	int			i;

	/*
	 * allocate and fill values and isnull arrays from the tuple, then replace
	 * selected columns from the input arrays.
	 */
	values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
	isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));

	heap_deform_tuple(tuple, tupleDesc, values, isnull);

	for (i = 0; i < nCols; i++)
	{
		int			attnum = replCols[i];

		if (attnum <= 0 || attnum > numberOfAttributes)
			elog(ERROR, "invalid column number %d", attnum);
		values[attnum - 1] = replValues[i];
		isnull[attnum - 1] = replIsnull[i];
	}

	/*
	 * create a new tuple from the values and isnull arrays
	 */
	newTuple = heap_form_tuple(tupleDesc, values, isnull);

	pfree(values);
	pfree(isnull);

	/*
	 * copy the identification info of the old tuple: t_ctid, t_self, and OID
	 * (if any)
	 */
	newTuple->t_data->t_ctid = tuple->t_data->t_ctid;
	newTuple->t_self = tuple->t_self;
	newTuple->t_tableOid = tuple->t_tableOid;
	if (tupleDesc->tdhasoid)
		HeapTupleSetOid(newTuple, HeapTupleGetOid(tuple));

	return newTuple;
}

1297 1298 1299 1300 1301 1302
/*
 * heap_deform_tuple
 *		Given a tuple, extract data into values/isnull arrays; this is
 *		the inverse of heap_form_tuple.
 *
 *		Storage for the values/isnull arrays is provided by the caller;
1303 1304
 *		it should be sized according to tupleDesc->natts not
 *		HeapTupleHeaderGetNatts(tuple->t_data).
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
 *
 *		Note that for pass-by-reference datatypes, the pointer placed
 *		in the Datum will point into the given tuple.
 *
 *		When all or most of a tuple's fields need to be extracted,
 *		this routine will be significantly quicker than a loop around
 *		heap_getattr; the loop will become O(N^2) as soon as any
 *		noncacheable attribute offsets are involved.
 */
void
heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc,
				  Datum *values, bool *isnull)
{
	HeapTupleHeader tup = tuple->t_data;
	bool		hasnulls = HeapTupleHasNulls(tuple);
	int			tdesc_natts = tupleDesc->natts;
	int			natts;			/* number of atts to extract */
	int			attnum;
	char	   *tp;				/* ptr to tuple data */
1324
	uint32		off;			/* offset in tuple data */
Tom Lane's avatar
Tom Lane committed
1325
	bits8	   *bp = tup->t_bits;	/* ptr to null bitmap in tuple */
1326 1327
	bool		slow = false;	/* can we use/set attcacheoff? */

1328
	natts = HeapTupleHeaderGetNatts(tup);
1329 1330

	/*
1331 1332 1333
	 * In inheritance situations, it is possible that the given tuple actually
	 * has more fields than the caller is expecting.  Don't run off the end of
	 * the caller's arrays.
1334 1335 1336 1337 1338 1339 1340 1341 1342
	 */
	natts = Min(natts, tdesc_natts);

	tp = (char *) tup + tup->t_hoff;

	off = 0;

	for (attnum = 0; attnum < natts; attnum++)
	{
1343
		Form_pg_attribute thisatt = TupleDescAttr(tupleDesc, attnum);
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356

		if (hasnulls && att_isnull(attnum, bp))
		{
			values[attnum] = (Datum) 0;
			isnull[attnum] = true;
			slow = true;		/* can't use attcacheoff anymore */
			continue;
		}

		isnull[attnum] = false;

		if (!slow && thisatt->attcacheoff >= 0)
			off = thisatt->attcacheoff;
1357 1358 1359
		else if (thisatt->attlen == -1)
		{
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1360 1361 1362 1363
			 * We can only cache the offset for a varlena attribute if the
			 * offset is already suitably aligned, so that there would be no
			 * pad bytes in any case: then the offset will be valid for either
			 * an aligned or unaligned value.
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
			 */
			if (!slow &&
				off == att_align_nominal(off, thisatt->attalign))
				thisatt->attcacheoff = off;
			else
			{
				off = att_align_pointer(off, thisatt->attalign, -1,
										tp + off);
				slow = true;
			}
		}
1375 1376
		else
		{
1377 1378
			/* not varlena, so safe to use att_align_nominal */
			off = att_align_nominal(off, thisatt->attalign);
1379 1380 1381 1382 1383 1384 1385

			if (!slow)
				thisatt->attcacheoff = off;
		}

		values[attnum] = fetchatt(thisatt, tp + off);

1386
		off = att_addlength_pointer(off, thisatt->attlen, tp + off);
1387 1388 1389 1390 1391 1392 1393

		if (thisatt->attlen <= 0)
			slow = true;		/* can't use attcacheoff anymore */
	}

	/*
	 * If tuple doesn't have all the atts indicated by tupleDesc, read the
1394
	 * rest as nulls or missing values as appropriate.
1395 1396
	 */
	for (; attnum < tdesc_natts; attnum++)
1397
		values[attnum] = getmissingattr(tupleDesc, attnum + 1, &isnull[attnum]);
1398 1399 1400 1401 1402 1403 1404
}

/*
 * slot_deform_tuple
 *		Given a TupleTableSlot, extract data from the slot's physical tuple
 *		into its Datum/isnull arrays.  Data is extracted up through the
 *		natts'th column (caller must ensure this is a legal column number).
1405
 *
1406
 *		This is essentially an incremental version of heap_deform_tuple:
1407 1408
 *		on each call we extract attributes up to the one needed, without
 *		re-computing information about previously extracted attributes.
1409
 *		slot->tts_nvalid is the number of attributes already extracted.
1410 1411
 */
static void
1412
slot_deform_tuple(TupleTableSlot *slot, int natts)
1413
{
1414 1415
	HeapTuple	tuple = slot->tts_tuple;
	TupleDesc	tupleDesc = slot->tts_tupleDescriptor;
1416 1417
	Datum	   *values = slot->tts_values;
	bool	   *isnull = slot->tts_isnull;
1418
	HeapTupleHeader tup = tuple->t_data;
1419 1420
	bool		hasnulls = HeapTupleHasNulls(tuple);
	int			attnum;
1421
	char	   *tp;				/* ptr to tuple data */
1422
	uint32		off;			/* offset in tuple data */
Tom Lane's avatar
Tom Lane committed
1423
	bits8	   *bp = tup->t_bits;	/* ptr to null bitmap in tuple */
1424
	bool		slow;			/* can we use/set attcacheoff? */
1425 1426

	/*
1427 1428
	 * Check whether the first call for this tuple, and initialize or restore
	 * loop state.
1429
	 */
1430
	attnum = slot->tts_nvalid;
1431 1432 1433 1434 1435 1436 1437 1438 1439
	if (attnum == 0)
	{
		/* Start from the first attribute */
		off = 0;
		slow = false;
	}
	else
	{
		/* Restore state from previous execution */
1440 1441
		off = slot->tts_off;
		slow = slot->tts_slow;
1442 1443 1444 1445 1446 1447
	}

	tp = (char *) tup + tup->t_hoff;

	for (; attnum < natts; attnum++)
	{
1448
		Form_pg_attribute thisatt = TupleDescAttr(tupleDesc, attnum);
1449 1450 1451 1452

		if (hasnulls && att_isnull(attnum, bp))
		{
			values[attnum] = (Datum) 0;
1453
			isnull[attnum] = true;
1454
			slow = true;		/* can't use attcacheoff anymore */
1455 1456 1457
			continue;
		}

1458 1459
		isnull[attnum] = false;

1460 1461
		if (!slow && thisatt->attcacheoff >= 0)
			off = thisatt->attcacheoff;
1462 1463 1464
		else if (thisatt->attlen == -1)
		{
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1465 1466 1467 1468
			 * We can only cache the offset for a varlena attribute if the
			 * offset is already suitably aligned, so that there would be no
			 * pad bytes in any case: then the offset will be valid for either
			 * an aligned or unaligned value.
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
			 */
			if (!slow &&
				off == att_align_nominal(off, thisatt->attalign))
				thisatt->attcacheoff = off;
			else
			{
				off = att_align_pointer(off, thisatt->attalign, -1,
										tp + off);
				slow = true;
			}
		}
1480 1481
		else
		{
1482 1483
			/* not varlena, so safe to use att_align_nominal */
			off = att_align_nominal(off, thisatt->attalign);
1484 1485 1486 1487 1488 1489 1490

			if (!slow)
				thisatt->attcacheoff = off;
		}

		values[attnum] = fetchatt(thisatt, tp + off);

1491
		off = att_addlength_pointer(off, thisatt->attlen, tp + off);
1492 1493

		if (thisatt->attlen <= 0)
1494
			slow = true;		/* can't use attcacheoff anymore */
1495 1496 1497 1498 1499
	}

	/*
	 * Save state for next execution
	 */
1500 1501 1502
	slot->tts_nvalid = attnum;
	slot->tts_off = off;
	slot->tts_slow = slow;
1503 1504
}

1505 1506
/*
 * slot_getattr
1507 1508 1509 1510 1511
 *		This function fetches an attribute of the slot's current tuple.
 *		It is functionally equivalent to heap_getattr, but fetches of
 *		multiple attributes of the same tuple will be optimized better,
 *		because we avoid O(N^2) behavior from multiple calls of
 *		nocachegetattr(), even when attcacheoff isn't usable.
1512 1513 1514 1515
 *
 *		A difference from raw heap_getattr is that attnums beyond the
 *		slot's tupdesc's last attribute will be considered NULL even
 *		when the physical tuple is longer than the tupdesc.
1516 1517 1518 1519
 */
Datum
slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
{
1520 1521 1522
	HeapTuple	tuple = slot->tts_tuple;
	TupleDesc	tupleDesc = slot->tts_tupleDescriptor;
	HeapTupleHeader tup;
1523 1524 1525 1526 1527

	/*
	 * system attributes are handled by heap_getsysattr
	 */
	if (attnum <= 0)
1528 1529 1530
	{
		if (tuple == NULL)		/* internal error */
			elog(ERROR, "cannot extract system attribute from virtual tuple");
Tom Lane's avatar
Tom Lane committed
1531
		if (tuple == &(slot->tts_minhdr))	/* internal error */
1532
			elog(ERROR, "cannot extract system attribute from minimal tuple");
1533
		return heap_getsysattr(tuple, attnum, tupleDesc, isnull);
1534
	}
1535 1536

	/*
1537
	 * fast path if desired attribute already cached
1538
	 */
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	if (attnum <= slot->tts_nvalid)
	{
		*isnull = slot->tts_isnull[attnum - 1];
		return slot->tts_values[attnum - 1];
	}

	/*
	 * return NULL if attnum is out of range according to the tupdesc
	 */
	if (attnum > tupleDesc->natts)
	{
		*isnull = true;
		return (Datum) 0;
	}
1553

1554
	/*
1555 1556
	 * otherwise we had better have a physical tuple (tts_nvalid should equal
	 * natts in all virtual-tuple cases)
1557
	 */
1558
	if (tuple == NULL)			/* internal error */
1559 1560 1561
		elog(ERROR, "cannot extract attribute from empty tuple slot");

	/*
1562 1563
	 * return NULL or missing value if attnum is out of range according to the
	 * tuple
1564
	 *
1565 1566 1567
	 * (We have to check this separately because of various inheritance and
	 * table-alteration scenarios: the tuple could be either longer or shorter
	 * than the tupdesc.)
1568 1569
	 */
	tup = tuple->t_data;
1570
	if (attnum > HeapTupleHeaderGetNatts(tup))
1571
		return getmissingattr(slot->tts_tupleDescriptor, attnum, isnull);
1572 1573

	/*
1574
	 * check if target attribute is null: no point in groveling through tuple
1575 1576 1577 1578 1579 1580 1581 1582
	 */
	if (HeapTupleHasNulls(tuple) && att_isnull(attnum - 1, tup->t_bits))
	{
		*isnull = true;
		return (Datum) 0;
	}

	/*
1583 1584 1585
	 * If the attribute's column has been dropped, we force a NULL result.
	 * This case should not happen in normal use, but it could happen if we
	 * are executing a plan cached before the column was dropped.
1586
	 */
1587
	if (TupleDescAttr(tupleDesc, attnum - 1)->attisdropped)
1588 1589 1590 1591 1592 1593
	{
		*isnull = true;
		return (Datum) 0;
	}

	/*
1594
	 * Extract the attribute, along with any preceding attributes.
1595
	 */
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
	slot_deform_tuple(slot, attnum);

	/*
	 * The result is acquired from tts_values array.
	 */
	*isnull = slot->tts_isnull[attnum - 1];
	return slot->tts_values[attnum - 1];
}

/*
 * slot_getallattrs
 *		This function forces all the entries of the slot's Datum/isnull
 *		arrays to be valid.  The caller may then extract data directly
 *		from those arrays instead of using slot_getattr.
 */
void
slot_getallattrs(TupleTableSlot *slot)
{
	int			tdesc_natts = slot->tts_tupleDescriptor->natts;
	int			attnum;
	HeapTuple	tuple;

	/* Quick out if we have 'em all already */
	if (slot->tts_nvalid == tdesc_natts)
		return;

	/*
1623 1624
	 * otherwise we had better have a physical tuple (tts_nvalid should equal
	 * natts in all virtual-tuple cases)
1625 1626
	 */
	tuple = slot->tts_tuple;
1627
	if (tuple == NULL)			/* internal error */
1628 1629 1630 1631 1632
		elog(ERROR, "cannot extract attribute from empty tuple slot");

	/*
	 * load up any slots available from physical tuple
	 */
1633
	attnum = HeapTupleHeaderGetNatts(tuple->t_data);
1634 1635 1636 1637
	attnum = Min(attnum, tdesc_natts);

	slot_deform_tuple(slot, attnum);

1638 1639
	attnum = slot->tts_nvalid;

1640 1641
	/*
	 * If tuple doesn't have all the atts indicated by tupleDesc, read the
1642
	 * rest as NULLS or missing values.
1643
	 */
1644 1645 1646
	if (attnum < tdesc_natts)
		slot_getmissingattrs(slot, attnum, tdesc_natts);

1647 1648
	slot->tts_nvalid = tdesc_natts;
}
1649

1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
/*
 * slot_getsomeattrs
 *		This function forces the entries of the slot's Datum/isnull
 *		arrays to be valid at least up through the attnum'th entry.
 */
void
slot_getsomeattrs(TupleTableSlot *slot, int attnum)
{
	HeapTuple	tuple;
	int			attno;

	/* Quick out if we have 'em all already */
	if (slot->tts_nvalid >= attnum)
		return;

	/* Check for caller error */
	if (attnum <= 0 || attnum > slot->tts_tupleDescriptor->natts)
		elog(ERROR, "invalid attribute number %d", attnum);

	/*
1670 1671
	 * otherwise we had better have a physical tuple (tts_nvalid should equal
	 * natts in all virtual-tuple cases)
1672 1673
	 */
	tuple = slot->tts_tuple;
1674
	if (tuple == NULL)			/* internal error */
1675 1676 1677 1678 1679
		elog(ERROR, "cannot extract attribute from empty tuple slot");

	/*
	 * load up any slots available from physical tuple
	 */
1680
	attno = HeapTupleHeaderGetNatts(tuple->t_data);
1681 1682 1683 1684
	attno = Min(attno, attnum);

	slot_deform_tuple(slot, attno);

1685 1686
	attno = slot->tts_nvalid;

1687
	/*
1688
	 * If tuple doesn't have all the atts indicated by attnum, read the
1689
	 * rest as NULLs or missing values
1690
	 */
1691 1692 1693
	if (attno < attnum)
		slot_getmissingattrs(slot, attno, attnum);

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
	slot->tts_nvalid = attnum;
}

/*
 * slot_attisnull
 *		Detect whether an attribute of the slot is null, without
 *		actually fetching it.
 */
bool
slot_attisnull(TupleTableSlot *slot, int attnum)
{
1705 1706
	HeapTuple	tuple = slot->tts_tuple;
	TupleDesc	tupleDesc = slot->tts_tupleDescriptor;
1707 1708

	/*
1709
	 * system attributes are handled by heap_attisnull
1710
	 */
1711 1712 1713 1714
	if (attnum <= 0)
	{
		if (tuple == NULL)		/* internal error */
			elog(ERROR, "cannot extract system attribute from virtual tuple");
Tom Lane's avatar
Tom Lane committed
1715
		if (tuple == &(slot->tts_minhdr))	/* internal error */
1716
			elog(ERROR, "cannot extract system attribute from minimal tuple");
1717
		return heap_attisnull(tuple, attnum, tupleDesc);
1718 1719 1720 1721 1722 1723 1724 1725 1726
	}

	/*
	 * fast path if desired attribute already cached
	 */
	if (attnum <= slot->tts_nvalid)
		return slot->tts_isnull[attnum - 1];

	/*
1727
	 * return NULL if attnum is out of range according to the tupdesc
1728 1729 1730 1731 1732
	 */
	if (attnum > tupleDesc->natts)
		return true;

	/*
1733 1734
	 * otherwise we had better have a physical tuple (tts_nvalid should equal
	 * natts in all virtual-tuple cases)
1735
	 */
1736
	if (tuple == NULL)			/* internal error */
1737 1738 1739
		elog(ERROR, "cannot extract attribute from empty tuple slot");

	/* and let the tuple tell it */
1740
	return heap_attisnull(tuple, attnum, tupleDesc);
1741 1742
}

1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
/*
 * slot_getsysattr
 *		This function fetches a system attribute of the slot's current tuple.
 *		Unlike slot_getattr, if the slot does not contain system attributes,
 *		this will return false (with a NULL attribute value) instead of
 *		throwing an error.
 */
bool
slot_getsysattr(TupleTableSlot *slot, int attnum,
				Datum *value, bool *isnull)
{
	HeapTuple	tuple = slot->tts_tuple;

	Assert(attnum < 0);			/* else caller error */
	if (tuple == NULL ||
		tuple == &(slot->tts_minhdr))
	{
		/* No physical tuple, or minimal tuple, so fail */
		*value = (Datum) 0;
		*isnull = true;
		return false;
	}
	*value = heap_getsysattr(tuple, attnum, slot->tts_tupleDescriptor, isnull);
	return true;
}

1769 1770
/*
 * heap_freetuple
1771 1772 1773 1774 1775 1776 1777 1778
 */
void
heap_freetuple(HeapTuple htup)
{
	pfree(htup);
}


1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
/*
 * heap_form_minimal_tuple
 *		construct a MinimalTuple from the given values[] and isnull[] arrays,
 *		which are of the length indicated by tupleDescriptor->natts
 *
 * This is exactly like heap_form_tuple() except that the result is a
 * "minimal" tuple lacking a HeapTupleData header as well as room for system
 * columns.
 *
 * The result is allocated in the current memory context.
 */
MinimalTuple
heap_form_minimal_tuple(TupleDesc tupleDescriptor,
						Datum *values,
						bool *isnull)
{
	MinimalTuple tuple;			/* return tuple */
Bruce Momjian's avatar
Bruce Momjian committed
1796 1797
	Size		len,
				data_len;
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
	int			hoff;
	bool		hasnull = false;
	int			numberOfAttributes = tupleDescriptor->natts;
	int			i;

	if (numberOfAttributes > MaxTupleAttributeNumber)
		ereport(ERROR,
				(errcode(ERRCODE_TOO_MANY_COLUMNS),
				 errmsg("number of columns (%d) exceeds limit (%d)",
						numberOfAttributes, MaxTupleAttributeNumber)));

	/*
1810
	 * Check for nulls
1811 1812 1813 1814 1815
	 */
	for (i = 0; i < numberOfAttributes; i++)
	{
		if (isnull[i])
		{
1816 1817
			hasnull = true;
			break;
1818 1819 1820 1821 1822 1823
		}
	}

	/*
	 * Determine total space needed
	 */
1824
	len = SizeofMinimalTupleHeader;
1825 1826 1827 1828 1829 1830 1831 1832 1833

	if (hasnull)
		len += BITMAPLEN(numberOfAttributes);

	if (tupleDescriptor->tdhasoid)
		len += sizeof(Oid);

	hoff = len = MAXALIGN(len); /* align user data safely */

1834 1835 1836
	data_len = heap_compute_data_size(tupleDescriptor, values, isnull);

	len += data_len;
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846

	/*
	 * Allocate and zero the space needed.
	 */
	tuple = (MinimalTuple) palloc0(len);

	/*
	 * And fill in the information.
	 */
	tuple->t_len = len;
1847
	HeapTupleHeaderSetNatts(tuple, numberOfAttributes);
1848 1849
	tuple->t_hoff = hoff + MINIMAL_TUPLE_OFFSET;

Tom Lane's avatar
Tom Lane committed
1850
	if (tupleDescriptor->tdhasoid)	/* else leave infomask = 0 */
1851 1852 1853 1854 1855 1856
		tuple->t_infomask = HEAP_HASOID;

	heap_fill_tuple(tupleDescriptor,
					values,
					isnull,
					(char *) tuple + hoff,
1857
					data_len,
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
					&tuple->t_infomask,
					(hasnull ? tuple->t_bits : NULL));

	return tuple;
}

/*
 * heap_free_minimal_tuple
 */
void
heap_free_minimal_tuple(MinimalTuple mtup)
{
	pfree(mtup);
}

/*
 * heap_copy_minimal_tuple
 *		copy a MinimalTuple
 *
 * The result is allocated in the current memory context.
 */
MinimalTuple
heap_copy_minimal_tuple(MinimalTuple mtup)
{
	MinimalTuple result;

	result = (MinimalTuple) palloc(mtup->t_len);
	memcpy(result, mtup, mtup->t_len);
	return result;
}

/*
 * heap_tuple_from_minimal_tuple
 *		create a HeapTuple by copying from a MinimalTuple;
 *		system columns are filled with zeroes
 *
 * The result is allocated in the current memory context.
 * The HeapTuple struct, tuple header, and tuple data are all allocated
 * as a single palloc() block.
 */
HeapTuple
heap_tuple_from_minimal_tuple(MinimalTuple mtup)
{
	HeapTuple	result;
	uint32		len = mtup->t_len + MINIMAL_TUPLE_OFFSET;

	result = (HeapTuple) palloc(HEAPTUPLESIZE + len);
	result->t_len = len;
	ItemPointerSetInvalid(&(result->t_self));
	result->t_tableOid = InvalidOid;
	result->t_data = (HeapTupleHeader) ((char *) result + HEAPTUPLESIZE);
	memcpy((char *) result->t_data + MINIMAL_TUPLE_OFFSET, mtup, mtup->t_len);
1910
	memset(result->t_data, 0, offsetof(HeapTupleHeaderData, t_infomask2));
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
	return result;
}

/*
 * minimal_tuple_from_heap_tuple
 *		create a MinimalTuple by copying from a HeapTuple
 *
 * The result is allocated in the current memory context.
 */
MinimalTuple
minimal_tuple_from_heap_tuple(HeapTuple htup)
{
	MinimalTuple result;
	uint32		len;

	Assert(htup->t_len > MINIMAL_TUPLE_OFFSET);
	len = htup->t_len - MINIMAL_TUPLE_OFFSET;
	result = (MinimalTuple) palloc(len);
	memcpy(result, (char *) htup->t_data + MINIMAL_TUPLE_OFFSET, len);
	result->t_len = len;
	return result;
}
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

/*
 * This mainly exists so JIT can inline the definition, but it's also
 * sometimes useful in debugging sessions.
 */
size_t
varsize_any(void *p)
{
	return VARSIZE_ANY(p);
}