Skip to content

Commit 9edd78c

Browse files
committed
fix: push ROWNUM evaluation before Sort in subqueries
Fixes ROWNUM returning 0 in SELECT list when combined with ORDER BY in subqueries (Issue #13). The fix pushes ROWNUM evaluation to the scan level before Sort nodes, ensuring values are materialized before sorting occurs. Changes: - Planner: detect ROWNUM+Sort pattern and push ROWNUM to scan level - Executor: add materialization flag to preserve ROWNUM values - Tests: add comprehensive test coverage for ROWNUM with ORDER BY - Tests: add test case for Issue #14 (correlated subquery bug)
1 parent 1fdd54b commit 9edd78c

8 files changed

Lines changed: 536 additions & 23 deletions

File tree

‎src/backend/executor/execExpr.c‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,41 @@ ExecInitExprList(List *nodes, PlanState *parent)
377377
* Caution: before PG v10, the targetList was a list of ExprStates; now it
378378
* should be the planner-created targetlist, since we do the compilation here.
379379
*/
380+
381+
/*
382+
* Helper function to check if an expression contains ROWNUM
383+
*/
384+
static bool
385+
expression_contains_rownum_walker(Node *node, void *context)
386+
{
387+
if (node == NULL)
388+
return false;
389+
390+
if (IsA(node, RownumExpr))
391+
return true;
392+
393+
return expression_tree_walker(node, expression_contains_rownum_walker, context);
394+
}
395+
396+
/*
397+
* Check if a target list contains ROWNUM expressions
398+
*/
399+
static bool
400+
targetlist_contains_rownum(List *targetList)
401+
{
402+
ListCell *lc;
403+
404+
foreach(lc, targetList)
405+
{
406+
TargetEntry *tle = lfirst_node(TargetEntry, lc);
407+
408+
if (expression_contains_rownum_walker((Node *) tle->expr, NULL))
409+
return true;
410+
}
411+
412+
return false;
413+
}
414+
380415
ProjectionInfo *
381416
ExecBuildProjectionInfo(List *targetList,
382417
ExprContext *econtext,
@@ -519,6 +554,13 @@ ExecBuildProjectionInfo(List *targetList,
519554

520555
ExecReadyExpr(state);
521556

557+
/*
558+
* Check if the target list contains ROWNUM expressions.
559+
* If so, we need to materialize the result tuple to preserve the
560+
* ROWNUM values and prevent re-evaluation in outer queries.
561+
*/
562+
projInfo->pi_needsMaterialization = targetlist_contains_rownum(targetList);
563+
522564
return projInfo;
523565
}
524566

‎src/backend/executor/execExprInterp.c‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3348,8 +3348,9 @@ ExecEvalRownum(ExprState *state, ExprEvalStep *op)
33483348
{
33493349
PlanState *planstate;
33503350
EState *estate = NULL;
3351+
int64 rownum_value = 1; /* default */
33513352

3352-
/* Safely get the EState from the parent PlanState */
3353+
/* Safely get the PlanState and EState */
33533354
if (state && state->parent)
33543355
{
33553356
planstate = state->parent;
@@ -3358,15 +3359,14 @@ ExecEvalRownum(ExprState *state, ExprEvalStep *op)
33583359
}
33593360

33603361
/*
3361-
* Return current row number as INT8 (bigint).
3362-
* The counter starts at 1 and is incremented before each ExecProcNode call.
3363-
* For standalone expressions without an estate, default to 1.
3362+
* Use the estate-level ROWNUM counter.
3363+
* When ROWNUM appears in a SELECT list, materialization (handled in
3364+
* ExecScanExtended) ensures the value is captured and not re-evaluated.
33643365
*/
3365-
if (estate)
3366-
*op->resvalue = Int64GetDatum(estate->es_rownum);
3367-
else
3368-
*op->resvalue = Int64GetDatum(1);
3366+
if (estate && estate->es_rownum > 0)
3367+
rownum_value = estate->es_rownum;
33693368

3369+
*op->resvalue = Int64GetDatum(rownum_value);
33703370
*op->resnull = false;
33713371
}
33723372

‎src/backend/executor/nodeResult.c‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,18 @@ ExecResult(PlanState *pstate)
132132
}
133133

134134
/* form the result tuple using ExecProject(), and return it */
135-
return ExecProject(node->ps.ps_ProjInfo);
135+
TupleTableSlot *result = ExecProject(node->ps.ps_ProjInfo);
136+
137+
/*
138+
* If the projection contains ROWNUM expressions, materialize
139+
* the virtual tuple to preserve the ROWNUM values as constants.
140+
*/
141+
if (node->ps.ps_ProjInfo && node->ps.ps_ProjInfo->pi_needsMaterialization)
142+
{
143+
ExecMaterializeSlot(result);
144+
}
145+
146+
return result;
136147
}
137148

138149
return NULL;

