Revert "Don't lock partitions pruned by initial pruning"

As pointed out by Tom Lane, the patch introduced fragile and invasive
design around plan invalidation handling when locking of prunable
partitions was deferred from plancache.c to the executor. In
particular, it violated assumptions about CachedPlan immutability and
altered executor APIs in ways that are difficult to justify given the
added complexity and overhead.

This also removes the firstResultRels field added to PlannedStmt in
commit 28317de72, which was intended to support deferred locking of
certain ModifyTable result relations.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/605328.1747710381@sss.pgh.pa.us
This commit is contained in:
Amit Langote 2025-05-22 14:17:24 +09:00
parent f3622b6476
commit 1722d5eb05
33 changed files with 90 additions and 673 deletions

View File

@ -81,7 +81,7 @@ static ExecutorRun_hook_type prev_ExecutorRun = NULL;
static ExecutorFinish_hook_type prev_ExecutorFinish = NULL; static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
static ExecutorEnd_hook_type prev_ExecutorEnd = NULL; static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
static bool explain_ExecutorStart(QueryDesc *queryDesc, int eflags); static void explain_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void explain_ExecutorRun(QueryDesc *queryDesc, static void explain_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction, ScanDirection direction,
uint64 count); uint64 count);
@ -261,11 +261,9 @@ _PG_init(void)
/* /*
* ExecutorStart hook: start up logging if needed * ExecutorStart hook: start up logging if needed
*/ */
static bool static void
explain_ExecutorStart(QueryDesc *queryDesc, int eflags) explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
{ {
bool plan_valid;
/* /*
* At the beginning of each top-level statement, decide whether we'll * At the beginning of each top-level statement, decide whether we'll
* sample this statement. If nested-statement explaining is enabled, * sample this statement. If nested-statement explaining is enabled,
@ -301,13 +299,9 @@ explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
} }
if (prev_ExecutorStart) if (prev_ExecutorStart)
plan_valid = prev_ExecutorStart(queryDesc, eflags); prev_ExecutorStart(queryDesc, eflags);
else else
plan_valid = standard_ExecutorStart(queryDesc, eflags); standard_ExecutorStart(queryDesc, eflags);
/* The plan may have become invalid during standard_ExecutorStart() */
if (!plan_valid)
return false;
if (auto_explain_enabled()) if (auto_explain_enabled())
{ {
@ -325,8 +319,6 @@ explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
MemoryContextSwitchTo(oldcxt); MemoryContextSwitchTo(oldcxt);
} }
} }
return true;
} }
/* /*

View File

@ -335,7 +335,7 @@ static PlannedStmt *pgss_planner(Query *parse,
const char *query_string, const char *query_string,
int cursorOptions, int cursorOptions,
ParamListInfo boundParams); ParamListInfo boundParams);
static bool pgss_ExecutorStart(QueryDesc *queryDesc, int eflags); static void pgss_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgss_ExecutorRun(QueryDesc *queryDesc, static void pgss_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction, ScanDirection direction,
uint64 count); uint64 count);
@ -989,19 +989,13 @@ pgss_planner(Query *parse,
/* /*
* ExecutorStart hook: start up tracking if needed * ExecutorStart hook: start up tracking if needed
*/ */
static bool static void
pgss_ExecutorStart(QueryDesc *queryDesc, int eflags) pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
{ {
bool plan_valid;
if (prev_ExecutorStart) if (prev_ExecutorStart)
plan_valid = prev_ExecutorStart(queryDesc, eflags); prev_ExecutorStart(queryDesc, eflags);
else else
plan_valid = standard_ExecutorStart(queryDesc, eflags); standard_ExecutorStart(queryDesc, eflags);
/* The plan may have become invalid during standard_ExecutorStart() */
if (!plan_valid)
return false;
/* /*
* If query has queryId zero, don't track it. This prevents double * If query has queryId zero, don't track it. This prevents double
@ -1024,8 +1018,6 @@ pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
MemoryContextSwitchTo(oldcxt); MemoryContextSwitchTo(oldcxt);
} }
} }
return true;
} }
/* /*

View File

@ -588,27 +588,6 @@ Improve the locking performance of queries that access many relations (Tomas Von
</para> </para>
</listitem> </listitem>
<!--
Author: Amit Langote <amitlan@postgresql.org>
2025-01-30 [bb3ec16e1] Move PartitionPruneInfo out of plan nodes into PlannedSt
Author: Amit Langote <amitlan@postgresql.org>
2025-01-31 [d47cbf474] Perform runtime initial pruning outside ExecInitNode()
Author: Amit Langote <amitlan@postgresql.org>
2025-02-07 [cbc127917] Track unpruned relids to avoid processing pruned relatio
Author: Amit Langote <amitlan@postgresql.org>
2025-02-20 [525392d57] Don't lock partitions pruned by initial pruning
-->
<listitem>
<para>
Avoid the locking of pruned partitions during execution (Amit Langote)
<ulink url="&commit_baseurl;bb3ec16e1">&sect;</ulink>
<ulink url="&commit_baseurl;d47cbf474">&sect;</ulink>
<ulink url="&commit_baseurl;cbc127917">&sect;</ulink>
<ulink url="&commit_baseurl;525392d57">&sect;</ulink>
</para>
</listitem>
<!-- <!--
Author: David Rowley <drowley@postgresql.org> Author: David Rowley <drowley@postgresql.org>
2024-08-20 [adf97c156] Speed up Hash Join by making ExprStates support hashing 2024-08-20 [adf97c156] Speed up Hash Join by making ExprStates support hashing

View File

@ -835,7 +835,7 @@ BeginCopyTo(ParseState *pstate,
((DR_copy *) dest)->cstate = cstate; ((DR_copy *) dest)->cstate = cstate;
/* Create a QueryDesc requesting no output */ /* Create a QueryDesc requesting no output */
cstate->queryDesc = CreateQueryDesc(plan, NULL, pstate->p_sourcetext, cstate->queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
GetActiveSnapshot(), GetActiveSnapshot(),
InvalidSnapshot, InvalidSnapshot,
dest, NULL, NULL, 0); dest, NULL, NULL, 0);
@ -845,8 +845,7 @@ BeginCopyTo(ParseState *pstate,
* *
* ExecutorStart computes a result tupdesc for us * ExecutorStart computes a result tupdesc for us
*/ */
if (!ExecutorStart(cstate->queryDesc, 0)) ExecutorStart(cstate->queryDesc, 0);
elog(ERROR, "ExecutorStart() failed unexpectedly");
tupDesc = cstate->queryDesc->tupDesc; tupDesc = cstate->queryDesc->tupDesc;
} }

View File

@ -334,13 +334,12 @@ ExecCreateTableAs(ParseState *pstate, CreateTableAsStmt *stmt,
UpdateActiveSnapshotCommandId(); UpdateActiveSnapshotCommandId();
/* Create a QueryDesc, redirecting output to our tuple receiver */ /* Create a QueryDesc, redirecting output to our tuple receiver */
queryDesc = CreateQueryDesc(plan, NULL, pstate->p_sourcetext, queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
GetActiveSnapshot(), InvalidSnapshot, GetActiveSnapshot(), InvalidSnapshot,
dest, params, queryEnv, 0); dest, params, queryEnv, 0);
/* call ExecutorStart to prepare the plan for execution */ /* call ExecutorStart to prepare the plan for execution */
if (!ExecutorStart(queryDesc, GetIntoRelEFlags(into))) ExecutorStart(queryDesc, GetIntoRelEFlags(into));
elog(ERROR, "ExecutorStart() failed unexpectedly");
/* run the plan to completion */ /* run the plan to completion */
ExecutorRun(queryDesc, ForwardScanDirection, 0); ExecutorRun(queryDesc, ForwardScanDirection, 0);

View File

