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