‎src/backend/optimizer/plan/createplan.c‎

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
7979
int flags);
8080
static List *build_path_tlist(PlannerInfo *root, Path *path);
8181
static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
82+
static bool contain_rownum_expr(Node *node);
8283
static List *get_gating_quals(PlannerInfo *root, List *quals);
8384
static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
8485
List *gating_quals);
@@ -2067,6 +2068,178 @@ create_projection_plan(PlannerInfo *root, ProjectionPath *best_path, int flags)
20672068
subplan = create_plan_recurse(root, best_path->subpath, 0);
20682069
tlist = build_path_tlist(root, &best_path->path);
20692070
needs_result_node = !tlist_same_exprs(tlist, subplan->targetlist);
2071+
2072+
/*
2073+
* Special handling for Oracle ROWNUM with Sort:
2074+
* If the projection contains ROWNUM and the subplan is a Sort,
2075+
* we need to ensure ROWNUM is evaluated BEFORE the sort, not after.
2076+
* Oracle semantics require ROWNUM to be assigned during row retrieval,
2077+
* before any ORDER BY clause is applied.
2078+
*/
2079+
if (needs_result_node &&
2080+
(IsA(subplan, Sort) || IsA(subplan, IncrementalSort)) &&
2081+
contain_rownum_expr((Node *) tlist))
2082+
{
2083+
Plan *sortinput;
2084+
List *new_input_tlist;
2085+
List *new_sort_tlist;
2086+
List *modified_tlist;
2087+
ListCell *lc;
2088+
Index new_resno;
2089+
Index rownum_sort_attno;
2090+
Index scan_rownum_start;
2091+
Index scan_rownum_attno;
2092+
int num_rownums;
2093+
2094+
/*
2095+
* Get the Sort's input plan (the scan).
2096+
* For both Sort and IncrementalSort, the input is in 'lefttree'.
2097+
*/
2098+
sortinput = subplan->lefttree;
2099+
new_resno = list_length(sortinput->targetlist) + 1;
2100+
2101+
/*
2102+
* Remember where ROWNUM columns start in the scan's output.
2103+
* We'll use this to create Vars in the Sort's target list.
2104+
*/
2105+
scan_rownum_start = new_resno;
2106+
2107+
/*
2108+
* Build a new target list for the sort's input that includes
2109+
* all existing columns plus any ROWNUM expressions from the
2110+
* final projection.
2111+
*/
2112+
new_input_tlist = list_copy(sortinput->targetlist);
2113+
2114+
foreach(lc, tlist)
2115+
{
2116+
TargetEntry *tle = lfirst_node(TargetEntry, lc);
2117+
2118+
if (IsA(tle->expr, RownumExpr))
2119+
{
2120+
TargetEntry *new_tle;
2121+
2122+
/*
2123+
* Add the ROWNUM expression to the scan's target list.
2124+
* This will cause it to be evaluated during scan time,
2125+
* when es_rownum has the correct value.
2126+
*/
2127+
new_tle = makeTargetEntry(copyObject(tle->expr),
2128+
new_resno++,
2129+
tle->resname,
2130+
false);
2131+
new_input_tlist = lappend(new_input_tlist, new_tle);
2132+
}
2133+
}
2134+
2135+
/* Update the sort input's target list */
2136+
sortinput->targetlist = new_input_tlist;
2137+
2138+
/*
2139+
* Also add the ROWNUM column(s) to the Sort's target list,
2140+
* so they get passed through the sort.
2141+
*/
2142+
new_sort_tlist = list_copy(subplan->targetlist);
2143+
2144+
/*
2145+
* Remember where the ROWNUM columns will start in the Sort's
2146+
* output - we'll need this later to create Vars referencing them.
2147+
*/
2148+
rownum_sort_attno = list_length(new_sort_tlist) + 1;
2149+
2150+
/* Track which scan column we're referencing for each ROWNUM */
2151+
scan_rownum_attno = scan_rownum_start;
2152+
2153+
foreach(lc, tlist)
2154+
{
2155+
TargetEntry *tle = lfirst_node(TargetEntry, lc);
2156+
2157+
if (IsA(tle->expr, RownumExpr))
2158+
{
2159+
TargetEntry *new_tle;
2160+
Var *var;
2161+
2162+
/*
2163+
* Create a Var that references the ROWNUM from the
2164+
* scan's output.
2165+
*/
2166+
var = makeVar(OUTER_VAR,
2167+
scan_rownum_attno++,
2168+
INT8OID,
2169+
-1,
2170+
InvalidOid,
2171+
0);
2172+
2173+
new_tle = makeTargetEntry((Expr *) var,
2174+
list_length(new_sort_tlist) + 1,
2175+
tle->resname,
2176+
false);
2177+
new_sort_tlist = lappend(new_sort_tlist, new_tle);
2178+
}
2179+
}
2180+
2181+
subplan->targetlist = new_sort_tlist;
2182+
2183+
/*
2184+
* Now modify the final projection tlist to replace RownumExpr
2185+
* with Vars that reference the Sort's output columns.
2186+
* This ensures the Result node doesn't re-evaluate ROWNUM.
2187+
*/
2188+
modified_tlist = NIL;
2189+
2190+
/* Count how many ROWNUM columns we added */
2191+
num_rownums = 0;
2192+
foreach(lc, tlist)
2193+
{
2194+
TargetEntry *tle = lfirst_node(TargetEntry, lc);
2195+
2196+
if (IsA(tle->expr, RownumExpr))
2197+
num_rownums++;
2198+
}
2199+
2200+
/* ROWNUM columns start at: total_length - num_rownums + 1 */
2201+
rownum_sort_attno = list_length(new_sort_tlist) - num_rownums + 1;
2202+
2203+
foreach(lc, tlist)
2204+
{
2205+
TargetEntry *tle = lfirst_node(TargetEntry, lc);
2206+
TargetEntry *new_tle;
2207+
2208+
if (IsA(tle->expr, RownumExpr))
2209+
{
2210+
Var *var;
2211+
2212+
/*
2213+
* Replace the RownumExpr with a Var referencing the
2214+
* ROWNUM column from the Sort's output.
2215+
*/
2216+
var = makeVar(OUTER_VAR,
2217+
rownum_sort_attno++,
2218+
INT8OID,
2219+
-1,
2220+
InvalidOid,
2221+
0);
2222+
2223+
new_tle = makeTargetEntry((Expr *) var,
2224+
list_length(modified_tlist) + 1,
2225+
tle->resname,
2226+
tle->resjunk);
2227+
}
2228+
else
2229+
{
2230+
/* Keep non-ROWNUM entries as-is */
2231+
new_tle = makeTargetEntry(copyObject(tle->expr),
2232+
list_length(modified_tlist) + 1,
2233+
tle->resname,
2234+
tle->resjunk);
2235+
}
2236+
2237+
modified_tlist = lappend(modified_tlist, new_tle);
2238+
}
2239+
2240+
/* Use the modified tlist for the Result node */
2241+
tlist = modified_tlist;
2242+
}
20702243
}
20712244

