1 /*-------------------------------------------------------------------------
4 * Relation-node lookup/construction routines
6 * Portions Copyright (c) 1996-2003, 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.58 2004/05/30 23:40:31 neilc 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"
26 static RelOptInfo *make_base_rel(Query *root, int relid);
27 static void build_joinrel_tlist(Query *root, RelOptInfo *joinrel);
28 static List *build_joinrel_restrictlist(Query *root,
30 RelOptInfo *outer_rel,
31 RelOptInfo *inner_rel,
33 static void build_joinrel_joinlist(RelOptInfo *joinrel,
34 RelOptInfo *outer_rel,
35 RelOptInfo *inner_rel);
36 static List *subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
38 static void subbuild_joinrel_joinlist(RelOptInfo *joinrel,
44 * Construct a new base relation RelOptInfo, and put it in the query's
48 build_base_rel(Query *root, int relid)
53 /* Rel should not exist already */
54 foreach(l, root->base_rel_list)
56 rel = (RelOptInfo *) lfirst(l);
57 if (relid == rel->relid)
58 elog(ERROR, "rel already exists");
61 /* It should not exist as an "other" rel, either */
62 foreach(l, root->other_rel_list)
64 rel = (RelOptInfo *) lfirst(l);
65 if (relid == rel->relid)
66 elog(ERROR, "rel already exists as \"other\" rel");
69 /* No existing RelOptInfo for this base rel, so make a new one */
70 rel = make_base_rel(root, relid);
72 /* and add it to the list */
73 root->base_rel_list = lcons(rel, root->base_rel_list);
78 * Returns relation entry corresponding to 'relid', creating a new one
79 * if necessary. This is for 'other' relations, which are much like
80 * base relations except that they live in a different list.
83 build_other_rel(Query *root, int relid)
89 foreach(l, root->other_rel_list)
91 rel = (RelOptInfo *) lfirst(l);
92 if (relid == rel->relid)
96 /* It should not exist as a base rel */
97 foreach(l, root->base_rel_list)
99 rel = (RelOptInfo *) lfirst(l);
100 if (relid == rel->relid)
101 elog(ERROR, "rel already exists as base rel");
104 /* No existing RelOptInfo for this other rel, so make a new one */
105 rel = make_base_rel(root, relid);
107 /* presently, must be an inheritance child rel */
108 Assert(rel->reloptkind == RELOPT_BASEREL);
109 rel->reloptkind = RELOPT_OTHER_CHILD_REL;
111 /* and add it to the list */
112 root->other_rel_list = lcons(rel, root->other_rel_list);
119 * Construct a base-relation RelOptInfo for the specified rangetable index.
121 * Common code for build_base_rel and build_other_rel.
124 make_base_rel(Query *root, int relid)
126 RelOptInfo *rel = makeNode(RelOptInfo);
127 RangeTblEntry *rte = rt_fetch(relid, root->rtable);
129 rel->reloptkind = RELOPT_BASEREL;
130 rel->relids = bms_make_singleton(relid);
133 FastListInit(&rel->reltargetlist);
135 rel->cheapest_startup_path = NULL;
136 rel->cheapest_total_path = NULL;
137 rel->cheapest_unique_path = NULL;
139 rel->rtekind = rte->rtekind;
140 /* min_attr, max_attr, attr_needed, attr_widths are set below */
141 rel->indexlist = NIL;
145 rel->baserestrictinfo = NIL;
146 rel->baserestrictcost.startup = 0;
147 rel->baserestrictcost.per_tuple = 0;
148 rel->outerjoinset = NULL;
150 rel->index_outer_relids = NULL;
151 rel->index_inner_paths = NIL;
153 /* Check type of rtable entry */
154 switch (rte->rtekind)
157 /* Table --- retrieve statistics from the system catalogs */
158 get_relation_info(rte->relid, rel);
162 /* Subquery or function --- need only set up attr range */
163 /* Note: 0 is included in range to support whole-row Vars */
165 rel->max_attr = list_length(rte->eref->colnames);
168 elog(ERROR, "unrecognized RTE kind: %d",
173 Assert(rel->max_attr >= rel->min_attr);
174 rel->attr_needed = (Relids *)
175 palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
176 rel->attr_widths = (int32 *)
177 palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
184 * Find a base or other relation entry, which must already exist
185 * (since we'd have no idea which list to add it to).
188 find_base_rel(Query *root, int relid)
193 foreach(l, root->base_rel_list)
195 rel = (RelOptInfo *) lfirst(l);
196 if (relid == rel->relid)
200 foreach(l, root->other_rel_list)
202 rel = (RelOptInfo *) lfirst(l);
203 if (relid == rel->relid)
207 elog(ERROR, "no relation entry for relid %d", relid);
209 return NULL; /* keep compiler quiet */
214 * Returns relation entry corresponding to 'relids' (a set of RT indexes),
215 * or NULL if none exists. This is for join relations.
218 find_join_rel(Query *root, Relids relids)
222 foreach(l, root->join_rel_list)
224 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
226 if (bms_equal(rel->relids, relids))
235 * Returns relation entry corresponding to the union of two given rels,
236 * creating a new relation entry if none already exists.
238 * 'joinrelids' is the Relids set that uniquely identifies the join
239 * 'outer_rel' and 'inner_rel' are relation nodes for the relations to be
241 * 'jointype': type of join (inner/outer)
242 * 'restrictlist_ptr': result variable. If not NULL, *restrictlist_ptr
243 * receives the list of RestrictInfo nodes that apply to this
244 * particular pair of joinable relations.
246 * restrictlist_ptr makes the routine's API a little grotty, but it saves
247 * duplicated calculation of the restrictlist...
250 build_join_rel(Query *root,
252 RelOptInfo *outer_rel,
253 RelOptInfo *inner_rel,
255 List **restrictlist_ptr)
261 * See if we already have a joinrel for this set of base rels.
263 joinrel = find_join_rel(root, joinrelids);
268 * Yes, so we only need to figure the restrictlist for this
269 * particular pair of component relations.
271 if (restrictlist_ptr)
272 *restrictlist_ptr = build_joinrel_restrictlist(root,
283 joinrel = makeNode(RelOptInfo);
284 joinrel->reloptkind = RELOPT_JOINREL;
285 joinrel->relids = bms_copy(joinrelids);
288 FastListInit(&joinrel->reltargetlist);
289 joinrel->pathlist = NIL;
290 joinrel->cheapest_startup_path = NULL;
291 joinrel->cheapest_total_path = NULL;
292 joinrel->cheapest_unique_path = NULL;
293 joinrel->relid = 0; /* indicates not a baserel */
294 joinrel->rtekind = RTE_JOIN;
295 joinrel->min_attr = 0;
296 joinrel->max_attr = 0;
297 joinrel->attr_needed = NULL;
298 joinrel->attr_widths = NULL;
299 joinrel->indexlist = NIL;
302 joinrel->subplan = NULL;
303 joinrel->baserestrictinfo = NIL;
304 joinrel->baserestrictcost.startup = 0;
305 joinrel->baserestrictcost.per_tuple = 0;
306 joinrel->outerjoinset = NULL;
307 joinrel->joininfo = NIL;
308 joinrel->index_outer_relids = NULL;
309 joinrel->index_inner_paths = NIL;
312 * Create a new tlist containing just the vars that need to be output
313 * from this join (ie, are needed for higher joinclauses or final
316 build_joinrel_tlist(root, joinrel);
319 * Construct restrict and join clause lists for the new joinrel. (The
320 * caller might or might not need the restrictlist, but I need it
321 * anyway for set_joinrel_size_estimates().)
323 restrictlist = build_joinrel_restrictlist(root,
328 if (restrictlist_ptr)
329 *restrictlist_ptr = restrictlist;
330 build_joinrel_joinlist(joinrel, outer_rel, inner_rel);
333 * Set estimates of the joinrel's size.
335 set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
336 jointype, restrictlist);
339 * Add the joinrel to the query's joinrel list.
341 root->join_rel_list = lcons(joinrel, root->join_rel_list);
347 * build_joinrel_tlist
348 * Builds a join relation's target list.
350 * The join's targetlist includes all Vars of its member relations that
351 * will still be needed above the join.
353 * In a former lifetime, this just merged the tlists of the two member
354 * relations first presented. While we could still do that, working from
355 * lists of Vars would mean doing a find_base_rel lookup for each Var.
356 * It seems more efficient to scan the list of base rels and collect the
357 * needed vars directly from there.
359 * We also compute the expected width of the join's output, making use
360 * of data that was cached at the baserel level by set_rel_width().
363 build_joinrel_tlist(Query *root, RelOptInfo *joinrel)
365 Relids relids = joinrel->relids;
368 FastListInit(&joinrel->reltargetlist);
371 foreach(rels, root->base_rel_list)
373 RelOptInfo *baserel = (RelOptInfo *) lfirst(rels);
376 if (!bms_is_member(baserel->relid, relids))
379 foreach(vars, FastListValue(&baserel->reltargetlist))
381 Var *var = (Var *) lfirst(vars);
382 int ndx = var->varattno - baserel->min_attr;
384 if (bms_nonempty_difference(baserel->attr_needed[ndx], relids))
386 FastAppend(&joinrel->reltargetlist, var);
387 Assert(baserel->attr_widths[ndx] > 0);
388 joinrel->width += baserel->attr_widths[ndx];
395 * build_joinrel_restrictlist
396 * build_joinrel_joinlist
397 * These routines build lists of restriction and join clauses for a
398 * join relation from the joininfo lists of the relations it joins.
400 * These routines are separate because the restriction list must be
401 * built afresh for each pair of input sub-relations we consider, whereas
402 * the join lists need only be computed once for any join RelOptInfo.
403 * The join lists are fully determined by the set of rels making up the
404 * joinrel, so we should get the same results (up to ordering) from any
405 * candidate pair of sub-relations. But the restriction list is whatever
406 * is not handled in the sub-relations, so it depends on which
407 * sub-relations are considered.
409 * If a join clause from an input relation refers to base rels still not
410 * present in the joinrel, then it is still a join clause for the joinrel;
411 * we put it into an appropriate JoinInfo list for the joinrel. Otherwise,
412 * the clause is now a restrict clause for the joined relation, and we
413 * return it to the caller of build_joinrel_restrictlist() to be stored in
414 * join paths made from this pair of sub-relations. (It will not need to
415 * be considered further up the join tree.)
417 * When building a restriction list, we eliminate redundant clauses.
418 * We don't try to do that for join clause lists, since the join clauses
419 * aren't really doing anything, just waiting to become part of higher
420 * levels' restriction lists.
422 * 'joinrel' is a join relation node
423 * 'outer_rel' and 'inner_rel' are a pair of relations that can be joined
425 * 'jointype' is the type of join used.
427 * build_joinrel_restrictlist() returns a list of relevant restrictinfos,
428 * whereas build_joinrel_joinlist() stores its results in the joinrel's
429 * joininfo lists. One or the other must accept each given clause!
431 * NB: Formerly, we made deep(!) copies of each input RestrictInfo to pass
432 * up to the join relation. I believe this is no longer necessary, because
433 * RestrictInfo nodes are no longer context-dependent. Instead, just include
434 * the original nodes in the lists made for the join relation.
437 build_joinrel_restrictlist(Query *root,
439 RelOptInfo *outer_rel,
440 RelOptInfo *inner_rel,
447 * Collect all the clauses that syntactically belong at this level.
449 rlist = list_concat(subbuild_joinrel_restrictlist(joinrel,
450 outer_rel->joininfo),
451 subbuild_joinrel_restrictlist(joinrel,
452 inner_rel->joininfo));
455 * Eliminate duplicate and redundant clauses.
457 * We must eliminate duplicates, since we will see many of the same
458 * clauses arriving from both input relations. Also, if a clause is a
459 * mergejoinable clause, it's possible that it is redundant with
460 * previous clauses (see optimizer/README for discussion). We detect
461 * that case and omit the redundant clause from the result list.
463 result = remove_redundant_join_clauses(root, rlist, jointype);
471 build_joinrel_joinlist(RelOptInfo *joinrel,
472 RelOptInfo *outer_rel,
473 RelOptInfo *inner_rel)
475 subbuild_joinrel_joinlist(joinrel, outer_rel->joininfo);
476 subbuild_joinrel_joinlist(joinrel, inner_rel->joininfo);
480 subbuild_joinrel_restrictlist(RelOptInfo *joinrel,
483 List *restrictlist = NIL;
486 foreach(xjoininfo, joininfo_list)
488 JoinInfo *joininfo = (JoinInfo *) lfirst(xjoininfo);
490 if (bms_is_subset(joininfo->unjoined_relids, joinrel->relids))
493 * Clauses in this JoinInfo list become restriction clauses
494 * for the joinrel, since they refer to no outside rels.
496 * We must copy the list to avoid disturbing the input relation,
497 * but we can use a shallow copy.
499 restrictlist = list_concat(restrictlist,
500 list_copy(joininfo->jinfo_restrictinfo));
505 * These clauses are still join clauses at this level, so we
506 * ignore them in this routine.
515 subbuild_joinrel_joinlist(RelOptInfo *joinrel,
520 foreach(xjoininfo, joininfo_list)
522 JoinInfo *joininfo = (JoinInfo *) lfirst(xjoininfo);
523 Relids new_unjoined_relids;
525 new_unjoined_relids = bms_difference(joininfo->unjoined_relids,
527 if (bms_is_empty(new_unjoined_relids))
530 * Clauses in this JoinInfo list become restriction clauses
531 * for the joinrel, since they refer to no outside rels. So we
532 * can ignore them in this routine.
534 bms_free(new_unjoined_relids);
539 * These clauses are still join clauses at this level, so find
540 * or make the appropriate JoinInfo item for the joinrel, and
541 * add the clauses to it, eliminating duplicates. (Since
542 * RestrictInfo nodes are normally multiply-linked rather than
543 * copied, pointer equality should be a sufficient test. If
544 * two equal() nodes should happen to sneak in, no great harm
545 * is done --- they'll be detected by redundant-clause testing
546 * when they reach a restriction list.)
548 JoinInfo *new_joininfo;
550 new_joininfo = make_joininfo_node(joinrel, new_unjoined_relids);
551 new_joininfo->jinfo_restrictinfo =
552 list_union_ptr(new_joininfo->jinfo_restrictinfo,
553 joininfo->jinfo_restrictinfo);