From 249126e761e13c4d8e7519569d483eaeca7dac25 Mon Sep 17 00:00:00 2001 From: Andres Freund Date: Wed, 4 Jul 2018 17:36:01 -0700 Subject: [PATCH] Use context with correct lifetime in hypothetical_dense_rank_final. The query lifetime expression context created in hypothetical_dense_rank_final() was buggily allocated in the calling memory context. I (Andres) broke that in bf6c614a2f2. Reported-By: Rajkumar Raghuwanshi Author: Amit Langote Discussion: https://postgr.es/m/CAKcux6kmzWmur5HhA_aU6gYVFu0RLQdgJJ+aC9SLdcOvBSrpfA@mail.gmail.com Backpatch: 11- --- src/backend/utils/adt/orderedsetaggs.c | 10 +++++++++- src/test/regress/expected/aggregates.out | 9 +++++++++ src/test/regress/sql/aggregates.sql | 3 +++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/backend/utils/adt/orderedsetaggs.c b/src/backend/utils/adt/orderedsetaggs.c index ed36851fdd..5867f3df07 100644 --- a/src/backend/utils/adt/orderedsetaggs.c +++ b/src/backend/utils/adt/orderedsetaggs.c @@ -1310,7 +1310,15 @@ hypothetical_dense_rank_final(PG_FUNCTION_ARGS) osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0); econtext = osastate->qstate->econtext; if (!econtext) - osastate->qstate->econtext = econtext = CreateStandaloneExprContext(); + { + MemoryContext oldcontext; + + /* Make sure to we create econtext under correct parent context. */ + oldcontext = MemoryContextSwitchTo(osastate->qstate->qcontext); + osastate->qstate->econtext = CreateStandaloneExprContext(); + econtext = osastate->qstate->econtext; + MemoryContextSwitchTo(oldcontext); + } /* Adjust nargs to be the number of direct (or aggregated) args */ if (nargs % 2 != 0) diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out index 10d6bb6824..a120dd83f7 100644 --- a/src/test/regress/expected/aggregates.out +++ b/src/test/regress/expected/aggregates.out @@ -2092,3 +2092,12 @@ SELECT variance(unique1::int4), sum(unique1::int8) FROM tenk1; (1 row) ROLLBACK; +-- test coverage for dense_rank +SELECT dense_rank(x) WITHIN GROUP (ORDER BY x) FROM (VALUES (1),(1),(2),(2),(3),(3)) v(x) GROUP BY (x) ORDER BY 1; + dense_rank +------------ + 1 + 1 + 1 +(3 rows) + diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql index 1b6db50956..7e77467ecd 100644 --- a/src/test/regress/sql/aggregates.sql +++ b/src/test/regress/sql/aggregates.sql @@ -925,3 +925,6 @@ EXPLAIN (COSTS OFF) SELECT variance(unique1::int4), sum(unique1::int8) FROM tenk1; ROLLBACK; + +-- test coverage for dense_rank +SELECT dense_rank(x) WITHIN GROUP (ORDER BY x) FROM (VALUES (1),(1),(2),(2),(3),(3)) v(x) GROUP BY (x) ORDER BY 1; -- 2.40.0