]> granicus.if.org Git - postgresql/blob - src/backend/executor/execMain.c
WITH CHECK OPTION support for auto-updatable VIEWs
[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 & EXEC_FLAG_EXPLAIN_ONLY;
869                 if (bms_is_member(i, plannedstmt->rewindPlanIDs))
870                         sp_eflags |= EXEC_FLAG_REWIND;
871
872                 subplanstate = ExecInitNode(subplan, estate, sp_eflags);
873
874                 estate->es_subplanstates = lappend(estate->es_subplanstates,
875                                                                                    subplanstate);
876
877                 i++;
878         }
879
880         /*
881          * Initialize the private state information for all the nodes in the query
882          * tree.  This opens files, allocates storage and leaves us ready to start
883          * processing tuples.
884          */
885         planstate = ExecInitNode(plan, estate, eflags);
886
887         /*
888          * Get the tuple descriptor describing the type of tuples to return.
889          */
890         tupType = ExecGetResultType(planstate);
891
892         /*
893          * Initialize the junk filter if needed.  SELECT queries need a filter if
894          * there are any junk attrs in the top-level tlist.
895          */
896         if (operation == CMD_SELECT)
897         {
898                 bool            junk_filter_needed = false;
899                 ListCell   *tlist;
900
901                 foreach(tlist, plan->targetlist)
902                 {
903                         TargetEntry *tle = (TargetEntry *) lfirst(tlist);
904
905                         if (tle->resjunk)
906                         {
907                                 junk_filter_needed = true;
908                                 break;
909                         }
910                 }
911
912                 if (junk_filter_needed)
913                 {
914                         JunkFilter *j;
915
916                         j = ExecInitJunkFilter(planstate->plan->targetlist,
917                                                                    tupType->tdhasoid,
918                                                                    ExecInitExtraTupleSlot(estate));
919                         estate->es_junkFilter = j;
920
921                         /* Want to return the cleaned tuple type */
922                         tupType = j->jf_cleanTupType;
923                 }
924         }
925
926         queryDesc->tupDesc = tupType;
927         queryDesc->planstate = planstate;
928 }
929
930 /*
931  * Check that a proposed result relation is a legal target for the operation
932  *
933  * Generally the parser and/or planner should have noticed any such mistake
934  * already, but let's make sure.
935  *
936  * Note: when changing this function, you probably also need to look at
937  * CheckValidRowMarkRel.
938  */
939 void
940 CheckValidResultRel(Relation resultRel, CmdType operation)
941 {
942         TriggerDesc *trigDesc = resultRel->trigdesc;
943         FdwRoutine *fdwroutine;
944
945         switch (resultRel->rd_rel->relkind)
946         {
947                 case RELKIND_RELATION:
948                         /* OK */
949                         break;
950                 case RELKIND_SEQUENCE:
951                         ereport(ERROR,
952                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
953                                          errmsg("cannot change sequence \"%s\"",
954                                                         RelationGetRelationName(resultRel))));
955                         break;
956                 case RELKIND_TOASTVALUE:
957                         ereport(ERROR,
958                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
959                                          errmsg("cannot change TOAST relation \"%s\"",
960                                                         RelationGetRelationName(resultRel))));
961                         break;
962                 case RELKIND_VIEW:
963
964                         /*
965                          * Okay only if there's a suitable INSTEAD OF trigger.  Messages
966                          * here should match rewriteHandler.c's rewriteTargetView, except
967                          * that we omit errdetail because we haven't got the information
968                          * handy (and given that we really shouldn't get here anyway, it's
969                          * not worth great exertion to get).
970                          */
971                         switch (operation)
972                         {
973                                 case CMD_INSERT:
974                                         if (!trigDesc || !trigDesc->trig_insert_instead_row)
975                                                 ereport(ERROR,
976                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
977                                                    errmsg("cannot insert into view \"%s\"",
978                                                                   RelationGetRelationName(resultRel)),
979                                                    errhint("To make the view insertable, provide an unconditional ON INSERT DO INSTEAD rule or an INSTEAD OF INSERT trigger.")));
980                                         break;
981                                 case CMD_UPDATE:
982                                         if (!trigDesc || !trigDesc->trig_update_instead_row)
983                                                 ereport(ERROR,
984                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
985                                                    errmsg("cannot update view \"%s\"",
986                                                                   RelationGetRelationName(resultRel)),
987                                                    errhint("To make the view updatable, provide an unconditional ON UPDATE DO INSTEAD rule or an INSTEAD OF UPDATE trigger.")));
988                                         break;
989                                 case CMD_DELETE:
990                                         if (!trigDesc || !trigDesc->trig_delete_instead_row)
991                                                 ereport(ERROR,
992                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
993                                                    errmsg("cannot delete from view \"%s\"",
994                                                                   RelationGetRelationName(resultRel)),
995                                                    errhint("To make the view updatable, provide an unconditional ON DELETE DO INSTEAD rule or an INSTEAD OF DELETE trigger.")));
996                                         break;
997                                 default:
998                                         elog(ERROR, "unrecognized CmdType: %d", (int) operation);
999                                         break;
1000                         }
1001                         break;
1002                 case RELKIND_MATVIEW:
1003                         if (!MatViewIncrementalMaintenanceIsEnabled())
1004                                 ereport(ERROR,
1005                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1006                                                  errmsg("cannot change materialized view \"%s\"",
1007                                                                 RelationGetRelationName(resultRel))));
1008                         break;
1009                 case RELKIND_FOREIGN_TABLE:
1010                         /* Okay only if the FDW supports it */
1011                         fdwroutine = GetFdwRoutineForRelation(resultRel, false);
1012                         switch (operation)
1013                         {
1014                                 case CMD_INSERT:
1015                                         if (fdwroutine->ExecForeignInsert == NULL)
1016                                                 ereport(ERROR,
1017                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1018                                                         errmsg("cannot insert into foreign table \"%s\"",
1019                                                                    RelationGetRelationName(resultRel))));
1020                                         if (fdwroutine->IsForeignRelUpdatable != NULL &&
1021                                                 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_INSERT)) == 0)
1022                                                 ereport(ERROR,
1023                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1024                                                 errmsg("foreign table \"%s\" does not allow inserts",
1025                                                            RelationGetRelationName(resultRel))));
1026                                         break;
1027                                 case CMD_UPDATE:
1028                                         if (fdwroutine->ExecForeignUpdate == NULL)
1029                                                 ereport(ERROR,
1030                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1031                                                                  errmsg("cannot update foreign table \"%s\"",
1032                                                                                 RelationGetRelationName(resultRel))));
1033                                         if (fdwroutine->IsForeignRelUpdatable != NULL &&
1034                                                 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_UPDATE)) == 0)
1035                                                 ereport(ERROR,
1036                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1037                                                 errmsg("foreign table \"%s\" does not allow updates",
1038                                                            RelationGetRelationName(resultRel))));
1039                                         break;
1040                                 case CMD_DELETE:
1041                                         if (fdwroutine->ExecForeignDelete == NULL)
1042                                                 ereport(ERROR,
1043                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1044                                                         errmsg("cannot delete from foreign table \"%s\"",
1045                                                                    RelationGetRelationName(resultRel))));
1046                                         if (fdwroutine->IsForeignRelUpdatable != NULL &&
1047                                                 (fdwroutine->IsForeignRelUpdatable(resultRel) & (1 << CMD_DELETE)) == 0)
1048                                                 ereport(ERROR,
1049                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1050                                                 errmsg("foreign table \"%s\" does not allow deletes",
1051                                                            RelationGetRelationName(resultRel))));
1052                                         break;
1053                                 default:
1054                                         elog(ERROR, "unrecognized CmdType: %d", (int) operation);
1055                                         break;
1056                         }
1057                         break;
1058                 default:
1059                         ereport(ERROR,
1060                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1061                                          errmsg("cannot change relation \"%s\"",
1062                                                         RelationGetRelationName(resultRel))));
1063                         break;
1064         }
1065 }
1066
1067 /*
1068  * Check that a proposed rowmark target relation is a legal target
1069  *
1070  * In most cases parser and/or planner should have noticed this already, but
1071  * they don't cover all cases.
1072  */
1073 static void
1074 CheckValidRowMarkRel(Relation rel, RowMarkType markType)
1075 {
1076         switch (rel->rd_rel->relkind)
1077         {
1078                 case RELKIND_RELATION:
1079                         /* OK */
1080                         break;
1081                 case RELKIND_SEQUENCE:
1082                         /* Must disallow this because we don't vacuum sequences */
1083                         ereport(ERROR,
1084                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1085                                          errmsg("cannot lock rows in sequence \"%s\"",
1086                                                         RelationGetRelationName(rel))));
1087                         break;
1088                 case RELKIND_TOASTVALUE:
1089                         /* We could allow this, but there seems no good reason to */
1090                         ereport(ERROR,
1091                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1092                                          errmsg("cannot lock rows in TOAST relation \"%s\"",
1093                                                         RelationGetRelationName(rel))));
1094                         break;
1095                 case RELKIND_VIEW:
1096                         /* Should not get here; planner should have expanded the view */
1097                         ereport(ERROR,
1098                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1099                                          errmsg("cannot lock rows in view \"%s\"",
1100                                                         RelationGetRelationName(rel))));
1101                         break;
1102                 case RELKIND_MATVIEW:
1103                         /* Should not get here */
1104                         ereport(ERROR,
1105                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1106                                          errmsg("cannot lock rows in materialized view \"%s\"",
1107                                                         RelationGetRelationName(rel))));
1108                         break;
1109                 case RELKIND_FOREIGN_TABLE:
1110                         /* Should not get here */
1111                         ereport(ERROR,
1112                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1113                                          errmsg("cannot lock rows in foreign table \"%s\"",
1114                                                         RelationGetRelationName(rel))));
1115                         break;
1116                 default:
1117                         ereport(ERROR,
1118                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1119                                          errmsg("cannot lock rows in relation \"%s\"",
1120                                                         RelationGetRelationName(rel))));
1121                         break;
1122         }
1123 }
1124
1125 /*
1126  * Initialize ResultRelInfo data for one result relation
1127  *
1128  * Caution: before Postgres 9.1, this function included the relkind checking
1129  * that's now in CheckValidResultRel, and it also did ExecOpenIndices if
1130  * appropriate.  Be sure callers cover those needs.
1131  */
1132 void
1133 InitResultRelInfo(ResultRelInfo *resultRelInfo,
1134                                   Relation resultRelationDesc,
1135                                   Index resultRelationIndex,
1136                                   int instrument_options)
1137 {
1138         MemSet(resultRelInfo, 0, sizeof(ResultRelInfo));
1139         resultRelInfo->type = T_ResultRelInfo;
1140         resultRelInfo->ri_RangeTableIndex = resultRelationIndex;
1141         resultRelInfo->ri_RelationDesc = resultRelationDesc;
1142         resultRelInfo->ri_NumIndices = 0;
1143         resultRelInfo->ri_IndexRelationDescs = NULL;
1144         resultRelInfo->ri_IndexRelationInfo = NULL;
1145         /* make a copy so as not to depend on relcache info not changing... */
1146         resultRelInfo->ri_TrigDesc = CopyTriggerDesc(resultRelationDesc->trigdesc);
1147         if (resultRelInfo->ri_TrigDesc)
1148         {
1149                 int                     n = resultRelInfo->ri_TrigDesc->numtriggers;
1150
1151                 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1152                         palloc0(n * sizeof(FmgrInfo));
1153                 resultRelInfo->ri_TrigWhenExprs = (List **)
1154                         palloc0(n * sizeof(List *));
1155                 if (instrument_options)
1156                         resultRelInfo->ri_TrigInstrument = InstrAlloc(n, instrument_options);
1157         }
1158         else
1159         {
1160                 resultRelInfo->ri_TrigFunctions = NULL;
1161                 resultRelInfo->ri_TrigWhenExprs = NULL;
1162                 resultRelInfo->ri_TrigInstrument = NULL;
1163         }
1164         if (resultRelationDesc->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1165                 resultRelInfo->ri_FdwRoutine = GetFdwRoutineForRelation(resultRelationDesc, true);
1166         else
1167                 resultRelInfo->ri_FdwRoutine = NULL;
1168         resultRelInfo->ri_FdwState = NULL;
1169         resultRelInfo->ri_ConstraintExprs = NULL;
1170         resultRelInfo->ri_junkFilter = NULL;
1171         resultRelInfo->ri_projectReturning = NULL;
1172 }
1173
1174 /*
1175  *              ExecGetTriggerResultRel
1176  *
1177  * Get a ResultRelInfo for a trigger target relation.  Most of the time,
1178  * triggers are fired on one of the result relations of the query, and so
1179  * we can just return a member of the es_result_relations array.  (Note: in
1180  * self-join situations there might be multiple members with the same OID;
1181  * if so it doesn't matter which one we pick.)  However, it is sometimes
1182  * necessary to fire triggers on other relations; this happens mainly when an
1183  * RI update trigger queues additional triggers on other relations, which will
1184  * be processed in the context of the outer query.      For efficiency's sake,
1185  * we want to have a ResultRelInfo for those triggers too; that can avoid
1186  * repeated re-opening of the relation.  (It also provides a way for EXPLAIN
1187  * ANALYZE to report the runtimes of such triggers.)  So we make additional
1188  * ResultRelInfo's as needed, and save them in es_trig_target_relations.
1189  */
1190 ResultRelInfo *
1191 ExecGetTriggerResultRel(EState *estate, Oid relid)
1192 {
1193         ResultRelInfo *rInfo;
1194         int                     nr;
1195         ListCell   *l;
1196         Relation        rel;
1197         MemoryContext oldcontext;
1198
1199         /* First, search through the query result relations */
1200         rInfo = estate->es_result_relations;
1201         nr = estate->es_num_result_relations;
1202         while (nr > 0)
1203         {
1204                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1205                         return rInfo;
1206                 rInfo++;
1207                 nr--;
1208         }
1209         /* Nope, but maybe we already made an extra ResultRelInfo for it */
1210         foreach(l, estate->es_trig_target_relations)
1211         {
1212                 rInfo = (ResultRelInfo *) lfirst(l);
1213                 if (RelationGetRelid(rInfo->ri_RelationDesc) == relid)
1214                         return rInfo;
1215         }
1216         /* Nope, so we need a new one */
1217
1218         /*
1219          * Open the target relation's relcache entry.  We assume that an
1220          * appropriate lock is still held by the backend from whenever the trigger
1221          * event got queued, so we need take no new lock here.  Also, we need not
1222          * recheck the relkind, so no need for CheckValidResultRel.
1223          */
1224         rel = heap_open(relid, NoLock);
1225
1226         /*
1227          * Make the new entry in the right context.
1228          */
1229         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1230         rInfo = makeNode(ResultRelInfo);
1231         InitResultRelInfo(rInfo,
1232                                           rel,
1233                                           0,            /* dummy rangetable index */
1234                                           estate->es_instrument);
1235         estate->es_trig_target_relations =
1236                 lappend(estate->es_trig_target_relations, rInfo);
1237         MemoryContextSwitchTo(oldcontext);
1238
1239         /*
1240          * Currently, we don't need any index information in ResultRelInfos used
1241          * only for triggers, so no need to call ExecOpenIndices.
1242          */
1243
1244         return rInfo;
1245 }
1246
1247 /*
1248  *              ExecContextForcesOids
1249  *
1250  * This is pretty grotty: when doing INSERT, UPDATE, or CREATE TABLE AS,
1251  * we need to ensure that result tuples have space for an OID iff they are
1252  * going to be stored into a relation that has OIDs.  In other contexts
1253  * we are free to choose whether to leave space for OIDs in result tuples
1254  * (we generally don't want to, but we do if a physical-tlist optimization
1255  * is possible).  This routine checks the plan context and returns TRUE if the
1256  * choice is forced, FALSE if the choice is not forced.  In the TRUE case,
1257  * *hasoids is set to the required value.
1258  *
1259  * One reason this is ugly is that all plan nodes in the plan tree will emit
1260  * tuples with space for an OID, though we really only need the topmost node
1261  * to do so.  However, node types like Sort don't project new tuples but just
1262  * return their inputs, and in those cases the requirement propagates down
1263  * to the input node.  Eventually we might make this code smart enough to
1264  * recognize how far down the requirement really goes, but for now we just
1265  * make all plan nodes do the same thing if the top level forces the choice.
1266  *
1267  * We assume that if we are generating tuples for INSERT or UPDATE,
1268  * estate->es_result_relation_info is already set up to describe the target
1269  * relation.  Note that in an UPDATE that spans an inheritance tree, some of
1270  * the target relations may have OIDs and some not.  We have to make the
1271  * decisions on a per-relation basis as we initialize each of the subplans of
1272  * the ModifyTable node, so ModifyTable has to set es_result_relation_info
1273  * while initializing each subplan.
1274  *
1275  * CREATE TABLE AS is even uglier, because we don't have the target relation's
1276  * descriptor available when this code runs; we have to look aside at the
1277  * flags passed to ExecutorStart().
1278  */
1279 bool
1280 ExecContextForcesOids(PlanState *planstate, bool *hasoids)
1281 {
1282         ResultRelInfo *ri = planstate->state->es_result_relation_info;
1283
1284         if (ri != NULL)
1285         {
1286                 Relation        rel = ri->ri_RelationDesc;
1287
1288                 if (rel != NULL)
1289                 {
1290                         *hasoids = rel->rd_rel->relhasoids;
1291                         return true;
1292                 }
1293         }
1294
1295         if (planstate->state->es_top_eflags & EXEC_FLAG_WITH_OIDS)
1296         {
1297                 *hasoids = true;
1298                 return true;
1299         }
1300         if (planstate->state->es_top_eflags & EXEC_FLAG_WITHOUT_OIDS)
1301         {
1302                 *hasoids = false;
1303                 return true;
1304         }
1305
1306         return false;
1307 }
1308
1309 /* ----------------------------------------------------------------
1310  *              ExecPostprocessPlan
1311  *
1312  *              Give plan nodes a final chance to execute before shutdown
1313  * ----------------------------------------------------------------
1314  */
1315 static void
1316 ExecPostprocessPlan(EState *estate)
1317 {
1318         ListCell   *lc;
1319
1320         /*
1321          * Make sure nodes run forward.
1322          */
1323         estate->es_direction = ForwardScanDirection;
1324
1325         /*
1326          * Run any secondary ModifyTable nodes to completion, in case the main
1327          * query did not fetch all rows from them.      (We do this to ensure that
1328          * such nodes have predictable results.)
1329          */
1330         foreach(lc, estate->es_auxmodifytables)
1331         {
1332                 PlanState  *ps = (PlanState *) lfirst(lc);
1333
1334                 for (;;)
1335                 {
1336                         TupleTableSlot *slot;
1337
1338                         /* Reset the per-output-tuple exprcontext each time */
1339                         ResetPerTupleExprContext(estate);
1340
1341                         slot = ExecProcNode(ps);
1342
1343                         if (TupIsNull(slot))
1344                                 break;
1345                 }
1346         }
1347 }
1348
1349 /* ----------------------------------------------------------------
1350  *              ExecEndPlan
1351  *
1352  *              Cleans up the query plan -- closes files and frees up storage
1353  *
1354  * NOTE: we are no longer very worried about freeing storage per se
1355  * in this code; FreeExecutorState should be guaranteed to release all
1356  * memory that needs to be released.  What we are worried about doing
1357  * is closing relations and dropping buffer pins.  Thus, for example,
1358  * tuple tables must be cleared or dropped to ensure pins are released.
1359  * ----------------------------------------------------------------
1360  */
1361 static void
1362 ExecEndPlan(PlanState *planstate, EState *estate)
1363 {
1364         ResultRelInfo *resultRelInfo;
1365         int                     i;
1366         ListCell   *l;
1367
1368         /*
1369          * shut down the node-type-specific query processing
1370          */
1371         ExecEndNode(planstate);
1372
1373         /*
1374          * for subplans too
1375          */
1376         foreach(l, estate->es_subplanstates)
1377         {
1378                 PlanState  *subplanstate = (PlanState *) lfirst(l);
1379
1380                 ExecEndNode(subplanstate);
1381         }
1382
1383         /*
1384          * destroy the executor's tuple table.  Actually we only care about
1385          * releasing buffer pins and tupdesc refcounts; there's no need to pfree
1386          * the TupleTableSlots, since the containing memory context is about to go
1387          * away anyway.
1388          */
1389         ExecResetTupleTable(estate->es_tupleTable, false);
1390
1391         /*
1392          * close the result relation(s) if any, but hold locks until xact commit.
1393          */
1394         resultRelInfo = estate->es_result_relations;
1395         for (i = estate->es_num_result_relations; i > 0; i--)
1396         {
1397                 /* Close indices and then the relation itself */
1398                 ExecCloseIndices(resultRelInfo);
1399                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1400                 resultRelInfo++;
1401         }
1402
1403         /*
1404          * likewise close any trigger target relations
1405          */
1406         foreach(l, estate->es_trig_target_relations)
1407         {
1408                 resultRelInfo = (ResultRelInfo *) lfirst(l);
1409                 /* Close indices and then the relation itself */
1410                 ExecCloseIndices(resultRelInfo);
1411                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
1412         }
1413
1414         /*
1415          * close any relations selected FOR [KEY] UPDATE/SHARE, again keeping
1416          * locks
1417          */
1418         foreach(l, estate->es_rowMarks)
1419         {
1420                 ExecRowMark *erm = (ExecRowMark *) lfirst(l);
1421
1422                 if (erm->relation)
1423                         heap_close(erm->relation, NoLock);
1424         }
1425 }
1426
1427 /* ----------------------------------------------------------------
1428  *              ExecutePlan
1429  *
1430  *              Processes the query plan until we have retrieved 'numberTuples' tuples,
1431  *              moving in the specified direction.
1432  *
1433  *              Runs to completion if numberTuples is 0
1434  *
1435  * Note: the ctid attribute is a 'junk' attribute that is removed before the
1436  * user can see it
1437  * ----------------------------------------------------------------
1438  */
1439 static void
1440 ExecutePlan(EState *estate,
1441                         PlanState *planstate,
1442                         CmdType operation,
1443                         bool sendTuples,
1444                         long numberTuples,
1445                         ScanDirection direction,
1446                         DestReceiver *dest)
1447 {
1448         TupleTableSlot *slot;
1449         long            current_tuple_count;
1450
1451         /*
1452          * initialize local variables
1453          */
1454         current_tuple_count = 0;
1455
1456         /*
1457          * Set the direction.
1458          */
1459         estate->es_direction = direction;
1460
1461         /*
1462          * Loop until we've processed the proper number of tuples from the plan.
1463          */
1464         for (;;)
1465         {
1466                 /* Reset the per-output-tuple exprcontext */
1467                 ResetPerTupleExprContext(estate);
1468
1469                 /*
1470                  * Execute the plan and obtain a tuple
1471                  */
1472                 slot = ExecProcNode(planstate);
1473
1474                 /*
1475                  * if the tuple is null, then we assume there is nothing more to
1476                  * process so we just end the loop...
1477                  */
1478                 if (TupIsNull(slot))
1479                         break;
1480
1481                 /*
1482                  * If we have a junk filter, then project a new tuple with the junk
1483                  * removed.
1484                  *
1485                  * Store this new "clean" tuple in the junkfilter's resultSlot.
1486                  * (Formerly, we stored it back over the "dirty" tuple, which is WRONG
1487                  * because that tuple slot has the wrong descriptor.)
1488                  */
1489                 if (estate->es_junkFilter != NULL)
1490                         slot = ExecFilterJunk(estate->es_junkFilter, slot);
1491
1492                 /*
1493                  * If we are supposed to send the tuple somewhere, do so. (In
1494                  * practice, this is probably always the case at this point.)
1495                  */
1496                 if (sendTuples)
1497                         (*dest->receiveSlot) (slot, dest);
1498
1499                 /*
1500                  * Count tuples processed, if this is a SELECT.  (For other operation
1501                  * types, the ModifyTable plan node must count the appropriate
1502                  * events.)
1503                  */
1504                 if (operation == CMD_SELECT)
1505                         (estate->es_processed)++;
1506
1507                 /*
1508                  * check our tuple count.. if we've processed the proper number then
1509                  * quit, else loop again and process more tuples.  Zero numberTuples
1510                  * means no limit.
1511                  */
1512                 current_tuple_count++;
1513                 if (numberTuples && numberTuples == current_tuple_count)
1514                         break;
1515         }
1516 }
1517
1518
1519 /*
1520  * ExecRelCheck --- check that tuple meets constraints for result relation
1521  *
1522  * Returns NULL if OK, else name of failed check constraint
1523  */
1524 static const char *
1525 ExecRelCheck(ResultRelInfo *resultRelInfo,
1526                          TupleTableSlot *slot, EState *estate)
1527 {
1528         Relation        rel = resultRelInfo->ri_RelationDesc;
1529         int                     ncheck = rel->rd_att->constr->num_check;
1530         ConstrCheck *check = rel->rd_att->constr->check;
1531         ExprContext *econtext;
1532         MemoryContext oldContext;
1533         List       *qual;
1534         int                     i;
1535
1536         /*
1537          * If first time through for this result relation, build expression
1538          * nodetrees for rel's constraint expressions.  Keep them in the per-query
1539          * memory context so they'll survive throughout the query.
1540          */
1541         if (resultRelInfo->ri_ConstraintExprs == NULL)
1542         {
1543                 oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
1544                 resultRelInfo->ri_ConstraintExprs =
1545                         (List **) palloc(ncheck * sizeof(List *));
1546                 for (i = 0; i < ncheck; i++)
1547                 {
1548                         /* ExecQual wants implicit-AND form */
1549                         qual = make_ands_implicit(stringToNode(check[i].ccbin));
1550                         resultRelInfo->ri_ConstraintExprs[i] = (List *)
1551                                 ExecPrepareExpr((Expr *) qual, estate);
1552                 }
1553                 MemoryContextSwitchTo(oldContext);
1554         }
1555
1556         /*
1557          * We will use the EState's per-tuple context for evaluating constraint
1558          * expressions (creating it if it's not already there).
1559          */
1560         econtext = GetPerTupleExprContext(estate);
1561
1562         /* Arrange for econtext's scan tuple to be the tuple under test */
1563         econtext->ecxt_scantuple = slot;
1564
1565         /* And evaluate the constraints */
1566         for (i = 0; i < ncheck; i++)
1567         {
1568                 qual = resultRelInfo->ri_ConstraintExprs[i];
1569
1570                 /*
1571                  * NOTE: SQL specifies that a NULL result from a constraint expression
1572                  * is not to be treated as a failure.  Therefore, tell ExecQual to
1573                  * return TRUE for NULL.
1574                  */
1575                 if (!ExecQual(qual, econtext, true))
1576                         return check[i].ccname;
1577         }
1578
1579         /* NULL result means no error */
1580         return NULL;
1581 }
1582
1583 void
1584 ExecConstraints(ResultRelInfo *resultRelInfo,
1585                                 TupleTableSlot *slot, EState *estate)
1586 {
1587         Relation        rel = resultRelInfo->ri_RelationDesc;
1588         TupleConstr *constr = rel->rd_att->constr;
1589
1590         Assert(constr);
1591
1592         if (constr->has_not_null)
1593         {
1594                 int                     natts = rel->rd_att->natts;
1595                 int                     attrChk;
1596
1597                 for (attrChk = 1; attrChk <= natts; attrChk++)
1598                 {
1599                         if (rel->rd_att->attrs[attrChk - 1]->attnotnull &&
1600                                 slot_attisnull(slot, attrChk))
1601                                 ereport(ERROR,
1602                                                 (errcode(ERRCODE_NOT_NULL_VIOLATION),
1603                                                  errmsg("null value in column \"%s\" violates not-null constraint",
1604                                                   NameStr(rel->rd_att->attrs[attrChk - 1]->attname)),
1605                                                  errdetail("Failing row contains %s.",
1606                                                                    ExecBuildSlotValueDescription(slot, 64)),
1607                                                  errtablecol(rel, attrChk)));
1608                 }
1609         }
1610
1611         if (constr->num_check > 0)
1612         {
1613                 const char *failed;
1614
1615                 if ((failed = ExecRelCheck(resultRelInfo, slot, estate)) != NULL)
1616                         ereport(ERROR,
1617                                         (errcode(ERRCODE_CHECK_VIOLATION),
1618                                          errmsg("new row for relation \"%s\" violates check constraint \"%s\"",
1619                                                         RelationGetRelationName(rel), failed),
1620                                          errdetail("Failing row contains %s.",
1621                                                            ExecBuildSlotValueDescription(slot, 64)),
1622                                          errtableconstraint(rel, failed)));
1623         }
1624 }
1625
1626 /*
1627  * ExecWithCheckOptions -- check that tuple satisfies any WITH CHECK OPTIONs
1628  */
1629 void
1630 ExecWithCheckOptions(ResultRelInfo *resultRelInfo,
1631                                          TupleTableSlot *slot, EState *estate)
1632 {
1633         ExprContext *econtext;
1634         ListCell   *l1, *l2;
1635
1636         /*
1637          * We will use the EState's per-tuple context for evaluating constraint
1638          * expressions (creating it if it's not already there).
1639          */
1640         econtext = GetPerTupleExprContext(estate);
1641
1642         /* Arrange for econtext's scan tuple to be the tuple under test */
1643         econtext->ecxt_scantuple = slot;
1644
1645         /* Check each of the constraints */
1646         forboth(l1, resultRelInfo->ri_WithCheckOptions,
1647                         l2, resultRelInfo->ri_WithCheckOptionExprs)
1648         {
1649                 WithCheckOption *wco = (WithCheckOption *) lfirst(l1);
1650                 ExprState          *wcoExpr = (ExprState *) lfirst(l2);
1651
1652                 /*
1653                  * WITH CHECK OPTION checks are intended to ensure that the new tuple
1654                  * is visible in the view.  If the view's qual evaluates to NULL, then
1655                  * the new tuple won't be included in the view.  Therefore we need to
1656                  * tell ExecQual to return FALSE for NULL (the opposite of what we do
1657                  * above for CHECK constraints).
1658                  */
1659                 if (!ExecQual((List *) wcoExpr, econtext, false))
1660                         ereport(ERROR,
1661                                         (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION),
1662                                          errmsg("new row violates WITH CHECK OPTION for view \"%s\"",
1663                                                         wco->viewname),
1664                                          errdetail("Failing row contains %s.",
1665                                                            ExecBuildSlotValueDescription(slot, 64))));
1666         }
1667 }
1668
1669 /*
1670  * ExecBuildSlotValueDescription -- construct a string representing a tuple
1671  *
1672  * This is intentionally very similar to BuildIndexValueDescription, but
1673  * unlike that function, we truncate long field values.  That seems necessary
1674  * here since heap field values could be very long, whereas index entries
1675  * typically aren't so wide.
1676  */
1677 static char *
1678 ExecBuildSlotValueDescription(TupleTableSlot *slot, int maxfieldlen)
1679 {
1680         StringInfoData buf;
1681         TupleDesc       tupdesc = slot->tts_tupleDescriptor;
1682         int                     i;
1683
1684         /* Make sure the tuple is fully deconstructed */
1685         slot_getallattrs(slot);
1686
1687         initStringInfo(&buf);
1688
1689         appendStringInfoChar(&buf, '(');
1690
1691         for (i = 0; i < tupdesc->natts; i++)
1692         {
1693                 char       *val;
1694                 int                     vallen;
1695
1696                 if (slot->tts_isnull[i])
1697                         val = "null";
1698                 else
1699                 {
1700                         Oid                     foutoid;
1701                         bool            typisvarlena;
1702
1703                         getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1704                                                           &foutoid, &typisvarlena);
1705                         val = OidOutputFunctionCall(foutoid, slot->tts_values[i]);
1706                 }
1707
1708                 if (i > 0)
1709                         appendStringInfoString(&buf, ", ");
1710
1711                 /* truncate if needed */
1712                 vallen = strlen(val);
1713                 if (vallen <= maxfieldlen)
1714                         appendStringInfoString(&buf, val);
1715                 else
1716                 {
1717                         vallen = pg_mbcliplen(val, vallen, maxfieldlen);
1718                         appendBinaryStringInfo(&buf, val, vallen);
1719                         appendStringInfoString(&buf, "...");
1720                 }
1721         }
1722
1723         appendStringInfoChar(&buf, ')');
1724
1725         return buf.data;
1726 }
1727
1728
1729 /*
1730  * ExecFindRowMark -- find the ExecRowMark struct for given rangetable index
1731  */
1732 ExecRowMark *
1733 ExecFindRowMark(EState *estate, Index rti)
1734 {
1735         ListCell   *lc;
1736
1737         foreach(lc, estate->es_rowMarks)
1738         {
1739                 ExecRowMark *erm = (ExecRowMark *) lfirst(lc);
1740
1741                 if (erm->rti == rti)
1742                         return erm;
1743         }
1744         elog(ERROR, "failed to find ExecRowMark for rangetable index %u", rti);
1745         return NULL;                            /* keep compiler quiet */
1746 }
1747
1748 /*
1749  * ExecBuildAuxRowMark -- create an ExecAuxRowMark struct
1750  *
1751  * Inputs are the underlying ExecRowMark struct and the targetlist of the
1752  * input plan node (not planstate node!).  We need the latter to find out
1753  * the column numbers of the resjunk columns.
1754  */
1755 ExecAuxRowMark *
1756 ExecBuildAuxRowMark(ExecRowMark *erm, List *targetlist)
1757 {
1758         ExecAuxRowMark *aerm = (ExecAuxRowMark *) palloc0(sizeof(ExecAuxRowMark));
1759         char            resname[32];
1760
1761         aerm->rowmark = erm;
1762
1763         /* Look up the resjunk columns associated with this rowmark */
1764         if (erm->relation)
1765         {
1766                 Assert(erm->markType != ROW_MARK_COPY);
1767
1768                 /* if child rel, need tableoid */
1769                 if (erm->rti != erm->prti)
1770                 {
1771                         snprintf(resname, sizeof(resname), "tableoid%u", erm->rowmarkId);
1772                         aerm->toidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1773                                                                                                                    resname);
1774                         if (!AttributeNumberIsValid(aerm->toidAttNo))
1775                                 elog(ERROR, "could not find junk %s column", resname);
1776                 }
1777
1778                 /* always need ctid for real relations */
1779                 snprintf(resname, sizeof(resname), "ctid%u", erm->rowmarkId);
1780                 aerm->ctidAttNo = ExecFindJunkAttributeInTlist(targetlist,
1781                                                                                                            resname);
1782                 if (!AttributeNumberIsValid(aerm->ctidAttNo))
1783                         elog(ERROR, "could not find junk %s column", resname);
1784         }
1785         else
1786         {
1787                 Assert(erm->markType == ROW_MARK_COPY);
1788
1789                 snprintf(resname, sizeof(resname), "wholerow%u", erm->rowmarkId);
1790                 aerm->wholeAttNo = ExecFindJunkAttributeInTlist(targetlist,
1791                                                                                                                 resname);
1792                 if (!AttributeNumberIsValid(aerm->wholeAttNo))
1793                         elog(ERROR, "could not find junk %s column", resname);
1794         }
1795
1796         return aerm;
1797 }
1798
1799
1800 /*
1801  * EvalPlanQual logic --- recheck modified tuple(s) to see if we want to
1802  * process the updated version under READ COMMITTED rules.
1803  *
1804  * See backend/executor/README for some info about how this works.
1805  */
1806
1807
1808 /*
1809  * Check a modified tuple to see if we want to process its updated version
1810  * under READ COMMITTED rules.
1811  *
1812  *      estate - outer executor state data
1813  *      epqstate - state for EvalPlanQual rechecking
1814  *      relation - table containing tuple
1815  *      rti - rangetable index of table containing tuple
1816  *      lockmode - requested tuple lock mode
1817  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1818  *      priorXmax - t_xmax from the outdated tuple
1819  *
1820  * *tid is also an output parameter: it's modified to hold the TID of the
1821  * latest version of the tuple (note this may be changed even on failure)
1822  *
1823  * Returns a slot containing the new candidate update/delete tuple, or
1824  * NULL if we determine we shouldn't process the row.
1825  *
1826  * Note: properly, lockmode should be declared as enum LockTupleMode,
1827  * but we use "int" to avoid having to include heapam.h in executor.h.
1828  */
1829 TupleTableSlot *
1830 EvalPlanQual(EState *estate, EPQState *epqstate,
1831                          Relation relation, Index rti, int lockmode,
1832                          ItemPointer tid, TransactionId priorXmax)
1833 {
1834         TupleTableSlot *slot;
1835         HeapTuple       copyTuple;
1836
1837         Assert(rti > 0);
1838
1839         /*
1840          * Get and lock the updated version of the row; if fail, return NULL.
1841          */
1842         copyTuple = EvalPlanQualFetch(estate, relation, lockmode,
1843                                                                   tid, priorXmax);
1844
1845         if (copyTuple == NULL)
1846                 return NULL;
1847
1848         /*
1849          * For UPDATE/DELETE we have to return tid of actual row we're executing
1850          * PQ for.
1851          */
1852         *tid = copyTuple->t_self;
1853
1854         /*
1855          * Need to run a recheck subquery.      Initialize or reinitialize EPQ state.
1856          */
1857         EvalPlanQualBegin(epqstate, estate);
1858
1859         /*
1860          * Free old test tuple, if any, and store new tuple where relation's scan
1861          * node will see it
1862          */
1863         EvalPlanQualSetTuple(epqstate, rti, copyTuple);
1864
1865         /*
1866          * Fetch any non-locked source rows
1867          */
1868         EvalPlanQualFetchRowMarks(epqstate);
1869
1870         /*
1871          * Run the EPQ query.  We assume it will return at most one tuple.
1872          */
1873         slot = EvalPlanQualNext(epqstate);
1874
1875         /*
1876          * If we got a tuple, force the slot to materialize the tuple so that it
1877          * is not dependent on any local state in the EPQ query (in particular,
1878          * it's highly likely that the slot contains references to any pass-by-ref
1879          * datums that may be present in copyTuple).  As with the next step, this
1880          * is to guard against early re-use of the EPQ query.
1881          */
1882         if (!TupIsNull(slot))
1883                 (void) ExecMaterializeSlot(slot);
1884
1885         /*
1886          * Clear out the test tuple.  This is needed in case the EPQ query is
1887          * re-used to test a tuple for a different relation.  (Not clear that can
1888          * really happen, but let's be safe.)
1889          */
1890         EvalPlanQualSetTuple(epqstate, rti, NULL);
1891
1892         return slot;
1893 }
1894
1895 /*
1896  * Fetch a copy of the newest version of an outdated tuple
1897  *
1898  *      estate - executor state data
1899  *      relation - table containing tuple
1900  *      lockmode - requested tuple lock mode
1901  *      *tid - t_ctid from the outdated tuple (ie, next updated version)
1902  *      priorXmax - t_xmax from the outdated tuple
1903  *
1904  * Returns a palloc'd copy of the newest tuple version, or NULL if we find
1905  * that there is no newest version (ie, the row was deleted not updated).
1906  * If successful, we have locked the newest tuple version, so caller does not
1907  * need to worry about it changing anymore.
1908  *
1909  * Note: properly, lockmode should be declared as enum LockTupleMode,
1910  * but we use "int" to avoid having to include heapam.h in executor.h.
1911  */
1912 HeapTuple
1913 EvalPlanQualFetch(EState *estate, Relation relation, int lockmode,
1914                                   ItemPointer tid, TransactionId priorXmax)
1915 {
1916         HeapTuple       copyTuple = NULL;
1917         HeapTupleData tuple;
1918         SnapshotData SnapshotDirty;
1919
1920         /*
1921          * fetch target tuple
1922          *
1923          * Loop here to deal with updated or busy tuples
1924          */
1925         InitDirtySnapshot(SnapshotDirty);
1926         tuple.t_self = *tid;
1927         for (;;)
1928         {
1929                 Buffer          buffer;
1930
1931                 if (heap_fetch(relation, &SnapshotDirty, &tuple, &buffer, true, NULL))
1932                 {
1933                         HTSU_Result test;
1934                         HeapUpdateFailureData hufd;
1935
1936                         /*
1937                          * If xmin isn't what we're expecting, the slot must have been
1938                          * recycled and reused for an unrelated tuple.  This implies that
1939                          * the latest version of the row was deleted, so we need do
1940                          * nothing.  (Should be safe to examine xmin without getting
1941                          * buffer's content lock, since xmin never changes in an existing
1942                          * tuple.)
1943                          */
1944                         if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
1945                                                                          priorXmax))
1946                         {
1947                                 ReleaseBuffer(buffer);
1948                                 return NULL;
1949                         }
1950
1951                         /* otherwise xmin should not be dirty... */
1952                         if (TransactionIdIsValid(SnapshotDirty.xmin))
1953                                 elog(ERROR, "t_xmin is uncommitted in tuple to be updated");
1954
1955                         /*
1956                          * If tuple is being updated by other transaction then we have to
1957                          * wait for its commit/abort.
1958                          */
1959                         if (TransactionIdIsValid(SnapshotDirty.xmax))
1960                         {
1961                                 ReleaseBuffer(buffer);
1962                                 XactLockTableWait(SnapshotDirty.xmax);
1963                                 continue;               /* loop back to repeat heap_fetch */
1964                         }
1965
1966                         /*
1967                          * If tuple was inserted by our own transaction, we have to check
1968                          * cmin against es_output_cid: cmin >= current CID means our
1969                          * command cannot see the tuple, so we should ignore it. Otherwise
1970                          * heap_lock_tuple() will throw an error, and so would any later
1971                          * attempt to update or delete the tuple.  (We need not check cmax
1972                          * because HeapTupleSatisfiesDirty will consider a tuple deleted
1973                          * by our transaction dead, regardless of cmax.) Wee just checked
1974                          * that priorXmax == xmin, so we can test that variable instead of
1975                          * doing HeapTupleHeaderGetXmin again.
1976                          */
1977                         if (TransactionIdIsCurrentTransactionId(priorXmax) &&
1978                                 HeapTupleHeaderGetCmin(tuple.t_data) >= estate->es_output_cid)
1979                         {
1980                                 ReleaseBuffer(buffer);
1981                                 return NULL;
1982                         }
1983
1984                         /*
1985                          * This is a live tuple, so now try to lock it.
1986                          */
1987                         test = heap_lock_tuple(relation, &tuple,
1988                                                                    estate->es_output_cid,
1989                                                                    lockmode, false /* wait */ ,
1990                                                                    false, &buffer, &hufd);
1991                         /* We now have two pins on the buffer, get rid of one */
1992                         ReleaseBuffer(buffer);
1993
1994                         switch (test)
1995                         {
1996                                 case HeapTupleSelfUpdated:
1997
1998                                         /*
1999                                          * The target tuple was already updated or deleted by the
2000                                          * current command, or by a later command in the current
2001                                          * transaction.  We *must* ignore the tuple in the former
2002                                          * case, so as to avoid the "Halloween problem" of
2003                                          * repeated update attempts.  In the latter case it might
2004                                          * be sensible to fetch the updated tuple instead, but
2005                                          * doing so would require changing heap_lock_tuple as well
2006                                          * as heap_update and heap_delete to not complain about
2007                                          * updating "invisible" tuples, which seems pretty scary.
2008                                          * So for now, treat the tuple as deleted and do not
2009                                          * process.
2010                                          */
2011                                         ReleaseBuffer(buffer);
2012                                         return NULL;
2013
2014                                 case HeapTupleMayBeUpdated:
2015                                         /* successfully locked */
2016                                         break;
2017
2018                                 case HeapTupleUpdated:
2019                                         ReleaseBuffer(buffer);
2020                                         if (IsolationUsesXactSnapshot())
2021                                                 ereport(ERROR,
2022                                                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2023                                                                  errmsg("could not serialize access due to concurrent update")));
2024                                         if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
2025                                         {
2026                                                 /* it was updated, so look at the updated version */
2027                                                 tuple.t_self = hufd.ctid;
2028                                                 /* updated row should have xmin matching this xmax */
2029                                                 priorXmax = hufd.xmax;
2030                                                 continue;
2031                                         }
2032                                         /* tuple was deleted, so give up */
2033                                         return NULL;
2034
2035                                 default:
2036                                         ReleaseBuffer(buffer);
2037                                         elog(ERROR, "unrecognized heap_lock_tuple status: %u",
2038                                                  test);
2039                                         return NULL;    /* keep compiler quiet */
2040                         }
2041
2042                         /*
2043                          * We got tuple - now copy it for use by recheck query.
2044                          */
2045                         copyTuple = heap_copytuple(&tuple);
2046                         ReleaseBuffer(buffer);
2047                         break;
2048                 }
2049
2050                 /*
2051                  * If the referenced slot was actually empty, the latest version of
2052                  * the row must have been deleted, so we need do nothing.
2053                  */
2054                 if (tuple.t_data == NULL)
2055                 {
2056                         ReleaseBuffer(buffer);
2057                         return NULL;
2058                 }
2059
2060                 /*
2061                  * As above, if xmin isn't what we're expecting, do nothing.
2062                  */
2063                 if (!TransactionIdEquals(HeapTupleHeaderGetXmin(tuple.t_data),
2064                                                                  priorXmax))
2065                 {
2066                         ReleaseBuffer(buffer);
2067                         return NULL;
2068                 }
2069
2070                 /*
2071                  * If we get here, the tuple was found but failed SnapshotDirty.
2072                  * Assuming the xmin is either a committed xact or our own xact (as it
2073                  * certainly should be if we're trying to modify the tuple), this must
2074                  * mean that the row was updated or deleted by either a committed xact
2075                  * or our own xact.  If it was deleted, we can ignore it; if it was
2076                  * updated then chain up to the next version and repeat the whole
2077                  * process.
2078                  *
2079                  * As above, it should be safe to examine xmax and t_ctid without the
2080                  * buffer content lock, because they can't be changing.
2081                  */
2082                 if (ItemPointerEquals(&tuple.t_self, &tuple.t_data->t_ctid))
2083                 {
2084                         /* deleted, so forget about it */
2085                         ReleaseBuffer(buffer);
2086                         return NULL;
2087                 }
2088
2089                 /* updated, so look at the updated row */
2090                 tuple.t_self = tuple.t_data->t_ctid;
2091                 /* updated row should have xmin matching this xmax */
2092                 priorXmax = HeapTupleHeaderGetUpdateXid(tuple.t_data);
2093                 ReleaseBuffer(buffer);
2094                 /* loop back to fetch next in chain */
2095         }
2096
2097         /*
2098          * Return the copied tuple
2099          */
2100         return copyTuple;
2101 }
2102
2103 /*
2104  * EvalPlanQualInit -- initialize during creation of a plan state node
2105  * that might need to invoke EPQ processing.
2106  *
2107  * Note: subplan/auxrowmarks can be NULL/NIL if they will be set later
2108  * with EvalPlanQualSetPlan.
2109  */
2110 void
2111 EvalPlanQualInit(EPQState *epqstate, EState *estate,
2112                                  Plan *subplan, List *auxrowmarks, int epqParam)
2113 {
2114         /* Mark the EPQ state inactive */
2115         epqstate->estate = NULL;
2116         epqstate->planstate = NULL;
2117         epqstate->origslot = NULL;
2118         /* ... and remember data that EvalPlanQualBegin will need */
2119         epqstate->plan = subplan;
2120         epqstate->arowMarks = auxrowmarks;
2121         epqstate->epqParam = epqParam;
2122 }
2123
2124 /*
2125  * EvalPlanQualSetPlan -- set or change subplan of an EPQState.
2126  *
2127  * We need this so that ModifyTuple can deal with multiple subplans.
2128  */
2129 void
2130 EvalPlanQualSetPlan(EPQState *epqstate, Plan *subplan, List *auxrowmarks)
2131 {
2132         /* If we have a live EPQ query, shut it down */
2133         EvalPlanQualEnd(epqstate);
2134         /* And set/change the plan pointer */
2135         epqstate->plan = subplan;
2136         /* The rowmarks depend on the plan, too */
2137         epqstate->arowMarks = auxrowmarks;
2138 }
2139
2140 /*
2141  * Install one test tuple into EPQ state, or clear test tuple if tuple == NULL
2142  *
2143  * NB: passed tuple must be palloc'd; it may get freed later
2144  */
2145 void
2146 EvalPlanQualSetTuple(EPQState *epqstate, Index rti, HeapTuple tuple)
2147 {
2148         EState     *estate = epqstate->estate;
2149
2150         Assert(rti > 0);
2151
2152         /*
2153          * free old test tuple, if any, and store new tuple where relation's scan
2154          * node will see it
2155          */
2156         if (estate->es_epqTuple[rti - 1] != NULL)
2157                 heap_freetuple(estate->es_epqTuple[rti - 1]);
2158         estate->es_epqTuple[rti - 1] = tuple;
2159         estate->es_epqTupleSet[rti - 1] = true;
2160 }
2161
2162 /*
2163  * Fetch back the current test tuple (if any) for the specified RTI
2164  */
2165 HeapTuple
2166 EvalPlanQualGetTuple(EPQState *epqstate, Index rti)
2167 {
2168         EState     *estate = epqstate->estate;
2169
2170         Assert(rti > 0);
2171
2172         return estate->es_epqTuple[rti - 1];
2173 }
2174
2175 /*
2176  * Fetch the current row values for any non-locked relations that need
2177  * to be scanned by an EvalPlanQual operation.  origslot must have been set
2178  * to contain the current result row (top-level row) that we need to recheck.
2179  */
2180 void
2181 EvalPlanQualFetchRowMarks(EPQState *epqstate)
2182 {
2183         ListCell   *l;
2184
2185         Assert(epqstate->origslot != NULL);
2186
2187         foreach(l, epqstate->arowMarks)
2188         {
2189                 ExecAuxRowMark *aerm = (ExecAuxRowMark *) lfirst(l);
2190                 ExecRowMark *erm = aerm->rowmark;
2191                 Datum           datum;
2192                 bool            isNull;
2193                 HeapTupleData tuple;
2194
2195                 if (RowMarkRequiresRowShareLock(erm->markType))
2196                         elog(ERROR, "EvalPlanQual doesn't support locking rowmarks");
2197
2198                 /* clear any leftover test tuple for this rel */
2199                 EvalPlanQualSetTuple(epqstate, erm->rti, NULL);
2200
2201                 if (erm->relation)
2202                 {
2203                         Buffer          buffer;
2204
2205                         Assert(erm->markType == ROW_MARK_REFERENCE);
2206
2207                         /* if child rel, must check whether it produced this row */
2208                         if (erm->rti != erm->prti)
2209                         {
2210                                 Oid                     tableoid;
2211
2212                                 datum = ExecGetJunkAttribute(epqstate->origslot,
2213                                                                                          aerm->toidAttNo,
2214                                                                                          &isNull);
2215                                 /* non-locked rels could be on the inside of outer joins */
2216                                 if (isNull)
2217                                         continue;
2218                                 tableoid = DatumGetObjectId(datum);
2219
2220                                 if (tableoid != RelationGetRelid(erm->relation))
2221                                 {
2222                                         /* this child is inactive right now */
2223                                         continue;
2224                                 }
2225                         }
2226
2227                         /* fetch the tuple's ctid */
2228                         datum = ExecGetJunkAttribute(epqstate->origslot,
2229                                                                                  aerm->ctidAttNo,
2230                                                                                  &isNull);
2231                         /* non-locked rels could be on the inside of outer joins */
2232                         if (isNull)
2233                                 continue;
2234                         tuple.t_self = *((ItemPointer) DatumGetPointer(datum));
2235
2236                         /* okay, fetch the tuple */
2237                         if (!heap_fetch(erm->relation, SnapshotAny, &tuple, &buffer,
2238                                                         false, NULL))
2239                                 elog(ERROR, "failed to fetch tuple for EvalPlanQual recheck");
2240
2241                         /* successful, copy and store tuple */
2242                         EvalPlanQualSetTuple(epqstate, erm->rti,
2243                                                                  heap_copytuple(&tuple));
2244                         ReleaseBuffer(buffer);
2245                 }
2246                 else
2247                 {
2248                         HeapTupleHeader td;
2249
2250                         Assert(erm->markType == ROW_MARK_COPY);
2251
2252                         /* fetch the whole-row Var for the relation */
2253                         datum = ExecGetJunkAttribute(epqstate->origslot,
2254                                                                                  aerm->wholeAttNo,
2255                                                                                  &isNull);
2256                         /* non-locked rels could be on the inside of outer joins */
2257                         if (isNull)
2258                                 continue;
2259                         td = DatumGetHeapTupleHeader(datum);
2260
2261                         /* build a temporary HeapTuple control structure */
2262                         tuple.t_len = HeapTupleHeaderGetDatumLength(td);
2263                         ItemPointerSetInvalid(&(tuple.t_self));
2264                         tuple.t_tableOid = InvalidOid;
2265                         tuple.t_data = td;
2266
2267                         /* copy and store tuple */
2268                         EvalPlanQualSetTuple(epqstate, erm->rti,
2269                                                                  heap_copytuple(&tuple));
2270                 }
2271         }
2272 }
2273
2274 /*
2275  * Fetch the next row (if any) from EvalPlanQual testing
2276  *
2277  * (In practice, there should never be more than one row...)
2278  */
2279 TupleTableSlot *
2280 EvalPlanQualNext(EPQState *epqstate)
2281 {
2282         MemoryContext oldcontext;
2283         TupleTableSlot *slot;
2284
2285         oldcontext = MemoryContextSwitchTo(epqstate->estate->es_query_cxt);
2286         slot = ExecProcNode(epqstate->planstate);
2287         MemoryContextSwitchTo(oldcontext);
2288
2289         return slot;
2290 }
2291
2292 /*
2293  * Initialize or reset an EvalPlanQual state tree
2294  */
2295 void
2296 EvalPlanQualBegin(EPQState *epqstate, EState *parentestate)
2297 {
2298         EState     *estate = epqstate->estate;
2299
2300         if (estate == NULL)
2301         {
2302                 /* First time through, so create a child EState */
2303                 EvalPlanQualStart(epqstate, parentestate, epqstate->plan);
2304         }
2305         else
2306         {
2307                 /*
2308                  * We already have a suitable child EPQ tree, so just reset it.
2309                  */
2310                 int                     rtsize = list_length(parentestate->es_range_table);
2311                 PlanState  *planstate = epqstate->planstate;
2312
2313                 MemSet(estate->es_epqScanDone, 0, rtsize * sizeof(bool));
2314
2315                 /* Recopy current values of parent parameters */
2316                 if (parentestate->es_plannedstmt->nParamExec > 0)
2317                 {
2318                         int                     i = parentestate->es_plannedstmt->nParamExec;
2319
2320                         while (--i >= 0)
2321                         {
2322                                 /* copy value if any, but not execPlan link */
2323                                 estate->es_param_exec_vals[i].value =
2324                                         parentestate->es_param_exec_vals[i].value;
2325                                 estate->es_param_exec_vals[i].isnull =
2326                                         parentestate->es_param_exec_vals[i].isnull;
2327                         }
2328                 }
2329
2330                 /*
2331                  * Mark child plan tree as needing rescan at all scan nodes.  The
2332                  * first ExecProcNode will take care of actually doing the rescan.
2333                  */
2334                 planstate->chgParam = bms_add_member(planstate->chgParam,
2335                                                                                          epqstate->epqParam);
2336         }
2337 }
2338
2339 /*
2340  * Start execution of an EvalPlanQual plan tree.
2341  *
2342  * This is a cut-down version of ExecutorStart(): we copy some state from
2343  * the top-level estate rather than initializing it fresh.
2344  */
2345 static void
2346 EvalPlanQualStart(EPQState *epqstate, EState *parentestate, Plan *planTree)
2347 {
2348         EState     *estate;
2349         int                     rtsize;
2350         MemoryContext oldcontext;
2351         ListCell   *l;
2352
2353         rtsize = list_length(parentestate->es_range_table);
2354
2355         epqstate->estate = estate = CreateExecutorState();
2356
2357         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2358
2359         /*
2360          * Child EPQ EStates share the parent's copy of unchanging state such as
2361          * the snapshot, rangetable, result-rel info, and external Param info.
2362          * They need their own copies of local state, including a tuple table,
2363          * es_param_exec_vals, etc.
2364          */
2365         estate->es_direction = ForwardScanDirection;
2366         estate->es_snapshot = parentestate->es_snapshot;
2367         estate->es_crosscheck_snapshot = parentestate->es_crosscheck_snapshot;
2368         estate->es_range_table = parentestate->es_range_table;
2369         estate->es_plannedstmt = parentestate->es_plannedstmt;
2370         estate->es_junkFilter = parentestate->es_junkFilter;
2371         estate->es_output_cid = parentestate->es_output_cid;
2372         estate->es_result_relations = parentestate->es_result_relations;
2373         estate->es_num_result_relations = parentestate->es_num_result_relations;
2374         estate->es_result_relation_info = parentestate->es_result_relation_info;
2375         /* es_trig_target_relations must NOT be copied */
2376         estate->es_rowMarks = parentestate->es_rowMarks;
2377         estate->es_top_eflags = parentestate->es_top_eflags;
2378         estate->es_instrument = parentestate->es_instrument;
2379         /* es_auxmodifytables must NOT be copied */
2380
2381         /*
2382          * The external param list is simply shared from parent.  The internal
2383          * param workspace has to be local state, but we copy the initial values
2384          * from the parent, so as to have access to any param values that were
2385          * already set from other parts of the parent's plan tree.
2386          */
2387         estate->es_param_list_info = parentestate->es_param_list_info;
2388         if (parentestate->es_plannedstmt->nParamExec > 0)
2389         {
2390                 int                     i = parentestate->es_plannedstmt->nParamExec;
2391
2392                 estate->es_param_exec_vals = (ParamExecData *)
2393                         palloc0(i * sizeof(ParamExecData));
2394                 while (--i >= 0)
2395                 {
2396                         /* copy value if any, but not execPlan link */
2397                         estate->es_param_exec_vals[i].value =
2398                                 parentestate->es_param_exec_vals[i].value;
2399                         estate->es_param_exec_vals[i].isnull =
2400                                 parentestate->es_param_exec_vals[i].isnull;
2401                 }
2402         }
2403
2404         /*
2405          * Each EState must have its own es_epqScanDone state, but if we have
2406          * nested EPQ checks they should share es_epqTuple arrays.      This allows
2407          * sub-rechecks to inherit the values being examined by an outer recheck.
2408          */
2409         estate->es_epqScanDone = (bool *) palloc0(rtsize * sizeof(bool));
2410         if (parentestate->es_epqTuple != NULL)
2411         {
2412                 estate->es_epqTuple = parentestate->es_epqTuple;
2413                 estate->es_epqTupleSet = parentestate->es_epqTupleSet;
2414         }
2415         else
2416         {
2417                 estate->es_epqTuple = (HeapTuple *)
2418                         palloc0(rtsize * sizeof(HeapTuple));
2419                 estate->es_epqTupleSet = (bool *)
2420                         palloc0(rtsize * sizeof(bool));
2421         }
2422
2423         /*
2424          * Each estate also has its own tuple table.
2425          */
2426         estate->es_tupleTable = NIL;
2427
2428         /*
2429          * Initialize private state information for each SubPlan.  We must do this
2430          * before running ExecInitNode on the main query tree, since
2431          * ExecInitSubPlan expects to be able to find these entries. Some of the
2432          * SubPlans might not be used in the part of the plan tree we intend to
2433          * run, but since it's not easy to tell which, we just initialize them
2434          * all.
2435          */
2436         Assert(estate->es_subplanstates == NIL);
2437         foreach(l, parentestate->es_plannedstmt->subplans)
2438         {
2439                 Plan       *subplan = (Plan *) lfirst(l);
2440                 PlanState  *subplanstate;
2441
2442                 subplanstate = ExecInitNode(subplan, estate, 0);
2443                 estate->es_subplanstates = lappend(estate->es_subplanstates,
2444                                                                                    subplanstate);
2445         }
2446
2447         /*
2448          * Initialize the private state information for all the nodes in the part
2449          * of the plan tree we need to run.  This opens files, allocates storage
2450          * and leaves us ready to start processing tuples.
2451          */
2452         epqstate->planstate = ExecInitNode(planTree, estate, 0);
2453
2454         MemoryContextSwitchTo(oldcontext);
2455 }
2456
2457 /*
2458  * EvalPlanQualEnd -- shut down at termination of parent plan state node,
2459  * or if we are done with the current EPQ child.
2460  *
2461  * This is a cut-down version of ExecutorEnd(); basically we want to do most
2462  * of the normal cleanup, but *not* close result relations (which we are
2463  * just sharing from the outer query).  We do, however, have to close any
2464  * trigger target relations that got opened, since those are not shared.
2465  * (There probably shouldn't be any of the latter, but just in case...)
2466  */
2467 void
2468 EvalPlanQualEnd(EPQState *epqstate)
2469 {
2470         EState     *estate = epqstate->estate;
2471         MemoryContext oldcontext;
2472         ListCell   *l;
2473
2474         if (estate == NULL)
2475                 return;                                 /* idle, so nothing to do */
2476
2477         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2478
2479         ExecEndNode(epqstate->planstate);
2480
2481         foreach(l, estate->es_subplanstates)
2482         {
2483                 PlanState  *subplanstate = (PlanState *) lfirst(l);
2484
2485                 ExecEndNode(subplanstate);
2486         }
2487
2488         /* throw away the per-estate tuple table */
2489         ExecResetTupleTable(estate->es_tupleTable, false);
2490
2491         /* close any trigger target relations attached to this EState */
2492         foreach(l, estate->es_trig_target_relations)
2493         {
2494                 ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
2495
2496                 /* Close indices and then the relation itself */
2497                 ExecCloseIndices(resultRelInfo);
2498                 heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2499         }
2500
2501         MemoryContextSwitchTo(oldcontext);
2502
2503         FreeExecutorState(estate);
2504
2505         /* Mark EPQState idle */
2506         epqstate->estate = NULL;
2507         epqstate->planstate = NULL;
2508         epqstate->origslot = NULL;
2509 }