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