diff --git a/src/backend/commands/prepare.c b/src/backend/commands/prepare.c index b945b1556a..63aa47f067 100644 --- a/src/backend/commands/prepare.c +++ b/src/backend/commands/prepare.c @@ -246,6 +246,17 @@ ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause, cplan = GetCachedPlan(entry->plansource, paramLI, false, NULL); plan_list = cplan->stmt_list; + /* + * DO NOT add any logic that could possibly throw an error between + * GetCachedPlan and PortalDefineQuery, or you'll leak the plan refcount. + */ + PortalDefineQuery(portal, + NULL, + query_string, + entry->plansource->commandTag, + plan_list, + cplan); + /* * For CREATE TABLE ... AS EXECUTE, we must verify that the prepared * statement is one that produces tuples. Currently we insist that it be @@ -289,13 +300,6 @@ ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause, count = FETCH_ALL; } - PortalDefineQuery(portal, - NULL, - query_string, - entry->plansource->commandTag, - plan_list, - cplan); - /* * Run the portal as appropriate. */