@ -369,8 +369,7 @@ standard_ExplainOneQuery(Query *query, int cursorOptions,
} }
/* run it (if needed) and produce output */ /* run it (if needed) and produce output */
ExplainOnePlan(plan, NULL, NULL, -1, into, es, queryString, params, ExplainOnePlan(plan, into, es, queryString, params, queryEnv,
queryEnv,
&planduration, (es->buffers ? &bufusage : NULL), &planduration, (es->buffers ? &bufusage : NULL),
es->memory ? &mem_counters : NULL); es->memory ? &mem_counters : NULL);
} }
@ -492,9 +491,7 @@ ExplainOneUtility(Node *utilityStmt, IntoClause *into, ExplainState *es,
* to call it. * to call it.
*/ */
void void
ExplainOnePlan(PlannedStmt *plannedstmt, CachedPlan *cplan, ExplainOnePlan(PlannedStmt *plannedstmt, IntoClause *into, ExplainState *es,
CachedPlanSource *plansource, int query_index,
IntoClause *into, ExplainState *es,
const char *queryString, ParamListInfo params, const char *queryString, ParamListInfo params,
QueryEnvironment *queryEnv, const instr_time *planduration, QueryEnvironment *queryEnv, const instr_time *planduration,
const BufferUsage *bufusage, const BufferUsage *bufusage,
@ -550,7 +547,7 @@ ExplainOnePlan(PlannedStmt *plannedstmt, CachedPlan *cplan,
dest = None_Receiver; dest = None_Receiver;
/* Create a QueryDesc for the query */ /* Create a QueryDesc for the query */
queryDesc = CreateQueryDesc(plannedstmt, cplan, queryString, queryDesc = CreateQueryDesc(plannedstmt, queryString,
GetActiveSnapshot(), InvalidSnapshot, GetActiveSnapshot(), InvalidSnapshot,
dest, params, queryEnv, instrument_option); dest, params, queryEnv, instrument_option);
@ -564,17 +561,8 @@ ExplainOnePlan(PlannedStmt *plannedstmt, CachedPlan *cplan,
if (into) if (into)
eflags |= GetIntoRelEFlags(into); eflags |= GetIntoRelEFlags(into);
/* Prepare the plan for execution. */ /* call ExecutorStart to prepare the plan for execution */
if (queryDesc->cplan) ExecutorStart(queryDesc, eflags);
{
ExecutorStartCachedPlan(queryDesc, eflags, plansource, query_index);
Assert(queryDesc->planstate);
}
else
{
if (!ExecutorStart(queryDesc, eflags))
elog(ERROR, "ExecutorStart() failed unexpectedly");
}
/* Execute the plan for statistics if asked for */ /* Execute the plan for statistics if asked for */
if (es->analyze) if (es->analyze)

View File

@ -993,13 +993,11 @@ execute_sql_string(const char *sql, const char *filename)
QueryDesc *qdesc; QueryDesc *qdesc;
qdesc = CreateQueryDesc(stmt, qdesc = CreateQueryDesc(stmt,
NULL,
sql, sql,
GetActiveSnapshot(), NULL, GetActiveSnapshot(), NULL,
dest, NULL, NULL, 0); dest, NULL, NULL, 0);
if (!ExecutorStart(qdesc, 0)) ExecutorStart(qdesc, 0);
elog(ERROR, "ExecutorStart() failed unexpectedly");
ExecutorRun(qdesc, ForwardScanDirection, 0); ExecutorRun(qdesc, ForwardScanDirection, 0);
ExecutorFinish(qdesc); ExecutorFinish(qdesc);
ExecutorEnd(qdesc); ExecutorEnd(qdesc);

View File

@ -438,13 +438,12 @@ refresh_matview_datafill(DestReceiver *dest, Query *query,
UpdateActiveSnapshotCommandId(); UpdateActiveSnapshotCommandId();
/* Create a QueryDesc, redirecting output to our tuple receiver */ /* Create a QueryDesc, redirecting output to our tuple receiver */
queryDesc = CreateQueryDesc(plan, NULL, queryString, queryDesc = CreateQueryDesc(plan, queryString,
GetActiveSnapshot(), InvalidSnapshot, GetActiveSnapshot(), InvalidSnapshot,
dest, NULL, NULL, 0); dest, NULL, NULL, 0);
/* call ExecutorStart to prepare the plan for execution */ /* call ExecutorStart to prepare the plan for execution */
if (!ExecutorStart(queryDesc, 0)) ExecutorStart(queryDesc, 0);
elog(ERROR, "ExecutorStart() failed unexpectedly");
/* run the plan */ /* run the plan */
ExecutorRun(queryDesc, ForwardScanDirection, 0); ExecutorRun(queryDesc, ForwardScanDirection, 0);

View File

@ -117,7 +117,6 @@ PerformCursorOpen(ParseState *pstate, DeclareCursorStmt *cstmt, ParamListInfo pa
queryString, queryString,
CMDTAG_SELECT, /* cursor's query is always a SELECT */ CMDTAG_SELECT, /* cursor's query is always a SELECT */
list_make1(plan), list_make1(plan),
NULL,
NULL); NULL);
/*---------- /*----------

View File

@ -205,8 +205,7 @@ ExecuteQuery(ParseState *pstate,
query_string, query_string,
entry->plansource->commandTag, entry->plansource->commandTag,
plan_list, plan_list,
cplan, cplan);
entry->plansource);
/* /*
* For CREATE TABLE ... AS EXECUTE, we must verify that the prepared * For CREATE TABLE ... AS EXECUTE, we must verify that the prepared
@ -586,7 +585,6 @@ ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into, ExplainState *es,
MemoryContextCounters mem_counters; MemoryContextCounters mem_counters;
MemoryContext planner_ctx = NULL; MemoryContext planner_ctx = NULL;
MemoryContext saved_ctx = NULL; MemoryContext saved_ctx = NULL;
int query_index = 0;
if (es->memory) if (es->memory)
{ {
@ -659,8 +657,7 @@ ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into, ExplainState *es,
PlannedStmt *pstmt = lfirst_node(PlannedStmt, p); PlannedStmt *pstmt = lfirst_node(PlannedStmt, p);
if (pstmt->commandType != CMD_UTILITY) if (pstmt->commandType != CMD_UTILITY)
ExplainOnePlan(pstmt, cplan, entry->plansource, query_index, ExplainOnePlan(pstmt, into, es, query_string, paramLI, pstate->p_queryEnv,
into, es, query_string, paramLI, pstate->p_queryEnv,
&planduration, (es->buffers ? &bufusage : NULL), &planduration, (es->buffers ? &bufusage : NULL),
es->memory ? &mem_counters : NULL); es->memory ? &mem_counters : NULL);
else else
@ -671,8 +668,6 @@ ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into, ExplainState *es,
/* Separate plans with an appropriate separator */ /* Separate plans with an appropriate separator */
if (lnext(plan_list, p) != NULL) if (lnext(plan_list, p) != NULL)
ExplainSeparatePlans(es); ExplainSeparatePlans(es);
query_index++;
} }
if (estate) if (estate)

View File

@ -5057,21 +5057,6 @@ AfterTriggerBeginQuery(void)
} }
/* ----------
* AfterTriggerAbortQuery()
*
* Called by standard_ExecutorEnd() if the query execution was aborted due to
* the plan becoming invalid during initialization.
* ----------
*/
void
AfterTriggerAbortQuery(void)
{
/* Revert the actions of AfterTriggerBeginQuery(). */
afterTriggers.query_depth--;
}
/* ---------- /* ----------
* AfterTriggerEndQuery() * AfterTriggerEndQuery()
* *

View File

@ -285,28 +285,6 @@ are typically reset to empty once per tuple. Per-tuple contexts are usually
associated with ExprContexts, and commonly each PlanState node has its own associated with ExprContexts, and commonly each PlanState node has its own
ExprContext to evaluate its qual and targetlist expressions in. ExprContext to evaluate its qual and targetlist expressions in.
Relation Locking
----------------
When the executor initializes a plan tree for execution, it doesn't lock
non-index relations if the plan tree is freshly generated and not derived
from a CachedPlan. This is because such locks have already been established
during the query's parsing, rewriting, and planning phases. However, with a
cached plan tree, some relations may remain unlocked. The function
AcquireExecutorLocks() only locks unprunable relations in the plan, deferring
the locking of prunable ones to executor initialization. This avoids
unnecessary locking of relations that will be pruned during "initial" runtime
pruning in ExecDoInitialPruning().
This approach creates a window where a cached plan tree with child tables
could become outdated if another backend modifies these tables before
ExecDoInitialPruning() locks them. As a result, the executor has the added duty
to verify the plan tree's validity whenever it locks a child table after
doing initial pruning. This validation is done by checking the CachedPlan.is_valid
flag. If the plan tree is outdated (is_valid = false), the executor stops
further initialization, cleans up anything in EState that would have been
allocated up to that point, and retries execution after recreating the
invalid plan in the CachedPlan. See ExecutorStartCachedPlan().
Query Processing Control Flow Query Processing Control Flow
----------------------------- -----------------------------
@ -315,13 +293,11 @@ This is a sketch of control flow for full query processing:
CreateQueryDesc CreateQueryDesc
ExecutorStart or ExecutorStartCachedPlan ExecutorStart
CreateExecutorState CreateExecutorState
creates per-query context creates per-query context
switch to per-query context to run ExecDoInitialPruning and ExecInitNode switch to per-query context to run ExecInitNode
AfterTriggerBeginQuery AfterTriggerBeginQuery
ExecDoInitialPruning
does initial pruning and locks surviving partitions if needed
ExecInitNode --- recursively scans plan tree ExecInitNode --- recursively scans plan tree
ExecInitNode ExecInitNode
recurse into subsidiary nodes recurse into subsidiary nodes
@ -345,12 +321,7 @@ This is a sketch of control flow for full query processing:
FreeQueryDesc FreeQueryDesc
As mentioned in the "Relation Locking" section, if the plan tree is found to Per above comments, it's not really critical for ExecEndNode to free any
be stale after locking partitions in ExecDoInitialPruning(), the control is
immediately returned to ExecutorStartCachedPlan(), which will create a new plan
tree and perform the steps starting from CreateExecutorState() again.
Per above comments, it's not really critical for ExecEndPlan to free any
memory; it'll all go away in FreeExecutorState anyway. However, we do need to memory; it'll all go away in FreeExecutorState anyway. However, we do need to
be careful to close relations, drop buffer pins, etc, so we do need to scan be careful to close relations, drop buffer pins, etc, so we do need to scan
the plan state tree to find these sorts of resources. the plan state tree to find these sorts of resources.

View File

@ -55,13 +55,11 @@
#include "parser/parse_relation.h" #include "parser/parse_relation.h"
#include "pgstat.h" #include "pgstat.h"
#include "rewrite/rewriteHandler.h" #include "rewrite/rewriteHandler.h"
#include "storage/lmgr.h"
#include "tcop/utility.h" #include "tcop/utility.h"
#include "utils/acl.h" #include "utils/acl.h"
#include "utils/backend_status.h" #include "utils/backend_status.h"
#include "utils/lsyscache.h" #include "utils/lsyscache.h"
#include "utils/partcache.h" #include "utils/partcache.h"
#include "utils/plancache.h"
#include "utils/rls.h" #include "utils/rls.h"
#include "utils/snapmgr.h" #include "utils/snapmgr.h"
@ -119,16 +117,11 @@ static void ReportNotNullViolationError(ResultRelInfo *resultRelInfo,
* get control when ExecutorStart is called. Such a plugin would * get control when ExecutorStart is called. Such a plugin would
* normally call standard_ExecutorStart(). * normally call standard_ExecutorStart().
* *
* Return value indicates if the plan has been initialized successfully so
* that queryDesc->planstate contains a valid PlanState tree. It may not
* if the plan got invalidated during InitPlan().
* ---------------------------------------------------------------- * ----------------------------------------------------------------
*/ */
bool void
ExecutorStart(QueryDesc *queryDesc, int eflags) ExecutorStart(QueryDesc *queryDesc, int eflags)
{ {
bool plan_valid;
/* /*
* In some cases (e.g. an EXECUTE statement or an execute message with the * In some cases (e.g. an EXECUTE statement or an execute message with the
* extended query protocol) the query_id won't be reported, so do it now. * extended query protocol) the query_id won't be reported, so do it now.
@ -140,14 +133,12 @@ ExecutorStart(QueryDesc *queryDesc, int eflags)
pgstat_report_query_id(queryDesc->plannedstmt->queryId, false); pgstat_report_query_id(queryDesc->plannedstmt->queryId, false);
if (ExecutorStart_hook) if (ExecutorStart_hook)
plan_valid = (*ExecutorStart_hook) (queryDesc, eflags); (*ExecutorStart_hook) (queryDesc, eflags);
else else
plan_valid = standard_ExecutorStart(queryDesc, eflags); standard_ExecutorStart(queryDesc, eflags);
return plan_valid;
} }
bool void
standard_ExecutorStart(QueryDesc *queryDesc, int eflags) standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
{ {
EState *estate; EState *estate;
@ -271,64 +262,6 @@ standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
InitPlan(queryDesc, eflags); InitPlan(queryDesc, eflags);
MemoryContextSwitchTo(oldcontext); MemoryContextSwitchTo(oldcontext);
return ExecPlanStillValid(queryDesc->estate);
}
/*
* ExecutorStartCachedPlan
* Start execution for a given query in the CachedPlanSource, replanning
* if the plan is invalidated due to deferred locks taken during the
* plan's initialization
*
* This function handles cases where the CachedPlan given in queryDesc->cplan
* might become invalid during the initialization of the plan given in
* queryDesc->plannedstmt, particularly when prunable relations in it are
* locked after performing initial pruning. If the locks invalidate the plan,
* the function calls UpdateCachedPlan() to replan all queries in the
* CachedPlan, and then retries initialization.
*
* The function repeats the process until ExecutorStart() successfully
* initializes the plan, that is without the CachedPlan becoming invalid.
*/
void
ExecutorStartCachedPlan(QueryDesc *queryDesc, int eflags,
CachedPlanSource *plansource,
int query_index)
{
if (unlikely(queryDesc->cplan == NULL))
elog(ERROR, "ExecutorStartCachedPlan(): missing CachedPlan");
if (unlikely(plansource == NULL))
elog(ERROR, "ExecutorStartCachedPlan(): missing CachedPlanSource");
/*
* Loop and retry with an updated plan until no further invalidation
* occurs.
*/
while (1)
{
if (!ExecutorStart(queryDesc, eflags))
{
/*
* Clean up the current execution state before creating the new
* plan to retry ExecutorStart(). Mark execution as aborted to
* ensure that AFTER trigger state is properly reset.
*/
queryDesc->estate->es_aborted = true;
ExecutorEnd(queryDesc);
/* Retry ExecutorStart() with an updated plan tree. */
queryDesc->plannedstmt = UpdateCachedPlan(plansource, query_index,
queryDesc->queryEnv);
}
else
/*
* Exit the loop if the plan is initialized successfully and no
* sinval messages were received that invalidated the CachedPlan.
*/
break;
}
} }
/* ---------------------------------------------------------------- /* ----------------------------------------------------------------
@ -387,7 +320,6 @@ standard_ExecutorRun(QueryDesc *queryDesc,
estate = queryDesc->estate; estate = queryDesc->estate;
Assert(estate != NULL); Assert(estate != NULL);
Assert(!estate->es_aborted);
Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY)); Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
/* caller must ensure the query's snapshot is active */ /* caller must ensure the query's snapshot is active */
@ -494,11 +426,8 @@ standard_ExecutorFinish(QueryDesc *queryDesc)
Assert(estate != NULL); Assert(estate != NULL);
Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY)); Assert(!(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
/* /* This should be run once and only once per Executor instance */
* This should be run once and only once per Executor instance and never Assert(!estate->es_finished);
* if the execution was aborted.
*/
Assert(!estate->es_finished && !estate->es_aborted);
/* Switch into per-query memory context */ /* Switch into per-query memory context */
oldcontext = MemoryContextSwitchTo(estate->es_query_cxt); oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
@ -561,10 +490,11 @@ standard_ExecutorEnd(QueryDesc *queryDesc)
(PgStat_Counter) estate->es_parallel_workers_launched); (PgStat_Counter) estate->es_parallel_workers_launched);
/* /*
* Check that ExecutorFinish was called, unless in EXPLAIN-only mode or if * Check that ExecutorFinish was called, unless in EXPLAIN-only mode. This
* execution was aborted. * Assert is needed because ExecutorFinish is new as of 9.1, and callers
* might forget to call it.
*/ */
Assert(estate->es_finished || estate->es_aborted || Assert(estate->es_finished ||
(estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY)); (estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY));
/* /*
@ -578,14 +508,6 @@ standard_ExecutorEnd(QueryDesc *queryDesc)
UnregisterSnapshot(estate->es_snapshot); UnregisterSnapshot(estate->es_snapshot);
UnregisterSnapshot(estate->es_crosscheck_snapshot); UnregisterSnapshot(estate->es_crosscheck_snapshot);
/*
* Reset AFTER trigger module if the query execution was aborted.
*/
if (estate->es_aborted &&
!(estate->es_top_eflags &
(EXEC_FLAG_SKIP_TRIGGERS | EXEC_FLAG_EXPLAIN_ONLY)))
AfterTriggerAbortQuery();
/* /*
* Must switch out of context before destroying it * Must switch out of context before destroying it
*/ */
@ -684,21 +606,6 @@ ExecCheckPermissions(List *rangeTable, List *rteperminfos,
(rte->rtekind == RTE_SUBQUERY && (rte->rtekind == RTE_SUBQUERY &&
rte->relkind == RELKIND_VIEW)); rte->relkind == RELKIND_VIEW));
/*
* Ensure that we have at least an AccessShareLock on relations
* whose permissions need to be checked.
*
* Skip this check in a parallel worker because locks won't be
* taken until ExecInitNode() performs plan initialization.
*
* XXX: ExecCheckPermissions() in a parallel worker may be
* redundant with the checks done in the leader process, so this
* should be reviewed to ensure its necessary.
*/
Assert(IsParallelWorker() ||
CheckRelationOidLockedByMe(rte->relid, AccessShareLock,
true));
(void) getRTEPermissionInfo(rteperminfos, rte); (void) getRTEPermissionInfo(rteperminfos, rte);
/* Many-to-one mapping not allowed */ /* Many-to-one mapping not allowed */
Assert(!bms_is_member(rte->perminfoindex, indexset)); Assert(!bms_is_member(rte->perminfoindex, indexset));
@ -924,12 +831,6 @@ ExecCheckXactReadOnly(PlannedStmt *plannedstmt)
* *
* Initializes the query plan: open files, allocate storage * Initializes the query plan: open files, allocate storage
* and start up the rule manager * and start up the rule manager
*
* If the plan originates from a CachedPlan (given in queryDesc->cplan),
* it can become invalid during runtime "initial" pruning when the
* remaining set of locks is taken. The function returns early in that
* case without initializing the plan, and the caller is expected to
* retry with a new valid plan.
* ---------------------------------------------------------------- * ----------------------------------------------------------------
*/ */
static void static void
@ -937,7 +838,6 @@ InitPlan(QueryDesc *queryDesc, int eflags)
{ {
CmdType operation = queryDesc->operation; CmdType operation = queryDesc->operation;
PlannedStmt *plannedstmt = queryDesc->plannedstmt; PlannedStmt *plannedstmt = queryDesc->plannedstmt;
CachedPlan *cachedplan = queryDesc->cplan;
Plan *plan = plannedstmt->planTree; Plan *plan = plannedstmt->planTree;
List *rangeTable = plannedstmt->rtable; List *rangeTable = plannedstmt->rtable;
EState *estate = queryDesc->estate; EState *estate = queryDesc->estate;
@ -958,7 +858,6 @@ InitPlan(QueryDesc *queryDesc, int eflags)
bms_copy(plannedstmt->unprunableRelids)); bms_copy(plannedstmt->unprunableRelids));
estate->es_plannedstmt = plannedstmt; estate->es_plannedstmt = plannedstmt;
estate->es_cachedplan = cachedplan;
estate->es_part_prune_infos = plannedstmt->partPruneInfos; estate->es_part_prune_infos = plannedstmt->partPruneInfos;
/* /*
@ -972,9 +871,6 @@ InitPlan(QueryDesc *queryDesc, int eflags)
*/ */
ExecDoInitialPruning(estate); ExecDoInitialPruning(estate);
if (!ExecPlanStillValid(estate))
return;
/* /*
* Next, build the ExecRowMark array from the PlanRowMark(s), if any. * Next, build the ExecRowMark array from the PlanRowMark(s), if any.
*/ */
@ -3092,9 +2988,6 @@ EvalPlanQualStart(EPQState *epqstate, Plan *planTree)
* the snapshot, rangetable, and external Param info. They need their own * the snapshot, rangetable, and external Param info. They need their own
* copies of local state, including a tuple table, es_param_exec_vals, * copies of local state, including a tuple table, es_param_exec_vals,
* result-rel info, etc. * result-rel info, etc.
*
* es_cachedplan is not copied because EPQ plan execution does not acquire
* any new locks that could invalidate the CachedPlan.
*/ */
rcestate->es_direction = ForwardScanDirection; rcestate->es_direction = ForwardScanDirection;
rcestate->es_snapshot = parentestate->es_snapshot; rcestate->es_snapshot = parentestate->es_snapshot;

