]> granicus.if.org Git - postgresql/blob - src/backend/executor/execMain.c
7df7f5cdf0d3a23ae3439445d695bcad7421ff57
[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-2011, PostgreSQL Global Development Group
25  * Portions Copyright (c) 1994, Regents of the University of California
26  *
27  *
28  * IDENTIFICATION
29  *        src/backend/executor/execMain.c
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34
35 #include "access/reloptions.h"
36 #include "access/sysattr.h"
37 #include "access/transam.h"
38 #include "access/xact.h"
39 #include "catalog/heap.h"
40 #include "catalog/namespace.h"
41 #include "catalog/toasting.h"
42 #include "commands/tablespace.h"
43 #include "commands/trigger.h"
44 #include "executor/execdebug.h"
45 #include "executor/instrument.h"
46 #include "miscadmin.h"
47 #include "optimizer/clauses.h"
48 #include "parser/parse_clause.h"
49 #include "parser/parsetree.h"
50 #include "storage/bufmgr.h"
51 #include "storage/lmgr.h"
52 #include "storage/smgr.h"
53 #include "tcop/utility.h"
54 #include "utils/acl.h"
55 #include "utils/lsyscache.h"
56 #include "utils/memutils.h"
57 #include "utils/snapmgr.h"
58 #include "utils/tqual.h"
59
60
61 /* Hooks for plugins to get control in ExecutorStart/Run/End() */
62 ExecutorStart_hook_type ExecutorStart_hook = NULL;
63 ExecutorRun_hook_type ExecutorRun_hook = NULL;
64 ExecutorEnd_hook_type ExecutorEnd_hook = NULL;
65
66 /* Hook for plugin to get control in ExecCheckRTPerms() */
67 ExecutorCheckPerms_hook_type ExecutorCheckPerms_hook = NULL;
68
69 /* decls for local routines only used within this module */
70 static void InitPlan(QueryDesc *queryDesc, int eflags);
71 static void ExecEndPlan(PlanState *planstate, EState *estate);
72 static void ExecutePlan(EState *estate, PlanState *planstate,
73                         CmdType operation,
74                         bool sendTuples,
75                         long numberTuples,
76                         ScanDirection direction,
77                         DestReceiver *dest);
78 static bool ExecCheckRTEPerms(RangeTblEntry *rte);
79 static void ExecCheckXactReadOnly(PlannedStmt *plannedstmt);
80 static void EvalPlanQualStart(EPQState *epqstate, EState *parentestate,
81                                   Plan *planTree);
82 static void OpenIntoRel(QueryDesc *queryDesc);
83 static void CloseIntoRel(QueryDesc *queryDesc);
84 static void intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
85 static void intorel_receive(TupleTableSlot *slot, DestReceiver *self);
86 static void intorel_shutdown(DestReceiver *self);
87 static void intorel_destroy(DestReceiver *self);
88
89 /* end of local decls */
90
91
92 /* ----------------------------------------------------------------
93  *              ExecutorStart
94  *
95  *              This routine must be called at the beginning of any execution of any
96  *              query plan
97  *
98  * Takes a QueryDesc previously created by CreateQueryDesc (it's not real
99  * clear why we bother to separate the two functions, but...).  The tupDesc
100  * field of the QueryDesc is filled in to describe the tuples that will be
101  * returned, and the internal fields (estate and planstate) are set up.
102  *
103  * eflags contains flag bits as described in executor.h.
104  *
105  * NB: the CurrentMemoryContext when this is called will become the parent
106  * of the per-query context used for this Executor invocation.
107  *
108  * We provide a function hook variable that lets loadable plugins
109  * get control when ExecutorStart is called.  Such a plugin would
110  * normally call standard_ExecutorStart().
111  *
112  * ----------------------------------------------------------------
113  */
114 void
115 ExecutorStart(QueryDesc *queryDesc, int eflags)
116 {
117         if (ExecutorStart_hook)
118                 (*ExecutorStart_hook) (queryDesc, eflags);
119         else
120                 standard_ExecutorStart(queryDesc, eflags);
121 }
122
123 void
124 standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
125 {
126         EState     *estate;
127         MemoryContext oldcontext;
128
129         /* sanity checks: queryDesc must not be started already */
130         Assert(queryDesc != NULL);
131         Assert(queryDesc->estate == NULL);
132
133         /*
134          * If the transaction is read-only, we need to check if any writes are
135          * planned to non-temporary tables.  EXPLAIN is considered read-only.
136          */
137         if (XactReadOnly && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
138                 ExecCheckXactReadOnly(queryDesc->plannedstmt);
139
140         /*
141          * Build EState, switch into per-query memory context for startup.
142          */
143         estate = CreateExecutorState();
144         queryDesc->estate = estate;
145
146         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
147
148         /*
149          * Fill in external parameters, if any, from queryDesc; and allocate
150          * workspace for internal parameters
151          */
152         estate->es_param_list_info = queryDesc->params;
153
154         if (queryDesc->plannedstmt->nParamExec > 0)
155                 estate->es_param_exec_vals = (ParamExecData *)
156                         palloc0(queryDesc->plannedstmt->nParamExec * sizeof(ParamExecData));
157
158         /*
159          * If non-read-only query, set the command ID to mark output tuples with
160          */
161         switch (queryDesc->operation)
162         {
163                 case CMD_SELECT:
164                         /* SELECT INTO and SELECT FOR UPDATE/SHARE need to mark tuples */
165                         if (queryDesc->plannedstmt->intoClause != NULL ||
166                                 queryDesc->plannedstmt->rowMarks != NIL)
167                                 estate->es_output_cid = GetCurrentCommandId(true);
168                         break;
169
170                 case CMD_INSERT:
171                 case CMD_DELETE:
172                 case CMD_UPDATE:
173                         estate->es_output_cid = GetCurrentCommandId(true);
174                         break;
175
176                 default:
177                         elog(ERROR, "unrecognized operation code: %d",
178                                  (int) queryDesc->operation);
179                         break;
180         }
181
182         /*
183          * Copy other important information into the EState
184          */
185         estate->es_snapshot = RegisterSnapshot(queryDesc->snapshot);
186         estate->es_crosscheck_snapshot = RegisterSnapshot(queryDesc->crosscheck_snapshot);
187         estate->es_instrument = queryDesc->instrument_options;
188
189         /*
190          * Initialize the plan state tree
191          */
192         InitPlan(queryDesc, eflags);
193
194         MemoryContextSwitchTo(oldcontext);
195 }
196
197 /* ----------------------------------------------------------------
198  *              ExecutorRun
199  *
200  *              This is the main routine of the executor module. It accepts
201  *              the query descriptor from the traffic cop and executes the
202  *              query plan.
203  *
204  *              ExecutorStart must have been called already.
205  *
206  *              If direction is NoMovementScanDirection then nothing is done
207  *              except to start up/shut down the destination.  Otherwise,
208  *              we retrieve up to 'count' tuples in the specified direction.
209  *
210  *              Note: count = 0 is interpreted as no portal limit, i.e., run to
211  *              completion.
212  *
213  *              There is no return value, but output tuples (if any) are sent to
214  *              the destination receiver specified in the QueryDesc; and the number
215  *              of tuples processed at the top level can be found in
216  *              estate->es_processed.
217  *
218  *              We provide a function hook variable that lets loadable plugins
219  *              get control when ExecutorRun is called.  Such a plugin would
220  *              normally call standard_ExecutorRun().
221  *
222  * ----------------------------------------------------------------
223  */
224 void
225 ExecutorRun(QueryDesc *queryDesc,
226                         ScanDirection direction, long count)
227 {
228         if (ExecutorRun_hook)
229                 (*ExecutorRun_hook) (queryDesc, direction, count);
230         else
231                 standard_ExecutorRun(queryDesc, direction, count);
232 }
233
234 void
235 standard_ExecutorRun(QueryDesc *queryDesc,
236                                          ScanDirection direction, long count)
237 {
238         EState     *estate;
239         CmdType         operation;
240         DestReceiver *dest;
241         bool            sendTuples;
242         MemoryContext oldcontext;
243
244         /* sanity checks */
245         Assert(queryDesc != NULL);
246
247         estate = queryDesc->estate;
248
249         Assert(estate != NULL);
250
251         /*
252          * Switch into per-query memory context
253          */
254         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
255
256         /* Allow instrumentation of ExecutorRun overall runtime */
257         if (queryDesc->totaltime)
258                 InstrStartNode(queryDesc->totaltime);
259
260         /*
261          * extract information from the query descriptor and the query feature.
262          */
263         operation = queryDesc->operation;
264         dest = queryDesc->dest;
265
266         /*
267          * startup tuple receiver, if we will be emitting tuples
268          */
269         estate->es_processed = 0;
270         estate->es_lastoid = InvalidOid;
271
272         sendTuples = (operation == CMD_SELECT ||
273                                   queryDesc->plannedstmt->hasReturning);
274
275         if (sendTuples)
276                 (*dest->rStartup) (dest, operation, queryDesc->tupDesc);
277
278         /*
279          * run plan
280          */
281         if (!ScanDirectionIsNoMovement(direction))
282                 ExecutePlan(estate,
283                                         queryDesc->planstate,
284                                         operation,
285                                         sendTuples,
286                                         count,
287                                         direction,
288                                         dest);
289
290         /*
291          * shutdown tuple receiver, if we started it
292          */
293         if (sendTuples)
294                 (*dest->rShutdown) (dest);
295
296         if (queryDesc->totaltime)
297                 InstrStopNode(queryDesc->totaltime, estate->es_processed);
298
299         MemoryContextSwitchTo(oldcontext);
300 }
301
302 /* ----------------------------------------------------------------
303  *              ExecutorEnd
304  *
305  *              This routine must be called at the end of execution of any
306  *              query plan
307  *
308  *              We provide a function hook variable that lets loadable plugins
309  *              get control when ExecutorEnd is called.  Such a plugin would
310  *              normally call standard_ExecutorEnd().
311  *
312  * ----------------------------------------------------------------
313  */
314 void
315 ExecutorEnd(QueryDesc *queryDesc)
316 {
317         if (ExecutorEnd_hook)
318                 (*ExecutorEnd_hook) (queryDesc);
319         else
320                 standard_ExecutorEnd(queryDesc);
321 }
322
323 void
324 standard_ExecutorEnd(QueryDesc *queryDesc)
325 {
326         EState     *estate;
327         MemoryContext oldcontext;
328
329         /* sanity checks */
330         Assert(queryDesc != NULL);
331
332         estate = queryDesc->estate;
333
334         Assert(estate != NULL);
335
336         /*
337          * Switch into per-query memory context to run ExecEndPlan
338          */
339         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
340
341         ExecEndPlan(queryDesc->planstate, estate);
342
343         /*
344          * Close the SELECT INTO relation if any
345          */
346         if (estate->es_select_into)
347                 CloseIntoRel(queryDesc);
348
349         /* do away with our snapshots */
350         UnregisterSnapshot(estate->es_snapshot);
351         UnregisterSnapshot(estate->es_crosscheck_snapshot);
352
353         /*
354          * Must switch out of context before destroying it
355          */
356         MemoryContextSwitchTo(oldcontext);
357
358         /*
359          * Release EState and per-query memory context.  This should release
360          * everything the executor has allocated.
361          */
362         FreeExecutorState(estate);
363
364         /* Reset queryDesc fields that no longer point to anything */
365         queryDesc->tupDesc = NULL;
366         queryDesc->estate = NULL;
367         queryDesc->planstate = NULL;
368         queryDesc->totaltime = NULL;
369 }
370
371 /* ----------------------------------------------------------------
372  *              ExecutorRewind
373  *
374  *              This routine may be called on an open queryDesc to rewind it
375  *              to the start.
376  * ----------------------------------------------------------------
377  */
378 void
379 ExecutorRewind(QueryDesc *queryDesc)
380 {
381         EState     *estate;
382         MemoryContext oldcontext;
383
384         /* sanity checks */
385         Assert(queryDesc != NULL);
386
387         estate = queryDesc->estate;
388
389         Assert(estate != NULL);
390
391         /* It's probably not sensible to rescan updating queries */
392         Assert(queryDesc->operation == CMD_SELECT);
393
394         /*
395          * Switch into per-query memory context
396          */
397         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
398
399         /*
400          * rescan plan
401          */
402         ExecReScan(queryDesc->planstate);
403
404         MemoryContextSwitchTo(oldcontext);
405 }
406
407
408 /*
409  * ExecCheckRTPerms
410  *              Check access permissions for all relations listed in a range table.
411  *
412  * Returns true if permissions are adequate.  Otherwise, throws an appropriate
413  * error if ereport_on_violation is true, or simply returns false otherwise.
414  */
415 bool
416 ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
417 {
418         ListCell   *l;
419         bool            result = true;
420
421         foreach(l, rangeTable)
422         {
423                 RangeTblEntry  *rte = (RangeTblEntry *) lfirst(l);
424
425                 result = ExecCheckRTEPerms(rte);
426                 if (!result)
427                 {
428                         Assert(rte->rtekind == RTE_RELATION);
429                         if (ereport_on_violation)
430                                 aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
431                                                            get_rel_name(rte->relid));
432                         return false;
433                 }
434         }
435
436         if (ExecutorCheckPerms_hook)
437                 result = (*ExecutorCheckPerms_hook)(rangeTable,
438                                                                                         ereport_on_violation);
439         return result;
440 }
441
442 /*
443  * ExecCheckRTEPerms
444  *              Check access permissions for a single RTE.
445  */
446 static bool
447 ExecCheckRTEPerms(RangeTblEntry *rte)
448 {
449         AclMode         requiredPerms;
450         AclMode         relPerms;
451         AclMode         remainingPerms;
452         Oid                     relOid;
453         Oid                     userid;
454         Bitmapset  *tmpset;
455         int                     col;
456
457         /*
458          * Only plain-relation RTEs need to be checked here.  Function RTEs are
459          * checked by init_fcache when the function is prepared for execution.
460          * Join, subquery, and special RTEs need no checks.
461          */
462         if (rte->rtekind != RTE_RELATION)
463                 return true;
464
465         /*
466          * No work if requiredPerms is empty.
467          */
468         requiredPerms = rte->requiredPerms;
469         if (requiredPerms == 0)
470                 return true;
471
472         relOid = rte->relid;
473
474         /*
475          * userid to check as: current user unless we have a setuid indication.
476          *
477          * Note: GetUserId() is presently fast enough that there's no harm in
478          * calling it separately for each RTE.  If that stops being true, we could
479          * call it once in ExecCheckRTPerms and pass the userid down from there.
480          * But for now, no need for the extra clutter.
481          */
482         userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
483
484         /*
485          * We must have *all* the requiredPerms bits, but some of the bits can be
486          * satisfied from column-level rather than relation-level permissions.
487          * First, remove any bits that are satisfied by relation permissions.
488          */
489         relPerms = pg_class_aclmask(relOid, userid, requiredPerms, ACLMASK_ALL);
490         remainingPerms = requiredPerms & ~relPerms;
491         if (remainingPerms != 0)
492         {
493                 /*
494                  * If we lack any permissions that exist only as relation permissions,
495                  * we can fail straight away.
496                  */
497                 if (remainingPerms & ~(ACL_SELECT | ACL_INSERT | ACL_UPDATE))
498                         return false;
499
500                 /*
501                  * Check to see if we have the needed privileges at column level.
502                  *
503                  * Note: failures just report a table-level error; it would be nicer
504                  * to report a column-level error if we have some but not all of the
505                  * column privileges.
506                  */
507                 if (remainingPerms & ACL_SELECT)
508                 {
509                         /*
510                          * When the query doesn't explicitly reference any columns (for
511                          * example, SELECT COUNT(*) FROM table), allow the query if we
512                          * have SELECT on any column of the rel, as per SQL spec.
513                          */
514                         if (bms_is_empty(rte->selectedCols))
515                         {
516                                 if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
517                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
518                                         return false;
519                         }
520
521                         tmpset = bms_copy(rte->selectedCols);
522                         while ((col = bms_first_member(tmpset)) >= 0)
523                         {
524                                 /* remove the column number offset */
525                                 col += FirstLowInvalidHeapAttributeNumber;
526                                 if (col == InvalidAttrNumber)
527                                 {
528                                         /* Whole-row reference, must have priv on all cols */
529                                         if (pg_attribute_aclcheck_all(relOid, userid, ACL_SELECT,
530                                                                                                   ACLMASK_ALL) != ACLCHECK_OK)
531                                                 return false;
532                                 }
533                                 else
534                                 {
535                                         if (pg_attribute_aclcheck(relOid, col, userid,
536                                                                                           ACL_SELECT) != ACLCHECK_OK)
537                                                 return false;
538                                 }
539                         }
540                         bms_free(tmpset);
541                 }
542
543                 /*
544                  * Basically the same for the mod columns, with either INSERT or
545                  * UPDATE privilege as specified by remainingPerms.
546                  */
547                 remainingPerms &= ~ACL_SELECT;
548                 if (remainingPerms != 0)
549                 {
550                         /*
551                          * When the query doesn't explicitly change any columns, allow the
552                          * query if we have permission on any column of the rel.  This is
553                          * to handle SELECT FOR UPDATE as well as possible corner cases in
554                          * INSERT and UPDATE.
555                          */
556                         if (bms_is_empty(rte->modifiedCols))
557                         {
558                                 if (pg_attribute_aclcheck_all(relOid, userid, remainingPerms,
559                                                                                           ACLMASK_ANY) != ACLCHECK_OK)
560                                         return false;
561                         }
562
563                         tmpset = bms_copy(rte->modifiedCols);
564                         while ((col = bms_first_member(tmpset)) >= 0)
565                         {
566                                 /* remove the column number offset */
567                                 col += FirstLowInvalidHeapAttributeNumber;
568                                 if (col == InvalidAttrNumber)
569                                 {
570                                         /* whole-row reference can't happen here */
571                                         elog(ERROR, "whole-row update is not implemented");
572                                 }
573                                 else
574                                 {
575                                         if (pg_attribute_aclcheck(relOid, col, userid,
576                                                                                           remainingPerms) != ACLCHECK_OK)
577                                                 return false;
578                                 }
579                         }
580                         bms_free(tmpset);
581                 }
582         }
583         return true;
584 }
585
586 /*
587  * Check that the query does not imply any writes to non-temp tables.
588  *
589  * Note: in a Hot Standby slave this would need to reject writes to temp
590  * tables as well; but an HS slave can't have created any temp tables
591  * in the first place, so no need to check that.
592  */
593 static void
594 ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
595 {
596         ListCell   *l;
597
598         /*
599          * CREATE TABLE AS or SELECT INTO?
600          *
601          * XXX should we allow this if the destination is temp?  Considering that
602          * it would still require catalog changes, probably not.
603          */
604         if (plannedstmt->intoClause != NULL)
605                 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
606
607         /* Fail if write permissions are requested on any non-temp table */
608         foreach(l, plannedstmt->rtable)
609         {
610                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
611
612                 if (rte->rtekind != RTE_RELATION)
613                         continue;
614
615                 if ((rte->requiredPerms & (~ACL_SELECT)) == 0)
616                         continue;
617
618                 if (isTempNamespace(get_rel_namespace(rte->relid)))
619                         continue;
620
621                 PreventCommandIfReadOnly(CreateCommandTag((Node *) plannedstmt));
622         }
623 }
624
625
626 /* ----------------------------------------------------------------
627  *              InitPlan
628  *
629  *              Initializes the query plan: open files, allocate storage
630  *              and start up the rule manager
631  * ----------------------------------------------------------------
632  */
633 static void
634 InitPlan(QueryDesc *queryDesc, int eflags)
635 {
636         CmdType         operation = queryDesc->operation;
637         PlannedStmt *plannedstmt = queryDesc->plannedstmt;
638         Plan       *plan = plannedstmt->planTree;
639         List       *rangeTable = plannedstmt->rtable;
640         EState     *estate = queryDesc->estate;
641         PlanState  *planstate;
642         TupleDesc       tupType;
643         ListCell   *l;
644         int                     i;
645
646         /*
647          * Do permissions checks
648          */
649         ExecCheckRTPerms(rangeTable, true);
650
651         /*
652          * initialize the node's execution state
653          */
654         estate->es_range_table = rangeTable;
655         estate->es_plannedstmt = plannedstmt;
656
657         /*
658          * initialize result relation stuff, and open/lock the result rels.
659          *
660          * We must do this before initializing the plan tree, else we might try to
661          * do a lock upgrade if a result rel is also a source rel.
662          */
663         if (plannedstmt->resultRelations)
664         {
665                 List       *resultRelations = plannedstmt->resultRelations;
666                 int                     numResultRelations = list_length(resultRelations);
667                 ResultRelInfo *resultRelInfos;
668                 ResultRelInfo *resultRelInfo;
669
670                 resultRelInfos = (ResultRelInfo *)
671                         palloc(numResultRelations * sizeof(ResultRelInfo));
672                 resultRelInfo = resultRelInfos;
673                 foreach(l, resultRelations)
674                 {
675                         Index           resultRelationIndex = lfirst_int(l);
676                         Oid                     resultRelationOid;
677                         Relation        resultRelation;
678
679                         resultRelationOid = getrelid(resultRelationIndex, rangeTable);
680                         resultRelation = heap_open(resultRelationOid, RowExclusiveLock);
681                         InitResultRelInfo(resultRelInfo,
682                                                           resultRelation,
683                                                           resultRelationIndex,
684                                                           operation,
685                                                           estate->es_instrument);
686                         resultRelInfo++;
687                 }
688                 estate->es_result_relations = resultRelInfos;
689                 estate->es_num_result_relations = numResultRelations;
690                 /* es_result_relation_info is NULL except when within ModifyTable */
691                 estate->es_result_relation_info = NULL;
692         }
693         else
694         {
695                 /*
696                  * if no result relation, then set state appropriately
697                  */
698                 estate->es_result_relations = NULL;
699                 estate->es_num_result_relations = 0;
700                 estate->es_result_relation_info = NULL;
701         }
702
703         /*
704          * Similarly, we have to lock relations selected FOR UPDATE/FOR SHARE
705          * before we initialize the plan tree, else we'd be risking lock upgrades.
706          * While we are at it, build the ExecRowMark list.
707          */
708         estate->es_rowMarks = NIL;
709         foreach(l, plannedstmt->rowMarks)
710         {
711                 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
712                 Oid                     relid;
713                 Relation        relation;
714                 ExecRowMark *erm;
715
716                 /* ignore "parent" rowmarks; they are irrelevant at runtime */
717                 if (rc->isParent)
718                         continue;
719
720                 switch (rc->markType)
721                 {
722                         case ROW_MARK_EXCLUSIVE:
723                         case ROW_MARK_SHARE:
724                                 relid = getrelid(rc->rti, rangeTable);
725                                 relation = heap_open(relid, RowShareLock);
726                                 break;
727                         case ROW_MARK_REFERENCE:
728                                 relid = getrelid(rc->rti, rangeTable);
729                                 relation = heap_open(relid, AccessShareLock);
730                                 break;
731                         case ROW_MARK_COPY:
732                                 /* there's no real table here ... */
733                                 relation = NULL;
734                                 break;
735                         default:
736                                 elog(ERROR, "unrecognized markType: %d", rc->markType);
737                                 relation = NULL;        /* keep compiler quiet */
738                                 break;
739                 }
740
741                 erm = (ExecRowMark *) palloc(sizeof(ExecRowMark));
742                 erm->relation = relation;
743                 erm->rti = rc->rti;
744                 erm->prti = rc->prti;
745                 erm->rowmarkId = rc->rowmarkId;
746                 erm->markType = rc->markType;
747                 erm->noWait = rc->noWait;
748                 ItemPointerSetInvalid(&(erm->curCtid));
749                 estate->es_rowMarks = lappend(estate->es_rowMarks, erm);
750         }
751
752         /*
753          * Detect whether we're doing SELECT INTO.  If so, set the es_into_oids
754          * flag appropriately so that the plan tree will be initialized with the
755          * correct tuple descriptors.  (Other SELECT INTO stuff comes later.)
756          */
757         estate->es_select_into = false;
758         if (operation == CMD_SELECT && plannedstmt->intoClause != NULL)
759         {
760                 estate->es_select_into = true;
761                 estate->es_into_oids = interpretOidsOption(plannedstmt->intoClause->options);
762         }
763
764         /*
765          * Initialize the executor's tuple table to empty.
766          */
767         estate->es_tupleTable = NIL;
768         estate->es_trig_tuple_slot = NULL;
769         estate->es_trig_oldtup_slot = NULL;
770
771         /* mark EvalPlanQual not active */
772         estate->es_epqTuple = NULL;
773         estate->es_epqTupleSet = NULL;
774         estate->es_epqScanDone = NULL;
775
776         /*
777          * Initialize private state information for each SubPlan.  We must do this
778          * before running ExecInitNode on the main query tree, since
779          * ExecInitSubPlan expects to be able to find these entries.
780          */
781         Assert(estate->es_subplanstates == NIL);
782         i = 1;                                          /* subplan indices count from 1 */
783         foreach(l, plannedstmt->subplans)
784         {
785                 Plan       *subplan = (Plan *) lfirst(l);
786                 PlanState  *subplanstate;
787                 int                     sp_eflags;
788
789                 /*
790                  * A subplan will never need to do BACKWARD scan nor MARK/RESTORE. If
791                  * it is a parameterless subplan (not initplan), we suggest that it be
792                  * prepared to handle REWIND efficiently; otherwise there is no need.
793                  */
794                 sp_eflags = eflags & EXEC_FLAG_EXPLAIN_ONLY;
795                 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
796                         sp_eflags |= EXEC_FLAG_REWIND;
797
798                 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
799
800                 estate->es_subplanstates = lappend(estate->es_subplanstates,
801                                                                                    subplanstate);
802
803                 i++;
804         }
805
806         /*
807          * Initialize the private state information for all the nodes in the query
808          * tree.  This opens files, allocates storage and leaves us ready to start
809          * processing tuples.
810          */
811         planstate = ExecInitNode(plan, estate, eflags);
812
813         /*
814          * Get the tuple descriptor describing the type of tuples to return. (this
815          * is especially important if we are creating a relation with "SELECT
816          * INTO")
817          */
818         tupType = ExecGetResultType(planstate);
819
820         /*
821          * Initialize the junk filter if needed.  SELECT queries need a filter if
822          * there are any junk attrs in the top-level tlist.
823          */
824         if (operation == CMD_SELECT)
825         {
826                 bool            junk_filter_needed = false;
827                 ListCell   *tlist;
828
829                 foreach(tlist, plan->targetlist)
830                 {
831                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
832
833                         if (tle->resjunk)
834                         {
835                                 junk_filter_needed = true;
836                                 break;
837                         }
838                 }
839
840                 if (junk_filter_needed)
841                 {
842                         JunkFilter *j;
843
844                         j = ExecInitJunkFilter(planstate->plan->targetlist,
845                                                                    tupType->tdhasoid,
846                                                                    ExecInitExtraTupleSlot(estate));
847                         estate->es_junkFilter = j;
848
849                         /* Want to return the cleaned tuple type */
850                         tupType = j->jf_cleanTupType;
851                 }
852         }
853
854         queryDesc->tupDesc = tupType;
855         queryDesc->planstate = planstate;
856
857         /*
858          * If doing SELECT INTO, initialize the "into" relation.  We must wait
859          * till now so we have the "clean" result tuple type to create the new
860          * table from.
861          *
862          * If EXPLAIN, skip creating the "into" relation.
863          */
864         if (estate->es_select_into && !(eflags & EXEC_FLAG_EXPLAIN_ONLY))
865                 OpenIntoRel(queryDesc);
866 }
867
868 /*
869  * Initialize ResultRelInfo data for one result relation
870  */
871 void
872 InitResultRelInfo(ResultRelInfo *resultRelInfo,
873                                   Relation resultRelationDesc,
874                                   Index resultRelationIndex,
875                                   CmdType operation,
876                                   int instrument_options)
877 {
878         TriggerDesc     *trigDesc = resultRelationDesc->trigdesc;
879
880         /*
881          * Check valid relkind ... in most cases parser and/or planner should have
882          * noticed this already, but let's make sure.  In the view case we do need
883          * a test here, because if the view wasn't rewritten by a rule, it had
884          * better have an INSTEAD trigger.
885          */
886         switch (resultRelationDesc->rd_rel->relkind)
887         {
888                 case RELKIND_RELATION:
889                         /* OK */
890                         break;
891                 case RELKIND_SEQUENCE:
892                         ereport(ERROR,
893                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
894                                          errmsg("cannot change sequence \"%s\"",
895                                                         RelationGetRelationName(resultRelationDesc))));
896                         break;
897                 case RELKIND_TOASTVALUE:
898                         ereport(ERROR,
899                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
900                                          errmsg("cannot change TOAST relation \"%s\"",
901                                                         RelationGetRelationName(resultRelationDesc))));
902                         break;
903                 case RELKIND_VIEW:
904                         switch (operation)
905                         {
906                                 case CMD_INSERT:
907                                         if (!trigDesc || !trigDesc->trig_insert_instead_row)
908                                                 ereport(ERROR,
909                                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
910                                                                  errmsg("cannot insert into view \"%s\"",
911                                                                                 RelationGetRelationName(resultRelationDesc)),
912                                                                  errhint("You need an unconditional ON INSERT DO INSTEAD rule or an INSTEAD OF INSERT trigger.")));
913                                         break;
914                                 case CMD_UPDATE:
915                                         if (!trigDesc || !trigDesc->trig_update_instead_row)
916                                                 ereport(ERROR,
917                                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
918                                                                  errmsg("cannot update view \"%s\"",
919                                                                                 RelationGetRelationName(resultRelationDesc)),
920                                                                  errhint("You need an unconditional ON UPDATE DO INSTEAD rule or an INSTEAD OF UPDATE trigger.")));
921                                         break;
922                                 case CMD_DELETE:
923                                         if (!trigDesc || !trigDesc->trig_delete_instead_row)
924                                                 ereport(ERROR,
925                                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
926                                                                  errmsg("cannot delete from view \"%s\"",
927                                                                                 RelationGetRelationName(resultRelationDesc)),
928                                                                  errhint("You need an unconditional ON DELETE DO INSTEAD rule or an INSTEAD OF DELETE trigger.")));
929                                         break;
930                                 default:
931                                         elog(ERROR, "unrecognized CmdType: %d", (int) operation);
932                                         break;
933                         }
934                         break;
935                 case RELKIND_FOREIGN_TABLE:
936                         ereport(ERROR,
937                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
938                                          errmsg("cannot change foreign table \"%s\"",
939                                                         RelationGetRelationName(resultRelationDesc))));
940                         break;
941                 default:
942                         ereport(ERROR,
943                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
944                                          errmsg("cannot change relation \"%s\"",
945                                                         RelationGetRelationName(resultRelationDesc))));
946                         break;
947         }
948
949         /* OK, fill in the node */
950         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
951         resultRelInfo->type = T_ResultRelInfo;
952         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
953         resultRelInfo->ri_RelationDesc = resultRelationDesc;
954         resultRelInfo->ri_NumIndices = 0;
955         resultRelInfo->ri_IndexRelationDescs = NULL;
956         resultRelInfo->ri_IndexRelationInfo = NULL;
957         /* make a copy so as not to depend on relcache info not changing... */
958         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(trigDesc);
959         if (resultRelInfo->ri_TrigDesc)
960         {
961                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
962
963                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
964                         palloc0(n * sizeof(FmgrInfo));
965                 resultRelInfo->ri_TrigWhenExprs = (List **)
966                         palloc0(n * sizeof(List *));
967                 if (instrument_options)
968                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
969         }
970         else
971         {
972                 resultRelInfo->ri_TrigFunctions = NULL;
973                 resultRelInfo->ri_TrigWhenExprs = NULL;
974                 resultRelInfo->ri_TrigInstrument = NULL;
975         }
976         resultRelInfo->ri_ConstraintExprs = NULL;
977         resultRelInfo->ri_junkFilter = NULL;
978         resultRelInfo->ri_projectReturning = NULL;
979
980         /*
981          * If there are indices on the result relation, open them and save
982          * descriptors in the result relation info, so that we can add new index
983          * entries for the tuples we add/update.  We need not do this for a
984          * DELETE, however, since deletion doesn't affect indexes.
985          */
986         if (resultRelationDesc->rd_rel->relhasindex &&
987                 operation != CMD_DELETE)
988                 ExecOpenIndices(resultRelInfo);
989 }
990
991 /*
992  *              ExecGetTriggerResultRel
993  *
994  * Get a ResultRelInfo for a trigger target relation.  Most of the time,
995  * triggers are fired on one of the result relations of the query, and so
996  * we can just return a member of the es_result_relations array.  (Note: in
997  * self-join situations there might be multiple members with the same OID;
998  * if so it doesn't matter which one we pick.)  However, it is sometimes
999  * necessary to fire triggers on other relations; this happens mainly when an
1000  * RI update trigger queues additional triggers on other relations, which will
1001  * be processed in the context of the outer query.      For efficiency's sake,
1002  * we want to have a ResultRelInfo for those triggers too; that can avoid
1003  * repeated re-opening of the relation.  (It also provides a way for EXPLAIN
1004  * ANALYZE to report the runtimes of such triggers.)  So we make additional
1005  * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1006  */
1007 ResultRelInfo *
1008 ExecGetTriggerResultRel(EState *estate, Oid relid)
1009 {
1010         ResultRelInfo *rInfo;
1011         int                     nr;
1012         ListCell   *l;
1013         Relation        rel;
1014         MemoryContext oldcontext;
1015
1016         /* First, search through the query result relations */
1017         rInfo = estate->es_result_relations;
1018         nr = estate->es_num_result_relations;
1019         while (nr > 0)
1020         {
1021                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1022                         return rInfo;
1023                 rInfo++;
1024                 nr--;
1025         }
1026         /* Nope, but maybe we already made an extra ResultRelInfo for it */
1027         foreach(l, estate->es_trig_target_relations)
1028         {
1029                 rInfo = (ResultRelInfo *) lfirst(l);
1030                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1031                         return rInfo;
1032         }
1033         /* Nope, so we need a new one */
1034
1035         /*
1036          * Open the target relation's relcache entry.  We assume that an
1037          * appropriate lock is still held by the backend from whenever the trigger
1038          * event got queued, so we need take no new lock here.
1039          */
1040         rel = heap_open(relid, NoLock);
1041
1042         /*
1043          * Make the new entry in the right context.  Currently, we don't need any
1044          * index information in ResultRelInfos used only for triggers, so tell
1045          * InitResultRelInfo it's a DELETE.
1046          */
1047         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1048         rInfo = makeNode(ResultRelInfo);
1049         InitResultRelInfo(rInfo,
1050                                           rel,
1051                                           0,            /* dummy rangetable index */
1052                                           CMD_DELETE,
1053                                           estate->es_instrument);
1054         estate->es_trig_target_relations =
1055                 lappend(estate->es_trig_target_relations, rInfo);
1056         MemoryContextSwitchTo(oldcontext);
1057
1058         return rInfo;
1059 }
1060
1061 /*
1062  *              ExecContextForcesOids
1063  *
1064  * This is pretty grotty: when doing INSERT, UPDATE, or SELECT INTO,
1065  * we need to ensure that result tuples have space for an OID iff they are
1066  * going to be stored into a relation that has OIDs.  In other contexts
1067  * we are free to choose whether to leave space for OIDs in result tuples
1068  * (we generally don't want to, but we do if a physical-tlist optimization
1069  * is possible).  This routine checks the plan context and returns TRUE if the
1070  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
1071  * *hasoids is set to the required value.
1072  *
1073  * One reason this is ugly is that all plan nodes in the plan tree will emit
1074  * tuples with space for an OID, though we really only need the topmost node
1075  * to do so.  However, node types like Sort don't project new tuples but just
1076  * return their inputs, and in those cases the requirement propagates down
1077  * to the input node.  Eventually we might make this code smart enough to
1078  * recognize how far down the requirement really goes, but for now we just
1079  * make all plan nodes do the same thing if the top level forces the choice.
1080  *
1081  * We assume that if we are generating tuples for INSERT or UPDATE,
1082  * estate->es_result_relation_info is already set up to describe the target
1083  * relation.  Note that in an UPDATE that spans an inheritance tree, some of
1084  * the target relations may have OIDs and some not.  We have to make the
1085  * decisions on a per-relation basis as we initialize each of the subplans of
1086  * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1087  * while initializing each subplan.
1088  *
1089  * SELECT INTO is even uglier, because we don't have the INTO relation's
1090  * descriptor available when this code runs; we have to look aside at a
1091  * flag set by InitPlan().
1092  */
1093 bool
1094 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1095 {
1096         ResultRelInfo *ri = planstate->state->es_result_relation_info;
1097
1098         if (ri != NULL)
1099         {
1100                 Relation        rel = ri->ri_RelationDesc;
1101
1102                 if (rel != NULL)
1103                 {
1104                         *hasoids = rel->rd_rel->relhasoids;
1105                         return true;
1106                 }
1107         }
1108
1109         if (planstate->state->es_select_into)
1110         {
1111                 *hasoids = planstate->state->es_into_oids;
1112                 return true;
1113         }
1114
1115         return false;
1116 }
1117
1118 /* ----------------------------------------------------------------
1119  *              ExecEndPlan
1120  *
1121  *              Cleans up the query plan -- closes files and frees up storage
1122  *
1123  * NOTE: we are no longer very worried about freeing storage per se
1124  * in this code; FreeExecutorState should be guaranteed to release all
1125  * memory that needs to be released.  What we are worried about doing
1126  * is closing relations and dropping buffer pins.  Thus, for example,
1127  * tuple tables must be cleared or dropped to ensure pins are released.
1128  * ----------------------------------------------------------------
1129  */
1130 static void
1131 ExecEndPlan(PlanState *planstate, EState *estate)
1132 {
1133         ResultRelInfo *resultRelInfo;
1134         int                     i;
1135         ListCell   *l;
1136
1137         /*
1138          * shut down the node-type-specific query processing
1139          */
1140         ExecEndNode(planstate);
1141
1142         /*
1143          * for subplans too
1144          */
1145         foreach(l, estate->es_subplanstates)
1146         {
1147                 PlanState  *subplanstate = (PlanState *) lfirst(l);
1148
1149                 ExecEndNode(subplanstate);
1150         }
1151
1152         /*
1153          * destroy the executor's tuple table.  Actually we only care about
1154          * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1155          * the TupleTableSlots, since the containing memory context is about to go
1156          * away anyway.
1157          */
1158         ExecResetTupleTable(estate->es_tupleTable, false);
1159
1160         /*
1161          * close the result relation(s) if any, but hold locks until xact commit.
1162          */
1163         resultRelInfo = estate->es_result_relations;
1164         for (i = estate->es_num_result_relations; i > 0; i--)
1165         {
1166                 /* Close indices and then the relation itself */
1167                 ExecCloseIndices(resultRelInfo);
1168                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1169                 resultRelInfo++;
1170         }
1171
1172         /*
1173          * likewise close any trigger target relations
1174          */
1175         foreach(l, estate->es_trig_target_relations)
1176         {
1177                 resultRelInfo = (ResultRelInfo *) lfirst(l);
1178                 /* Close indices and then the relation itself */
1179                 ExecCloseIndices(resultRelInfo);
1180                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1181         }
1182
1183         /*
1184          * close any relations selected FOR UPDATE/FOR SHARE, again keeping locks
1185          */
1186         foreach(l, estate->es_rowMarks)
1187         {
1188                 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1189
1190                 if (erm->relation)
1191                         heap_close(erm->relation, NoLock);
1192         }
1193 }
1194
1195 /* ----------------------------------------------------------------
1196  *              ExecutePlan
1197  *
1198  *              Processes the query plan until we have processed 'numberTuples' tuples,
1199  *              moving in the specified direction.
1200  *
1201  *              Runs to completion if numberTuples is 0
1202  *
1203  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1204  * user can see it
1205  * ----------------------------------------------------------------
1206  */
1207 static void
1208 ExecutePlan(EState *estate,
1209                         PlanState *planstate,
1210                         CmdType operation,
1211                         bool sendTuples,
1212                         long numberTuples,
1213                         ScanDirection direction,
1214                         DestReceiver *dest)
1215 {
1216         TupleTableSlot *slot;
1217         long            current_tuple_count;
1218
1219         /*
1220          * initialize local variables
1221          */
1222         current_tuple_count = 0;
1223
1224         /*
1225          * Set the direction.
1226          */
1227         estate->es_direction = direction;
1228
1229         /*
1230          * Loop until we've processed the proper number of tuples from the plan.
1231          */
1232         for (;;)
1233         {
1234                 /* Reset the per-output-tuple exprcontext */
1235                 ResetPerTupleExprContext(estate);
1236
1237                 /*
1238                  * Execute the plan and obtain a tuple
1239                  */
1240                 slot = ExecProcNode(planstate);
1241
1242                 /*
1243                  * if the tuple is null, then we assume there is nothing more to
1244                  * process so we just end the loop...
1245                  */
1246                 if (TupIsNull(slot))
1247                         break;
1248
1249                 /*
1250                  * If we have a junk filter, then project a new tuple with the junk
1251                  * removed.
1252                  *
1253                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1254                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1255                  * because that tuple slot has the wrong descriptor.)
1256                  */
1257                 if (estate->es_junkFilter != NULL)
1258                         slot = ExecFilterJunk(estate->es_junkFilter, slot);
1259
1260                 /*
1261                  * If we are supposed to send the tuple somewhere, do so. (In
1262                  * practice, this is probably always the case at this point.)
1263                  */
1264                 if (sendTuples)
1265                         (*dest->receiveSlot) (slot, dest);
1266
1267                 /*
1268                  * Count tuples processed, if this is a SELECT.  (For other operation
1269                  * types, the ModifyTable plan node must count the appropriate
1270                  * events.)
1271                  */
1272                 if (operation == CMD_SELECT)
1273                         (estate->es_processed)++;
1274
1275                 /*
1276                  * check our tuple count.. if we've processed the proper number then
1277                  * quit, else loop again and process more tuples.  Zero numberTuples
1278                  * means no limit.
1279                  */
1280                 current_tuple_count++;
1281                 if (numberTuples && numberTuples == current_tuple_count)
1282                         break;
1283         }
1284 }
1285
1286
1287 /*
1288  * ExecRelCheck --- check that tuple meets constraints for result relation
1289  */
1290 static const char *
1291 ExecRelCheck(ResultRelInfo *resultRelInfo,
1292                          TupleTableSlot *slot, EState *estate)
1293 {
1294         Relation        rel = resultRelInfo->ri_RelationDesc;
1295         int                     ncheck = rel->rd_att->constr->num_check;
1296         ConstrCheck *check = rel->rd_att->constr->check;
1297         ExprContext *econtext;
1298         MemoryContext oldContext;
1299         List       *qual;
1300         int                     i;
1301
1302         /*
1303          * If first time through for this result relation, build expression
1304          * nodetrees for rel's constraint expressions.  Keep them in the per-query
1305          * memory context so they'll survive throughout the query.
1306          */
1307         if (resultRelInfo->ri_ConstraintExprs == NULL)
1308         {
1309                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1310                 resultRelInfo->ri_ConstraintExprs =
1311                         (List **) palloc(ncheck * sizeof(List *));
1312                 for (i = 0; i < ncheck; i++)
1313                 {
1314                         /* ExecQual wants implicit-AND form */
1315                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
1316                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
1317                                 ExecPrepareExpr((Expr *) qual, estate);
1318                 }
1319                 MemoryContextSwitchTo(oldContext);
1320         }
1321
1322         /*
1323          * We will use the EState's per-tuple context for evaluating constraint
1324          * expressions (creating it if it's not already there).
1325          */
1326         econtext = GetPerTupleExprContext(estate);
1327
1328         /* Arrange for econtext's scan tuple to be the tuple under test */
1329         econtext->ecxt_scantuple = slot;
1330
1331         /* And evaluate the constraints */
1332         for (i = 0; i < ncheck; i++)
1333         {
1334                 qual = resultRelInfo->ri_ConstraintExprs[i];
1335
1336                 /*
1337                  * NOTE: SQL92 specifies that a NULL result from a constraint
1338                  * expression is not to be treated as a failure.  Therefore, tell
1339                  * ExecQual to return TRUE for NULL.
1340                  */
1341                 if (!ExecQual(qual, econtext, true))
1342                         return check[i].ccname;
1343         }
1344
1345         /* NULL result means no error */
1346         return NULL;
1347 }
1348
1349 void
1350 ExecConstraints(ResultRelInfo *resultRelInfo,
1351                                 TupleTableSlot *slot, EState *estate)
1352 {
1353         Relation        rel = resultRelInfo->ri_RelationDesc;
1354         TupleConstr *constr = rel->rd_att->constr;
1355
1356         Assert(constr);
1357
1358         if (constr->has_not_null)
1359         {
1360                 int                     natts = rel->rd_att->natts;
1361                 int                     attrChk;
1362
1363                 for (attrChk = 1; attrChk <= natts; attrChk++)
1364                 {
1365                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1366                                 slot_attisnull(slot, attrChk))
1367                                 ereport(ERROR,
1368                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1369                                                  errmsg("null value in column \"%s\" violates not-null constraint",
1370                                                 NameStr(rel->rd_att->attrs[attrChk - 1]->attname))));
1371                 }
1372         }
1373
1374         if (constr->num_check > 0)
1375         {
1376                 const char *failed;
1377
1378                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1379                         ereport(ERROR,
1380                                         (errcode(ERRCODE_CHECK_VIOLATION),
1381                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1382                                                         RelationGetRelationName(rel), failed)));
1383         }
1384 }
1385
1386
1387 /*
1388  * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1389  */
1390 ExecRowMark *
1391 ExecFindRowMark(EState *estate, Index rti)
1392 {
1393         ListCell   *lc;
1394
1395         foreach(lc, estate->es_rowMarks)
1396         {
1397                 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1398
1399                 if (erm->rti == rti)
1400                         return erm;
1401         }
1402         elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1403         return NULL;                            /* keep compiler quiet */
1404 }
1405
1406 /*
1407  * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1408  *
1409  * Inputs are the underlying ExecRowMark struct and the targetlist of the
1410  * input plan node (not planstate node!).  We need the latter to find out
1411  * the column numbers of the resjunk columns.
1412  */
1413 ExecAuxRowMark *
1414 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1415 {
1416         ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1417         char            resname[32];
1418
1419         aerm->rowmark = erm;
1420
1421         /* Look up the resjunk columns associated with this rowmark */
1422         if (erm->relation)
1423         {
1424                 Assert(erm->markType != ROW_MARK_COPY);
1425
1426                 /* if child rel, need tableoid */
1427                 if (erm->rti != erm->prti)
1428                 {
1429                         snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1430                         aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1431                                                                                                                    resname);
1432                         if (!AttributeNumberIsValid(aerm->toidAttNo))
1433                                 elog(ERROR, "could not find junk %s column", resname);
1434                 }
1435
1436                 /* always need ctid for real relations */
1437                 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1438                 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1439                                                                                                            resname);
1440                 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1441                         elog(ERROR, "could not find junk %s column", resname);
1442         }
1443         else
1444         {
1445                 Assert(erm->markType == ROW_MARK_COPY);
1446
1447                 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1448                 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1449                                                                                                                 resname);
1450                 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1451                         elog(ERROR, "could not find junk %s column", resname);
1452         }
1453
1454         return aerm;
1455 }
1456
1457
1458 /*
1459  * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1460  * process the updated version under READ COMMITTED rules.
1461  *
1462  * See backend/executor/README for some info about how this works.
1463  */
1464
1465
1466 /*
1467  * Check a modified tuple to see if we want to process its updated version
1468  * under READ COMMITTED rules.
1469  *
1470  *      estate - outer executor state data
1471  *      epqstate - state for EvalPlanQual rechecking
1472  *      relation - table containing tuple
1473  *      rti - rangetable index of table containing tuple
1474  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1475  *      priorXmax - t_xmax from the outdated tuple
1476  *
1477  * *tid is also an output parameter: it's modified to hold the TID of the
1478  * latest version of the tuple (note this may be changed even on failure)
1479  *
1480  * Returns a slot containing the new candidate update/delete tuple, or
1481  * NULL if we determine we shouldn't process the row.
1482  */
1483 TupleTableSlot *
1484 EvalPlanQual(EState *estate, EPQState *epqstate,
1485                          Relation relation, Index rti,
1486                          ItemPointer tid, TransactionId priorXmax)
1487 {
1488         TupleTableSlot *slot;
1489         HeapTuple       copyTuple;
1490
1491         Assert(rti > 0);
1492
1493         /*
1494          * Get and lock the updated version of the row; if fail, return NULL.
1495          */
1496         copyTuple = EvalPlanQualFetch(estate, relation, LockTupleExclusive,
1497                                                                   tid, priorXmax);
1498
1499         if (copyTuple == NULL)
1500                 return NULL;
1501
1502         /*
1503          * For UPDATE/DELETE we have to return tid of actual row we're executing
1504          * PQ for.
1505          */
1506         *tid = copyTuple->t_self;
1507
1508         /*
1509          * Need to run a recheck subquery.      Initialize or reinitialize EPQ state.
1510          */
1511         EvalPlanQualBegin(epqstate, estate);
1512
1513         /*
1514          * Free old test tuple, if any, and store new tuple where relation's scan
1515          * node will see it
1516          */
1517         EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1518
1519         /*
1520          * Fetch any non-locked source rows
1521          */
1522         EvalPlanQualFetchRowMarks(epqstate);
1523
1524         /*
1525          * Run the EPQ query.  We assume it will return at most one tuple.
1526          */
1527         slot = EvalPlanQualNext(epqstate);
1528
1529         /*
1530          * If we got a tuple, force the slot to materialize the tuple so that it
1531          * is not dependent on any local state in the EPQ query (in particular,
1532          * it's highly likely that the slot contains references to any pass-by-ref
1533          * datums that may be present in copyTuple).  As with the next step, this
1534          * is to guard against early re-use of the EPQ query.
1535          */
1536         if (!TupIsNull(slot))
1537                 (void) ExecMaterializeSlot(slot);
1538
1539         /*
1540          * Clear out the test tuple.  This is needed in case the EPQ query is
1541          * re-used to test a tuple for a different relation.  (Not clear that can
1542          * really happen, but let's be safe.)
1543          */
1544         EvalPlanQualSetTuple(epqstate, rti, NULL);
1545
1546         return slot;
1547 }
1548
1549 /*
1550  * Fetch a copy of the newest version of an outdated tuple
1551  *
1552  *      estate - executor state data
1553  *      relation - table containing tuple
1554  *      lockmode - requested tuple lock mode
1555  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1556  *      priorXmax - t_xmax from the outdated tuple
1557  *
1558  * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1559  * that there is no newest version (ie, the row was deleted not updated).
1560  * If successful, we have locked the newest tuple version, so caller does not
1561  * need to worry about it changing anymore.
1562  *
1563  * Note: properly, lockmode should be declared as enum LockTupleMode,
1564  * but we use "int" to avoid having to include heapam.h in executor.h.
1565  */
1566 HeapTuple
1567 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1568                                   ItemPointer tid, TransactionId priorXmax)
1569 {
1570         HeapTuple       copyTuple = NULL;
1571         HeapTupleData tuple;
1572         SnapshotData SnapshotDirty;
1573
1574         /*
1575          * fetch target tuple
1576          *
1577          * Loop here to deal with updated or busy tuples
1578          */
1579         InitDirtySnapshot(SnapshotDirty);
1580         tuple.t_self = *tid;
1581         for (;;)
1582         {
1583                 Buffer          buffer;
1584
1585                 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1586                 {
1587                         HTSU_Result test;
1588                         ItemPointerData update_ctid;
1589                         TransactionId update_xmax;
1590
1591                         /*
1592                          * If xmin isn't what we're expecting, the slot must have been
1593                          * recycled and reused for an unrelated tuple.  This implies that
1594                          * the latest version of the row was deleted, so we need do
1595                          * nothing.  (Should be safe to examine xmin without getting
1596                          * buffer's content lock, since xmin never changes in an existing
1597                          * tuple.)
1598                          */
1599                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1600                                                                          priorXmax))
1601                         {
1602                                 ReleaseBuffer(buffer);
1603                                 return NULL;
1604                         }
1605
1606                         /* otherwise xmin should not be dirty... */
1607                         if (TransactionIdIsValid(SnapshotDirty.xmin))
1608                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1609
1610                         /*
1611                          * If tuple is being updated by other transaction then we have to
1612                          * wait for its commit/abort.
1613                          */
1614                         if (TransactionIdIsValid(SnapshotDirty.xmax))
1615                         {
1616                                 ReleaseBuffer(buffer);
1617                                 XactLockTableWait(SnapshotDirty.xmax);
1618                                 continue;               /* loop back to repeat heap_fetch */
1619                         }
1620
1621                         /*
1622                          * If tuple was inserted by our own transaction, we have to check
1623                          * cmin against es_output_cid: cmin >= current CID means our
1624                          * command cannot see the tuple, so we should ignore it.  Without
1625                          * this we are open to the "Halloween problem" of indefinitely
1626                          * re-updating the same tuple. (We need not check cmax because
1627                          * HeapTupleSatisfiesDirty will consider a tuple deleted by our
1628                          * transaction dead, regardless of cmax.)  We just checked that
1629                          * priorXmax == xmin, so we can test that variable instead of
1630                          * doing HeapTupleHeaderGetXmin again.
1631                          */
1632                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1633                                 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1634                         {
1635                                 ReleaseBuffer(buffer);
1636                                 return NULL;
1637                         }
1638
1639                         /*
1640                          * This is a live tuple, so now try to lock it.
1641                          */
1642                         test = heap_lock_tuple(relation, &tuple, &buffer,
1643                                                                    &update_ctid, &update_xmax,
1644                                                                    estate->es_output_cid,
1645                                                                    lockmode, false);
1646                         /* We now have two pins on the buffer, get rid of one */
1647                         ReleaseBuffer(buffer);
1648
1649                         switch (test)
1650                         {
1651                                 case HeapTupleSelfUpdated:
1652                                         /* treat it as deleted; do not process */
1653                                         ReleaseBuffer(buffer);
1654                                         return NULL;
1655
1656                                 case HeapTupleMayBeUpdated:
1657                                         /* successfully locked */
1658                                         break;
1659
1660                                 case HeapTupleUpdated:
1661                                         ReleaseBuffer(buffer);
1662                                         if (IsolationUsesXactSnapshot())
1663                                                 ereport(ERROR,
1664                                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1665                                                                  errmsg("could not serialize access due to concurrent update")));
1666                                         if (!ItemPointerEquals(&update_ctid, &tuple.t_self))
1667                                         {
1668                                                 /* it was updated, so look at the updated version */
1669                                                 tuple.t_self = update_ctid;
1670                                                 /* updated row should have xmin matching this xmax */
1671                                                 priorXmax = update_xmax;
1672                                                 continue;
1673                                         }
1674                                         /* tuple was deleted, so give up */
1675                                         return NULL;
1676
1677                                 default:
1678                                         ReleaseBuffer(buffer);
1679                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
1680                                                  test);
1681                                         return NULL;    /* keep compiler quiet */
1682                         }
1683
1684                         /*
1685                          * We got tuple - now copy it for use by recheck query.
1686                          */
1687                         copyTuple = heap_copytuple(&tuple);
1688                         ReleaseBuffer(buffer);
1689                         break;
1690                 }
1691
1692                 /*
1693                  * If the referenced slot was actually empty, the latest version of
1694                  * the row must have been deleted, so we need do nothing.
1695                  */
1696                 if (tuple.t_data == NULL)
1697                 {
1698                         ReleaseBuffer(buffer);
1699                         return NULL;
1700                 }
1701
1702                 /*
1703                  * As above, if xmin isn't what we're expecting, do nothing.
1704                  */
1705                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1706                                                                  priorXmax))
1707                 {
1708                         ReleaseBuffer(buffer);
1709                         return NULL;
1710                 }
1711
1712                 /*
1713                  * If we get here, the tuple was found but failed SnapshotDirty.
1714                  * Assuming the xmin is either a committed xact or our own xact (as it
1715                  * certainly should be if we're trying to modify the tuple), this must
1716                  * mean that the row was updated or deleted by either a committed xact
1717                  * or our own xact.  If it was deleted, we can ignore it; if it was
1718                  * updated then chain up to the next version and repeat the whole
1719                  * process.
1720                  *
1721                  * As above, it should be safe to examine xmax and t_ctid without the
1722                  * buffer content lock, because they can't be changing.
1723                  */
1724                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
1725                 {
1726                         /* deleted, so forget about it */
1727                         ReleaseBuffer(buffer);
1728                         return NULL;
1729                 }
1730
1731                 /* updated, so look at the updated row */
1732                 tuple.t_self = tuple.t_data->t_ctid;
1733                 /* updated row should have xmin matching this xmax */
1734                 priorXmax = HeapTupleHeaderGetXmax(tuple.t_data);
1735                 ReleaseBuffer(buffer);
1736                 /* loop back to fetch next in chain */
1737         }
1738
1739         /*
1740          * Return the copied tuple
1741          */
1742         return copyTuple;
1743 }
1744
1745 /*
1746  * EvalPlanQualInit -- initialize during creation of a plan state node
1747  * that might need to invoke EPQ processing.
1748  *
1749  * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
1750  * with EvalPlanQualSetPlan.
1751  */
1752 void
1753 EvalPlanQualInit(EPQState *epqstate, EState *estate,
1754                                  Plan *subplan, List *auxrowmarks, int epqParam)
1755 {
1756         /* Mark the EPQ state inactive */
1757         epqstate->estate = NULL;
1758         epqstate->planstate = NULL;
1759         epqstate->origslot = NULL;
1760         /* ... and remember data that EvalPlanQualBegin will need */
1761         epqstate->plan = subplan;
1762         epqstate->arowMarks = auxrowmarks;
1763         epqstate->epqParam = epqParam;
1764 }
1765
1766 /*
1767  * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
1768  *
1769  * We need this so that ModifyTuple can deal with multiple subplans.
1770  */
1771 void
1772 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
1773 {
1774         /* If we have a live EPQ query, shut it down */
1775         EvalPlanQualEnd(epqstate);
1776         /* And set/change the plan pointer */
1777         epqstate->plan = subplan;
1778         /* The rowmarks depend on the plan, too */
1779         epqstate->arowMarks = auxrowmarks;
1780 }
1781
1782 /*
1783  * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
1784  *
1785  * NB: passed tuple must be palloc'd; it may get freed later
1786  */
1787 void
1788 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
1789 {
1790         EState     *estate = epqstate->estate;
1791
1792         Assert(rti > 0);
1793
1794         /*
1795          * free old test tuple, if any, and store new tuple where relation's scan
1796          * node will see it
1797          */
1798         if (estate->es_epqTuple[rti - 1] != NULL)
1799                 heap_freetuple(estate->es_epqTuple[rti - 1]);
1800         estate->es_epqTuple[rti - 1] = tuple;
1801         estate->es_epqTupleSet[rti - 1] = true;
1802 }
1803
1804 /*
1805  * Fetch back the current test tuple (if any) for the specified RTI
1806  */
1807 HeapTuple
1808 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
1809 {
1810         EState     *estate = epqstate->estate;
1811
1812         Assert(rti > 0);
1813
1814         return estate->es_epqTuple[rti - 1];
1815 }
1816
1817 /*
1818  * Fetch the current row values for any non-locked relations that need
1819  * to be scanned by an EvalPlanQual operation.  origslot must have been set
1820  * to contain the current result row (top-level row) that we need to recheck.
1821  */
1822 void
1823 EvalPlanQualFetchRowMarks(EPQState *epqstate)
1824 {
1825         ListCell   *l;
1826
1827         Assert(epqstate->origslot != NULL);
1828
1829         foreach(l, epqstate->arowMarks)
1830         {
1831                 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
1832                 ExecRowMark *erm = aerm->rowmark;
1833                 Datum           datum;
1834                 bool            isNull;
1835                 HeapTupleData tuple;
1836
1837                 if (RowMarkRequiresRowShareLock(erm->markType))
1838                         elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
1839
1840                 /* clear any leftover test tuple for this rel */
1841                 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
1842
1843                 if (erm->relation)
1844                 {
1845                         Buffer          buffer;
1846
1847                         Assert(erm->markType == ROW_MARK_REFERENCE);
1848
1849                         /* if child rel, must check whether it produced this row */
1850                         if (erm->rti != erm->prti)
1851                         {
1852                                 Oid                     tableoid;
1853
1854                                 datum = ExecGetJunkAttribute(epqstate->origslot,
1855                                                                                          aerm->toidAttNo,
1856                                                                                          &isNull);
1857                                 /* non-locked rels could be on the inside of outer joins */
1858                                 if (isNull)
1859                                         continue;
1860                                 tableoid = DatumGetObjectId(datum);
1861
1862                                 if (tableoid != RelationGetRelid(erm->relation))
1863                                 {
1864                                         /* this child is inactive right now */
1865                                         continue;
1866                                 }
1867                         }
1868
1869                         /* fetch the tuple's ctid */
1870                         datum = ExecGetJunkAttribute(epqstate->origslot,
1871                                                                                  aerm->ctidAttNo,
1872                                                                                  &isNull);
1873                         /* non-locked rels could be on the inside of outer joins */
1874                         if (isNull)
1875                                 continue;
1876                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
1877
1878                         /* okay, fetch the tuple */
1879                         if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
1880                                                         false, NULL))
1881                                 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
1882
1883                         /* successful, copy and store tuple */
1884                         EvalPlanQualSetTuple(epqstate, erm->rti,
1885                                                                  heap_copytuple(&tuple));
1886                         ReleaseBuffer(buffer);
1887                 }
1888                 else
1889                 {
1890                         HeapTupleHeader td;
1891
1892                         Assert(erm->markType == ROW_MARK_COPY);
1893
1894                         /* fetch the whole-row Var for the relation */
1895                         datum = ExecGetJunkAttribute(epqstate->origslot,
1896                                                                                  aerm->wholeAttNo,
1897                                                                                  &isNull);
1898                         /* non-locked rels could be on the inside of outer joins */
1899                         if (isNull)
1900                                 continue;
1901                         td = DatumGetHeapTupleHeader(datum);
1902
1903                         /* build a temporary HeapTuple control structure */
1904                         tuple.t_len = HeapTupleHeaderGetDatumLength(td);
1905                         ItemPointerSetInvalid(&(tuple.t_self));
1906                         tuple.t_tableOid = InvalidOid;
1907                         tuple.t_data = td;
1908
1909                         /* copy and store tuple */
1910                         EvalPlanQualSetTuple(epqstate, erm->rti,
1911                                                                  heap_copytuple(&tuple));
1912                 }
1913         }
1914 }
1915
1916 /*
1917  * Fetch the next row (if any) from EvalPlanQual testing
1918  *
1919  * (In practice, there should never be more than one row...)
1920  */
1921 TupleTableSlot *
1922 EvalPlanQualNext(EPQState *epqstate)
1923 {
1924         MemoryContext oldcontext;
1925         TupleTableSlot *slot;
1926
1927         oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
1928         slot = ExecProcNode(epqstate->planstate);
1929         MemoryContextSwitchTo(oldcontext);
1930
1931         return slot;
1932 }
1933
1934 /*
1935  * Initialize or reset an EvalPlanQual state tree
1936  */
1937 void
1938 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
1939 {
1940         EState     *estate = epqstate->estate;
1941
1942         if (estate == NULL)
1943         {
1944                 /* First time through, so create a child EState */
1945                 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
1946         }
1947         else
1948         {
1949                 /*
1950                  * We already have a suitable child EPQ tree, so just reset it.
1951                  */
1952                 int                     rtsize = list_length(parentestate->es_range_table);
1953                 PlanState  *planstate = epqstate->planstate;
1954
1955                 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
1956
1957                 /* Recopy current values of parent parameters */
1958                 if (parentestate->es_plannedstmt->nParamExec > 0)
1959                 {
1960                         int                     i = parentestate->es_plannedstmt->nParamExec;
1961
1962                         while (--i >= 0)
1963                         {
1964                                 /* copy value if any, but not execPlan link */
1965                                 estate->es_param_exec_vals[i].value =
1966                                         parentestate->es_param_exec_vals[i].value;
1967                                 estate->es_param_exec_vals[i].isnull =
1968                                         parentestate->es_param_exec_vals[i].isnull;
1969                         }
1970                 }
1971
1972                 /*
1973                  * Mark child plan tree as needing rescan at all scan nodes.  The
1974                  * first ExecProcNode will take care of actually doing the rescan.
1975                  */
1976                 planstate->chgParam = bms_add_member(planstate->chgParam,
1977                                                                                          epqstate->epqParam);
1978         }
1979 }
1980
1981 /*
1982  * Start execution of an EvalPlanQual plan tree.
1983  *
1984  * This is a cut-down version of ExecutorStart(): we copy some state from
1985  * the top-level estate rather than initializing it fresh.
1986  */
1987 static void
1988 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
1989 {
1990         EState     *estate;
1991         int                     rtsize;
1992         MemoryContext oldcontext;
1993         ListCell   *l;
1994
1995         rtsize = list_length(parentestate->es_range_table);
1996
1997         epqstate->estate = estate = CreateExecutorState();
1998
1999         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2000
2001         /*
2002          * Child EPQ EStates share the parent's copy of unchanging state such as
2003          * the snapshot, rangetable, result-rel info, and external Param info.
2004          * They need their own copies of local state, including a tuple table,
2005          * es_param_exec_vals, etc.
2006          */
2007         estate->es_direction = ForwardScanDirection;
2008         estate->es_snapshot = parentestate->es_snapshot;
2009         estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2010         estate->es_range_table = parentestate->es_range_table;
2011         estate->es_plannedstmt = parentestate->es_plannedstmt;
2012         estate->es_junkFilter = parentestate->es_junkFilter;
2013         estate->es_output_cid = parentestate->es_output_cid;
2014         estate->es_result_relations = parentestate->es_result_relations;
2015         estate->es_num_result_relations = parentestate->es_num_result_relations;
2016         estate->es_result_relation_info = parentestate->es_result_relation_info;
2017         /* es_trig_target_relations must NOT be copied */
2018         estate->es_rowMarks = parentestate->es_rowMarks;
2019         estate->es_instrument = parentestate->es_instrument;
2020         estate->es_select_into = parentestate->es_select_into;
2021         estate->es_into_oids = parentestate->es_into_oids;
2022
2023         /*
2024          * The external param list is simply shared from parent.  The internal
2025          * param workspace has to be local state, but we copy the initial values
2026          * from the parent, so as to have access to any param values that were
2027          * already set from other parts of the parent's plan tree.
2028          */
2029         estate->es_param_list_info = parentestate->es_param_list_info;
2030         if (parentestate->es_plannedstmt->nParamExec > 0)
2031         {
2032                 int                     i = parentestate->es_plannedstmt->nParamExec;
2033
2034                 estate->es_param_exec_vals = (ParamExecData *)
2035                         palloc0(i * sizeof(ParamExecData));
2036                 while (--i >= 0)
2037                 {
2038                         /* copy value if any, but not execPlan link */
2039                         estate->es_param_exec_vals[i].value =
2040                                 parentestate->es_param_exec_vals[i].value;
2041                         estate->es_param_exec_vals[i].isnull =
2042                                 parentestate->es_param_exec_vals[i].isnull;
2043                 }
2044         }
2045
2046         /*
2047          * Each EState must have its own es_epqScanDone state, but if we have
2048          * nested EPQ checks they should share es_epqTuple arrays.      This allows
2049          * sub-rechecks to inherit the values being examined by an outer recheck.
2050          */
2051         estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2052         if (parentestate->es_epqTuple != NULL)
2053         {
2054                 estate->es_epqTuple = parentestate->es_epqTuple;
2055                 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2056         }
2057         else
2058         {
2059                 estate->es_epqTuple = (HeapTuple *)
2060                         palloc0(rtsize * sizeof(HeapTuple));
2061                 estate->es_epqTupleSet = (bool *)
2062                         palloc0(rtsize * sizeof(bool));
2063         }
2064
2065         /*
2066          * Each estate also has its own tuple table.
2067          */
2068         estate->es_tupleTable = NIL;
2069
2070         /*
2071          * Initialize private state information for each SubPlan.  We must do this
2072          * before running ExecInitNode on the main query tree, since
2073          * ExecInitSubPlan expects to be able to find these entries. Some of the
2074          * SubPlans might not be used in the part of the plan tree we intend to
2075          * run, but since it's not easy to tell which, we just initialize them
2076          * all.
2077          */
2078         Assert(estate->es_subplanstates == NIL);
2079         foreach(l, parentestate->es_plannedstmt->subplans)
2080         {
2081                 Plan       *subplan = (Plan *) lfirst(l);
2082                 PlanState  *subplanstate;
2083
2084                 subplanstate = ExecInitNode(subplan, estate, 0);
2085
2086                 estate->es_subplanstates = lappend(estate->es_subplanstates,
2087                                                                                    subplanstate);
2088         }
2089
2090         /*
2091          * Initialize the private state information for all the nodes in the part
2092          * of the plan tree we need to run.  This opens files, allocates storage
2093          * and leaves us ready to start processing tuples.
2094          */
2095         epqstate->planstate = ExecInitNode(planTree, estate, 0);
2096
2097         MemoryContextSwitchTo(oldcontext);
2098 }
2099
2100 /*
2101  * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2102  * or if we are done with the current EPQ child.
2103  *
2104  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2105  * of the normal cleanup, but *not* close result relations (which we are
2106  * just sharing from the outer query).  We do, however, have to close any
2107  * trigger target relations that got opened, since those are not shared.
2108  * (There probably shouldn't be any of the latter, but just in case...)
2109  */
2110 void
2111 EvalPlanQualEnd(EPQState *epqstate)
2112 {
2113         EState     *estate = epqstate->estate;
2114         MemoryContext oldcontext;
2115         ListCell   *l;
2116
2117         if (estate == NULL)
2118                 return;                                 /* idle, so nothing to do */
2119
2120         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2121
2122         ExecEndNode(epqstate->planstate);
2123
2124         foreach(l, estate->es_subplanstates)
2125         {
2126                 PlanState  *subplanstate = (PlanState *) lfirst(l);
2127
2128                 ExecEndNode(subplanstate);
2129         }
2130
2131         /* throw away the per-estate tuple table */
2132         ExecResetTupleTable(estate->es_tupleTable, false);
2133
2134         /* close any trigger target relations attached to this EState */
2135         foreach(l, estate->es_trig_target_relations)
2136         {
2137                 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2138
2139                 /* Close indices and then the relation itself */
2140                 ExecCloseIndices(resultRelInfo);
2141                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2142         }
2143
2144         MemoryContextSwitchTo(oldcontext);
2145
2146         FreeExecutorState(estate);
2147
2148         /* Mark EPQState idle */
2149         epqstate->estate = NULL;
2150         epqstate->planstate = NULL;
2151         epqstate->origslot = NULL;
2152 }
2153
2154
2155 /*
2156  * Support for SELECT INTO (a/k/a CREATE TABLE AS)
2157  *
2158  * We implement SELECT INTO by diverting SELECT's normal output with
2159  * a specialized DestReceiver type.
2160  */
2161
2162 typedef struct
2163 {
2164         DestReceiver pub;                       /* publicly-known function pointers */
2165         EState     *estate;                     /* EState we are working with */
2166         Relation        rel;                    /* Relation to write to */
2167         int                     hi_options;             /* heap_insert performance options */
2168         BulkInsertState bistate;        /* bulk insert state */
2169 } DR_intorel;
2170
2171 /*
2172  * OpenIntoRel --- actually create the SELECT INTO target relation
2173  *
2174  * This also replaces QueryDesc->dest with the special DestReceiver for
2175  * SELECT INTO.  We assume that the correct result tuple type has already
2176  * been placed in queryDesc->tupDesc.
2177  */
2178 static void
2179 OpenIntoRel(QueryDesc *queryDesc)
2180 {
2181         IntoClause *into = queryDesc->plannedstmt->intoClause;
2182         EState     *estate = queryDesc->estate;
2183         Relation        intoRelationDesc;
2184         char       *intoName;
2185         Oid                     namespaceId;
2186         Oid                     tablespaceId;
2187         Datum           reloptions;
2188         AclResult       aclresult;
2189         Oid                     intoRelationId;
2190         TupleDesc       tupdesc;
2191         DR_intorel *myState;
2192         static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
2193
2194         Assert(into);
2195
2196         /*
2197          * XXX This code needs to be kept in sync with DefineRelation(). Maybe we
2198          * should try to use that function instead.
2199          */
2200
2201         /*
2202          * Check consistency of arguments
2203          */
2204         if (into->onCommit != ONCOMMIT_NOOP
2205                 && into->rel->relpersistence != RELPERSISTENCE_TEMP)
2206                 ereport(ERROR,
2207                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
2208                                  errmsg("ON COMMIT can only be used on temporary tables")));
2209
2210         /*
2211          * Security check: disallow creating temp tables from security-restricted
2212          * code.  This is needed because calling code might not expect untrusted
2213          * tables to appear in pg_temp at the front of its search path.
2214          */
2215         if (into->rel->relpersistence == RELPERSISTENCE_TEMP
2216                 && InSecurityRestrictedOperation())
2217                 ereport(ERROR,
2218                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2219                                  errmsg("cannot create temporary table within security-restricted operation")));
2220
2221         /*
2222          * Find namespace to create in, check its permissions
2223          */
2224         intoName = into->rel->relname;
2225         namespaceId = RangeVarGetCreationNamespace(into->rel);
2226
2227         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
2228                                                                           ACL_CREATE);
2229         if (aclresult != ACLCHECK_OK)
2230                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2231                                            get_namespace_name(namespaceId));
2232
2233         /*
2234          * Select tablespace to use.  If not specified, use default tablespace
2235          * (which may in turn default to database's default).
2236          */
2237         if (into->tableSpaceName)
2238         {
2239                 tablespaceId = get_tablespace_oid(into->tableSpaceName, false);
2240         }
2241         else
2242         {
2243                 tablespaceId = GetDefaultTablespace(into->rel->relpersistence);
2244                 /* note InvalidOid is OK in this case */
2245         }
2246
2247         /* Check permissions except when using the database's default space */
2248         if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace)
2249         {
2250                 AclResult       aclresult;
2251
2252                 aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
2253                                                                                    ACL_CREATE);
2254
2255                 if (aclresult != ACLCHECK_OK)
2256                         aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
2257                                                    get_tablespace_name(tablespaceId));
2258         }
2259
2260         /* Parse and validate any reloptions */
2261         reloptions = transformRelOptions((Datum) 0,
2262                                                                          into->options,
2263                                                                          NULL,
2264                                                                          validnsps,
2265                                                                          true,
2266                                                                          false);
2267         (void) heap_reloptions(RELKIND_RELATION, reloptions, true);
2268
2269         /* Copy the tupdesc because heap_create_with_catalog modifies it */
2270         tupdesc = CreateTupleDescCopy(queryDesc->tupDesc);
2271
2272         /* Now we can actually create the new relation */
2273         intoRelationId = heap_create_with_catalog(intoName,
2274                                                                                           namespaceId,
2275                                                                                           tablespaceId,
2276                                                                                           InvalidOid,
2277                                                                                           InvalidOid,
2278                                                                                           InvalidOid,
2279                                                                                           GetUserId(),
2280                                                                                           tupdesc,
2281                                                                                           NIL,
2282                                                                                           RELKIND_RELATION,
2283                                                                                           into->rel->relpersistence,
2284                                                                                           false,
2285                                                                                           false,
2286                                                                                           true,
2287                                                                                           0,
2288                                                                                           into->onCommit,
2289                                                                                           reloptions,
2290                                                                                           true,
2291                                                                                           allowSystemTableMods,
2292                                                                                           false);
2293         Assert(intoRelationId != InvalidOid);
2294
2295         FreeTupleDesc(tupdesc);
2296
2297         /*
2298          * Advance command counter so that the newly-created relation's catalog
2299          * tuples will be visible to heap_open.
2300          */
2301         CommandCounterIncrement();
2302
2303         /*
2304          * If necessary, create a TOAST table for the INTO relation. Note that
2305          * AlterTableCreateToastTable ends with CommandCounterIncrement(), so that
2306          * the TOAST table will be visible for insertion.
2307          */
2308         reloptions = transformRelOptions((Datum) 0,
2309                                                                          into->options,
2310                                                                          "toast",
2311                                                                          validnsps,
2312                                                                          true,
2313                                                                          false);
2314
2315         (void) heap_reloptions(RELKIND_TOASTVALUE, reloptions, true);
2316
2317         AlterTableCreateToastTable(intoRelationId, reloptions);
2318
2319         /*
2320          * And open the constructed table for writing.
2321          */
2322         intoRelationDesc = heap_open(intoRelationId, AccessExclusiveLock);
2323
2324         /*
2325          * Now replace the query's DestReceiver with one for SELECT INTO
2326          */
2327         queryDesc->dest = CreateDestReceiver(DestIntoRel);
2328         myState = (DR_intorel *) queryDesc->dest;
2329         Assert(myState->pub.mydest == DestIntoRel);
2330         myState->estate = estate;
2331         myState->rel = intoRelationDesc;
2332
2333         /*
2334          * We can skip WAL-logging the insertions, unless PITR or streaming
2335          * replication is in use. We can skip the FSM in any case.
2336          */
2337         myState->hi_options = HEAP_INSERT_SKIP_FSM |
2338                 (XLogIsNeeded() ? 0 : HEAP_INSERT_SKIP_WAL);
2339         myState->bistate = GetBulkInsertState();
2340
2341         /* Not using WAL requires smgr_targblock be initially invalid */
2342         Assert(RelationGetTargetBlock(intoRelationDesc) == InvalidBlockNumber);
2343 }
2344
2345 /*
2346  * CloseIntoRel --- clean up SELECT INTO at ExecutorEnd time
2347  */
2348 static void
2349 CloseIntoRel(QueryDesc *queryDesc)
2350 {
2351         DR_intorel *myState = (DR_intorel *) queryDesc->dest;
2352
2353         /* OpenIntoRel might never have gotten called */
2354         if (myState && myState->pub.mydest == DestIntoRel && myState->rel)
2355         {
2356                 FreeBulkInsertState(myState->bistate);
2357
2358                 /* If we skipped using WAL, must heap_sync before commit */
2359                 if (myState->hi_options & HEAP_INSERT_SKIP_WAL)
2360                         heap_sync(myState->rel);
2361
2362                 /* close rel, but keep lock until commit */
2363                 heap_close(myState->rel, NoLock);
2364
2365                 myState->rel = NULL;
2366         }
2367 }
2368
2369 /*
2370  * CreateIntoRelDestReceiver -- create a suitable DestReceiver object
2371  */
2372 DestReceiver *
2373 CreateIntoRelDestReceiver(void)
2374 {
2375         DR_intorel *self = (DR_intorel *) palloc0(sizeof(DR_intorel));
2376
2377         self->pub.receiveSlot = intorel_receive;
2378         self->pub.rStartup = intorel_startup;
2379         self->pub.rShutdown = intorel_shutdown;
2380         self->pub.rDestroy = intorel_destroy;
2381         self->pub.mydest = DestIntoRel;
2382
2383         /* private fields will be set by OpenIntoRel */
2384
2385         return (DestReceiver *) self;
2386 }
2387
2388 /*
2389  * intorel_startup --- executor startup
2390  */
2391 static void
2392 intorel_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2393 {
2394         /* no-op */
2395 }
2396
2397 /*
2398  * intorel_receive --- receive one tuple
2399  */
2400 static void
2401 intorel_receive(TupleTableSlot *slot, DestReceiver *self)
2402 {
2403         DR_intorel *myState = (DR_intorel *) self;
2404         HeapTuple       tuple;
2405
2406         /*
2407          * get the heap tuple out of the tuple table slot, making sure we have a
2408          * writable copy
2409          */
2410         tuple = ExecMaterializeSlot(slot);
2411
2412         /*
2413          * force assignment of new OID (see comments in ExecInsert)
2414          */
2415         if (myState->rel->rd_rel->relhasoids)
2416                 HeapTupleSetOid(tuple, InvalidOid);
2417
2418         heap_insert(myState->rel,
2419                                 tuple,
2420                                 myState->estate->es_output_cid,
2421                                 myState->hi_options,
2422                                 myState->bistate);
2423
2424         /* We know this is a newly created relation, so there are no indexes */
2425 }
2426
2427 /*
2428  * intorel_shutdown --- executor end
2429  */
2430 static void
2431 intorel_shutdown(DestReceiver *self)
2432 {
2433         /* no-op */
2434 }
2435
2436 /*
2437  * intorel_destroy --- release DestReceiver object
2438  */
2439 static void
2440 intorel_destroy(DestReceiver *self)
2441 {
2442         pfree(self);
2443 }