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