]> granicus.if.org Git - postgresql/blob - src/backend/executor/execTuples.c
Update copyright for the year 2010.
[postgresql] / src / backend / executor / execTuples.c
1 /*-------------------------------------------------------------------------
2  *
3  * execTuples.c
4  *        Routines dealing with TupleTableSlots.  These are used for resource
5  *        management associated with tuples (eg, releasing buffer pins for
6  *        tuples in disk buffers, or freeing the memory occupied by transient
7  *        tuples).  Slots also provide access abstraction that lets us implement
8  *        "virtual" tuples to reduce data-copying overhead.
9  *
10  *        Routines dealing with the type information for tuples. Currently,
11  *        the type information for a tuple is an array of FormData_pg_attribute.
12  *        This information is needed by routines manipulating tuples
13  *        (getattribute, formtuple, etc.).
14  *
15  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
16  * Portions Copyright (c) 1994, Regents of the University of California
17  *
18  *
19  * IDENTIFICATION
20  *        $PostgreSQL: pgsql/src/backend/executor/execTuples.c,v 1.111 2010/01/02 16:57:41 momjian Exp $
21  *
22  *-------------------------------------------------------------------------
23  */
24 /*
25  * INTERFACE ROUTINES
26  *
27  *       SLOT CREATION/DESTRUCTION
28  *              MakeTupleTableSlot              - create an empty slot
29  *              ExecAllocTableSlot              - create a slot within a tuple table
30  *              ExecResetTupleTable             - clear and optionally delete a tuple table
31  *              MakeSingleTupleTableSlot - make a standalone slot, set its descriptor
32  *              ExecDropSingleTupleTableSlot - destroy a standalone slot
33  *
34  *       SLOT ACCESSORS
35  *              ExecSetSlotDescriptor   - set a slot's tuple descriptor
36  *              ExecStoreTuple                  - store a physical tuple in the slot
37  *              ExecStoreMinimalTuple   - store a minimal physical tuple in the slot
38  *              ExecClearTuple                  - clear contents of a slot
39  *              ExecStoreVirtualTuple   - mark slot as containing a virtual tuple
40  *              ExecCopySlotTuple               - build a physical tuple from a slot
41  *              ExecCopySlotMinimalTuple - build a minimal physical tuple from a slot
42  *              ExecMaterializeSlot             - convert virtual to physical storage
43  *              ExecCopySlot                    - copy one slot's contents to another
44  *
45  *       CONVENIENCE INITIALIZATION ROUTINES
46  *              ExecInitResultTupleSlot    \    convenience routines to initialize
47  *              ExecInitScanTupleSlot           \       the various tuple slots for nodes
48  *              ExecInitExtraTupleSlot          /       which store copies of tuples.
49  *              ExecInitNullTupleSlot      /
50  *
51  *       Routines that probably belong somewhere else:
52  *              ExecTypeFromTL                  - form a TupleDesc from a target list
53  *
54  *       EXAMPLE OF HOW TABLE ROUTINES WORK
55  *              Suppose we have a query such as SELECT emp.name FROM emp and we have
56  *              a single SeqScan node in the query plan.
57  *
58  *              At ExecutorStart()
59  *              ----------------
60  *              - ExecInitSeqScan() calls ExecInitScanTupleSlot() and
61  *                ExecInitResultTupleSlot() to construct TupleTableSlots
62  *                for the tuples returned by the access methods and the
63  *                tuples resulting from performing target list projections.
64  *
65  *              During ExecutorRun()
66  *              ----------------
67  *              - SeqNext() calls ExecStoreTuple() to place the tuple returned
68  *                by the access methods into the scan tuple slot.
69  *
70  *              - ExecSeqScan() calls ExecStoreTuple() to take the result
71  *                tuple from ExecProject() and place it into the result tuple slot.
72  *
73  *              - ExecutePlan() calls ExecSelect(), which passes the result slot
74  *                to printtup(), which uses slot_getallattrs() to extract the
75  *                individual Datums for printing.
76  *
77  *              At ExecutorEnd()
78  *              ----------------
79  *              - EndPlan() calls ExecResetTupleTable() to clean up any remaining
80  *                tuples left over from executing the query.
81  *
82  *              The important thing to watch in the executor code is how pointers
83  *              to the slots containing tuples are passed instead of the tuples
84  *              themselves.  This facilitates the communication of related information
85  *              (such as whether or not a tuple should be pfreed, what buffer contains
86  *              this tuple, the tuple's tuple descriptor, etc).  It also allows us
87  *              to avoid physically constructing projection tuples in many cases.
88  */
89 #include "postgres.h"
90
91 #include "funcapi.h"
92 #include "catalog/pg_type.h"
93 #include "nodes/nodeFuncs.h"
94 #include "storage/bufmgr.h"
95 #include "utils/builtins.h"
96 #include "utils/lsyscache.h"
97 #include "utils/typcache.h"
98
99
100 static TupleDesc ExecTypeFromTLInternal(List *targetList,
101                                            bool hasoid, bool skipjunk);
102
103
104 /* ----------------------------------------------------------------
105  *                                tuple table create/delete functions
106  * ----------------------------------------------------------------
107  */
108
109 /* --------------------------------
110  *              MakeTupleTableSlot
111  *
112  *              Basic routine to make an empty TupleTableSlot.
113  * --------------------------------
114  */
115 TupleTableSlot *
116 MakeTupleTableSlot(void)
117 {
118         TupleTableSlot *slot = makeNode(TupleTableSlot);
119
120         slot->tts_isempty = true;
121         slot->tts_shouldFree = false;
122         slot->tts_shouldFreeMin = false;
123         slot->tts_tuple = NULL;
124         slot->tts_tupleDescriptor = NULL;
125         slot->tts_mcxt = CurrentMemoryContext;
126         slot->tts_buffer = InvalidBuffer;
127         slot->tts_nvalid = 0;
128         slot->tts_values = NULL;
129         slot->tts_isnull = NULL;
130         slot->tts_mintuple = NULL;
131
132         return slot;
133 }
134
135 /* --------------------------------
136  *              ExecAllocTableSlot
137  *
138  *              Create a tuple table slot within a tuple table (which is just a List).
139  * --------------------------------
140  */
141 TupleTableSlot *
142 ExecAllocTableSlot(List **tupleTable)
143 {
144         TupleTableSlot *slot = MakeTupleTableSlot();
145
146         *tupleTable = lappend(*tupleTable, slot);
147
148         return slot;
149 }
150
151 /* --------------------------------
152  *              ExecResetTupleTable
153  *
154  *              This releases any resources (buffer pins, tupdesc refcounts)
155  *              held by the tuple table, and optionally releases the memory
156  *              occupied by the tuple table data structure.
157  *              It is expected that this routine be called by EndPlan().
158  * --------------------------------
159  */
160 void
161 ExecResetTupleTable(List *tupleTable,   /* tuple table */
162                                         bool shouldFree)        /* true if we should free memory */
163 {
164         ListCell   *lc;
165
166         foreach(lc, tupleTable)
167         {
168                 TupleTableSlot *slot = (TupleTableSlot *) lfirst(lc);
169
170                 /* Sanity checks */
171                 Assert(IsA(slot, TupleTableSlot));
172
173                 /* Always release resources and reset the slot to empty */
174                 ExecClearTuple(slot);
175                 if (slot->tts_tupleDescriptor)
176                 {
177                         ReleaseTupleDesc(slot->tts_tupleDescriptor);
178                         slot->tts_tupleDescriptor = NULL;
179                 }
180
181                 /* If shouldFree, release memory occupied by the slot itself */
182                 if (shouldFree)
183                 {
184                         if (slot->tts_values)
185                                 pfree(slot->tts_values);
186                         if (slot->tts_isnull)
187                                 pfree(slot->tts_isnull);
188                         pfree(slot);
189                 }
190         }
191
192         /* If shouldFree, release the list structure */
193         if (shouldFree)
194                 list_free(tupleTable);
195 }
196
197 /* --------------------------------
198  *              MakeSingleTupleTableSlot
199  *
200  *              This is a convenience routine for operations that need a
201  *              standalone TupleTableSlot not gotten from the main executor
202  *              tuple table.  It makes a single slot and initializes it
203  *              to use the given tuple descriptor.
204  * --------------------------------
205  */
206 TupleTableSlot *
207 MakeSingleTupleTableSlot(TupleDesc tupdesc)
208 {
209         TupleTableSlot *slot = MakeTupleTableSlot();
210
211         ExecSetSlotDescriptor(slot, tupdesc);
212
213         return slot;
214 }
215
216 /* --------------------------------
217  *              ExecDropSingleTupleTableSlot
218  *
219  *              Release a TupleTableSlot made with MakeSingleTupleTableSlot.
220  *              DON'T use this on a slot that's part of a tuple table list!
221  * --------------------------------
222  */
223 void
224 ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
225 {
226         /* This should match ExecResetTupleTable's processing of one slot */
227         Assert(IsA(slot, TupleTableSlot));
228         ExecClearTuple(slot);
229         if (slot->tts_tupleDescriptor)
230                 ReleaseTupleDesc(slot->tts_tupleDescriptor);
231         if (slot->tts_values)
232                 pfree(slot->tts_values);
233         if (slot->tts_isnull)
234                 pfree(slot->tts_isnull);
235         pfree(slot);
236 }
237
238
239 /* ----------------------------------------------------------------
240  *                                tuple table slot accessor functions
241  * ----------------------------------------------------------------
242  */
243
244 /* --------------------------------
245  *              ExecSetSlotDescriptor
246  *
247  *              This function is used to set the tuple descriptor associated
248  *              with the slot's tuple.  The passed descriptor must have lifespan
249  *              at least equal to the slot's.  If it is a reference-counted descriptor
250  *              then the reference count is incremented for as long as the slot holds
251  *              a reference.
252  * --------------------------------
253  */
254 void
255 ExecSetSlotDescriptor(TupleTableSlot *slot,             /* slot to change */
256                                           TupleDesc tupdesc)            /* new tuple descriptor */
257 {
258         /* For safety, make sure slot is empty before changing it */
259         ExecClearTuple(slot);
260
261         /*
262          * Release any old descriptor.  Also release old Datum/isnull arrays if
263          * present (we don't bother to check if they could be re-used).
264          */
265         if (slot->tts_tupleDescriptor)
266                 ReleaseTupleDesc(slot->tts_tupleDescriptor);
267
268         if (slot->tts_values)
269                 pfree(slot->tts_values);
270         if (slot->tts_isnull)
271                 pfree(slot->tts_isnull);
272
273         /*
274          * Install the new descriptor; if it's refcounted, bump its refcount.
275          */
276         slot->tts_tupleDescriptor = tupdesc;
277         PinTupleDesc(tupdesc);
278
279         /*
280          * Allocate Datum/isnull arrays of the appropriate size.  These must have
281          * the same lifetime as the slot, so allocate in the slot's own context.
282          */
283         slot->tts_values = (Datum *)
284                 MemoryContextAlloc(slot->tts_mcxt, tupdesc->natts * sizeof(Datum));
285         slot->tts_isnull = (bool *)
286                 MemoryContextAlloc(slot->tts_mcxt, tupdesc->natts * sizeof(bool));
287 }
288
289 /* --------------------------------
290  *              ExecStoreTuple
291  *
292  *              This function is used to store a physical tuple into a specified
293  *              slot in the tuple table.
294  *
295  *              tuple:  tuple to store
296  *              slot:   slot to store it in
297  *              buffer: disk buffer if tuple is in a disk page, else InvalidBuffer
298  *              shouldFree: true if ExecClearTuple should pfree() the tuple
299  *                                      when done with it
300  *
301  * If 'buffer' is not InvalidBuffer, the tuple table code acquires a pin
302  * on the buffer which is held until the slot is cleared, so that the tuple
303  * won't go away on us.
304  *
305  * shouldFree is normally set 'true' for tuples constructed on-the-fly.
306  * It must always be 'false' for tuples that are stored in disk pages,
307  * since we don't want to try to pfree those.
308  *
309  * Another case where it is 'false' is when the referenced tuple is held
310  * in a tuple table slot belonging to a lower-level executor Proc node.
311  * In this case the lower-level slot retains ownership and responsibility
312  * for eventually releasing the tuple.  When this method is used, we must
313  * be certain that the upper-level Proc node will lose interest in the tuple
314  * sooner than the lower-level one does!  If you're not certain, copy the
315  * lower-level tuple with heap_copytuple and let the upper-level table
316  * slot assume ownership of the copy!
317  *
318  * Return value is just the passed-in slot pointer.
319  *
320  * NOTE: before PostgreSQL 8.1, this function would accept a NULL tuple
321  * pointer and effectively behave like ExecClearTuple (though you could
322  * still specify a buffer to pin, which would be an odd combination).
323  * This saved a couple lines of code in a few places, but seemed more likely
324  * to mask logic errors than to be really useful, so it's now disallowed.
325  * --------------------------------
326  */
327 TupleTableSlot *
328 ExecStoreTuple(HeapTuple tuple,
329                            TupleTableSlot *slot,
330                            Buffer buffer,
331                            bool shouldFree)
332 {
333         /*
334          * sanity checks
335          */
336         Assert(tuple != NULL);
337         Assert(slot != NULL);
338         Assert(slot->tts_tupleDescriptor != NULL);
339         /* passing shouldFree=true for a tuple on a disk page is not sane */
340         Assert(BufferIsValid(buffer) ? (!shouldFree) : true);
341
342         /*
343          * Free any old physical tuple belonging to the slot.
344          */
345         if (slot->tts_shouldFree)
346                 heap_freetuple(slot->tts_tuple);
347         if (slot->tts_shouldFreeMin)
348                 heap_free_minimal_tuple(slot->tts_mintuple);
349
350         /*
351          * Store the new tuple into the specified slot.
352          */
353         slot->tts_isempty = false;
354         slot->tts_shouldFree = shouldFree;
355         slot->tts_shouldFreeMin = false;
356         slot->tts_tuple = tuple;
357         slot->tts_mintuple = NULL;
358
359         /* Mark extracted state invalid */
360         slot->tts_nvalid = 0;
361
362         /*
363          * If tuple is on a disk page, keep the page pinned as long as we hold a
364          * pointer into it.  We assume the caller already has such a pin.
365          *
366          * This is coded to optimize the case where the slot previously held a
367          * tuple on the same disk page: in that case releasing and re-acquiring
368          * the pin is a waste of cycles.  This is a common situation during
369          * seqscans, so it's worth troubling over.
370          */
371         if (slot->tts_buffer != buffer)
372         {
373                 if (BufferIsValid(slot->tts_buffer))
374                         ReleaseBuffer(slot->tts_buffer);
375                 slot->tts_buffer = buffer;
376                 if (BufferIsValid(buffer))
377                         IncrBufferRefCount(buffer);
378         }
379
380         return slot;
381 }
382
383 /* --------------------------------
384  *              ExecStoreMinimalTuple
385  *
386  *              Like ExecStoreTuple, but insert a "minimal" tuple into the slot.
387  *
388  * No 'buffer' parameter since minimal tuples are never stored in relations.
389  * --------------------------------
390  */
391 TupleTableSlot *
392 ExecStoreMinimalTuple(MinimalTuple mtup,
393                                           TupleTableSlot *slot,
394                                           bool shouldFree)
395 {
396         /*
397          * sanity checks
398          */
399         Assert(mtup != NULL);
400         Assert(slot != NULL);
401         Assert(slot->tts_tupleDescriptor != NULL);
402
403         /*
404          * Free any old physical tuple belonging to the slot.
405          */
406         if (slot->tts_shouldFree)
407                 heap_freetuple(slot->tts_tuple);
408         if (slot->tts_shouldFreeMin)
409                 heap_free_minimal_tuple(slot->tts_mintuple);
410
411         /*
412          * Drop the pin on the referenced buffer, if there is one.
413          */
414         if (BufferIsValid(slot->tts_buffer))
415                 ReleaseBuffer(slot->tts_buffer);
416
417         slot->tts_buffer = InvalidBuffer;
418
419         /*
420          * Store the new tuple into the specified slot.
421          */
422         slot->tts_isempty = false;
423         slot->tts_shouldFree = false;
424         slot->tts_shouldFreeMin = shouldFree;
425         slot->tts_tuple = &slot->tts_minhdr;
426         slot->tts_mintuple = mtup;
427
428         slot->tts_minhdr.t_len = mtup->t_len + MINIMAL_TUPLE_OFFSET;
429         slot->tts_minhdr.t_data = (HeapTupleHeader) ((char *) mtup - MINIMAL_TUPLE_OFFSET);
430         /* no need to set t_self or t_tableOid since we won't allow access */
431
432         /* Mark extracted state invalid */
433         slot->tts_nvalid = 0;
434
435         return slot;
436 }
437
438 /* --------------------------------
439  *              ExecClearTuple
440  *
441  *              This function is used to clear out a slot in the tuple table.
442  *
443  *              NB: only the tuple is cleared, not the tuple descriptor (if any).
444  * --------------------------------
445  */
446 TupleTableSlot *                                /* return: slot passed */
447 ExecClearTuple(TupleTableSlot *slot)    /* slot in which to store tuple */
448 {
449         /*
450          * sanity checks
451          */
452         Assert(slot != NULL);
453
454         /*
455          * Free the old physical tuple if necessary.
456          */
457         if (slot->tts_shouldFree)
458                 heap_freetuple(slot->tts_tuple);
459         if (slot->tts_shouldFreeMin)
460                 heap_free_minimal_tuple(slot->tts_mintuple);
461
462         slot->tts_tuple = NULL;
463         slot->tts_mintuple = NULL;
464         slot->tts_shouldFree = false;
465         slot->tts_shouldFreeMin = false;
466
467         /*
468          * Drop the pin on the referenced buffer, if there is one.
469          */
470         if (BufferIsValid(slot->tts_buffer))
471                 ReleaseBuffer(slot->tts_buffer);
472
473         slot->tts_buffer = InvalidBuffer;
474
475         /*
476          * Mark it empty.
477          */
478         slot->tts_isempty = true;
479         slot->tts_nvalid = 0;
480
481         return slot;
482 }
483
484 /* --------------------------------
485  *              ExecStoreVirtualTuple
486  *                      Mark a slot as containing a virtual tuple.
487  *
488  * The protocol for loading a slot with virtual tuple data is:
489  *              * Call ExecClearTuple to mark the slot empty.
490  *              * Store data into the Datum/isnull arrays.
491  *              * Call ExecStoreVirtualTuple to mark the slot valid.
492  * This is a bit unclean but it avoids one round of data copying.
493  * --------------------------------
494  */
495 TupleTableSlot *
496 ExecStoreVirtualTuple(TupleTableSlot *slot)
497 {
498         /*
499          * sanity checks
500          */
501         Assert(slot != NULL);
502         Assert(slot->tts_tupleDescriptor != NULL);
503         Assert(slot->tts_isempty);
504
505         slot->tts_isempty = false;
506         slot->tts_nvalid = slot->tts_tupleDescriptor->natts;
507
508         return slot;
509 }
510
511 /* --------------------------------
512  *              ExecStoreAllNullTuple
513  *                      Set up the slot to contain a null in every column.
514  *
515  * At first glance this might sound just like ExecClearTuple, but it's
516  * entirely different: the slot ends up full, not empty.
517  * --------------------------------
518  */
519 TupleTableSlot *
520 ExecStoreAllNullTuple(TupleTableSlot *slot)
521 {
522         /*
523          * sanity checks
524          */
525         Assert(slot != NULL);
526         Assert(slot->tts_tupleDescriptor != NULL);
527
528         /* Clear any old contents */
529         ExecClearTuple(slot);
530
531         /*
532          * Fill all the columns of the virtual tuple with nulls
533          */
534         MemSet(slot->tts_values, 0,
535                    slot->tts_tupleDescriptor->natts * sizeof(Datum));
536         memset(slot->tts_isnull, true,
537                    slot->tts_tupleDescriptor->natts * sizeof(bool));
538
539         return ExecStoreVirtualTuple(slot);
540 }
541
542 /* --------------------------------
543  *              ExecCopySlotTuple
544  *                      Obtain a copy of a slot's regular physical tuple.  The copy is
545  *                      palloc'd in the current memory context.
546  *                      The slot itself is undisturbed.
547  *
548  *              This works even if the slot contains a virtual or minimal tuple;
549  *              however the "system columns" of the result will not be meaningful.
550  * --------------------------------
551  */
552 HeapTuple
553 ExecCopySlotTuple(TupleTableSlot *slot)
554 {
555         /*
556          * sanity checks
557          */
558         Assert(slot != NULL);
559         Assert(!slot->tts_isempty);
560
561         /*
562          * If we have a physical tuple (either format) then just copy it.
563          */
564         if (TTS_HAS_PHYSICAL_TUPLE(slot))
565                 return heap_copytuple(slot->tts_tuple);
566         if (slot->tts_mintuple)
567                 return heap_tuple_from_minimal_tuple(slot->tts_mintuple);
568
569         /*
570          * Otherwise we need to build a tuple from the Datum array.
571          */
572         return heap_form_tuple(slot->tts_tupleDescriptor,
573                                                    slot->tts_values,
574                                                    slot->tts_isnull);
575 }
576
577 /* --------------------------------
578  *              ExecCopySlotMinimalTuple
579  *                      Obtain a copy of a slot's minimal physical tuple.  The copy is
580  *                      palloc'd in the current memory context.
581  *                      The slot itself is undisturbed.
582  * --------------------------------
583  */
584 MinimalTuple
585 ExecCopySlotMinimalTuple(TupleTableSlot *slot)
586 {
587         /*
588          * sanity checks
589          */
590         Assert(slot != NULL);
591         Assert(!slot->tts_isempty);
592
593         /*
594          * If we have a physical tuple then just copy it.  Prefer to copy
595          * tts_mintuple since that's a tad cheaper.
596          */
597         if (slot->tts_mintuple)
598                 return heap_copy_minimal_tuple(slot->tts_mintuple);
599         if (slot->tts_tuple)
600                 return minimal_tuple_from_heap_tuple(slot->tts_tuple);
601
602         /*
603          * Otherwise we need to build a tuple from the Datum array.
604          */
605         return heap_form_minimal_tuple(slot->tts_tupleDescriptor,
606                                                                    slot->tts_values,
607                                                                    slot->tts_isnull);
608 }
609
610 /* --------------------------------
611  *              ExecFetchSlotTuple
612  *                      Fetch the slot's regular physical tuple.
613  *
614  *              If the slot contains a virtual tuple, we convert it to physical
615  *              form.  The slot retains ownership of the physical tuple.
616  *              If it contains a minimal tuple we convert to regular form and store
617  *              that in addition to the minimal tuple (not instead of, because
618  *              callers may hold pointers to Datums within the minimal tuple).
619  *
620  * The main difference between this and ExecMaterializeSlot() is that this
621  * does not guarantee that the contained tuple is local storage.
622  * Hence, the result must be treated as read-only.
623  * --------------------------------
624  */
625 HeapTuple
626 ExecFetchSlotTuple(TupleTableSlot *slot)
627 {
628         /*
629          * sanity checks
630          */
631         Assert(slot != NULL);
632         Assert(!slot->tts_isempty);
633
634         /*
635          * If we have a regular physical tuple then just return it.
636          */
637         if (TTS_HAS_PHYSICAL_TUPLE(slot))
638                 return slot->tts_tuple;
639
640         /*
641          * Otherwise materialize the slot...
642          */
643         return ExecMaterializeSlot(slot);
644 }
645
646 /* --------------------------------
647  *              ExecFetchSlotMinimalTuple
648  *                      Fetch the slot's minimal physical tuple.
649  *
650  *              If the slot contains a virtual tuple, we convert it to minimal
651  *              physical form.  The slot retains ownership of the minimal tuple.
652  *              If it contains a regular tuple we convert to minimal form and store
653  *              that in addition to the regular tuple (not instead of, because
654  *              callers may hold pointers to Datums within the regular tuple).
655  *
656  * As above, the result must be treated as read-only.
657  * --------------------------------
658  */
659 MinimalTuple
660 ExecFetchSlotMinimalTuple(TupleTableSlot *slot)
661 {
662         MemoryContext oldContext;
663
664         /*
665          * sanity checks
666          */
667         Assert(slot != NULL);
668         Assert(!slot->tts_isempty);
669
670         /*
671          * If we have a minimal physical tuple (local or not) then just return it.
672          */
673         if (slot->tts_mintuple)
674                 return slot->tts_mintuple;
675
676         /*
677          * Otherwise, copy or build a minimal tuple, and store it into the slot.
678          *
679          * We may be called in a context that is shorter-lived than the tuple
680          * slot, but we have to ensure that the materialized tuple will survive
681          * anyway.
682          */
683         oldContext = MemoryContextSwitchTo(slot->tts_mcxt);
684         slot->tts_mintuple = ExecCopySlotMinimalTuple(slot);
685         slot->tts_shouldFreeMin = true;
686         MemoryContextSwitchTo(oldContext);
687
688         /*
689          * Note: we may now have a situation where we have a local minimal tuple
690          * attached to a virtual or non-local physical tuple.  There seems no harm
691          * in that at the moment, but if any materializes, we should change this
692          * function to force the slot into minimal-tuple-only state.
693          */
694
695         return slot->tts_mintuple;
696 }
697
698 /* --------------------------------
699  *              ExecFetchSlotTupleDatum
700  *                      Fetch the slot's tuple as a composite-type Datum.
701  *
702  *              We convert the slot's contents to local physical-tuple form,
703  *              and fill in the Datum header fields.  Note that the result
704  *              always points to storage owned by the slot.
705  * --------------------------------
706  */
707 Datum
708 ExecFetchSlotTupleDatum(TupleTableSlot *slot)
709 {
710         HeapTuple       tup;
711         HeapTupleHeader td;
712         TupleDesc       tupdesc;
713
714         /* Make sure we can scribble on the slot contents ... */
715         tup = ExecMaterializeSlot(slot);
716         /* ... and set up the composite-Datum header fields, in case not done */
717         td = tup->t_data;
718         tupdesc = slot->tts_tupleDescriptor;
719         HeapTupleHeaderSetDatumLength(td, tup->t_len);
720         HeapTupleHeaderSetTypeId(td, tupdesc->tdtypeid);
721         HeapTupleHeaderSetTypMod(td, tupdesc->tdtypmod);
722         return PointerGetDatum(td);
723 }
724
725 /* --------------------------------
726  *              ExecMaterializeSlot
727  *                      Force a slot into the "materialized" state.
728  *
729  *              This causes the slot's tuple to be a local copy not dependent on
730  *              any external storage.  A pointer to the contained tuple is returned.
731  *
732  *              A typical use for this operation is to prepare a computed tuple
733  *              for being stored on disk.  The original data may or may not be
734  *              virtual, but in any case we need a private copy for heap_insert
735  *              to scribble on.
736  * --------------------------------
737  */
738 HeapTuple
739 ExecMaterializeSlot(TupleTableSlot *slot)
740 {
741         MemoryContext oldContext;
742
743         /*
744          * sanity checks
745          */
746         Assert(slot != NULL);
747         Assert(!slot->tts_isempty);
748
749         /*
750          * If we have a regular physical tuple, and it's locally palloc'd, we have
751          * nothing to do.
752          */
753         if (slot->tts_tuple && slot->tts_shouldFree)
754                 return slot->tts_tuple;
755
756         /*
757          * Otherwise, copy or build a physical tuple, and store it into the slot.
758          *
759          * We may be called in a context that is shorter-lived than the tuple
760          * slot, but we have to ensure that the materialized tuple will survive
761          * anyway.
762          */
763         oldContext = MemoryContextSwitchTo(slot->tts_mcxt);
764         slot->tts_tuple = ExecCopySlotTuple(slot);
765         slot->tts_shouldFree = true;
766         MemoryContextSwitchTo(oldContext);
767
768         /*
769          * Drop the pin on the referenced buffer, if there is one.
770          */
771         if (BufferIsValid(slot->tts_buffer))
772                 ReleaseBuffer(slot->tts_buffer);
773
774         slot->tts_buffer = InvalidBuffer;
775
776         /*
777          * Mark extracted state invalid.  This is important because the slot is
778          * not supposed to depend any more on the previous external data; we
779          * mustn't leave any dangling pass-by-reference datums in tts_values.
780          * However, we have not actually invalidated any such datums, if there
781          * happen to be any previously fetched from the slot.  (Note in particular
782          * that we have not pfree'd tts_mintuple, if there is one.)
783          */
784         slot->tts_nvalid = 0;
785
786         /*
787          * On the same principle of not depending on previous remote storage,
788          * forget the mintuple if it's not local storage.  (If it is local
789          * storage, we must not pfree it now, since callers might have already
790          * fetched datum pointers referencing it.)
791          */
792         if (!slot->tts_shouldFreeMin)
793                 slot->tts_mintuple = NULL;
794
795         return slot->tts_tuple;
796 }
797
798 /* --------------------------------
799  *              ExecCopySlot
800  *                      Copy the source slot's contents into the destination slot.
801  *
802  *              The destination acquires a private copy that will not go away
803  *              if the source is cleared.
804  *
805  *              The caller must ensure the slots have compatible tupdescs.
806  * --------------------------------
807  */
808 TupleTableSlot *
809 ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
810 {
811         HeapTuple       newTuple;
812         MemoryContext oldContext;
813
814         /*
815          * There might be ways to optimize this when the source is virtual, but
816          * for now just always build a physical copy.  Make sure it is in the
817          * right context.
818          */
819         oldContext = MemoryContextSwitchTo(dstslot->tts_mcxt);
820         newTuple = ExecCopySlotTuple(srcslot);
821         MemoryContextSwitchTo(oldContext);
822
823         return ExecStoreTuple(newTuple, dstslot, InvalidBuffer, true);
824 }
825
826
827 /* ----------------------------------------------------------------
828  *                              convenience initialization routines
829  * ----------------------------------------------------------------
830  */
831
832 /* --------------------------------
833  *              ExecInit{Result,Scan,Extra}TupleSlot
834  *
835  *              These are convenience routines to initialize the specified slot
836  *              in nodes inheriting the appropriate state.      ExecInitExtraTupleSlot
837  *              is used for initializing special-purpose slots.
838  * --------------------------------
839  */
840
841 /* ----------------
842  *              ExecInitResultTupleSlot
843  * ----------------
844  */
845 void
846 ExecInitResultTupleSlot(EState *estate, PlanState *planstate)
847 {
848         planstate->ps_ResultTupleSlot = ExecAllocTableSlot(&estate->es_tupleTable);
849 }
850
851 /* ----------------
852  *              ExecInitScanTupleSlot
853  * ----------------
854  */
855 void
856 ExecInitScanTupleSlot(EState *estate, ScanState *scanstate)
857 {
858         scanstate->ss_ScanTupleSlot = ExecAllocTableSlot(&estate->es_tupleTable);
859 }
860
861 /* ----------------
862  *              ExecInitExtraTupleSlot
863  * ----------------
864  */
865 TupleTableSlot *
866 ExecInitExtraTupleSlot(EState *estate)
867 {
868         return ExecAllocTableSlot(&estate->es_tupleTable);
869 }
870
871 /* ----------------
872  *              ExecInitNullTupleSlot
873  *
874  * Build a slot containing an all-nulls tuple of the given type.
875  * This is used as a substitute for an input tuple when performing an
876  * outer join.
877  * ----------------
878  */
879 TupleTableSlot *
880 ExecInitNullTupleSlot(EState *estate, TupleDesc tupType)
881 {
882         TupleTableSlot *slot = ExecInitExtraTupleSlot(estate);
883
884         ExecSetSlotDescriptor(slot, tupType);
885
886         return ExecStoreAllNullTuple(slot);
887 }
888
889 /* ----------------------------------------------------------------
890  *              ExecTypeFromTL
891  *
892  *              Generate a tuple descriptor for the result tuple of a targetlist.
893  *              (A parse/plan tlist must be passed, not an ExprState tlist.)
894  *              Note that resjunk columns, if any, are included in the result.
895  *
896  *              Currently there are about 4 different places where we create
897  *              TupleDescriptors.  They should all be merged, or perhaps
898  *              be rewritten to call BuildDesc().
899  * ----------------------------------------------------------------
900  */
901 TupleDesc
902 ExecTypeFromTL(List *targetList, bool hasoid)
903 {
904         return ExecTypeFromTLInternal(targetList, hasoid, false);
905 }
906
907 /* ----------------------------------------------------------------
908  *              ExecCleanTypeFromTL
909  *
910  *              Same as above, but resjunk columns are omitted from the result.
911  * ----------------------------------------------------------------
912  */
913 TupleDesc
914 ExecCleanTypeFromTL(List *targetList, bool hasoid)
915 {
916         return ExecTypeFromTLInternal(targetList, hasoid, true);
917 }
918
919 static TupleDesc
920 ExecTypeFromTLInternal(List *targetList, bool hasoid, bool skipjunk)
921 {
922         TupleDesc       typeInfo;
923         ListCell   *l;
924         int                     len;
925         int                     cur_resno = 1;
926
927         if (skipjunk)
928                 len = ExecCleanTargetListLength(targetList);
929         else
930                 len = ExecTargetListLength(targetList);
931         typeInfo = CreateTemplateTupleDesc(len, hasoid);
932
933         foreach(l, targetList)
934         {
935                 TargetEntry *tle = lfirst(l);
936
937                 if (skipjunk && tle->resjunk)
938                         continue;
939                 TupleDescInitEntry(typeInfo,
940                                                    cur_resno++,
941                                                    tle->resname,
942                                                    exprType((Node *) tle->expr),
943                                                    exprTypmod((Node *) tle->expr),
944                                                    0);
945         }
946
947         return typeInfo;
948 }
949
950 /*
951  * ExecTypeFromExprList - build a tuple descriptor from a list of Exprs
952  *
953  * Here we must make up an arbitrary set of field names.
954  */
955 TupleDesc
956 ExecTypeFromExprList(List *exprList)
957 {
958         TupleDesc       typeInfo;
959         ListCell   *l;
960         int                     cur_resno = 1;
961         char            fldname[NAMEDATALEN];
962
963         typeInfo = CreateTemplateTupleDesc(list_length(exprList), false);
964
965         foreach(l, exprList)
966         {
967                 Node       *e = lfirst(l);
968
969                 sprintf(fldname, "f%d", cur_resno);
970
971                 TupleDescInitEntry(typeInfo,
972                                                    cur_resno++,
973                                                    fldname,
974                                                    exprType(e),
975                                                    exprTypmod(e),
976                                                    0);
977         }
978
979         return typeInfo;
980 }
981
982 /*
983  * BlessTupleDesc - make a completed tuple descriptor useful for SRFs
984  *
985  * Rowtype Datums returned by a function must contain valid type information.
986  * This happens "for free" if the tupdesc came from a relcache entry, but
987  * not if we have manufactured a tupdesc for a transient RECORD datatype.
988  * In that case we have to notify typcache.c of the existence of the type.
989  */
990 TupleDesc
991 BlessTupleDesc(TupleDesc tupdesc)
992 {
993         if (tupdesc->tdtypeid == RECORDOID &&
994                 tupdesc->tdtypmod < 0)
995                 assign_record_type_typmod(tupdesc);
996
997         return tupdesc;                         /* just for notational convenience */
998 }
999
1000 /*
1001  * TupleDescGetSlot - Initialize a slot based on the supplied tupledesc
1002  *
1003  * Note: this is obsolete; it is sufficient to call BlessTupleDesc on
1004  * the tupdesc.  We keep it around just for backwards compatibility with
1005  * existing user-written SRFs.
1006  */
1007 TupleTableSlot *
1008 TupleDescGetSlot(TupleDesc tupdesc)
1009 {
1010         TupleTableSlot *slot;
1011
1012         /* The useful work is here */
1013         BlessTupleDesc(tupdesc);
1014
1015         /* Make a standalone slot */
1016         slot = MakeSingleTupleTableSlot(tupdesc);
1017
1018         /* Return the slot */
1019         return slot;
1020 }
1021
1022 /*
1023  * TupleDescGetAttInMetadata - Build an AttInMetadata structure based on the
1024  * supplied TupleDesc. AttInMetadata can be used in conjunction with C strings
1025  * to produce a properly formed tuple.
1026  */
1027 AttInMetadata *
1028 TupleDescGetAttInMetadata(TupleDesc tupdesc)
1029 {
1030         int                     natts = tupdesc->natts;
1031         int                     i;
1032         Oid                     atttypeid;
1033         Oid                     attinfuncid;
1034         FmgrInfo   *attinfuncinfo;
1035         Oid                *attioparams;
1036         int32      *atttypmods;
1037         AttInMetadata *attinmeta;
1038
1039         attinmeta = (AttInMetadata *) palloc(sizeof(AttInMetadata));
1040
1041         /* "Bless" the tupledesc so that we can make rowtype datums with it */
1042         attinmeta->tupdesc = BlessTupleDesc(tupdesc);
1043
1044         /*
1045          * Gather info needed later to call the "in" function for each attribute
1046          */
1047         attinfuncinfo = (FmgrInfo *) palloc0(natts * sizeof(FmgrInfo));
1048         attioparams = (Oid *) palloc0(natts * sizeof(Oid));
1049         atttypmods = (int32 *) palloc0(natts * sizeof(int32));
1050
1051         for (i = 0; i < natts; i++)
1052         {
1053                 /* Ignore dropped attributes */
1054                 if (!tupdesc->attrs[i]->attisdropped)
1055                 {
1056                         atttypeid = tupdesc->attrs[i]->atttypid;
1057                         getTypeInputInfo(atttypeid, &attinfuncid, &attioparams[i]);
1058                         fmgr_info(attinfuncid, &attinfuncinfo[i]);
1059                         atttypmods[i] = tupdesc->attrs[i]->atttypmod;
1060                 }
1061         }
1062         attinmeta->attinfuncs = attinfuncinfo;
1063         attinmeta->attioparams = attioparams;
1064         attinmeta->atttypmods = atttypmods;
1065
1066         return attinmeta;
1067 }
1068
1069 /*
1070  * BuildTupleFromCStrings - build a HeapTuple given user data in C string form.
1071  * values is an array of C strings, one for each attribute of the return tuple.
1072  * A NULL string pointer indicates we want to create a NULL field.
1073  */
1074 HeapTuple
1075 BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
1076 {
1077         TupleDesc       tupdesc = attinmeta->tupdesc;
1078         int                     natts = tupdesc->natts;
1079         Datum      *dvalues;
1080         bool       *nulls;
1081         int                     i;
1082         HeapTuple       tuple;
1083
1084         dvalues = (Datum *) palloc(natts * sizeof(Datum));
1085         nulls = (bool *) palloc(natts * sizeof(bool));
1086
1087         /* Call the "in" function for each non-dropped attribute */
1088         for (i = 0; i < natts; i++)
1089         {
1090                 if (!tupdesc->attrs[i]->attisdropped)
1091                 {
1092                         /* Non-dropped attributes */
1093                         dvalues[i] = InputFunctionCall(&attinmeta->attinfuncs[i],
1094                                                                                    values[i],
1095                                                                                    attinmeta->attioparams[i],
1096                                                                                    attinmeta->atttypmods[i]);
1097                         if (values[i] != NULL)
1098                                 nulls[i] = false;
1099                         else
1100                                 nulls[i] = true;
1101                 }
1102                 else
1103                 {
1104                         /* Handle dropped attributes by setting to NULL */
1105                         dvalues[i] = (Datum) 0;
1106                         nulls[i] = true;
1107                 }
1108         }
1109
1110         /*
1111          * Form a tuple
1112          */
1113         tuple = heap_form_tuple(tupdesc, dvalues, nulls);
1114
1115         /*
1116          * Release locally palloc'd space.  XXX would probably be good to pfree
1117          * values of pass-by-reference datums, as well.
1118          */
1119         pfree(dvalues);
1120         pfree(nulls);
1121
1122         return tuple;
1123 }
1124
1125 /*
1126  * Functions for sending tuples to the frontend (or other specified destination)
1127  * as though it is a SELECT result. These are used by utility commands that
1128  * need to project directly to the destination and don't need or want full
1129  * table function capability. Currently used by EXPLAIN and SHOW ALL.
1130  */
1131 TupOutputState *
1132 begin_tup_output_tupdesc(DestReceiver *dest, TupleDesc tupdesc)
1133 {
1134         TupOutputState *tstate;
1135
1136         tstate = (TupOutputState *) palloc(sizeof(TupOutputState));
1137
1138         tstate->slot = MakeSingleTupleTableSlot(tupdesc);
1139         tstate->dest = dest;
1140
1141         (*tstate->dest->rStartup) (tstate->dest, (int) CMD_SELECT, tupdesc);
1142
1143         return tstate;
1144 }
1145
1146 /*
1147  * write a single tuple
1148  */
1149 void
1150 do_tup_output(TupOutputState *tstate, Datum *values, bool *isnull)
1151 {
1152         TupleTableSlot *slot = tstate->slot;
1153         int                     natts = slot->tts_tupleDescriptor->natts;
1154
1155         /* make sure the slot is clear */
1156         ExecClearTuple(slot);
1157
1158         /* insert data */
1159         memcpy(slot->tts_values, values, natts * sizeof(Datum));
1160         memcpy(slot->tts_isnull, isnull, natts * sizeof(bool));
1161
1162         /* mark slot as containing a virtual tuple */
1163         ExecStoreVirtualTuple(slot);
1164
1165         /* send the tuple to the receiver */
1166         (*tstate->dest->receiveSlot) (slot, tstate->dest);
1167
1168         /* clean up */
1169         ExecClearTuple(slot);
1170 }
1171
1172 /*
1173  * write a chunk of text, breaking at newline characters
1174  *
1175  * Should only be used with a single-TEXT-attribute tupdesc.
1176  */
1177 void
1178 do_text_output_multiline(TupOutputState *tstate, char *text)
1179 {
1180         Datum           values[1];
1181         bool            isnull[1] = { false };
1182
1183         while (*text)
1184         {
1185                 char       *eol;
1186                 int                     len;
1187
1188                 eol = strchr(text, '\n');
1189                 if (eol)
1190                 {
1191                         len = eol - text;
1192                         eol++;
1193                 }
1194                 else
1195                 {
1196                         len = strlen(text);
1197                         eol += len;
1198                 }
1199
1200                 values[0] = PointerGetDatum(cstring_to_text_with_len(text, len));
1201                 do_tup_output(tstate, values, isnull);
1202                 pfree(DatumGetPointer(values[0]));
1203                 text = eol;
1204         }
1205 }
1206
1207 void
1208 end_tup_output(TupOutputState *tstate)
1209 {
1210         (*tstate->dest->rShutdown) (tstate->dest);
1211         /* note that destroying the dest is not ours to do */
1212         ExecDropSingleTupleTableSlot(tstate->slot);
1213         pfree(tstate);
1214 }