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

Generated by: LCOV version 1.14