1 /*-------------------------------------------------------------------------
4 * Relation-node lookup/construction routines
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/util/relnode.c,v 1.89 2008/01/01 19:45:50 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "optimizer/cost.h"
18 #include "optimizer/pathnode.h"
19 #include "optimizer/paths.h"
20 #include "optimizer/plancat.h"
21 #include "optimizer/restrictinfo.h"
22 #include "parser/parsetree.h"
23 #include "utils/hsearch.h"
26 typedef struct JoinHashEntry
28 Relids join_relids; /* hash key --- MUST BE FIRST */
32 static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
33 RelOptInfo *input_rel);
34 static List *build_joinrel_restrictlist(PlannerInfo *root,
36 RelOptInfo *outer_rel,
37 RelOptInfo *inner_rel);
38 static void build_joinrel_joinlist(RelOptInfo *joinrel,
39 RelOptInfo *outer_rel,
40 RelOptInfo *inner_rel);
41 static List *subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
43 List *new_restrictlist);
44 static List *subbuild_joinrel_joinlist(RelOptInfo *joinrel,
51 * Construct a new RelOptInfo for a base relation or 'other' relation.
54 build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
59 /* Rel should not exist already */
60 Assert(relid > 0 && relid < root->simple_rel_array_size);
61 if (root->simple_rel_array[relid] != NULL)
62 elog(ERROR, "rel %d already exists", relid);
64 /* Fetch RTE for relation */
65 rte = root->simple_rte_array[relid];
68 rel = makeNode(RelOptInfo);
69 rel->reloptkind = reloptkind;
70 rel->relids = bms_make_singleton(relid);
73 rel->reltargetlist = NIL;
75 rel->cheapest_startup_path = NULL;
76 rel->cheapest_total_path = NULL;
77 rel->cheapest_unique_path = NULL;
79 rel->rtekind = rte->rtekind;
80 /* min_attr, max_attr, attr_needed, attr_widths are set below */
86 rel->baserestrictinfo = NIL;
87 rel->baserestrictcost.startup = 0;
88 rel->baserestrictcost.per_tuple = 0;
90 rel->has_eclass_joins = false;
91 rel->index_outer_relids = NULL;
92 rel->index_inner_paths = NIL;
94 /* Check type of rtable entry */
98 /* Table --- retrieve statistics from the system catalogs */
99 get_relation_info(root, rte->relid, rte->inh, rel);
106 * Subquery, function, or values list --- set up attr range and
109 * Note: 0 is included in range to support whole-row Vars
112 rel->max_attr = list_length(rte->eref->colnames);
113 rel->attr_needed = (Relids *)
114 palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
115 rel->attr_widths = (int32 *)
116 palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
119 elog(ERROR, "unrecognized RTE kind: %d",
124 /* Save the finished struct in the query's simple_rel_array */
125 root->simple_rel_array[relid] = rel;
128 * If this rel is an appendrel parent, recurse to build "other rel"
129 * RelOptInfos for its children. They are "other rels" because they are
130 * not in the main join tree, but we will need RelOptInfos to plan access
137 foreach(l, root->append_rel_list)
139 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
141 /* append_rel_list contains all append rels; ignore others */
142 if (appinfo->parent_relid != relid)
145 (void) build_simple_rel(root, appinfo->child_relid,
146 RELOPT_OTHER_MEMBER_REL);
155 * Find a base or other relation entry, which must already exist.
158 find_base_rel(PlannerInfo *root, int relid)
164 if (relid < root->simple_rel_array_size)
166 rel = root->simple_rel_array[relid];
171 elog(ERROR, "no relation entry for relid %d", relid);
173 return NULL; /* keep compiler quiet */
177 * build_join_rel_hash
178 * Construct the auxiliary hash table for join relations.
181 build_join_rel_hash(PlannerInfo *root)
187 /* Create the hash table */
188 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
189 hash_ctl.keysize = sizeof(Relids);
190 hash_ctl.entrysize = sizeof(JoinHashEntry);
191 hash_ctl.hash = bitmap_hash;
192 hash_ctl.match = bitmap_match;
193 hash_ctl.hcxt = CurrentMemoryContext;
194 hashtab = hash_create("JoinRelHashTable",
197 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
199 /* Insert all the already-existing joinrels */
200 foreach(l, root->join_rel_list)
202 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
203 JoinHashEntry *hentry;
206 hentry = (JoinHashEntry *) hash_search(hashtab,
211 hentry->join_rel = rel;
214 root->join_rel_hash = hashtab;
219 * Returns relation entry corresponding to 'relids' (a set of RT indexes),
220 * or NULL if none exists. This is for join relations.
223 find_join_rel(PlannerInfo *root, Relids relids)
226 * Switch to using hash lookup when list grows "too long". The threshold
227 * is arbitrary and is known only here.
229 if (!root->join_rel_hash && list_length(root->join_rel_list) > 32)
230 build_join_rel_hash(root);
233 * Use either hashtable lookup or linear search, as appropriate.
235 * Note: the seemingly redundant hashkey variable is used to avoid taking
236 * the address of relids; unless the compiler is exceedingly smart, doing
237 * so would force relids out of a register and thus probably slow down the
240 if (root->join_rel_hash)
242 Relids hashkey = relids;
243 JoinHashEntry *hentry;
245 hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
250 return hentry->join_rel;
256 foreach(l, root->join_rel_list)
258 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
260 if (bms_equal(rel->relids, relids))
270 * Returns relation entry corresponding to the union of two given rels,
271 * creating a new relation entry if none already exists.
273 * 'joinrelids' is the Relids set that uniquely identifies the join
274 * 'outer_rel' and 'inner_rel' are relation nodes for the relations to be
276 * 'jointype': type of join (inner/outer)
277 * 'restrictlist_ptr': result variable. If not NULL, *restrictlist_ptr
278 * receives the list of RestrictInfo nodes that apply to this
279 * particular pair of joinable relations.
281 * restrictlist_ptr makes the routine's API a little grotty, but it saves
282 * duplicated calculation of the restrictlist...
285 build_join_rel(PlannerInfo *root,
287 RelOptInfo *outer_rel,
288 RelOptInfo *inner_rel,
290 List **restrictlist_ptr)
296 * See if we already have a joinrel for this set of base rels.
298 joinrel = find_join_rel(root, joinrelids);
303 * Yes, so we only need to figure the restrictlist for this particular
304 * pair of component relations.
306 if (restrictlist_ptr)
307 *restrictlist_ptr = build_joinrel_restrictlist(root,
317 joinrel = makeNode(RelOptInfo);
318 joinrel->reloptkind = RELOPT_JOINREL;
319 joinrel->relids = bms_copy(joinrelids);
322 joinrel->reltargetlist = NIL;
323 joinrel->pathlist = NIL;
324 joinrel->cheapest_startup_path = NULL;
325 joinrel->cheapest_total_path = NULL;
326 joinrel->cheapest_unique_path = NULL;
327 joinrel->relid = 0; /* indicates not a baserel */
328 joinrel->rtekind = RTE_JOIN;
329 joinrel->min_attr = 0;
330 joinrel->max_attr = 0;
331 joinrel->attr_needed = NULL;
332 joinrel->attr_widths = NULL;
333 joinrel->indexlist = NIL;
336 joinrel->subplan = NULL;
337 joinrel->subrtable = NIL;
338 joinrel->baserestrictinfo = NIL;
339 joinrel->baserestrictcost.startup = 0;
340 joinrel->baserestrictcost.per_tuple = 0;
341 joinrel->joininfo = NIL;
342 joinrel->has_eclass_joins = false;
343 joinrel->index_outer_relids = NULL;
344 joinrel->index_inner_paths = NIL;
347 * Create a new tlist containing just the vars that need to be output from
348 * this join (ie, are needed for higher joinclauses or final output).
350 * NOTE: the tlist order for a join rel will depend on which pair of outer
351 * and inner rels we first try to build it from. But the contents should
352 * be the same regardless.
354 build_joinrel_tlist(root, joinrel, outer_rel);
355 build_joinrel_tlist(root, joinrel, inner_rel);
358 * Construct restrict and join clause lists for the new joinrel. (The
359 * caller might or might not need the restrictlist, but I need it anyway
360 * for set_joinrel_size_estimates().)
362 restrictlist = build_joinrel_restrictlist(root, joinrel,
363 outer_rel, inner_rel);
364 if (restrictlist_ptr)
365 *restrictlist_ptr = restrictlist;
366 build_joinrel_joinlist(joinrel, outer_rel, inner_rel);
369 * This is also the right place to check whether the joinrel has any
370 * pending EquivalenceClass joins.
372 joinrel->has_eclass_joins = has_relevant_eclass_joinclause(root, joinrel);
375 * Set estimates of the joinrel's size.
377 set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
378 jointype, restrictlist);
381 * Add the joinrel to the query's joinrel list, and store it into the
382 * auxiliary hashtable if there is one. NB: GEQO requires us to append
383 * the new joinrel to the end of the list!
385 root->join_rel_list = lappend(root->join_rel_list, joinrel);
387 if (root->join_rel_hash)
389 JoinHashEntry *hentry;
392 hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
397 hentry->join_rel = joinrel;
404 * build_joinrel_tlist
405 * Builds a join relation's target list.
407 * The join's targetlist includes all Vars of its member relations that
408 * will still be needed above the join. This subroutine adds all such
409 * Vars from the specified input rel's tlist to the join rel's tlist.
411 * We also compute the expected width of the join's output, making use
412 * of data that was cached at the baserel level by set_rel_width().
415 build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
416 RelOptInfo *input_rel)
418 Relids relids = joinrel->relids;
421 foreach(vars, input_rel->reltargetlist)
423 Var *origvar = (Var *) lfirst(vars);
429 * We can't run into any child RowExprs here, but we could find a
430 * whole-row Var with a ConvertRowtypeExpr atop it.
433 while (!IsA(var, Var))
435 if (IsA(var, ConvertRowtypeExpr))
436 var = (Var *) ((ConvertRowtypeExpr *) var)->arg;
438 elog(ERROR, "unexpected node type in reltargetlist: %d",
442 /* Get the Var's original base rel */
443 baserel = find_base_rel(root, var->varno);
445 /* Is it still needed above this joinrel? */
446 ndx = var->varattno - baserel->min_attr;
447 if (bms_nonempty_difference(baserel->attr_needed[ndx], relids))
449 /* Yup, add it to the output */
450 joinrel->reltargetlist = lappend(joinrel->reltargetlist, origvar);
451 joinrel->width += baserel->attr_widths[ndx];
457 * build_joinrel_restrictlist
458 * build_joinrel_joinlist
459 * These routines build lists of restriction and join clauses for a
460 * join relation from the joininfo lists of the relations it joins.
462 * These routines are separate because the restriction list must be
463 * built afresh for each pair of input sub-relations we consider, whereas
464 * the join list need only be computed once for any join RelOptInfo.
465 * The join list is fully determined by the set of rels making up the
466 * joinrel, so we should get the same results (up to ordering) from any
467 * candidate pair of sub-relations. But the restriction list is whatever
468 * is not handled in the sub-relations, so it depends on which
469 * sub-relations are considered.
471 * If a join clause from an input relation refers to base rels still not
472 * present in the joinrel, then it is still a join clause for the joinrel;
473 * we put it into the joininfo list for the joinrel. Otherwise,
474 * the clause is now a restrict clause for the joined relation, and we
475 * return it to the caller of build_joinrel_restrictlist() to be stored in
476 * join paths made from this pair of sub-relations. (It will not need to
477 * be considered further up the join tree.)
479 * In many case we will find the same RestrictInfos in both input
480 * relations' joinlists, so be careful to eliminate duplicates.
481 * Pointer equality should be a sufficient test for dups, since all
482 * the various joinlist entries ultimately refer to RestrictInfos
483 * pushed into them by distribute_restrictinfo_to_rels().
485 * 'joinrel' is a join relation node
486 * 'outer_rel' and 'inner_rel' are a pair of relations that can be joined
489 * build_joinrel_restrictlist() returns a list of relevant restrictinfos,
490 * whereas build_joinrel_joinlist() stores its results in the joinrel's
491 * joininfo list. One or the other must accept each given clause!
493 * NB: Formerly, we made deep(!) copies of each input RestrictInfo to pass
494 * up to the join relation. I believe this is no longer necessary, because
495 * RestrictInfo nodes are no longer context-dependent. Instead, just include
496 * the original nodes in the lists made for the join relation.
499 build_joinrel_restrictlist(PlannerInfo *root,
501 RelOptInfo *outer_rel,
502 RelOptInfo *inner_rel)
507 * Collect all the clauses that syntactically belong at this level,
508 * eliminating any duplicates (important since we will see many of the
509 * same clauses arriving from both input relations).
511 result = subbuild_joinrel_restrictlist(joinrel, outer_rel->joininfo, NIL);
512 result = subbuild_joinrel_restrictlist(joinrel, inner_rel->joininfo, result);
515 * Add on any clauses derived from EquivalenceClasses. These cannot be
516 * redundant with the clauses in the joininfo lists, so don't bother
519 result = list_concat(result,
520 generate_join_implied_equalities(root,
529 build_joinrel_joinlist(RelOptInfo *joinrel,
530 RelOptInfo *outer_rel,
531 RelOptInfo *inner_rel)
536 * Collect all the clauses that syntactically belong above this level,
537 * eliminating any duplicates (important since we will see many of the
538 * same clauses arriving from both input relations).
540 result = subbuild_joinrel_joinlist(joinrel, outer_rel->joininfo, NIL);
541 result = subbuild_joinrel_joinlist(joinrel, inner_rel->joininfo, result);
543 joinrel->joininfo = result;
547 subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
549 List *new_restrictlist)
553 foreach(l, joininfo_list)
555 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
557 if (bms_is_subset(rinfo->required_relids, joinrel->relids))
560 * This clause becomes a restriction clause for the joinrel, since
561 * it refers to no outside rels. Add it to the list, being
562 * careful to eliminate duplicates. (Since RestrictInfo nodes in
563 * different joinlists will have been multiply-linked rather than
564 * copied, pointer equality should be a sufficient test.)
566 new_restrictlist = list_append_unique_ptr(new_restrictlist, rinfo);
571 * This clause is still a join clause at this level, so we ignore
572 * it in this routine.
577 return new_restrictlist;
581 subbuild_joinrel_joinlist(RelOptInfo *joinrel,
587 foreach(l, joininfo_list)
589 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
591 if (bms_is_subset(rinfo->required_relids, joinrel->relids))
594 * This clause becomes a restriction clause for the joinrel, since
595 * it refers to no outside rels. So we can ignore it in this
602 * This clause is still a join clause at this level, so add it to
603 * the new joininfo list, being careful to eliminate duplicates.
604 * (Since RestrictInfo nodes in different joinlists will have been
605 * multiply-linked rather than copied, pointer equality should be
606 * a sufficient test.)
608 new_joininfo = list_append_unique_ptr(new_joininfo, rinfo);