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