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