1 /*-------------------------------------------------------------------------
4 * Routines to find possible search paths for processing a query
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/path/allpaths.c,v 1.145 2006/04/30 18:30:39 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "nodes/makefuncs.h"
19 #ifdef OPTIMIZER_DEBUG
20 #include "nodes/print.h"
22 #include "optimizer/clauses.h"
23 #include "optimizer/cost.h"
24 #include "optimizer/geqo.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/plancat.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/var.h"
31 #include "parser/parsetree.h"
32 #include "parser/parse_clause.h"
33 #include "parser/parse_expr.h"
34 #include "rewrite/rewriteManip.h"
37 /* These parameters are set by GUC */
38 bool enable_geqo = false; /* just in case GUC doesn't set it */
42 static void set_base_rel_pathlists(PlannerInfo *root);
43 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti);
44 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
46 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
47 Index rti, RangeTblEntry *rte);
48 static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
49 Index rti, RangeTblEntry *rte);
50 static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
52 static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
53 static RelOptInfo *make_one_rel_by_joins(PlannerInfo *root, int levels_needed,
55 static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
56 bool *differentTypes);
57 static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
58 bool *differentTypes);
59 static void compare_tlist_datatypes(List *tlist, List *colTypes,
60 bool *differentTypes);
61 static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
62 bool *differentTypes);
63 static void subquery_push_qual(Query *subquery,
64 RangeTblEntry *rte, Index rti, Node *qual);
65 static void recurse_push_qual(Node *setOp, Query *topquery,
66 RangeTblEntry *rte, Index rti, Node *qual);
71 * Finds all possible access paths for executing a query, returning a
72 * single rel that represents the join of all base rels in the query.
75 make_one_rel(PlannerInfo *root, List *joinlist)
80 * Generate access paths for the base rels.
82 set_base_rel_pathlists(root);
85 * Generate access paths for the entire join tree.
87 rel = make_rel_from_joinlist(root, joinlist);
90 * The result should join all and only the query's base rels.
92 #ifdef USE_ASSERT_CHECKING
94 int num_base_rels = 0;
97 for (rti = 1; rti < root->simple_rel_array_size; rti++)
99 RelOptInfo *brel = root->simple_rel_array[rti];
104 Assert(brel->relid == rti); /* sanity check on array */
106 /* ignore RTEs that are "other rels" */
107 if (brel->reloptkind != RELOPT_BASEREL)
110 Assert(bms_is_member(rti, rel->relids));
114 Assert(bms_num_members(rel->relids) == num_base_rels);
122 * set_base_rel_pathlists
123 * Finds all paths available for scanning each base-relation entry.
124 * Sequential scan and any available indices are considered.
125 * Each useful path is attached to its relation's 'pathlist' field.
128 set_base_rel_pathlists(PlannerInfo *root)
132 for (rti = 1; rti < root->simple_rel_array_size; rti++)
134 RelOptInfo *rel = root->simple_rel_array[rti];
136 /* there may be empty slots corresponding to non-baserel RTEs */
140 Assert(rel->relid == rti); /* sanity check on array */
142 /* ignore RTEs that are "other rels" */
143 if (rel->reloptkind != RELOPT_BASEREL)
146 set_rel_pathlist(root, rel, rti);
152 * Build access paths for a base relation
155 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti)
157 RangeTblEntry *rte = rt_fetch(rti, root->parse->rtable);
161 /* It's an "append relation", process accordingly */
162 set_append_rel_pathlist(root, rel, rti, rte);
164 else if (rel->rtekind == RTE_SUBQUERY)
166 /* Subquery --- generate a separate plan for it */
167 set_subquery_pathlist(root, rel, rti, rte);
169 else if (rel->rtekind == RTE_FUNCTION)
171 /* RangeFunction --- generate a separate plan for it */
172 set_function_pathlist(root, rel, rte);
177 Assert(rel->rtekind == RTE_RELATION);
178 set_plain_rel_pathlist(root, rel, rte);
181 #ifdef OPTIMIZER_DEBUG
182 debug_print_rel(root, rel);
187 * set_plain_rel_pathlist
188 * Build access paths for a plain relation (no subquery, no inheritance)
191 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
193 /* Mark rel with estimated output rows, width, etc */
194 set_baserel_size_estimates(root, rel);
196 /* Test any partial indexes of rel for applicability */
197 check_partial_indexes(root, rel);
200 * Check to see if we can extract any restriction conditions from join
201 * quals that are OR-of-AND structures. If so, add them to the rel's
202 * restriction list, and recompute the size estimates.
204 if (create_or_index_quals(root, rel))
205 set_baserel_size_estimates(root, rel);
208 * If we can prove we don't need to scan the rel via constraint exclusion,
209 * set up a single dummy path for it. (Rather than inventing a special
210 * "dummy" path type, we represent this as an AppendPath with no members.)
212 if (relation_excluded_by_constraints(rel, rte))
214 /* Reset output-rows estimate to 0 */
217 add_path(rel, (Path *) create_append_path(rel, NIL));
219 /* Select cheapest path (pretty easy in this case...) */
226 * Generate paths and add them to the rel's pathlist.
228 * Note: add_path() will discard any paths that are dominated by another
229 * available path, keeping only those paths that are superior along at
230 * least one dimension of cost or sortedness.
233 /* Consider sequential scan */
234 add_path(rel, create_seqscan_path(root, rel));
236 /* Consider index scans */
237 create_index_paths(root, rel);
239 /* Consider TID scans */
240 create_tidscan_paths(root, rel);
242 /* Now find the cheapest of the paths for this rel */
247 * set_append_rel_pathlist
248 * Build access paths for an "append relation"
250 * The passed-in rel and RTE represent the entire append relation. The
251 * relation's contents are computed by appending together the output of
252 * the individual member relations. Note that in the inheritance case,
253 * the first member relation is actually the same table as is mentioned in
254 * the parent RTE ... but it has a different RTE and RelOptInfo. This is
255 * a good thing because their outputs are not the same size.
258 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
259 Index rti, RangeTblEntry *rte)
261 int parentRTindex = rti;
262 List *subpaths = NIL;
266 * XXX for now, can't handle inherited expansion of FOR UPDATE/SHARE; can
267 * we do better? (This will take some redesign because the executor
268 * currently supposes that every rowMark relation is involved in every
269 * row returned by the query.)
271 if (get_rowmark(root->parse, parentRTindex))
273 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
274 errmsg("SELECT FOR UPDATE/SHARE is not supported for inheritance queries")));
277 * Initialize to compute size estimates for whole append relation
283 * Generate access paths for each member relation, and pick the cheapest
286 foreach(l, root->append_rel_list)
288 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
290 RelOptInfo *childrel;
292 ListCell *parentvars;
295 /* append_rel_list contains all append rels; ignore others */
296 if (appinfo->parent_relid != parentRTindex)
299 childRTindex = appinfo->child_relid;
302 * Make a RelOptInfo for the child so we can do planning. Mark it as
303 * an "other rel" since it will not be part of the main join tree.
305 childrel = build_simple_rel(root, childRTindex,
306 RELOPT_OTHER_MEMBER_REL);
309 * Copy the parent's targetlist and quals to the child, with
310 * appropriate substitution of variables.
312 childrel->reltargetlist = (List *)
313 adjust_appendrel_attrs((Node *) rel->reltargetlist,
315 childrel->baserestrictinfo = (List *)
316 adjust_appendrel_attrs((Node *) rel->baserestrictinfo,
318 childrel->joininfo = (List *)
319 adjust_appendrel_attrs((Node *) rel->joininfo,
323 * Copy the parent's attr_needed data as well, with appropriate
324 * adjustment of relids and attribute numbers.
326 pfree(childrel->attr_needed);
327 childrel->attr_needed =
328 adjust_appendrel_attr_needed(rel, appinfo,
333 * Compute the child's access paths, and add the cheapest one
334 * to the Append path we are constructing for the parent.
336 * It's possible that the child is itself an appendrel, in which
337 * case we can "cut out the middleman" and just add its child
338 * paths to our own list. (We don't try to do this earlier because
339 * we need to apply both levels of transformation to the quals.)
340 * This test also handles the case where the child rel need not
341 * be scanned because of constraint exclusion: it'll have an
342 * Append path with no subpaths, and will vanish from our list.
344 set_rel_pathlist(root, childrel, childRTindex);
346 childpath = childrel->cheapest_total_path;
347 if (IsA(childpath, AppendPath))
348 subpaths = list_concat(subpaths,
349 ((AppendPath *) childpath)->subpaths);
351 subpaths = lappend(subpaths, childpath);
354 * Propagate size information from the child back to the parent. For
355 * simplicity, we use the largest widths from any child as the parent
358 rel->rows += childrel->rows;
359 if (childrel->width > rel->width)
360 rel->width = childrel->width;
362 forboth(parentvars, rel->reltargetlist,
363 childvars, childrel->reltargetlist)
365 Var *parentvar = (Var *) lfirst(parentvars);
366 Var *childvar = (Var *) lfirst(childvars);
368 if (IsA(parentvar, Var) &&
371 int pndx = parentvar->varattno - rel->min_attr;
372 int cndx = childvar->varattno - childrel->min_attr;
374 if (childrel->attr_widths[cndx] > rel->attr_widths[pndx])
375 rel->attr_widths[pndx] = childrel->attr_widths[cndx];
381 * Finally, build Append path and install it as the only access path for
382 * the parent rel. (Note: this is correct even if we have zero or one
383 * live subpath due to constraint exclusion.)
385 add_path(rel, (Path *) create_append_path(rel, subpaths));
387 /* Select cheapest path (pretty easy in this case...) */
391 /* quick-and-dirty test to see if any joining is needed */
393 has_multiple_baserels(PlannerInfo *root)
395 int num_base_rels = 0;
398 for (rti = 1; rti < root->simple_rel_array_size; rti++)
400 RelOptInfo *brel = root->simple_rel_array[rti];
405 /* ignore RTEs that are "other rels" */
406 if (brel->reloptkind == RELOPT_BASEREL)
407 if (++num_base_rels > 1)
414 * set_subquery_pathlist
415 * Build the (single) access path for a subquery RTE
418 set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
419 Index rti, RangeTblEntry *rte)
421 Query *parse = root->parse;
422 Query *subquery = rte->subquery;
423 bool *differentTypes;
424 double tuple_fraction;
426 List *subquery_pathkeys;
428 /* We need a workspace for keeping track of set-op type coercions */
429 differentTypes = (bool *)
430 palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
433 * If there are any restriction clauses that have been attached to the
434 * subquery relation, consider pushing them down to become WHERE or HAVING
435 * quals of the subquery itself. This transformation is useful because it
436 * may allow us to generate a better plan for the subquery than evaluating
437 * all the subquery output rows and then filtering them.
439 * There are several cases where we cannot push down clauses. Restrictions
440 * involving the subquery are checked by subquery_is_pushdown_safe().
441 * Restrictions on individual clauses are checked by
442 * qual_is_pushdown_safe().
444 * Non-pushed-down clauses will get evaluated as qpquals of the
447 * XXX Are there any cases where we want to make a policy decision not to
448 * push down a pushable qual, because it'd result in a worse plan?
450 if (rel->baserestrictinfo != NIL &&
451 subquery_is_pushdown_safe(subquery, subquery, differentTypes))
453 /* OK to consider pushing down individual quals */
454 List *upperrestrictlist = NIL;
457 foreach(l, rel->baserestrictinfo)
459 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
460 Node *clause = (Node *) rinfo->clause;
462 if (qual_is_pushdown_safe(subquery, rti, clause, differentTypes))
465 subquery_push_qual(subquery, rte, rti, clause);
469 /* Keep it in the upper query */
470 upperrestrictlist = lappend(upperrestrictlist, rinfo);
473 rel->baserestrictinfo = upperrestrictlist;
476 pfree(differentTypes);
479 * We can safely pass the outer tuple_fraction down to the subquery if the
480 * outer level has no joining, aggregation, or sorting to do. Otherwise
481 * we'd better tell the subquery to plan for full retrieval. (XXX This
482 * could probably be made more intelligent ...)
484 if (parse->hasAggs ||
485 parse->groupClause ||
487 parse->distinctClause ||
489 has_multiple_baserels(root))
490 tuple_fraction = 0.0; /* default case */
492 tuple_fraction = root->tuple_fraction;
494 /* Generate the plan for the subquery */
495 rel->subplan = subquery_planner(subquery, tuple_fraction,
498 /* Copy number of output rows from subplan */
499 rel->tuples = rel->subplan->plan_rows;
501 /* Mark rel with estimated output rows, width, etc */
502 set_baserel_size_estimates(root, rel);
504 /* Convert subquery pathkeys to outer representation */
505 pathkeys = convert_subquery_pathkeys(root, rel, subquery_pathkeys);
507 /* Generate appropriate path */
508 add_path(rel, create_subqueryscan_path(rel, pathkeys));
510 /* Select cheapest path (pretty easy in this case...) */
515 * set_function_pathlist
516 * Build the (single) access path for a function RTE
519 set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
521 /* Mark rel with estimated output rows, width, etc */
522 set_function_size_estimates(root, rel);
524 /* Generate appropriate path */
525 add_path(rel, create_functionscan_path(root, rel));
527 /* Select cheapest path (pretty easy in this case...) */
532 * make_rel_from_joinlist
533 * Build access paths using a "joinlist" to guide the join path search.
535 * See comments for deconstruct_jointree() for definition of the joinlist
539 make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
546 * Count the number of child joinlist nodes. This is the depth of the
547 * dynamic-programming algorithm we must employ to consider all ways of
548 * joining the child nodes.
550 levels_needed = list_length(joinlist);
552 if (levels_needed <= 0)
553 return NULL; /* nothing to do? */
556 * Construct a list of rels corresponding to the child joinlist nodes.
557 * This may contain both base rels and rels constructed according to
561 foreach(jl, joinlist)
563 Node *jlnode = (Node *) lfirst(jl);
566 if (IsA(jlnode, RangeTblRef))
568 int varno = ((RangeTblRef *) jlnode)->rtindex;
570 thisrel = find_base_rel(root, varno);
572 else if (IsA(jlnode, List))
574 /* Recurse to handle subproblem */
575 thisrel = make_rel_from_joinlist(root, (List *) jlnode);
579 elog(ERROR, "unrecognized joinlist node type: %d",
580 (int) nodeTag(jlnode));
581 thisrel = NULL; /* keep compiler quiet */
584 initial_rels = lappend(initial_rels, thisrel);
587 if (levels_needed == 1)
590 * Single joinlist node, so we're done.
592 return (RelOptInfo *) linitial(initial_rels);
597 * Consider the different orders in which we could join the rels,
598 * using either GEQO or regular optimizer.
600 if (enable_geqo && levels_needed >= geqo_threshold)
601 return geqo(root, levels_needed, initial_rels);
603 return make_one_rel_by_joins(root, levels_needed, initial_rels);
608 * make_one_rel_by_joins
609 * Find all possible joinpaths for a query by successively finding ways
610 * to join component relations into join relations.
612 * 'levels_needed' is the number of iterations needed, ie, the number of
613 * independent jointree items in the query. This is > 1.
615 * 'initial_rels' is a list of RelOptInfo nodes for each independent
616 * jointree item. These are the components to be joined together.
618 * Returns the final level of join relations, i.e., the relation that is
619 * the result of joining all the original relations together.
622 make_one_rel_by_joins(PlannerInfo *root, int levels_needed, List *initial_rels)
629 * We employ a simple "dynamic programming" algorithm: we first find all
630 * ways to build joins of two jointree items, then all ways to build joins
631 * of three items (from two-item joins and single items), then four-item
632 * joins, and so on until we have considered all ways to join all the
633 * items into one rel.
635 * joinitems[j] is a list of all the j-item rels. Initially we set
636 * joinitems[1] to represent all the single-jointree-item relations.
638 joinitems = (List **) palloc0((levels_needed + 1) * sizeof(List *));
640 joinitems[1] = initial_rels;
642 for (lev = 2; lev <= levels_needed; lev++)
647 * Determine all possible pairs of relations to be joined at this
648 * level, and build paths for making each one from every available
649 * pair of lower-level relations.
651 joinitems[lev] = make_rels_by_joins(root, lev, joinitems);
654 * Do cleanup work on each just-processed rel.
656 foreach(x, joinitems[lev])
658 rel = (RelOptInfo *) lfirst(x);
660 /* Find and save the cheapest paths for this rel */
663 #ifdef OPTIMIZER_DEBUG
664 debug_print_rel(root, rel);
670 * We should have a single rel at the final level.
672 if (joinitems[levels_needed] == NIL)
673 elog(ERROR, "failed to build any %d-way joins", levels_needed);
674 Assert(list_length(joinitems[levels_needed]) == 1);
676 rel = (RelOptInfo *) linitial(joinitems[levels_needed]);
681 /*****************************************************************************
682 * PUSHING QUALS DOWN INTO SUBQUERIES
683 *****************************************************************************/
686 * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
688 * subquery is the particular component query being checked. topquery
689 * is the top component of a set-operations tree (the same Query if no
690 * set-op is involved).
692 * Conditions checked here:
694 * 1. If the subquery has a LIMIT clause, we must not push down any quals,
695 * since that could change the set of rows returned.
697 * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
698 * quals into it, because that would change the results.
700 * 3. For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
701 * push quals into each component query, but the quals can only reference
702 * subquery columns that suffer no type coercions in the set operation.
703 * Otherwise there are possible semantic gotchas. So, we check the
704 * component queries to see if any of them have different output types;
705 * differentTypes[k] is set true if column k has different type in any
709 subquery_is_pushdown_safe(Query *subquery, Query *topquery,
710 bool *differentTypes)
712 SetOperationStmt *topop;
715 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
718 /* Are we at top level, or looking at a setop component? */
719 if (subquery == topquery)
721 /* Top level, so check any component queries */
722 if (subquery->setOperations != NULL)
723 if (!recurse_pushdown_safe(subquery->setOperations, topquery,
729 /* Setop component must not have more components (too weird) */
730 if (subquery->setOperations != NULL)
732 /* Check whether setop component output types match top level */
733 topop = (SetOperationStmt *) topquery->setOperations;
734 Assert(topop && IsA(topop, SetOperationStmt));
735 compare_tlist_datatypes(subquery->targetList,
743 * Helper routine to recurse through setOperations tree
746 recurse_pushdown_safe(Node *setOp, Query *topquery,
747 bool *differentTypes)
749 if (IsA(setOp, RangeTblRef))
751 RangeTblRef *rtr = (RangeTblRef *) setOp;
752 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
753 Query *subquery = rte->subquery;
755 Assert(subquery != NULL);
756 return subquery_is_pushdown_safe(subquery, topquery, differentTypes);
758 else if (IsA(setOp, SetOperationStmt))
760 SetOperationStmt *op = (SetOperationStmt *) setOp;
762 /* EXCEPT is no good */
763 if (op->op == SETOP_EXCEPT)
766 if (!recurse_pushdown_safe(op->larg, topquery, differentTypes))
768 if (!recurse_pushdown_safe(op->rarg, topquery, differentTypes))
773 elog(ERROR, "unrecognized node type: %d",
774 (int) nodeTag(setOp));
780 * Compare tlist's datatypes against the list of set-operation result types.
781 * For any items that are different, mark the appropriate element of
782 * differentTypes[] to show that this column will have type conversions.
785 compare_tlist_datatypes(List *tlist, List *colTypes,
786 bool *differentTypes)
789 ListCell *colType = list_head(colTypes);
793 TargetEntry *tle = (TargetEntry *) lfirst(l);
796 continue; /* ignore resjunk columns */
798 elog(ERROR, "wrong number of tlist entries");
799 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
800 differentTypes[tle->resno] = true;
801 colType = lnext(colType);
804 elog(ERROR, "wrong number of tlist entries");
808 * qual_is_pushdown_safe - is a particular qual safe to push down?
810 * qual is a restriction clause applying to the given subquery (whose RTE
811 * has index rti in the parent query).
813 * Conditions checked here:
815 * 1. The qual must not contain any subselects (mainly because I'm not sure
816 * it will work correctly: sublinks will already have been transformed into
817 * subplans in the qual, but not in the subquery).
819 * 2. The qual must not refer to the whole-row output of the subquery
820 * (since there is no easy way to name that within the subquery itself).
822 * 3. The qual must not refer to any subquery output columns that were
823 * found to have inconsistent types across a set operation tree by
824 * subquery_is_pushdown_safe().
826 * 4. If the subquery uses DISTINCT ON, we must not push down any quals that
827 * refer to non-DISTINCT output columns, because that could change the set
828 * of rows returned. This condition is vacuous for DISTINCT, because then
829 * there are no non-DISTINCT output columns, but unfortunately it's fairly
830 * expensive to tell the difference between DISTINCT and DISTINCT ON in the
831 * parsetree representation. It's cheaper to just make sure all the Vars
832 * in the qual refer to DISTINCT columns.
834 * 5. We must not push down any quals that refer to subselect outputs that
835 * return sets, else we'd introduce functions-returning-sets into the
836 * subquery's WHERE/HAVING quals.
839 qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
840 bool *differentTypes)
845 Bitmapset *tested = NULL;
847 /* Refuse subselects (point 1) */
848 if (contain_subplans(qual))
852 * Examine all Vars used in clause; since it's a restriction clause, all
853 * such Vars must refer to subselect output columns.
855 vars = pull_var_clause(qual, false);
858 Var *var = (Var *) lfirst(vl);
861 Assert(var->varno == rti);
864 if (var->varattno == 0)
871 * We use a bitmapset to avoid testing the same attno more than once.
872 * (NB: this only works because subquery outputs can't have negative
875 if (bms_is_member(var->varattno, tested))
877 tested = bms_add_member(tested, var->varattno);
880 if (differentTypes[var->varattno])
886 /* Must find the tlist element referenced by the Var */
887 tle = get_tle_by_resno(subquery->targetList, var->varattno);
889 Assert(!tle->resjunk);
891 /* If subquery uses DISTINCT or DISTINCT ON, check point 4 */
892 if (subquery->distinctClause != NIL &&
893 !targetIsInSortList(tle, subquery->distinctClause))
895 /* non-DISTINCT column, so fail */
900 /* Refuse functions returning sets (point 5) */
901 if (expression_returns_set((Node *) tle->expr))
915 * subquery_push_qual - push down a qual that we have determined is safe
918 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
920 if (subquery->setOperations != NULL)
922 /* Recurse to push it separately to each component query */
923 recurse_push_qual(subquery->setOperations, subquery,
929 * We need to replace Vars in the qual (which must refer to outputs of
930 * the subquery) with copies of the subquery's targetlist expressions.
931 * Note that at this point, any uplevel Vars in the qual should have
932 * been replaced with Params, so they need no work.
934 * This step also ensures that when we are pushing into a setop tree,
935 * each component query gets its own copy of the qual.
937 qual = ResolveNew(qual, rti, 0, rte,
938 subquery->targetList,
942 * Now attach the qual to the proper place: normally WHERE, but if the
943 * subquery uses grouping or aggregation, put it in HAVING (since the
944 * qual really refers to the group-result rows).
946 if (subquery->hasAggs || subquery->groupClause || subquery->havingQual)
947 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
949 subquery->jointree->quals =
950 make_and_qual(subquery->jointree->quals, qual);
953 * We need not change the subquery's hasAggs or hasSublinks flags,
954 * since we can't be pushing down any aggregates that weren't there
955 * before, and we don't push down subselects at all.
961 * Helper routine to recurse through setOperations tree
964 recurse_push_qual(Node *setOp, Query *topquery,
965 RangeTblEntry *rte, Index rti, Node *qual)
967 if (IsA(setOp, RangeTblRef))
969 RangeTblRef *rtr = (RangeTblRef *) setOp;
970 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
971 Query *subquery = subrte->subquery;
973 Assert(subquery != NULL);
974 subquery_push_qual(subquery, rte, rti, qual);
976 else if (IsA(setOp, SetOperationStmt))
978 SetOperationStmt *op = (SetOperationStmt *) setOp;
980 recurse_push_qual(op->larg, topquery, rte, rti, qual);
981 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
985 elog(ERROR, "unrecognized node type: %d",
986 (int) nodeTag(setOp));
990 /*****************************************************************************
992 *****************************************************************************/
994 #ifdef OPTIMIZER_DEBUG
997 print_relids(Relids relids)
1003 tmprelids = bms_copy(relids);
1004 while ((x = bms_first_member(tmprelids)) >= 0)
1011 bms_free(tmprelids);
1015 print_restrictclauses(PlannerInfo *root, List *clauses)
1021 RestrictInfo *c = lfirst(l);
1023 print_expr((Node *) c->clause, root->parse->rtable);
1030 print_path(PlannerInfo *root, Path *path, int indent)
1034 Path *subpath = NULL;
1037 switch (nodeTag(path))
1045 case T_BitmapHeapPath:
1046 ptype = "BitmapHeapScan";
1048 case T_BitmapAndPath:
1049 ptype = "BitmapAndPath";
1051 case T_BitmapOrPath:
1052 ptype = "BitmapOrPath";
1062 subpath = ((ResultPath *) path)->subpath;
1064 case T_MaterialPath:
1066 subpath = ((MaterialPath *) path)->subpath;
1070 subpath = ((UniquePath *) path)->subpath;
1077 ptype = "MergeJoin";
1089 for (i = 0; i < indent; i++)
1091 printf("%s", ptype);
1096 print_relids(path->parent->relids);
1097 printf(") rows=%.0f", path->parent->rows);
1099 printf(" cost=%.2f..%.2f\n", path->startup_cost, path->total_cost);
1103 for (i = 0; i < indent; i++)
1105 printf(" pathkeys: ");
1106 print_pathkeys(path->pathkeys, root->parse->rtable);
1111 JoinPath *jp = (JoinPath *) path;
1113 for (i = 0; i < indent; i++)
1115 printf(" clauses: ");
1116 print_restrictclauses(root, jp->joinrestrictinfo);
1119 if (IsA(path, MergePath))
1121 MergePath *mp = (MergePath *) path;
1123 if (mp->outersortkeys || mp->innersortkeys)
1125 for (i = 0; i < indent; i++)
1127 printf(" sortouter=%d sortinner=%d\n",
1128 ((mp->outersortkeys) ? 1 : 0),
1129 ((mp->innersortkeys) ? 1 : 0));
1133 print_path(root, jp->outerjoinpath, indent + 1);
1134 print_path(root, jp->innerjoinpath, indent + 1);
1138 print_path(root, subpath, indent + 1);
1142 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
1146 printf("RELOPTINFO (");
1147 print_relids(rel->relids);
1148 printf("): rows=%.0f width=%d\n", rel->rows, rel->width);
1150 if (rel->baserestrictinfo)
1152 printf("\tbaserestrictinfo: ");
1153 print_restrictclauses(root, rel->baserestrictinfo);
1159 printf("\tjoininfo: ");
1160 print_restrictclauses(root, rel->joininfo);
1164 printf("\tpath list:\n");
1165 foreach(l, rel->pathlist)
1166 print_path(root, lfirst(l), 1);
1167 printf("\n\tcheapest startup path:\n");
1168 print_path(root, rel->cheapest_startup_path, 1);
1169 printf("\n\tcheapest total path:\n");
1170 print_path(root, rel->cheapest_total_path, 1);
1175 #endif /* OPTIMIZER_DEBUG */