View File

@ -1278,15 +1278,8 @@ ExecParallelGetQueryDesc(shm_toc *toc, DestReceiver *receiver,
paramspace = shm_toc_lookup(toc, PARALLEL_KEY_PARAMLISTINFO, false); paramspace = shm_toc_lookup(toc, PARALLEL_KEY_PARAMLISTINFO, false);
paramLI = RestoreParamList(&paramspace); paramLI = RestoreParamList(&paramspace);
/* /* Create a QueryDesc for the query. */
* Create a QueryDesc for the query. We pass NULL for cachedplan, because
* we don't have a pointer to the CachedPlan in the leader's process. It's
* fine because the only reason the executor needs to see it is to decide
* if it should take locks on certain relations, but parallel workers
* always take locks anyway.
*/
return CreateQueryDesc(pstmt, return CreateQueryDesc(pstmt,
NULL,
queryString, queryString,
GetActiveSnapshot(), InvalidSnapshot, GetActiveSnapshot(), InvalidSnapshot,
receiver, paramLI, NULL, instrument_options); receiver, paramLI, NULL, instrument_options);
@ -1471,8 +1464,7 @@ ParallelQueryMain(dsm_segment *seg, shm_toc *toc)
/* Start up the executor */ /* Start up the executor */
queryDesc->plannedstmt->jitFlags = fpes->jit_flags; queryDesc->plannedstmt->jitFlags = fpes->jit_flags;
if (!ExecutorStart(queryDesc, fpes->eflags)) ExecutorStart(queryDesc, fpes->eflags);
elog(ERROR, "ExecutorStart() failed unexpectedly");
/* Special executor initialization steps for parallel workers */ /* Special executor initialization steps for parallel workers */
queryDesc->planstate->state->es_query_dsa = area; queryDesc->planstate->state->es_query_dsa = area;

View File

@ -26,7 +26,6 @@
#include "partitioning/partdesc.h" #include "partitioning/partdesc.h"
#include "partitioning/partprune.h" #include "partitioning/partprune.h"
#include "rewrite/rewriteManip.h" #include "rewrite/rewriteManip.h"
#include "storage/lmgr.h"
#include "utils/acl.h" #include "utils/acl.h"
#include "utils/lsyscache.h" #include "utils/lsyscache.h"
#include "utils/partcache.h" #include "utils/partcache.h"
@ -1771,8 +1770,7 @@ adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap)
* ExecDoInitialPruning: * ExecDoInitialPruning:
* Perform runtime "initial" pruning, if necessary, to determine the set * Perform runtime "initial" pruning, if necessary, to determine the set
* of child subnodes that need to be initialized during ExecInitNode() for * of child subnodes that need to be initialized during ExecInitNode() for
* all plan nodes that contain a PartitionPruneInfo. This also locks the * all plan nodes that contain a PartitionPruneInfo.
* leaf partitions whose subnodes will be initialized if needed.
* *
* ExecInitPartitionExecPruning: * ExecInitPartitionExecPruning:
* Updates the PartitionPruneState found at given part_prune_index in * Updates the PartitionPruneState found at given part_prune_index in
@ -1798,8 +1796,7 @@ adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap)
* ExecDoInitialPruning * ExecDoInitialPruning
* Perform runtime "initial" pruning, if necessary, to determine the set * Perform runtime "initial" pruning, if necessary, to determine the set
* of child subnodes that need to be initialized during ExecInitNode() for * of child subnodes that need to be initialized during ExecInitNode() for
* plan nodes that support partition pruning. This also locks the leaf * plan nodes that support partition pruning.
* partitions whose subnodes will be initialized if needed.
* *
* This function iterates over each PartitionPruneInfo entry in * This function iterates over each PartitionPruneInfo entry in
* estate->es_part_prune_infos. For each entry, it creates a PartitionPruneState * estate->es_part_prune_infos. For each entry, it creates a PartitionPruneState
@ -1821,9 +1818,7 @@ adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap)
void void
ExecDoInitialPruning(EState *estate) ExecDoInitialPruning(EState *estate)
{ {
PlannedStmt *stmt = estate->es_plannedstmt;
ListCell *lc; ListCell *lc;
List *locked_relids = NIL;
foreach(lc, estate->es_part_prune_infos) foreach(lc, estate->es_part_prune_infos)
{ {
@ -1849,68 +1844,11 @@ ExecDoInitialPruning(EState *estate)
else else
validsubplan_rtis = all_leafpart_rtis; validsubplan_rtis = all_leafpart_rtis;
if (ExecShouldLockRelations(estate))
{
int rtindex = -1;
while ((rtindex = bms_next_member(validsubplan_rtis,
rtindex)) >= 0)
{
RangeTblEntry *rte = exec_rt_fetch(rtindex, estate);
Assert(rte->rtekind == RTE_RELATION &&
rte->rellockmode != NoLock);
LockRelationOid(rte->relid, rte->rellockmode);
locked_relids = lappend_int(locked_relids, rtindex);
}
}
estate->es_unpruned_relids = bms_add_members(estate->es_unpruned_relids, estate->es_unpruned_relids = bms_add_members(estate->es_unpruned_relids,
validsubplan_rtis); validsubplan_rtis);
estate->es_part_prune_results = lappend(estate->es_part_prune_results, estate->es_part_prune_results = lappend(estate->es_part_prune_results,
validsubplans); validsubplans);
} }
/*
* Lock the first result relation of each ModifyTable node, even if it was
* pruned. This is required for ExecInitModifyTable(), which keeps its
* first result relation if all other result relations have been pruned,
* because some executor paths (e.g., in nodeModifyTable.c and
* execPartition.c) rely on there being at least one result relation.
*
* There's room for improvement here --- we actually only need to do this
* if all other result relations of the ModifyTable node were pruned, but
* we don't have an easy way to tell that here.
*/
if (stmt->resultRelations && ExecShouldLockRelations(estate))
{
foreach(lc, stmt->firstResultRels)
{
Index firstResultRel = lfirst_int(lc);
if (!bms_is_member(firstResultRel, estate->es_unpruned_relids))
{
RangeTblEntry *rte = exec_rt_fetch(firstResultRel, estate);
Assert(rte->rtekind == RTE_RELATION && rte->rellockmode != NoLock);
LockRelationOid(rte->relid, rte->rellockmode);
locked_relids = lappend_int(locked_relids, firstResultRel);
}
}
}
/*
* Release the useless locks if the plan won't be executed. This is the
* same as what CheckCachedPlan() in plancache.c does.
*/
if (!ExecPlanStillValid(estate))
{
foreach(lc, locked_relids)
{
RangeTblEntry *rte = exec_rt_fetch(lfirst_int(lc), estate);
UnlockRelationOid(rte->relid, rte->rellockmode);
}
}
} }
/* /*

View File

@ -147,7 +147,6 @@ CreateExecutorState(void)
estate->es_top_eflags = 0; estate->es_top_eflags = 0;
estate->es_instrument = 0; estate->es_instrument = 0;
estate->es_finished = false; estate->es_finished = false;
estate->es_aborted = false;
estate->es_exprcontexts = NIL; estate->es_exprcontexts = NIL;

View File

@ -34,6 +34,7 @@
#include "utils/funccache.h" #include "utils/funccache.h"
#include "utils/lsyscache.h" #include "utils/lsyscache.h"
#include "utils/memutils.h" #include "utils/memutils.h"
#include "utils/plancache.h"
#include "utils/snapmgr.h" #include "utils/snapmgr.h"
#include "utils/syscache.h" #include "utils/syscache.h"
@ -1338,7 +1339,6 @@ postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
dest = None_Receiver; dest = None_Receiver;
es->qd = CreateQueryDesc(es->stmt, es->qd = CreateQueryDesc(es->stmt,
NULL,
fcache->func->src, fcache->func->src,
GetActiveSnapshot(), GetActiveSnapshot(),
InvalidSnapshot, InvalidSnapshot,
@ -1363,8 +1363,7 @@ postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
eflags = EXEC_FLAG_SKIP_TRIGGERS; eflags = EXEC_FLAG_SKIP_TRIGGERS;
else else
eflags = 0; /* default run-to-completion flags */ eflags = 0; /* default run-to-completion flags */
if (!ExecutorStart(es->qd, eflags)) ExecutorStart(es->qd, eflags);
elog(ERROR, "ExecutorStart() failed unexpectedly");
} }
es->status = F_EXEC_RUN; es->status = F_EXEC_RUN;

