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

Generated by: LCOV version 1.14