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