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