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