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