1
/*-------------------------------------------------------------------------
4
* Post-processing of a completed plan tree: fix references to subplan
5
* vars, and compute regproc values for operators
7
* Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
8
* Portions Copyright (c) 1994, Regents of the University of California
12
* $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.105 2004-12-31 22:00:09 pgsql Exp $
14
*-------------------------------------------------------------------------
18
#include "nodes/makefuncs.h"
19
#include "optimizer/clauses.h"
20
#include "optimizer/planmain.h"
21
#include "optimizer/tlist.h"
22
#include "optimizer/var.h"
23
#include "parser/parsetree.h"
24
#include "utils/lsyscache.h"
33
bool tlists_have_non_vars;
34
} join_references_context;
39
List *subplan_targetlist;
40
bool tlist_has_non_vars;
41
} replace_vars_with_subplan_refs_context;
43
static void fix_expr_references(Plan *plan, Node *node);
44
static bool fix_expr_references_walker(Node *node, void *context);
45
static void set_join_references(Join *join, List *rtable);
46
static void set_uppernode_references(Plan *plan, Index subvarno);
47
static bool targetlist_has_non_vars(List *tlist);
48
static List *join_references(List *clauses,
53
bool tlists_have_non_vars);
54
static Node *join_references_mutator(Node *node,
55
join_references_context *context);
56
static Node *replace_vars_with_subplan_refs(Node *node,
58
List *subplan_targetlist,
59
bool tlist_has_non_vars);
60
static Node *replace_vars_with_subplan_refs_mutator(Node *node,
61
replace_vars_with_subplan_refs_context *context);
62
static bool fix_opfuncids_walker(Node *node, void *context);
63
static void set_sa_opfuncid(ScalarArrayOpExpr *opexpr);
66
/*****************************************************************************
70
*****************************************************************************/
74
* This is the final processing pass of the planner/optimizer. The plan
75
* tree is complete; we just have to adjust some representational details
76
* for the convenience of the executor. We update Vars in upper plan nodes
77
* to refer to the outputs of their subplans, and we compute regproc OIDs
78
* for operators (ie, we look up the function that implements each op).
80
* set_plan_references recursively traverses the whole plan tree.
82
* Returns nothing of interest, but modifies internal fields of nodes.
85
set_plan_references(Plan *plan, List *rtable)
93
* Plan-type-specific fixes
95
switch (nodeTag(plan))
98
fix_expr_references(plan, (Node *) plan->targetlist);
99
fix_expr_references(plan, (Node *) plan->qual);
102
fix_expr_references(plan, (Node *) plan->targetlist);
103
fix_expr_references(plan, (Node *) plan->qual);
104
fix_expr_references(plan,
105
(Node *) ((IndexScan *) plan)->indxqual);
106
fix_expr_references(plan,
107
(Node *) ((IndexScan *) plan)->indxqualorig);
110
fix_expr_references(plan, (Node *) plan->targetlist);
111
fix_expr_references(plan, (Node *) plan->qual);
112
fix_expr_references(plan,
113
(Node *) ((TidScan *) plan)->tideval);
120
* We do not do set_uppernode_references() here, because a
121
* SubqueryScan will always have been created with correct
122
* references to its subplan's outputs to begin with.
124
fix_expr_references(plan, (Node *) plan->targetlist);
125
fix_expr_references(plan, (Node *) plan->qual);
127
/* Recurse into subplan too */
128
rte = rt_fetch(((SubqueryScan *) plan)->scan.scanrelid,
130
Assert(rte->rtekind == RTE_SUBQUERY);
131
set_plan_references(((SubqueryScan *) plan)->subplan,
132
rte->subquery->rtable);
139
fix_expr_references(plan, (Node *) plan->targetlist);
140
fix_expr_references(plan, (Node *) plan->qual);
141
rte = rt_fetch(((FunctionScan *) plan)->scan.scanrelid,
143
Assert(rte->rtekind == RTE_FUNCTION);
144
fix_expr_references(plan, rte->funcexpr);
148
set_join_references((Join *) plan, rtable);
149
fix_expr_references(plan, (Node *) plan->targetlist);
150
fix_expr_references(plan, (Node *) plan->qual);
151
fix_expr_references(plan, (Node *) ((Join *) plan)->joinqual);
154
set_join_references((Join *) plan, rtable);
155
fix_expr_references(plan, (Node *) plan->targetlist);
156
fix_expr_references(plan, (Node *) plan->qual);
157
fix_expr_references(plan, (Node *) ((Join *) plan)->joinqual);
158
fix_expr_references(plan,
159
(Node *) ((MergeJoin *) plan)->mergeclauses);
162
set_join_references((Join *) plan, rtable);
163
fix_expr_references(plan, (Node *) plan->targetlist);
164
fix_expr_references(plan, (Node *) plan->qual);
165
fix_expr_references(plan, (Node *) ((Join *) plan)->joinqual);
166
fix_expr_references(plan,
167
(Node *) ((HashJoin *) plan)->hashclauses);
176
* These plan types don't actually bother to evaluate their
177
* targetlists or quals (because they just return their
178
* unmodified input tuples). The optimizer is lazy about
179
* creating really valid targetlists for them. Best to just
180
* leave the targetlist alone. In particular, we do not want
181
* to process subplans for them, since we will likely end up
182
* reprocessing subplans that also appear in lower levels of
189
* Like the plan types above, Limit doesn't evaluate its tlist
190
* or quals. It does have live expressions for limit/offset,
193
fix_expr_references(plan, ((Limit *) plan)->limitOffset);
194
fix_expr_references(plan, ((Limit *) plan)->limitCount);
198
set_uppernode_references(plan, (Index) 0);
199
fix_expr_references(plan, (Node *) plan->targetlist);
200
fix_expr_references(plan, (Node *) plan->qual);
205
* Result may or may not have a subplan; no need to fix up
206
* subplan references if it hasn't got one...
208
* XXX why does Result use a different subvarno from Agg/Group?
210
if (plan->lefttree != NULL)
211
set_uppernode_references(plan, (Index) OUTER);
212
fix_expr_references(plan, (Node *) plan->targetlist);
213
fix_expr_references(plan, (Node *) plan->qual);
214
fix_expr_references(plan, ((Result *) plan)->resconstantqual);
219
* Append, like Sort et al, doesn't actually evaluate its
220
* targetlist or quals, and we haven't bothered to give it its
221
* own tlist copy. So, don't fix targetlist/qual. But do
222
* recurse into child plans.
224
foreach(l, ((Append *) plan)->appendplans)
225
set_plan_references((Plan *) lfirst(l), rtable);
228
elog(ERROR, "unrecognized node type: %d",
229
(int) nodeTag(plan));
234
* Now recurse into child plans and initplans, if any
236
* NOTE: it is essential that we recurse into child plans AFTER we set
237
* subplan references in this plan's tlist and quals. If we did the
238
* reference-adjustments bottom-up, then we would fail to match this
239
* plan's var nodes against the already-modified nodes of the
240
* children. Fortunately, that consideration doesn't apply to SubPlan
241
* nodes; else we'd need two passes over the expression trees.
243
set_plan_references(plan->lefttree, rtable);
244
set_plan_references(plan->righttree, rtable);
246
foreach(l, plan->initPlan)
248
SubPlan *sp = (SubPlan *) lfirst(l);
250
Assert(IsA(sp, SubPlan));
251
set_plan_references(sp->plan, sp->rtable);
256
* fix_expr_references
257
* Do final cleanup on expressions (targetlists or quals).
259
* This consists of looking up operator opcode info for OpExpr nodes
260
* and recursively performing set_plan_references on subplans.
262
* The Plan argument is currently unused, but might be needed again someday.
265
fix_expr_references(Plan *plan, Node *node)
267
/* This tree walk requires no special setup, so away we go... */
268
fix_expr_references_walker(node, NULL);
272
fix_expr_references_walker(Node *node, void *context)
276
if (IsA(node, OpExpr))
277
set_opfuncid((OpExpr *) node);
278
else if (IsA(node, DistinctExpr))
279
set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
280
else if (IsA(node, ScalarArrayOpExpr))
281
set_sa_opfuncid((ScalarArrayOpExpr *) node);
282
else if (IsA(node, NullIfExpr))
283
set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
284
else if (IsA(node, SubPlan))
286
SubPlan *sp = (SubPlan *) node;
288
set_plan_references(sp->plan, sp->rtable);
290
return expression_tree_walker(node, fix_expr_references_walker, context);
294
* set_join_references
295
* Modifies the target list and quals of a join node to reference its
296
* subplans, by setting the varnos to OUTER or INNER and setting attno
297
* values to the result domain number of either the corresponding outer
298
* or inner join tuple item.
300
* In the case of a nestloop with inner indexscan, we will also need to
301
* apply the same transformation to any outer vars appearing in the
302
* quals of the child indexscan.
304
* 'join' is a join plan node
305
* 'rtable' is the associated range table
308
set_join_references(Join *join, List *rtable)
310
Plan *outer_plan = join->plan.lefttree;
311
Plan *inner_plan = join->plan.righttree;
312
List *outer_tlist = outer_plan->targetlist;
313
List *inner_tlist = inner_plan->targetlist;
314
bool tlists_have_non_vars;
316
tlists_have_non_vars = targetlist_has_non_vars(outer_tlist) ||
317
targetlist_has_non_vars(inner_tlist);
319
/* All join plans have tlist, qual, and joinqual */
320
join->plan.targetlist = join_references(join->plan.targetlist,
325
tlists_have_non_vars);
326
join->plan.qual = join_references(join->plan.qual,
331
tlists_have_non_vars);
332
join->joinqual = join_references(join->joinqual,
337
tlists_have_non_vars);
339
/* Now do join-type-specific stuff */
340
if (IsA(join, NestLoop))
342
if (IsA(inner_plan, IndexScan))
345
* An index is being used to reduce the number of tuples
346
* scanned in the inner relation. If there are join clauses
347
* being used with the index, we must update their outer-rel
348
* var nodes to refer to the outer side of the join.
350
IndexScan *innerscan = (IndexScan *) inner_plan;
351
List *indxqualorig = innerscan->indxqualorig;
353
/* No work needed if indxqual refers only to its own rel... */
354
if (NumRelids((Node *) indxqualorig) > 1)
356
Index innerrel = innerscan->scan.scanrelid;
358
/* only refs to outer vars get changed in the inner qual */
359
innerscan->indxqualorig = join_references(indxqualorig,
364
tlists_have_non_vars);
365
innerscan->indxqual = join_references(innerscan->indxqual,
370
tlists_have_non_vars);
373
* We must fix the inner qpqual too, if it has join
374
* clauses (this could happen if special operators are
375
* involved: some indxquals may get rechecked as qpquals).
377
if (NumRelids((Node *) inner_plan->qual) > 1)
378
inner_plan->qual = join_references(inner_plan->qual,
383
tlists_have_non_vars);
386
else if (IsA(inner_plan, TidScan))
388
TidScan *innerscan = (TidScan *) inner_plan;
389
Index innerrel = innerscan->scan.scanrelid;
391
innerscan->tideval = join_references(innerscan->tideval,
396
tlists_have_non_vars);
399
else if (IsA(join, MergeJoin))
401
MergeJoin *mj = (MergeJoin *) join;
403
mj->mergeclauses = join_references(mj->mergeclauses,
408
tlists_have_non_vars);
410
else if (IsA(join, HashJoin))
412
HashJoin *hj = (HashJoin *) join;
414
hj->hashclauses = join_references(hj->hashclauses,
419
tlists_have_non_vars);
424
* set_uppernode_references
425
* Update the targetlist and quals of an upper-level plan node
426
* to refer to the tuples returned by its lefttree subplan.
428
* This is used for single-input plan types like Agg, Group, Result.
430
* In most cases, we have to match up individual Vars in the tlist and
431
* qual expressions with elements of the subplan's tlist (which was
432
* generated by flatten_tlist() from these selfsame expressions, so it
433
* should have all the required variables). There is an important exception,
434
* however: GROUP BY and ORDER BY expressions will have been pushed into the
435
* subplan tlist unflattened. If these values are also needed in the output
436
* then we want to reference the subplan tlist element rather than recomputing
440
set_uppernode_references(Plan *plan, Index subvarno)
442
Plan *subplan = plan->lefttree;
443
List *subplan_targetlist,
446
bool tlist_has_non_vars;
449
subplan_targetlist = subplan->targetlist;
451
subplan_targetlist = NIL;
453
tlist_has_non_vars = targetlist_has_non_vars(subplan_targetlist);
455
output_targetlist = NIL;
456
foreach(l, plan->targetlist)
458
TargetEntry *tle = (TargetEntry *) lfirst(l);
461
newexpr = replace_vars_with_subplan_refs((Node *) tle->expr,
465
output_targetlist = lappend(output_targetlist,
466
makeTargetEntry(tle->resdom,
469
plan->targetlist = output_targetlist;
471
plan->qual = (List *)
472
replace_vars_with_subplan_refs((Node *) plan->qual,
479
* targetlist_has_non_vars --- are there any non-Var entries in tlist?
481
* In most cases, subplan tlists will be "flat" tlists with only Vars.
482
* Checking for this allows us to save comparisons in common cases.
485
targetlist_has_non_vars(List *tlist)
491
TargetEntry *tle = (TargetEntry *) lfirst(l);
493
if (tle->expr && !IsA(tle->expr, Var))
501
* Creates a new set of targetlist entries or join qual clauses by
502
* changing the varno/varattno values of variables in the clauses
503
* to reference target list values from the outer and inner join
504
* relation target lists.
506
* This is used in two different scenarios: a normal join clause, where
507
* all the Vars in the clause *must* be replaced by OUTER or INNER references;
508
* and an indexscan being used on the inner side of a nestloop join.
509
* In the latter case we want to replace the outer-relation Vars by OUTER
510
* references, but not touch the Vars of the inner relation.
512
* For a normal join, acceptable_rel should be zero so that any failure to
513
* match a Var will be reported as an error. For the indexscan case,
514
* pass inner_tlist = NIL and acceptable_rel = the ID of the inner relation.
516
* 'clauses' is the targetlist or list of join clauses
517
* 'rtable' is the current range table
518
* 'outer_tlist' is the target list of the outer join relation
519
* 'inner_tlist' is the target list of the inner join relation, or NIL
520
* 'acceptable_rel' is either zero or the rangetable index of a relation
521
* whose Vars may appear in the clause without provoking an error.
523
* Returns the new expression tree. The original clause structure is
527
join_references(List *clauses,
531
Index acceptable_rel,
532
bool tlists_have_non_vars)
534
join_references_context context;
536
context.rtable = rtable;
537
context.outer_tlist = outer_tlist;
538
context.inner_tlist = inner_tlist;
539
context.acceptable_rel = acceptable_rel;
540
context.tlists_have_non_vars = tlists_have_non_vars;
541
return (List *) join_references_mutator((Node *) clauses, &context);
545
join_references_mutator(Node *node,
546
join_references_context *context)
552
Var *var = (Var *) node;
555
/* First look for the var in the input tlists */
556
resdom = tlist_member((Node *) var, context->outer_tlist);
559
Var *newvar = (Var *) copyObject(var);
561
newvar->varno = OUTER;
562
newvar->varattno = resdom->resno;
563
return (Node *) newvar;
565
resdom = tlist_member((Node *) var, context->inner_tlist);
568
Var *newvar = (Var *) copyObject(var);
570
newvar->varno = INNER;
571
newvar->varattno = resdom->resno;
572
return (Node *) newvar;
575
/* Return the Var unmodified, if it's for acceptable_rel */
576
if (var->varno == context->acceptable_rel)
577
return (Node *) copyObject(var);
579
/* No referent found for Var */
580
elog(ERROR, "variable not found in subplan target lists");
582
/* Try matching more complex expressions too, if tlists have any */
583
if (context->tlists_have_non_vars)
587
resdom = tlist_member(node, context->outer_tlist);
590
/* Found a matching subplan output expression */
593
newvar = makeVar(OUTER,
598
newvar->varnoold = 0; /* wasn't ever a plain Var */
599
newvar->varoattno = 0;
600
return (Node *) newvar;
602
resdom = tlist_member(node, context->inner_tlist);
605
/* Found a matching subplan output expression */
608
newvar = makeVar(INNER,
613
newvar->varnoold = 0; /* wasn't ever a plain Var */
614
newvar->varoattno = 0;
615
return (Node *) newvar;
618
return expression_tree_mutator(node,
619
join_references_mutator,
624
* replace_vars_with_subplan_refs
625
* This routine modifies an expression tree so that all Var nodes
626
* reference target nodes of a subplan. It is used to fix up
627
* target and qual expressions of non-join upper-level plan nodes.
629
* An error is raised if no matching var can be found in the subplan tlist
630
* --- so this routine should only be applied to nodes whose subplans'
631
* targetlists were generated via flatten_tlist() or some such method.
633
* If tlist_has_non_vars is true, then we try to match whole subexpressions
634
* against elements of the subplan tlist, so that we can avoid recomputing
635
* expressions that were already computed by the subplan. (This is relatively
636
* expensive, so we don't want to try it in the common case where the
637
* subplan tlist is just a flattened list of Vars.)
639
* 'node': the tree to be fixed (a target item or qual)
640
* 'subvarno': varno to be assigned to all Vars
641
* 'subplan_targetlist': target list for subplan
642
* 'tlist_has_non_vars': true if subplan_targetlist contains non-Var exprs
644
* The resulting tree is a copy of the original in which all Var nodes have
645
* varno = subvarno, varattno = resno of corresponding subplan target.
646
* The original tree is not modified.
649
replace_vars_with_subplan_refs(Node *node,
651
List *subplan_targetlist,
652
bool tlist_has_non_vars)
654
replace_vars_with_subplan_refs_context context;
656
context.subvarno = subvarno;
657
context.subplan_targetlist = subplan_targetlist;
658
context.tlist_has_non_vars = tlist_has_non_vars;
659
return replace_vars_with_subplan_refs_mutator(node, &context);
663
replace_vars_with_subplan_refs_mutator(Node *node,
664
replace_vars_with_subplan_refs_context *context)
670
Var *var = (Var *) node;
674
resdom = tlist_member((Node *) var, context->subplan_targetlist);
676
elog(ERROR, "variable not found in subplan target list");
677
newvar = (Var *) copyObject(var);
678
newvar->varno = context->subvarno;
679
newvar->varattno = resdom->resno;
680
return (Node *) newvar;
682
/* Try matching more complex expressions too, if tlist has any */
683
if (context->tlist_has_non_vars)
687
resdom = tlist_member(node, context->subplan_targetlist);
690
/* Found a matching subplan output expression */
693
newvar = makeVar(context->subvarno,
698
newvar->varnoold = 0; /* wasn't ever a plain Var */
699
newvar->varoattno = 0;
700
return (Node *) newvar;
703
return expression_tree_mutator(node,
704
replace_vars_with_subplan_refs_mutator,
708
/*****************************************************************************
709
* OPERATOR REGPROC LOOKUP
710
*****************************************************************************/
714
* Calculate opfuncid field from opno for each OpExpr node in given tree.
715
* The given tree can be anything expression_tree_walker handles.
717
* The argument is modified in-place. (This is OK since we'd want the
718
* same change for any node, even if it gets visited more than once due to
722
fix_opfuncids(Node *node)
724
/* This tree walk requires no special setup, so away we go... */
725
fix_opfuncids_walker(node, NULL);
729
fix_opfuncids_walker(Node *node, void *context)
733
if (IsA(node, OpExpr))
734
set_opfuncid((OpExpr *) node);
735
else if (IsA(node, DistinctExpr))
736
set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
737
else if (IsA(node, ScalarArrayOpExpr))
738
set_sa_opfuncid((ScalarArrayOpExpr *) node);
739
else if (IsA(node, NullIfExpr))
740
set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
741
return expression_tree_walker(node, fix_opfuncids_walker, context);
746
* Set the opfuncid (procedure OID) in an OpExpr node,
747
* if it hasn't been set already.
749
* Because of struct equivalence, this can also be used for
750
* DistinctExpr and NullIfExpr nodes.
753
set_opfuncid(OpExpr *opexpr)
755
if (opexpr->opfuncid == InvalidOid)
756
opexpr->opfuncid = get_opcode(opexpr->opno);
761
* As above, for ScalarArrayOpExpr nodes.
764
set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
766
if (opexpr->opfuncid == InvalidOid)
767
opexpr->opfuncid = get_opcode(opexpr->opno);