20722245
/*
@@ -7412,6 +7585,31 @@ is_projection_capable_path(Path *path)
74127585
return true;
74137586
}
74147587

7588+
/*
7589+
* contain_rownum_expr
7590+
* Check whether a node tree contains any ROWNUM expressions.
7591+
*
7592+
* This is used to detect when we need special handling for Oracle ROWNUM
7593+
* pseudocolumn in combination with Sort nodes.
7594+
*/
7595+
static bool
7596+
contain_rownum_expr_walker(Node *node, void *context)
7597+
{
7598+
if (node == NULL)
7599+
return false;
7600+
7601+
if (IsA(node, RownumExpr))
7602+
return true;
7603+
7604+
return expression_tree_walker(node, contain_rownum_expr_walker, context);
7605+
}
7606+
7607+
static bool
7608+
contain_rownum_expr(Node *node)
7609+
{
7610+
return contain_rownum_expr_walker(node, NULL);
7611+
}
7612+
74157613
/*
74167614
* is_projection_capable_plan
74177615
* Check whether a given Plan node is able to do projection.

‎src/include/executor/execScan.h‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,30 @@ ExecScanExtended(ScanState *node,
226226

227227
if (projInfo)
228228
{
229+
TupleTableSlot *result;
230+
229231
/*
230232
* Form a projection tuple, store it in the result tuple slot
231233
* and return it.
232234
*/
233-
return ExecProject(projInfo);
235+
result = ExecProject(projInfo);
236+
237+
/*
238+
* If the projection contains ROWNUM expressions, materialize
239+
* the virtual tuple to preserve the ROWNUM values as constants.
240+
* This prevents re-evaluation when the tuple is read by outer
241+
* queries (e.g., in subqueries with ORDER BY).
242+
*
243+
* Oracle materializes ROWNUM values in SELECT lists, so when
244+
* a subquery projects ROWNUM, the value must be captured NOW
245+
* and not re-evaluated later in different contexts.
246+
*/
247+
if (projInfo->pi_needsMaterialization)
248+
{
249+
ExecMaterializeSlot(result);
250+
}
251+
252+
return result;
234253
}
235254
else
236255
{

‎src/include/nodes/execnodes.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,8 @@ typedef struct ProjectionInfo
380380
ExprState pi_state;
381381
/* expression context in which to evaluate expression */
382382
ExprContext *pi_exprContext;
383+
/* true if projection contains volatile exprs like ROWNUM that need materialization */
384+
bool pi_needsMaterialization;
383385
} ProjectionInfo;
384386

385387
/* ----------------

0 commit comments

Comments
 (0)