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.159 2007/02/19 07:03:28 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(root->glob, subquery,
521 root->query_level + 1,
525 /* Copy number of output rows from subplan */
526 rel->tuples = rel->subplan->plan_rows;
528 /* Mark rel with estimated output rows, width, etc */
529 set_baserel_size_estimates(root, rel);
531 /* Convert subquery pathkeys to outer representation */
532 pathkeys = convert_subquery_pathkeys(root, rel, subquery_pathkeys);
534 /* Generate appropriate path */
535 add_path(rel, create_subqueryscan_path(rel, pathkeys));
537 /* Select cheapest path (pretty easy in this case...) */
542 * set_function_pathlist
543 * Build the (single) access path for a function RTE
546 set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
548 /* Mark rel with estimated output rows, width, etc */
549 set_function_size_estimates(root, rel);
551 /* Generate appropriate path */
552 add_path(rel, create_functionscan_path(root, rel));
554 /* Select cheapest path (pretty easy in this case...) */
559 * set_values_pathlist
560 * Build the (single) access path for a VALUES RTE
563 set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
565 /* Mark rel with estimated output rows, width, etc */
566 set_values_size_estimates(root, rel);
568 /* Generate appropriate path */
569 add_path(rel, create_valuesscan_path(root, rel));
571 /* Select cheapest path (pretty easy in this case...) */
576 * make_rel_from_joinlist
577 * Build access paths using a "joinlist" to guide the join path search.
579 * See comments for deconstruct_jointree() for definition of the joinlist
583 make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
590 * Count the number of child joinlist nodes. This is the depth of the
591 * dynamic-programming algorithm we must employ to consider all ways of
592 * joining the child nodes.
594 levels_needed = list_length(joinlist);
596 if (levels_needed <= 0)
597 return NULL; /* nothing to do? */
600 * Construct a list of rels corresponding to the child joinlist nodes.
601 * This may contain both base rels and rels constructed according to
605 foreach(jl, joinlist)
607 Node *jlnode = (Node *) lfirst(jl);
610 if (IsA(jlnode, RangeTblRef))
612 int varno = ((RangeTblRef *) jlnode)->rtindex;
614 thisrel = find_base_rel(root, varno);
616 else if (IsA(jlnode, List))
618 /* Recurse to handle subproblem */
619 thisrel = make_rel_from_joinlist(root, (List *) jlnode);
623 elog(ERROR, "unrecognized joinlist node type: %d",
624 (int) nodeTag(jlnode));
625 thisrel = NULL; /* keep compiler quiet */
628 initial_rels = lappend(initial_rels, thisrel);
631 if (levels_needed == 1)
634 * Single joinlist node, so we're done.
636 return (RelOptInfo *) linitial(initial_rels);
641 * Consider the different orders in which we could join the rels,
642 * using either GEQO or regular optimizer.
644 if (enable_geqo && levels_needed >= geqo_threshold)
645 return geqo(root, levels_needed, initial_rels);
647 return make_one_rel_by_joins(root, levels_needed, initial_rels);
652 * make_one_rel_by_joins
653 * Find all possible joinpaths for a query by successively finding ways
654 * to join component relations into join relations.
656 * 'levels_needed' is the number of iterations needed, ie, the number of
657 * independent jointree items in the query. This is > 1.
659 * 'initial_rels' is a list of RelOptInfo nodes for each independent
660 * jointree item. These are the components to be joined together.
662 * Returns the final level of join relations, i.e., the relation that is
663 * the result of joining all the original relations together.
666 make_one_rel_by_joins(PlannerInfo *root, int levels_needed, List *initial_rels)
673 * We employ a simple "dynamic programming" algorithm: we first find all
674 * ways to build joins of two jointree items, then all ways to build joins
675 * of three items (from two-item joins and single items), then four-item
676 * joins, and so on until we have considered all ways to join all the
677 * items into one rel.
679 * joinitems[j] is a list of all the j-item rels. Initially we set
680 * joinitems[1] to represent all the single-jointree-item relations.
682 joinitems = (List **) palloc0((levels_needed + 1) * sizeof(List *));
684 joinitems[1] = initial_rels;
686 for (lev = 2; lev <= levels_needed; lev++)
691 * Determine all possible pairs of relations to be joined at this
692 * level, and build paths for making each one from every available
693 * pair of lower-level relations.
695 joinitems[lev] = make_rels_by_joins(root, lev, joinitems);
698 * Do cleanup work on each just-processed rel.
700 foreach(x, joinitems[lev])
702 rel = (RelOptInfo *) lfirst(x);
704 /* Find and save the cheapest paths for this rel */
707 #ifdef OPTIMIZER_DEBUG
708 debug_print_rel(root, rel);
714 * We should have a single rel at the final level.
716 if (joinitems[levels_needed] == NIL)
717 elog(ERROR, "failed to build any %d-way joins", levels_needed);
718 Assert(list_length(joinitems[levels_needed]) == 1);
720 rel = (RelOptInfo *) linitial(joinitems[levels_needed]);
725 /*****************************************************************************
726 * PUSHING QUALS DOWN INTO SUBQUERIES
727 *****************************************************************************/
730 * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
732 * subquery is the particular component query being checked. topquery
733 * is the top component of a set-operations tree (the same Query if no
734 * set-op is involved).
736 * Conditions checked here:
738 * 1. If the subquery has a LIMIT clause, we must not push down any quals,
739 * since that could change the set of rows returned.
741 * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
742 * quals into it, because that would change the results.
744 * 3. For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
745 * push quals into each component query, but the quals can only reference
746 * subquery columns that suffer no type coercions in the set operation.
747 * Otherwise there are possible semantic gotchas. So, we check the
748 * component queries to see if any of them have different output types;
749 * differentTypes[k] is set true if column k has different type in any
753 subquery_is_pushdown_safe(Query *subquery, Query *topquery,
754 bool *differentTypes)
756 SetOperationStmt *topop;
759 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
762 /* Are we at top level, or looking at a setop component? */
763 if (subquery == topquery)
765 /* Top level, so check any component queries */
766 if (subquery->setOperations != NULL)
767 if (!recurse_pushdown_safe(subquery->setOperations, topquery,
773 /* Setop component must not have more components (too weird) */
774 if (subquery->setOperations != NULL)
776 /* Check whether setop component output types match top level */
777 topop = (SetOperationStmt *) topquery->setOperations;
778 Assert(topop && IsA(topop, SetOperationStmt));
779 compare_tlist_datatypes(subquery->targetList,
787 * Helper routine to recurse through setOperations tree
790 recurse_pushdown_safe(Node *setOp, Query *topquery,
791 bool *differentTypes)
793 if (IsA(setOp, RangeTblRef))
795 RangeTblRef *rtr = (RangeTblRef *) setOp;
796 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
797 Query *subquery = rte->subquery;
799 Assert(subquery != NULL);
800 return subquery_is_pushdown_safe(subquery, topquery, differentTypes);
802 else if (IsA(setOp, SetOperationStmt))
804 SetOperationStmt *op = (SetOperationStmt *) setOp;
806 /* EXCEPT is no good */
807 if (op->op == SETOP_EXCEPT)
810 if (!recurse_pushdown_safe(op->larg, topquery, differentTypes))
812 if (!recurse_pushdown_safe(op->rarg, topquery, differentTypes))
817 elog(ERROR, "unrecognized node type: %d",
818 (int) nodeTag(setOp));
824 * Compare tlist's datatypes against the list of set-operation result types.
825 * For any items that are different, mark the appropriate element of
826 * differentTypes[] to show that this column will have type conversions.
828 * We don't have to care about typmods here: the only allowed difference
829 * between set-op input and output typmods is input is a specific typmod
830 * and output is -1, and that does not require a coercion.
833 compare_tlist_datatypes(List *tlist, List *colTypes,
834 bool *differentTypes)
837 ListCell *colType = list_head(colTypes);
841 TargetEntry *tle = (TargetEntry *) lfirst(l);
844 continue; /* ignore resjunk columns */
846 elog(ERROR, "wrong number of tlist entries");
847 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
848 differentTypes[tle->resno] = true;
849 colType = lnext(colType);
852 elog(ERROR, "wrong number of tlist entries");
856 * qual_is_pushdown_safe - is a particular qual safe to push down?
858 * qual is a restriction clause applying to the given subquery (whose RTE
859 * has index rti in the parent query).
861 * Conditions checked here:
863 * 1. The qual must not contain any subselects (mainly because I'm not sure
864 * it will work correctly: sublinks will already have been transformed into
865 * subplans in the qual, but not in the subquery).
867 * 2. The qual must not refer to the whole-row output of the subquery
868 * (since there is no easy way to name that within the subquery itself).
870 * 3. The qual must not refer to any subquery output columns that were
871 * found to have inconsistent types across a set operation tree by
872 * subquery_is_pushdown_safe().
874 * 4. If the subquery uses DISTINCT ON, we must not push down any quals that
875 * refer to non-DISTINCT output columns, because that could change the set
876 * of rows returned. This condition is vacuous for DISTINCT, because then
877 * there are no non-DISTINCT output columns, but unfortunately it's fairly
878 * expensive to tell the difference between DISTINCT and DISTINCT ON in the
879 * parsetree representation. It's cheaper to just make sure all the Vars
880 * in the qual refer to DISTINCT columns.
882 * 5. We must not push down any quals that refer to subselect outputs that
883 * return sets, else we'd introduce functions-returning-sets into the
884 * subquery's WHERE/HAVING quals.
886 * 6. We must not push down any quals that refer to subselect outputs that
887 * contain volatile functions, for fear of introducing strange results due
888 * to multiple evaluation of a volatile function.
891 qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
892 bool *differentTypes)
897 Bitmapset *tested = NULL;
899 /* Refuse subselects (point 1) */
900 if (contain_subplans(qual))
904 * Examine all Vars used in clause; since it's a restriction clause, all
905 * such Vars must refer to subselect output columns.
907 vars = pull_var_clause(qual, false);
910 Var *var = (Var *) lfirst(vl);
913 Assert(var->varno == rti);
916 if (var->varattno == 0)
923 * We use a bitmapset to avoid testing the same attno more than once.
924 * (NB: this only works because subquery outputs can't have negative
927 if (bms_is_member(var->varattno, tested))
929 tested = bms_add_member(tested, var->varattno);
932 if (differentTypes[var->varattno])
938 /* Must find the tlist element referenced by the Var */
939 tle = get_tle_by_resno(subquery->targetList, var->varattno);
941 Assert(!tle->resjunk);
943 /* If subquery uses DISTINCT or DISTINCT ON, check point 4 */
944 if (subquery->distinctClause != NIL &&
945 !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
947 /* non-DISTINCT column, so fail */
952 /* Refuse functions returning sets (point 5) */
953 if (expression_returns_set((Node *) tle->expr))
959 /* Refuse volatile functions (point 6) */
960 if (contain_volatile_functions((Node *) tle->expr))
974 * subquery_push_qual - push down a qual that we have determined is safe
977 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
979 if (subquery->setOperations != NULL)
981 /* Recurse to push it separately to each component query */
982 recurse_push_qual(subquery->setOperations, subquery,
988 * We need to replace Vars in the qual (which must refer to outputs of
989 * the subquery) with copies of the subquery's targetlist expressions.
990 * Note that at this point, any uplevel Vars in the qual should have
991 * been replaced with Params, so they need no work.
993 * This step also ensures that when we are pushing into a setop tree,
994 * each component query gets its own copy of the qual.
996 qual = ResolveNew(qual, rti, 0, rte,
997 subquery->targetList,
1001 * Now attach the qual to the proper place: normally WHERE, but if the
1002 * subquery uses grouping or aggregation, put it in HAVING (since the
1003 * qual really refers to the group-result rows).
1005 if (subquery->hasAggs || subquery->groupClause || subquery->havingQual)
1006 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
1008 subquery->jointree->quals =
1009 make_and_qual(subquery->jointree->quals, qual);
1012 * We need not change the subquery's hasAggs or hasSublinks flags,
1013 * since we can't be pushing down any aggregates that weren't there
1014 * before, and we don't push down subselects at all.
1020 * Helper routine to recurse through setOperations tree
1023 recurse_push_qual(Node *setOp, Query *topquery,
1024 RangeTblEntry *rte, Index rti, Node *qual)
1026 if (IsA(setOp, RangeTblRef))
1028 RangeTblRef *rtr = (RangeTblRef *) setOp;
1029 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
1030 Query *subquery = subrte->subquery;
1032 Assert(subquery != NULL);
1033 subquery_push_qual(subquery, rte, rti, qual);
1035 else if (IsA(setOp, SetOperationStmt))
1037 SetOperationStmt *op = (SetOperationStmt *) setOp;
1039 recurse_push_qual(op->larg, topquery, rte, rti, qual);
1040 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
1044 elog(ERROR, "unrecognized node type: %d",
1045 (int) nodeTag(setOp));
1049 /*****************************************************************************
1051 *****************************************************************************/
1053 #ifdef OPTIMIZER_DEBUG
1056 print_relids(Relids relids)
1062 tmprelids = bms_copy(relids);
1063 while ((x = bms_first_member(tmprelids)) >= 0)
1070 bms_free(tmprelids);
1074 print_restrictclauses(PlannerInfo *root, List *clauses)
1080 RestrictInfo *c = lfirst(l);
1082 print_expr((Node *) c->clause, root->parse->rtable);
1089 print_path(PlannerInfo *root, Path *path, int indent)
1093 Path *subpath = NULL;
1096 switch (nodeTag(path))
1104 case T_BitmapHeapPath:
1105 ptype = "BitmapHeapScan";
1107 case T_BitmapAndPath:
1108 ptype = "BitmapAndPath";
1110 case T_BitmapOrPath:
1111 ptype = "BitmapOrPath";
1122 case T_MaterialPath:
1124 subpath = ((MaterialPath *) path)->subpath;
1128 subpath = ((UniquePath *) path)->subpath;
1135 ptype = "MergeJoin";
1147 for (i = 0; i < indent; i++)
1149 printf("%s", ptype);
1154 print_relids(path->parent->relids);
1155 printf(") rows=%.0f", path->parent->rows);
1157 printf(" cost=%.2f..%.2f\n", path->startup_cost, path->total_cost);
1161 for (i = 0; i < indent; i++)
1163 printf(" pathkeys: ");
1164 print_pathkeys(path->pathkeys, root->parse->rtable);
1169 JoinPath *jp = (JoinPath *) path;
1171 for (i = 0; i < indent; i++)
1173 printf(" clauses: ");
1174 print_restrictclauses(root, jp->joinrestrictinfo);
1177 if (IsA(path, MergePath))
1179 MergePath *mp = (MergePath *) path;
1181 if (mp->outersortkeys || mp->innersortkeys)
1183 for (i = 0; i < indent; i++)
1185 printf(" sortouter=%d sortinner=%d\n",
1186 ((mp->outersortkeys) ? 1 : 0),
1187 ((mp->innersortkeys) ? 1 : 0));
1191 print_path(root, jp->outerjoinpath, indent + 1);
1192 print_path(root, jp->innerjoinpath, indent + 1);
1196 print_path(root, subpath, indent + 1);
1200 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
1204 printf("RELOPTINFO (");
1205 print_relids(rel->relids);
1206 printf("): rows=%.0f width=%d\n", rel->rows, rel->width);
1208 if (rel->baserestrictinfo)
1210 printf("\tbaserestrictinfo: ");
1211 print_restrictclauses(root, rel->baserestrictinfo);
1217 printf("\tjoininfo: ");
1218 print_restrictclauses(root, rel->joininfo);
1222 printf("\tpath list:\n");
1223 foreach(l, rel->pathlist)
1224 print_path(root, lfirst(l), 1);
1225 printf("\n\tcheapest startup path:\n");
1226 print_path(root, rel->cheapest_startup_path, 1);
1227 printf("\n\tcheapest total path:\n");
1228 print_path(root, rel->cheapest_total_path, 1);
1233 #endif /* OPTIMIZER_DEBUG */