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