1 /*-------------------------------------------------------------------------
4 * Relation-node lookup/construction routines
6 * Portions Copyright (c) 1996-2005, 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.73 2005/11/22 18:17:15 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "optimizer/cost.h"
18 #include "optimizer/joininfo.h"
19 #include "optimizer/pathnode.h"
20 #include "optimizer/plancat.h"
21 #include "optimizer/restrictinfo.h"
22 #include "optimizer/tlist.h"
23 #include "parser/parsetree.h"
24 #include "utils/hsearch.h"
27 typedef struct JoinHashEntry
29 Relids join_relids; /* hash key --- MUST BE FIRST */
33 static RelOptInfo *make_reloptinfo(PlannerInfo *root, int relid,
34 RelOptKind reloptkind);
35 static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
36 RelOptInfo *input_rel);
37 static List *build_joinrel_restrictlist(PlannerInfo *root,
39 RelOptInfo *outer_rel,
40 RelOptInfo *inner_rel,
42 static void build_joinrel_joinlist(RelOptInfo *joinrel,
43 RelOptInfo *outer_rel,
44 RelOptInfo *inner_rel);
45 static List *subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
47 static void subbuild_joinrel_joinlist(RelOptInfo *joinrel,
53 * Construct a new base relation RelOptInfo, and put it in the query's
57 build_base_rel(PlannerInfo *root, int relid)
61 /* Rel should not exist already */
62 if (relid < root->base_rel_array_size &&
63 root->base_rel_array[relid] != NULL)
64 elog(ERROR, "rel already exists");
66 /* No existing RelOptInfo for this base rel, so make a new one */
67 (void) make_reloptinfo(root, relid, RELOPT_BASEREL);
72 * Returns relation entry corresponding to 'relid', creating a new one
73 * if necessary. This is for 'other' relations, which are much like
74 * base relations except that they have a different RelOptKind.
77 build_other_rel(PlannerInfo *root, int relid)
84 if (relid < root->base_rel_array_size)
86 rel = root->base_rel_array[relid];
89 /* it should not exist as a base rel */
90 if (rel->reloptkind == RELOPT_BASEREL)
91 elog(ERROR, "rel already exists as base rel");
97 /* No existing RelOptInfo for this other rel, so make a new one */
98 /* presently, must be an inheritance child rel */
99 rel = make_reloptinfo(root, relid, RELOPT_OTHER_CHILD_REL);
106 * Construct a RelOptInfo for the specified rangetable index,
107 * and enter it into base_rel_array.
109 * Common code for build_base_rel and build_other_rel.
112 make_reloptinfo(PlannerInfo *root, int relid, RelOptKind reloptkind)
114 RelOptInfo *rel = makeNode(RelOptInfo);
115 RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable);
117 rel->reloptkind = reloptkind;
118 rel->relids = bms_make_singleton(relid);
121 rel->reltargetlist = NIL;
123 rel->cheapest_startup_path = NULL;
124 rel->cheapest_total_path = NULL;
125 rel->cheapest_unique_path = NULL;
127 rel->rtekind = rte->rtekind;
128 /* min_attr, max_attr, attr_needed, attr_widths are set below */
129 rel->indexlist = NIL;
133 rel->baserestrictinfo = NIL;
134 rel->baserestrictcost.startup = 0;
135 rel->baserestrictcost.per_tuple = 0;
136 rel->outerjoinset = NULL;
138 rel->index_outer_relids = NULL;
139 rel->index_inner_paths = NIL;
141 /* Check type of rtable entry */
142 switch (rte->rtekind)
145 /* Table --- retrieve statistics from the system catalogs */
146 get_relation_info(rte->relid, rel);
150 /* Subquery or function --- set up attr range and arrays */
151 /* Note: 0 is included in range to support whole-row Vars */
153 rel->max_attr = list_length(rte->eref->colnames);
154 rel->attr_needed = (Relids *)
155 palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
156 rel->attr_widths = (int32 *)
157 palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
160 elog(ERROR, "unrecognized RTE kind: %d",
165 /* Add the finished struct to the base_rel_array */
166 if (relid >= root->base_rel_array_size)
168 int oldsize = root->base_rel_array_size;
171 newsize = Max(oldsize * 2, relid + 1);
172 root->base_rel_array = (RelOptInfo **)
173 repalloc(root->base_rel_array, newsize * sizeof(RelOptInfo *));
174 MemSet(root->base_rel_array + oldsize, 0,
175 (newsize - oldsize) * sizeof(RelOptInfo *));
176 root->base_rel_array_size = newsize;
179 root->base_rel_array[relid] = rel;
186 * Find a base or other relation entry, which must already exist.
189 find_base_rel(PlannerInfo *root, int relid)
195 if (relid < root->base_rel_array_size)
197 rel = root->base_rel_array[relid];
202 elog(ERROR, "no relation entry for relid %d", relid);
204 return NULL; /* keep compiler quiet */
208 * build_join_rel_hash
209 * Construct the auxiliary hash table for join relations.
212 build_join_rel_hash(PlannerInfo *root)
218 /* Create the hash table */
219 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
220 hash_ctl.keysize = sizeof(Relids);
221 hash_ctl.entrysize = sizeof(JoinHashEntry);
222 hash_ctl.hash = bitmap_hash;
223 hash_ctl.match = bitmap_match;
224 hash_ctl.hcxt = CurrentMemoryContext;
225 hashtab = hash_create("JoinRelHashTable",
228 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
230 /* Insert all the already-existing joinrels */
231 foreach(l, root->join_rel_list)
233 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
234 JoinHashEntry *hentry;
237 hentry = (JoinHashEntry *) hash_search(hashtab,
242 hentry->join_rel = rel;
245 root->join_rel_hash = hashtab;
250 * Returns relation entry corresponding to 'relids' (a set of RT indexes),
251 * or NULL if none exists. This is for join relations.
254 find_join_rel(PlannerInfo *root, Relids relids)
257 * Switch to using hash lookup when list grows "too long". The threshold
258 * is arbitrary and is known only here.
260 if (!root->join_rel_hash && list_length(root->join_rel_list) > 32)
261 build_join_rel_hash(root);
264 * Use either hashtable lookup or linear search, as appropriate.
266 * Note: the seemingly redundant hashkey variable is used to avoid taking
267 * the address of relids; unless the compiler is exceedingly smart, doing
268 * so would force relids out of a register and thus probably slow down the
271 if (root->join_rel_hash)
273 Relids hashkey = relids;
274 JoinHashEntry *hentry;
276 hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
281 return hentry->join_rel;
287 foreach(l, root->join_rel_list)
289 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
291 if (bms_equal(rel->relids, relids))
301 * Returns relation entry corresponding to the union of two given rels,
302 * creating a new relation entry if none already exists.
304 * 'joinrelids' is the Relids set that uniquely identifies the join
305 * 'outer_rel' and 'inner_rel' are relation nodes for the relations to be
307 * 'jointype': type of join (inner/outer)
308 * 'restrictlist_ptr': result variable. If not NULL, *restrictlist_ptr
309 * receives the list of RestrictInfo nodes that apply to this
310 * particular pair of joinable relations.
312 * restrictlist_ptr makes the routine's API a little grotty, but it saves
313 * duplicated calculation of the restrictlist...
316 build_join_rel(PlannerInfo *root,
318 RelOptInfo *outer_rel,
319 RelOptInfo *inner_rel,
321 List **restrictlist_ptr)
327 * See if we already have a joinrel for this set of base rels.
329 joinrel = find_join_rel(root, joinrelids);
334 * Yes, so we only need to figure the restrictlist for this particular
335 * pair of component relations.
337 if (restrictlist_ptr)
338 *restrictlist_ptr = build_joinrel_restrictlist(root,
349 joinrel = makeNode(RelOptInfo);
350 joinrel->reloptkind = RELOPT_JOINREL;
351 joinrel->relids = bms_copy(joinrelids);
354 joinrel->reltargetlist = NIL;
355 joinrel->pathlist = NIL;
356 joinrel->cheapest_startup_path = NULL;
357 joinrel->cheapest_total_path = NULL;
358 joinrel->cheapest_unique_path = NULL;
359 joinrel->relid = 0; /* indicates not a baserel */
360 joinrel->rtekind = RTE_JOIN;
361 joinrel->min_attr = 0;
362 joinrel->max_attr = 0;
363 joinrel->attr_needed = NULL;
364 joinrel->attr_widths = NULL;
365 joinrel->indexlist = NIL;
368 joinrel->subplan = NULL;
369 joinrel->baserestrictinfo = NIL;
370 joinrel->baserestrictcost.startup = 0;
371 joinrel->baserestrictcost.per_tuple = 0;
372 joinrel->outerjoinset = NULL;
373 joinrel->joininfo = NIL;
374 joinrel->index_outer_relids = NULL;
375 joinrel->index_inner_paths = NIL;
378 * Create a new tlist containing just the vars that need to be output from
379 * this join (ie, are needed for higher joinclauses or final output).
381 * NOTE: the tlist order for a join rel will depend on which pair of outer
382 * and inner rels we first try to build it from. But the contents should
383 * be the same regardless.
385 build_joinrel_tlist(root, joinrel, outer_rel);
386 build_joinrel_tlist(root, joinrel, inner_rel);
389 * Construct restrict and join clause lists for the new joinrel. (The
390 * caller might or might not need the restrictlist, but I need it anyway
391 * for set_joinrel_size_estimates().)
393 restrictlist = build_joinrel_restrictlist(root,
398 if (restrictlist_ptr)
399 *restrictlist_ptr = restrictlist;
400 build_joinrel_joinlist(joinrel, outer_rel, inner_rel);
403 * Set estimates of the joinrel's size.
405 set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
406 jointype, restrictlist);
409 * Add the joinrel to the query's joinrel list, and store it into the
410 * auxiliary hashtable if there is one. NB: GEQO requires us to append
411 * the new joinrel to the end of the list!
413 root->join_rel_list = lappend(root->join_rel_list, joinrel);
415 if (root->join_rel_hash)
417 JoinHashEntry *hentry;
420 hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
425 hentry->join_rel = joinrel;
432 * build_joinrel_tlist
433 * Builds a join relation's target list.
435 * The join's targetlist includes all Vars of its member relations that
436 * will still be needed above the join. This subroutine adds all such
437 * Vars from the specified input rel's tlist to the join rel's tlist.
439 * We also compute the expected width of the join's output, making use
440 * of data that was cached at the baserel level by set_rel_width().
443 build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
444 RelOptInfo *input_rel)
446 Relids relids = joinrel->relids;
449 foreach(vars, input_rel->reltargetlist)
451 Var *var = (Var *) lfirst(vars);
455 /* We can't run into any child RowExprs here */
456 Assert(IsA(var, Var));
458 /* Get the Var's original base rel */
459 baserel = find_base_rel(root, var->varno);
461 /* Is it still needed above this joinrel? */
462 ndx = var->varattno - baserel->min_attr;
463 if (bms_nonempty_difference(baserel->attr_needed[ndx], relids))
465 /* Yup, add it to the output */
466 joinrel->reltargetlist = lappend(joinrel->reltargetlist, var);
467 Assert(baserel->attr_widths[ndx] > 0);
468 joinrel->width += baserel->attr_widths[ndx];
474 * build_joinrel_restrictlist
475 * build_joinrel_joinlist
476 * These routines build lists of restriction and join clauses for a
477 * join relation from the joininfo lists of the relations it joins.
479 * These routines are separate because the restriction list must be
480 * built afresh for each pair of input sub-relations we consider, whereas
481 * the join list need only be computed once for any join RelOptInfo.
482 * The join list is fully determined by the set of rels making up the
483 * joinrel, so we should get the same results (up to ordering) from any
484 * candidate pair of sub-relations. But the restriction list is whatever
485 * is not handled in the sub-relations, so it depends on which
486 * sub-relations are considered.
488 * If a join clause from an input relation refers to base rels still not
489 * present in the joinrel, then it is still a join clause for the joinrel;
490 * we put it into the joininfo list for the joinrel. Otherwise,
491 * the clause is now a restrict clause for the joined relation, and we
492 * return it to the caller of build_joinrel_restrictlist() to be stored in
493 * join paths made from this pair of sub-relations. (It will not need to
494 * be considered further up the join tree.)
496 * When building a restriction list, we eliminate redundant clauses.
497 * We don't try to do that for join clause lists, since the join clauses
498 * aren't really doing anything, just waiting to become part of higher
499 * levels' restriction lists.
501 * 'joinrel' is a join relation node
502 * 'outer_rel' and 'inner_rel' are a pair of relations that can be joined
504 * 'jointype' is the type of join used.
506 * build_joinrel_restrictlist() returns a list of relevant restrictinfos,
507 * whereas build_joinrel_joinlist() stores its results in the joinrel's
508 * joininfo list. One or the other must accept each given clause!
510 * NB: Formerly, we made deep(!) copies of each input RestrictInfo to pass
511 * up to the join relation. I believe this is no longer necessary, because
512 * RestrictInfo nodes are no longer context-dependent. Instead, just include
513 * the original nodes in the lists made for the join relation.
516 build_joinrel_restrictlist(PlannerInfo *root,
518 RelOptInfo *outer_rel,
519 RelOptInfo *inner_rel,
526 * Collect all the clauses that syntactically belong at this level.
528 rlist = list_concat(subbuild_joinrel_restrictlist(joinrel,
529 outer_rel->joininfo),
530 subbuild_joinrel_restrictlist(joinrel,
531 inner_rel->joininfo));
534 * Eliminate duplicate and redundant clauses.
536 * We must eliminate duplicates, since we will see many of the same
537 * clauses arriving from both input relations. Also, if a clause is a
538 * mergejoinable clause, it's possible that it is redundant with previous
539 * clauses (see optimizer/README for discussion). We detect that case and
540 * omit the redundant clause from the result list.
542 result = remove_redundant_join_clauses(root, rlist,
543 IS_OUTER_JOIN(jointype));
551 build_joinrel_joinlist(RelOptInfo *joinrel,
552 RelOptInfo *outer_rel,
553 RelOptInfo *inner_rel)
555 subbuild_joinrel_joinlist(joinrel, outer_rel->joininfo);
556 subbuild_joinrel_joinlist(joinrel, inner_rel->joininfo);
560 subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
563 List *restrictlist = NIL;
566 foreach(l, joininfo_list)
568 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
570 if (bms_is_subset(rinfo->required_relids, joinrel->relids))
573 * This clause becomes a restriction clause for the joinrel, since
574 * it refers to no outside rels. We don't bother to check for
575 * duplicates here --- build_joinrel_restrictlist will do that.
577 restrictlist = lappend(restrictlist, rinfo);
582 * This clause is still a join clause at this level, so we ignore
583 * it in this routine.
592 subbuild_joinrel_joinlist(RelOptInfo *joinrel,
597 foreach(l, joininfo_list)
599 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
601 if (bms_is_subset(rinfo->required_relids, joinrel->relids))
604 * This clause becomes a restriction clause for the joinrel, since
605 * it refers to no outside rels. So we can ignore it in this
612 * This clause is still a join clause at this level, so add it to
613 * the joininfo list for the joinrel, being careful to eliminate
614 * duplicates. (Since RestrictInfo nodes are normally
615 * multiply-linked rather than copied, pointer equality should be
616 * a sufficient test. If two equal() nodes should happen to sneak
617 * in, no great harm is done --- they'll be detected by
618 * redundant-clause testing when they reach a restriction list.)
620 joinrel->joininfo = list_append_unique_ptr(joinrel->joininfo,