1 /*-------------------------------------------------------------------------
4 * Routines to find possible search paths for processing a query
6 * Portions Copyright (c) 1996-2007, 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.158 2007/01/28 18:50:40 tgl Exp $
13 *-------------------------------------------------------------------------
18 #ifdef OPTIMIZER_DEBUG
19 #include "nodes/print.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/geqo.h"
24 #include "optimizer/pathnode.h"
25 #include "optimizer/paths.h"
26 #include "optimizer/plancat.h"
27 #include "optimizer/planner.h"
28 #include "optimizer/prep.h"
29 #include "optimizer/var.h"
30 #include "parser/parse_clause.h"
31 #include "parser/parse_expr.h"
32 #include "parser/parsetree.h"
33 #include "rewrite/rewriteManip.h"
36 /* These parameters are set by GUC */
37 bool enable_geqo = false; /* just in case GUC doesn't set it */
41 static void set_base_rel_pathlists(PlannerInfo *root);
42 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti);
43 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
45 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
46 Index rti, RangeTblEntry *rte);
47 static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
48 Index rti, RangeTblEntry *rte);
49 static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
51 static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel,
53 static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
54 static RelOptInfo *make_one_rel_by_joins(PlannerInfo *root, int levels_needed,
56 static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
57 bool *differentTypes);
58 static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
59 bool *differentTypes);
60 static void compare_tlist_datatypes(List *tlist, List *colTypes,
61 bool *differentTypes);
62 static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
63 bool *differentTypes);
64 static void subquery_push_qual(Query *subquery,
65 RangeTblEntry *rte, Index rti, Node *qual);
66 static void recurse_push_qual(Node *setOp, Query *topquery,
67 RangeTblEntry *rte, Index rti, Node *qual);
72 * Finds all possible access paths for executing a query, returning a
73 * single rel that represents the join of all base rels in the query.
76 make_one_rel(PlannerInfo *root, List *joinlist)
81 * Generate access paths for the base rels.
83 set_base_rel_pathlists(root);
86 * Generate access paths for the entire join tree.
88 rel = make_rel_from_joinlist(root, joinlist);
91 * The result should join all and only the query's base rels.
93 #ifdef USE_ASSERT_CHECKING
95 int num_base_rels = 0;
98 for (rti = 1; rti < root->simple_rel_array_size; rti++)
100 RelOptInfo *brel = root->simple_rel_array[rti];
105 Assert(brel->relid == rti); /* sanity check on array */
107 /* ignore RTEs that are "other rels" */
108 if (brel->reloptkind != RELOPT_BASEREL)
111 Assert(bms_is_member(rti, rel->relids));
115 Assert(bms_num_members(rel->relids) == num_base_rels);
123 * set_base_rel_pathlists
124 * Finds all paths available for scanning each base-relation entry.
125 * Sequential scan and any available indices are considered.
126 * Each useful path is attached to its relation's 'pathlist' field.
129 set_base_rel_pathlists(PlannerInfo *root)
133 for (rti = 1; rti < root->simple_rel_array_size; rti++)
135 RelOptInfo *rel = root->simple_rel_array[rti];
137 /* there may be empty slots corresponding to non-baserel RTEs */
141 Assert(rel->relid == rti); /* sanity check on array */
143 /* ignore RTEs that are "other rels" */
144 if (rel->reloptkind != RELOPT_BASEREL)
147 set_rel_pathlist(root, rel, rti);
153 * Build access paths for a base relation
156 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti)
158 RangeTblEntry *rte = rt_fetch(rti, root->parse->rtable);
162 /* It's an "append relation", process accordingly */
163 set_append_rel_pathlist(root, rel, rti, rte);
165 else if (rel->rtekind == RTE_SUBQUERY)
167 /* Subquery --- generate a separate plan for it */
168 set_subquery_pathlist(root, rel, rti, rte);
170 else if (rel->rtekind == RTE_FUNCTION)
172 /* RangeFunction --- generate a separate plan for it */
173 set_function_pathlist(root, rel, rte);
175 else if (rel->rtekind == RTE_VALUES)
177 /* Values list --- generate a separate plan for it */
178 set_values_pathlist(root, rel, rte);
183 Assert(rel->rtekind == RTE_RELATION);
184 set_plain_rel_pathlist(root, rel, rte);
187 #ifdef OPTIMIZER_DEBUG
188 debug_print_rel(root, rel);
193 * set_plain_rel_pathlist
194 * Build access paths for a plain relation (no subquery, no inheritance)
197 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
199 /* Mark rel with estimated output rows, width, etc */
200 set_baserel_size_estimates(root, rel);
202 /* Test any partial indexes of rel for applicability */
203 check_partial_indexes(root, rel);
206 * Check to see if we can extract any restriction conditions from join
207 * quals that are OR-of-AND structures. If so, add them to the rel's
208 * restriction list, and recompute the size estimates.
210 if (create_or_index_quals(root, rel))
211 set_baserel_size_estimates(root, rel);
214 * If we can prove we don't need to scan the rel via constraint exclusion,
215 * set up a single dummy path for it. (Rather than inventing a special
216 * "dummy" path type, we represent this as an AppendPath with no members.)
218 if (relation_excluded_by_constraints(rel, rte))
220 /* Reset output-rows estimate to 0 */
223 add_path(rel, (Path *) create_append_path(rel, NIL));
225 /* Select cheapest path (pretty easy in this case...) */
232 * Generate paths and add them to the rel's pathlist.
234 * Note: add_path() will discard any paths that are dominated by another
235 * available path, keeping only those paths that are superior along at
236 * least one dimension of cost or sortedness.
239 /* Consider sequential scan */
240 add_path(rel, create_seqscan_path(root, rel));
242 /* Consider index scans */
243 create_index_paths(root, rel);
245 /* Consider TID scans */
246 create_tidscan_paths(root, rel);
248 /* Now find the cheapest of the paths for this rel */
253 * set_append_rel_pathlist
254 * Build access paths for an "append relation"
256 * The passed-in rel and RTE represent the entire append relation. The
257 * relation's contents are computed by appending together the output of
258 * the individual member relations. Note that in the inheritance case,
259 * the first member relation is actually the same table as is mentioned in
260 * the parent RTE ... but it has a different RTE and RelOptInfo. This is
261 * a good thing because their outputs are not the same size.
264 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
265 Index rti, RangeTblEntry *rte)
267 int parentRTindex = rti;
268 List *subpaths = NIL;
272 * XXX for now, can't handle inherited expansion of FOR UPDATE/SHARE; can
273 * we do better? (This will take some redesign because the executor
274 * currently supposes that every rowMark relation is involved in every row
275 * returned by the query.)
277 if (get_rowmark(root->parse, parentRTindex))
279 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
280 errmsg("SELECT FOR UPDATE/SHARE is not supported for inheritance queries")));
283 * Initialize to compute size estimates for whole append relation
289 * Generate access paths for each member relation, and pick the cheapest
292 foreach(l, root->append_rel_list)
294 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
296 RelOptInfo *childrel;
298 ListCell *parentvars;
301 /* append_rel_list contains all append rels; ignore others */
302 if (appinfo->parent_relid != parentRTindex)
305 childRTindex = appinfo->child_relid;
308 * The child rel's RelOptInfo was already created during
309 * add_base_rels_to_query.
311 childrel = find_base_rel(root, childRTindex);
312 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
315 * Copy the parent's targetlist and quals to the child, with
316 * appropriate substitution of variables.
318 childrel->reltargetlist = (List *)
319 adjust_appendrel_attrs((Node *) rel->reltargetlist,
321 childrel->baserestrictinfo = (List *)
322 adjust_appendrel_attrs((Node *) rel->baserestrictinfo,
324 childrel->joininfo = (List *)
325 adjust_appendrel_attrs((Node *) rel->joininfo,
329 * We have to make child entries in the EquivalenceClass data
330 * structures as well.
332 if (rel->has_eclass_joins)
334 add_child_rel_equivalences(root, appinfo, rel, childrel);
335 childrel->has_eclass_joins = true;
339 * Copy the parent's attr_needed data as well, with appropriate
340 * adjustment of relids and attribute numbers.
342 pfree(childrel->attr_needed);
343 childrel->attr_needed =
344 adjust_appendrel_attr_needed(rel, appinfo,
349 * Compute the child's access paths, and add the cheapest one to the
350 * Append path we are constructing for the parent.
352 * It's possible that the child is itself an appendrel, in which case
353 * we can "cut out the middleman" and just add its child paths to our
354 * own list. (We don't try to do this earlier because we need to
355 * apply both levels of transformation to the quals.) This test also
356 * handles the case where the child rel need not be scanned because of
357 * constraint exclusion: it'll have an Append path with no subpaths,
358 * and will vanish from our list.
360 set_rel_pathlist(root, childrel, childRTindex);
362 childpath = childrel->cheapest_total_path;
363 if (IsA(childpath, AppendPath))
364 subpaths = list_concat(subpaths,
365 ((AppendPath *) childpath)->subpaths);
367 subpaths = lappend(subpaths, childpath);
370 * Propagate size information from the child back to the parent. For
371 * simplicity, we use the largest widths from any child as the parent
374 rel->rows += childrel->rows;
375 if (childrel->width > rel->width)
376 rel->width = childrel->width;
378 forboth(parentvars, rel->reltargetlist,
379 childvars, childrel->reltargetlist)
381 Var *parentvar = (Var *) lfirst(parentvars);
382 Var *childvar = (Var *) lfirst(childvars);
384 if (IsA(parentvar, Var) &&
387 int pndx = parentvar->varattno - rel->min_attr;
388 int cndx = childvar->varattno - childrel->min_attr;
390 if (childrel->attr_widths[cndx] > rel->attr_widths[pndx])
391 rel->attr_widths[pndx] = childrel->attr_widths[cndx];
397 * Set "raw tuples" count equal to "rows" for the appendrel; needed
398 * because some places assume rel->tuples is valid for any baserel.
400 rel->tuples = rel->rows;
403 * Finally, build Append path and install it as the only access path for
404 * the parent rel. (Note: this is correct even if we have zero or one
405 * live subpath due to constraint exclusion.)
407 add_path(rel, (Path *) create_append_path(rel, subpaths));
409 /* Select cheapest path (pretty easy in this case...) */
413 /* quick-and-dirty test to see if any joining is needed */
415 has_multiple_baserels(PlannerInfo *root)
417 int num_base_rels = 0;
420 for (rti = 1; rti < root->simple_rel_array_size; rti++)
422 RelOptInfo *brel = root->simple_rel_array[rti];
427 /* ignore RTEs that are "other rels" */
428 if (brel->reloptkind == RELOPT_BASEREL)
429 if (++num_base_rels > 1)
436 * set_subquery_pathlist
437 * Build the (single) access path for a subquery RTE
440 set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
441 Index rti, RangeTblEntry *rte)
443 Query *parse = root->parse;
444 Query *subquery = rte->subquery;
445 bool *differentTypes;
446 double tuple_fraction;
448 List *subquery_pathkeys;
450 /* We need a workspace for keeping track of set-op type coercions */
451 differentTypes = (bool *)
452 palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
455 * If there are any restriction clauses that have been attached to the
456 * subquery relation, consider pushing them down to become WHERE or HAVING
457 * quals of the subquery itself. This transformation is useful because it
458 * may allow us to generate a better plan for the subquery than evaluating
459 * all the subquery output rows and then filtering them.
461 * There are several cases where we cannot push down clauses. Restrictions
462 * involving the subquery are checked by subquery_is_pushdown_safe().
463 * Restrictions on individual clauses are checked by
464 * qual_is_pushdown_safe(). Also, we don't want to push down
465 * pseudoconstant clauses; better to have the gating node above the
468 * Non-pushed-down clauses will get evaluated as qpquals of the
471 * XXX Are there any cases where we want to make a policy decision not to
472 * push down a pushable qual, because it'd result in a worse plan?
474 if (rel->baserestrictinfo != NIL &&
475 subquery_is_pushdown_safe(subquery, subquery, differentTypes))
477 /* OK to consider pushing down individual quals */
478 List *upperrestrictlist = NIL;
481 foreach(l, rel->baserestrictinfo)
483 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
484 Node *clause = (Node *) rinfo->clause;
486 if (!rinfo->pseudoconstant &&
487 qual_is_pushdown_safe(subquery, rti, clause, differentTypes))
490 subquery_push_qual(subquery, rte, rti, clause);
494 /* Keep it in the upper query */
495 upperrestrictlist = lappend(upperrestrictlist, rinfo);
498 rel->baserestrictinfo = upperrestrictlist;
501 pfree(differentTypes);
504 * We can safely pass the outer tuple_fraction down to the subquery if the
505 * outer level has no joining, aggregation, or sorting to do. Otherwise
506 * we'd better tell the subquery to plan for full retrieval. (XXX This
507 * could probably be made more intelligent ...)
509 if (parse->hasAggs ||
510 parse->groupClause ||
512 parse->distinctClause ||
514 has_multiple_baserels(root))
515 tuple_fraction = 0.0; /* default case */
517 tuple_fraction = root->tuple_fraction;
519 /* Generate the plan for the subquery */
520 rel->subplan = subquery_planner(subquery, tuple_fraction,
523 /* Copy number of output rows from subplan */
524 rel->tuples = rel->subplan->plan_rows;
526 /* Mark rel with estimated output rows, width, etc */
527 set_baserel_size_estimates(root, rel);
529 /* Convert subquery pathkeys to outer representation */
530 pathkeys = convert_subquery_pathkeys(root, rel, subquery_pathkeys);
532 /* Generate appropriate path */
533 add_path(rel, create_subqueryscan_path(rel, pathkeys));
535 /* Select cheapest path (pretty easy in this case...) */
540 * set_function_pathlist
541 * Build the (single) access path for a function RTE
544 set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
546 /* Mark rel with estimated output rows, width, etc */
547 set_function_size_estimates(root, rel);
549 /* Generate appropriate path */
550 add_path(rel, create_functionscan_path(root, rel));
552 /* Select cheapest path (pretty easy in this case...) */
557 * set_values_pathlist
558 * Build the (single) access path for a VALUES RTE
561 set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
563 /* Mark rel with estimated output rows, width, etc */
564 set_values_size_estimates(root, rel);
566 /* Generate appropriate path */
567 add_path(rel, create_valuesscan_path(root, rel));
569 /* Select cheapest path (pretty easy in this case...) */
574 * make_rel_from_joinlist
575 * Build access paths using a "joinlist" to guide the join path search.
577 * See comments for deconstruct_jointree() for definition of the joinlist
581 make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
588 * Count the number of child joinlist nodes. This is the depth of the
589 * dynamic-programming algorithm we must employ to consider all ways of
590 * joining the child nodes.
592 levels_needed = list_length(joinlist);
594 if (levels_needed <= 0)
595 return NULL; /* nothing to do? */
598 * Construct a list of rels corresponding to the child joinlist nodes.
599 * This may contain both base rels and rels constructed according to
603 foreach(jl, joinlist)
605 Node *jlnode = (Node *) lfirst(jl);
608 if (IsA(jlnode, RangeTblRef))
610 int varno = ((RangeTblRef *) jlnode)->rtindex;
612 thisrel = find_base_rel(root, varno);
614 else if (IsA(jlnode, List))
616 /* Recurse to handle subproblem */
617 thisrel = make_rel_from_joinlist(root, (List *) jlnode);
621 elog(ERROR, "unrecognized joinlist node type: %d",
622 (int) nodeTag(jlnode));
623 thisrel = NULL; /* keep compiler quiet */
626 initial_rels = lappend(initial_rels, thisrel);
629 if (levels_needed == 1)
632 * Single joinlist node, so we're done.
634 return (RelOptInfo *) linitial(initial_rels);
639 * Consider the different orders in which we could join the rels,
640 * using either GEQO or regular optimizer.
642 if (enable_geqo && levels_needed >= geqo_threshold)
643 return geqo(root, levels_needed, initial_rels);
645 return make_one_rel_by_joins(root, levels_needed, initial_rels);
650 * make_one_rel_by_joins
651 * Find all possible joinpaths for a query by successively finding ways
652 * to join component relations into join relations.
654 * 'levels_needed' is the number of iterations needed, ie, the number of
655 * independent jointree items in the query. This is > 1.
657 * 'initial_rels' is a list of RelOptInfo nodes for each independent
658 * jointree item. These are the components to be joined together.
660 * Returns the final level of join relations, i.e., the relation that is
661 * the result of joining all the original relations together.
664 make_one_rel_by_joins(PlannerInfo *root, int levels_needed, List *initial_rels)
671 * We employ a simple "dynamic programming" algorithm: we first find all
672 * ways to build joins of two jointree items, then all ways to build joins
673 * of three items (from two-item joins and single items), then four-item
674 * joins, and so on until we have considered all ways to join all the
675 * items into one rel.
677 * joinitems[j] is a list of all the j-item rels. Initially we set
678 * joinitems[1] to represent all the single-jointree-item relations.
680 joinitems = (List **) palloc0((levels_needed + 1) * sizeof(List *));
682 joinitems[1] = initial_rels;
684 for (lev = 2; lev <= levels_needed; lev++)
689 * Determine all possible pairs of relations to be joined at this
690 * level, and build paths for making each one from every available
691 * pair of lower-level relations.
693 joinitems[lev] = make_rels_by_joins(root, lev, joinitems);
696 * Do cleanup work on each just-processed rel.
698 foreach(x, joinitems[lev])
700 rel = (RelOptInfo *) lfirst(x);
702 /* Find and save the cheapest paths for this rel */
705 #ifdef OPTIMIZER_DEBUG
706 debug_print_rel(root, rel);
712 * We should have a single rel at the final level.
714 if (joinitems[levels_needed] == NIL)
715 elog(ERROR, "failed to build any %d-way joins", levels_needed);
716 Assert(list_length(joinitems[levels_needed]) == 1);
718 rel = (RelOptInfo *) linitial(joinitems[levels_needed]);
723 /*****************************************************************************
724 * PUSHING QUALS DOWN INTO SUBQUERIES
725 *****************************************************************************/
728 * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
730 * subquery is the particular component query being checked. topquery
731 * is the top component of a set-operations tree (the same Query if no
732 * set-op is involved).
734 * Conditions checked here:
736 * 1. If the subquery has a LIMIT clause, we must not push down any quals,
737 * since that could change the set of rows returned.
739 * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
740 * quals into it, because that would change the results.
742 * 3. For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
743 * push quals into each component query, but the quals can only reference
744 * subquery columns that suffer no type coercions in the set operation.
745 * Otherwise there are possible semantic gotchas. So, we check the
746 * component queries to see if any of them have different output types;
747 * differentTypes[k] is set true if column k has different type in any
751 subquery_is_pushdown_safe(Query *subquery, Query *topquery,
752 bool *differentTypes)
754 SetOperationStmt *topop;
757 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
760 /* Are we at top level, or looking at a setop component? */
761 if (subquery == topquery)
763 /* Top level, so check any component queries */
764 if (subquery->setOperations != NULL)
765 if (!recurse_pushdown_safe(subquery->setOperations, topquery,
771 /* Setop component must not have more components (too weird) */
772 if (subquery->setOperations != NULL)
774 /* Check whether setop component output types match top level */
775 topop = (SetOperationStmt *) topquery->setOperations;
776 Assert(topop && IsA(topop, SetOperationStmt));
777 compare_tlist_datatypes(subquery->targetList,
785 * Helper routine to recurse through setOperations tree
788 recurse_pushdown_safe(Node *setOp, Query *topquery,
789 bool *differentTypes)
791 if (IsA(setOp, RangeTblRef))
793 RangeTblRef *rtr = (RangeTblRef *) setOp;
794 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
795 Query *subquery = rte->subquery;
797 Assert(subquery != NULL);
798 return subquery_is_pushdown_safe(subquery, topquery, differentTypes);
800 else if (IsA(setOp, SetOperationStmt))
802 SetOperationStmt *op = (SetOperationStmt *) setOp;
804 /* EXCEPT is no good */
805 if (op->op == SETOP_EXCEPT)
808 if (!recurse_pushdown_safe(op->larg, topquery, differentTypes))
810 if (!recurse_pushdown_safe(op->rarg, topquery, differentTypes))
815 elog(ERROR, "unrecognized node type: %d",
816 (int) nodeTag(setOp));
822 * Compare tlist's datatypes against the list of set-operation result types.
823 * For any items that are different, mark the appropriate element of
824 * differentTypes[] to show that this column will have type conversions.
826 * We don't have to care about typmods here: the only allowed difference
827 * between set-op input and output typmods is input is a specific typmod
828 * and output is -1, and that does not require a coercion.
831 compare_tlist_datatypes(List *tlist, List *colTypes,
832 bool *differentTypes)
835 ListCell *colType = list_head(colTypes);
839 TargetEntry *tle = (TargetEntry *) lfirst(l);
842 continue; /* ignore resjunk columns */
844 elog(ERROR, "wrong number of tlist entries");
845 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
846 differentTypes[tle->resno] = true;
847 colType = lnext(colType);
850 elog(ERROR, "wrong number of tlist entries");
854 * qual_is_pushdown_safe - is a particular qual safe to push down?
856 * qual is a restriction clause applying to the given subquery (whose RTE
857 * has index rti in the parent query).
859 * Conditions checked here:
861 * 1. The qual must not contain any subselects (mainly because I'm not sure
862 * it will work correctly: sublinks will already have been transformed into
863 * subplans in the qual, but not in the subquery).
865 * 2. The qual must not refer to the whole-row output of the subquery
866 * (since there is no easy way to name that within the subquery itself).
868 * 3. The qual must not refer to any subquery output columns that were
869 * found to have inconsistent types across a set operation tree by
870 * subquery_is_pushdown_safe().
872 * 4. If the subquery uses DISTINCT ON, we must not push down any quals that
873 * refer to non-DISTINCT output columns, because that could change the set
874 * of rows returned. This condition is vacuous for DISTINCT, because then
875 * there are no non-DISTINCT output columns, but unfortunately it's fairly
876 * expensive to tell the difference between DISTINCT and DISTINCT ON in the
877 * parsetree representation. It's cheaper to just make sure all the Vars
878 * in the qual refer to DISTINCT columns.
880 * 5. We must not push down any quals that refer to subselect outputs that
881 * return sets, else we'd introduce functions-returning-sets into the
882 * subquery's WHERE/HAVING quals.
884 * 6. We must not push down any quals that refer to subselect outputs that
885 * contain volatile functions, for fear of introducing strange results due
886 * to multiple evaluation of a volatile function.
889 qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
890 bool *differentTypes)
895 Bitmapset *tested = NULL;
897 /* Refuse subselects (point 1) */
898 if (contain_subplans(qual))
902 * Examine all Vars used in clause; since it's a restriction clause, all
903 * such Vars must refer to subselect output columns.
905 vars = pull_var_clause(qual, false);
908 Var *var = (Var *) lfirst(vl);
911 Assert(var->varno == rti);
914 if (var->varattno == 0)
921 * We use a bitmapset to avoid testing the same attno more than once.
922 * (NB: this only works because subquery outputs can't have negative
925 if (bms_is_member(var->varattno, tested))
927 tested = bms_add_member(tested, var->varattno);
930 if (differentTypes[var->varattno])
936 /* Must find the tlist element referenced by the Var */
937 tle = get_tle_by_resno(subquery->targetList, var->varattno);
939 Assert(!tle->resjunk);
941 /* If subquery uses DISTINCT or DISTINCT ON, check point 4 */
942 if (subquery->distinctClause != NIL &&
943 !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
945 /* non-DISTINCT column, so fail */
950 /* Refuse functions returning sets (point 5) */
951 if (expression_returns_set((Node *) tle->expr))
957 /* Refuse volatile functions (point 6) */
958 if (contain_volatile_functions((Node *) tle->expr))
972 * subquery_push_qual - push down a qual that we have determined is safe
975 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
977 if (subquery->setOperations != NULL)
979 /* Recurse to push it separately to each component query */
980 recurse_push_qual(subquery->setOperations, subquery,
986 * We need to replace Vars in the qual (which must refer to outputs of
987 * the subquery) with copies of the subquery's targetlist expressions.
988 * Note that at this point, any uplevel Vars in the qual should have
989 * been replaced with Params, so they need no work.
991 * This step also ensures that when we are pushing into a setop tree,
992 * each component query gets its own copy of the qual.
994 qual = ResolveNew(qual, rti, 0, rte,
995 subquery->targetList,
999 * Now attach the qual to the proper place: normally WHERE, but if the
1000 * subquery uses grouping or aggregation, put it in HAVING (since the
1001 * qual really refers to the group-result rows).
1003 if (subquery->hasAggs || subquery->groupClause || subquery->havingQual)
1004 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
1006 subquery->jointree->quals =
1007 make_and_qual(subquery->jointree->quals, qual);
1010 * We need not change the subquery's hasAggs or hasSublinks flags,
1011 * since we can't be pushing down any aggregates that weren't there
1012 * before, and we don't push down subselects at all.
1018 * Helper routine to recurse through setOperations tree
1021 recurse_push_qual(Node *setOp, Query *topquery,
1022 RangeTblEntry *rte, Index rti, Node *qual)
1024 if (IsA(setOp, RangeTblRef))
1026 RangeTblRef *rtr = (RangeTblRef *) setOp;
1027 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
1028 Query *subquery = subrte->subquery;
1030 Assert(subquery != NULL);
1031 subquery_push_qual(subquery, rte, rti, qual);
1033 else if (IsA(setOp, SetOperationStmt))
1035 SetOperationStmt *op = (SetOperationStmt *) setOp;
1037 recurse_push_qual(op->larg, topquery, rte, rti, qual);
1038 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
1042 elog(ERROR, "unrecognized node type: %d",
1043 (int) nodeTag(setOp));
1047 /*****************************************************************************
1049 *****************************************************************************/
1051 #ifdef OPTIMIZER_DEBUG
1054 print_relids(Relids relids)
1060 tmprelids = bms_copy(relids);
1061 while ((x = bms_first_member(tmprelids)) >= 0)
1068 bms_free(tmprelids);
1072 print_restrictclauses(PlannerInfo *root, List *clauses)
1078 RestrictInfo *c = lfirst(l);
1080 print_expr((Node *) c->clause, root->parse->rtable);
1087 print_path(PlannerInfo *root, Path *path, int indent)
1091 Path *subpath = NULL;
1094 switch (nodeTag(path))
1102 case T_BitmapHeapPath:
1103 ptype = "BitmapHeapScan";
1105 case T_BitmapAndPath:
1106 ptype = "BitmapAndPath";
1108 case T_BitmapOrPath:
1109 ptype = "BitmapOrPath";
1120 case T_MaterialPath:
1122 subpath = ((MaterialPath *) path)->subpath;
1126 subpath = ((UniquePath *) path)->subpath;
1133 ptype = "MergeJoin";
1145 for (i = 0; i < indent; i++)
1147 printf("%s", ptype);
1152 print_relids(path->parent->relids);
1153 printf(") rows=%.0f", path->parent->rows);
1155 printf(" cost=%.2f..%.2f\n", path->startup_cost, path->total_cost);
1159 for (i = 0; i < indent; i++)
1161 printf(" pathkeys: ");
1162 print_pathkeys(path->pathkeys, root->parse->rtable);
1167 JoinPath *jp = (JoinPath *) path;
1169 for (i = 0; i < indent; i++)
1171 printf(" clauses: ");
1172 print_restrictclauses(root, jp->joinrestrictinfo);
1175 if (IsA(path, MergePath))
1177 MergePath *mp = (MergePath *) path;
1179 if (mp->outersortkeys || mp->innersortkeys)
1181 for (i = 0; i < indent; i++)
1183 printf(" sortouter=%d sortinner=%d\n",
1184 ((mp->outersortkeys) ? 1 : 0),
1185 ((mp->innersortkeys) ? 1 : 0));
1189 print_path(root, jp->outerjoinpath, indent + 1);
1190 print_path(root, jp->innerjoinpath, indent + 1);
1194 print_path(root, subpath, indent + 1);
1198 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
1202 printf("RELOPTINFO (");
1203 print_relids(rel->relids);
1204 printf("): rows=%.0f width=%d\n", rel->rows, rel->width);
1206 if (rel->baserestrictinfo)
1208 printf("\tbaserestrictinfo: ");
1209 print_restrictclauses(root, rel->baserestrictinfo);
1215 printf("\tjoininfo: ");
1216 print_restrictclauses(root, rel->joininfo);
1220 printf("\tpath list:\n");
1221 foreach(l, rel->pathlist)
1222 print_path(root, lfirst(l), 1);
1223 printf("\n\tcheapest startup path:\n");
1224 print_path(root, rel->cheapest_startup_path, 1);
1225 printf("\n\tcheapest total path:\n");
1226 print_path(root, rel->cheapest_total_path, 1);
1231 #endif /* OPTIMIZER_DEBUG */