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