LCOV - code coverage report
Current view: top level - src/backend/executor - execMain.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 773 836 92.5 %
Date: 2019-06-19 14:06:47 Functions: 40 40 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13