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