]> granicus.if.org Git - postgresql/blob - src/backend/access/common/heaptuple.c
Add FILLFACTOR to CREATE INDEX.
[postgresql] / src / backend / access / common / heaptuple.c
1 /*-------------------------------------------------------------------------
2  *
3  * heaptuple.c
4  *        This file contains heap tuple accessor and mutator routines, as well
5  *        as various tuple utilities.
6  *
7  * NOTE: there is massive duplication of code in this module to
8  * support both the convention that a null is marked by a bool TRUE,
9  * and the convention that a null is marked by a char 'n'.      The latter
10  * convention is deprecated but it'll probably be a long time before
11  * we can get rid of it entirely.
12  *
13  *
14  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
15  * Portions Copyright (c) 1994, Regents of the University of California
16  *
17  *
18  * IDENTIFICATION
19  *        $PostgreSQL: pgsql/src/backend/access/common/heaptuple.c,v 1.108 2006/07/02 02:23:18 momjian Exp $
20  *
21  *-------------------------------------------------------------------------
22  */
23
24 #include "postgres.h"
25
26 #include "access/heapam.h"
27 #include "access/tuptoaster.h"
28 #include "catalog/pg_type.h"
29 #include "executor/tuptable.h"
30
31
32 /* ----------------------------------------------------------------
33  *                                              misc support routines
34  * ----------------------------------------------------------------
35  */
36
37 /*
38  * heap_compute_data_size
39  *              Determine size of the data area of a tuple to be constructed
40  */
41 Size
42 heap_compute_data_size(TupleDesc tupleDesc,
43                                            Datum *values,
44                                            bool *isnull)
45 {
46         Size            data_length = 0;
47         int                     i;
48         int                     numberOfAttributes = tupleDesc->natts;
49         Form_pg_attribute *att = tupleDesc->attrs;
50
51         for (i = 0; i < numberOfAttributes; i++)
52         {
53                 if (isnull[i])
54                         continue;
55
56                 data_length = att_align(data_length, att[i]->attalign);
57                 data_length = att_addlength(data_length, att[i]->attlen, values[i]);
58         }
59
60         return data_length;
61 }
62
63 /* ----------------
64  *              ComputeDataSize
65  *
66  * Determine size of the data area of a tuple to be constructed
67  *
68  * OLD API with char 'n'/' ' convention for indicating nulls
69  * ----------------
70  */
71 static Size
72 ComputeDataSize(TupleDesc tupleDesc,
73                                 Datum *values,
74                                 char *nulls)
75 {
76         Size            data_length = 0;
77         int                     i;
78         int                     numberOfAttributes = tupleDesc->natts;
79         Form_pg_attribute *att = tupleDesc->attrs;
80
81         for (i = 0; i < numberOfAttributes; i++)
82         {
83                 if (nulls[i] != ' ')
84                         continue;
85
86                 data_length = att_align(data_length, att[i]->attalign);
87                 data_length = att_addlength(data_length, att[i]->attlen, values[i]);
88         }
89
90         return data_length;
91 }
92
93 /*
94  * heap_fill_tuple
95  *              Load data portion of a tuple from values/isnull arrays
96  *
97  * We also fill the null bitmap (if any) and set the infomask bits
98  * that reflect the tuple's data contents.
99  */
100 void
101 heap_fill_tuple(TupleDesc tupleDesc,
102                                 Datum *values, bool *isnull,
103                                 char *data, uint16 *infomask, bits8 *bit)
104 {
105         bits8      *bitP;
106         int                     bitmask;
107         int                     i;
108         int                     numberOfAttributes = tupleDesc->natts;
109         Form_pg_attribute *att = tupleDesc->attrs;
110
111         if (bit != NULL)
112         {
113                 bitP = &bit[-1];
114                 bitmask = HIGHBIT;
115         }
116         else
117         {
118                 /* just to keep compiler quiet */
119                 bitP = NULL;
120                 bitmask = 0;
121         }
122
123         *infomask &= ~(HEAP_HASNULL | HEAP_HASVARWIDTH | HEAP_HASEXTENDED);
124
125         for (i = 0; i < numberOfAttributes; i++)
126         {
127                 Size            data_length;
128
129                 if (bit != NULL)
130                 {
131                         if (bitmask != HIGHBIT)
132                                 bitmask <<= 1;
133                         else
134                         {
135                                 bitP += 1;
136                                 *bitP = 0x0;
137                                 bitmask = 1;
138                         }
139
140                         if (isnull[i])
141                         {
142                                 *infomask |= HEAP_HASNULL;
143                                 continue;
144                         }
145
146                         *bitP |= bitmask;
147                 }
148
149                 /* XXX we are aligning the pointer itself, not the offset */
150                 data = (char *) att_align((long) data, att[i]->attalign);
151
152                 if (att[i]->attbyval)
153                 {
154                         /* pass-by-value */
155                         store_att_byval(data, values[i], att[i]->attlen);
156                         data_length = att[i]->attlen;
157                 }
158                 else if (att[i]->attlen == -1)
159                 {
160                         /* varlena */
161                         *infomask |= HEAP_HASVARWIDTH;
162                         if (VARATT_IS_EXTERNAL(values[i]))
163                                 *infomask |= HEAP_HASEXTERNAL;
164                         if (VARATT_IS_COMPRESSED(values[i]))
165                                 *infomask |= HEAP_HASCOMPRESSED;
166                         data_length = VARATT_SIZE(DatumGetPointer(values[i]));
167                         memcpy(data, DatumGetPointer(values[i]), data_length);
168                 }
169                 else if (att[i]->attlen == -2)
170                 {
171                         /* cstring */
172                         *infomask |= HEAP_HASVARWIDTH;
173                         data_length = strlen(DatumGetCString(values[i])) + 1;
174                         memcpy(data, DatumGetPointer(values[i]), data_length);
175                 }
176                 else
177                 {
178                         /* fixed-length pass-by-reference */
179                         Assert(att[i]->attlen > 0);
180                         data_length = att[i]->attlen;
181                         memcpy(data, DatumGetPointer(values[i]), data_length);
182                 }
183
184                 data += data_length;
185         }
186 }
187
188 /* ----------------
189  *              DataFill
190  *
191  * Load data portion of a tuple from values/nulls arrays
192  *
193  * OLD API with char 'n'/' ' convention for indicating nulls
194  * ----------------
195  */
196 static void
197 DataFill(char *data,
198                  TupleDesc tupleDesc,
199                  Datum *values,
200                  char *nulls,
201                  uint16 *infomask,
202                  bits8 *bit)
203 {
204         bits8      *bitP;
205         int                     bitmask;
206         int                     i;
207         int                     numberOfAttributes = tupleDesc->natts;
208         Form_pg_attribute *att = tupleDesc->attrs;
209
210         if (bit != NULL)
211         {
212                 bitP = &bit[-1];
213                 bitmask = HIGHBIT;
214         }
215         else
216         {
217                 /* just to keep compiler quiet */
218                 bitP = NULL;
219                 bitmask = 0;
220         }
221
222         *infomask &= ~(HEAP_HASNULL | HEAP_HASVARWIDTH | HEAP_HASEXTENDED);
223
224         for (i = 0; i < numberOfAttributes; i++)
225         {
226                 Size            data_length;
227
228                 if (bit != NULL)
229                 {
230                         if (bitmask != HIGHBIT)
231                                 bitmask <<= 1;
232                         else
233                         {
234                                 bitP += 1;
235                                 *bitP = 0x0;
236                                 bitmask = 1;
237                         }
238
239                         if (nulls[i] == 'n')
240                         {
241                                 *infomask |= HEAP_HASNULL;
242                                 continue;
243                         }
244
245                         *bitP |= bitmask;
246                 }
247
248                 /* XXX we are aligning the pointer itself, not the offset */
249                 data = (char *) att_align((long) data, att[i]->attalign);
250
251                 if (att[i]->attbyval)
252                 {
253                         /* pass-by-value */
254                         store_att_byval(data, values[i], att[i]->attlen);
255                         data_length = att[i]->attlen;
256                 }
257                 else if (att[i]->attlen == -1)
258                 {
259                         /* varlena */
260                         *infomask |= HEAP_HASVARWIDTH;
261                         if (VARATT_IS_EXTERNAL(values[i]))
262                                 *infomask |= HEAP_HASEXTERNAL;
263                         if (VARATT_IS_COMPRESSED(values[i]))
264                                 *infomask |= HEAP_HASCOMPRESSED;
265                         data_length = VARATT_SIZE(DatumGetPointer(values[i]));
266                         memcpy(data, DatumGetPointer(values[i]), data_length);
267                 }
268                 else if (att[i]->attlen == -2)
269                 {
270                         /* cstring */
271                         *infomask |= HEAP_HASVARWIDTH;
272                         data_length = strlen(DatumGetCString(values[i])) + 1;
273                         memcpy(data, DatumGetPointer(values[i]), data_length);
274                 }
275                 else
276                 {
277                         /* fixed-length pass-by-reference */
278                         Assert(att[i]->attlen > 0);
279                         data_length = att[i]->attlen;
280                         memcpy(data, DatumGetPointer(values[i]), data_length);
281                 }
282
283                 data += data_length;
284         }
285 }
286
287 /* ----------------------------------------------------------------
288  *                                              heap tuple interface
289  * ----------------------------------------------------------------
290  */
291
292 /* ----------------
293  *              heap_attisnull  - returns TRUE iff tuple attribute is not present
294  * ----------------
295  */
296 bool
297 heap_attisnull(HeapTuple tup, int attnum)
298 {
299         if (attnum > (int) tup->t_data->t_natts)
300                 return true;
301
302         if (attnum > 0)
303         {
304                 if (HeapTupleNoNulls(tup))
305                         return false;
306                 return att_isnull(attnum - 1, tup->t_data->t_bits);
307         }
308
309         switch (attnum)
310         {
311                 case TableOidAttributeNumber:
312                 case SelfItemPointerAttributeNumber:
313                 case ObjectIdAttributeNumber:
314                 case MinTransactionIdAttributeNumber:
315                 case MinCommandIdAttributeNumber:
316                 case MaxTransactionIdAttributeNumber:
317                 case MaxCommandIdAttributeNumber:
318                         /* these are never null */
319                         break;
320
321                 default:
322                         elog(ERROR, "invalid attnum: %d", attnum);
323         }
324
325         return false;
326 }
327
328 /* ----------------
329  *              nocachegetattr
330  *
331  *              This only gets called from fastgetattr() macro, in cases where
332  *              we can't use a cacheoffset and the value is not null.
333  *
334  *              This caches attribute offsets in the attribute descriptor.
335  *
336  *              An alternate way to speed things up would be to cache offsets
337  *              with the tuple, but that seems more difficult unless you take
338  *              the storage hit of actually putting those offsets into the
339  *              tuple you send to disk.  Yuck.
340  *
341  *              This scheme will be slightly slower than that, but should
342  *              perform well for queries which hit large #'s of tuples.  After
343  *              you cache the offsets once, examining all the other tuples using
344  *              the same attribute descriptor will go much quicker. -cim 5/4/91
345  *
346  *              NOTE: if you need to change this code, see also heap_deform_tuple.
347  * ----------------
348  */
349 Datum
350 nocachegetattr(HeapTuple tuple,
351                            int attnum,
352                            TupleDesc tupleDesc,
353                            bool *isnull)
354 {
355         HeapTupleHeader tup = tuple->t_data;
356         Form_pg_attribute *att = tupleDesc->attrs;
357         char       *tp;                         /* ptr to att in tuple */
358         bits8      *bp = tup->t_bits;           /* ptr to null bitmap in tuple */
359         bool            slow = false;   /* do we have to walk nulls? */
360
361         (void) isnull;                          /* not used */
362 #ifdef IN_MACRO
363 /* This is handled in the macro */
364         Assert(attnum > 0);
365
366         if (isnull)
367                 *isnull = false;
368 #endif
369
370         attnum--;
371
372         /* ----------------
373          *       Three cases:
374          *
375          *       1: No nulls and no variable-width attributes.
376          *       2: Has a null or a var-width AFTER att.
377          *       3: Has nulls or var-widths BEFORE att.
378          * ----------------
379          */
380
381         if (HeapTupleNoNulls(tuple))
382         {
383 #ifdef IN_MACRO
384 /* This is handled in the macro */
385                 if (att[attnum]->attcacheoff != -1)
386                 {
387                         return fetchatt(att[attnum],
388                                                         (char *) tup + tup->t_hoff +
389                                                         att[attnum]->attcacheoff);
390                 }
391 #endif
392         }
393         else
394         {
395                 /*
396                  * there's a null somewhere in the tuple
397                  *
398                  * check to see if desired att is null
399                  */
400
401 #ifdef IN_MACRO
402 /* This is handled in the macro */
403                 if (att_isnull(attnum, bp))
404                 {
405                         if (isnull)
406                                 *isnull = true;
407                         return (Datum) NULL;
408                 }
409 #endif
410
411                 /*
412                  * Now check to see if any preceding bits are null...
413                  */
414                 {
415                         int                     byte = attnum >> 3;
416                         int                     finalbit = attnum & 0x07;
417
418                         /* check for nulls "before" final bit of last byte */
419                         if ((~bp[byte]) & ((1 << finalbit) - 1))
420                                 slow = true;
421                         else
422                         {
423                                 /* check for nulls in any "earlier" bytes */
424                                 int                     i;
425
426                                 for (i = 0; i < byte; i++)
427                                 {
428                                         if (bp[i] != 0xFF)
429                                         {
430                                                 slow = true;
431                                                 break;
432                                         }
433                                 }
434                         }
435                 }
436         }
437
438         tp = (char *) tup + tup->t_hoff;
439
440         /*
441          * now check for any non-fixed length attrs before our attribute
442          */
443         if (!slow)
444         {
445                 if (att[attnum]->attcacheoff != -1)
446                 {
447                         return fetchatt(att[attnum],
448                                                         tp + att[attnum]->attcacheoff);
449                 }
450                 else if (HeapTupleHasVarWidth(tuple))
451                 {
452                         int                     j;
453
454                         /*
455                          * In for(), we test <= and not < because we want to see if we can
456                          * go past it in initializing offsets.
457                          */
458                         for (j = 0; j <= attnum; j++)
459                         {
460                                 if (att[j]->attlen <= 0)
461                                 {
462                                         slow = true;
463                                         break;
464                                 }
465                         }
466                 }
467         }
468
469         /*
470          * If slow is false, and we got here, we know that we have a tuple with no
471          * nulls or var-widths before the target attribute. If possible, we also
472          * want to initialize the remainder of the attribute cached offset values.
473          */
474         if (!slow)
475         {
476                 int                     j = 1;
477                 long            off;
478
479                 /*
480                  * need to set cache for some atts
481                  */
482
483                 att[0]->attcacheoff = 0;
484
485                 while (j < attnum && att[j]->attcacheoff > 0)
486                         j++;
487
488                 off = att[j - 1]->attcacheoff + att[j - 1]->attlen;
489
490                 for (; j <= attnum ||
491                 /* Can we compute more?  We will probably need them */
492                          (j < tup->t_natts &&
493                           att[j]->attcacheoff == -1 &&
494                           (HeapTupleNoNulls(tuple) || !att_isnull(j, bp)) &&
495                           (HeapTupleAllFixed(tuple) || att[j]->attlen > 0)); j++)
496                 {
497                         off = att_align(off, att[j]->attalign);
498
499                         att[j]->attcacheoff = off;
500
501                         off = att_addlength(off, att[j]->attlen, tp + off);
502                 }
503
504                 return fetchatt(att[attnum], tp + att[attnum]->attcacheoff);
505         }
506         else
507         {
508                 bool            usecache = true;
509                 int                     off = 0;
510                 int                     i;
511
512                 /*
513                  * Now we know that we have to walk the tuple CAREFULLY.
514                  *
515                  * Note - This loop is a little tricky.  For each non-null attribute,
516                  * we have to first account for alignment padding before the attr,
517                  * then advance over the attr based on its length.      Nulls have no
518                  * storage and no alignment padding either.  We can use/set
519                  * attcacheoff until we pass either a null or a var-width attribute.
520                  */
521
522                 for (i = 0; i < attnum; i++)
523                 {
524                         if (HeapTupleHasNulls(tuple) && att_isnull(i, bp))
525                         {
526                                 usecache = false;
527                                 continue;
528                         }
529
530                         /* If we know the next offset, we can skip the alignment calc */
531                         if (usecache && att[i]->attcacheoff != -1)
532                                 off = att[i]->attcacheoff;
533                         else
534                         {
535                                 off = att_align(off, att[i]->attalign);
536
537                                 if (usecache)
538                                         att[i]->attcacheoff = off;
539                         }
540
541                         off = att_addlength(off, att[i]->attlen, tp + off);
542
543                         if (usecache && att[i]->attlen <= 0)
544                                 usecache = false;
545                 }
546
547                 off = att_align(off, att[attnum]->attalign);
548
549                 return fetchatt(att[attnum], tp + off);
550         }
551 }
552
553 /* ----------------
554  *              heap_getsysattr
555  *
556  *              Fetch the value of a system attribute for a tuple.
557  *
558  * This is a support routine for the heap_getattr macro.  The macro
559  * has already determined that the attnum refers to a system attribute.
560  * ----------------
561  */
562 Datum
563 heap_getsysattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
564 {
565         Datum           result;
566
567         Assert(tup);
568
569         /* Currently, no sys attribute ever reads as NULL. */
570         if (isnull)
571                 *isnull = false;
572
573         switch (attnum)
574         {
575                 case SelfItemPointerAttributeNumber:
576                         /* pass-by-reference datatype */
577                         result = PointerGetDatum(&(tup->t_self));
578                         break;
579                 case ObjectIdAttributeNumber:
580                         result = ObjectIdGetDatum(HeapTupleGetOid(tup));
581                         break;
582                 case MinTransactionIdAttributeNumber:
583                         result = TransactionIdGetDatum(HeapTupleHeaderGetXmin(tup->t_data));
584                         break;
585                 case MinCommandIdAttributeNumber:
586                         result = CommandIdGetDatum(HeapTupleHeaderGetCmin(tup->t_data));
587                         break;
588                 case MaxTransactionIdAttributeNumber:
589                         result = TransactionIdGetDatum(HeapTupleHeaderGetXmax(tup->t_data));
590                         break;
591                 case MaxCommandIdAttributeNumber:
592                         result = CommandIdGetDatum(HeapTupleHeaderGetCmax(tup->t_data));
593                         break;
594                 case TableOidAttributeNumber:
595                         result = ObjectIdGetDatum(tup->t_tableOid);
596                         break;
597                 default:
598                         elog(ERROR, "invalid attnum: %d", attnum);
599                         result = 0;                     /* keep compiler quiet */
600                         break;
601         }
602         return result;
603 }
604
605 /* ----------------
606  *              heap_copytuple
607  *
608  *              returns a copy of an entire tuple
609  *
610  * The HeapTuple struct, tuple header, and tuple data are all allocated
611  * as a single palloc() block.
612  * ----------------
613  */
614 HeapTuple
615 heap_copytuple(HeapTuple tuple)
616 {
617         HeapTuple       newTuple;
618
619         if (!HeapTupleIsValid(tuple) || tuple->t_data == NULL)
620                 return NULL;
621
622         newTuple = (HeapTuple) palloc(HEAPTUPLESIZE + tuple->t_len);
623         newTuple->t_len = tuple->t_len;
624         newTuple->t_self = tuple->t_self;
625         newTuple->t_tableOid = tuple->t_tableOid;
626         newTuple->t_data = (HeapTupleHeader) ((char *) newTuple + HEAPTUPLESIZE);
627         memcpy((char *) newTuple->t_data, (char *) tuple->t_data, tuple->t_len);
628         return newTuple;
629 }
630
631 /* ----------------
632  *              heap_copytuple_with_tuple
633  *
634  *              copy a tuple into a caller-supplied HeapTuple management struct
635  * ----------------
636  */
637 void
638 heap_copytuple_with_tuple(HeapTuple src, HeapTuple dest)
639 {
640         if (!HeapTupleIsValid(src) || src->t_data == NULL)
641         {
642                 dest->t_data = NULL;
643                 return;
644         }
645
646         dest->t_len = src->t_len;
647         dest->t_self = src->t_self;
648         dest->t_tableOid = src->t_tableOid;
649         dest->t_data = (HeapTupleHeader) palloc(src->t_len);
650         memcpy((char *) dest->t_data, (char *) src->t_data, src->t_len);
651 }
652
653 /*
654  * heap_form_tuple
655  *              construct a tuple from the given values[] and isnull[] arrays,
656  *              which are of the length indicated by tupleDescriptor->natts
657  *
658  * The result is allocated in the current memory context.
659  */
660 HeapTuple
661 heap_form_tuple(TupleDesc tupleDescriptor,
662                                 Datum *values,
663                                 bool *isnull)
664 {
665         HeapTuple       tuple;                  /* return tuple */
666         HeapTupleHeader td;                     /* tuple data */
667         unsigned long len;
668         int                     hoff;
669         bool            hasnull = false;
670         Form_pg_attribute *att = tupleDescriptor->attrs;
671         int                     numberOfAttributes = tupleDescriptor->natts;
672         int                     i;
673
674         if (numberOfAttributes > MaxTupleAttributeNumber)
675                 ereport(ERROR,
676                                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
677                                  errmsg("number of columns (%d) exceeds limit (%d)",
678                                                 numberOfAttributes, MaxTupleAttributeNumber)));
679
680         /*
681          * Check for nulls and embedded tuples; expand any toasted attributes in
682          * embedded tuples.  This preserves the invariant that toasting can only
683          * go one level deep.
684          *
685          * We can skip calling toast_flatten_tuple_attribute() if the attribute
686          * couldn't possibly be of composite type.  All composite datums are
687          * varlena and have alignment 'd'; furthermore they aren't arrays. Also,
688          * if an attribute is already toasted, it must have been sent to disk
689          * already and so cannot contain toasted attributes.
690          */
691         for (i = 0; i < numberOfAttributes; i++)
692         {
693                 if (isnull[i])
694                         hasnull = true;
695                 else if (att[i]->attlen == -1 &&
696                                  att[i]->attalign == 'd' &&
697                                  att[i]->attndims == 0 &&
698                                  !VARATT_IS_EXTENDED(values[i]))
699                 {
700                         values[i] = toast_flatten_tuple_attribute(values[i],
701                                                                                                           att[i]->atttypid,
702                                                                                                           att[i]->atttypmod);
703                 }
704         }
705
706         /*
707          * Determine total space needed
708          */
709         len = offsetof(HeapTupleHeaderData, t_bits);
710
711         if (hasnull)
712                 len += BITMAPLEN(numberOfAttributes);
713
714         if (tupleDescriptor->tdhasoid)
715                 len += sizeof(Oid);
716
717         hoff = len = MAXALIGN(len); /* align user data safely */
718
719         len += heap_compute_data_size(tupleDescriptor, values, isnull);
720
721         /*
722          * Allocate and zero the space needed.  Note that the tuple body and
723          * HeapTupleData management structure are allocated in one chunk.
724          */
725         tuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
726         tuple->t_data = td = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
727
728         /*
729          * And fill in the information.  Note we fill the Datum fields even though
730          * this tuple may never become a Datum.
731          */
732         tuple->t_len = len;
733         ItemPointerSetInvalid(&(tuple->t_self));
734         tuple->t_tableOid = InvalidOid;
735
736         HeapTupleHeaderSetDatumLength(td, len);
737         HeapTupleHeaderSetTypeId(td, tupleDescriptor->tdtypeid);
738         HeapTupleHeaderSetTypMod(td, tupleDescriptor->tdtypmod);
739
740         td->t_natts = numberOfAttributes;
741         td->t_hoff = hoff;
742
743         if (tupleDescriptor->tdhasoid)          /* else leave infomask = 0 */
744                 td->t_infomask = HEAP_HASOID;
745
746         heap_fill_tuple(tupleDescriptor,
747                                         values,
748                                         isnull,
749                                         (char *) td + hoff,
750                                         &td->t_infomask,
751                                         (hasnull ? td->t_bits : NULL));
752
753         return tuple;
754 }
755
756 /* ----------------
757  *              heap_formtuple
758  *
759  *              construct a tuple from the given values[] and nulls[] arrays
760  *
761  *              Null attributes are indicated by a 'n' in the appropriate byte
762  *              of nulls[]. Non-null attributes are indicated by a ' ' (space).
763  *
764  * OLD API with char 'n'/' ' convention for indicating nulls
765  * ----------------
766  */
767 HeapTuple
768 heap_formtuple(TupleDesc tupleDescriptor,
769                            Datum *values,
770                            char *nulls)
771 {
772         HeapTuple       tuple;                  /* return tuple */
773         HeapTupleHeader td;                     /* tuple data */
774         unsigned long len;
775         int                     hoff;
776         bool            hasnull = false;
777         Form_pg_attribute *att = tupleDescriptor->attrs;
778         int                     numberOfAttributes = tupleDescriptor->natts;
779         int                     i;
780
781         if (numberOfAttributes > MaxTupleAttributeNumber)
782                 ereport(ERROR,
783                                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
784                                  errmsg("number of columns (%d) exceeds limit (%d)",
785                                                 numberOfAttributes, MaxTupleAttributeNumber)));
786
787         /*
788          * Check for nulls and embedded tuples; expand any toasted attributes in
789          * embedded tuples.  This preserves the invariant that toasting can only
790          * go one level deep.
791          *
792          * We can skip calling toast_flatten_tuple_attribute() if the attribute
793          * couldn't possibly be of composite type.  All composite datums are
794          * varlena and have alignment 'd'; furthermore they aren't arrays. Also,
795          * if an attribute is already toasted, it must have been sent to disk
796          * already and so cannot contain toasted attributes.
797          */
798         for (i = 0; i < numberOfAttributes; i++)
799         {
800                 if (nulls[i] != ' ')
801                         hasnull = true;
802                 else if (att[i]->attlen == -1 &&
803                                  att[i]->attalign == 'd' &&
804                                  att[i]->attndims == 0 &&
805                                  !VARATT_IS_EXTENDED(values[i]))
806                 {
807                         values[i] = toast_flatten_tuple_attribute(values[i],
808                                                                                                           att[i]->atttypid,
809                                                                                                           att[i]->atttypmod);
810                 }
811         }
812
813         /*
814          * Determine total space needed
815          */
816         len = offsetof(HeapTupleHeaderData, t_bits);
817
818         if (hasnull)
819                 len += BITMAPLEN(numberOfAttributes);
820
821         if (tupleDescriptor->tdhasoid)
822                 len += sizeof(Oid);
823
824         hoff = len = MAXALIGN(len); /* align user data safely */
825
826         len += ComputeDataSize(tupleDescriptor, values, nulls);
827
828         /*
829          * Allocate and zero the space needed.  Note that the tuple body and
830          * HeapTupleData management structure are allocated in one chunk.
831          */
832         tuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
833         tuple->t_data = td = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
834
835         /*
836          * And fill in the information.  Note we fill the Datum fields even though
837          * this tuple may never become a Datum.
838          */
839         tuple->t_len = len;
840         ItemPointerSetInvalid(&(tuple->t_self));
841         tuple->t_tableOid = InvalidOid;
842
843         HeapTupleHeaderSetDatumLength(td, len);
844         HeapTupleHeaderSetTypeId(td, tupleDescriptor->tdtypeid);
845         HeapTupleHeaderSetTypMod(td, tupleDescriptor->tdtypmod);
846
847         td->t_natts = numberOfAttributes;
848         td->t_hoff = hoff;
849
850         if (tupleDescriptor->tdhasoid)          /* else leave infomask = 0 */
851                 td->t_infomask = HEAP_HASOID;
852
853         DataFill((char *) td + hoff,
854                          tupleDescriptor,
855                          values,
856                          nulls,
857                          &td->t_infomask,
858                          (hasnull ? td->t_bits : NULL));
859
860         return tuple;
861 }
862
863 /*
864  * heap_modify_tuple
865  *              form a new tuple from an old tuple and a set of replacement values.
866  *
867  * The replValues, replIsnull, and doReplace arrays must be of the length
868  * indicated by tupleDesc->natts.  The new tuple is constructed using the data
869  * from replValues/replIsnull at columns where doReplace is true, and using
870  * the data from the old tuple at columns where doReplace is false.
871  *
872  * The result is allocated in the current memory context.
873  */
874 HeapTuple
875 heap_modify_tuple(HeapTuple tuple,
876                                   TupleDesc tupleDesc,
877                                   Datum *replValues,
878                                   bool *replIsnull,
879                                   bool *doReplace)
880 {
881         int                     numberOfAttributes = tupleDesc->natts;
882         int                     attoff;
883         Datum      *values;
884         bool       *isnull;
885         HeapTuple       newTuple;
886
887         /*
888          * allocate and fill values and isnull arrays from either the tuple or the
889          * repl information, as appropriate.
890          *
891          * NOTE: it's debatable whether to use heap_deform_tuple() here or just
892          * heap_getattr() only the non-replaced colums.  The latter could win if
893          * there are many replaced columns and few non-replaced ones. However,
894          * heap_deform_tuple costs only O(N) while the heap_getattr way would cost
895          * O(N^2) if there are many non-replaced columns, so it seems better to
896          * err on the side of linear cost.
897          */
898         values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
899         isnull = (bool *) palloc(numberOfAttributes * sizeof(bool));
900
901         heap_deform_tuple(tuple, tupleDesc, values, isnull);
902
903         for (attoff = 0; attoff < numberOfAttributes; attoff++)
904         {
905                 if (doReplace[attoff])
906                 {
907                         values[attoff] = replValues[attoff];
908                         isnull[attoff] = replIsnull[attoff];
909                 }
910         }
911
912         /*
913          * create a new tuple from the values and isnull arrays
914          */
915         newTuple = heap_form_tuple(tupleDesc, values, isnull);
916
917         pfree(values);
918         pfree(isnull);
919
920         /*
921          * copy the identification info of the old tuple: t_ctid, t_self, and OID
922          * (if any)
923          */
924         newTuple->t_data->t_ctid = tuple->t_data->t_ctid;
925         newTuple->t_self = tuple->t_self;
926         newTuple->t_tableOid = tuple->t_tableOid;
927         if (tupleDesc->tdhasoid)
928                 HeapTupleSetOid(newTuple, HeapTupleGetOid(tuple));
929
930         return newTuple;
931 }
932
933 /* ----------------
934  *              heap_modifytuple
935  *
936  *              forms a new tuple from an old tuple and a set of replacement values.
937  *              returns a new palloc'ed tuple.
938  *
939  * OLD API with char 'n'/' ' convention for indicating nulls, and
940  * char 'r'/' ' convention for indicating whether to replace columns.
941  * ----------------
942  */
943 HeapTuple
944 heap_modifytuple(HeapTuple tuple,
945                                  TupleDesc tupleDesc,
946                                  Datum *replValues,
947                                  char *replNulls,
948                                  char *replActions)
949 {
950         int                     numberOfAttributes = tupleDesc->natts;
951         int                     attoff;
952         Datum      *values;
953         char       *nulls;
954         HeapTuple       newTuple;
955
956         /*
957          * allocate and fill values and nulls arrays from either the tuple or the
958          * repl information, as appropriate.
959          *
960          * NOTE: it's debatable whether to use heap_deformtuple() here or just
961          * heap_getattr() only the non-replaced colums.  The latter could win if
962          * there are many replaced columns and few non-replaced ones. However,
963          * heap_deformtuple costs only O(N) while the heap_getattr way would cost
964          * O(N^2) if there are many non-replaced columns, so it seems better to
965          * err on the side of linear cost.
966          */
967         values = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
968         nulls = (char *) palloc(numberOfAttributes * sizeof(char));
969
970         heap_deformtuple(tuple, tupleDesc, values, nulls);
971
972         for (attoff = 0; attoff < numberOfAttributes; attoff++)
973         {
974                 if (replActions[attoff] == 'r')
975                 {
976                         values[attoff] = replValues[attoff];
977                         nulls[attoff] = replNulls[attoff];
978                 }
979                 else if (replActions[attoff] != ' ')
980                         elog(ERROR, "unrecognized replace flag: %d",
981                                  (int) replActions[attoff]);
982         }
983
984         /*
985          * create a new tuple from the values and nulls arrays
986          */
987         newTuple = heap_formtuple(tupleDesc, values, nulls);
988
989         pfree(values);
990         pfree(nulls);
991
992         /*
993          * copy the identification info of the old tuple: t_ctid, t_self, and OID
994          * (if any)
995          */
996         newTuple->t_data->t_ctid = tuple->t_data->t_ctid;
997         newTuple->t_self = tuple->t_self;
998         newTuple->t_tableOid = tuple->t_tableOid;
999         if (tupleDesc->tdhasoid)
1000                 HeapTupleSetOid(newTuple, HeapTupleGetOid(tuple));
1001
1002         return newTuple;
1003 }
1004
1005 /*
1006  * heap_deform_tuple
1007  *              Given a tuple, extract data into values/isnull arrays; this is
1008  *              the inverse of heap_form_tuple.
1009  *
1010  *              Storage for the values/isnull arrays is provided by the caller;
1011  *              it should be sized according to tupleDesc->natts not tuple->t_natts.
1012  *
1013  *              Note that for pass-by-reference datatypes, the pointer placed
1014  *              in the Datum will point into the given tuple.
1015  *
1016  *              When all or most of a tuple's fields need to be extracted,
1017  *              this routine will be significantly quicker than a loop around
1018  *              heap_getattr; the loop will become O(N^2) as soon as any
1019  *              noncacheable attribute offsets are involved.
1020  */
1021 void
1022 heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc,
1023                                   Datum *values, bool *isnull)
1024 {
1025         HeapTupleHeader tup = tuple->t_data;
1026         bool            hasnulls = HeapTupleHasNulls(tuple);
1027         Form_pg_attribute *att = tupleDesc->attrs;
1028         int                     tdesc_natts = tupleDesc->natts;
1029         int                     natts;                  /* number of atts to extract */
1030         int                     attnum;
1031         char       *tp;                         /* ptr to tuple data */
1032         long            off;                    /* offset in tuple data */
1033         bits8      *bp = tup->t_bits;           /* ptr to null bitmap in tuple */
1034         bool            slow = false;   /* can we use/set attcacheoff? */
1035
1036         natts = tup->t_natts;
1037
1038         /*
1039          * In inheritance situations, it is possible that the given tuple actually
1040          * has more fields than the caller is expecting.  Don't run off the end of
1041          * the caller's arrays.
1042          */
1043         natts = Min(natts, tdesc_natts);
1044
1045         tp = (char *) tup + tup->t_hoff;
1046
1047         off = 0;
1048
1049         for (attnum = 0; attnum < natts; attnum++)
1050         {
1051                 Form_pg_attribute thisatt = att[attnum];
1052
1053                 if (hasnulls && att_isnull(attnum, bp))
1054                 {
1055                         values[attnum] = (Datum) 0;
1056                         isnull[attnum] = true;
1057                         slow = true;            /* can't use attcacheoff anymore */
1058                         continue;
1059                 }
1060
1061                 isnull[attnum] = false;
1062
1063                 if (!slow && thisatt->attcacheoff >= 0)
1064                         off = thisatt->attcacheoff;
1065                 else
1066                 {
1067                         off = att_align(off, thisatt->attalign);
1068
1069                         if (!slow)
1070                                 thisatt->attcacheoff = off;
1071                 }
1072
1073                 values[attnum] = fetchatt(thisatt, tp + off);
1074
1075                 off = att_addlength(off, thisatt->attlen, tp + off);
1076
1077                 if (thisatt->attlen <= 0)
1078                         slow = true;            /* can't use attcacheoff anymore */
1079         }
1080
1081         /*
1082          * If tuple doesn't have all the atts indicated by tupleDesc, read the
1083          * rest as null
1084          */
1085         for (; attnum < tdesc_natts; attnum++)
1086         {
1087                 values[attnum] = (Datum) 0;
1088                 isnull[attnum] = true;
1089         }
1090 }
1091
1092 /* ----------------
1093  *              heap_deformtuple
1094  *
1095  *              Given a tuple, extract data into values/nulls arrays; this is
1096  *              the inverse of heap_formtuple.
1097  *
1098  *              Storage for the values/nulls arrays is provided by the caller;
1099  *              it should be sized according to tupleDesc->natts not tuple->t_natts.
1100  *
1101  *              Note that for pass-by-reference datatypes, the pointer placed
1102  *              in the Datum will point into the given tuple.
1103  *
1104  *              When all or most of a tuple's fields need to be extracted,
1105  *              this routine will be significantly quicker than a loop around
1106  *              heap_getattr; the loop will become O(N^2) as soon as any
1107  *              noncacheable attribute offsets are involved.
1108  *
1109  * OLD API with char 'n'/' ' convention for indicating nulls
1110  * ----------------
1111  */
1112 void
1113 heap_deformtuple(HeapTuple tuple,
1114                                  TupleDesc tupleDesc,
1115                                  Datum *values,
1116                                  char *nulls)
1117 {
1118         HeapTupleHeader tup = tuple->t_data;
1119         bool            hasnulls = HeapTupleHasNulls(tuple);
1120         Form_pg_attribute *att = tupleDesc->attrs;
1121         int                     tdesc_natts = tupleDesc->natts;
1122         int                     natts;                  /* number of atts to extract */
1123         int                     attnum;
1124         char       *tp;                         /* ptr to tuple data */
1125         long            off;                    /* offset in tuple data */
1126         bits8      *bp = tup->t_bits;           /* ptr to null bitmap in tuple */
1127         bool            slow = false;   /* can we use/set attcacheoff? */
1128
1129         natts = tup->t_natts;
1130
1131         /*
1132          * In inheritance situations, it is possible that the given tuple actually
1133          * has more fields than the caller is expecting.  Don't run off the end of
1134          * the caller's arrays.
1135          */
1136         natts = Min(natts, tdesc_natts);
1137
1138         tp = (char *) tup + tup->t_hoff;
1139
1140         off = 0;
1141
1142         for (attnum = 0; attnum < natts; attnum++)
1143         {
1144                 Form_pg_attribute thisatt = att[attnum];
1145
1146                 if (hasnulls && att_isnull(attnum, bp))
1147                 {
1148                         values[attnum] = (Datum) 0;
1149                         nulls[attnum] = 'n';
1150                         slow = true;            /* can't use attcacheoff anymore */
1151                         continue;
1152                 }
1153
1154                 nulls[attnum] = ' ';
1155
1156                 if (!slow && thisatt->attcacheoff >= 0)
1157                         off = thisatt->attcacheoff;
1158                 else
1159                 {
1160                         off = att_align(off, thisatt->attalign);
1161
1162                         if (!slow)
1163                                 thisatt->attcacheoff = off;
1164                 }
1165
1166                 values[attnum] = fetchatt(thisatt, tp + off);
1167
1168                 off = att_addlength(off, thisatt->attlen, tp + off);
1169
1170                 if (thisatt->attlen <= 0)
1171                         slow = true;            /* can't use attcacheoff anymore */
1172         }
1173
1174         /*
1175          * If tuple doesn't have all the atts indicated by tupleDesc, read the
1176          * rest as null
1177          */
1178         for (; attnum < tdesc_natts; attnum++)
1179         {
1180                 values[attnum] = (Datum) 0;
1181                 nulls[attnum] = 'n';
1182         }
1183 }
1184
1185 /*
1186  * slot_deform_tuple
1187  *              Given a TupleTableSlot, extract data from the slot's physical tuple
1188  *              into its Datum/isnull arrays.  Data is extracted up through the
1189  *              natts'th column (caller must ensure this is a legal column number).
1190  *
1191  *              This is essentially an incremental version of heap_deform_tuple:
1192  *              on each call we extract attributes up to the one needed, without
1193  *              re-computing information about previously extracted attributes.
1194  *              slot->tts_nvalid is the number of attributes already extracted.
1195  */
1196 static void
1197 slot_deform_tuple(TupleTableSlot *slot, int natts)
1198 {
1199         HeapTuple       tuple = slot->tts_tuple;
1200         TupleDesc       tupleDesc = slot->tts_tupleDescriptor;
1201         Datum      *values = slot->tts_values;
1202         bool       *isnull = slot->tts_isnull;
1203         HeapTupleHeader tup = tuple->t_data;
1204         bool            hasnulls = HeapTupleHasNulls(tuple);
1205         Form_pg_attribute *att = tupleDesc->attrs;
1206         int                     attnum;
1207         char       *tp;                         /* ptr to tuple data */
1208         long            off;                    /* offset in tuple data */
1209         bits8      *bp = tup->t_bits;           /* ptr to null bitmap in tuple */
1210         bool            slow;                   /* can we use/set attcacheoff? */
1211
1212         /*
1213          * Check whether the first call for this tuple, and initialize or restore
1214          * loop state.
1215          */
1216         attnum = slot->tts_nvalid;
1217         if (attnum == 0)
1218         {
1219                 /* Start from the first attribute */
1220                 off = 0;
1221                 slow = false;
1222         }
1223         else
1224         {
1225                 /* Restore state from previous execution */
1226                 off = slot->tts_off;
1227                 slow = slot->tts_slow;
1228         }
1229
1230         tp = (char *) tup + tup->t_hoff;
1231
1232         for (; attnum < natts; attnum++)
1233         {
1234                 Form_pg_attribute thisatt = att[attnum];
1235
1236                 if (hasnulls && att_isnull(attnum, bp))
1237                 {
1238                         values[attnum] = (Datum) 0;
1239                         isnull[attnum] = true;
1240                         slow = true;            /* can't use attcacheoff anymore */
1241                         continue;
1242                 }
1243
1244                 isnull[attnum] = false;
1245
1246                 if (!slow && thisatt->attcacheoff >= 0)
1247                         off = thisatt->attcacheoff;
1248                 else
1249                 {
1250                         off = att_align(off, thisatt->attalign);
1251
1252                         if (!slow)
1253                                 thisatt->attcacheoff = off;
1254                 }
1255
1256                 values[attnum] = fetchatt(thisatt, tp + off);
1257
1258                 off = att_addlength(off, thisatt->attlen, tp + off);
1259
1260                 if (thisatt->attlen <= 0)
1261                         slow = true;            /* can't use attcacheoff anymore */
1262         }
1263
1264         /*
1265          * Save state for next execution
1266          */
1267         slot->tts_nvalid = attnum;
1268         slot->tts_off = off;
1269         slot->tts_slow = slow;
1270 }
1271
1272 /*
1273  * slot_getattr
1274  *              This function fetches an attribute of the slot's current tuple.
1275  *              It is functionally equivalent to heap_getattr, but fetches of
1276  *              multiple attributes of the same tuple will be optimized better,
1277  *              because we avoid O(N^2) behavior from multiple calls of
1278  *              nocachegetattr(), even when attcacheoff isn't usable.
1279  *
1280  *              A difference from raw heap_getattr is that attnums beyond the
1281  *              slot's tupdesc's last attribute will be considered NULL even
1282  *              when the physical tuple is longer than the tupdesc.
1283  */
1284 Datum
1285 slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
1286 {
1287         HeapTuple       tuple = slot->tts_tuple;
1288         TupleDesc       tupleDesc = slot->tts_tupleDescriptor;
1289         HeapTupleHeader tup;
1290
1291         /*
1292          * system attributes are handled by heap_getsysattr
1293          */
1294         if (attnum <= 0)
1295         {
1296                 if (tuple == NULL)              /* internal error */
1297                         elog(ERROR, "cannot extract system attribute from virtual tuple");
1298                 if (slot->tts_mintuple) /* internal error */
1299                         elog(ERROR, "cannot extract system attribute from minimal tuple");
1300                 return heap_getsysattr(tuple, attnum, tupleDesc, isnull);
1301         }
1302
1303         /*
1304          * fast path if desired attribute already cached
1305          */
1306         if (attnum <= slot->tts_nvalid)
1307         {
1308                 *isnull = slot->tts_isnull[attnum - 1];
1309                 return slot->tts_values[attnum - 1];
1310         }
1311
1312         /*
1313          * return NULL if attnum is out of range according to the tupdesc
1314          */
1315         if (attnum > tupleDesc->natts)
1316         {
1317                 *isnull = true;
1318                 return (Datum) 0;
1319         }
1320
1321         /*
1322          * otherwise we had better have a physical tuple (tts_nvalid should equal
1323          * natts in all virtual-tuple cases)
1324          */
1325         if (tuple == NULL)                      /* internal error */
1326                 elog(ERROR, "cannot extract attribute from empty tuple slot");
1327
1328         /*
1329          * return NULL if attnum is out of range according to the tuple
1330          *
1331          * (We have to check this separately because of various inheritance and
1332          * table-alteration scenarios: the tuple could be either longer or shorter
1333          * than the tupdesc.)
1334          */
1335         tup = tuple->t_data;
1336         if (attnum > tup->t_natts)
1337         {
1338                 *isnull = true;
1339                 return (Datum) 0;
1340         }
1341
1342         /*
1343          * check if target attribute is null: no point in groveling through tuple
1344          */
1345         if (HeapTupleHasNulls(tuple) && att_isnull(attnum - 1, tup->t_bits))
1346         {
1347                 *isnull = true;
1348                 return (Datum) 0;
1349         }
1350
1351         /*
1352          * If the attribute's column has been dropped, we force a NULL result.
1353          * This case should not happen in normal use, but it could happen if we
1354          * are executing a plan cached before the column was dropped.
1355          */
1356         if (tupleDesc->attrs[attnum - 1]->attisdropped)
1357         {
1358                 *isnull = true;
1359                 return (Datum) 0;
1360         }
1361
1362         /*
1363          * Extract the attribute, along with any preceding attributes.
1364          */
1365         slot_deform_tuple(slot, attnum);
1366
1367         /*
1368          * The result is acquired from tts_values array.
1369          */
1370         *isnull = slot->tts_isnull[attnum - 1];
1371         return slot->tts_values[attnum - 1];
1372 }
1373
1374 /*
1375  * slot_getallattrs
1376  *              This function forces all the entries of the slot's Datum/isnull
1377  *              arrays to be valid.  The caller may then extract data directly
1378  *              from those arrays instead of using slot_getattr.
1379  */
1380 void
1381 slot_getallattrs(TupleTableSlot *slot)
1382 {
1383         int                     tdesc_natts = slot->tts_tupleDescriptor->natts;
1384         int                     attnum;
1385         HeapTuple       tuple;
1386
1387         /* Quick out if we have 'em all already */
1388         if (slot->tts_nvalid == tdesc_natts)
1389                 return;
1390
1391         /*
1392          * otherwise we had better have a physical tuple (tts_nvalid should equal
1393          * natts in all virtual-tuple cases)
1394          */
1395         tuple = slot->tts_tuple;
1396         if (tuple == NULL)                      /* internal error */
1397                 elog(ERROR, "cannot extract attribute from empty tuple slot");
1398
1399         /*
1400          * load up any slots available from physical tuple
1401          */
1402         attnum = tuple->t_data->t_natts;
1403         attnum = Min(attnum, tdesc_natts);
1404
1405         slot_deform_tuple(slot, attnum);
1406
1407         /*
1408          * If tuple doesn't have all the atts indicated by tupleDesc, read the
1409          * rest as null
1410          */
1411         for (; attnum < tdesc_natts; attnum++)
1412         {
1413                 slot->tts_values[attnum] = (Datum) 0;
1414                 slot->tts_isnull[attnum] = true;
1415         }
1416         slot->tts_nvalid = tdesc_natts;
1417 }
1418
1419 /*
1420  * slot_getsomeattrs
1421  *              This function forces the entries of the slot's Datum/isnull
1422  *              arrays to be valid at least up through the attnum'th entry.
1423  */
1424 void
1425 slot_getsomeattrs(TupleTableSlot *slot, int attnum)
1426 {
1427         HeapTuple       tuple;
1428         int                     attno;
1429
1430         /* Quick out if we have 'em all already */
1431         if (slot->tts_nvalid >= attnum)
1432                 return;
1433
1434         /* Check for caller error */
1435         if (attnum <= 0 || attnum > slot->tts_tupleDescriptor->natts)
1436                 elog(ERROR, "invalid attribute number %d", attnum);
1437
1438         /*
1439          * otherwise we had better have a physical tuple (tts_nvalid should equal
1440          * natts in all virtual-tuple cases)
1441          */
1442         tuple = slot->tts_tuple;
1443         if (tuple == NULL)                      /* internal error */
1444                 elog(ERROR, "cannot extract attribute from empty tuple slot");
1445
1446         /*
1447          * load up any slots available from physical tuple
1448          */
1449         attno = tuple->t_data->t_natts;
1450         attno = Min(attno, attnum);
1451
1452         slot_deform_tuple(slot, attno);
1453
1454         /*
1455          * If tuple doesn't have all the atts indicated by tupleDesc, read the
1456          * rest as null
1457          */
1458         for (; attno < attnum; attno++)
1459         {
1460                 slot->tts_values[attno] = (Datum) 0;
1461                 slot->tts_isnull[attno] = true;
1462         }
1463         slot->tts_nvalid = attnum;
1464 }
1465
1466 /*
1467  * slot_attisnull
1468  *              Detect whether an attribute of the slot is null, without
1469  *              actually fetching it.
1470  */
1471 bool
1472 slot_attisnull(TupleTableSlot *slot, int attnum)
1473 {
1474         HeapTuple       tuple = slot->tts_tuple;
1475         TupleDesc       tupleDesc = slot->tts_tupleDescriptor;
1476
1477         /*
1478          * system attributes are handled by heap_attisnull
1479          */
1480         if (attnum <= 0)
1481         {
1482                 if (tuple == NULL)              /* internal error */
1483                         elog(ERROR, "cannot extract system attribute from virtual tuple");
1484                 if (slot->tts_mintuple) /* internal error */
1485                         elog(ERROR, "cannot extract system attribute from minimal tuple");
1486                 return heap_attisnull(tuple, attnum);
1487         }
1488
1489         /*
1490          * fast path if desired attribute already cached
1491          */
1492         if (attnum <= slot->tts_nvalid)
1493                 return slot->tts_isnull[attnum - 1];
1494
1495         /*
1496          * return NULL if attnum is out of range according to the tupdesc
1497          */
1498         if (attnum > tupleDesc->natts)
1499                 return true;
1500
1501         /*
1502          * otherwise we had better have a physical tuple (tts_nvalid should equal
1503          * natts in all virtual-tuple cases)
1504          */
1505         if (tuple == NULL)                      /* internal error */
1506                 elog(ERROR, "cannot extract attribute from empty tuple slot");
1507
1508         /* and let the tuple tell it */
1509         return heap_attisnull(tuple, attnum);
1510 }
1511
1512 /*
1513  * heap_freetuple
1514  */
1515 void
1516 heap_freetuple(HeapTuple htup)
1517 {
1518         pfree(htup);
1519 }
1520
1521
1522 /*
1523  * heap_form_minimal_tuple
1524  *              construct a MinimalTuple from the given values[] and isnull[] arrays,
1525  *              which are of the length indicated by tupleDescriptor->natts
1526  *
1527  * This is exactly like heap_form_tuple() except that the result is a
1528  * "minimal" tuple lacking a HeapTupleData header as well as room for system
1529  * columns.
1530  *
1531  * The result is allocated in the current memory context.
1532  */
1533 MinimalTuple
1534 heap_form_minimal_tuple(TupleDesc tupleDescriptor,
1535                                                 Datum *values,
1536                                                 bool *isnull)
1537 {
1538         MinimalTuple tuple;                     /* return tuple */
1539         unsigned long len;
1540         int                     hoff;
1541         bool            hasnull = false;
1542         Form_pg_attribute *att = tupleDescriptor->attrs;
1543         int                     numberOfAttributes = tupleDescriptor->natts;
1544         int                     i;
1545
1546         if (numberOfAttributes > MaxTupleAttributeNumber)
1547                 ereport(ERROR,
1548                                 (errcode(ERRCODE_TOO_MANY_COLUMNS),
1549                                  errmsg("number of columns (%d) exceeds limit (%d)",
1550                                                 numberOfAttributes, MaxTupleAttributeNumber)));
1551
1552         /*
1553          * Check for nulls and embedded tuples; expand any toasted attributes in
1554          * embedded tuples.  This preserves the invariant that toasting can only
1555          * go one level deep.
1556          *
1557          * We can skip calling toast_flatten_tuple_attribute() if the attribute
1558          * couldn't possibly be of composite type.  All composite datums are
1559          * varlena and have alignment 'd'; furthermore they aren't arrays. Also,
1560          * if an attribute is already toasted, it must have been sent to disk
1561          * already and so cannot contain toasted attributes.
1562          */
1563         for (i = 0; i < numberOfAttributes; i++)
1564         {
1565                 if (isnull[i])
1566                         hasnull = true;
1567                 else if (att[i]->attlen == -1 &&
1568                                  att[i]->attalign == 'd' &&
1569                                  att[i]->attndims == 0 &&
1570                                  !VARATT_IS_EXTENDED(values[i]))
1571                 {
1572                         values[i] = toast_flatten_tuple_attribute(values[i],
1573                                                                                                           att[i]->atttypid,
1574                                                                                                           att[i]->atttypmod);
1575                 }
1576         }
1577
1578         /*
1579          * Determine total space needed
1580          */
1581         len = offsetof(MinimalTupleData, t_bits);
1582
1583         if (hasnull)
1584                 len += BITMAPLEN(numberOfAttributes);
1585
1586         if (tupleDescriptor->tdhasoid)
1587                 len += sizeof(Oid);
1588
1589         hoff = len = MAXALIGN(len); /* align user data safely */
1590
1591         len += heap_compute_data_size(tupleDescriptor, values, isnull);
1592
1593         /*
1594          * Allocate and zero the space needed.
1595          */
1596         tuple = (MinimalTuple) palloc0(len);
1597
1598         /*
1599          * And fill in the information.
1600          */
1601         tuple->t_len = len;
1602         tuple->t_natts = numberOfAttributes;
1603         tuple->t_hoff = hoff + MINIMAL_TUPLE_OFFSET;
1604
1605         if (tupleDescriptor->tdhasoid)          /* else leave infomask = 0 */
1606                 tuple->t_infomask = HEAP_HASOID;
1607
1608         heap_fill_tuple(tupleDescriptor,
1609                                         values,
1610                                         isnull,
1611                                         (char *) tuple + hoff,
1612                                         &tuple->t_infomask,
1613                                         (hasnull ? tuple->t_bits : NULL));
1614
1615         return tuple;
1616 }
1617
1618 /*
1619  * heap_free_minimal_tuple
1620  */
1621 void
1622 heap_free_minimal_tuple(MinimalTuple mtup)
1623 {
1624         pfree(mtup);
1625 }
1626
1627 /*
1628  * heap_copy_minimal_tuple
1629  *              copy a MinimalTuple
1630  *
1631  * The result is allocated in the current memory context.
1632  */
1633 MinimalTuple
1634 heap_copy_minimal_tuple(MinimalTuple mtup)
1635 {
1636         MinimalTuple result;
1637
1638         result = (MinimalTuple) palloc(mtup->t_len);
1639         memcpy(result, mtup, mtup->t_len);
1640         return result;
1641 }
1642
1643 /*
1644  * heap_tuple_from_minimal_tuple
1645  *              create a HeapTuple by copying from a MinimalTuple;
1646  *              system columns are filled with zeroes
1647  *
1648  * The result is allocated in the current memory context.
1649  * The HeapTuple struct, tuple header, and tuple data are all allocated
1650  * as a single palloc() block.
1651  */
1652 HeapTuple
1653 heap_tuple_from_minimal_tuple(MinimalTuple mtup)
1654 {
1655         HeapTuple       result;
1656         uint32          len = mtup->t_len + MINIMAL_TUPLE_OFFSET;
1657
1658         result = (HeapTuple) palloc(HEAPTUPLESIZE + len);
1659         result->t_len = len;
1660         ItemPointerSetInvalid(&(result->t_self));
1661         result->t_tableOid = InvalidOid;
1662         result->t_data = (HeapTupleHeader) ((char *) result + HEAPTUPLESIZE);
1663         memcpy((char *) result->t_data + MINIMAL_TUPLE_OFFSET, mtup, mtup->t_len);
1664         memset(result->t_data, 0, offsetof(HeapTupleHeaderData, t_natts));
1665         return result;
1666 }
1667
1668 /*
1669  * minimal_tuple_from_heap_tuple
1670  *              create a MinimalTuple by copying from a HeapTuple
1671  *
1672  * The result is allocated in the current memory context.
1673  */
1674 MinimalTuple
1675 minimal_tuple_from_heap_tuple(HeapTuple htup)
1676 {
1677         MinimalTuple result;
1678         uint32          len;
1679
1680         Assert(htup->t_len > MINIMAL_TUPLE_OFFSET);
1681         len = htup->t_len - MINIMAL_TUPLE_OFFSET;
1682         result = (MinimalTuple) palloc(len);
1683         memcpy(result, (char *) htup->t_data + MINIMAL_TUPLE_OFFSET, len);
1684         result->t_len = len;
1685         return result;
1686 }
1687
1688
1689 /* ----------------
1690  *              heap_addheader
1691  *
1692  * This routine forms a HeapTuple by copying the given structure (tuple
1693  * data) and adding a generic header.  Note that the tuple data is
1694  * presumed to contain no null fields and no varlena fields.
1695  *
1696  * This routine is really only useful for certain system tables that are
1697  * known to be fixed-width and null-free.  It is used in some places for
1698  * pg_class, but that is a gross hack (it only works because relacl can
1699  * be omitted from the tuple entirely in those places).
1700  * ----------------
1701  */
1702 HeapTuple
1703 heap_addheader(int natts,               /* max domain index */
1704                            bool withoid,        /* reserve space for oid */
1705                            Size structlen,      /* its length */
1706                            void *structure) /* pointer to the struct */
1707 {
1708         HeapTuple       tuple;
1709         HeapTupleHeader td;
1710         Size            len;
1711         int                     hoff;
1712
1713         AssertArg(natts > 0);
1714
1715         /* header needs no null bitmap */
1716         hoff = offsetof(HeapTupleHeaderData, t_bits);
1717         if (withoid)
1718                 hoff += sizeof(Oid);
1719         hoff = MAXALIGN(hoff);
1720         len = hoff + structlen;
1721
1722         tuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
1723         tuple->t_data = td = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
1724
1725         tuple->t_len = len;
1726         ItemPointerSetInvalid(&(tuple->t_self));
1727         tuple->t_tableOid = InvalidOid;
1728
1729         /* we don't bother to fill the Datum fields */
1730
1731         td->t_natts = natts;
1732         td->t_hoff = hoff;
1733
1734         if (withoid)                            /* else leave infomask = 0 */
1735                 td->t_infomask = HEAP_HASOID;
1736
1737         memcpy((char *) td + hoff, structure, structlen);
1738
1739         return tuple;
1740 }
1741
1742 /*
1743  * build_class_tuple
1744  *
1745  *      XXX Natts_pg_class_fixed is a hack - see pg_class.h
1746  */
1747 HeapTuple
1748 build_class_tuple(Form_pg_class pgclass, ArrayType *options)
1749 {
1750         HeapTuple               tuple;
1751         HeapTupleHeader td;
1752         Form_pg_class   data;   /* contents of tuple */
1753         Size                    len;
1754         Size                    size;
1755         int                             hoff;
1756
1757         /* size of pg_class tuple with options */
1758         if (options)
1759                 size = offsetof(FormData_pg_class, reloptions) + VARATT_SIZE(options);
1760         else
1761                 size = CLASS_TUPLE_SIZE;
1762
1763         /* header needs no null bitmap */
1764         hoff = offsetof(HeapTupleHeaderData, t_bits);
1765         hoff += sizeof(Oid);
1766         hoff = MAXALIGN(hoff);
1767         len = hoff + size;
1768
1769         tuple = (HeapTuple) palloc0(HEAPTUPLESIZE + len);
1770         tuple->t_data = td = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
1771
1772         tuple->t_len = len;
1773         ItemPointerSetInvalid(&(tuple->t_self));
1774         tuple->t_tableOid = InvalidOid;
1775
1776         /* we don't bother to fill the Datum fields */
1777
1778         td->t_natts = Natts_pg_class_fixed;
1779         td->t_hoff = hoff;
1780         td->t_infomask = HEAP_HASOID;
1781
1782         data = (Form_pg_class) ((char *) td + hoff);
1783         memcpy(data, pgclass, CLASS_TUPLE_SIZE);
1784         if (options)
1785         {
1786                 td->t_natts++;
1787                 memcpy(data->reloptions, options, VARATT_SIZE(options));
1788         }
1789
1790         return tuple;
1791 }