]> granicus.if.org Git - postgresql/blob - src/backend/executor/execMain.c
0352d9a5e43d8052b15475b57683c32e222575ad
[postgresql] / src / backend / executor / execMain.c
1 /*-------------------------------------------------------------------------
2  *
3  * execMain.c
4  *        top level executor interface routines
5  *
6  * INTERFACE ROUTINES
7  *      ExecutorStart()
8  *      ExecutorRun()
9  *      ExecutorEnd()
10  *
11  *      The old ExecutorMain() has been replaced by ExecutorStart(),
12  *      ExecutorRun() and ExecutorEnd()
13  *
14  *      These three procedures are the external interfaces to the executor.
15  *      In each case, the query descriptor is required as an argument.
16  *
17  *      ExecutorStart() must be called at the beginning of execution of any
18  *      query plan and ExecutorEnd() should always be called at the end of
19  *      execution of a plan.
20  *
21  *      ExecutorRun accepts direction and count arguments that specify whether
22  *      the plan is to be executed forwards, backwards, and for how many tuples.
23  *
24  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
25  * Portions Copyright (c) 1994, Regents of the University of California
26  *
27  *
28  * IDENTIFICATION
29  *        $PostgreSQL: pgsql/src/backend/executor/execMain.c,v 1.321 2009/01/22 20:16:03 tgl Exp $
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34
35 #include "access/heapam.h"
36 #include "access/reloptions.h"
37 #include "access/sysattr.h"
38 #include "access/transam.h"
39 #include "access/xact.h"
40 #include "catalog/heap.h"
41 #include "catalog/namespace.h"
42 #include "catalog/toasting.h"
43 #include "commands/tablespace.h"
44 #include "commands/trigger.h"
45 #include "executor/execdebug.h"
46 #include "executor/instrument.h"
47 #include "executor/nodeSubplan.h"
48 #include "miscadmin.h"
49 #include "nodes/nodeFuncs.h"
50 #include "optimizer/clauses.h"
51 #include "parser/parse_clause.h"
52 #include "parser/parsetree.h"
53 #include "storage/bufmgr.h"
54 #include "storage/lmgr.h"
55 #include "storage/smgr.h"
56 #include "utils/acl.h"
57 #include "utils/builtins.h"
58 #include "utils/lsyscache.h"
59 #include "utils/memutils.h"
60 #include "utils/snapmgr.h"
61 #include "utils/tqual.h"
62
63
64 /* Hooks for plugins to get control in ExecutorStart/Run/End() */
65 ExecutorStart_hook_type ExecutorStart_hook = NULL;
66 ExecutorRun_hook_type   ExecutorRun_hook = NULL;
67 ExecutorEnd_hook_type   ExecutorEnd_hook = NULL;
68
69 typedef struct evalPlanQual
70 {
71         Index           rti;
72         EState     *estate;
73         PlanState  *planstate;
74         struct evalPlanQual *next;      /* stack of active PlanQual plans */
75         struct evalPlanQual *free;      /* list of free PlanQual plans */
76 } evalPlanQual;
77
78 /* decls for local routines only used within this module */
79 static void InitPlan(QueryDesc *queryDesc, int eflags);
80 static void ExecCheckPlanOutput(Relation resultRel, List *targetList);
81 static void ExecEndPlan(PlanState *planstate, EState *estate);
82 static void ExecutePlan(EState *estate, PlanState *planstate,
83                         CmdType operation,
84                         long numberTuples,
85                         ScanDirection direction,
86                         DestReceiver *dest);
87 static void ExecSelect(TupleTableSlot *slot,
88                    DestReceiver *dest, EState *estate);
89 static void ExecInsert(TupleTableSlot *slot, ItemPointer tupleid,
90                    TupleTableSlot *planSlot,
91                    DestReceiver *dest, EState *estate);
92 static void ExecDelete(ItemPointer tupleid,
93                    TupleTableSlot *planSlot,
94                    DestReceiver *dest, EState *estate);
95 static void ExecUpdate(TupleTableSlot *slot, ItemPointer tupleid,
96                    TupleTableSlot *planSlot,
97                    DestReceiver *dest, EState *estate);
98 static void ExecProcessReturning(ProjectionInfo *projectReturning,
99                                          TupleTableSlot *tupleSlot,
100                                          TupleTableSlot *planSlot,
101                                          DestReceiver *dest);
102 static TupleTableSlot *EvalPlanQualNext(EState *estate);
103 static void EndEvalPlanQual(EState *estate);
104 static void ExecCheckRTPerms(List *rangeTable);
105 static void ExecCheckRTEPerms(RangeTblEntry *rte);
106 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
107 static void EvalPlanQualStart(evalPlanQual *epq, EState *estate,
108                                   evalPlanQual *priorepq);
109 static void EvalPlanQualStop(evalPlanQual *epq);
110 static void OpenIntoRel(QueryDesc *queryDesc);
111 static void CloseIntoRel(QueryDesc *queryDesc);
112 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
113 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
114 static void intorel_shutdown(DestReceiver *self);
115 static void intorel_destroy(DestReceiver *self);
116
117 /* end of local decls */
118
119
120 /* ----------------------------------------------------------------
121  *              ExecutorStart
122  *
123  *              This routine must be called at the beginning of any execution of any
124  *              query plan
125  *
126  * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
127  * clear why we bother to separate the two functions, but...).  The tupDesc
128  * field of the QueryDesc is filled in to describe the tuples that will be
129  * returned, and the internal fields (estate and planstate) are set up.
130  *
131  * eflags contains flag bits as described in executor.h.
132  *
133  * NB: the CurrentMemoryContext when this is called will become the parent
134  * of the per-query context used for this Executor invocation.
135  *
136  * We provide a function hook variable that lets loadable plugins
137  * get control when ExecutorStart is called.  Such a plugin would
138  * normally call standard_ExecutorStart().
139  *
140  * ----------------------------------------------------------------
141  */
142 void
143 ExecutorStart(QueryDesc *queryDesc, int eflags)
144 {
145         if (ExecutorStart_hook)
146                 (*ExecutorStart_hook) (queryDesc, eflags);
147         else
148                 standard_ExecutorStart(queryDesc, eflags);
149 }
150
151 void
152 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
153 {
154         EState     *estate;
155         MemoryContext oldcontext;
156
157         /* sanity checks: queryDesc must not be started already */
158         Assert(queryDesc != NULL);
159         Assert(queryDesc->estate == NULL);
160
161         /*
162          * If the transaction is read-only, we need to check if any writes are
163          * planned to non-temporary tables.  EXPLAIN is considered read-only.
164          */
165         if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
166                 ExecCheckXactReadOnly(queryDesc->plannedstmt);
167
168         /*
169          * Build EState, switch into per-query memory context for startup.
170          */
171         estate = CreateExecutorState();
172         queryDesc->estate = estate;
173
174         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
175
176         /*
177          * Fill in parameters, if any, from queryDesc
178          */
179         estate->es_param_list_info = queryDesc->params;
180
181         if (queryDesc->plannedstmt->nParamExec > 0)
182                 estate->es_param_exec_vals = (ParamExecData *)
183                         palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
184
185         /*
186          * If non-read-only query, set the command ID to mark output tuples with
187          */
188         switch (queryDesc->operation)
189         {
190                 case CMD_SELECT:
191                         /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
192                         if (queryDesc->plannedstmt->intoClause != NULL ||
193                                 queryDesc->plannedstmt->rowMarks != NIL)
194                                 estate->es_output_cid = GetCurrentCommandId(true);
195                         break;
196
197                 case CMD_INSERT:
198                 case CMD_DELETE:
199                 case CMD_UPDATE:
200                         estate->es_output_cid = GetCurrentCommandId(true);
201                         break;
202
203                 default:
204                         elog(ERROR, "unrecognized operation code: %d",
205                                  (int) queryDesc->operation);
206                         break;
207         }
208
209         /*
210          * Copy other important information into the EState
211          */
212         estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
213         estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
214         estate->es_instrument = queryDesc->doInstrument;
215
216         /*
217          * Initialize the plan state tree
218          */
219         InitPlan(queryDesc, eflags);
220
221         MemoryContextSwitchTo(oldcontext);
222 }
223
224 /* ----------------------------------------------------------------
225  *              ExecutorRun
226  *
227  *              This is the main routine of the executor module. It accepts
228  *              the query descriptor from the traffic cop and executes the
229  *              query plan.
230  *
231  *              ExecutorStart must have been called already.
232  *
233  *              If direction is NoMovementScanDirection then nothing is done
234  *              except to start up/shut down the destination.  Otherwise,
235  *              we retrieve up to 'count' tuples in the specified direction.
236  *
237  *              Note: count = 0 is interpreted as no portal limit, i.e., run to
238  *              completion.
239  *
240  *              There is no return value, but output tuples (if any) are sent to
241  *              the destination receiver specified in the QueryDesc; and the number
242  *              of tuples processed at the top level can be found in
243  *              estate->es_processed.
244  *
245  *              We provide a function hook variable that lets loadable plugins
246  *              get control when ExecutorRun is called.  Such a plugin would
247  *              normally call standard_ExecutorRun().
248  *
249  * ----------------------------------------------------------------
250  */
251 void
252 ExecutorRun(QueryDesc *queryDesc,
253                         ScanDirection direction, long count)
254 {
255         if (ExecutorRun_hook)
256                 (*ExecutorRun_hook) (queryDesc, direction, count);
257         else
258                 standard_ExecutorRun(queryDesc, direction, count);
259 }
260
261 void
262 standard_ExecutorRun(QueryDesc *queryDesc,
263                                          ScanDirection direction, long count)
264 {
265         EState     *estate;
266         CmdType         operation;
267         DestReceiver *dest;
268         bool            sendTuples;
269         MemoryContext oldcontext;
270
271         /* sanity checks */
272         Assert(queryDesc != NULL);
273
274         estate = queryDesc->estate;
275
276         Assert(estate != NULL);
277
278         /*
279          * Switch into per-query memory context
280          */
281         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
282
283         /* Allow instrumentation of ExecutorRun overall runtime */
284         if (queryDesc->totaltime)
285                 InstrStartNode(queryDesc->totaltime);
286
287         /*
288          * extract information from the query descriptor and the query feature.
289          */
290         operation = queryDesc->operation;
291         dest = queryDesc->dest;
292
293         /*
294          * startup tuple receiver, if we will be emitting tuples
295          */
296         estate->es_processed = 0;
297         estate->es_lastoid = InvalidOid;
298
299         sendTuples = (operation == CMD_SELECT ||
300                                   queryDesc->plannedstmt->returningLists);
301
302         if (sendTuples)
303                 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
304
305         /*
306          * run plan
307          */
308         if (!ScanDirectionIsNoMovement(direction))
309                 ExecutePlan(estate,
310                                         queryDesc->planstate,
311                                         operation,
312                                         count,
313                                         direction,
314                                         dest);
315
316         /*
317          * shutdown tuple receiver, if we started it
318          */
319         if (sendTuples)
320                 (*dest->rShutdown) (dest);
321
322         if (queryDesc->totaltime)
323                 InstrStopNode(queryDesc->totaltime, estate->es_processed);
324
325         MemoryContextSwitchTo(oldcontext);
326 }
327
328 /* ----------------------------------------------------------------
329  *              ExecutorEnd
330  *
331  *              This routine must be called at the end of execution of any
332  *              query plan
333  *
334  *              We provide a function hook variable that lets loadable plugins
335  *              get control when ExecutorEnd is called.  Such a plugin would
336  *              normally call standard_ExecutorEnd().
337  *
338  * ----------------------------------------------------------------
339  */
340 void
341 ExecutorEnd(QueryDesc *queryDesc)
342 {
343         if (ExecutorEnd_hook)
344                 (*ExecutorEnd_hook) (queryDesc);
345         else
346                 standard_ExecutorEnd(queryDesc);
347 }
348
349 void
350 standard_ExecutorEnd(QueryDesc *queryDesc)
351 {
352         EState     *estate;
353         MemoryContext oldcontext;
354
355         /* sanity checks */
356         Assert(queryDesc != NULL);
357
358         estate = queryDesc->estate;
359
360         Assert(estate != NULL);
361
362         /*
363          * Switch into per-query memory context to run ExecEndPlan
364          */
365         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
366
367         ExecEndPlan(queryDesc->planstate, estate);
368
369         /*
370          * Close the SELECT INTO relation if any
371          */
372         if (estate->es_select_into)
373                 CloseIntoRel(queryDesc);
374
375         /* do away with our snapshots */
376         UnregisterSnapshot(estate->es_snapshot);
377         UnregisterSnapshot(estate->es_crosscheck_snapshot);
378
379         /*
380          * Must switch out of context before destroying it
381          */
382         MemoryContextSwitchTo(oldcontext);
383
384         /*
385          * Release EState and per-query memory context.  This should release
386          * everything the executor has allocated.
387          */
388         FreeExecutorState(estate);
389
390         /* Reset queryDesc fields that no longer point to anything */
391         queryDesc->tupDesc = NULL;
392         queryDesc->estate = NULL;
393         queryDesc->planstate = NULL;
394         queryDesc->totaltime = NULL;
395 }
396
397 /* ----------------------------------------------------------------
398  *              ExecutorRewind
399  *
400  *              This routine may be called on an open queryDesc to rewind it
401  *              to the start.
402  * ----------------------------------------------------------------
403  */
404 void
405 ExecutorRewind(QueryDesc *queryDesc)
406 {
407         EState     *estate;
408         MemoryContext oldcontext;
409
410         /* sanity checks */
411         Assert(queryDesc != NULL);
412
413         estate = queryDesc->estate;
414
415         Assert(estate != NULL);
416
417         /* It's probably not sensible to rescan updating queries */
418         Assert(queryDesc->operation == CMD_SELECT);
419
420         /*
421          * Switch into per-query memory context
422          */
423         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
424
425         /*
426          * rescan plan
427          */
428         ExecReScan(queryDesc->planstate, NULL);
429
430         MemoryContextSwitchTo(oldcontext);
431 }
432
433
434 /*
435  * ExecCheckRTPerms
436  *              Check access permissions for all relations listed in a range table.
437  */
438 static void
439 ExecCheckRTPerms(List *rangeTable)
440 {
441         ListCell   *l;
442
443         foreach(l, rangeTable)
444         {
445                 ExecCheckRTEPerms((RangeTblEntry *) lfirst(l));
446         }
447 }
448
449 /*
450  * ExecCheckRTEPerms
451  *              Check access permissions for a single RTE.
452  */
453 static void
454 ExecCheckRTEPerms(RangeTblEntry *rte)
455 {
456         AclMode         requiredPerms;
457         AclMode         relPerms;
458         AclMode         remainingPerms;
459         Oid                     relOid;
460         Oid                     userid;
461         Bitmapset  *tmpset;
462         int                     col;
463
464         /*
465          * Only plain-relation RTEs need to be checked here.  Function RTEs are
466          * checked by init_fcache when the function is prepared for execution.
467          * Join, subquery, and special RTEs need no checks.
468          */
469         if (rte->rtekind != RTE_RELATION)
470                 return;
471
472         /*
473          * No work if requiredPerms is empty.
474          */
475         requiredPerms = rte->requiredPerms;
476         if (requiredPerms == 0)
477                 return;
478
479         relOid = rte->relid;
480
481         /*
482          * userid to check as: current user unless we have a setuid indication.
483          *
484          * Note: GetUserId() is presently fast enough that there's no harm in
485          * calling it separately for each RTE.  If that stops being true, we could
486          * call it once in ExecCheckRTPerms and pass the userid down from there.
487          * But for now, no need for the extra clutter.
488          */
489         userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
490
491         /*
492          * We must have *all* the requiredPerms bits, but some of the bits can be
493          * satisfied from column-level rather than relation-level permissions.
494          * First, remove any bits that are satisfied by relation permissions.
495          */
496         relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
497         remainingPerms = requiredPerms & ~relPerms;
498         if (remainingPerms != 0)
499         {
500                 /*
501                  * If we lack any permissions that exist only as relation permissions,
502                  * we can fail straight away.
503                  */
504                 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
505                         aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
506                                                    get_rel_name(relOid));
507
508                 /*
509                  * Check to see if we have the needed privileges at column level.
510                  *
511                  * Note: failures just report a table-level error; it would be nicer
512                  * to report a column-level error if we have some but not all of the
513                  * column privileges.
514                  */
515                 if (remainingPerms & ACL_SELECT)
516                 {
517                         /*
518                          * When the query doesn't explicitly reference any columns (for
519                          * example, SELECT COUNT(*) FROM table), allow the query if we
520                          * have SELECT on any column of the rel, as per SQL spec.
521                          */
522                         if (bms_is_empty(rte->selectedCols))
523                         {
524                                 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
525                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
526                                         aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
527                                                                    get_rel_name(relOid));
528                         }
529
530                         tmpset = bms_copy(rte->selectedCols);
531                         while ((col = bms_first_member(tmpset)) >= 0)
532                         {
533                                 /* remove the column number offset */
534                                 col += FirstLowInvalidHeapAttributeNumber;
535                                 if (col == InvalidAttrNumber)
536                                 {
537                                         /* Whole-row reference, must have priv on all cols */
538                                         if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
539                                                                                                   ACLMASK_ALL) != ACLCHECK_OK)
540                                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
541                                                                            get_rel_name(relOid));
542                                 }
543                                 else
544                                 {
545                                         if (pg_attribute_aclcheck(relOid, col, userid, ACL_SELECT)
546                                                 != ACLCHECK_OK)
547                                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
548                                                                            get_rel_name(relOid));
549                                 }
550                         }
551                         bms_free(tmpset);
552                 }
553
554                 /*
555                  * Basically the same for the mod columns, with either INSERT or UPDATE
556                  * privilege as specified by remainingPerms.
557                  */
558                 remainingPerms &= ~ACL_SELECT;
559                 if (remainingPerms != 0)
560                 {
561                         /*
562                          * When the query doesn't explicitly change any columns, allow
563                          * the query if we have permission on any column of the rel.  This
564                          * is to handle SELECT FOR UPDATE as well as possible corner cases
565                          * in INSERT and UPDATE.
566                          */
567                         if (bms_is_empty(rte->modifiedCols))
568                         {
569                                 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
570                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
571                                         aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
572                                                                    get_rel_name(relOid));
573                         }
574
575                         tmpset = bms_copy(rte->modifiedCols);
576                         while ((col = bms_first_member(tmpset)) >= 0)
577                         {
578                                 /* remove the column number offset */
579                                 col += FirstLowInvalidHeapAttributeNumber;
580                                 if (col == InvalidAttrNumber)
581                                 {
582                                         /* whole-row reference can't happen here */
583                                         elog(ERROR, "whole-row update is not implemented");
584                                 }
585                                 else
586                                 {
587                                         if (pg_attribute_aclcheck(relOid, col, userid, remainingPerms)
588                                                 != ACLCHECK_OK)
589                                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
590                                                                            get_rel_name(relOid));
591                                 }
592                         }
593                         bms_free(tmpset);
594                 }
595         }
596 }
597
598 /*
599  * Check that the query does not imply any writes to non-temp tables.
600  */
601 static void
602 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
603 {
604         ListCell   *l;
605
606         /*
607          * CREATE TABLE AS or SELECT INTO?
608          *
609          * XXX should we allow this if the destination is temp?
610          */
611         if (plannedstmt->intoClause != NULL)
612                 goto fail;
613
614         /* Fail if write permissions are requested on any non-temp table */
615         foreach(l, plannedstmt->rtable)
616         {
617                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
618
619                 if (rte->rtekind != RTE_RELATION)
620                         continue;
621
622                 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
623                         continue;
624
625                 if (isTempNamespace(get_rel_namespace(rte->relid)))
626                         continue;
627
628                 goto fail;
629         }
630
631         return;
632
633 fail:
634         ereport(ERROR,
635                         (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
636                          errmsg("transaction is read-only")));
637 }
638
639
640 /* ----------------------------------------------------------------
641  *              InitPlan
642  *
643  *              Initializes the query plan: open files, allocate storage
644  *              and start up the rule manager
645  * ----------------------------------------------------------------
646  */
647 static void
648 InitPlan(QueryDesc *queryDesc, int eflags)
649 {
650         CmdType         operation = queryDesc->operation;
651         PlannedStmt *plannedstmt = queryDesc->plannedstmt;
652         Plan       *plan = plannedstmt->planTree;
653         List       *rangeTable = plannedstmt->rtable;
654         EState     *estate = queryDesc->estate;
655         PlanState  *planstate;
656         TupleDesc       tupType;
657         ListCell   *l;
658         int                     i;
659
660         /*
661          * Do permissions checks
662          */
663         ExecCheckRTPerms(rangeTable);
664
665         /*
666          * initialize the node's execution state
667          */
668         estate->es_range_table = rangeTable;
669
670         /*
671          * initialize result relation stuff
672          */
673         if (plannedstmt->resultRelations)
674         {
675                 List       *resultRelations = plannedstmt->resultRelations;
676                 int                     numResultRelations = list_length(resultRelations);
677                 ResultRelInfo *resultRelInfos;
678                 ResultRelInfo *resultRelInfo;
679
680                 resultRelInfos = (ResultRelInfo *)
681                         palloc(numResultRelations * sizeof(ResultRelInfo));
682                 resultRelInfo = resultRelInfos;
683                 foreach(l, resultRelations)
684                 {
685                         Index           resultRelationIndex = lfirst_int(l);
686                         Oid                     resultRelationOid;
687                         Relation        resultRelation;
688
689                         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
690                         resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
691                         InitResultRelInfo(resultRelInfo,
692                                                           resultRelation,
693                                                           resultRelationIndex,
694                                                           operation,
695                                                           estate->es_instrument);
696                         resultRelInfo++;
697                 }
698                 estate->es_result_relations = resultRelInfos;
699                 estate->es_num_result_relations = numResultRelations;
700                 /* Initialize to first or only result rel */
701                 estate->es_result_relation_info = resultRelInfos;
702         }
703         else
704         {
705                 /*
706                  * if no result relation, then set state appropriately
707                  */
708                 estate->es_result_relations = NULL;
709                 estate->es_num_result_relations = 0;
710                 estate->es_result_relation_info = NULL;
711         }
712
713         /*
714          * Detect whether we're doing SELECT INTO.  If so, set the es_into_oids
715          * flag appropriately so that the plan tree will be initialized with the
716          * correct tuple descriptors.  (Other SELECT INTO stuff comes later.)
717          */
718         estate->es_select_into = false;
719         if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
720         {
721                 estate->es_select_into = true;
722                 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
723         }
724
725         /*
726          * Have to lock relations selected FOR UPDATE/FOR SHARE before we
727          * initialize the plan tree, else we'd be doing a lock upgrade. While we
728          * are at it, build the ExecRowMark list.
729          */
730         estate->es_rowMarks = NIL;
731         foreach(l, plannedstmt->rowMarks)
732         {
733                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
734                 Oid                     relid;
735                 Relation        relation;
736                 ExecRowMark *erm;
737
738                 /* ignore "parent" rowmarks; they are irrelevant at runtime */
739                 if (rc->isParent)
740                         continue;
741
742                 relid = getrelid(rc->rti, rangeTable);
743                 relation = heap_open(relid, RowShareLock);
744                 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
745                 erm->relation = relation;
746                 erm->rti = rc->rti;
747                 erm->prti = rc->prti;
748                 erm->forUpdate = rc->forUpdate;
749                 erm->noWait = rc->noWait;
750                 /* We'll locate the junk attrs below */
751                 erm->ctidAttNo = InvalidAttrNumber;
752                 erm->toidAttNo = InvalidAttrNumber;
753                 ItemPointerSetInvalid(&(erm->curCtid));
754                 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
755         }
756
757         /*
758          * Initialize the executor "tuple" table.  We need slots for all the plan
759          * nodes, plus possibly output slots for the junkfilter(s). At this point
760          * we aren't sure if we need junkfilters, so just add slots for them
761          * unconditionally.  Also, if it's not a SELECT, set up a slot for use for
762          * trigger output tuples.  Also, one for RETURNING-list evaluation.
763          */
764         {
765                 int                     nSlots;
766
767                 /* Slots for the main plan tree */
768                 nSlots = ExecCountSlotsNode(plan);
769                 /* Add slots for subplans and initplans */
770                 foreach(l, plannedstmt->subplans)
771                 {
772                         Plan       *subplan = (Plan *) lfirst(l);
773
774                         nSlots += ExecCountSlotsNode(subplan);
775                 }
776                 /* Add slots for junkfilter(s) */
777                 if (plannedstmt->resultRelations != NIL)
778                         nSlots += list_length(plannedstmt->resultRelations);
779                 else
780                         nSlots += 1;
781                 if (operation != CMD_SELECT)
782                         nSlots++;                       /* for es_trig_tuple_slot */
783                 if (plannedstmt->returningLists)
784                         nSlots++;                       /* for RETURNING projection */
785
786                 estate->es_tupleTable = ExecCreateTupleTable(nSlots);
787
788                 if (operation != CMD_SELECT)
789                         estate->es_trig_tuple_slot =
790                                 ExecAllocTableSlot(estate->es_tupleTable);
791         }
792
793         /* mark EvalPlanQual not active */
794         estate->es_plannedstmt = plannedstmt;
795         estate->es_evalPlanQual = NULL;
796         estate->es_evTupleNull = NULL;
797         estate->es_evTuple = NULL;
798         estate->es_useEvalPlan = false;
799
800         /*
801          * Initialize private state information for each SubPlan.  We must do this
802          * before running ExecInitNode on the main query tree, since
803          * ExecInitSubPlan expects to be able to find these entries.
804          */
805         Assert(estate->es_subplanstates == NIL);
806         i = 1;                                          /* subplan indices count from 1 */
807         foreach(l, plannedstmt->subplans)
808         {
809                 Plan       *subplan = (Plan *) lfirst(l);
810                 PlanState  *subplanstate;
811                 int                     sp_eflags;
812
813                 /*
814                  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
815                  * it is a parameterless subplan (not initplan), we suggest that it be
816                  * prepared to handle REWIND efficiently; otherwise there is no need.
817                  */
818                 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
819                 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
820                         sp_eflags |= EXEC_FLAG_REWIND;
821
822                 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
823
824                 estate->es_subplanstates = lappend(estate->es_subplanstates,
825                                                                                    subplanstate);
826
827                 i++;
828         }
829
830         /*
831          * Initialize the private state information for all the nodes in the query
832          * tree.  This opens files, allocates storage and leaves us ready to start
833          * processing tuples.
834          */
835         planstate = ExecInitNode(plan, estate, eflags);
836
837         /*
838          * Get the tuple descriptor describing the type of tuples to return. (this
839          * is especially important if we are creating a relation with "SELECT
840          * INTO")
841          */
842         tupType = ExecGetResultType(planstate);
843
844         /*
845          * Initialize the junk filter if needed.  SELECT and INSERT queries need a
846          * filter if there are any junk attrs in the tlist.  UPDATE and
847          * DELETE always need a filter, since there's always a junk 'ctid'
848          * attribute present --- no need to look first.
849          *
850          * This section of code is also a convenient place to verify that the
851          * output of an INSERT or UPDATE matches the target table(s).
852          */
853         {
854                 bool            junk_filter_needed = false;
855                 ListCell   *tlist;
856
857                 switch (operation)
858                 {
859                         case CMD_SELECT:
860                         case CMD_INSERT:
861                                 foreach(tlist, plan->targetlist)
862                                 {
863                                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
864
865                                         if (tle->resjunk)
866                                         {
867                                                 junk_filter_needed = true;
868                                                 break;
869                                         }
870                                 }
871                                 break;
872                         case CMD_UPDATE:
873                         case CMD_DELETE:
874                                 junk_filter_needed = true;
875                                 break;
876                         default:
877                                 break;
878                 }
879
880                 if (junk_filter_needed)
881                 {
882                         /*
883                          * If there are multiple result relations, each one needs its own
884                          * junk filter.  Note this is only possible for UPDATE/DELETE, so
885                          * we can't be fooled by some needing a filter and some not.
886                          */
887                         if (list_length(plannedstmt->resultRelations) > 1)
888                         {
889                                 PlanState **appendplans;
890                                 int                     as_nplans;
891                                 ResultRelInfo *resultRelInfo;
892
893                                 /* Top plan had better be an Append here. */
894                                 Assert(IsA(plan, Append));
895                                 Assert(((Append *) plan)->isTarget);
896                                 Assert(IsA(planstate, AppendState));
897                                 appendplans = ((AppendState *) planstate)->appendplans;
898                                 as_nplans = ((AppendState *) planstate)->as_nplans;
899                                 Assert(as_nplans == estate->es_num_result_relations);
900                                 resultRelInfo = estate->es_result_relations;
901                                 for (i = 0; i < as_nplans; i++)
902                                 {
903                                         PlanState  *subplan = appendplans[i];
904                                         JunkFilter *j;
905
906                                         if (operation == CMD_UPDATE)
907                                                 ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc,
908                                                                                         subplan->plan->targetlist);
909
910                                         j = ExecInitJunkFilter(subplan->plan->targetlist,
911                                                         resultRelInfo->ri_RelationDesc->rd_att->tdhasoid,
912                                                                   ExecAllocTableSlot(estate->es_tupleTable));
913
914                                         /*
915                                          * Since it must be UPDATE/DELETE, there had better be a
916                                          * "ctid" junk attribute in the tlist ... but ctid could
917                                          * be at a different resno for each result relation. We
918                                          * look up the ctid resnos now and save them in the
919                                          * junkfilters.
920                                          */
921                                         j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
922                                         if (!AttributeNumberIsValid(j->jf_junkAttNo))
923                                                 elog(ERROR, "could not find junk ctid column");
924                                         resultRelInfo->ri_junkFilter = j;
925                                         resultRelInfo++;
926                                 }
927
928                                 /*
929                                  * Set active junkfilter too; at this point ExecInitAppend has
930                                  * already selected an active result relation...
931                                  */
932                                 estate->es_junkFilter =
933                                         estate->es_result_relation_info->ri_junkFilter;
934
935                                 /*
936                                  * We currently can't support rowmarks in this case, because
937                                  * the associated junk CTIDs might have different resnos in
938                                  * different subplans.
939                                  */
940                                 if (estate->es_rowMarks)
941                                         ereport(ERROR,
942                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
943                                                          errmsg("SELECT FOR UPDATE/SHARE is not supported within a query with multiple result relations")));
944                         }
945                         else
946                         {
947                                 /* Normal case with just one JunkFilter */
948                                 JunkFilter *j;
949
950                                 if (operation == CMD_INSERT || operation == CMD_UPDATE)
951                                         ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
952                                                                                 planstate->plan->targetlist);
953
954                                 j = ExecInitJunkFilter(planstate->plan->targetlist,
955                                                                            tupType->tdhasoid,
956                                                                   ExecAllocTableSlot(estate->es_tupleTable));
957                                 estate->es_junkFilter = j;
958                                 if (estate->es_result_relation_info)
959                                         estate->es_result_relation_info->ri_junkFilter = j;
960
961                                 if (operation == CMD_SELECT)
962                                 {
963                                         /* For SELECT, want to return the cleaned tuple type */
964                                         tupType = j->jf_cleanTupType;
965                                 }
966                                 else if (operation == CMD_UPDATE || operation == CMD_DELETE)
967                                 {
968                                         /* For UPDATE/DELETE, find the ctid junk attr now */
969                                         j->jf_junkAttNo = ExecFindJunkAttribute(j, "ctid");
970                                         if (!AttributeNumberIsValid(j->jf_junkAttNo))
971                                                 elog(ERROR, "could not find junk ctid column");
972                                 }
973
974                                 /* For SELECT FOR UPDATE/SHARE, find the junk attrs now */
975                                 foreach(l, estate->es_rowMarks)
976                                 {
977                                         ExecRowMark *erm = (ExecRowMark *) lfirst(l);
978                                         char            resname[32];
979
980                                         /* always need the ctid */
981                                         snprintf(resname, sizeof(resname), "ctid%u",
982                                                          erm->prti);
983                                         erm->ctidAttNo = ExecFindJunkAttribute(j, resname);
984                                         if (!AttributeNumberIsValid(erm->ctidAttNo))
985                                                 elog(ERROR, "could not find junk \"%s\" column",
986                                                          resname);
987                                         /* if child relation, need tableoid too */
988                                         if (erm->rti != erm->prti)
989                                         {
990                                                 snprintf(resname, sizeof(resname), "tableoid%u",
991                                                                  erm->prti);
992                                                 erm->toidAttNo = ExecFindJunkAttribute(j, resname);
993                                                 if (!AttributeNumberIsValid(erm->toidAttNo))
994                                                         elog(ERROR, "could not find junk \"%s\" column",
995                                                                  resname);
996                                         }
997                                 }
998                         }
999                 }
1000                 else
1001                 {
1002                         if (operation == CMD_INSERT)
1003                                 ExecCheckPlanOutput(estate->es_result_relation_info->ri_RelationDesc,
1004                                                                         planstate->plan->targetlist);
1005
1006                         estate->es_junkFilter = NULL;
1007                         if (estate->es_rowMarks)
1008                                 elog(ERROR, "SELECT FOR UPDATE/SHARE, but no junk columns");
1009                 }
1010         }
1011
1012         /*
1013          * Initialize RETURNING projections if needed.
1014          */
1015         if (plannedstmt->returningLists)
1016         {
1017                 TupleTableSlot *slot;
1018                 ExprContext *econtext;
1019                 ResultRelInfo *resultRelInfo;
1020
1021                 /*
1022                  * We set QueryDesc.tupDesc to be the RETURNING rowtype in this case.
1023                  * We assume all the sublists will generate the same output tupdesc.
1024                  */
1025                 tupType = ExecTypeFromTL((List *) linitial(plannedstmt->returningLists),
1026                                                                  false);
1027
1028                 /* Set up a slot for the output of the RETURNING projection(s) */
1029                 slot = ExecAllocTableSlot(estate->es_tupleTable);
1030                 ExecSetSlotDescriptor(slot, tupType);
1031                 /* Need an econtext too */
1032                 econtext = CreateExprContext(estate);
1033
1034                 /*
1035                  * Build a projection for each result rel.      Note that any SubPlans in
1036                  * the RETURNING lists get attached to the topmost plan node.
1037                  */
1038                 Assert(list_length(plannedstmt->returningLists) == estate->es_num_result_relations);
1039                 resultRelInfo = estate->es_result_relations;
1040                 foreach(l, plannedstmt->returningLists)
1041                 {
1042                         List       *rlist = (List *) lfirst(l);
1043                         List       *rliststate;
1044
1045                         rliststate = (List *) ExecInitExpr((Expr *) rlist, planstate);
1046                         resultRelInfo->ri_projectReturning =
1047                                 ExecBuildProjectionInfo(rliststate, econtext, slot,
1048                                                                          resultRelInfo->ri_RelationDesc->rd_att);
1049                         resultRelInfo++;
1050                 }
1051         }
1052
1053         queryDesc->tupDesc = tupType;
1054         queryDesc->planstate = planstate;
1055
1056         /*
1057          * If doing SELECT INTO, initialize the "into" relation.  We must wait
1058          * till now so we have the "clean" result tuple type to create the new
1059          * table from.
1060          *
1061          * If EXPLAIN, skip creating the "into" relation.
1062          */
1063         if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
1064                 OpenIntoRel(queryDesc);
1065 }
1066
1067 /*
1068  * Initialize ResultRelInfo data for one result relation
1069  */
1070 void
1071 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1072                                   Relation resultRelationDesc,
1073                                   Index resultRelationIndex,
1074                                   CmdType operation,
1075                                   bool doInstrument)
1076 {
1077         /*
1078          * Check valid relkind ... parser and/or planner should have noticed this
1079          * already, but let's make sure.
1080          */
1081         switch (resultRelationDesc->rd_rel->relkind)
1082         {
1083                 case RELKIND_RELATION:
1084                         /* OK */
1085                         break;
1086                 case RELKIND_SEQUENCE:
1087                         ereport(ERROR,
1088                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1089                                          errmsg("cannot change sequence \"%s\"",
1090                                                         RelationGetRelationName(resultRelationDesc))));
1091                         break;
1092                 case RELKIND_TOASTVALUE:
1093                         ereport(ERROR,
1094                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1095                                          errmsg("cannot change TOAST relation \"%s\"",
1096                                                         RelationGetRelationName(resultRelationDesc))));
1097                         break;
1098                 case RELKIND_VIEW:
1099                         ereport(ERROR,
1100                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1101                                          errmsg("cannot change view \"%s\"",
1102                                                         RelationGetRelationName(resultRelationDesc))));
1103                         break;
1104                 default:
1105                         ereport(ERROR,
1106                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1107                                          errmsg("cannot change relation \"%s\"",
1108                                                         RelationGetRelationName(resultRelationDesc))));
1109                         break;
1110         }
1111
1112         /* OK, fill in the node */
1113         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1114         resultRelInfo->type = T_ResultRelInfo;
1115         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1116         resultRelInfo->ri_RelationDesc = resultRelationDesc;
1117         resultRelInfo->ri_NumIndices = 0;
1118         resultRelInfo->ri_IndexRelationDescs = NULL;
1119         resultRelInfo->ri_IndexRelationInfo = NULL;
1120         /* make a copy so as not to depend on relcache info not changing... */
1121         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1122         if (resultRelInfo->ri_TrigDesc)
1123         {
1124                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
1125
1126                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1127                         palloc0(n * sizeof(FmgrInfo));
1128                 if (doInstrument)
1129                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n);
1130                 else
1131                         resultRelInfo->ri_TrigInstrument = NULL;
1132         }
1133         else
1134         {
1135                 resultRelInfo->ri_TrigFunctions = NULL;
1136                 resultRelInfo->ri_TrigInstrument = NULL;
1137         }
1138         resultRelInfo->ri_ConstraintExprs = NULL;
1139         resultRelInfo->ri_junkFilter = NULL;
1140         resultRelInfo->ri_projectReturning = NULL;
1141
1142         /*
1143          * If there are indices on the result relation, open them and save
1144          * descriptors in the result relation info, so that we can add new index
1145          * entries for the tuples we add/update.  We need not do this for a
1146          * DELETE, however, since deletion doesn't affect indexes.
1147          */
1148         if (resultRelationDesc->rd_rel->relhasindex &&
1149                 operation != CMD_DELETE)
1150                 ExecOpenIndices(resultRelInfo);
1151 }
1152
1153 /*
1154  * Verify that the tuples to be produced by INSERT or UPDATE match the
1155  * target relation's rowtype
1156  *
1157  * We do this to guard against stale plans.  If plan invalidation is
1158  * functioning properly then we should never get a failure here, but better
1159  * safe than sorry.  Note that this is called after we have obtained lock
1160  * on the target rel, so the rowtype can't change underneath us.
1161  *
1162  * The plan output is represented by its targetlist, because that makes
1163  * handling the dropped-column case easier.
1164  */
1165 static void
1166 ExecCheckPlanOutput(Relation resultRel, List *targetList)
1167 {
1168         TupleDesc       resultDesc = RelationGetDescr(resultRel);
1169         int                     attno = 0;
1170         ListCell   *lc;
1171
1172         foreach(lc, targetList)
1173         {
1174                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1175                 Form_pg_attribute attr;
1176
1177                 if (tle->resjunk)
1178                         continue;                       /* ignore junk tlist items */
1179
1180                 if (attno >= resultDesc->natts)
1181                         ereport(ERROR,
1182                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1183                                          errmsg("table row type and query-specified row type do not match"),
1184                                          errdetail("Query has too many columns.")));
1185                 attr = resultDesc->attrs[attno++];
1186
1187                 if (!attr->attisdropped)
1188                 {
1189                         /* Normal case: demand type match */
1190                         if (exprType((Node *) tle->expr) != attr->atttypid)
1191                                 ereport(ERROR,
1192                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1193                                                  errmsg("table row type and query-specified row type do not match"),
1194                                                  errdetail("Table has type %s at ordinal position %d, but query expects %s.",
1195                                                                    format_type_be(attr->atttypid),
1196                                                                    attno,
1197                                                                    format_type_be(exprType((Node *) tle->expr)))));
1198                 }
1199                 else
1200                 {
1201                         /*
1202                          * For a dropped column, we can't check atttypid (it's likely 0).
1203                          * In any case the planner has most likely inserted an INT4 null.
1204                          * What we insist on is just *some* NULL constant.
1205                          */
1206                         if (!IsA(tle->expr, Const) ||
1207                                 !((Const *) tle->expr)->constisnull)
1208                                 ereport(ERROR,
1209                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1210                                                  errmsg("table row type and query-specified row type do not match"),
1211                                                  errdetail("Query provides a value for a dropped column at ordinal position %d.",
1212                                                                    attno)));
1213                 }
1214         }
1215         if (attno != resultDesc->natts)
1216                 ereport(ERROR,
1217                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1218                                  errmsg("table row type and query-specified row type do not match"),
1219                                  errdetail("Query has too few columns.")));
1220 }
1221
1222 /*
1223  *              ExecGetTriggerResultRel
1224  *
1225  * Get a ResultRelInfo for a trigger target relation.  Most of the time,
1226  * triggers are fired on one of the result relations of the query, and so
1227  * we can just return a member of the es_result_relations array.  (Note: in
1228  * self-join situations there might be multiple members with the same OID;
1229  * if so it doesn't matter which one we pick.)  However, it is sometimes
1230  * necessary to fire triggers on other relations; this happens mainly when an
1231  * RI update trigger queues additional triggers on other relations, which will
1232  * be processed in the context of the outer query.      For efficiency's sake,
1233  * we want to have a ResultRelInfo for those triggers too; that can avoid
1234  * repeated re-opening of the relation.  (It also provides a way for EXPLAIN
1235  * ANALYZE to report the runtimes of such triggers.)  So we make additional
1236  * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1237  */
1238 ResultRelInfo *
1239 ExecGetTriggerResultRel(EState *estate, Oid relid)
1240 {
1241         ResultRelInfo *rInfo;
1242         int                     nr;
1243         ListCell   *l;
1244         Relation        rel;
1245         MemoryContext oldcontext;
1246
1247         /* First, search through the query result relations */
1248         rInfo = estate->es_result_relations;
1249         nr = estate->es_num_result_relations;
1250         while (nr > 0)
1251         {
1252                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1253                         return rInfo;
1254                 rInfo++;
1255                 nr--;
1256         }
1257         /* Nope, but maybe we already made an extra ResultRelInfo for it */
1258         foreach(l, estate->es_trig_target_relations)
1259         {
1260                 rInfo = (ResultRelInfo *) lfirst(l);
1261                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1262                         return rInfo;
1263         }
1264         /* Nope, so we need a new one */
1265
1266         /*
1267          * Open the target relation's relcache entry.  We assume that an
1268          * appropriate lock is still held by the backend from whenever the trigger
1269          * event got queued, so we need take no new lock here.
1270          */
1271         rel = heap_open(relid, NoLock);
1272
1273         /*
1274          * Make the new entry in the right context.  Currently, we don't need any
1275          * index information in ResultRelInfos used only for triggers, so tell
1276          * InitResultRelInfo it's a DELETE.
1277          */
1278         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1279         rInfo = makeNode(ResultRelInfo);
1280         InitResultRelInfo(rInfo,
1281                                           rel,
1282                                           0,            /* dummy rangetable index */
1283                                           CMD_DELETE,
1284                                           estate->es_instrument);
1285         estate->es_trig_target_relations =
1286                 lappend(estate->es_trig_target_relations, rInfo);
1287         MemoryContextSwitchTo(oldcontext);
1288
1289         return rInfo;
1290 }
1291
1292 /*
1293  *              ExecContextForcesOids
1294  *
1295  * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1296  * we need to ensure that result tuples have space for an OID iff they are
1297  * going to be stored into a relation that has OIDs.  In other contexts
1298  * we are free to choose whether to leave space for OIDs in result tuples
1299  * (we generally don't want to, but we do if a physical-tlist optimization
1300  * is possible).  This routine checks the plan context and returns TRUE if the
1301  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
1302  * *hasoids is set to the required value.
1303  *
1304  * One reason this is ugly is that all plan nodes in the plan tree will emit
1305  * tuples with space for an OID, though we really only need the topmost node
1306  * to do so.  However, node types like Sort don't project new tuples but just
1307  * return their inputs, and in those cases the requirement propagates down
1308  * to the input node.  Eventually we might make this code smart enough to
1309  * recognize how far down the requirement really goes, but for now we just
1310  * make all plan nodes do the same thing if the top level forces the choice.
1311  *
1312  * We assume that estate->es_result_relation_info is already set up to
1313  * describe the target relation.  Note that in an UPDATE that spans an
1314  * inheritance tree, some of the target relations may have OIDs and some not.
1315  * We have to make the decisions on a per-relation basis as we initialize
1316  * each of the child plans of the topmost Append plan.
1317  *
1318  * SELECT INTO is even uglier, because we don't have the INTO relation's
1319  * descriptor available when this code runs; we have to look aside at a
1320  * flag set by InitPlan().
1321  */
1322 bool
1323 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1324 {
1325         if (planstate->state->es_select_into)
1326         {
1327                 *hasoids = planstate->state->es_into_oids;
1328                 return true;
1329         }
1330         else
1331         {
1332                 ResultRelInfo *ri = planstate->state->es_result_relation_info;
1333
1334                 if (ri != NULL)
1335                 {
1336                         Relation        rel = ri->ri_RelationDesc;
1337
1338                         if (rel != NULL)
1339                         {
1340                                 *hasoids = rel->rd_rel->relhasoids;
1341                                 return true;
1342                         }
1343                 }
1344         }
1345
1346         return false;
1347 }
1348
1349 /* ----------------------------------------------------------------
1350  *              ExecEndPlan
1351  *
1352  *              Cleans up the query plan -- closes files and frees up storage
1353  *
1354  * NOTE: we are no longer very worried about freeing storage per se
1355  * in this code; FreeExecutorState should be guaranteed to release all
1356  * memory that needs to be released.  What we are worried about doing
1357  * is closing relations and dropping buffer pins.  Thus, for example,
1358  * tuple tables must be cleared or dropped to ensure pins are released.
1359  * ----------------------------------------------------------------
1360  */
1361 static void
1362 ExecEndPlan(PlanState *planstate, EState *estate)
1363 {
1364         ResultRelInfo *resultRelInfo;
1365         int                     i;
1366         ListCell   *l;
1367
1368         /*
1369          * shut down any PlanQual processing we were doing
1370          */
1371         if (estate->es_evalPlanQual != NULL)
1372                 EndEvalPlanQual(estate);
1373
1374         /*
1375          * shut down the node-type-specific query processing
1376          */
1377         ExecEndNode(planstate);
1378
1379         /*
1380          * for subplans too
1381          */
1382         foreach(l, estate->es_subplanstates)
1383         {
1384                 PlanState  *subplanstate = (PlanState *) lfirst(l);
1385
1386                 ExecEndNode(subplanstate);
1387         }
1388
1389         /*
1390          * destroy the executor "tuple" table.
1391          */
1392         ExecDropTupleTable(estate->es_tupleTable, true);
1393         estate->es_tupleTable = NULL;
1394
1395         /*
1396          * close the result relation(s) if any, but hold locks until xact commit.
1397          */
1398         resultRelInfo = estate->es_result_relations;
1399         for (i = estate->es_num_result_relations; i > 0; i--)
1400         {
1401                 /* Close indices and then the relation itself */
1402                 ExecCloseIndices(resultRelInfo);
1403                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1404                 resultRelInfo++;
1405         }
1406
1407         /*
1408          * likewise close any trigger target relations
1409          */
1410         foreach(l, estate->es_trig_target_relations)
1411         {
1412                 resultRelInfo = (ResultRelInfo *) lfirst(l);
1413                 /* Close indices and then the relation itself */
1414                 ExecCloseIndices(resultRelInfo);
1415                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1416         }
1417
1418         /*
1419          * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1420          */
1421         foreach(l, estate->es_rowMarks)
1422         {
1423                 ExecRowMark *erm = lfirst(l);
1424
1425                 heap_close(erm->relation, NoLock);
1426         }
1427 }
1428
1429 /* ----------------------------------------------------------------
1430  *              ExecutePlan
1431  *
1432  *              Processes the query plan until we have processed 'numberTuples' tuples,
1433  *              moving in the specified direction.
1434  *
1435  *              Runs to completion if numberTuples is 0
1436  *
1437  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1438  * user can see it
1439  * ----------------------------------------------------------------
1440  */
1441 static void
1442 ExecutePlan(EState *estate,
1443                         PlanState *planstate,
1444                         CmdType operation,
1445                         long numberTuples,
1446                         ScanDirection direction,
1447                         DestReceiver *dest)
1448 {
1449         JunkFilter *junkfilter;
1450         TupleTableSlot *planSlot;
1451         TupleTableSlot *slot;
1452         ItemPointer tupleid = NULL;
1453         ItemPointerData tuple_ctid;
1454         long            current_tuple_count;
1455
1456         /*
1457          * initialize local variables
1458          */
1459         current_tuple_count = 0;
1460
1461         /*
1462          * Set the direction.
1463          */
1464         estate->es_direction = direction;
1465
1466         /*
1467          * Process BEFORE EACH STATEMENT triggers
1468          */
1469         switch (operation)
1470         {
1471                 case CMD_UPDATE:
1472                         ExecBSUpdateTriggers(estate, estate->es_result_relation_info);
1473                         break;
1474                 case CMD_DELETE:
1475                         ExecBSDeleteTriggers(estate, estate->es_result_relation_info);
1476                         break;
1477                 case CMD_INSERT:
1478                         ExecBSInsertTriggers(estate, estate->es_result_relation_info);
1479                         break;
1480                 default:
1481                         /* do nothing */
1482                         break;
1483         }
1484
1485         /*
1486          * Loop until we've processed the proper number of tuples from the plan.
1487          */
1488         for (;;)
1489         {
1490                 /* Reset the per-output-tuple exprcontext */
1491                 ResetPerTupleExprContext(estate);
1492
1493                 /*
1494                  * Execute the plan and obtain a tuple
1495                  */
1496 lnext:  ;
1497                 if (estate->es_useEvalPlan)
1498                 {
1499                         planSlot = EvalPlanQualNext(estate);
1500                         if (TupIsNull(planSlot))
1501                                 planSlot = ExecProcNode(planstate);
1502                 }
1503                 else
1504                         planSlot = ExecProcNode(planstate);
1505
1506                 /*
1507                  * if the tuple is null, then we assume there is nothing more to
1508                  * process so we just end the loop...
1509                  */
1510                 if (TupIsNull(planSlot))
1511                         break;
1512                 slot = planSlot;
1513
1514                 /*
1515                  * If we have a junk filter, then project a new tuple with the junk
1516                  * removed.
1517                  *
1518                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1519                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1520                  * because that tuple slot has the wrong descriptor.)
1521                  *
1522                  * But first, extract all the junk information we need.
1523                  */
1524                 if ((junkfilter = estate->es_junkFilter) != NULL)
1525                 {
1526                         /*
1527                          * Process any FOR UPDATE or FOR SHARE locking requested.
1528                          */
1529                         if (estate->es_rowMarks != NIL)
1530                         {
1531                                 ListCell   *l;
1532
1533                 lmark:  ;
1534                                 foreach(l, estate->es_rowMarks)
1535                                 {
1536                                         ExecRowMark *erm = lfirst(l);
1537                                         Datum           datum;
1538                                         bool            isNull;
1539                                         HeapTupleData tuple;
1540                                         Buffer          buffer;
1541                                         ItemPointerData update_ctid;
1542                                         TransactionId update_xmax;
1543                                         TupleTableSlot *newSlot;
1544                                         LockTupleMode lockmode;
1545                                         HTSU_Result test;
1546
1547                                         /* if child rel, must check whether it produced this row */
1548                                         if (erm->rti != erm->prti)
1549                                         {
1550                                                 Oid             tableoid;
1551
1552                                                 datum = ExecGetJunkAttribute(slot,
1553                                                                                                          erm->toidAttNo,
1554                                                                                                          &isNull);
1555                                                 /* shouldn't ever get a null result... */
1556                                                 if (isNull)
1557                                                         elog(ERROR, "tableoid is NULL");
1558                                                 tableoid = DatumGetObjectId(datum);
1559
1560                                                 if (tableoid != RelationGetRelid(erm->relation))
1561                                                 {
1562                                                         /* this child is inactive right now */
1563                                                         ItemPointerSetInvalid(&(erm->curCtid));
1564                                                         continue;
1565                                                 }
1566                                         }
1567
1568                                         /* okay, fetch the tuple by ctid */
1569                                         datum = ExecGetJunkAttribute(slot,
1570                                                                                                  erm->ctidAttNo,
1571                                                                                                  &isNull);
1572                                         /* shouldn't ever get a null result... */
1573                                         if (isNull)
1574                                                 elog(ERROR, "ctid is NULL");
1575                                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1576
1577                                         if (erm->forUpdate)
1578                                                 lockmode = LockTupleExclusive;
1579                                         else
1580                                                 lockmode = LockTupleShared;
1581
1582                                         test = heap_lock_tuple(erm->relation, &tuple, &buffer,
1583                                                                                    &update_ctid, &update_xmax,
1584                                                                                    estate->es_output_cid,
1585                                                                                    lockmode, erm->noWait);
1586                                         ReleaseBuffer(buffer);
1587                                         switch (test)
1588                                         {
1589                                                 case HeapTupleSelfUpdated:
1590                                                         /* treat it as deleted; do not process */
1591                                                         goto lnext;
1592
1593                                                 case HeapTupleMayBeUpdated:
1594                                                         break;
1595
1596                                                 case HeapTupleUpdated:
1597                                                         if (IsXactIsoLevelSerializable)
1598                                                                 ereport(ERROR,
1599                                                                  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1600                                                                   errmsg("could not serialize access due to concurrent update")));
1601                                                         if (!ItemPointerEquals(&update_ctid,
1602                                                                                                    &tuple.t_self))
1603                                                         {
1604                                                                 /* updated, so look at updated version */
1605                                                                 newSlot = EvalPlanQual(estate,
1606                                                                                                            erm->rti,
1607                                                                                                            &update_ctid,
1608                                                                                                            update_xmax);
1609                                                                 if (!TupIsNull(newSlot))
1610                                                                 {
1611                                                                         slot = planSlot = newSlot;
1612                                                                         estate->es_useEvalPlan = true;
1613                                                                         goto lmark;
1614                                                                 }
1615                                                         }
1616
1617                                                         /*
1618                                                          * if tuple was deleted or PlanQual failed for
1619                                                          * updated tuple - we must not return this tuple!
1620                                                          */
1621                                                         goto lnext;
1622
1623                                                 default:
1624                                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1625                                                                  test);
1626                                         }
1627
1628                                         /* Remember tuple TID for WHERE CURRENT OF */
1629                                         erm->curCtid = tuple.t_self;
1630                                 }
1631                         }
1632
1633                         /*
1634                          * extract the 'ctid' junk attribute.
1635                          */
1636                         if (operation == CMD_UPDATE || operation == CMD_DELETE)
1637                         {
1638                                 Datum           datum;
1639                                 bool            isNull;
1640
1641                                 datum = ExecGetJunkAttribute(slot, junkfilter->jf_junkAttNo,
1642                                                                                          &isNull);
1643                                 /* shouldn't ever get a null result... */
1644                                 if (isNull)
1645                                         elog(ERROR, "ctid is NULL");
1646
1647                                 tupleid = (ItemPointer) DatumGetPointer(datum);
1648                                 tuple_ctid = *tupleid;  /* make sure we don't free the ctid!! */
1649                                 tupleid = &tuple_ctid;
1650                         }
1651
1652                         /*
1653                          * Create a new "clean" tuple with all junk attributes removed. We
1654                          * don't need to do this for DELETE, however (there will in fact
1655                          * be no non-junk attributes in a DELETE!)
1656                          */
1657                         if (operation != CMD_DELETE)
1658                                 slot = ExecFilterJunk(junkfilter, slot);
1659                 }
1660
1661                 /*
1662                  * now that we have a tuple, do the appropriate thing with it.. either
1663                  * send it to the output destination, add it to a relation someplace,
1664                  * delete it from a relation, or modify some of its attributes.
1665                  */
1666                 switch (operation)
1667                 {
1668                         case CMD_SELECT:
1669                                 ExecSelect(slot, dest, estate);
1670                                 break;
1671
1672                         case CMD_INSERT:
1673                                 ExecInsert(slot, tupleid, planSlot, dest, estate);
1674                                 break;
1675
1676                         case CMD_DELETE:
1677                                 ExecDelete(tupleid, planSlot, dest, estate);
1678                                 break;
1679
1680                         case CMD_UPDATE:
1681                                 ExecUpdate(slot, tupleid, planSlot, dest, estate);
1682                                 break;
1683
1684                         default:
1685                                 elog(ERROR, "unrecognized operation code: %d",
1686                                          (int) operation);
1687                                 break;
1688                 }
1689
1690                 /*
1691                  * check our tuple count.. if we've processed the proper number then
1692                  * quit, else loop again and process more tuples.  Zero numberTuples
1693                  * means no limit.
1694                  */
1695                 current_tuple_count++;
1696                 if (numberTuples && numberTuples == current_tuple_count)
1697                         break;
1698         }
1699
1700         /*
1701          * Process AFTER EACH STATEMENT triggers
1702          */
1703         switch (operation)
1704         {
1705                 case CMD_UPDATE:
1706                         ExecASUpdateTriggers(estate, estate->es_result_relation_info);
1707                         break;
1708                 case CMD_DELETE:
1709                         ExecASDeleteTriggers(estate, estate->es_result_relation_info);
1710                         break;
1711                 case CMD_INSERT:
1712                         ExecASInsertTriggers(estate, estate->es_result_relation_info);
1713                         break;
1714                 default:
1715                         /* do nothing */
1716                         break;
1717         }
1718 }
1719
1720 /* ----------------------------------------------------------------
1721  *              ExecSelect
1722  *
1723  *              SELECTs are easy.. we just pass the tuple to the appropriate
1724  *              output function.
1725  * ----------------------------------------------------------------
1726  */
1727 static void
1728 ExecSelect(TupleTableSlot *slot,
1729                    DestReceiver *dest,
1730                    EState *estate)
1731 {
1732         (*dest->receiveSlot) (slot, dest);
1733         IncrRetrieved();
1734         (estate->es_processed)++;
1735 }
1736
1737 /* ----------------------------------------------------------------
1738  *              ExecInsert
1739  *
1740  *              INSERTs are trickier.. we have to insert the tuple into
1741  *              the base relation and insert appropriate tuples into the
1742  *              index relations.
1743  * ----------------------------------------------------------------
1744  */
1745 static void
1746 ExecInsert(TupleTableSlot *slot,
1747                    ItemPointer tupleid,
1748                    TupleTableSlot *planSlot,
1749                    DestReceiver *dest,
1750                    EState *estate)
1751 {
1752         HeapTuple       tuple;
1753         ResultRelInfo *resultRelInfo;
1754         Relation        resultRelationDesc;
1755         Oid                     newId;
1756
1757         /*
1758          * get the heap tuple out of the tuple table slot, making sure we have a
1759          * writable copy
1760          */
1761         tuple = ExecMaterializeSlot(slot);
1762
1763         /*
1764          * get information on the (current) result relation
1765          */
1766         resultRelInfo = estate->es_result_relation_info;
1767         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1768
1769         /* BEFORE ROW INSERT Triggers */
1770         if (resultRelInfo->ri_TrigDesc &&
1771                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1772         {
1773                 HeapTuple       newtuple;
1774
1775                 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1776
1777                 if (newtuple == NULL)   /* "do nothing" */
1778                         return;
1779
1780                 if (newtuple != tuple)  /* modified by Trigger(s) */
1781                 {
1782                         /*
1783                          * Put the modified tuple into a slot for convenience of routines
1784                          * below.  We assume the tuple was allocated in per-tuple memory
1785                          * context, and therefore will go away by itself. The tuple table
1786                          * slot should not try to clear it.
1787                          */
1788                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
1789
1790                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
1791                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
1792                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
1793                         slot = newslot;
1794                         tuple = newtuple;
1795                 }
1796         }
1797
1798         /*
1799          * Check the constraints of the tuple
1800          */
1801         if (resultRelationDesc->rd_att->constr)
1802                 ExecConstraints(resultRelInfo, slot, estate);
1803
1804         /*
1805          * insert the tuple
1806          *
1807          * Note: heap_insert returns the tid (location) of the new tuple in the
1808          * t_self field.
1809          */
1810         newId = heap_insert(resultRelationDesc, tuple,
1811                                                 estate->es_output_cid, 0, NULL);
1812
1813         IncrAppended();
1814         (estate->es_processed)++;
1815         estate->es_lastoid = newId;
1816         setLastTid(&(tuple->t_self));
1817
1818         /*
1819          * insert index entries for tuple
1820          */
1821         if (resultRelInfo->ri_NumIndices > 0)
1822                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
1823
1824         /* AFTER ROW INSERT Triggers */
1825         ExecARInsertTriggers(estate, resultRelInfo, tuple);
1826
1827         /* Process RETURNING if present */
1828         if (resultRelInfo->ri_projectReturning)
1829                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1830                                                          slot, planSlot, dest);
1831 }
1832
1833 /* ----------------------------------------------------------------
1834  *              ExecDelete
1835  *
1836  *              DELETE is like UPDATE, except that we delete the tuple and no
1837  *              index modifications are needed
1838  * ----------------------------------------------------------------
1839  */
1840 static void
1841 ExecDelete(ItemPointer tupleid,
1842                    TupleTableSlot *planSlot,
1843                    DestReceiver *dest,
1844                    EState *estate)
1845 {
1846         ResultRelInfo *resultRelInfo;
1847         Relation        resultRelationDesc;
1848         HTSU_Result result;
1849         ItemPointerData update_ctid;
1850         TransactionId update_xmax;
1851
1852         /*
1853          * get information on the (current) result relation
1854          */
1855         resultRelInfo = estate->es_result_relation_info;
1856         resultRelationDesc = resultRelInfo->ri_RelationDesc;
1857
1858         /* BEFORE ROW DELETE Triggers */
1859         if (resultRelInfo->ri_TrigDesc &&
1860                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_DELETE] > 0)
1861         {
1862                 bool            dodelete;
1863
1864                 dodelete = ExecBRDeleteTriggers(estate, resultRelInfo, tupleid);
1865
1866                 if (!dodelete)                  /* "do nothing" */
1867                         return;
1868         }
1869
1870         /*
1871          * delete the tuple
1872          *
1873          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
1874          * the row to be deleted is visible to that snapshot, and throw a can't-
1875          * serialize error if not.      This is a special-case behavior needed for
1876          * referential integrity updates in serializable transactions.
1877          */
1878 ldelete:;
1879         result = heap_delete(resultRelationDesc, tupleid,
1880                                                  &update_ctid, &update_xmax,
1881                                                  estate->es_output_cid,
1882                                                  estate->es_crosscheck_snapshot,
1883                                                  true /* wait for commit */ );
1884         switch (result)
1885         {
1886                 case HeapTupleSelfUpdated:
1887                         /* already deleted by self; nothing to do */
1888                         return;
1889
1890                 case HeapTupleMayBeUpdated:
1891                         break;
1892
1893                 case HeapTupleUpdated:
1894                         if (IsXactIsoLevelSerializable)
1895                                 ereport(ERROR,
1896                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1897                                                  errmsg("could not serialize access due to concurrent update")));
1898                         else if (!ItemPointerEquals(tupleid, &update_ctid))
1899                         {
1900                                 TupleTableSlot *epqslot;
1901
1902                                 epqslot = EvalPlanQual(estate,
1903                                                                            resultRelInfo->ri_RangeTableIndex,
1904                                                                            &update_ctid,
1905                                                                            update_xmax);
1906                                 if (!TupIsNull(epqslot))
1907                                 {
1908                                         *tupleid = update_ctid;
1909                                         goto ldelete;
1910                                 }
1911                         }
1912                         /* tuple already deleted; nothing to do */
1913                         return;
1914
1915                 default:
1916                         elog(ERROR, "unrecognized heap_delete status: %u", result);
1917                         return;
1918         }
1919
1920         IncrDeleted();
1921         (estate->es_processed)++;
1922
1923         /*
1924          * Note: Normally one would think that we have to delete index tuples
1925          * associated with the heap tuple now...
1926          *
1927          * ... but in POSTGRES, we have no need to do this because VACUUM will
1928          * take care of it later.  We can't delete index tuples immediately
1929          * anyway, since the tuple is still visible to other transactions.
1930          */
1931
1932         /* AFTER ROW DELETE Triggers */
1933         ExecARDeleteTriggers(estate, resultRelInfo, tupleid);
1934
1935         /* Process RETURNING if present */
1936         if (resultRelInfo->ri_projectReturning)
1937         {
1938                 /*
1939                  * We have to put the target tuple into a slot, which means first we
1940                  * gotta fetch it.      We can use the trigger tuple slot.
1941                  */
1942                 TupleTableSlot *slot = estate->es_trig_tuple_slot;
1943                 HeapTupleData deltuple;
1944                 Buffer          delbuffer;
1945
1946                 deltuple.t_self = *tupleid;
1947                 if (!heap_fetch(resultRelationDesc, SnapshotAny,
1948                                                 &deltuple, &delbuffer, false, NULL))
1949                         elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
1950
1951                 if (slot->tts_tupleDescriptor != RelationGetDescr(resultRelationDesc))
1952                         ExecSetSlotDescriptor(slot, RelationGetDescr(resultRelationDesc));
1953                 ExecStoreTuple(&deltuple, slot, InvalidBuffer, false);
1954
1955                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
1956                                                          slot, planSlot, dest);
1957
1958                 ExecClearTuple(slot);
1959                 ReleaseBuffer(delbuffer);
1960         }
1961 }
1962
1963 /* ----------------------------------------------------------------
1964  *              ExecUpdate
1965  *
1966  *              note: we can't run UPDATE queries with transactions
1967  *              off because UPDATEs are actually INSERTs and our
1968  *              scan will mistakenly loop forever, updating the tuple
1969  *              it just inserted..      This should be fixed but until it
1970  *              is, we don't want to get stuck in an infinite loop
1971  *              which corrupts your database..
1972  * ----------------------------------------------------------------
1973  */
1974 static void
1975 ExecUpdate(TupleTableSlot *slot,
1976                    ItemPointer tupleid,
1977                    TupleTableSlot *planSlot,
1978                    DestReceiver *dest,
1979                    EState *estate)
1980 {
1981         HeapTuple       tuple;
1982         ResultRelInfo *resultRelInfo;
1983         Relation        resultRelationDesc;
1984         HTSU_Result result;
1985         ItemPointerData update_ctid;
1986         TransactionId update_xmax;
1987
1988         /*
1989          * abort the operation if not running transactions
1990          */
1991         if (IsBootstrapProcessingMode())
1992                 elog(ERROR, "cannot UPDATE during bootstrap");
1993
1994         /*
1995          * get the heap tuple out of the tuple table slot, making sure we have a
1996          * writable copy
1997          */
1998         tuple = ExecMaterializeSlot(slot);
1999
2000         /*
2001          * get information on the (current) result relation
2002          */
2003         resultRelInfo = estate->es_result_relation_info;
2004         resultRelationDesc = resultRelInfo->ri_RelationDesc;
2005
2006         /* BEFORE ROW UPDATE Triggers */
2007         if (resultRelInfo->ri_TrigDesc &&
2008                 resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_UPDATE] > 0)
2009         {
2010                 HeapTuple       newtuple;
2011
2012                 newtuple = ExecBRUpdateTriggers(estate, resultRelInfo,
2013                                                                                 tupleid, tuple);
2014
2015                 if (newtuple == NULL)   /* "do nothing" */
2016                         return;
2017
2018                 if (newtuple != tuple)  /* modified by Trigger(s) */
2019                 {
2020                         /*
2021                          * Put the modified tuple into a slot for convenience of routines
2022                          * below.  We assume the tuple was allocated in per-tuple memory
2023                          * context, and therefore will go away by itself. The tuple table
2024                          * slot should not try to clear it.
2025                          */
2026                         TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2027
2028                         if (newslot->tts_tupleDescriptor != slot->tts_tupleDescriptor)
2029                                 ExecSetSlotDescriptor(newslot, slot->tts_tupleDescriptor);
2030                         ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2031                         slot = newslot;
2032                         tuple = newtuple;
2033                 }
2034         }
2035
2036         /*
2037          * Check the constraints of the tuple
2038          *
2039          * If we generate a new candidate tuple after EvalPlanQual testing, we
2040          * must loop back here and recheck constraints.  (We don't need to redo
2041          * triggers, however.  If there are any BEFORE triggers then trigger.c
2042          * will have done heap_lock_tuple to lock the correct tuple, so there's no
2043          * need to do them again.)
2044          */
2045 lreplace:;
2046         if (resultRelationDesc->rd_att->constr)
2047                 ExecConstraints(resultRelInfo, slot, estate);
2048
2049         /*
2050          * replace the heap tuple
2051          *
2052          * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
2053          * the row to be updated is visible to that snapshot, and throw a can't-
2054          * serialize error if not.      This is a special-case behavior needed for
2055          * referential integrity updates in serializable transactions.
2056          */
2057         result = heap_update(resultRelationDesc, tupleid, tuple,
2058                                                  &update_ctid, &update_xmax,
2059                                                  estate->es_output_cid,
2060                                                  estate->es_crosscheck_snapshot,
2061                                                  true /* wait for commit */ );
2062         switch (result)
2063         {
2064                 case HeapTupleSelfUpdated:
2065                         /* already deleted by self; nothing to do */
2066                         return;
2067
2068                 case HeapTupleMayBeUpdated:
2069                         break;
2070
2071                 case HeapTupleUpdated:
2072                         if (IsXactIsoLevelSerializable)
2073                                 ereport(ERROR,
2074                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2075                                                  errmsg("could not serialize access due to concurrent update")));
2076                         else if (!ItemPointerEquals(tupleid, &update_ctid))
2077                         {
2078                                 TupleTableSlot *epqslot;
2079
2080                                 epqslot = EvalPlanQual(estate,
2081                                                                            resultRelInfo->ri_RangeTableIndex,
2082                                                                            &update_ctid,
2083                                                                            update_xmax);
2084                                 if (!TupIsNull(epqslot))
2085                                 {
2086                                         *tupleid = update_ctid;
2087                                         slot = ExecFilterJunk(estate->es_junkFilter, epqslot);
2088                                         tuple = ExecMaterializeSlot(slot);
2089                                         goto lreplace;
2090                                 }
2091                         }
2092                         /* tuple already deleted; nothing to do */
2093                         return;
2094
2095                 default:
2096                         elog(ERROR, "unrecognized heap_update status: %u", result);
2097                         return;
2098         }
2099
2100         IncrReplaced();
2101         (estate->es_processed)++;
2102
2103         /*
2104          * Note: instead of having to update the old index tuples associated with
2105          * the heap tuple, all we do is form and insert new index tuples. This is
2106          * because UPDATEs are actually DELETEs and INSERTs, and index tuple
2107          * deletion is done later by VACUUM (see notes in ExecDelete).  All we do
2108          * here is insert new index tuples.  -cim 9/27/89
2109          */
2110
2111         /*
2112          * insert index entries for tuple
2113          *
2114          * Note: heap_update returns the tid (location) of the new tuple in the
2115          * t_self field.
2116          *
2117          * If it's a HOT update, we mustn't insert new index entries.
2118          */
2119         if (resultRelInfo->ri_NumIndices > 0 && !HeapTupleIsHeapOnly(tuple))
2120                 ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);
2121
2122         /* AFTER ROW UPDATE Triggers */
2123         ExecARUpdateTriggers(estate, resultRelInfo, tupleid, tuple);
2124
2125         /* Process RETURNING if present */
2126         if (resultRelInfo->ri_projectReturning)
2127                 ExecProcessReturning(resultRelInfo->ri_projectReturning,
2128                                                          slot, planSlot, dest);
2129 }
2130
2131 /*
2132  * ExecRelCheck --- check that tuple meets constraints for result relation
2133  */
2134 static const char *
2135 ExecRelCheck(ResultRelInfo *resultRelInfo,
2136                          TupleTableSlot *slot, EState *estate)
2137 {
2138         Relation        rel = resultRelInfo->ri_RelationDesc;
2139         int                     ncheck = rel->rd_att->constr->num_check;
2140         ConstrCheck *check = rel->rd_att->constr->check;
2141         ExprContext *econtext;
2142         MemoryContext oldContext;
2143         List       *qual;
2144         int                     i;
2145
2146         /*
2147          * If first time through for this result relation, build expression
2148          * nodetrees for rel's constraint expressions.  Keep them in the per-query
2149          * memory context so they'll survive throughout the query.
2150          */
2151         if (resultRelInfo->ri_ConstraintExprs == NULL)
2152         {
2153                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
2154                 resultRelInfo->ri_ConstraintExprs =
2155                         (List **) palloc(ncheck * sizeof(List *));
2156                 for (i = 0; i < ncheck; i++)
2157                 {
2158                         /* ExecQual wants implicit-AND form */
2159                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
2160                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
2161                                 ExecPrepareExpr((Expr *) qual, estate);
2162                 }
2163                 MemoryContextSwitchTo(oldContext);
2164         }
2165
2166         /*
2167          * We will use the EState's per-tuple context for evaluating constraint
2168          * expressions (creating it if it's not already there).
2169          */
2170         econtext = GetPerTupleExprContext(estate);
2171
2172         /* Arrange for econtext's scan tuple to be the tuple under test */
2173         econtext->ecxt_scantuple = slot;
2174
2175         /* And evaluate the constraints */
2176         for (i = 0; i < ncheck; i++)
2177         {
2178                 qual = resultRelInfo->ri_ConstraintExprs[i];
2179
2180                 /*
2181                  * NOTE: SQL92 specifies that a NULL result from a constraint
2182                  * expression is not to be treated as a failure.  Therefore, tell
2183                  * ExecQual to return TRUE for NULL.
2184                  */
2185                 if (!ExecQual(qual, econtext, true))
2186                         return check[i].ccname;
2187         }
2188
2189         /* NULL result means no error */
2190         return NULL;
2191 }
2192
2193 void
2194 ExecConstraints(ResultRelInfo *resultRelInfo,
2195                                 TupleTableSlot *slot, EState *estate)
2196 {
2197         Relation        rel = resultRelInfo->ri_RelationDesc;
2198         TupleConstr *constr = rel->rd_att->constr;
2199
2200         Assert(constr);
2201
2202         if (constr->has_not_null)
2203         {
2204                 int                     natts = rel->rd_att->natts;
2205                 int                     attrChk;
2206
2207                 for (attrChk = 1; attrChk <= natts; attrChk++)
2208                 {
2209                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
2210                                 slot_attisnull(slot, attrChk))
2211                                 ereport(ERROR,
2212                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
2213                                                  errmsg("null value in column \"%s\" violates not-null constraint",
2214                                                 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
2215                 }
2216         }
2217
2218         if (constr->num_check > 0)
2219         {
2220                 const char *failed;
2221
2222                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
2223                         ereport(ERROR,
2224                                         (errcode(ERRCODE_CHECK_VIOLATION),
2225                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
2226                                                         RelationGetRelationName(rel), failed)));
2227         }
2228 }
2229
2230 /*
2231  * ExecProcessReturning --- evaluate a RETURNING list and send to dest
2232  *
2233  * projectReturning: RETURNING projection info for current result rel
2234  * tupleSlot: slot holding tuple actually inserted/updated/deleted
2235  * planSlot: slot holding tuple returned by top plan node
2236  * dest: where to send the output
2237  */
2238 static void
2239 ExecProcessReturning(ProjectionInfo *projectReturning,
2240                                          TupleTableSlot *tupleSlot,
2241                                          TupleTableSlot *planSlot,
2242                                          DestReceiver *dest)
2243 {
2244         ExprContext *econtext = projectReturning->pi_exprContext;
2245         TupleTableSlot *retSlot;
2246
2247         /*
2248          * Reset per-tuple memory context to free any expression evaluation
2249          * storage allocated in the previous cycle.
2250          */
2251         ResetExprContext(econtext);
2252
2253         /* Make tuple and any needed join variables available to ExecProject */
2254         econtext->ecxt_scantuple = tupleSlot;
2255         econtext->ecxt_outertuple = planSlot;
2256
2257         /* Compute the RETURNING expressions */
2258         retSlot = ExecProject(projectReturning, NULL);
2259
2260         /* Send to dest */
2261         (*dest->receiveSlot) (retSlot, dest);
2262
2263         ExecClearTuple(retSlot);
2264 }
2265
2266 /*
2267  * Check a modified tuple to see if we want to process its updated version
2268  * under READ COMMITTED rules.
2269  *
2270  * See backend/executor/README for some info about how this works.
2271  *
2272  *      estate - executor state data
2273  *      rti - rangetable index of table containing tuple
2274  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
2275  *      priorXmax - t_xmax from the outdated tuple
2276  *
2277  * *tid is also an output parameter: it's modified to hold the TID of the
2278  * latest version of the tuple (note this may be changed even on failure)
2279  *
2280  * Returns a slot containing the new candidate update/delete tuple, or
2281  * NULL if we determine we shouldn't process the row.
2282  */
2283 TupleTableSlot *
2284 EvalPlanQual(EState *estate, Index rti,
2285                          ItemPointer tid, TransactionId priorXmax)
2286 {
2287         evalPlanQual *epq;
2288         EState     *epqstate;
2289         Relation        relation;
2290         HeapTupleData tuple;
2291         HeapTuple       copyTuple = NULL;
2292         SnapshotData SnapshotDirty;
2293         bool            endNode;
2294
2295         Assert(rti != 0);
2296
2297         /*
2298          * find relation containing target tuple
2299          */
2300         if (estate->es_result_relation_info != NULL &&
2301                 estate->es_result_relation_info->ri_RangeTableIndex == rti)
2302                 relation = estate->es_result_relation_info->ri_RelationDesc;
2303         else
2304         {
2305                 ListCell   *l;
2306
2307                 relation = NULL;
2308                 foreach(l, estate->es_rowMarks)
2309                 {
2310                         ExecRowMark *erm = lfirst(l);
2311
2312                         if (erm->rti == rti)
2313                         {
2314                                 relation = erm->relation;
2315                                 break;
2316                         }
2317                 }
2318                 if (relation == NULL)
2319                         elog(ERROR, "could not find RowMark for RT index %u", rti);
2320         }
2321
2322         /*
2323          * fetch tid tuple
2324          *
2325          * Loop here to deal with updated or busy tuples
2326          */
2327         InitDirtySnapshot(SnapshotDirty);
2328         tuple.t_self = *tid;
2329         for (;;)
2330         {
2331                 Buffer          buffer;
2332
2333                 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
2334                 {
2335                         /*
2336                          * If xmin isn't what we're expecting, the slot must have been
2337                          * recycled and reused for an unrelated tuple.  This implies that
2338                          * the latest version of the row was deleted, so we need do
2339                          * nothing.  (Should be safe to examine xmin without getting
2340                          * buffer's content lock, since xmin never changes in an existing
2341                          * tuple.)
2342                          */
2343                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2344                                                                          priorXmax))
2345                         {
2346                                 ReleaseBuffer(buffer);
2347                                 return NULL;
2348                         }
2349
2350                         /* otherwise xmin should not be dirty... */
2351                         if (TransactionIdIsValid(SnapshotDirty.xmin))
2352                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
2353
2354                         /*
2355                          * If tuple is being updated by other transaction then we have to
2356                          * wait for its commit/abort.
2357                          */
2358                         if (TransactionIdIsValid(SnapshotDirty.xmax))
2359                         {
2360                                 ReleaseBuffer(buffer);
2361                                 XactLockTableWait(SnapshotDirty.xmax);
2362                                 continue;               /* loop back to repeat heap_fetch */
2363                         }
2364
2365                         /*
2366                          * If tuple was inserted by our own transaction, we have to check
2367                          * cmin against es_output_cid: cmin >= current CID means our
2368                          * command cannot see the tuple, so we should ignore it.  Without
2369                          * this we are open to the "Halloween problem" of indefinitely
2370                          * re-updating the same tuple. (We need not check cmax because
2371                          * HeapTupleSatisfiesDirty will consider a tuple deleted by our
2372                          * transaction dead, regardless of cmax.)  We just checked that
2373                          * priorXmax == xmin, so we can test that variable instead of
2374                          * doing HeapTupleHeaderGetXmin again.
2375                          */
2376                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
2377                                 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
2378                         {
2379                                 ReleaseBuffer(buffer);
2380                                 return NULL;
2381                         }
2382
2383                         /*
2384                          * We got tuple - now copy it for use by recheck query.
2385                          */
2386                         copyTuple = heap_copytuple(&tuple);
2387                         ReleaseBuffer(buffer);
2388                         break;
2389                 }
2390
2391                 /*
2392                  * If the referenced slot was actually empty, the latest version of
2393                  * the row must have been deleted, so we need do nothing.
2394                  */
2395                 if (tuple.t_data == NULL)
2396                 {
2397                         ReleaseBuffer(buffer);
2398                         return NULL;
2399                 }
2400
2401                 /*
2402                  * As above, if xmin isn't what we're expecting, do nothing.
2403                  */
2404                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2405                                                                  priorXmax))
2406                 {
2407                         ReleaseBuffer(buffer);
2408                         return NULL;
2409                 }
2410
2411                 /*
2412                  * If we get here, the tuple was found but failed SnapshotDirty.
2413                  * Assuming the xmin is either a committed xact or our own xact (as it
2414                  * certainly should be if we're trying to modify the tuple), this must
2415                  * mean that the row was updated or deleted by either a committed xact
2416                  * or our own xact.  If it was deleted, we can ignore it; if it was
2417                  * updated then chain up to the next version and repeat the whole
2418                  * test.
2419                  *
2420                  * As above, it should be safe to examine xmax and t_ctid without the
2421                  * buffer content lock, because they can't be changing.
2422                  */
2423                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2424                 {
2425                         /* deleted, so forget about it */
2426                         ReleaseBuffer(buffer);
2427                         return NULL;
2428                 }
2429
2430                 /* updated, so look at the updated row */
2431                 tuple.t_self = tuple.t_data->t_ctid;
2432                 /* updated row should have xmin matching this xmax */
2433                 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
2434                 ReleaseBuffer(buffer);
2435                 /* loop back to fetch next in chain */
2436         }
2437
2438         /*
2439          * For UPDATE/DELETE we have to return tid of actual row we're executing
2440          * PQ for.
2441          */
2442         *tid = tuple.t_self;
2443
2444         /*
2445          * Need to run a recheck subquery.      Find or create a PQ stack entry.
2446          */
2447         epq = estate->es_evalPlanQual;
2448         endNode = true;
2449
2450         if (epq != NULL && epq->rti == 0)
2451         {
2452                 /* Top PQ stack entry is idle, so re-use it */
2453                 Assert(!(estate->es_useEvalPlan) && epq->next == NULL);
2454                 epq->rti = rti;
2455                 endNode = false;
2456         }
2457
2458         /*
2459          * If this is request for another RTE - Ra, - then we have to check wasn't
2460          * PlanQual requested for Ra already and if so then Ra' row was updated
2461          * again and we have to re-start old execution for Ra and forget all what
2462          * we done after Ra was suspended. Cool? -:))
2463          */
2464         if (epq != NULL && epq->rti != rti &&
2465                 epq->estate->es_evTuple[rti - 1] != NULL)
2466         {
2467                 do
2468                 {
2469                         evalPlanQual *oldepq;
2470
2471                         /* stop execution */
2472                         EvalPlanQualStop(epq);
2473                         /* pop previous PlanQual from the stack */
2474                         oldepq = epq->next;
2475                         Assert(oldepq && oldepq->rti != 0);
2476                         /* push current PQ to freePQ stack */
2477                         oldepq->free = epq;
2478                         epq = oldepq;
2479                         estate->es_evalPlanQual = epq;
2480                 } while (epq->rti != rti);
2481         }
2482
2483         /*
2484          * If we are requested for another RTE then we have to suspend execution
2485          * of current PlanQual and start execution for new one.
2486          */
2487         if (epq == NULL || epq->rti != rti)
2488         {
2489                 /* try to reuse plan used previously */
2490                 evalPlanQual *newepq = (epq != NULL) ? epq->free : NULL;
2491
2492                 if (newepq == NULL)             /* first call or freePQ stack is empty */
2493                 {
2494                         newepq = (evalPlanQual *) palloc0(sizeof(evalPlanQual));
2495                         newepq->free = NULL;
2496                         newepq->estate = NULL;
2497                         newepq->planstate = NULL;
2498                 }
2499                 else
2500                 {
2501                         /* recycle previously used PlanQual */
2502                         Assert(newepq->estate == NULL);
2503                         epq->free = NULL;
2504                 }
2505                 /* push current PQ to the stack */
2506                 newepq->next = epq;
2507                 epq = newepq;
2508                 estate->es_evalPlanQual = epq;
2509                 epq->rti = rti;
2510                 endNode = false;
2511         }
2512
2513         Assert(epq->rti == rti);
2514
2515         /*
2516          * Ok - we're requested for the same RTE.  Unfortunately we still have to
2517          * end and restart execution of the plan, because ExecReScan wouldn't
2518          * ensure that upper plan nodes would reset themselves.  We could make
2519          * that work if insertion of the target tuple were integrated with the
2520          * Param mechanism somehow, so that the upper plan nodes know that their
2521          * children's outputs have changed.
2522          *
2523          * Note that the stack of free evalPlanQual nodes is quite useless at the
2524          * moment, since it only saves us from pallocing/releasing the
2525          * evalPlanQual nodes themselves.  But it will be useful once we implement
2526          * ReScan instead of end/restart for re-using PlanQual nodes.
2527          */
2528         if (endNode)
2529         {
2530                 /* stop execution */
2531                 EvalPlanQualStop(epq);
2532         }
2533
2534         /*
2535          * Initialize new recheck query.
2536          *
2537          * Note: if we were re-using PlanQual plans via ExecReScan, we'd need to
2538          * instead copy down changeable state from the top plan (including
2539          * es_result_relation_info, es_junkFilter) and reset locally changeable
2540          * state in the epq (including es_param_exec_vals, es_evTupleNull).
2541          */
2542         EvalPlanQualStart(epq, estate, epq->next);
2543
2544         /*
2545          * free old RTE' tuple, if any, and store target tuple where relation's
2546          * scan node will see it
2547          */
2548         epqstate = epq->estate;
2549         if (epqstate->es_evTuple[rti - 1] != NULL)
2550                 heap_freetuple(epqstate->es_evTuple[rti - 1]);
2551         epqstate->es_evTuple[rti - 1] = copyTuple;
2552
2553         return EvalPlanQualNext(estate);
2554 }
2555
2556 static TupleTableSlot *
2557 EvalPlanQualNext(EState *estate)
2558 {
2559         evalPlanQual *epq = estate->es_evalPlanQual;
2560         MemoryContext oldcontext;
2561         TupleTableSlot *slot;
2562
2563         Assert(epq->rti != 0);
2564
2565 lpqnext:;
2566         oldcontext = MemoryContextSwitchTo(epq->estate->es_query_cxt);
2567         slot = ExecProcNode(epq->planstate);
2568         MemoryContextSwitchTo(oldcontext);
2569
2570         /*
2571          * No more tuples for this PQ. Continue previous one.
2572          */
2573         if (TupIsNull(slot))
2574         {
2575                 evalPlanQual *oldepq;
2576
2577                 /* stop execution */
2578                 EvalPlanQualStop(epq);
2579                 /* pop old PQ from the stack */
2580                 oldepq = epq->next;
2581                 if (oldepq == NULL)
2582                 {
2583                         /* this is the first (oldest) PQ - mark as free */
2584                         epq->rti = 0;
2585                         estate->es_useEvalPlan = false;
2586                         /* and continue Query execution */
2587                         return NULL;
2588                 }
2589                 Assert(oldepq->rti != 0);
2590                 /* push current PQ to freePQ stack */
2591                 oldepq->free = epq;
2592                 epq = oldepq;
2593                 estate->es_evalPlanQual = epq;
2594                 goto lpqnext;
2595         }
2596
2597         return slot;
2598 }
2599
2600 static void
2601 EndEvalPlanQual(EState *estate)
2602 {
2603         evalPlanQual *epq = estate->es_evalPlanQual;
2604
2605         if (epq->rti == 0)                      /* plans already shutdowned */
2606         {
2607                 Assert(epq->next == NULL);
2608                 return;
2609         }
2610
2611         for (;;)
2612         {
2613                 evalPlanQual *oldepq;
2614
2615                 /* stop execution */
2616                 EvalPlanQualStop(epq);
2617                 /* pop old PQ from the stack */
2618                 oldepq = epq->next;
2619                 if (oldepq == NULL)
2620                 {
2621                         /* this is the first (oldest) PQ - mark as free */
2622                         epq->rti = 0;
2623                         estate->es_useEvalPlan = false;
2624                         break;
2625                 }
2626                 Assert(oldepq->rti != 0);
2627                 /* push current PQ to freePQ stack */
2628                 oldepq->free = epq;
2629                 epq = oldepq;
2630                 estate->es_evalPlanQual = epq;
2631         }
2632 }
2633
2634 /*
2635  * Start execution of one level of PlanQual.
2636  *
2637  * This is a cut-down version of ExecutorStart(): we copy some state from
2638  * the top-level estate rather than initializing it fresh.
2639  */
2640 static void
2641 EvalPlanQualStart(evalPlanQual *epq, EState *estate, evalPlanQual *priorepq)
2642 {
2643         EState     *epqstate;
2644         int                     rtsize;
2645         MemoryContext oldcontext;
2646         ListCell   *l;
2647
2648         rtsize = list_length(estate->es_range_table);
2649
2650         epq->estate = epqstate = CreateExecutorState();
2651
2652         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2653
2654         /*
2655          * The epqstates share the top query's copy of unchanging state such as
2656          * the snapshot, rangetable, result-rel info, and external Param info.
2657          * They need their own copies of local state, including a tuple table,
2658          * es_param_exec_vals, etc.
2659          */
2660         epqstate->es_direction = ForwardScanDirection;
2661         epqstate->es_snapshot = estate->es_snapshot;
2662         epqstate->es_crosscheck_snapshot = estate->es_crosscheck_snapshot;
2663         epqstate->es_range_table = estate->es_range_table;
2664         epqstate->es_output_cid = estate->es_output_cid;
2665         epqstate->es_result_relations = estate->es_result_relations;
2666         epqstate->es_num_result_relations = estate->es_num_result_relations;
2667         epqstate->es_result_relation_info = estate->es_result_relation_info;
2668         epqstate->es_junkFilter = estate->es_junkFilter;
2669         /* es_trig_target_relations must NOT be copied */
2670         epqstate->es_param_list_info = estate->es_param_list_info;
2671         if (estate->es_plannedstmt->nParamExec > 0)
2672                 epqstate->es_param_exec_vals = (ParamExecData *)
2673                         palloc0(estate->es_plannedstmt->nParamExec * sizeof(ParamExecData));
2674         epqstate->es_rowMarks = estate->es_rowMarks;
2675         epqstate->es_instrument = estate->es_instrument;
2676         epqstate->es_select_into = estate->es_select_into;
2677         epqstate->es_into_oids = estate->es_into_oids;
2678         epqstate->es_plannedstmt = estate->es_plannedstmt;
2679
2680         /*
2681          * Each epqstate must have its own es_evTupleNull state, but all the stack
2682          * entries share es_evTuple state.      This allows sub-rechecks to inherit
2683          * the value being examined by an outer recheck.
2684          */
2685         epqstate->es_evTupleNull = (bool *) palloc0(rtsize * sizeof(bool));
2686         if (priorepq == NULL)
2687                 /* first PQ stack entry */
2688                 epqstate->es_evTuple = (HeapTuple *)
2689                         palloc0(rtsize * sizeof(HeapTuple));
2690         else
2691                 /* later stack entries share the same storage */
2692                 epqstate->es_evTuple = priorepq->estate->es_evTuple;
2693
2694         /*
2695          * Create sub-tuple-table; we needn't redo the CountSlots work though.
2696          */
2697         epqstate->es_tupleTable =
2698                 ExecCreateTupleTable(estate->es_tupleTable->size);
2699
2700         /*
2701          * Initialize private state information for each SubPlan.  We must do this
2702          * before running ExecInitNode on the main query tree, since
2703          * ExecInitSubPlan expects to be able to find these entries.
2704          */
2705         Assert(epqstate->es_subplanstates == NIL);
2706         foreach(l, estate->es_plannedstmt->subplans)
2707         {
2708                 Plan       *subplan = (Plan *) lfirst(l);
2709                 PlanState  *subplanstate;
2710
2711                 subplanstate = ExecInitNode(subplan, epqstate, 0);
2712
2713                 epqstate->es_subplanstates = lappend(epqstate->es_subplanstates,
2714                                                                                          subplanstate);
2715         }
2716
2717         /*
2718          * Initialize the private state information for all the nodes in the query
2719          * tree.  This opens files, allocates storage and leaves us ready to start
2720          * processing tuples.
2721          */
2722         epq->planstate = ExecInitNode(estate->es_plannedstmt->planTree, epqstate, 0);
2723
2724         MemoryContextSwitchTo(oldcontext);
2725 }
2726
2727 /*
2728  * End execution of one level of PlanQual.
2729  *
2730  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2731  * of the normal cleanup, but *not* close result relations (which we are
2732  * just sharing from the outer query).  We do, however, have to close any
2733  * trigger target relations that got opened, since those are not shared.
2734  */
2735 static void
2736 EvalPlanQualStop(evalPlanQual *epq)
2737 {
2738         EState     *epqstate = epq->estate;
2739         MemoryContext oldcontext;
2740         ListCell   *l;
2741
2742         oldcontext = MemoryContextSwitchTo(epqstate->es_query_cxt);
2743
2744         ExecEndNode(epq->planstate);
2745
2746         foreach(l, epqstate->es_subplanstates)
2747         {
2748                 PlanState  *subplanstate = (PlanState *) lfirst(l);
2749
2750                 ExecEndNode(subplanstate);
2751         }
2752
2753         ExecDropTupleTable(epqstate->es_tupleTable, true);
2754         epqstate->es_tupleTable = NULL;
2755
2756         if (epqstate->es_evTuple[epq->rti - 1] != NULL)
2757         {
2758                 heap_freetuple(epqstate->es_evTuple[epq->rti - 1]);
2759                 epqstate->es_evTuple[epq->rti - 1] = NULL;
2760         }
2761
2762         foreach(l, epqstate->es_trig_target_relations)
2763         {
2764                 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2765
2766                 /* Close indices and then the relation itself */
2767                 ExecCloseIndices(resultRelInfo);
2768                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2769         }
2770
2771         MemoryContextSwitchTo(oldcontext);
2772
2773         FreeExecutorState(epqstate);
2774
2775         epq->estate = NULL;
2776         epq->planstate = NULL;
2777 }
2778
2779 /*
2780  * ExecGetActivePlanTree --- get the active PlanState tree from a QueryDesc
2781  *
2782  * Ordinarily this is just the one mentioned in the QueryDesc, but if we
2783  * are looking at a row returned by the EvalPlanQual machinery, we need
2784  * to look at the subsidiary state instead.
2785  */
2786 PlanState *
2787 ExecGetActivePlanTree(QueryDesc *queryDesc)
2788 {
2789         EState     *estate = queryDesc->estate;
2790
2791         if (estate && estate->es_useEvalPlan && estate->es_evalPlanQual != NULL)
2792                 return estate->es_evalPlanQual->planstate;
2793         else
2794                 return queryDesc->planstate;
2795 }
2796
2797
2798 /*
2799  * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2800  *
2801  * We implement SELECT INTO by diverting SELECT's normal output with
2802  * a specialized DestReceiver type.
2803  */
2804
2805 typedef struct
2806 {
2807         DestReceiver pub;                       /* publicly-known function pointers */
2808         EState     *estate;                     /* EState we are working with */
2809         Relation        rel;                    /* Relation to write to */
2810         int                     hi_options;             /* heap_insert performance options */
2811         BulkInsertState bistate;        /* bulk insert state */
2812 } DR_intorel;
2813
2814 /*
2815  * OpenIntoRel --- actually create the SELECT INTO target relation
2816  *
2817  * This also replaces QueryDesc->dest with the special DestReceiver for
2818  * SELECT INTO.  We assume that the correct result tuple type has already
2819  * been placed in queryDesc->tupDesc.
2820  */
2821 static void
2822 OpenIntoRel(QueryDesc *queryDesc)
2823 {
2824         IntoClause *into = queryDesc->plannedstmt->intoClause;
2825         EState     *estate = queryDesc->estate;
2826         Relation        intoRelationDesc;
2827         char       *intoName;
2828         Oid                     namespaceId;
2829         Oid                     tablespaceId;
2830         Datum           reloptions;
2831         AclResult       aclresult;
2832         Oid                     intoRelationId;
2833         TupleDesc       tupdesc;
2834         DR_intorel *myState;
2835
2836         Assert(into);
2837
2838         /*
2839          * Check consistency of arguments
2840          */
2841         if (into->onCommit != ONCOMMIT_NOOP && !into->rel->istemp)
2842                 ereport(ERROR,
2843                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2844                                  errmsg("ON COMMIT can only be used on temporary tables")));
2845
2846         /*
2847          * Find namespace to create in, check its permissions
2848          */
2849         intoName = into->rel->relname;
2850         namespaceId = RangeVarGetCreationNamespace(into->rel);
2851
2852         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2853                                                                           ACL_CREATE);
2854         if (aclresult != ACLCHECK_OK)
2855                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2856                                            get_namespace_name(namespaceId));
2857
2858         /*
2859          * Select tablespace to use.  If not specified, use default tablespace
2860          * (which may in turn default to database's default).
2861          */
2862         if (into->tableSpaceName)
2863         {
2864                 tablespaceId = get_tablespace_oid(into->tableSpaceName);
2865                 if (!OidIsValid(tablespaceId))
2866                         ereport(ERROR,
2867                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
2868                                          errmsg("tablespace \"%s\" does not exist",
2869                                                         into->tableSpaceName)));
2870         }
2871         else
2872         {
2873                 tablespaceId = GetDefaultTablespace(into->rel->istemp);
2874                 /* note InvalidOid is OK in this case */
2875         }
2876
2877         /* Check permissions except when using the database's default space */
2878         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2879         {
2880                 AclResult       aclresult;
2881
2882                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2883                                                                                    ACL_CREATE);
2884
2885                 if (aclresult != ACLCHECK_OK)
2886                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2887                                                    get_tablespace_name(tablespaceId));
2888         }
2889
2890         /* Parse and validate any reloptions */
2891         reloptions = transformRelOptions((Datum) 0,
2892                                                                          into->options,
2893                                                                          true,
2894                                                                          false);
2895         (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2896
2897         /* Copy the tupdesc because heap_create_with_catalog modifies it */
2898         tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2899
2900         /* Now we can actually create the new relation */
2901         intoRelationId = heap_create_with_catalog(intoName,
2902                                                                                           namespaceId,
2903                                                                                           tablespaceId,
2904                                                                                           InvalidOid,
2905                                                                                           GetUserId(),
2906                                                                                           tupdesc,
2907                                                                                           NIL,
2908                                                                                           RELKIND_RELATION,
2909                                                                                           false,
2910                                                                                           true,
2911                                                                                           0,
2912                                                                                           into->onCommit,
2913                                                                                           reloptions,
2914                                                                                           allowSystemTableMods);
2915
2916         FreeTupleDesc(tupdesc);
2917
2918         /*
2919          * Advance command counter so that the newly-created relation's catalog
2920          * tuples will be visible to heap_open.
2921          */
2922         CommandCounterIncrement();
2923
2924         /*
2925          * If necessary, create a TOAST table for the INTO relation. Note that
2926          * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2927          * the TOAST table will be visible for insertion.
2928          */
2929         AlterTableCreateToastTable(intoRelationId);
2930
2931         /*
2932          * And open the constructed table for writing.
2933          */
2934         intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2935
2936         /*
2937          * Now replace the query's DestReceiver with one for SELECT INTO
2938          */
2939         queryDesc->dest = CreateDestReceiver(DestIntoRel);
2940         myState = (DR_intorel *) queryDesc->dest;
2941         Assert(myState->pub.mydest == DestIntoRel);
2942         myState->estate = estate;
2943         myState->rel = intoRelationDesc;
2944
2945         /*
2946          * We can skip WAL-logging the insertions, unless PITR is in use.  We
2947          * can skip the FSM in any case.
2948          */
2949         myState->hi_options = HEAP_INSERT_SKIP_FSM |
2950                 (XLogArchivingActive() ? 0 : HEAP_INSERT_SKIP_WAL);
2951         myState->bistate = GetBulkInsertState();
2952
2953         /* Not using WAL requires rd_targblock be initially invalid */
2954         Assert(intoRelationDesc->rd_targblock == InvalidBlockNumber);
2955 }
2956
2957 /*
2958  * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2959  */
2960 static void
2961 CloseIntoRel(QueryDesc *queryDesc)
2962 {
2963         DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2964
2965         /* OpenIntoRel might never have gotten called */
2966         if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2967         {
2968                 FreeBulkInsertState(myState->bistate);
2969
2970                 /* If we skipped using WAL, must heap_sync before commit */
2971                 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2972                         heap_sync(myState->rel);
2973
2974                 /* close rel, but keep lock until commit */
2975                 heap_close(myState->rel, NoLock);
2976
2977                 myState->rel = NULL;
2978         }
2979 }
2980
2981 /*
2982  * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2983  */
2984 DestReceiver *
2985 CreateIntoRelDestReceiver(void)
2986 {
2987         DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2988
2989         self->pub.receiveSlot = intorel_receive;
2990         self->pub.rStartup = intorel_startup;
2991         self->pub.rShutdown = intorel_shutdown;
2992         self->pub.rDestroy = intorel_destroy;
2993         self->pub.mydest = DestIntoRel;
2994
2995         /* private fields will be set by OpenIntoRel */
2996
2997         return (DestReceiver *) self;
2998 }
2999
3000 /*
3001  * intorel_startup --- executor startup
3002  */
3003 static void
3004 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
3005 {
3006         /* no-op */
3007 }
3008
3009 /*
3010  * intorel_receive --- receive one tuple
3011  */
3012 static void
3013 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
3014 {
3015         DR_intorel *myState = (DR_intorel *) self;
3016         HeapTuple       tuple;
3017
3018         /*
3019          * get the heap tuple out of the tuple table slot, making sure we have a
3020          * writable copy
3021          */
3022         tuple = ExecMaterializeSlot(slot);
3023
3024         heap_insert(myState->rel,
3025                                 tuple,
3026                                 myState->estate->es_output_cid,
3027                                 myState->hi_options,
3028                                 myState->bistate);
3029
3030         /* We know this is a newly created relation, so there are no indexes */
3031
3032         IncrAppended();
3033 }
3034
3035 /*
3036  * intorel_shutdown --- executor end
3037  */
3038 static void
3039 intorel_shutdown(DestReceiver *self)
3040 {
3041         /* no-op */
3042 }
3043
3044 /*
3045  * intorel_destroy --- release DestReceiver object
3046  */
3047 static void
3048 intorel_destroy(DestReceiver *self)
3049 {
3050         pfree(self);
3051 }