View File

@ -70,8 +70,7 @@ static int _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes,
Datum *Values, const char *Nulls); Datum *Values, const char *Nulls);
static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount, static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount);
CachedPlanSource *plansource, int query_index);
static void _SPI_error_callback(void *arg); static void _SPI_error_callback(void *arg);
@ -1686,8 +1685,7 @@ SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
query_string, query_string,
plansource->commandTag, plansource->commandTag,
stmt_list, stmt_list,
cplan, cplan);
plansource);
/* /*
* Set up options for portal. Default SCROLL type is chosen the same way * Set up options for portal. Default SCROLL type is chosen the same way
@ -2502,7 +2500,6 @@ _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1); CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
List *stmt_list; List *stmt_list;
ListCell *lc2; ListCell *lc2;
int query_index = 0;
spicallbackarg.query = plansource->query_string; spicallbackarg.query = plansource->query_string;
@ -2693,16 +2690,14 @@ _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
snap = InvalidSnapshot; snap = InvalidSnapshot;
qdesc = CreateQueryDesc(stmt, qdesc = CreateQueryDesc(stmt,
cplan,
plansource->query_string, plansource->query_string,
snap, crosscheck_snapshot, snap, crosscheck_snapshot,
dest, dest,
options->params, options->params,
_SPI_current->queryEnv, _SPI_current->queryEnv,
0); 0);
res = _SPI_pquery(qdesc, fire_triggers,
res = _SPI_pquery(qdesc, fire_triggers, canSetTag ? options->tcount : 0, canSetTag ? options->tcount : 0);
plansource, query_index);
FreeQueryDesc(qdesc); FreeQueryDesc(qdesc);
} }
else else
@ -2799,8 +2794,6 @@ _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
my_res = res; my_res = res;
goto fail; goto fail;
} }
query_index++;
} }
/* Done with this plan, so release refcount */ /* Done with this plan, so release refcount */
@ -2878,8 +2871,7 @@ _SPI_convert_params(int nargs, Oid *argtypes,
} }
static int static int
_SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount, _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
CachedPlanSource *plansource, int query_index)
{ {
int operation = queryDesc->operation; int operation = queryDesc->operation;
int eflags; int eflags;
@ -2935,16 +2927,7 @@ _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount,
else else
eflags = EXEC_FLAG_SKIP_TRIGGERS; eflags = EXEC_FLAG_SKIP_TRIGGERS;
if (queryDesc->cplan) ExecutorStart(queryDesc, eflags);
{
ExecutorStartCachedPlan(queryDesc, eflags, plansource, query_index);
Assert(queryDesc->planstate);
}
else
{
if (!ExecutorStart(queryDesc, eflags))
elog(ERROR, "ExecutorStart() failed unexpectedly");
}
ExecutorRun(queryDesc, ForwardScanDirection, tcount); ExecutorRun(queryDesc, ForwardScanDirection, tcount);

View File

@ -331,7 +331,6 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
glob->finalrteperminfos = NIL; glob->finalrteperminfos = NIL;
glob->finalrowmarks = NIL; glob->finalrowmarks = NIL;
glob->resultRelations = NIL; glob->resultRelations = NIL;
glob->firstResultRels = NIL;
glob->appendRelations = NIL; glob->appendRelations = NIL;
glob->partPruneInfos = NIL; glob->partPruneInfos = NIL;
glob->relationOids = NIL; glob->relationOids = NIL;
@ -571,7 +570,6 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
glob->prunableRelids); glob->prunableRelids);
result->permInfos = glob->finalrteperminfos; result->permInfos = glob->finalrteperminfos;
result->resultRelations = glob->resultRelations; result->resultRelations = glob->resultRelations;
result->firstResultRels = glob->firstResultRels;
result->appendRelations = glob->appendRelations; result->appendRelations = glob->appendRelations;
result->subplans = glob->subplans; result->subplans = glob->subplans;
result->rewindPlanIDs = glob->rewindPlanIDs; result->rewindPlanIDs = glob->rewindPlanIDs;

