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

Generated by: LCOV version 1.13