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