1 /*-------------------------------------------------------------------------
4 * Routines to find possible search paths for processing a query
6 * Portions Copyright (c) 1996-2008, 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.167 2008/01/01 19:45:50 momjian 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 */
40 /* Hook for plugins to replace standard_join_search() */
41 join_search_hook_type join_search_hook = NULL;
44 static void set_base_rel_pathlists(PlannerInfo *root);
45 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
46 Index rti, RangeTblEntry *rte);
47 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
49 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
50 Index rti, RangeTblEntry *rte);
51 static void set_dummy_rel_pathlist(RelOptInfo *rel);
52 static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
53 Index rti, RangeTblEntry *rte);
54 static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
56 static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel,
58 static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
59 static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
60 bool *differentTypes);
61 static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
62 bool *differentTypes);
63 static void compare_tlist_datatypes(List *tlist, List *colTypes,
64 bool *differentTypes);
65 static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
66 bool *differentTypes);
67 static void subquery_push_qual(Query *subquery,
68 RangeTblEntry *rte, Index rti, Node *qual);
69 static void recurse_push_qual(Node *setOp, Query *topquery,
70 RangeTblEntry *rte, Index rti, Node *qual);
75 * Finds all possible access paths for executing a query, returning a
76 * single rel that represents the join of all base rels in the query.
79 make_one_rel(PlannerInfo *root, List *joinlist)
84 * Generate access paths for the base rels.
86 set_base_rel_pathlists(root);
89 * Generate access paths for the entire join tree.
91 rel = make_rel_from_joinlist(root, joinlist);
94 * The result should join all and only the query's base rels.
96 #ifdef USE_ASSERT_CHECKING
98 int num_base_rels = 0;
101 for (rti = 1; rti < root->simple_rel_array_size; rti++)
103 RelOptInfo *brel = root->simple_rel_array[rti];
108 Assert(brel->relid == rti); /* sanity check on array */
110 /* ignore RTEs that are "other rels" */
111 if (brel->reloptkind != RELOPT_BASEREL)
114 Assert(bms_is_member(rti, rel->relids));
118 Assert(bms_num_members(rel->relids) == num_base_rels);
126 * set_base_rel_pathlists
127 * Finds all paths available for scanning each base-relation entry.
128 * Sequential scan and any available indices are considered.
129 * Each useful path is attached to its relation's 'pathlist' field.
132 set_base_rel_pathlists(PlannerInfo *root)
136 for (rti = 1; rti < root->simple_rel_array_size; rti++)
138 RelOptInfo *rel = root->simple_rel_array[rti];
140 /* there may be empty slots corresponding to non-baserel RTEs */
144 Assert(rel->relid == rti); /* sanity check on array */
146 /* ignore RTEs that are "other rels" */
147 if (rel->reloptkind != RELOPT_BASEREL)
150 set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
156 * Build access paths for a base relation
159 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
160 Index rti, RangeTblEntry *rte)
164 /* It's an "append relation", process accordingly */
165 set_append_rel_pathlist(root, rel, rti, rte);
167 else if (rel->rtekind == RTE_SUBQUERY)
169 /* Subquery --- generate a separate plan for it */
170 set_subquery_pathlist(root, rel, rti, rte);
172 else if (rel->rtekind == RTE_FUNCTION)
174 /* RangeFunction --- generate a separate plan for it */
175 set_function_pathlist(root, rel, rte);
177 else if (rel->rtekind == RTE_VALUES)
179 /* Values list --- generate a separate plan for it */
180 set_values_pathlist(root, rel, rte);
185 Assert(rel->rtekind == RTE_RELATION);
186 set_plain_rel_pathlist(root, rel, rte);
189 #ifdef OPTIMIZER_DEBUG
190 debug_print_rel(root, rel);
195 * set_plain_rel_pathlist
196 * Build access paths for a plain relation (no subquery, no inheritance)
199 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
202 * If we can prove we don't need to scan the rel via constraint exclusion,
203 * set up a single dummy path for it. We only need to check for regular
204 * baserels; if it's an otherrel, CE was already checked in
205 * set_append_rel_pathlist().
207 if (rel->reloptkind == RELOPT_BASEREL &&
208 relation_excluded_by_constraints(rel, rte))
210 set_dummy_rel_pathlist(rel);
214 /* Mark rel with estimated output rows, width, etc */
215 set_baserel_size_estimates(root, rel);
217 /* Test any partial indexes of rel for applicability */
218 check_partial_indexes(root, rel);
221 * Check to see if we can extract any restriction conditions from join
222 * quals that are OR-of-AND structures. If so, add them to the rel's
223 * restriction list, and recompute the size estimates.
225 if (create_or_index_quals(root, rel))
226 set_baserel_size_estimates(root, rel);
229 * Generate paths and add them to the rel's pathlist.
231 * Note: add_path() will discard any paths that are dominated by another
232 * available path, keeping only those paths that are superior along at
233 * least one dimension of cost or sortedness.
236 /* Consider sequential scan */
237 add_path(rel, create_seqscan_path(root, rel));
239 /* Consider index scans */
240 create_index_paths(root, rel);
242 /* Consider TID scans */
243 create_tidscan_paths(root, rel);
245 /* Now find the cheapest of the paths for this rel */
250 * set_append_rel_pathlist
251 * Build access paths for an "append relation"
253 * The passed-in rel and RTE represent the entire append relation. The
254 * relation's contents are computed by appending together the output of
255 * the individual member relations. Note that in the inheritance case,
256 * the first member relation is actually the same table as is mentioned in
257 * the parent RTE ... but it has a different RTE and RelOptInfo. This is
258 * a good thing because their outputs are not the same size.
261 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
262 Index rti, RangeTblEntry *rte)
264 int parentRTindex = rti;
265 List *subpaths = NIL;
269 * XXX for now, can't handle inherited expansion of FOR UPDATE/SHARE; can
270 * we do better? (This will take some redesign because the executor
271 * currently supposes that every rowMark relation is involved in every row
272 * returned by the query.)
274 if (get_rowmark(root->parse, parentRTindex))
276 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
277 errmsg("SELECT FOR UPDATE/SHARE is not supported for inheritance queries")));
280 * Initialize to compute size estimates for whole append relation
286 * Generate access paths for each member relation, and pick the cheapest
289 foreach(l, root->append_rel_list)
291 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
293 RangeTblEntry *childRTE;
294 RelOptInfo *childrel;
296 ListCell *parentvars;
299 /* append_rel_list contains all append rels; ignore others */
300 if (appinfo->parent_relid != parentRTindex)
303 childRTindex = appinfo->child_relid;
304 childRTE = root->simple_rte_array[childRTindex];
307 * The child rel's RelOptInfo was already created during
308 * add_base_rels_to_query.
310 childrel = find_base_rel(root, childRTindex);
311 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
314 * We have to copy the parent's targetlist and quals to the child,
315 * with appropriate substitution of variables. However, only the
316 * baserestrictinfo quals are needed before we can check for
317 * constraint exclusion; so do that first and then check to see if we
318 * can disregard this child.
320 childrel->baserestrictinfo = (List *)
321 adjust_appendrel_attrs((Node *) rel->baserestrictinfo,
324 if (relation_excluded_by_constraints(childrel, childRTE))
327 * This child need not be scanned, so we can omit it from the
328 * appendrel. Mark it with a dummy cheapest-path though, in case
329 * best_appendrel_indexscan() looks at it later.
331 set_dummy_rel_pathlist(childrel);
335 /* CE failed, so finish copying targetlist and join quals */
336 childrel->joininfo = (List *)
337 adjust_appendrel_attrs((Node *) rel->joininfo,
339 childrel->reltargetlist = (List *)
340 adjust_appendrel_attrs((Node *) rel->reltargetlist,
344 * We have to make child entries in the EquivalenceClass data
345 * structures as well.
347 if (rel->has_eclass_joins)
349 add_child_rel_equivalences(root, appinfo, rel, childrel);
350 childrel->has_eclass_joins = true;
354 * Copy the parent's attr_needed data as well, with appropriate
355 * adjustment of relids and attribute numbers.
357 pfree(childrel->attr_needed);
358 childrel->attr_needed =
359 adjust_appendrel_attr_needed(rel, appinfo,
364 * Compute the child's access paths, and add the cheapest one to the
365 * Append path we are constructing for the parent.
367 * It's possible that the child is itself an appendrel, in which case
368 * we can "cut out the middleman" and just add its child paths to our
369 * own list. (We don't try to do this earlier because we need to
370 * apply both levels of transformation to the quals.)
372 set_rel_pathlist(root, childrel, childRTindex, childRTE);
374 childpath = childrel->cheapest_total_path;
375 if (IsA(childpath, AppendPath))
376 subpaths = list_concat(subpaths,
377 ((AppendPath *) childpath)->subpaths);
379 subpaths = lappend(subpaths, childpath);
382 * Propagate size information from the child back to the parent. For
383 * simplicity, we use the largest widths from any child as the parent
384 * estimates. (If you want to change this, beware of child
385 * attr_widths[] entries that haven't been set and are still 0.)
387 rel->rows += childrel->rows;
388 if (childrel->width > rel->width)
389 rel->width = childrel->width;
391 forboth(parentvars, rel->reltargetlist,
392 childvars, childrel->reltargetlist)
394 Var *parentvar = (Var *) lfirst(parentvars);
395 Var *childvar = (Var *) lfirst(childvars);
397 if (IsA(parentvar, Var) &&
400 int pndx = parentvar->varattno - rel->min_attr;
401 int cndx = childvar->varattno - childrel->min_attr;
403 if (childrel->attr_widths[cndx] > rel->attr_widths[pndx])
404 rel->attr_widths[pndx] = childrel->attr_widths[cndx];
410 * Set "raw tuples" count equal to "rows" for the appendrel; needed
411 * because some places assume rel->tuples is valid for any baserel.
413 rel->tuples = rel->rows;
416 * Finally, build Append path and install it as the only access path for
417 * the parent rel. (Note: this is correct even if we have zero or one
418 * live subpath due to constraint exclusion.)
420 add_path(rel, (Path *) create_append_path(rel, subpaths));
422 /* Select cheapest path (pretty easy in this case...) */
427 * set_dummy_rel_pathlist
428 * Build a dummy path for a relation that's been excluded by constraints
430 * Rather than inventing a special "dummy" path type, we represent this as an
431 * AppendPath with no members.
434 set_dummy_rel_pathlist(RelOptInfo *rel)
436 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
440 add_path(rel, (Path *) create_append_path(rel, NIL));
442 /* Select cheapest path (pretty easy in this case...) */
446 /* quick-and-dirty test to see if any joining is needed */
448 has_multiple_baserels(PlannerInfo *root)
450 int num_base_rels = 0;
453 for (rti = 1; rti < root->simple_rel_array_size; rti++)
455 RelOptInfo *brel = root->simple_rel_array[rti];
460 /* ignore RTEs that are "other rels" */
461 if (brel->reloptkind == RELOPT_BASEREL)
462 if (++num_base_rels > 1)
469 * set_subquery_pathlist
470 * Build the (single) access path for a subquery RTE
473 set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
474 Index rti, RangeTblEntry *rte)
476 Query *parse = root->parse;
477 Query *subquery = rte->subquery;
478 bool *differentTypes;
479 double tuple_fraction;
480 PlannerInfo *subroot;
483 /* We need a workspace for keeping track of set-op type coercions */
484 differentTypes = (bool *)
485 palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
488 * If there are any restriction clauses that have been attached to the
489 * subquery relation, consider pushing them down to become WHERE or HAVING
490 * quals of the subquery itself. This transformation is useful because it
491 * may allow us to generate a better plan for the subquery than evaluating
492 * all the subquery output rows and then filtering them.
494 * There are several cases where we cannot push down clauses. Restrictions
495 * involving the subquery are checked by subquery_is_pushdown_safe().
496 * Restrictions on individual clauses are checked by
497 * qual_is_pushdown_safe(). Also, we don't want to push down
498 * pseudoconstant clauses; better to have the gating node above the
501 * Non-pushed-down clauses will get evaluated as qpquals of the
504 * XXX Are there any cases where we want to make a policy decision not to
505 * push down a pushable qual, because it'd result in a worse plan?
507 if (rel->baserestrictinfo != NIL &&
508 subquery_is_pushdown_safe(subquery, subquery, differentTypes))
510 /* OK to consider pushing down individual quals */
511 List *upperrestrictlist = NIL;
514 foreach(l, rel->baserestrictinfo)
516 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
517 Node *clause = (Node *) rinfo->clause;
519 if (!rinfo->pseudoconstant &&
520 qual_is_pushdown_safe(subquery, rti, clause, differentTypes))
523 subquery_push_qual(subquery, rte, rti, clause);
527 /* Keep it in the upper query */
528 upperrestrictlist = lappend(upperrestrictlist, rinfo);
531 rel->baserestrictinfo = upperrestrictlist;
534 pfree(differentTypes);
537 * We can safely pass the outer tuple_fraction down to the subquery if the
538 * outer level has no joining, aggregation, or sorting to do. Otherwise
539 * we'd better tell the subquery to plan for full retrieval. (XXX This
540 * could probably be made more intelligent ...)
542 if (parse->hasAggs ||
543 parse->groupClause ||
545 parse->distinctClause ||
547 has_multiple_baserels(root))
548 tuple_fraction = 0.0; /* default case */
550 tuple_fraction = root->tuple_fraction;
552 /* Generate the plan for the subquery */
553 rel->subplan = subquery_planner(root->glob, subquery,
554 root->query_level + 1,
557 rel->subrtable = subroot->parse->rtable;
559 /* Copy number of output rows from subplan */
560 rel->tuples = rel->subplan->plan_rows;
562 /* Mark rel with estimated output rows, width, etc */
563 set_baserel_size_estimates(root, rel);
565 /* Convert subquery pathkeys to outer representation */
566 pathkeys = convert_subquery_pathkeys(root, rel, subroot->query_pathkeys);
568 /* Generate appropriate path */
569 add_path(rel, create_subqueryscan_path(rel, pathkeys));
571 /* Select cheapest path (pretty easy in this case...) */
576 * set_function_pathlist
577 * Build the (single) access path for a function RTE
580 set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
582 /* Mark rel with estimated output rows, width, etc */
583 set_function_size_estimates(root, rel);
585 /* Generate appropriate path */
586 add_path(rel, create_functionscan_path(root, rel));
588 /* Select cheapest path (pretty easy in this case...) */
593 * set_values_pathlist
594 * Build the (single) access path for a VALUES RTE
597 set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
599 /* Mark rel with estimated output rows, width, etc */
600 set_values_size_estimates(root, rel);
602 /* Generate appropriate path */
603 add_path(rel, create_valuesscan_path(root, rel));
605 /* Select cheapest path (pretty easy in this case...) */
610 * make_rel_from_joinlist
611 * Build access paths using a "joinlist" to guide the join path search.
613 * See comments for deconstruct_jointree() for definition of the joinlist
617 make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
624 * Count the number of child joinlist nodes. This is the depth of the
625 * dynamic-programming algorithm we must employ to consider all ways of
626 * joining the child nodes.
628 levels_needed = list_length(joinlist);
630 if (levels_needed <= 0)
631 return NULL; /* nothing to do? */
634 * Construct a list of rels corresponding to the child joinlist nodes.
635 * This may contain both base rels and rels constructed according to
639 foreach(jl, joinlist)
641 Node *jlnode = (Node *) lfirst(jl);
644 if (IsA(jlnode, RangeTblRef))
646 int varno = ((RangeTblRef *) jlnode)->rtindex;
648 thisrel = find_base_rel(root, varno);
650 else if (IsA(jlnode, List))
652 /* Recurse to handle subproblem */
653 thisrel = make_rel_from_joinlist(root, (List *) jlnode);
657 elog(ERROR, "unrecognized joinlist node type: %d",
658 (int) nodeTag(jlnode));
659 thisrel = NULL; /* keep compiler quiet */
662 initial_rels = lappend(initial_rels, thisrel);
665 if (levels_needed == 1)
668 * Single joinlist node, so we're done.
670 return (RelOptInfo *) linitial(initial_rels);
675 * Consider the different orders in which we could join the rels,
676 * using a plugin, GEQO, or the regular join search code.
678 if (join_search_hook)
679 return (*join_search_hook) (root, levels_needed, initial_rels);
680 else if (enable_geqo && levels_needed >= geqo_threshold)
681 return geqo(root, levels_needed, initial_rels);
683 return standard_join_search(root, levels_needed, initial_rels);
688 * standard_join_search
689 * Find possible joinpaths for a query by successively finding ways
690 * to join component relations into join relations.
692 * 'levels_needed' is the number of iterations needed, ie, the number of
693 * independent jointree items in the query. This is > 1.
695 * 'initial_rels' is a list of RelOptInfo nodes for each independent
696 * jointree item. These are the components to be joined together.
697 * Note that levels_needed == list_length(initial_rels).
699 * Returns the final level of join relations, i.e., the relation that is
700 * the result of joining all the original relations together.
701 * At least one implementation path must be provided for this relation and
702 * all required sub-relations.
704 * To support loadable plugins that modify planner behavior by changing the
705 * join searching algorithm, we provide a hook variable that lets a plugin
706 * replace or supplement this function. Any such hook must return the same
707 * final join relation as the standard code would, but it might have a
708 * different set of implementation paths attached, and only the sub-joinrels
709 * needed for these paths need have been instantiated.
711 * Note to plugin authors: the functions invoked during standard_join_search()
712 * modify root->join_rel_list and root->join_rel_hash. If you want to do more
713 * than one join-order search, you'll probably need to save and restore the
714 * original states of those data structures. See geqo_eval() for an example.
717 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
724 * We employ a simple "dynamic programming" algorithm: we first find all
725 * ways to build joins of two jointree items, then all ways to build joins
726 * of three items (from two-item joins and single items), then four-item
727 * joins, and so on until we have considered all ways to join all the
728 * items into one rel.
730 * joinitems[j] is a list of all the j-item rels. Initially we set
731 * joinitems[1] to represent all the single-jointree-item relations.
733 joinitems = (List **) palloc0((levels_needed + 1) * sizeof(List *));
735 joinitems[1] = initial_rels;
737 for (lev = 2; lev <= levels_needed; lev++)
742 * Determine all possible pairs of relations to be joined at this
743 * level, and build paths for making each one from every available
744 * pair of lower-level relations.
746 joinitems[lev] = join_search_one_level(root, lev, joinitems);
749 * Do cleanup work on each just-processed rel.
751 foreach(x, joinitems[lev])
753 rel = (RelOptInfo *) lfirst(x);
755 /* Find and save the cheapest paths for this rel */
758 #ifdef OPTIMIZER_DEBUG
759 debug_print_rel(root, rel);
765 * We should have a single rel at the final level.
767 if (joinitems[levels_needed] == NIL)
768 elog(ERROR, "failed to build any %d-way joins", levels_needed);
769 Assert(list_length(joinitems[levels_needed]) == 1);
771 rel = (RelOptInfo *) linitial(joinitems[levels_needed]);
776 /*****************************************************************************
777 * PUSHING QUALS DOWN INTO SUBQUERIES
778 *****************************************************************************/
781 * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
783 * subquery is the particular component query being checked. topquery
784 * is the top component of a set-operations tree (the same Query if no
785 * set-op is involved).
787 * Conditions checked here:
789 * 1. If the subquery has a LIMIT clause, we must not push down any quals,
790 * since that could change the set of rows returned.
792 * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
793 * quals into it, because that would change the results.
795 * 3. For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
796 * push quals into each component query, but the quals can only reference
797 * subquery columns that suffer no type coercions in the set operation.
798 * Otherwise there are possible semantic gotchas. So, we check the
799 * component queries to see if any of them have different output types;
800 * differentTypes[k] is set true if column k has different type in any
804 subquery_is_pushdown_safe(Query *subquery, Query *topquery,
805 bool *differentTypes)
807 SetOperationStmt *topop;
810 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
813 /* Are we at top level, or looking at a setop component? */
814 if (subquery == topquery)
816 /* Top level, so check any component queries */
817 if (subquery->setOperations != NULL)
818 if (!recurse_pushdown_safe(subquery->setOperations, topquery,
824 /* Setop component must not have more components (too weird) */
825 if (subquery->setOperations != NULL)
827 /* Check whether setop component output types match top level */
828 topop = (SetOperationStmt *) topquery->setOperations;
829 Assert(topop && IsA(topop, SetOperationStmt));
830 compare_tlist_datatypes(subquery->targetList,
838 * Helper routine to recurse through setOperations tree
841 recurse_pushdown_safe(Node *setOp, Query *topquery,
842 bool *differentTypes)
844 if (IsA(setOp, RangeTblRef))
846 RangeTblRef *rtr = (RangeTblRef *) setOp;
847 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
848 Query *subquery = rte->subquery;
850 Assert(subquery != NULL);
851 return subquery_is_pushdown_safe(subquery, topquery, differentTypes);
853 else if (IsA(setOp, SetOperationStmt))
855 SetOperationStmt *op = (SetOperationStmt *) setOp;
857 /* EXCEPT is no good */
858 if (op->op == SETOP_EXCEPT)
861 if (!recurse_pushdown_safe(op->larg, topquery, differentTypes))
863 if (!recurse_pushdown_safe(op->rarg, topquery, differentTypes))
868 elog(ERROR, "unrecognized node type: %d",
869 (int) nodeTag(setOp));
875 * Compare tlist's datatypes against the list of set-operation result types.
876 * For any items that are different, mark the appropriate element of
877 * differentTypes[] to show that this column will have type conversions.
879 * We don't have to care about typmods here: the only allowed difference
880 * between set-op input and output typmods is input is a specific typmod
881 * and output is -1, and that does not require a coercion.
884 compare_tlist_datatypes(List *tlist, List *colTypes,
885 bool *differentTypes)
888 ListCell *colType = list_head(colTypes);
892 TargetEntry *tle = (TargetEntry *) lfirst(l);
895 continue; /* ignore resjunk columns */
897 elog(ERROR, "wrong number of tlist entries");
898 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
899 differentTypes[tle->resno] = true;
900 colType = lnext(colType);
903 elog(ERROR, "wrong number of tlist entries");
907 * qual_is_pushdown_safe - is a particular qual safe to push down?
909 * qual is a restriction clause applying to the given subquery (whose RTE
910 * has index rti in the parent query).
912 * Conditions checked here:
914 * 1. The qual must not contain any subselects (mainly because I'm not sure
915 * it will work correctly: sublinks will already have been transformed into
916 * subplans in the qual, but not in the subquery).
918 * 2. The qual must not refer to the whole-row output of the subquery
919 * (since there is no easy way to name that within the subquery itself).
921 * 3. The qual must not refer to any subquery output columns that were
922 * found to have inconsistent types across a set operation tree by
923 * subquery_is_pushdown_safe().
925 * 4. If the subquery uses DISTINCT ON, we must not push down any quals that
926 * refer to non-DISTINCT output columns, because that could change the set
927 * of rows returned. This condition is vacuous for DISTINCT, because then
928 * there are no non-DISTINCT output columns, but unfortunately it's fairly
929 * expensive to tell the difference between DISTINCT and DISTINCT ON in the
930 * parsetree representation. It's cheaper to just make sure all the Vars
931 * in the qual refer to DISTINCT columns.
933 * 5. We must not push down any quals that refer to subselect outputs that
934 * return sets, else we'd introduce functions-returning-sets into the
935 * subquery's WHERE/HAVING quals.
937 * 6. We must not push down any quals that refer to subselect outputs that
938 * contain volatile functions, for fear of introducing strange results due
939 * to multiple evaluation of a volatile function.
942 qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
943 bool *differentTypes)
948 Bitmapset *tested = NULL;
950 /* Refuse subselects (point 1) */
951 if (contain_subplans(qual))
955 * Examine all Vars used in clause; since it's a restriction clause, all
956 * such Vars must refer to subselect output columns.
958 vars = pull_var_clause(qual, false);
961 Var *var = (Var *) lfirst(vl);
964 Assert(var->varno == rti);
967 if (var->varattno == 0)
974 * We use a bitmapset to avoid testing the same attno more than once.
975 * (NB: this only works because subquery outputs can't have negative
978 if (bms_is_member(var->varattno, tested))
980 tested = bms_add_member(tested, var->varattno);
983 if (differentTypes[var->varattno])
989 /* Must find the tlist element referenced by the Var */
990 tle = get_tle_by_resno(subquery->targetList, var->varattno);
992 Assert(!tle->resjunk);
994 /* If subquery uses DISTINCT or DISTINCT ON, check point 4 */
995 if (subquery->distinctClause != NIL &&
996 !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
998 /* non-DISTINCT column, so fail */
1003 /* Refuse functions returning sets (point 5) */
1004 if (expression_returns_set((Node *) tle->expr))
1010 /* Refuse volatile functions (point 6) */
1011 if (contain_volatile_functions((Node *) tle->expr))
1025 * subquery_push_qual - push down a qual that we have determined is safe
1028 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
1030 if (subquery->setOperations != NULL)
1032 /* Recurse to push it separately to each component query */
1033 recurse_push_qual(subquery->setOperations, subquery,
1039 * We need to replace Vars in the qual (which must refer to outputs of
1040 * the subquery) with copies of the subquery's targetlist expressions.
1041 * Note that at this point, any uplevel Vars in the qual should have
1042 * been replaced with Params, so they need no work.
1044 * This step also ensures that when we are pushing into a setop tree,
1045 * each component query gets its own copy of the qual.
1047 qual = ResolveNew(qual, rti, 0, rte,
1048 subquery->targetList,
1052 * Now attach the qual to the proper place: normally WHERE, but if the
1053 * subquery uses grouping or aggregation, put it in HAVING (since the
1054 * qual really refers to the group-result rows).
1056 if (subquery->hasAggs || subquery->groupClause || subquery->havingQual)
1057 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
1059 subquery->jointree->quals =
1060 make_and_qual(subquery->jointree->quals, qual);
1063 * We need not change the subquery's hasAggs or hasSublinks flags,
1064 * since we can't be pushing down any aggregates that weren't there
1065 * before, and we don't push down subselects at all.
1071 * Helper routine to recurse through setOperations tree
1074 recurse_push_qual(Node *setOp, Query *topquery,
1075 RangeTblEntry *rte, Index rti, Node *qual)
1077 if (IsA(setOp, RangeTblRef))
1079 RangeTblRef *rtr = (RangeTblRef *) setOp;
1080 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
1081 Query *subquery = subrte->subquery;
1083 Assert(subquery != NULL);
1084 subquery_push_qual(subquery, rte, rti, qual);
1086 else if (IsA(setOp, SetOperationStmt))
1088 SetOperationStmt *op = (SetOperationStmt *) setOp;
1090 recurse_push_qual(op->larg, topquery, rte, rti, qual);
1091 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
1095 elog(ERROR, "unrecognized node type: %d",
1096 (int) nodeTag(setOp));
1100 /*****************************************************************************
1102 *****************************************************************************/
1104 #ifdef OPTIMIZER_DEBUG
1107 print_relids(Relids relids)
1113 tmprelids = bms_copy(relids);
1114 while ((x = bms_first_member(tmprelids)) >= 0)
1121 bms_free(tmprelids);
1125 print_restrictclauses(PlannerInfo *root, List *clauses)
1131 RestrictInfo *c = lfirst(l);
1133 print_expr((Node *) c->clause, root->parse->rtable);
1140 print_path(PlannerInfo *root, Path *path, int indent)
1144 Path *subpath = NULL;
1147 switch (nodeTag(path))
1155 case T_BitmapHeapPath:
1156 ptype = "BitmapHeapScan";
1158 case T_BitmapAndPath:
1159 ptype = "BitmapAndPath";
1161 case T_BitmapOrPath:
1162 ptype = "BitmapOrPath";
1173 case T_MaterialPath:
1175 subpath = ((MaterialPath *) path)->subpath;
1179 subpath = ((UniquePath *) path)->subpath;
1186 ptype = "MergeJoin";
1198 for (i = 0; i < indent; i++)
1200 printf("%s", ptype);
1205 print_relids(path->parent->relids);
1206 printf(") rows=%.0f", path->parent->rows);
1208 printf(" cost=%.2f..%.2f\n", path->startup_cost, path->total_cost);
1212 for (i = 0; i < indent; i++)
1214 printf(" pathkeys: ");
1215 print_pathkeys(path->pathkeys, root->parse->rtable);
1220 JoinPath *jp = (JoinPath *) path;
1222 for (i = 0; i < indent; i++)
1224 printf(" clauses: ");
1225 print_restrictclauses(root, jp->joinrestrictinfo);
1228 if (IsA(path, MergePath))
1230 MergePath *mp = (MergePath *) path;
1232 if (mp->outersortkeys || mp->innersortkeys)
1234 for (i = 0; i < indent; i++)
1236 printf(" sortouter=%d sortinner=%d\n",
1237 ((mp->outersortkeys) ? 1 : 0),
1238 ((mp->innersortkeys) ? 1 : 0));
1242 print_path(root, jp->outerjoinpath, indent + 1);
1243 print_path(root, jp->innerjoinpath, indent + 1);
1247 print_path(root, subpath, indent + 1);
1251 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
1255 printf("RELOPTINFO (");
1256 print_relids(rel->relids);
1257 printf("): rows=%.0f width=%d\n", rel->rows, rel->width);
1259 if (rel->baserestrictinfo)
1261 printf("\tbaserestrictinfo: ");
1262 print_restrictclauses(root, rel->baserestrictinfo);
1268 printf("\tjoininfo: ");
1269 print_restrictclauses(root, rel->joininfo);
1273 printf("\tpath list:\n");
1274 foreach(l, rel->pathlist)
1275 print_path(root, lfirst(l), 1);
1276 printf("\n\tcheapest startup path:\n");
1277 print_path(root, rel->cheapest_startup_path, 1);
1278 printf("\n\tcheapest total path:\n");
1279 print_path(root, rel->cheapest_total_path, 1);
1284 #endif /* OPTIMIZER_DEBUG */