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