]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/allpaths.c
458dae0489c029bd743c75c82f8e5102067e89bf
[postgresql] / src / backend / optimizer / path / allpaths.c
1 /*-------------------------------------------------------------------------
2  *
3  * allpaths.c
4  *        Routines to find possible search paths for processing a query
5  *
6  * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/optimizer/path/allpaths.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <math.h>
19
20 #include "catalog/pg_class.h"
21 #include "foreign/fdwapi.h"
22 #include "nodes/nodeFuncs.h"
23 #ifdef OPTIMIZER_DEBUG
24 #include "nodes/print.h"
25 #endif
26 #include "optimizer/clauses.h"
27 #include "optimizer/cost.h"
28 #include "optimizer/geqo.h"
29 #include "optimizer/pathnode.h"
30 #include "optimizer/paths.h"
31 #include "optimizer/plancat.h"
32 #include "optimizer/planner.h"
33 #include "optimizer/prep.h"
34 #include "optimizer/restrictinfo.h"
35 #include "optimizer/var.h"
36 #include "parser/parse_clause.h"
37 #include "parser/parsetree.h"
38 #include "rewrite/rewriteManip.h"
39 #include "utils/lsyscache.h"
40
41
42 /* These parameters are set by GUC */
43 bool            enable_geqo = false;    /* just in case GUC doesn't set it */
44 int                     geqo_threshold;
45
46 /* Hook for plugins to replace standard_join_search() */
47 join_search_hook_type join_search_hook = NULL;
48
49
50 static void set_base_rel_sizes(PlannerInfo *root);
51 static void set_base_rel_pathlists(PlannerInfo *root);
52 static void set_rel_size(PlannerInfo *root, RelOptInfo *rel,
53                          Index rti, RangeTblEntry *rte);
54 static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
55                                  Index rti, RangeTblEntry *rte);
56 static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel,
57                                    RangeTblEntry *rte);
58 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
59                                            RangeTblEntry *rte);
60 static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel,
61                                  RangeTblEntry *rte);
62 static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel,
63                                          RangeTblEntry *rte);
64 static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
65                                         Index rti, RangeTblEntry *rte);
66 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
67                                                 Index rti, RangeTblEntry *rte);
68 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
69                                                    List *live_childrels,
70                                                    List *all_child_pathkeys);
71 static List *accumulate_append_subpath(List *subpaths, Path *path);
72 static void set_dummy_rel_pathlist(RelOptInfo *rel);
73 static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
74                                           Index rti, RangeTblEntry *rte);
75 static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
76                                           RangeTblEntry *rte);
77 static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel,
78                                         RangeTblEntry *rte);
79 static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel,
80                                  RangeTblEntry *rte);
81 static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel,
82                                            RangeTblEntry *rte);
83 static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
84 static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
85                                                   bool *differentTypes);
86 static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
87                                           bool *differentTypes);
88 static void compare_tlist_datatypes(List *tlist, List *colTypes,
89                                                 bool *differentTypes);
90 static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
91                                           bool *differentTypes);
92 static void subquery_push_qual(Query *subquery,
93                                    RangeTblEntry *rte, Index rti, Node *qual);
94 static void recurse_push_qual(Node *setOp, Query *topquery,
95                                   RangeTblEntry *rte, Index rti, Node *qual);
96
97
98 /*
99  * make_one_rel
100  *        Finds all possible access paths for executing a query, returning a
101  *        single rel that represents the join of all base rels in the query.
102  */
103 RelOptInfo *
104 make_one_rel(PlannerInfo *root, List *joinlist)
105 {
106         RelOptInfo *rel;
107         Index           rti;
108
109         /*
110          * Construct the all_baserels Relids set.
111          */
112         root->all_baserels = NULL;
113         for (rti = 1; rti < root->simple_rel_array_size; rti++)
114         {
115                 RelOptInfo *brel = root->simple_rel_array[rti];
116
117                 /* there may be empty slots corresponding to non-baserel RTEs */
118                 if (brel == NULL)
119                         continue;
120
121                 Assert(brel->relid == rti);             /* sanity check on array */
122
123                 /* ignore RTEs that are "other rels" */
124                 if (brel->reloptkind != RELOPT_BASEREL)
125                         continue;
126
127                 root->all_baserels = bms_add_member(root->all_baserels, brel->relid);
128         }
129
130         /*
131          * Generate access paths for the base rels.
132          */
133         set_base_rel_sizes(root);
134         set_base_rel_pathlists(root);
135
136         /*
137          * Generate access paths for the entire join tree.
138          */
139         rel = make_rel_from_joinlist(root, joinlist);
140
141         /*
142          * The result should join all and only the query's base rels.
143          */
144         Assert(bms_equal(rel->relids, root->all_baserels));
145
146         return rel;
147 }
148
149 /*
150  * set_base_rel_sizes
151  *        Set the size estimates (rows and widths) for each base-relation entry.
152  *
153  * We do this in a separate pass over the base rels so that rowcount
154  * estimates are available for parameterized path generation.
155  */
156 static void
157 set_base_rel_sizes(PlannerInfo *root)
158 {
159         Index           rti;
160
161         for (rti = 1; rti < root->simple_rel_array_size; rti++)
162         {
163                 RelOptInfo *rel = root->simple_rel_array[rti];
164
165                 /* there may be empty slots corresponding to non-baserel RTEs */
166                 if (rel == NULL)
167                         continue;
168
169                 Assert(rel->relid == rti);              /* sanity check on array */
170
171                 /* ignore RTEs that are "other rels" */
172                 if (rel->reloptkind != RELOPT_BASEREL)
173                         continue;
174
175                 set_rel_size(root, rel, rti, root->simple_rte_array[rti]);
176         }
177 }
178
179 /*
180  * set_base_rel_pathlists
181  *        Finds all paths available for scanning each base-relation entry.
182  *        Sequential scan and any available indices are considered.
183  *        Each useful path is attached to its relation's 'pathlist' field.
184  */
185 static void
186 set_base_rel_pathlists(PlannerInfo *root)
187 {
188         Index           rti;
189
190         for (rti = 1; rti < root->simple_rel_array_size; rti++)
191         {
192                 RelOptInfo *rel = root->simple_rel_array[rti];
193
194                 /* there may be empty slots corresponding to non-baserel RTEs */
195                 if (rel == NULL)
196                         continue;
197
198                 Assert(rel->relid == rti);              /* sanity check on array */
199
200                 /* ignore RTEs that are "other rels" */
201                 if (rel->reloptkind != RELOPT_BASEREL)
202                         continue;
203
204                 set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
205         }
206 }
207
208 /*
209  * set_rel_size
210  *        Set size estimates for a base relation
211  */
212 static void
213 set_rel_size(PlannerInfo *root, RelOptInfo *rel,
214                          Index rti, RangeTblEntry *rte)
215 {
216         if (rel->reloptkind == RELOPT_BASEREL &&
217                 relation_excluded_by_constraints(root, rel, rte))
218         {
219                 /*
220                  * We proved we don't need to scan the rel via constraint exclusion,
221                  * so set up a single dummy path for it.  Here we only check this for
222                  * regular baserels; if it's an otherrel, CE was already checked in
223                  * set_append_rel_pathlist().
224                  *
225                  * In this case, we go ahead and set up the relation's path right away
226                  * instead of leaving it for set_rel_pathlist to do.  This is because
227                  * we don't have a convention for marking a rel as dummy except by
228                  * assigning a dummy path to it.
229                  */
230                 set_dummy_rel_pathlist(rel);
231         }
232         else if (rte->inh)
233         {
234                 /* It's an "append relation", process accordingly */
235                 set_append_rel_size(root, rel, rti, rte);
236         }
237         else
238         {
239                 switch (rel->rtekind)
240                 {
241                         case RTE_RELATION:
242                                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
243                                 {
244                                         /* Foreign table */
245                                         set_foreign_size(root, rel, rte);
246                                 }
247                                 else
248                                 {
249                                         /* Plain relation */
250                                         set_plain_rel_size(root, rel, rte);
251                                 }
252                                 break;
253                         case RTE_SUBQUERY:
254
255                                 /*
256                                  * Subqueries don't support making a choice between
257                                  * parameterized and unparameterized paths, so just go ahead
258                                  * and build their paths immediately.
259                                  */
260                                 set_subquery_pathlist(root, rel, rti, rte);
261                                 break;
262                         case RTE_FUNCTION:
263                                 set_function_size_estimates(root, rel);
264                                 break;
265                         case RTE_VALUES:
266                                 set_values_size_estimates(root, rel);
267                                 break;
268                         case RTE_CTE:
269
270                                 /*
271                                  * CTEs don't support making a choice between parameterized
272                                  * and unparameterized paths, so just go ahead and build their
273                                  * paths immediately.
274                                  */
275                                 if (rte->self_reference)
276                                         set_worktable_pathlist(root, rel, rte);
277                                 else
278                                         set_cte_pathlist(root, rel, rte);
279                                 break;
280                         default:
281                                 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
282                                 break;
283                 }
284         }
285 }
286
287 /*
288  * set_rel_pathlist
289  *        Build access paths for a base relation
290  */
291 static void
292 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
293                                  Index rti, RangeTblEntry *rte)
294 {
295         if (IS_DUMMY_REL(rel))
296         {
297                 /* We already proved the relation empty, so nothing more to do */
298         }
299         else if (rte->inh)
300         {
301                 /* It's an "append relation", process accordingly */
302                 set_append_rel_pathlist(root, rel, rti, rte);
303         }
304         else
305         {
306                 switch (rel->rtekind)
307                 {
308                         case RTE_RELATION:
309                                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
310                                 {
311                                         /* Foreign table */
312                                         set_foreign_pathlist(root, rel, rte);
313                                 }
314                                 else
315                                 {
316                                         /* Plain relation */
317                                         set_plain_rel_pathlist(root, rel, rte);
318                                 }
319                                 break;
320                         case RTE_SUBQUERY:
321                                 /* Subquery --- fully handled during set_rel_size */
322                                 break;
323                         case RTE_FUNCTION:
324                                 /* RangeFunction */
325                                 set_function_pathlist(root, rel, rte);
326                                 break;
327                         case RTE_VALUES:
328                                 /* Values list */
329                                 set_values_pathlist(root, rel, rte);
330                                 break;
331                         case RTE_CTE:
332                                 /* CTE reference --- fully handled during set_rel_size */
333                                 break;
334                         default:
335                                 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
336                                 break;
337                 }
338         }
339
340 #ifdef OPTIMIZER_DEBUG
341         debug_print_rel(root, rel);
342 #endif
343 }
344
345 /*
346  * set_plain_rel_size
347  *        Set size estimates for a plain relation (no subquery, no inheritance)
348  */
349 static void
350 set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
351 {
352         /*
353          * Test any partial indexes of rel for applicability.  We must do this
354          * first since partial unique indexes can affect size estimates.
355          */
356         check_partial_indexes(root, rel);
357
358         /* Mark rel with estimated output rows, width, etc */
359         set_baserel_size_estimates(root, rel);
360
361         /*
362          * Check to see if we can extract any restriction conditions from join
363          * quals that are OR-of-AND structures.  If so, add them to the rel's
364          * restriction list, and redo the above steps.
365          */
366         if (create_or_index_quals(root, rel))
367         {
368                 check_partial_indexes(root, rel);
369                 set_baserel_size_estimates(root, rel);
370         }
371 }
372
373 /*
374  * set_plain_rel_pathlist
375  *        Build access paths for a plain relation (no subquery, no inheritance)
376  */
377 static void
378 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
379 {
380         Relids          required_outer;
381
382         /*
383          * We don't support pushing join clauses into the quals of a seqscan, but
384          * it could still have required parameterization due to LATERAL refs in
385          * its tlist.  (That can only happen if the seqscan is on a relation
386          * pulled up out of a UNION ALL appendrel.)
387          */
388         required_outer = rel->lateral_relids;
389
390         /* Consider sequential scan */
391         add_path(rel, create_seqscan_path(root, rel, required_outer));
392
393         /* Consider index scans */
394         create_index_paths(root, rel);
395
396         /* Consider TID scans */
397         create_tidscan_paths(root, rel);
398
399         /* Now find the cheapest of the paths for this rel */
400         set_cheapest(rel);
401 }
402
403 /*
404  * set_foreign_size
405  *              Set size estimates for a foreign table RTE
406  */
407 static void
408 set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
409 {
410         /* Mark rel with estimated output rows, width, etc */
411         set_foreign_size_estimates(root, rel);
412
413         /* Get FDW routine pointers for the rel */
414         rel->fdwroutine = GetFdwRoutineByRelId(rte->relid);
415
416         /* Let FDW adjust the size estimates, if it can */
417         rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
418 }
419
420 /*
421  * set_foreign_pathlist
422  *              Build access paths for a foreign table RTE
423  */
424 static void
425 set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
426 {
427         /* Call the FDW's GetForeignPaths function to generate path(s) */
428         rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
429
430         /* Select cheapest path */
431         set_cheapest(rel);
432 }
433
434 /*
435  * set_append_rel_size
436  *        Set size estimates for an "append relation"
437  *
438  * The passed-in rel and RTE represent the entire append relation.      The
439  * relation's contents are computed by appending together the output of
440  * the individual member relations.  Note that in the inheritance case,
441  * the first member relation is actually the same table as is mentioned in
442  * the parent RTE ... but it has a different RTE and RelOptInfo.  This is
443  * a good thing because their outputs are not the same size.
444  */
445 static void
446 set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
447                                         Index rti, RangeTblEntry *rte)
448 {
449         int                     parentRTindex = rti;
450         double          parent_rows;
451         double          parent_size;
452         double     *parent_attrsizes;
453         int                     nattrs;
454         ListCell   *l;
455
456         /*
457          * Initialize to compute size estimates for whole append relation.
458          *
459          * We handle width estimates by weighting the widths of different child
460          * rels proportionally to their number of rows.  This is sensible because
461          * the use of width estimates is mainly to compute the total relation
462          * "footprint" if we have to sort or hash it.  To do this, we sum the
463          * total equivalent size (in "double" arithmetic) and then divide by the
464          * total rowcount estimate.  This is done separately for the total rel
465          * width and each attribute.
466          *
467          * Note: if you consider changing this logic, beware that child rels could
468          * have zero rows and/or width, if they were excluded by constraints.
469          */
470         parent_rows = 0;
471         parent_size = 0;
472         nattrs = rel->max_attr - rel->min_attr + 1;
473         parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
474
475         foreach(l, root->append_rel_list)
476         {
477                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
478                 int                     childRTindex;
479                 RangeTblEntry *childRTE;
480                 RelOptInfo *childrel;
481                 List       *childquals;
482                 Node       *childqual;
483                 ListCell   *parentvars;
484                 ListCell   *childvars;
485
486                 /* append_rel_list contains all append rels; ignore others */
487                 if (appinfo->parent_relid != parentRTindex)
488                         continue;
489
490                 childRTindex = appinfo->child_relid;
491                 childRTE = root->simple_rte_array[childRTindex];
492
493                 /*
494                  * The child rel's RelOptInfo was already created during
495                  * add_base_rels_to_query.
496                  */
497                 childrel = find_base_rel(root, childRTindex);
498                 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
499
500                 /*
501                  * We have to copy the parent's targetlist and quals to the child,
502                  * with appropriate substitution of variables.  However, only the
503                  * baserestrictinfo quals are needed before we can check for
504                  * constraint exclusion; so do that first and then check to see if we
505                  * can disregard this child.
506                  *
507                  * As of 8.4, the child rel's targetlist might contain non-Var
508                  * expressions, which means that substitution into the quals could
509                  * produce opportunities for const-simplification, and perhaps even
510                  * pseudoconstant quals.  To deal with this, we strip the RestrictInfo
511                  * nodes, do the substitution, do const-simplification, and then
512                  * reconstitute the RestrictInfo layer.
513                  */
514                 childquals = get_all_actual_clauses(rel->baserestrictinfo);
515                 childquals = (List *) adjust_appendrel_attrs(root,
516                                                                                                          (Node *) childquals,
517                                                                                                          appinfo);
518                 childqual = eval_const_expressions(root, (Node *)
519                                                                                    make_ands_explicit(childquals));
520                 if (childqual && IsA(childqual, Const) &&
521                         (((Const *) childqual)->constisnull ||
522                          !DatumGetBool(((Const *) childqual)->constvalue)))
523                 {
524                         /*
525                          * Restriction reduces to constant FALSE or constant NULL after
526                          * substitution, so this child need not be scanned.
527                          */
528                         set_dummy_rel_pathlist(childrel);
529                         continue;
530                 }
531                 childquals = make_ands_implicit((Expr *) childqual);
532                 childquals = make_restrictinfos_from_actual_clauses(root,
533                                                                                                                         childquals);
534                 childrel->baserestrictinfo = childquals;
535
536                 if (relation_excluded_by_constraints(root, childrel, childRTE))
537                 {
538                         /*
539                          * This child need not be scanned, so we can omit it from the
540                          * appendrel.
541                          */
542                         set_dummy_rel_pathlist(childrel);
543                         continue;
544                 }
545
546                 /*
547                  * CE failed, so finish copying/modifying targetlist and join quals.
548                  *
549                  * Note: the resulting childrel->reltargetlist may contain arbitrary
550                  * expressions, which otherwise would not occur in a reltargetlist.
551                  * Code that might be looking at an appendrel child must cope with
552                  * such.  Note in particular that "arbitrary expression" can include
553                  * "Var belonging to another relation", due to LATERAL references.
554                  */
555                 childrel->joininfo = (List *)
556                         adjust_appendrel_attrs(root,
557                                                                    (Node *) rel->joininfo,
558                                                                    appinfo);
559                 childrel->reltargetlist = (List *)
560                         adjust_appendrel_attrs(root,
561                                                                    (Node *) rel->reltargetlist,
562                                                                    appinfo);
563
564                 /*
565                  * We have to make child entries in the EquivalenceClass data
566                  * structures as well.  This is needed either if the parent
567                  * participates in some eclass joins (because we will want to consider
568                  * inner-indexscan joins on the individual children) or if the parent
569                  * has useful pathkeys (because we should try to build MergeAppend
570                  * paths that produce those sort orderings).
571                  */
572                 if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
573                         add_child_rel_equivalences(root, appinfo, rel, childrel);
574                 childrel->has_eclass_joins = rel->has_eclass_joins;
575
576                 /*
577                  * Note: we could compute appropriate attr_needed data for the child's
578                  * variables, by transforming the parent's attr_needed through the
579                  * translated_vars mapping.  However, currently there's no need
580                  * because attr_needed is only examined for base relations not
581                  * otherrels.  So we just leave the child's attr_needed empty.
582                  */
583
584                 /*
585                  * Compute the child's size.
586                  */
587                 set_rel_size(root, childrel, childRTindex, childRTE);
588
589                 /*
590                  * It is possible that constraint exclusion detected a contradiction
591                  * within a child subquery, even though we didn't prove one above. If
592                  * so, we can skip this child.
593                  */
594                 if (IS_DUMMY_REL(childrel))
595                         continue;
596
597                 /*
598                  * Accumulate size information from each live child.
599                  */
600                 if (childrel->rows > 0)
601                 {
602                         parent_rows += childrel->rows;
603                         parent_size += childrel->width * childrel->rows;
604
605                         /*
606                          * Accumulate per-column estimates too.  We need not do anything
607                          * for PlaceHolderVars in the parent list.      If child expression
608                          * isn't a Var, or we didn't record a width estimate for it, we
609                          * have to fall back on a datatype-based estimate.
610                          *
611                          * By construction, child's reltargetlist is 1-to-1 with parent's.
612                          */
613                         forboth(parentvars, rel->reltargetlist,
614                                         childvars, childrel->reltargetlist)
615                         {
616                                 Var                *parentvar = (Var *) lfirst(parentvars);
617                                 Node       *childvar = (Node *) lfirst(childvars);
618
619                                 if (IsA(parentvar, Var))
620                                 {
621                                         int                     pndx = parentvar->varattno - rel->min_attr;
622                                         int32           child_width = 0;
623
624                                         if (IsA(childvar, Var) &&
625                                                 ((Var *) childvar)->varno == childrel->relid)
626                                         {
627                                                 int                     cndx = ((Var *) childvar)->varattno - childrel->min_attr;
628
629                                                 child_width = childrel->attr_widths[cndx];
630                                         }
631                                         if (child_width <= 0)
632                                                 child_width = get_typavgwidth(exprType(childvar),
633                                                                                                           exprTypmod(childvar));
634                                         Assert(child_width > 0);
635                                         parent_attrsizes[pndx] += child_width * childrel->rows;
636                                 }
637                         }
638                 }
639         }
640
641         /*
642          * Save the finished size estimates.
643          */
644         rel->rows = parent_rows;
645         if (parent_rows > 0)
646         {
647                 int                     i;
648
649                 rel->width = rint(parent_size / parent_rows);
650                 for (i = 0; i < nattrs; i++)
651                         rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
652         }
653         else
654                 rel->width = 0;                 /* attr_widths should be zero already */
655
656         /*
657          * Set "raw tuples" count equal to "rows" for the appendrel; needed
658          * because some places assume rel->tuples is valid for any baserel.
659          */
660         rel->tuples = parent_rows;
661
662         pfree(parent_attrsizes);
663 }
664
665 /*
666  * set_append_rel_pathlist
667  *        Build access paths for an "append relation"
668  */
669 static void
670 set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
671                                                 Index rti, RangeTblEntry *rte)
672 {
673         int                     parentRTindex = rti;
674         List       *live_childrels = NIL;
675         List       *subpaths = NIL;
676         bool            subpaths_valid = true;
677         List       *all_child_pathkeys = NIL;
678         List       *all_child_outers = NIL;
679         ListCell   *l;
680
681         /*
682          * Generate access paths for each member relation, and remember the
683          * cheapest path for each one.  Also, identify all pathkeys (orderings)
684          * and parameterizations (required_outer sets) available for the member
685          * relations.
686          */
687         foreach(l, root->append_rel_list)
688         {
689                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
690                 int                     childRTindex;
691                 RangeTblEntry *childRTE;
692                 RelOptInfo *childrel;
693                 ListCell   *lcp;
694
695                 /* append_rel_list contains all append rels; ignore others */
696                 if (appinfo->parent_relid != parentRTindex)
697                         continue;
698
699                 /* Re-locate the child RTE and RelOptInfo */
700                 childRTindex = appinfo->child_relid;
701                 childRTE = root->simple_rte_array[childRTindex];
702                 childrel = root->simple_rel_array[childRTindex];
703
704                 /*
705                  * Compute the child's access paths.
706                  */
707                 set_rel_pathlist(root, childrel, childRTindex, childRTE);
708
709                 /*
710                  * If child is dummy, ignore it.
711                  */
712                 if (IS_DUMMY_REL(childrel))
713                         continue;
714
715                 /*
716                  * Child is live, so add it to the live_childrels list for use below.
717                  */
718                 live_childrels = lappend(live_childrels, childrel);
719
720                 /*
721                  * If child has an unparameterized cheapest-total path, add that to
722                  * the unparameterized Append path we are constructing for the parent.
723                  * If not, there's no workable unparameterized path.
724                  */
725                 if (childrel->cheapest_total_path->param_info == NULL)
726                         subpaths = accumulate_append_subpath(subpaths,
727                                                                                          childrel->cheapest_total_path);
728                 else
729                         subpaths_valid = false;
730
731                 /*
732                  * Collect lists of all the available path orderings and
733                  * parameterizations for all the children.      We use these as a
734                  * heuristic to indicate which sort orderings and parameterizations we
735                  * should build Append and MergeAppend paths for.
736                  */
737                 foreach(lcp, childrel->pathlist)
738                 {
739                         Path       *childpath = (Path *) lfirst(lcp);
740                         List       *childkeys = childpath->pathkeys;
741                         Relids          childouter = PATH_REQ_OUTER(childpath);
742
743                         /* Unsorted paths don't contribute to pathkey list */
744                         if (childkeys != NIL)
745                         {
746                                 ListCell   *lpk;
747                                 bool            found = false;
748
749                                 /* Have we already seen this ordering? */
750                                 foreach(lpk, all_child_pathkeys)
751                                 {
752                                         List       *existing_pathkeys = (List *) lfirst(lpk);
753
754                                         if (compare_pathkeys(existing_pathkeys,
755                                                                                  childkeys) == PATHKEYS_EQUAL)
756                                         {
757                                                 found = true;
758                                                 break;
759                                         }
760                                 }
761                                 if (!found)
762                                 {
763                                         /* No, so add it to all_child_pathkeys */
764                                         all_child_pathkeys = lappend(all_child_pathkeys,
765                                                                                                  childkeys);
766                                 }
767                         }
768
769                         /* Unparameterized paths don't contribute to param-set list */
770                         if (childouter)
771                         {
772                                 ListCell   *lco;
773                                 bool            found = false;
774
775                                 /* Have we already seen this param set? */
776                                 foreach(lco, all_child_outers)
777                                 {
778                                         Relids          existing_outers = (Relids) lfirst(lco);
779
780                                         if (bms_equal(existing_outers, childouter))
781                                         {
782                                                 found = true;
783                                                 break;
784                                         }
785                                 }
786                                 if (!found)
787                                 {
788                                         /* No, so add it to all_child_outers */
789                                         all_child_outers = lappend(all_child_outers,
790                                                                                            childouter);
791                                 }
792                         }
793                 }
794         }
795
796         /*
797          * If we found unparameterized paths for all children, build an unordered,
798          * unparameterized Append path for the rel.  (Note: this is correct even
799          * if we have zero or one live subpath due to constraint exclusion.)
800          */
801         if (subpaths_valid)
802                 add_path(rel, (Path *) create_append_path(rel, subpaths, NULL));
803
804         /*
805          * Also build unparameterized MergeAppend paths based on the collected
806          * list of child pathkeys.
807          */
808         if (subpaths_valid)
809                 generate_mergeappend_paths(root, rel, live_childrels,
810                                                                    all_child_pathkeys);
811
812         /*
813          * Build Append paths for each parameterization seen among the child rels.
814          * (This may look pretty expensive, but in most cases of practical
815          * interest, the child rels will expose mostly the same parameterizations,
816          * so that not that many cases actually get considered here.)
817          *
818          * The Append node itself cannot enforce quals, so all qual checking must
819          * be done in the child paths.  This means that to have a parameterized
820          * Append path, we must have the exact same parameterization for each
821          * child path; otherwise some children might be failing to check the
822          * moved-down quals.  To make them match up, we can try to increase the
823          * parameterization of lesser-parameterized paths.
824          */
825         foreach(l, all_child_outers)
826         {
827                 Relids          required_outer = (Relids) lfirst(l);
828                 ListCell   *lcr;
829
830                 /* Select the child paths for an Append with this parameterization */
831                 subpaths = NIL;
832                 subpaths_valid = true;
833                 foreach(lcr, live_childrels)
834                 {
835                         RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
836                         Path       *cheapest_total;
837
838                         cheapest_total =
839                                 get_cheapest_path_for_pathkeys(childrel->pathlist,
840                                                                                            NIL,
841                                                                                            required_outer,
842                                                                                            TOTAL_COST);
843                         Assert(cheapest_total != NULL);
844
845                         /* Children must have exactly the desired parameterization */
846                         if (!bms_equal(PATH_REQ_OUTER(cheapest_total), required_outer))
847                         {
848                                 cheapest_total = reparameterize_path(root, cheapest_total,
849                                                                                                          required_outer, 1.0);
850                                 if (cheapest_total == NULL)
851                                 {
852                                         subpaths_valid = false;
853                                         break;
854                                 }
855                         }
856
857                         subpaths = accumulate_append_subpath(subpaths, cheapest_total);
858                 }
859
860                 if (subpaths_valid)
861                         add_path(rel, (Path *)
862                                          create_append_path(rel, subpaths, required_outer));
863         }
864
865         /* Select cheapest paths */
866         set_cheapest(rel);
867 }
868
869 /*
870  * generate_mergeappend_paths
871  *              Generate MergeAppend paths for an append relation
872  *
873  * Generate a path for each ordering (pathkey list) appearing in
874  * all_child_pathkeys.
875  *
876  * We consider both cheapest-startup and cheapest-total cases, ie, for each
877  * interesting ordering, collect all the cheapest startup subpaths and all the
878  * cheapest total paths, and build a MergeAppend path for each case.
879  *
880  * We don't currently generate any parameterized MergeAppend paths.  While
881  * it would not take much more code here to do so, it's very unclear that it
882  * is worth the planning cycles to investigate such paths: there's little
883  * use for an ordered path on the inside of a nestloop.  In fact, it's likely
884  * that the current coding of add_path would reject such paths out of hand,
885  * because add_path gives no credit for sort ordering of parameterized paths,
886  * and a parameterized MergeAppend is going to be more expensive than the
887  * corresponding parameterized Append path.  If we ever try harder to support
888  * parameterized mergejoin plans, it might be worth adding support for
889  * parameterized MergeAppends to feed such joins.  (See notes in
890  * optimizer/README for why that might not ever happen, though.)
891  */
892 static void
893 generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
894                                                    List *live_childrels,
895                                                    List *all_child_pathkeys)
896 {
897         ListCell   *lcp;
898
899         foreach(lcp, all_child_pathkeys)
900         {
901                 List       *pathkeys = (List *) lfirst(lcp);
902                 List       *startup_subpaths = NIL;
903                 List       *total_subpaths = NIL;
904                 bool            startup_neq_total = false;
905                 ListCell   *lcr;
906
907                 /* Select the child paths for this ordering... */
908                 foreach(lcr, live_childrels)
909                 {
910                         RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
911                         Path       *cheapest_startup,
912                                            *cheapest_total;
913
914                         /* Locate the right paths, if they are available. */
915                         cheapest_startup =
916                                 get_cheapest_path_for_pathkeys(childrel->pathlist,
917                                                                                            pathkeys,
918                                                                                            NULL,
919                                                                                            STARTUP_COST);
920                         cheapest_total =
921                                 get_cheapest_path_for_pathkeys(childrel->pathlist,
922                                                                                            pathkeys,
923                                                                                            NULL,
924                                                                                            TOTAL_COST);
925
926                         /*
927                          * If we can't find any paths with the right order just use the
928                          * cheapest-total path; we'll have to sort it later.
929                          */
930                         if (cheapest_startup == NULL || cheapest_total == NULL)
931                         {
932                                 cheapest_startup = cheapest_total =
933                                         childrel->cheapest_total_path;
934                                 /* Assert we do have an unparameterized path for this child */
935                                 Assert(cheapest_total->param_info == NULL);
936                         }
937
938                         /*
939                          * Notice whether we actually have different paths for the
940                          * "cheapest" and "total" cases; frequently there will be no point
941                          * in two create_merge_append_path() calls.
942                          */
943                         if (cheapest_startup != cheapest_total)
944                                 startup_neq_total = true;
945
946                         startup_subpaths =
947                                 accumulate_append_subpath(startup_subpaths, cheapest_startup);
948                         total_subpaths =
949                                 accumulate_append_subpath(total_subpaths, cheapest_total);
950                 }
951
952                 /* ... and build the MergeAppend paths */
953                 add_path(rel, (Path *) create_merge_append_path(root,
954                                                                                                                 rel,
955                                                                                                                 startup_subpaths,
956                                                                                                                 pathkeys,
957                                                                                                                 NULL));
958                 if (startup_neq_total)
959                         add_path(rel, (Path *) create_merge_append_path(root,
960                                                                                                                         rel,
961                                                                                                                         total_subpaths,
962                                                                                                                         pathkeys,
963                                                                                                                         NULL));
964         }
965 }
966
967 /*
968  * accumulate_append_subpath
969  *              Add a subpath to the list being built for an Append or MergeAppend
970  *
971  * It's possible that the child is itself an Append path, in which case
972  * we can "cut out the middleman" and just add its child paths to our
973  * own list.  (We don't try to do this earlier because we need to
974  * apply both levels of transformation to the quals.)
975  */
976 static List *
977 accumulate_append_subpath(List *subpaths, Path *path)
978 {
979         if (IsA(path, AppendPath))
980         {
981                 AppendPath *apath = (AppendPath *) path;
982
983                 /* list_copy is important here to avoid sharing list substructure */
984                 return list_concat(subpaths, list_copy(apath->subpaths));
985         }
986         else
987                 return lappend(subpaths, path);
988 }
989
990 /*
991  * set_dummy_rel_pathlist
992  *        Build a dummy path for a relation that's been excluded by constraints
993  *
994  * Rather than inventing a special "dummy" path type, we represent this as an
995  * AppendPath with no members (see also IS_DUMMY_PATH/IS_DUMMY_REL macros).
996  */
997 static void
998 set_dummy_rel_pathlist(RelOptInfo *rel)
999 {
1000         /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
1001         rel->rows = 0;
1002         rel->width = 0;
1003
1004         /* Discard any pre-existing paths; no further need for them */
1005         rel->pathlist = NIL;
1006
1007         add_path(rel, (Path *) create_append_path(rel, NIL, NULL));
1008
1009         /* Select cheapest path (pretty easy in this case...) */
1010         set_cheapest(rel);
1011 }
1012
1013 /* quick-and-dirty test to see if any joining is needed */
1014 static bool
1015 has_multiple_baserels(PlannerInfo *root)
1016 {
1017         int                     num_base_rels = 0;
1018         Index           rti;
1019
1020         for (rti = 1; rti < root->simple_rel_array_size; rti++)
1021         {
1022                 RelOptInfo *brel = root->simple_rel_array[rti];
1023
1024                 if (brel == NULL)
1025                         continue;
1026
1027                 /* ignore RTEs that are "other rels" */
1028                 if (brel->reloptkind == RELOPT_BASEREL)
1029                         if (++num_base_rels > 1)
1030                                 return true;
1031         }
1032         return false;
1033 }
1034
1035 /*
1036  * set_subquery_pathlist
1037  *              Build the (single) access path for a subquery RTE
1038  *
1039  * We don't currently support generating parameterized paths for subqueries
1040  * by pushing join clauses down into them; it seems too expensive to re-plan
1041  * the subquery multiple times to consider different alternatives.      So the
1042  * subquery will have exactly one path.  (The path will be parameterized
1043  * if the subquery contains LATERAL references, otherwise not.)  Since there's
1044  * no freedom of action here, there's no need for a separate set_subquery_size
1045  * phase: we just make the path right away.
1046  */
1047 static void
1048 set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
1049                                           Index rti, RangeTblEntry *rte)
1050 {
1051         Query      *parse = root->parse;
1052         Query      *subquery = rte->subquery;
1053         Relids          required_outer;
1054         bool       *differentTypes;
1055         double          tuple_fraction;
1056         PlannerInfo *subroot;
1057         List       *pathkeys;
1058
1059         /*
1060          * Must copy the Query so that planning doesn't mess up the RTE contents
1061          * (really really need to fix the planner to not scribble on its input,
1062          * someday).
1063          */
1064         subquery = copyObject(subquery);
1065
1066         /*
1067          * If it's a LATERAL subquery, it might contain some Vars of the current
1068          * query level, requiring it to be treated as parameterized, even though
1069          * we don't support pushing down join quals into subqueries.
1070          */
1071         required_outer = rel->lateral_relids;
1072
1073         /* We need a workspace for keeping track of set-op type coercions */
1074         differentTypes = (bool *)
1075                 palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
1076
1077         /*
1078          * If there are any restriction clauses that have been attached to the
1079          * subquery relation, consider pushing them down to become WHERE or HAVING
1080          * quals of the subquery itself.  This transformation is useful because it
1081          * may allow us to generate a better plan for the subquery than evaluating
1082          * all the subquery output rows and then filtering them.
1083          *
1084          * There are several cases where we cannot push down clauses. Restrictions
1085          * involving the subquery are checked by subquery_is_pushdown_safe().
1086          * Restrictions on individual clauses are checked by
1087          * qual_is_pushdown_safe().  Also, we don't want to push down
1088          * pseudoconstant clauses; better to have the gating node above the
1089          * subquery.
1090          *
1091          * Also, if the sub-query has the "security_barrier" flag, it means the
1092          * sub-query originated from a view that must enforce row-level security.
1093          * Then we must not push down quals that contain leaky functions.
1094          *
1095          * Non-pushed-down clauses will get evaluated as qpquals of the
1096          * SubqueryScan node.
1097          *
1098          * XXX Are there any cases where we want to make a policy decision not to
1099          * push down a pushable qual, because it'd result in a worse plan?
1100          */
1101         if (rel->baserestrictinfo != NIL &&
1102                 subquery_is_pushdown_safe(subquery, subquery, differentTypes))
1103         {
1104                 /* OK to consider pushing down individual quals */
1105                 List       *upperrestrictlist = NIL;
1106                 ListCell   *l;
1107
1108                 foreach(l, rel->baserestrictinfo)
1109                 {
1110                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1111                         Node       *clause = (Node *) rinfo->clause;
1112
1113                         if (!rinfo->pseudoconstant &&
1114                                 (!rte->security_barrier ||
1115                                  !contain_leaky_functions(clause)) &&
1116                                 qual_is_pushdown_safe(subquery, rti, clause, differentTypes))
1117                         {
1118                                 /* Push it down */
1119                                 subquery_push_qual(subquery, rte, rti, clause);
1120                         }
1121                         else
1122                         {
1123                                 /* Keep it in the upper query */
1124                                 upperrestrictlist = lappend(upperrestrictlist, rinfo);
1125                         }
1126                 }
1127                 rel->baserestrictinfo = upperrestrictlist;
1128         }
1129
1130         pfree(differentTypes);
1131
1132         /*
1133          * We can safely pass the outer tuple_fraction down to the subquery if the
1134          * outer level has no joining, aggregation, or sorting to do. Otherwise
1135          * we'd better tell the subquery to plan for full retrieval. (XXX This
1136          * could probably be made more intelligent ...)
1137          */
1138         if (parse->hasAggs ||
1139                 parse->groupClause ||
1140                 parse->havingQual ||
1141                 parse->distinctClause ||
1142                 parse->sortClause ||
1143                 has_multiple_baserels(root))
1144                 tuple_fraction = 0.0;   /* default case */
1145         else
1146                 tuple_fraction = root->tuple_fraction;
1147
1148         /* plan_params should not be in use in current query level */
1149         Assert(root->plan_params == NIL);
1150
1151         /* Generate the plan for the subquery */
1152         rel->subplan = subquery_planner(root->glob, subquery,
1153                                                                         root,
1154                                                                         false, tuple_fraction,
1155                                                                         &subroot);
1156         rel->subroot = subroot;
1157
1158         /* Isolate the params needed by this specific subplan */
1159         rel->subplan_params = root->plan_params;
1160         root->plan_params = NIL;
1161
1162         /*
1163          * It's possible that constraint exclusion proved the subquery empty. If
1164          * so, it's convenient to turn it back into a dummy path so that we will
1165          * recognize appropriate optimizations at this level.
1166          */
1167         if (is_dummy_plan(rel->subplan))
1168         {
1169                 set_dummy_rel_pathlist(rel);
1170                 return;
1171         }
1172
1173         /* Mark rel with estimated output rows, width, etc */
1174         set_subquery_size_estimates(root, rel);
1175
1176         /* Convert subquery pathkeys to outer representation */
1177         pathkeys = convert_subquery_pathkeys(root, rel, subroot->query_pathkeys);
1178
1179         /* Generate appropriate path */
1180         add_path(rel, create_subqueryscan_path(root, rel, pathkeys, required_outer));
1181
1182         /* Select cheapest path (pretty easy in this case...) */
1183         set_cheapest(rel);
1184 }
1185
1186 /*
1187  * set_function_pathlist
1188  *              Build the (single) access path for a function RTE
1189  */
1190 static void
1191 set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
1192 {
1193         Relids          required_outer;
1194
1195         /*
1196          * We don't support pushing join clauses into the quals of a function
1197          * scan, but it could still have required parameterization due to LATERAL
1198          * refs in the function expression.
1199          */
1200         required_outer = rel->lateral_relids;
1201
1202         /* Generate appropriate path */
1203         add_path(rel, create_functionscan_path(root, rel, required_outer));
1204
1205         /* Select cheapest path (pretty easy in this case...) */
1206         set_cheapest(rel);
1207 }
1208
1209 /*
1210  * set_values_pathlist
1211  *              Build the (single) access path for a VALUES RTE
1212  */
1213 static void
1214 set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
1215 {
1216         Relids          required_outer;
1217
1218         /*
1219          * We don't support pushing join clauses into the quals of a values scan,
1220          * but it could still have required parameterization due to LATERAL refs
1221          * in the values expressions.
1222          */
1223         required_outer = rel->lateral_relids;
1224
1225         /* Generate appropriate path */
1226         add_path(rel, create_valuesscan_path(root, rel, required_outer));
1227
1228         /* Select cheapest path (pretty easy in this case...) */
1229         set_cheapest(rel);
1230 }
1231
1232 /*
1233  * set_cte_pathlist
1234  *              Build the (single) access path for a non-self-reference CTE RTE
1235  *
1236  * There's no need for a separate set_cte_size phase, since we don't
1237  * support join-qual-parameterized paths for CTEs.
1238  */
1239 static void
1240 set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
1241 {
1242         Plan       *cteplan;
1243         PlannerInfo *cteroot;
1244         Index           levelsup;
1245         int                     ndx;
1246         ListCell   *lc;
1247         int                     plan_id;
1248         Relids          required_outer;
1249
1250         /*
1251          * Find the referenced CTE, and locate the plan previously made for it.
1252          */
1253         levelsup = rte->ctelevelsup;
1254         cteroot = root;
1255         while (levelsup-- > 0)
1256         {
1257                 cteroot = cteroot->parent_root;
1258                 if (!cteroot)                   /* shouldn't happen */
1259                         elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1260         }
1261
1262         /*
1263          * Note: cte_plan_ids can be shorter than cteList, if we are still working
1264          * on planning the CTEs (ie, this is a side-reference from another CTE).
1265          * So we mustn't use forboth here.
1266          */
1267         ndx = 0;
1268         foreach(lc, cteroot->parse->cteList)
1269         {
1270                 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1271
1272                 if (strcmp(cte->ctename, rte->ctename) == 0)
1273                         break;
1274                 ndx++;
1275         }
1276         if (lc == NULL)                         /* shouldn't happen */
1277                 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
1278         if (ndx >= list_length(cteroot->cte_plan_ids))
1279                 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1280         plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
1281         Assert(plan_id > 0);
1282         cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
1283
1284         /* Mark rel with estimated output rows, width, etc */
1285         set_cte_size_estimates(root, rel, cteplan);
1286
1287         /*
1288          * We don't support pushing join clauses into the quals of a CTE scan, but
1289          * it could still have required parameterization due to LATERAL refs in
1290          * its tlist.  (That can only happen if the CTE scan is on a relation
1291          * pulled up out of a UNION ALL appendrel.)
1292          */
1293         required_outer = rel->lateral_relids;
1294
1295         /* Generate appropriate path */
1296         add_path(rel, create_ctescan_path(root, rel, required_outer));
1297
1298         /* Select cheapest path (pretty easy in this case...) */
1299         set_cheapest(rel);
1300 }
1301
1302 /*
1303  * set_worktable_pathlist
1304  *              Build the (single) access path for a self-reference CTE RTE
1305  *
1306  * There's no need for a separate set_worktable_size phase, since we don't
1307  * support join-qual-parameterized paths for CTEs.
1308  */
1309 static void
1310 set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
1311 {
1312         Plan       *cteplan;
1313         PlannerInfo *cteroot;
1314         Index           levelsup;
1315         Relids          required_outer;
1316
1317         /*
1318          * We need to find the non-recursive term's plan, which is in the plan
1319          * level that's processing the recursive UNION, which is one level *below*
1320          * where the CTE comes from.
1321          */
1322         levelsup = rte->ctelevelsup;
1323         if (levelsup == 0)                      /* shouldn't happen */
1324                 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1325         levelsup--;
1326         cteroot = root;
1327         while (levelsup-- > 0)
1328         {
1329                 cteroot = cteroot->parent_root;
1330                 if (!cteroot)                   /* shouldn't happen */
1331                         elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1332         }
1333         cteplan = cteroot->non_recursive_plan;
1334         if (!cteplan)                           /* shouldn't happen */
1335                 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1336
1337         /* Mark rel with estimated output rows, width, etc */
1338         set_cte_size_estimates(root, rel, cteplan);
1339
1340         /*
1341          * We don't support pushing join clauses into the quals of a worktable
1342          * scan, but it could still have required parameterization due to LATERAL
1343          * refs in its tlist.  (That can only happen if the worktable scan is on a
1344          * relation pulled up out of a UNION ALL appendrel.  I'm not sure this is
1345          * actually possible given the restrictions on recursive references, but
1346          * it's easy enough to support.)
1347          */
1348         required_outer = rel->lateral_relids;
1349
1350         /* Generate appropriate path */
1351         add_path(rel, create_worktablescan_path(root, rel, required_outer));
1352
1353         /* Select cheapest path (pretty easy in this case...) */
1354         set_cheapest(rel);
1355 }
1356
1357 /*
1358  * make_rel_from_joinlist
1359  *        Build access paths using a "joinlist" to guide the join path search.
1360  *
1361  * See comments for deconstruct_jointree() for definition of the joinlist
1362  * data structure.
1363  */
1364 static RelOptInfo *
1365 make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
1366 {
1367         int                     levels_needed;
1368         List       *initial_rels;
1369         ListCell   *jl;
1370
1371         /*
1372          * Count the number of child joinlist nodes.  This is the depth of the
1373          * dynamic-programming algorithm we must employ to consider all ways of
1374          * joining the child nodes.
1375          */
1376         levels_needed = list_length(joinlist);
1377
1378         if (levels_needed <= 0)
1379                 return NULL;                    /* nothing to do? */
1380
1381         /*
1382          * Construct a list of rels corresponding to the child joinlist nodes.
1383          * This may contain both base rels and rels constructed according to
1384          * sub-joinlists.
1385          */
1386         initial_rels = NIL;
1387         foreach(jl, joinlist)
1388         {
1389                 Node       *jlnode = (Node *) lfirst(jl);
1390                 RelOptInfo *thisrel;
1391
1392                 if (IsA(jlnode, RangeTblRef))
1393                 {
1394                         int                     varno = ((RangeTblRef *) jlnode)->rtindex;
1395
1396                         thisrel = find_base_rel(root, varno);
1397                 }
1398                 else if (IsA(jlnode, List))
1399                 {
1400                         /* Recurse to handle subproblem */
1401                         thisrel = make_rel_from_joinlist(root, (List *) jlnode);
1402                 }
1403                 else
1404                 {
1405                         elog(ERROR, "unrecognized joinlist node type: %d",
1406                                  (int) nodeTag(jlnode));
1407                         thisrel = NULL;         /* keep compiler quiet */
1408                 }
1409
1410                 initial_rels = lappend(initial_rels, thisrel);
1411         }
1412
1413         if (levels_needed == 1)
1414         {
1415                 /*
1416                  * Single joinlist node, so we're done.
1417                  */
1418                 return (RelOptInfo *) linitial(initial_rels);
1419         }
1420         else
1421         {
1422                 /*
1423                  * Consider the different orders in which we could join the rels,
1424                  * using a plugin, GEQO, or the regular join search code.
1425                  *
1426                  * We put the initial_rels list into a PlannerInfo field because
1427                  * has_legal_joinclause() needs to look at it (ugly :-().
1428                  */
1429                 root->initial_rels = initial_rels;
1430
1431                 if (join_search_hook)
1432                         return (*join_search_hook) (root, levels_needed, initial_rels);
1433                 else if (enable_geqo && levels_needed >= geqo_threshold)
1434                         return geqo(root, levels_needed, initial_rels);
1435                 else
1436                         return standard_join_search(root, levels_needed, initial_rels);
1437         }
1438 }
1439
1440 /*
1441  * standard_join_search
1442  *        Find possible joinpaths for a query by successively finding ways
1443  *        to join component relations into join relations.
1444  *
1445  * 'levels_needed' is the number of iterations needed, ie, the number of
1446  *              independent jointree items in the query.  This is > 1.
1447  *
1448  * 'initial_rels' is a list of RelOptInfo nodes for each independent
1449  *              jointree item.  These are the components to be joined together.
1450  *              Note that levels_needed == list_length(initial_rels).
1451  *
1452  * Returns the final level of join relations, i.e., the relation that is
1453  * the result of joining all the original relations together.
1454  * At least one implementation path must be provided for this relation and
1455  * all required sub-relations.
1456  *
1457  * To support loadable plugins that modify planner behavior by changing the
1458  * join searching algorithm, we provide a hook variable that lets a plugin
1459  * replace or supplement this function.  Any such hook must return the same
1460  * final join relation as the standard code would, but it might have a
1461  * different set of implementation paths attached, and only the sub-joinrels
1462  * needed for these paths need have been instantiated.
1463  *
1464  * Note to plugin authors: the functions invoked during standard_join_search()
1465  * modify root->join_rel_list and root->join_rel_hash.  If you want to do more
1466  * than one join-order search, you'll probably need to save and restore the
1467  * original states of those data structures.  See geqo_eval() for an example.
1468  */
1469 RelOptInfo *
1470 standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
1471 {
1472         int                     lev;
1473         RelOptInfo *rel;
1474
1475         /*
1476          * This function cannot be invoked recursively within any one planning
1477          * problem, so join_rel_level[] can't be in use already.
1478          */
1479         Assert(root->join_rel_level == NULL);
1480
1481         /*
1482          * We employ a simple "dynamic programming" algorithm: we first find all
1483          * ways to build joins of two jointree items, then all ways to build joins
1484          * of three items (from two-item joins and single items), then four-item
1485          * joins, and so on until we have considered all ways to join all the
1486          * items into one rel.
1487          *
1488          * root->join_rel_level[j] is a list of all the j-item rels.  Initially we
1489          * set root->join_rel_level[1] to represent all the single-jointree-item
1490          * relations.
1491          */
1492         root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
1493
1494         root->join_rel_level[1] = initial_rels;
1495
1496         for (lev = 2; lev <= levels_needed; lev++)
1497         {
1498                 ListCell   *lc;
1499
1500                 /*
1501                  * Determine all possible pairs of relations to be joined at this
1502                  * level, and build paths for making each one from every available
1503                  * pair of lower-level relations.
1504                  */
1505                 join_search_one_level(root, lev);
1506
1507                 /*
1508                  * Do cleanup work on each just-processed rel.
1509                  */
1510                 foreach(lc, root->join_rel_level[lev])
1511                 {
1512                         rel = (RelOptInfo *) lfirst(lc);
1513
1514                         /* Find and save the cheapest paths for this rel */
1515                         set_cheapest(rel);
1516
1517 #ifdef OPTIMIZER_DEBUG
1518                         debug_print_rel(root, rel);
1519 #endif
1520                 }
1521         }
1522
1523         /*
1524          * We should have a single rel at the final level.
1525          */
1526         if (root->join_rel_level[levels_needed] == NIL)
1527                 elog(ERROR, "failed to build any %d-way joins", levels_needed);
1528         Assert(list_length(root->join_rel_level[levels_needed]) == 1);
1529
1530         rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
1531
1532         root->join_rel_level = NULL;
1533
1534         return rel;
1535 }
1536
1537 /*****************************************************************************
1538  *                      PUSHING QUALS DOWN INTO SUBQUERIES
1539  *****************************************************************************/
1540
1541 /*
1542  * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
1543  *
1544  * subquery is the particular component query being checked.  topquery
1545  * is the top component of a set-operations tree (the same Query if no
1546  * set-op is involved).
1547  *
1548  * Conditions checked here:
1549  *
1550  * 1. If the subquery has a LIMIT clause, we must not push down any quals,
1551  * since that could change the set of rows returned.
1552  *
1553  * 2. If the subquery contains any window functions, we can't push quals
1554  * into it, because that could change the results.
1555  *
1556  * 3. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
1557  * quals into it, because that could change the results.
1558  *
1559  * 4. For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
1560  * push quals into each component query, but the quals can only reference
1561  * subquery columns that suffer no type coercions in the set operation.
1562  * Otherwise there are possible semantic gotchas.  So, we check the
1563  * component queries to see if any of them have different output types;
1564  * differentTypes[k] is set true if column k has different type in any
1565  * component.
1566  */
1567 static bool
1568 subquery_is_pushdown_safe(Query *subquery, Query *topquery,
1569                                                   bool *differentTypes)
1570 {
1571         SetOperationStmt *topop;
1572
1573         /* Check point 1 */
1574         if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
1575                 return false;
1576
1577         /* Check point 2 */
1578         if (subquery->hasWindowFuncs)
1579                 return false;
1580
1581         /* Are we at top level, or looking at a setop component? */
1582         if (subquery == topquery)
1583         {
1584                 /* Top level, so check any component queries */
1585                 if (subquery->setOperations != NULL)
1586                         if (!recurse_pushdown_safe(subquery->setOperations, topquery,
1587                                                                            differentTypes))
1588                                 return false;
1589         }
1590         else
1591         {
1592                 /* Setop component must not have more components (too weird) */
1593                 if (subquery->setOperations != NULL)
1594                         return false;
1595                 /* Check whether setop component output types match top level */
1596                 topop = (SetOperationStmt *) topquery->setOperations;
1597                 Assert(topop && IsA(topop, SetOperationStmt));
1598                 compare_tlist_datatypes(subquery->targetList,
1599                                                                 topop->colTypes,
1600                                                                 differentTypes);
1601         }
1602         return true;
1603 }
1604
1605 /*
1606  * Helper routine to recurse through setOperations tree
1607  */
1608 static bool
1609 recurse_pushdown_safe(Node *setOp, Query *topquery,
1610                                           bool *differentTypes)
1611 {
1612         if (IsA(setOp, RangeTblRef))
1613         {
1614                 RangeTblRef *rtr = (RangeTblRef *) setOp;
1615                 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
1616                 Query      *subquery = rte->subquery;
1617
1618                 Assert(subquery != NULL);
1619                 return subquery_is_pushdown_safe(subquery, topquery, differentTypes);
1620         }
1621         else if (IsA(setOp, SetOperationStmt))
1622         {
1623                 SetOperationStmt *op = (SetOperationStmt *) setOp;
1624
1625                 /* EXCEPT is no good */
1626                 if (op->op == SETOP_EXCEPT)
1627                         return false;
1628                 /* Else recurse */
1629                 if (!recurse_pushdown_safe(op->larg, topquery, differentTypes))
1630                         return false;
1631                 if (!recurse_pushdown_safe(op->rarg, topquery, differentTypes))
1632                         return false;
1633         }
1634         else
1635         {
1636                 elog(ERROR, "unrecognized node type: %d",
1637                          (int) nodeTag(setOp));
1638         }
1639         return true;
1640 }
1641
1642 /*
1643  * Compare tlist's datatypes against the list of set-operation result types.
1644  * For any items that are different, mark the appropriate element of
1645  * differentTypes[] to show that this column will have type conversions.
1646  *
1647  * We don't have to care about typmods here: the only allowed difference
1648  * between set-op input and output typmods is input is a specific typmod
1649  * and output is -1, and that does not require a coercion.
1650  */
1651 static void
1652 compare_tlist_datatypes(List *tlist, List *colTypes,
1653                                                 bool *differentTypes)
1654 {
1655         ListCell   *l;
1656         ListCell   *colType = list_head(colTypes);
1657
1658         foreach(l, tlist)
1659         {
1660                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1661
1662                 if (tle->resjunk)
1663                         continue;                       /* ignore resjunk columns */
1664                 if (colType == NULL)
1665                         elog(ERROR, "wrong number of tlist entries");
1666                 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
1667                         differentTypes[tle->resno] = true;
1668                 colType = lnext(colType);
1669         }
1670         if (colType != NULL)
1671                 elog(ERROR, "wrong number of tlist entries");
1672 }
1673
1674 /*
1675  * qual_is_pushdown_safe - is a particular qual safe to push down?
1676  *
1677  * qual is a restriction clause applying to the given subquery (whose RTE
1678  * has index rti in the parent query).
1679  *
1680  * Conditions checked here:
1681  *
1682  * 1. The qual must not contain any subselects (mainly because I'm not sure
1683  * it will work correctly: sublinks will already have been transformed into
1684  * subplans in the qual, but not in the subquery).
1685  *
1686  * 2. The qual must not refer to the whole-row output of the subquery
1687  * (since there is no easy way to name that within the subquery itself).
1688  *
1689  * 3. The qual must not refer to any subquery output columns that were
1690  * found to have inconsistent types across a set operation tree by
1691  * subquery_is_pushdown_safe().
1692  *
1693  * 4. If the subquery uses DISTINCT ON, we must not push down any quals that
1694  * refer to non-DISTINCT output columns, because that could change the set
1695  * of rows returned.  (This condition is vacuous for DISTINCT, because then
1696  * there are no non-DISTINCT output columns, so we needn't check.  But note
1697  * we are assuming that the qual can't distinguish values that the DISTINCT
1698  * operator sees as equal.      This is a bit shaky but we have no way to test
1699  * for the case, and it's unlikely enough that we shouldn't refuse the
1700  * optimization just because it could theoretically happen.)
1701  *
1702  * 5. We must not push down any quals that refer to subselect outputs that
1703  * return sets, else we'd introduce functions-returning-sets into the
1704  * subquery's WHERE/HAVING quals.
1705  *
1706  * 6. We must not push down any quals that refer to subselect outputs that
1707  * contain volatile functions, for fear of introducing strange results due
1708  * to multiple evaluation of a volatile function.
1709  */
1710 static bool
1711 qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual,
1712                                           bool *differentTypes)
1713 {
1714         bool            safe = true;
1715         List       *vars;
1716         ListCell   *vl;
1717         Bitmapset  *tested = NULL;
1718
1719         /* Refuse subselects (point 1) */
1720         if (contain_subplans(qual))
1721                 return false;
1722
1723         /*
1724          * It would be unsafe to push down window function calls, but at least for
1725          * the moment we could never see any in a qual anyhow.  (The same applies
1726          * to aggregates, which we check for in pull_var_clause below.)
1727          */
1728         Assert(!contain_window_function(qual));
1729
1730         /*
1731          * Examine all Vars used in clause; since it's a restriction clause, all
1732          * such Vars must refer to subselect output columns.
1733          */
1734         vars = pull_var_clause(qual,
1735                                                    PVC_REJECT_AGGREGATES,
1736                                                    PVC_INCLUDE_PLACEHOLDERS);
1737         foreach(vl, vars)
1738         {
1739                 Var                *var = (Var *) lfirst(vl);
1740                 TargetEntry *tle;
1741
1742                 /*
1743                  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
1744                  * It's not clear whether a PHV could safely be pushed down, and even
1745                  * less clear whether such a situation could arise in any cases of
1746                  * practical interest anyway.  So for the moment, just refuse to push
1747                  * down.
1748                  */
1749                 if (!IsA(var, Var))
1750                 {
1751                         safe = false;
1752                         break;
1753                 }
1754
1755                 Assert(var->varno == rti);
1756
1757                 /* Check point 2 */
1758                 if (var->varattno == 0)
1759                 {
1760                         safe = false;
1761                         break;
1762                 }
1763
1764                 /*
1765                  * We use a bitmapset to avoid testing the same attno more than once.
1766                  * (NB: this only works because subquery outputs can't have negative
1767                  * attnos.)
1768                  */
1769                 if (bms_is_member(var->varattno, tested))
1770                         continue;
1771                 tested = bms_add_member(tested, var->varattno);
1772
1773                 /* Check point 3 */
1774                 if (differentTypes[var->varattno])
1775                 {
1776                         safe = false;
1777                         break;
1778                 }
1779
1780                 /* Must find the tlist element referenced by the Var */
1781                 tle = get_tle_by_resno(subquery->targetList, var->varattno);
1782                 Assert(tle != NULL);
1783                 Assert(!tle->resjunk);
1784
1785                 /* If subquery uses DISTINCT ON, check point 4 */
1786                 if (subquery->hasDistinctOn &&
1787                         !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
1788                 {
1789                         /* non-DISTINCT column, so fail */
1790                         safe = false;
1791                         break;
1792                 }
1793
1794                 /* Refuse functions returning sets (point 5) */
1795                 if (expression_returns_set((Node *) tle->expr))
1796                 {
1797                         safe = false;
1798                         break;
1799                 }
1800
1801                 /* Refuse volatile functions (point 6) */
1802                 if (contain_volatile_functions((Node *) tle->expr))
1803                 {
1804                         safe = false;
1805                         break;
1806                 }
1807         }
1808
1809         list_free(vars);
1810         bms_free(tested);
1811
1812         return safe;
1813 }
1814
1815 /*
1816  * subquery_push_qual - push down a qual that we have determined is safe
1817  */
1818 static void
1819 subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
1820 {
1821         if (subquery->setOperations != NULL)
1822         {
1823                 /* Recurse to push it separately to each component query */
1824                 recurse_push_qual(subquery->setOperations, subquery,
1825                                                   rte, rti, qual);
1826         }
1827         else
1828         {
1829                 /*
1830                  * We need to replace Vars in the qual (which must refer to outputs of
1831                  * the subquery) with copies of the subquery's targetlist expressions.
1832                  * Note that at this point, any uplevel Vars in the qual should have
1833                  * been replaced with Params, so they need no work.
1834                  *
1835                  * This step also ensures that when we are pushing into a setop tree,
1836                  * each component query gets its own copy of the qual.
1837                  */
1838                 qual = ResolveNew(qual, rti, 0, rte,
1839                                                   subquery->targetList,
1840                                                   CMD_SELECT, 0,
1841                                                   &subquery->hasSubLinks);
1842
1843                 /*
1844                  * Now attach the qual to the proper place: normally WHERE, but if the
1845                  * subquery uses grouping or aggregation, put it in HAVING (since the
1846                  * qual really refers to the group-result rows).
1847                  */
1848                 if (subquery->hasAggs || subquery->groupClause || subquery->havingQual)
1849                         subquery->havingQual = make_and_qual(subquery->havingQual, qual);
1850                 else
1851                         subquery->jointree->quals =
1852                                 make_and_qual(subquery->jointree->quals, qual);
1853
1854                 /*
1855                  * We need not change the subquery's hasAggs or hasSublinks flags,
1856                  * since we can't be pushing down any aggregates that weren't there
1857                  * before, and we don't push down subselects at all.
1858                  */
1859         }
1860 }
1861
1862 /*
1863  * Helper routine to recurse through setOperations tree
1864  */
1865 static void
1866 recurse_push_qual(Node *setOp, Query *topquery,
1867                                   RangeTblEntry *rte, Index rti, Node *qual)
1868 {
1869         if (IsA(setOp, RangeTblRef))
1870         {
1871                 RangeTblRef *rtr = (RangeTblRef *) setOp;
1872                 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
1873                 Query      *subquery = subrte->subquery;
1874
1875                 Assert(subquery != NULL);
1876                 subquery_push_qual(subquery, rte, rti, qual);
1877         }
1878         else if (IsA(setOp, SetOperationStmt))
1879         {
1880                 SetOperationStmt *op = (SetOperationStmt *) setOp;
1881
1882                 recurse_push_qual(op->larg, topquery, rte, rti, qual);
1883                 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
1884         }
1885         else
1886         {
1887                 elog(ERROR, "unrecognized node type: %d",
1888                          (int) nodeTag(setOp));
1889         }
1890 }
1891
1892 /*****************************************************************************
1893  *                      DEBUG SUPPORT
1894  *****************************************************************************/
1895
1896 #ifdef OPTIMIZER_DEBUG
1897
1898 static void
1899 print_relids(Relids relids)
1900 {
1901         Relids          tmprelids;
1902         int                     x;
1903         bool            first = true;
1904
1905         tmprelids = bms_copy(relids);
1906         while ((x = bms_first_member(tmprelids)) >= 0)
1907         {
1908                 if (!first)
1909                         printf(" ");
1910                 printf("%d", x);
1911                 first = false;
1912         }
1913         bms_free(tmprelids);
1914 }
1915
1916 static void
1917 print_restrictclauses(PlannerInfo *root, List *clauses)
1918 {
1919         ListCell   *l;
1920
1921         foreach(l, clauses)
1922         {
1923                 RestrictInfo *c = lfirst(l);
1924
1925                 print_expr((Node *) c->clause, root->parse->rtable);
1926                 if (lnext(l))
1927                         printf(", ");
1928         }
1929 }
1930
1931 static void
1932 print_path(PlannerInfo *root, Path *path, int indent)
1933 {
1934         const char *ptype;
1935         bool            join = false;
1936         Path       *subpath = NULL;
1937         int                     i;
1938
1939         switch (nodeTag(path))
1940         {
1941                 case T_Path:
1942                         ptype = "SeqScan";
1943                         break;
1944                 case T_IndexPath:
1945                         ptype = "IdxScan";
1946                         break;
1947                 case T_BitmapHeapPath:
1948                         ptype = "BitmapHeapScan";
1949                         break;
1950                 case T_BitmapAndPath:
1951                         ptype = "BitmapAndPath";
1952                         break;
1953                 case T_BitmapOrPath:
1954                         ptype = "BitmapOrPath";
1955                         break;
1956                 case T_TidPath:
1957                         ptype = "TidScan";
1958                         break;
1959                 case T_ForeignPath:
1960                         ptype = "ForeignScan";
1961                         break;
1962                 case T_AppendPath:
1963                         ptype = "Append";
1964                         break;
1965                 case T_MergeAppendPath:
1966                         ptype = "MergeAppend";
1967                         break;
1968                 case T_ResultPath:
1969                         ptype = "Result";
1970                         break;
1971                 case T_MaterialPath:
1972                         ptype = "Material";
1973                         subpath = ((MaterialPath *) path)->subpath;
1974                         break;
1975                 case T_UniquePath:
1976                         ptype = "Unique";
1977                         subpath = ((UniquePath *) path)->subpath;
1978                         break;
1979                 case T_NestPath:
1980                         ptype = "NestLoop";
1981                         join = true;
1982                         break;
1983                 case T_MergePath:
1984                         ptype = "MergeJoin";
1985                         join = true;
1986                         break;
1987                 case T_HashPath:
1988                         ptype = "HashJoin";
1989                         join = true;
1990                         break;
1991                 default:
1992                         ptype = "???Path";
1993                         break;
1994         }
1995
1996         for (i = 0; i < indent; i++)
1997                 printf("\t");
1998         printf("%s", ptype);
1999
2000         if (path->parent)
2001         {
2002                 printf("(");
2003                 print_relids(path->parent->relids);
2004                 printf(") rows=%.0f", path->parent->rows);
2005         }
2006         printf(" cost=%.2f..%.2f\n", path->startup_cost, path->total_cost);
2007
2008         if (path->pathkeys)
2009         {
2010                 for (i = 0; i < indent; i++)
2011                         printf("\t");
2012                 printf("  pathkeys: ");
2013                 print_pathkeys(path->pathkeys, root->parse->rtable);
2014         }
2015
2016         if (join)
2017         {
2018                 JoinPath   *jp = (JoinPath *) path;
2019
2020                 for (i = 0; i < indent; i++)
2021                         printf("\t");
2022                 printf("  clauses: ");
2023                 print_restrictclauses(root, jp->joinrestrictinfo);
2024                 printf("\n");
2025
2026                 if (IsA(path, MergePath))
2027                 {
2028                         MergePath  *mp = (MergePath *) path;
2029
2030                         for (i = 0; i < indent; i++)
2031                                 printf("\t");
2032                         printf("  sortouter=%d sortinner=%d materializeinner=%d\n",
2033                                    ((mp->outersortkeys) ? 1 : 0),
2034                                    ((mp->innersortkeys) ? 1 : 0),
2035                                    ((mp->materialize_inner) ? 1 : 0));
2036                 }
2037
2038                 print_path(root, jp->outerjoinpath, indent + 1);
2039                 print_path(root, jp->innerjoinpath, indent + 1);
2040         }
2041
2042         if (subpath)
2043                 print_path(root, subpath, indent + 1);
2044 }
2045
2046 void
2047 debug_print_rel(PlannerInfo *root, RelOptInfo *rel)
2048 {
2049         ListCell   *l;
2050
2051         printf("RELOPTINFO (");
2052         print_relids(rel->relids);
2053         printf("): rows=%.0f width=%d\n", rel->rows, rel->width);
2054
2055         if (rel->baserestrictinfo)
2056         {
2057                 printf("\tbaserestrictinfo: ");
2058                 print_restrictclauses(root, rel->baserestrictinfo);
2059                 printf("\n");
2060         }
2061
2062         if (rel->joininfo)
2063         {
2064                 printf("\tjoininfo: ");
2065                 print_restrictclauses(root, rel->joininfo);
2066                 printf("\n");
2067         }
2068
2069         printf("\tpath list:\n");
2070         foreach(l, rel->pathlist)
2071                 print_path(root, lfirst(l), 1);
2072         if (rel->cheapest_startup_path)
2073         {
2074                 printf("\n\tcheapest startup path:\n");
2075                 print_path(root, rel->cheapest_startup_path, 1);
2076         }
2077         if (rel->cheapest_total_path)
2078         {
2079                 printf("\n\tcheapest total path:\n");
2080                 print_path(root, rel->cheapest_total_path, 1);
2081         }
2082         printf("\n");
2083         fflush(stdout);
2084 }
2085
2086 #endif   /* OPTIMIZER_DEBUG */