View File

@ -1248,9 +1248,6 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
lappend_int(root->glob->resultRelations, lappend_int(root->glob->resultRelations,
splan->rootRelation); splan->rootRelation);
} }
root->glob->firstResultRels =
lappend_int(root->glob->firstResultRels,
linitial_int(splan->resultRelations));
} }
break; break;
case T_Append: case T_Append:

View File

@ -1226,7 +1226,6 @@ exec_simple_query(const char *query_string)
query_string, query_string,
commandTag, commandTag,
plantree_list, plantree_list,
NULL,
NULL); NULL);
/* /*
@ -2028,8 +2027,7 @@ exec_bind_message(StringInfo input_message)
query_string, query_string,
psrc->commandTag, psrc->commandTag,
cplan->stmt_list, cplan->stmt_list,
cplan, cplan);
psrc);
/* Portal is defined, set the plan ID based on its contents. */ /* Portal is defined, set the plan ID based on its contents. */
foreach(lc, portal->stmts) foreach(lc, portal->stmts)

View File

@ -19,7 +19,6 @@
#include "access/xact.h" #include "access/xact.h"
#include "commands/prepare.h" #include "commands/prepare.h"
#include "executor/execdesc.h"
#include "executor/executor.h" #include "executor/executor.h"
#include "executor/tstoreReceiver.h" #include "executor/tstoreReceiver.h"
#include "miscadmin.h" #include "miscadmin.h"
@ -38,9 +37,6 @@ Portal ActivePortal = NULL;
static void ProcessQuery(PlannedStmt *plan, static void ProcessQuery(PlannedStmt *plan,
CachedPlan *cplan,
CachedPlanSource *plansource,
int query_index,
const char *sourceText, const char *sourceText,
ParamListInfo params, ParamListInfo params,
QueryEnvironment *queryEnv, QueryEnvironment *queryEnv,
@ -70,7 +66,6 @@ static void DoPortalRewind(Portal portal);
*/ */
QueryDesc * QueryDesc *
CreateQueryDesc(PlannedStmt *plannedstmt, CreateQueryDesc(PlannedStmt *plannedstmt,
CachedPlan *cplan,
const char *sourceText, const char *sourceText,
Snapshot snapshot, Snapshot snapshot,
Snapshot crosscheck_snapshot, Snapshot crosscheck_snapshot,
@ -83,7 +78,6 @@ CreateQueryDesc(PlannedStmt *plannedstmt,
qd->operation = plannedstmt->commandType; /* operation */ qd->operation = plannedstmt->commandType; /* operation */
qd->plannedstmt = plannedstmt; /* plan */ qd->plannedstmt = plannedstmt; /* plan */
qd->cplan = cplan; /* CachedPlan supplying the plannedstmt */
qd->sourceText = sourceText; /* query text */ qd->sourceText = sourceText; /* query text */
qd->snapshot = RegisterSnapshot(snapshot); /* snapshot */ qd->snapshot = RegisterSnapshot(snapshot); /* snapshot */
/* RI check snapshot */ /* RI check snapshot */
@ -129,9 +123,6 @@ FreeQueryDesc(QueryDesc *qdesc)
* PORTAL_ONE_RETURNING, or PORTAL_ONE_MOD_WITH portal * PORTAL_ONE_RETURNING, or PORTAL_ONE_MOD_WITH portal
* *
* plan: the plan tree for the query * plan: the plan tree for the query
* cplan: CachedPlan supplying the plan
* plansource: CachedPlanSource supplying the cplan
* query_index: index of the query in plansource->query_list
* sourceText: the source text of the query * sourceText: the source text of the query
* params: any parameters needed * params: any parameters needed
* dest: where to send results * dest: where to send results
@ -144,9 +135,6 @@ FreeQueryDesc(QueryDesc *qdesc)
*/ */
static void static void
ProcessQuery(PlannedStmt *plan, ProcessQuery(PlannedStmt *plan,
CachedPlan *cplan,
CachedPlanSource *plansource,
int query_index,
const char *sourceText, const char *sourceText,
ParamListInfo params, ParamListInfo params,
QueryEnvironment *queryEnv, QueryEnvironment *queryEnv,
@ -158,23 +146,14 @@ ProcessQuery(PlannedStmt *plan,
/* /*
* Create the QueryDesc object * Create the QueryDesc object
*/ */
queryDesc = CreateQueryDesc(plan, cplan, sourceText, queryDesc = CreateQueryDesc(plan, sourceText,
GetActiveSnapshot(), InvalidSnapshot, GetActiveSnapshot(), InvalidSnapshot,
dest, params, queryEnv, 0); dest, params, queryEnv, 0);
/* /*
* Prepare the plan for execution * Call ExecutorStart to prepare the plan for execution
*/ */
if (queryDesc->cplan) ExecutorStart(queryDesc, 0);
{
ExecutorStartCachedPlan(queryDesc, 0, plansource, query_index);
Assert(queryDesc->planstate);
}
else
{
if (!ExecutorStart(queryDesc, 0))
elog(ERROR, "ExecutorStart() failed unexpectedly");
}
/* /*
* Run the plan to completion. * Run the plan to completion.
@ -515,7 +494,6 @@ PortalStart(Portal portal, ParamListInfo params,
* the destination to DestNone. * the destination to DestNone.
*/ */
queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts), queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
portal->cplan,
portal->sourceText, portal->sourceText,
GetActiveSnapshot(), GetActiveSnapshot(),
InvalidSnapshot, InvalidSnapshot,
@ -535,19 +513,9 @@ PortalStart(Portal portal, ParamListInfo params,
myeflags = eflags; myeflags = eflags;
/* /*
* Prepare the plan for execution. * Call ExecutorStart to prepare the plan for execution
*/ */
if (portal->cplan) ExecutorStart(queryDesc, myeflags);
{
ExecutorStartCachedPlan(queryDesc, myeflags,
portal->plansource, 0);
Assert(queryDesc->planstate);
}
else
{
if (!ExecutorStart(queryDesc, myeflags))
elog(ERROR, "ExecutorStart() failed unexpectedly");
}
/* /*
* This tells PortalCleanup to shut down the executor * This tells PortalCleanup to shut down the executor
@ -1221,7 +1189,6 @@ PortalRunMulti(Portal portal,
{ {
bool active_snapshot_set = false; bool active_snapshot_set = false;
ListCell *stmtlist_item; ListCell *stmtlist_item;
int query_index = 0;
/* /*
* If the destination is DestRemoteExecute, change to DestNone. The * If the destination is DestRemoteExecute, change to DestNone. The
@ -1303,9 +1270,6 @@ PortalRunMulti(Portal portal,
{ {
/* statement can set tag string */ /* statement can set tag string */
ProcessQuery(pstmt, ProcessQuery(pstmt,
portal->cplan,
portal->plansource,
query_index,
portal->sourceText, portal->sourceText,
portal->portalParams, portal->portalParams,
portal->queryEnv, portal->queryEnv,
@ -1315,9 +1279,6 @@ PortalRunMulti(Portal portal,
{ {
/* stmt added by rewrite cannot set tag */ /* stmt added by rewrite cannot set tag */
ProcessQuery(pstmt, ProcessQuery(pstmt,
portal->cplan,
portal->plansource,
query_index,
portal->sourceText, portal->sourceText,
portal->portalParams, portal->portalParams,
portal->queryEnv, portal->queryEnv,
@ -1382,8 +1343,6 @@ PortalRunMulti(Portal portal,
*/ */
if (lnext(portal->stmts, stmtlist_item) != NULL) if (lnext(portal->stmts, stmtlist_item) != NULL)
CommandCounterIncrement(); CommandCounterIncrement();
query_index++;
} }
/* Pop the snapshot if we pushed one. */ /* Pop the snapshot if we pushed one. */

View File

@ -92,8 +92,7 @@ static void ReleaseGenericPlan(CachedPlanSource *plansource);
static bool StmtPlanRequiresRevalidation(CachedPlanSource *plansource); static bool StmtPlanRequiresRevalidation(CachedPlanSource *plansource);
static bool BuildingPlanRequiresSnapshot(CachedPlanSource *plansource); static bool BuildingPlanRequiresSnapshot(CachedPlanSource *plansource);
static List *RevalidateCachedQuery(CachedPlanSource *plansource, static List *RevalidateCachedQuery(CachedPlanSource *plansource,
QueryEnvironment *queryEnv, QueryEnvironment *queryEnv);
bool release_generic);
static bool CheckCachedPlan(CachedPlanSource *plansource); static bool CheckCachedPlan(CachedPlanSource *plansource);
static CachedPlan *BuildCachedPlan(CachedPlanSource *plansource, List *qlist, static CachedPlan *BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
ParamListInfo boundParams, QueryEnvironment *queryEnv); ParamListInfo boundParams, QueryEnvironment *queryEnv);
@ -663,17 +662,10 @@ BuildingPlanRequiresSnapshot(CachedPlanSource *plansource)
* The result value is the transient analyzed-and-rewritten query tree if we * The result value is the transient analyzed-and-rewritten query tree if we
* had to do re-analysis, and NIL otherwise. (This is returned just to save * had to do re-analysis, and NIL otherwise. (This is returned just to save
* a tree copying step in a subsequent BuildCachedPlan call.) * a tree copying step in a subsequent BuildCachedPlan call.)
*
* This also releases and drops the generic plan (plansource->gplan), if any,
* as most callers will typically build a new CachedPlan for the plansource
* right after this. However, when called from UpdateCachedPlan(), the
* function does not release the generic plan, as UpdateCachedPlan() updates
* an existing CachedPlan in place.
*/ */
static List * static List *
RevalidateCachedQuery(CachedPlanSource *plansource, RevalidateCachedQuery(CachedPlanSource *plansource,
QueryEnvironment *queryEnv, QueryEnvironment *queryEnv)
bool release_generic)
{ {
bool snapshot_set; bool snapshot_set;
List *tlist; /* transient query-tree list */ List *tlist; /* transient query-tree list */
@ -772,9 +764,8 @@ RevalidateCachedQuery(CachedPlanSource *plansource,
MemoryContextDelete(qcxt); MemoryContextDelete(qcxt);
} }
/* Drop the generic plan reference, if any, and if requested */ /* Drop the generic plan reference if any */
if (release_generic) ReleaseGenericPlan(plansource);
ReleaseGenericPlan(plansource);
/* /*
* Now re-do parse analysis and rewrite. This not incidentally acquires * Now re-do parse analysis and rewrite. This not incidentally acquires
@ -937,10 +928,8 @@ RevalidateCachedQuery(CachedPlanSource *plansource,
* Caller must have already called RevalidateCachedQuery to verify that the * Caller must have already called RevalidateCachedQuery to verify that the
* querytree is up to date. * querytree is up to date.
* *
* On a "true" return, we have acquired locks on the "unprunableRelids" set * On a "true" return, we have acquired the locks needed to run the plan.
* for all plans in plansource->stmt_list. However, the plans are not fully * (We must do this for the "true" result to be race-condition-free.)
* race-condition-free until the executor acquires locks on the prunable
* relations that survive initial runtime pruning during InitPlan().
*/ */
static bool static bool
CheckCachedPlan(CachedPlanSource *plansource) CheckCachedPlan(CachedPlanSource *plansource)
@ -1025,8 +1014,6 @@ CheckCachedPlan(CachedPlanSource *plansource)
* Planning work is done in the caller's memory context. The finished plan * Planning work is done in the caller's memory context. The finished plan
* is in a child memory context, which typically should get reparented * is in a child memory context, which typically should get reparented
* (unless this is a one-shot plan, in which case we don't copy the plan). * (unless this is a one-shot plan, in which case we don't copy the plan).
*
* Note: When changing this, you should also look at UpdateCachedPlan().
*/ */
static CachedPlan * static CachedPlan *
BuildCachedPlan(CachedPlanSource *plansource, List *qlist, BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
@ -1037,7 +1024,6 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
bool snapshot_set; bool snapshot_set;
bool is_transient; bool is_transient;
MemoryContext plan_context; MemoryContext plan_context;
MemoryContext stmt_context = NULL;
MemoryContext oldcxt = CurrentMemoryContext; MemoryContext oldcxt = CurrentMemoryContext;
ListCell *lc; ListCell *lc;
@ -1055,7 +1041,7 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
* let's treat it as real and redo the RevalidateCachedQuery call. * let's treat it as real and redo the RevalidateCachedQuery call.
*/ */
if (!plansource->is_valid) if (!plansource->is_valid)
qlist = RevalidateCachedQuery(plansource, queryEnv, true); qlist = RevalidateCachedQuery(plansource, queryEnv);
/* /*
* If we don't already have a copy of the querytree list that can be * If we don't already have a copy of the querytree list that can be
@ -1093,19 +1079,10 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
PopActiveSnapshot(); PopActiveSnapshot();
/* /*
* Normally, we create a dedicated memory context for the CachedPlan and * Normally we make a dedicated memory context for the CachedPlan and its
* its subsidiary data. Although it's usually not very large, the context * subsidiary data. (It's probably not going to be large, but just in
* is designed to allow growth if necessary. * case, allow it to grow large. It's transient for the moment.) But for
* * a one-shot plan, we just leave it in the caller's memory context.
* The PlannedStmts are stored in a separate child context (stmt_context)
* of the CachedPlan's memory context. This separation allows
* UpdateCachedPlan() to free and replace the PlannedStmts without
* affecting the CachedPlan structure or its stmt_list List.
*
* For one-shot plans, we instead use the caller's memory context, as the
* CachedPlan will not persist. stmt_context will be set to NULL in this
* case, because UpdateCachedPlan() should never get called on a one-shot
* plan.
*/ */
if (!plansource->is_oneshot) if (!plansource->is_oneshot)
{ {
@ -1114,17 +1091,12 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
ALLOCSET_START_SMALL_SIZES); ALLOCSET_START_SMALL_SIZES);
MemoryContextCopyAndSetIdentifier(plan_context, plansource->query_string); MemoryContextCopyAndSetIdentifier(plan_context, plansource->query_string);
stmt_context = AllocSetContextCreate(CurrentMemoryContext, /*
"CachedPlan PlannedStmts", * Copy plan into the new context.
ALLOCSET_START_SMALL_SIZES); */
MemoryContextCopyAndSetIdentifier(stmt_context, plansource->query_string);
MemoryContextSetParent(stmt_context, plan_context);
MemoryContextSwitchTo(stmt_context);
plist = copyObject(plist);
MemoryContextSwitchTo(plan_context); MemoryContextSwitchTo(plan_context);
plist = list_copy(plist);
plist = copyObject(plist);
} }
else else
plan_context = CurrentMemoryContext; plan_context = CurrentMemoryContext;
@ -1165,10 +1137,8 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
plan->saved_xmin = InvalidTransactionId; plan->saved_xmin = InvalidTransactionId;
plan->refcount = 0; plan->refcount = 0;
plan->context = plan_context; plan->context = plan_context;
plan->stmt_context = stmt_context;
plan->is_oneshot = plansource->is_oneshot; plan->is_oneshot = plansource->is_oneshot;
plan->is_saved = false; plan->is_saved = false;
plan->is_reused = false;
plan->is_valid = true; plan->is_valid = true;
/* assign generation number to new plan */ /* assign generation number to new plan */
@ -1179,113 +1149,6 @@ BuildCachedPlan(CachedPlanSource *plansource, List *qlist,
return plan; return plan;
} }
/*
* UpdateCachedPlan
* Create fresh plans for all queries in the CachedPlanSource, replacing
* those in the generic plan's stmt_list, and return the plan for the
* query_index'th query.
*
* This function is primarily used by ExecutorStartCachedPlan() to handle
* cases where the original generic CachedPlan becomes invalid. Such
* invalidation may occur when prunable relations in the old plan for the
* query_index'th query are locked in preparation for execution.
*
* Note that invalidations received during the execution of the query_index'th
* query can affect both the queries that have already finished execution
* (e.g., due to concurrent modifications on prunable relations that were not
* locked during their execution) and also the queries that have not yet been
* executed. As a result, this function updates all plans to ensure
* CachedPlan.is_valid is safely set to true.
*
* The old PlannedStmts in plansource->gplan->stmt_list are freed here, so
* the caller and any of its callers must not rely on them remaining accessible
* after this function is called.
*/
PlannedStmt *
UpdateCachedPlan(CachedPlanSource *plansource, int query_index,
QueryEnvironment *queryEnv)
{
List *query_list = plansource->query_list,
*plan_list;
ListCell *l1,
*l2;
CachedPlan *plan = plansource->gplan;
MemoryContext oldcxt;
Assert(ActiveSnapshotSet());
/* Sanity checks (XXX can be Asserts?) */
if (plan == NULL)
elog(ERROR, "UpdateCachedPlan() called in the wrong context: plansource->gplan is NULL");
else if (plan->is_valid)
elog(ERROR, "UpdateCachedPlan() called in the wrong context: plansource->gplan->is_valid is true");
else if (plan->is_oneshot)
elog(ERROR, "UpdateCachedPlan() called in the wrong context: plansource->gplan->is_oneshot is true");
/*
* The plansource might have become invalid since GetCachedPlan() returned
* the CachedPlan. See the comment in BuildCachedPlan() for details on why
* this might happen. Although invalidation is likely a false positive as
* stated there, we make the plan valid to ensure the query list used for
* planning is up to date.
*
* The risk of catching an invalidation is higher here than when
* BuildCachedPlan() is called from GetCachedPlan(), because this function
* is normally called long after GetCachedPlan() returns the CachedPlan,
* so much more processing could have occurred including things that mark
* the CachedPlanSource invalid.
*
* Note: Do not release plansource->gplan, because the upstream callers
* (such as the callers of ExecutorStartCachedPlan()) would still be
* referencing it.
*/
if (!plansource->is_valid)
query_list = RevalidateCachedQuery(plansource, queryEnv, false);
Assert(query_list != NIL);
/*
* Build a new generic plan for all the queries after making a copy to be
* scribbled on by the planner.
*/
query_list = copyObject(query_list);
/*
* Planning work is done in the caller's memory context. The resulting
* PlannedStmt is then copied into plan->stmt_context after throwing away
* the old ones.
*/
plan_list = pg_plan_queries(query_list, plansource->query_string,
plansource->cursor_options, NULL);
Assert(list_length(plan_list) == list_length(plan->stmt_list));
MemoryContextReset(plan->stmt_context);
oldcxt = MemoryContextSwitchTo(plan->stmt_context);
forboth(l1, plan_list, l2, plan->stmt_list)
{
PlannedStmt *plannedstmt = lfirst(l1);
lfirst(l2) = copyObject(plannedstmt);
}
MemoryContextSwitchTo(oldcxt);
/*
* XXX Should this also (re)set the properties of the CachedPlan that are
* set in BuildCachedPlan() after creating the fresh plans such as
* planRoleId, dependsOnRole, and saved_xmin?
*/
/*
* We've updated all the plans that might have been invalidated, so mark
* the CachedPlan as valid.
*/
plan->is_valid = true;
/* Also update generic_cost because we just created a new generic plan. */
plansource->generic_cost = cached_plan_cost(plan, false);
return list_nth_node(PlannedStmt, plan->stmt_list, query_index);
}
/* /*
* choose_custom_plan: choose whether to use custom or generic plan * choose_custom_plan: choose whether to use custom or generic plan
* *
@ -1402,13 +1265,8 @@ cached_plan_cost(CachedPlan *plan, bool include_planner)
* plan or a custom plan for the given parameters: the caller does not know * plan or a custom plan for the given parameters: the caller does not know
* which it will get. * which it will get.
* *
* On return, the plan is valid, but if it is a reused generic plan, not all * On return, the plan is valid and we have sufficient locks to begin
* locks are acquired. In such cases, CheckCachedPlan() does not take locks * execution.
* on relations subject to initial runtime pruning; instead, these locks are
* deferred until execution startup, when ExecDoInitialPruning() performs
* initial pruning. The plan's "is_reused" flag is set to indicate that
* CachedPlanRequiresLocking() should return true when called by
* ExecDoInitialPruning().
* *
* On return, the refcount of the plan has been incremented; a later * On return, the refcount of the plan has been incremented; a later
* ReleaseCachedPlan() call is expected. If "owner" is not NULL then * ReleaseCachedPlan() call is expected. If "owner" is not NULL then
@ -1434,7 +1292,7 @@ GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams,
elog(ERROR, "cannot apply ResourceOwner to non-saved cached plan"); elog(ERROR, "cannot apply ResourceOwner to non-saved cached plan");
/* Make sure the querytree list is valid and we have parse-time locks */ /* Make sure the querytree list is valid and we have parse-time locks */
qlist = RevalidateCachedQuery(plansource, queryEnv, true); qlist = RevalidateCachedQuery(plansource, queryEnv);
/* Decide whether to use a custom plan */ /* Decide whether to use a custom plan */
customplan = choose_custom_plan(plansource, boundParams); customplan = choose_custom_plan(plansource, boundParams);
@ -1446,8 +1304,6 @@ GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams,
/* We want a generic plan, and we already have a valid one */ /* We want a generic plan, and we already have a valid one */
plan = plansource->gplan; plan = plansource->gplan;
Assert(plan->magic == CACHEDPLAN_MAGIC); Assert(plan->magic == CACHEDPLAN_MAGIC);
/* Reusing the existing plan, so not all locks may be acquired. */
plan->is_reused = true;
} }
else else
{ {
@ -1913,7 +1769,7 @@ CachedPlanGetTargetList(CachedPlanSource *plansource,
return NIL; return NIL;
/* Make sure the querytree list is valid and we have parse-time locks */ /* Make sure the querytree list is valid and we have parse-time locks */
RevalidateCachedQuery(plansource, queryEnv, true); RevalidateCachedQuery(plansource, queryEnv);
/* Get the primary statement and find out what it returns */ /* Get the primary statement and find out what it returns */
pstmt = QueryListGetPrimaryStmt(plansource->query_list); pstmt = QueryListGetPrimaryStmt(plansource->query_list);
@ -2035,7 +1891,7 @@ AcquireExecutorLocks(List *stmt_list, bool acquire)
foreach(lc1, stmt_list) foreach(lc1, stmt_list)
{ {
PlannedStmt *plannedstmt = lfirst_node(PlannedStmt, lc1); PlannedStmt *plannedstmt = lfirst_node(PlannedStmt, lc1);
int rtindex; ListCell *lc2;
if (plannedstmt->commandType == CMD_UTILITY) if (plannedstmt->commandType == CMD_UTILITY)
{ {
@ -2053,16 +1909,13 @@ AcquireExecutorLocks(List *stmt_list, bool acquire)
continue; continue;
} }
rtindex = -1; foreach(lc2, plannedstmt->rtable)
while ((rtindex = bms_next_member(plannedstmt->unprunableRelids,
rtindex)) >= 0)
{ {
RangeTblEntry *rte = list_nth_node(RangeTblEntry, RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
plannedstmt->rtable,
rtindex - 1);
Assert(rte->rtekind == RTE_RELATION || if (!(rte->rtekind == RTE_RELATION ||
(rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid))); (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid))))
continue;
/* /*
* Acquire the appropriate type of lock on each relation OID. Note * Acquire the appropriate type of lock on each relation OID. Note

View File

@ -284,8 +284,7 @@ PortalDefineQuery(Portal portal,
const char *sourceText, const char *sourceText,
CommandTag commandTag, CommandTag commandTag,
List *stmts, List *stmts,
CachedPlan *cplan, CachedPlan *cplan)
CachedPlanSource *plansource)
{ {
Assert(PortalIsValid(portal)); Assert(PortalIsValid(portal));
Assert(portal->status == PORTAL_NEW); Assert(portal->status == PORTAL_NEW);
@ -300,7 +299,6 @@ PortalDefineQuery(Portal portal,
portal->commandTag = commandTag; portal->commandTag = commandTag;
portal->stmts = stmts; portal->stmts = stmts;
portal->cplan = cplan; portal->cplan = cplan;
portal->plansource = plansource;
portal->status = PORTAL_DEFINED; portal->status = PORTAL_DEFINED;
} }

View File

@ -63,10 +63,8 @@ extern void ExplainOneUtility(Node *utilityStmt, IntoClause *into,
struct ExplainState *es, ParseState *pstate, struct ExplainState *es, ParseState *pstate,
ParamListInfo params); ParamListInfo params);
extern void ExplainOnePlan(PlannedStmt *plannedstmt, CachedPlan *cplan, extern void ExplainOnePlan(PlannedStmt *plannedstmt, IntoClause *into,
CachedPlanSource *plansource, int query_index, struct ExplainState *es, const char *queryString,
IntoClause *into, struct ExplainState *es,
const char *queryString,
ParamListInfo params, QueryEnvironment *queryEnv, ParamListInfo params, QueryEnvironment *queryEnv,
const instr_time *planduration, const instr_time *planduration,
const BufferUsage *bufusage, const BufferUsage *bufusage,

View File

@ -258,7 +258,6 @@ extern void ExecASTruncateTriggers(EState *estate,
extern void AfterTriggerBeginXact(void); extern void AfterTriggerBeginXact(void);
extern void AfterTriggerBeginQuery(void); extern void AfterTriggerBeginQuery(void);
extern void AfterTriggerEndQuery(EState *estate); extern void AfterTriggerEndQuery(EState *estate);
extern void AfterTriggerAbortQuery(void);
extern void AfterTriggerFireDeferred(void); extern void AfterTriggerFireDeferred(void);
extern void AfterTriggerEndXact(bool isCommit); extern void AfterTriggerEndXact(bool isCommit);
extern void AfterTriggerBeginSubXact(void); extern void AfterTriggerBeginSubXact(void);

View File

@ -35,7 +35,6 @@ typedef struct QueryDesc
/* These fields are provided by CreateQueryDesc */ /* These fields are provided by CreateQueryDesc */
CmdType operation; /* CMD_SELECT, CMD_UPDATE, etc. */ CmdType operation; /* CMD_SELECT, CMD_UPDATE, etc. */
PlannedStmt *plannedstmt; /* planner's output (could be utility, too) */ PlannedStmt *plannedstmt; /* planner's output (could be utility, too) */
CachedPlan *cplan; /* CachedPlan that supplies the plannedstmt */
const char *sourceText; /* source text of the query */ const char *sourceText; /* source text of the query */
Snapshot snapshot; /* snapshot to use for query */ Snapshot snapshot; /* snapshot to use for query */
Snapshot crosscheck_snapshot; /* crosscheck for RI update/delete */ Snapshot crosscheck_snapshot; /* crosscheck for RI update/delete */
@ -58,7 +57,6 @@ typedef struct QueryDesc
/* in pquery.c */ /* in pquery.c */
extern QueryDesc *CreateQueryDesc(PlannedStmt *plannedstmt, extern QueryDesc *CreateQueryDesc(PlannedStmt *plannedstmt,
CachedPlan *cplan,
const char *sourceText, const char *sourceText,
Snapshot snapshot, Snapshot snapshot,
Snapshot crosscheck_snapshot, Snapshot crosscheck_snapshot,

View File

@ -19,7 +19,6 @@
#include "nodes/lockoptions.h" #include "nodes/lockoptions.h"
#include "nodes/parsenodes.h" #include "nodes/parsenodes.h"
#include "utils/memutils.h" #include "utils/memutils.h"
#include "utils/plancache.h"
/* /*
@ -73,7 +72,7 @@
/* Hook for plugins to get control in ExecutorStart() */ /* Hook for plugins to get control in ExecutorStart() */
typedef bool (*ExecutorStart_hook_type) (QueryDesc *queryDesc, int eflags); typedef void (*ExecutorStart_hook_type) (QueryDesc *queryDesc, int eflags);
extern PGDLLIMPORT ExecutorStart_hook_type ExecutorStart_hook; extern PGDLLIMPORT ExecutorStart_hook_type ExecutorStart_hook;
/* Hook for plugins to get control in ExecutorRun() */ /* Hook for plugins to get control in ExecutorRun() */
@ -229,11 +228,8 @@ ExecGetJunkAttribute(TupleTableSlot *slot, AttrNumber attno, bool *isNull)
/* /*
* prototypes from functions in execMain.c * prototypes from functions in execMain.c
*/ */
extern bool ExecutorStart(QueryDesc *queryDesc, int eflags); extern void ExecutorStart(QueryDesc *queryDesc, int eflags);
extern void ExecutorStartCachedPlan(QueryDesc *queryDesc, int eflags, extern void standard_ExecutorStart(QueryDesc *queryDesc, int eflags);
CachedPlanSource *plansource,
int query_index);
extern bool standard_ExecutorStart(QueryDesc *queryDesc, int eflags);
extern void ExecutorRun(QueryDesc *queryDesc, extern void ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction, uint64 count); ScanDirection direction, uint64 count);
extern void standard_ExecutorRun(QueryDesc *queryDesc, extern void standard_ExecutorRun(QueryDesc *queryDesc,
@ -300,30 +296,6 @@ extern void ExecEndNode(PlanState *node);
extern void ExecShutdownNode(PlanState *node); extern void ExecShutdownNode(PlanState *node);
extern void ExecSetTupleBound(int64 tuples_needed, PlanState *child_node); extern void ExecSetTupleBound(int64 tuples_needed, PlanState *child_node);
/*
* Is the CachedPlan in es_cachedplan still valid?
*
* Called from InitPlan() because invalidation messages that affect the plan
* might be received after locks have been taken on runtime-prunable relations.
* The caller should take appropriate action if the plan has become invalid.
*/
static inline bool
ExecPlanStillValid(EState *estate)
{
return estate->es_cachedplan == NULL ? true :
CachedPlanValid(estate->es_cachedplan);
}
/*
* Locks are needed only if running a cached plan that might contain unlocked
* relations, such as a reused generic plan.
*/
static inline bool
ExecShouldLockRelations(EState *estate)
{
return estate->es_cachedplan == NULL ? false :
CachedPlanRequiresLocking(estate->es_cachedplan);
}
/* ---------------------------------------------------------------- /* ----------------------------------------------------------------
* ExecProcNode * ExecProcNode

View File

@ -42,7 +42,6 @@
#include "storage/condition_variable.h" #include "storage/condition_variable.h"
#include "utils/hsearch.h" #include "utils/hsearch.h"
#include "utils/queryenvironment.h" #include "utils/queryenvironment.h"
#include "utils/plancache.h"
#include "utils/reltrigger.h" #include "utils/reltrigger.h"
#include "utils/sharedtuplestore.h" #include "utils/sharedtuplestore.h"
#include "utils/snapshot.h" #include "utils/snapshot.h"
@ -664,7 +663,6 @@ typedef struct EState
* ExecRowMarks, or NULL if none */ * ExecRowMarks, or NULL if none */
List *es_rteperminfos; /* List of RTEPermissionInfo */ List *es_rteperminfos; /* List of RTEPermissionInfo */
PlannedStmt *es_plannedstmt; /* link to top of plan tree */ PlannedStmt *es_plannedstmt; /* link to top of plan tree */
CachedPlan *es_cachedplan; /* CachedPlan providing the plan tree */
List *es_part_prune_infos; /* List of PartitionPruneInfo */ List *es_part_prune_infos; /* List of PartitionPruneInfo */
List *es_part_prune_states; /* List of PartitionPruneState */ List *es_part_prune_states; /* List of PartitionPruneState */
List *es_part_prune_results; /* List of Bitmapset */ List *es_part_prune_results; /* List of Bitmapset */
@ -717,7 +715,6 @@ typedef struct EState
int es_top_eflags; /* eflags passed to ExecutorStart */ int es_top_eflags; /* eflags passed to ExecutorStart */
int es_instrument; /* OR of InstrumentOption flags */ int es_instrument; /* OR of InstrumentOption flags */
bool es_finished; /* true when ExecutorFinish is done */ bool es_finished; /* true when ExecutorFinish is done */
bool es_aborted; /* true when execution was aborted */
List *es_exprcontexts; /* List of ExprContexts within EState */ List *es_exprcontexts; /* List of ExprContexts within EState */

View File

@ -138,9 +138,6 @@ typedef struct PlannerGlobal
/* "flat" list of integer RT indexes */ /* "flat" list of integer RT indexes */
List *resultRelations; List *resultRelations;
/* "flat" list of integer RT indexes (one per ModifyTable node) */
List *firstResultRels;
/* "flat" list of AppendRelInfos */ /* "flat" list of AppendRelInfos */
List *appendRelations; List *appendRelations;

View File

@ -105,13 +105,6 @@ typedef struct PlannedStmt
/* integer list of RT indexes, or NIL */ /* integer list of RT indexes, or NIL */
List *resultRelations; List *resultRelations;
/*
* rtable indexes of first target relation in each ModifyTable node in the
* plan for INSERT/UPDATE/DELETE/MERGE
*/
/* integer list of RT indexes, or NIL */
List *firstResultRels;
/* list of AppendRelInfo nodes */ /* list of AppendRelInfo nodes */
List *appendRelations; List *appendRelations;

View File

@ -18,8 +18,6 @@
#include "access/tupdesc.h" #include "access/tupdesc.h"
#include "lib/ilist.h" #include "lib/ilist.h"
#include "nodes/params.h" #include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "tcop/cmdtag.h" #include "tcop/cmdtag.h"
#include "utils/queryenvironment.h" #include "utils/queryenvironment.h"
#include "utils/resowner.h" #include "utils/resowner.h"
@ -153,11 +151,10 @@ typedef struct CachedPlanSource
* The reference count includes both the link from the parent CachedPlanSource * The reference count includes both the link from the parent CachedPlanSource
* (if any), and any active plan executions, so the plan can be discarded * (if any), and any active plan executions, so the plan can be discarded
* exactly when refcount goes to zero. Both the struct itself and the * exactly when refcount goes to zero. Both the struct itself and the
* subsidiary data, except the PlannedStmts in stmt_list live in the context * subsidiary data live in the context denoted by the context field.
* denoted by the context field; the PlannedStmts live in the context denoted * This makes it easy to free a no-longer-needed cached plan. (However,
* by stmt_context. Separate contexts makes it easy to free a no-longer-needed * if is_oneshot is true, the context does not belong solely to the CachedPlan
* cached plan. (However, if is_oneshot is true, the context does not belong * so no freeing is possible.)
* solely to the CachedPlan so no freeing is possible.)
*/ */
typedef struct CachedPlan typedef struct CachedPlan
{ {
@ -165,7 +162,6 @@ typedef struct CachedPlan
List *stmt_list; /* list of PlannedStmts */ List *stmt_list; /* list of PlannedStmts */
bool is_oneshot; /* is it a "oneshot" plan? */ bool is_oneshot; /* is it a "oneshot" plan? */
bool is_saved; /* is CachedPlan in a long-lived context? */ bool is_saved; /* is CachedPlan in a long-lived context? */
bool is_reused; /* is it a reused generic plan? */
bool is_valid; /* is the stmt_list currently valid? */ bool is_valid; /* is the stmt_list currently valid? */
Oid planRoleId; /* Role ID the plan was created for */ Oid planRoleId; /* Role ID the plan was created for */
bool dependsOnRole; /* is plan specific to that role? */ bool dependsOnRole; /* is plan specific to that role? */
@ -174,10 +170,6 @@ typedef struct CachedPlan
int generation; /* parent's generation number for this plan */ int generation; /* parent's generation number for this plan */
int refcount; /* count of live references to this struct */ int refcount; /* count of live references to this struct */
MemoryContext context; /* context containing this CachedPlan */ MemoryContext context; /* context containing this CachedPlan */
MemoryContext stmt_context; /* context containing the PlannedStmts in
* stmt_list, but not the List itself which is
* in the above context; NULL if is_oneshot is
* true. */
} CachedPlan; } CachedPlan;
/* /*
@ -249,10 +241,6 @@ extern CachedPlan *GetCachedPlan(CachedPlanSource *plansource,
ParamListInfo boundParams, ParamListInfo boundParams,
ResourceOwner owner, ResourceOwner owner,
QueryEnvironment *queryEnv); QueryEnvironment *queryEnv);
extern PlannedStmt *UpdateCachedPlan(CachedPlanSource *plansource,
int query_index,
QueryEnvironment *queryEnv);
extern void ReleaseCachedPlan(CachedPlan *plan, ResourceOwner owner); extern void ReleaseCachedPlan(CachedPlan *plan, ResourceOwner owner);
extern bool CachedPlanAllowsSimpleValidityCheck(CachedPlanSource *plansource, extern bool CachedPlanAllowsSimpleValidityCheck(CachedPlanSource *plansource,
@ -265,30 +253,4 @@ extern bool CachedPlanIsSimplyValid(CachedPlanSource *plansource,
extern CachedExpression *GetCachedExpression(Node *expr); extern CachedExpression *GetCachedExpression(Node *expr);
extern void FreeCachedExpression(CachedExpression *cexpr); extern void FreeCachedExpression(CachedExpression *cexpr);
/*
* CachedPlanRequiresLocking: should the executor acquire additional locks?
*
* If the plan is a saved generic plan, the executor must acquire locks for
* relations that are not covered by AcquireExecutorLocks(), such as partitions
* that are subject to initial runtime pruning.
*/
static inline bool
CachedPlanRequiresLocking(CachedPlan *cplan)
{
return !cplan->is_oneshot && cplan->is_reused;
}
/*
* CachedPlanValid
* Returns whether a cached generic plan is still valid.
*
* Invoked by the executor to check if the plan has not been invalidated after
* taking locks during the initialization of the plan.
*/
static inline bool
CachedPlanValid(CachedPlan *cplan)
{
return cplan->is_valid;
}
#endif /* PLANCACHE_H */ #endif /* PLANCACHE_H */

View File

@ -138,7 +138,6 @@ typedef struct PortalData
QueryCompletion qc; /* command completion data for executed query */ QueryCompletion qc; /* command completion data for executed query */
List *stmts; /* list of PlannedStmts */ List *stmts; /* list of PlannedStmts */
CachedPlan *cplan; /* CachedPlan, if stmts are from one */ CachedPlan *cplan; /* CachedPlan, if stmts are from one */
CachedPlanSource *plansource; /* CachedPlanSource, for cplan */
ParamListInfo portalParams; /* params to pass to query */ ParamListInfo portalParams; /* params to pass to query */
QueryEnvironment *queryEnv; /* environment for query */ QueryEnvironment *queryEnv; /* environment for query */
@ -241,8 +240,7 @@ extern void PortalDefineQuery(Portal portal,
const char *sourceText, const char *sourceText,
CommandTag commandTag, CommandTag commandTag,
List *stmts, List *stmts,
CachedPlan *cplan, CachedPlan *cplan);
CachedPlanSource *plansource);
extern PlannedStmt *PortalGetPrimaryStmt(Portal portal); extern PlannedStmt *PortalGetPrimaryStmt(Portal portal);
extern void PortalCreateHoldStore(Portal portal); extern void PortalCreateHoldStore(Portal portal);
extern void PortalHashTableDeleteAll(void); extern void PortalHashTableDeleteAll(void);