Header And Logo

PostgreSQL
| The world's most advanced open source database.

initsplan.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * initsplan.c
00004  *    Target list, qualification, joininfo initialization routines
00005  *
00006  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00007  * Portions Copyright (c) 1994, Regents of the University of California
00008  *
00009  *
00010  * IDENTIFICATION
00011  *    src/backend/optimizer/plan/initsplan.c
00012  *
00013  *-------------------------------------------------------------------------
00014  */
00015 #include "postgres.h"
00016 
00017 #include "catalog/pg_type.h"
00018 #include "nodes/nodeFuncs.h"
00019 #include "optimizer/clauses.h"
00020 #include "optimizer/joininfo.h"
00021 #include "optimizer/pathnode.h"
00022 #include "optimizer/paths.h"
00023 #include "optimizer/placeholder.h"
00024 #include "optimizer/planmain.h"
00025 #include "optimizer/planner.h"
00026 #include "optimizer/prep.h"
00027 #include "optimizer/restrictinfo.h"
00028 #include "optimizer/var.h"
00029 #include "rewrite/rewriteManip.h"
00030 #include "utils/lsyscache.h"
00031 
00032 
00033 /* These parameters are set by GUC */
00034 int         from_collapse_limit;
00035 int         join_collapse_limit;
00036 
00037 
00038 static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel,
00039                            Index rtindex);
00040 static void add_lateral_info(PlannerInfo *root, Index rhs, Relids lhs);
00041 static List *deconstruct_recurse(PlannerInfo *root, Node *jtnode,
00042                     bool below_outer_join,
00043                     Relids *qualscope, Relids *inner_join_rels);
00044 static SpecialJoinInfo *make_outerjoininfo(PlannerInfo *root,
00045                    Relids left_rels, Relids right_rels,
00046                    Relids inner_join_rels,
00047                    JoinType jointype, List *clause);
00048 static void distribute_qual_to_rels(PlannerInfo *root, Node *clause,
00049                         bool is_deduced,
00050                         bool below_outer_join,
00051                         JoinType jointype,
00052                         Relids qualscope,
00053                         Relids ojscope,
00054                         Relids outerjoin_nonnullable,
00055                         Relids deduced_nullable_relids);
00056 static bool check_outerjoin_delay(PlannerInfo *root, Relids *relids_p,
00057                       Relids *nullable_relids_p, bool is_pushed_down);
00058 static bool check_equivalence_delay(PlannerInfo *root,
00059                         RestrictInfo *restrictinfo);
00060 static bool check_redundant_nullability_qual(PlannerInfo *root, Node *clause);
00061 static void check_mergejoinable(RestrictInfo *restrictinfo);
00062 static void check_hashjoinable(RestrictInfo *restrictinfo);
00063 
00064 
00065 /*****************************************************************************
00066  *
00067  *   JOIN TREES
00068  *
00069  *****************************************************************************/
00070 
00071 /*
00072  * add_base_rels_to_query
00073  *
00074  *    Scan the query's jointree and create baserel RelOptInfos for all
00075  *    the base relations (ie, table, subquery, and function RTEs)
00076  *    appearing in the jointree.
00077  *
00078  * The initial invocation must pass root->parse->jointree as the value of
00079  * jtnode.  Internally, the function recurses through the jointree.
00080  *
00081  * At the end of this process, there should be one baserel RelOptInfo for
00082  * every non-join RTE that is used in the query.  Therefore, this routine
00083  * is the only place that should call build_simple_rel with reloptkind
00084  * RELOPT_BASEREL.  (Note: build_simple_rel recurses internally to build
00085  * "other rel" RelOptInfos for the members of any appendrels we find here.)
00086  */
00087 void
00088 add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
00089 {
00090     if (jtnode == NULL)
00091         return;
00092     if (IsA(jtnode, RangeTblRef))
00093     {
00094         int         varno = ((RangeTblRef *) jtnode)->rtindex;
00095 
00096         (void) build_simple_rel(root, varno, RELOPT_BASEREL);
00097     }
00098     else if (IsA(jtnode, FromExpr))
00099     {
00100         FromExpr   *f = (FromExpr *) jtnode;
00101         ListCell   *l;
00102 
00103         foreach(l, f->fromlist)
00104             add_base_rels_to_query(root, lfirst(l));
00105     }
00106     else if (IsA(jtnode, JoinExpr))
00107     {
00108         JoinExpr   *j = (JoinExpr *) jtnode;
00109 
00110         add_base_rels_to_query(root, j->larg);
00111         add_base_rels_to_query(root, j->rarg);
00112     }
00113     else
00114         elog(ERROR, "unrecognized node type: %d",
00115              (int) nodeTag(jtnode));
00116 }
00117 
00118 
00119 /*****************************************************************************
00120  *
00121  *   TARGET LISTS
00122  *
00123  *****************************************************************************/
00124 
00125 /*
00126  * build_base_rel_tlists
00127  *    Add targetlist entries for each var needed in the query's final tlist
00128  *    to the appropriate base relations.
00129  *
00130  * We mark such vars as needed by "relation 0" to ensure that they will
00131  * propagate up through all join plan steps.
00132  */
00133 void
00134 build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
00135 {
00136     List       *tlist_vars = pull_var_clause((Node *) final_tlist,
00137                                              PVC_RECURSE_AGGREGATES,
00138                                              PVC_INCLUDE_PLACEHOLDERS);
00139 
00140     if (tlist_vars != NIL)
00141     {
00142         add_vars_to_targetlist(root, tlist_vars, bms_make_singleton(0), true);
00143         list_free(tlist_vars);
00144     }
00145 }
00146 
00147 /*
00148  * add_vars_to_targetlist
00149  *    For each variable appearing in the list, add it to the owning
00150  *    relation's targetlist if not already present, and mark the variable
00151  *    as being needed for the indicated join (or for final output if
00152  *    where_needed includes "relation 0").
00153  *
00154  *    The list may also contain PlaceHolderVars.  These don't necessarily
00155  *    have a single owning relation; we keep their attr_needed info in
00156  *    root->placeholder_list instead.  If create_new_ph is true, it's OK
00157  *    to create new PlaceHolderInfos, and we also have to update ph_may_need;
00158  *    otherwise, the PlaceHolderInfos must already exist, and we should only
00159  *    update their ph_needed.  (It should be true before deconstruct_jointree
00160  *    begins, and false after that.)
00161  */
00162 void
00163 add_vars_to_targetlist(PlannerInfo *root, List *vars,
00164                        Relids where_needed, bool create_new_ph)
00165 {
00166     ListCell   *temp;
00167 
00168     Assert(!bms_is_empty(where_needed));
00169 
00170     foreach(temp, vars)
00171     {
00172         Node       *node = (Node *) lfirst(temp);
00173 
00174         if (IsA(node, Var))
00175         {
00176             Var        *var = (Var *) node;
00177             RelOptInfo *rel = find_base_rel(root, var->varno);
00178             int         attno = var->varattno;
00179 
00180             Assert(attno >= rel->min_attr && attno <= rel->max_attr);
00181             attno -= rel->min_attr;
00182             if (rel->attr_needed[attno] == NULL)
00183             {
00184                 /* Variable not yet requested, so add to reltargetlist */
00185                 /* XXX is copyObject necessary here? */
00186                 rel->reltargetlist = lappend(rel->reltargetlist,
00187                                              copyObject(var));
00188             }
00189             rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno],
00190                                                       where_needed);
00191         }
00192         else if (IsA(node, PlaceHolderVar))
00193         {
00194             PlaceHolderVar *phv = (PlaceHolderVar *) node;
00195             PlaceHolderInfo *phinfo = find_placeholder_info(root, phv,
00196                                                             create_new_ph);
00197 
00198             /* Always adjust ph_needed */
00199             phinfo->ph_needed = bms_add_members(phinfo->ph_needed,
00200                                                 where_needed);
00201 
00202             /*
00203              * If we are creating PlaceHolderInfos, mark them with the correct
00204              * maybe-needed locations.  Otherwise, it's too late to change
00205              * that, so we'd better not have set ph_needed to more than
00206              * ph_may_need.
00207              */
00208             if (create_new_ph)
00209                 mark_placeholder_maybe_needed(root, phinfo, where_needed);
00210             else
00211                 Assert(bms_is_subset(phinfo->ph_needed, phinfo->ph_may_need));
00212         }
00213         else
00214             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
00215     }
00216 }
00217 
00218 
00219 /*****************************************************************************
00220  *
00221  *    LATERAL REFERENCES
00222  *
00223  *****************************************************************************/
00224 
00225 /*
00226  * find_lateral_references
00227  *    For each LATERAL subquery, extract all its references to Vars and
00228  *    PlaceHolderVars of the current query level, and make sure those values
00229  *    will be available for evaluation of the subquery.
00230  *
00231  * While later planning steps ensure that the Var/PHV source rels are on the
00232  * outside of nestloops relative to the LATERAL subquery, we also need to
00233  * ensure that the Vars/PHVs propagate up to the nestloop join level; this
00234  * means setting suitable where_needed values for them.
00235  *
00236  * This has to run before deconstruct_jointree, since it might result in
00237  * creation of PlaceHolderInfos or extension of their ph_may_need sets.
00238  */
00239 void
00240 find_lateral_references(PlannerInfo *root)
00241 {
00242     Index       rti;
00243 
00244     /* We need do nothing if the query contains no LATERAL RTEs */
00245     if (!root->hasLateralRTEs)
00246         return;
00247 
00248     /*
00249      * Examine all baserels (the rel array has been set up by now).
00250      */
00251     for (rti = 1; rti < root->simple_rel_array_size; rti++)
00252     {
00253         RelOptInfo *brel = root->simple_rel_array[rti];
00254 
00255         /* there may be empty slots corresponding to non-baserel RTEs */
00256         if (brel == NULL)
00257             continue;
00258 
00259         Assert(brel->relid == rti);     /* sanity check on array */
00260 
00261         /*
00262          * This bit is less obvious than it might look.  We ignore appendrel
00263          * otherrels and consider only their parent baserels.  In a case where
00264          * a LATERAL-containing UNION ALL subquery was pulled up, it is the
00265          * otherrels that are actually going to be in the plan.  However, we
00266          * want to mark all their lateral references as needed by the parent,
00267          * because it is the parent's relid that will be used for join
00268          * planning purposes.  And the parent's RTE will contain all the
00269          * lateral references we need to know, since the pulled-up members are
00270          * nothing but copies of parts of the original RTE's subquery.  We
00271          * could visit the children instead and transform their references
00272          * back to the parent's relid, but it would be much more complicated
00273          * for no real gain.  (Important here is that the child members have
00274          * not yet received any processing beyond being pulled up.)
00275          */
00276 
00277         /* ignore RTEs that are "other rels" */
00278         if (brel->reloptkind != RELOPT_BASEREL)
00279             continue;
00280 
00281         extract_lateral_references(root, brel, rti);
00282     }
00283 }
00284 
00285 static void
00286 extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex)
00287 {
00288     RangeTblEntry *rte = root->simple_rte_array[rtindex];
00289     List       *vars;
00290     List       *newvars;
00291     Relids      where_needed;
00292     ListCell   *lc;
00293 
00294     /* No cross-references are possible if it's not LATERAL */
00295     if (!rte->lateral)
00296         return;
00297 
00298     /* Fetch the appropriate variables */
00299     if (rte->rtekind == RTE_SUBQUERY)
00300         vars = pull_vars_of_level((Node *) rte->subquery, 1);
00301     else if (rte->rtekind == RTE_FUNCTION)
00302         vars = pull_vars_of_level(rte->funcexpr, 0);
00303     else if (rte->rtekind == RTE_VALUES)
00304         vars = pull_vars_of_level((Node *) rte->values_lists, 0);
00305     else
00306     {
00307         Assert(false);
00308         return;                 /* keep compiler quiet */
00309     }
00310 
00311     if (vars == NIL)
00312         return;                 /* nothing to do */
00313 
00314     /* Copy each Var (or PlaceHolderVar) and adjust it to match our level */
00315     newvars = NIL;
00316     foreach(lc, vars)
00317     {
00318         Node   *node = (Node *) lfirst(lc);
00319 
00320         node = copyObject(node);
00321         if (IsA(node, Var))
00322         {
00323             Var    *var = (Var *) node;
00324 
00325             /* Adjustment is easy since it's just one node */
00326             var->varlevelsup = 0;
00327         }
00328         else if (IsA(node, PlaceHolderVar))
00329         {
00330             PlaceHolderVar *phv = (PlaceHolderVar *) node;
00331             int     levelsup = phv->phlevelsup;
00332 
00333             /* Have to work harder to adjust the contained expression too */
00334             if (levelsup != 0)
00335                 IncrementVarSublevelsUp(node, -levelsup, 0);
00336 
00337             /*
00338              * If we pulled the PHV out of a subquery RTE, its expression
00339              * needs to be preprocessed.  subquery_planner() already did this
00340              * for level-zero PHVs in function and values RTEs, though.
00341              */
00342             if (levelsup > 0)
00343                 phv->phexpr = preprocess_phv_expression(root, phv->phexpr);
00344         }
00345         else
00346             Assert(false);
00347         newvars = lappend(newvars, node);
00348     }
00349 
00350     list_free(vars);
00351 
00352     /*
00353      * We mark the Vars as being "needed" at the LATERAL RTE.  This is a bit
00354      * of a cheat: a more formal approach would be to mark each one as needed
00355      * at the join of the LATERAL RTE with its source RTE.  But it will work,
00356      * and it's much less tedious than computing a separate where_needed for
00357      * each Var.
00358      */
00359     where_needed = bms_make_singleton(rtindex);
00360 
00361     /* Push the Vars into their source relations' targetlists */
00362     add_vars_to_targetlist(root, newvars, where_needed, true);
00363 
00364     /* Remember the lateral references for create_lateral_join_info */
00365     brel->lateral_vars = newvars;
00366 }
00367 
00368 /*
00369  * create_lateral_join_info
00370  *    For each LATERAL subquery, create LateralJoinInfo(s) and add them to
00371  *    root->lateral_info_list, and fill in the per-rel lateral_relids sets.
00372  *
00373  * This has to run after deconstruct_jointree, because we need to know the
00374  * final ph_eval_at values for referenced PlaceHolderVars.
00375  */
00376 void
00377 create_lateral_join_info(PlannerInfo *root)
00378 {
00379     Index       rti;
00380 
00381     /* We need do nothing if the query contains no LATERAL RTEs */
00382     if (!root->hasLateralRTEs)
00383         return;
00384 
00385     /*
00386      * Examine all baserels (the rel array has been set up by now).
00387      */
00388     for (rti = 1; rti < root->simple_rel_array_size; rti++)
00389     {
00390         RelOptInfo *brel = root->simple_rel_array[rti];
00391         Relids      lateral_relids;
00392         ListCell *lc;
00393 
00394         /* there may be empty slots corresponding to non-baserel RTEs */
00395         if (brel == NULL)
00396             continue;
00397 
00398         Assert(brel->relid == rti);     /* sanity check on array */
00399 
00400         /* ignore RTEs that are "other rels" */
00401         if (brel->reloptkind != RELOPT_BASEREL)
00402             continue;
00403 
00404         lateral_relids = NULL;
00405 
00406         /* consider each laterally-referenced Var or PHV */
00407         foreach(lc, brel->lateral_vars)
00408         {
00409             Node   *node = (Node *) lfirst(lc);
00410 
00411             if (IsA(node, Var))
00412             {
00413                 Var    *var = (Var *) node;
00414 
00415                 add_lateral_info(root, rti, bms_make_singleton(var->varno));
00416                 lateral_relids = bms_add_member(lateral_relids,
00417                                                 var->varno);
00418             }
00419             else if (IsA(node, PlaceHolderVar))
00420             {
00421                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
00422                 PlaceHolderInfo *phinfo = find_placeholder_info(root, phv,
00423                                                                 false);
00424 
00425                 add_lateral_info(root, rti, bms_copy(phinfo->ph_eval_at));
00426                 lateral_relids = bms_add_members(lateral_relids,
00427                                                  phinfo->ph_eval_at);
00428             }
00429             else
00430                 Assert(false);
00431         }
00432 
00433         /* We now know all the relids needed for lateral refs in this rel */
00434         if (bms_is_empty(lateral_relids))
00435             continue;           /* ensure lateral_relids is NULL if empty */
00436         brel->lateral_relids = lateral_relids;
00437 
00438         /*
00439          * If it's an appendrel parent, copy its lateral_relids to each child
00440          * rel.  We intentionally give each child rel the same minimum
00441          * parameterization, even though it's quite possible that some don't
00442          * reference all the lateral rels.  This is because any append path
00443          * for the parent will have to have the same parameterization for
00444          * every child anyway, and there's no value in forcing extra
00445          * reparameterize_path() calls.
00446          */
00447         if (root->simple_rte_array[rti]->inh)
00448         {
00449             foreach(lc, root->append_rel_list)
00450             {
00451                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
00452                 RelOptInfo *childrel;
00453 
00454                 if (appinfo->parent_relid != rti)
00455                     continue;
00456                 childrel = root->simple_rel_array[appinfo->child_relid];
00457                 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
00458                 Assert(childrel->lateral_relids == NULL);
00459                 childrel->lateral_relids = lateral_relids;
00460             }
00461         }
00462     }
00463 }
00464 
00465 /*
00466  * add_lateral_info
00467  *      Add a LateralJoinInfo to root->lateral_info_list, if needed
00468  *
00469  * We suppress redundant list entries.  The passed lhs set must be freshly
00470  * made; we free it if not used in a new list entry.
00471  */
00472 static void
00473 add_lateral_info(PlannerInfo *root, Index rhs, Relids lhs)
00474 {
00475     LateralJoinInfo *ljinfo;
00476     ListCell   *l;
00477 
00478     Assert(!bms_is_member(rhs, lhs));
00479 
00480     /*
00481      * If an existing list member has the same RHS and an LHS that is a subset
00482      * of the new one, it's redundant, but we don't trouble to get rid of it.
00483      * The only case that is really worth worrying about is identical entries,
00484      * and we handle that well enough with this simple logic.
00485      */
00486     foreach(l, root->lateral_info_list)
00487     {
00488         ljinfo = (LateralJoinInfo *) lfirst(l);
00489         if (rhs == ljinfo->lateral_rhs &&
00490             bms_is_subset(lhs, ljinfo->lateral_lhs))
00491         {
00492             bms_free(lhs);
00493             return;
00494         }
00495     }
00496 
00497     /* Not there, so make a new entry */
00498     ljinfo = makeNode(LateralJoinInfo);
00499     ljinfo->lateral_rhs = rhs;
00500     ljinfo->lateral_lhs = lhs;
00501     root->lateral_info_list = lappend(root->lateral_info_list, ljinfo);
00502 }
00503 
00504 
00505 /*****************************************************************************
00506  *
00507  *    JOIN TREE PROCESSING
00508  *
00509  *****************************************************************************/
00510 
00511 /*
00512  * deconstruct_jointree
00513  *    Recursively scan the query's join tree for WHERE and JOIN/ON qual
00514  *    clauses, and add these to the appropriate restrictinfo and joininfo
00515  *    lists belonging to base RelOptInfos.  Also, add SpecialJoinInfo nodes
00516  *    to root->join_info_list for any outer joins appearing in the query tree.
00517  *    Return a "joinlist" data structure showing the join order decisions
00518  *    that need to be made by make_one_rel().
00519  *
00520  * The "joinlist" result is a list of items that are either RangeTblRef
00521  * jointree nodes or sub-joinlists.  All the items at the same level of
00522  * joinlist must be joined in an order to be determined by make_one_rel()
00523  * (note that legal orders may be constrained by SpecialJoinInfo nodes).
00524  * A sub-joinlist represents a subproblem to be planned separately. Currently
00525  * sub-joinlists arise only from FULL OUTER JOIN or when collapsing of
00526  * subproblems is stopped by join_collapse_limit or from_collapse_limit.
00527  *
00528  * NOTE: when dealing with inner joins, it is appropriate to let a qual clause
00529  * be evaluated at the lowest level where all the variables it mentions are
00530  * available.  However, we cannot push a qual down into the nullable side(s)
00531  * of an outer join since the qual might eliminate matching rows and cause a
00532  * NULL row to be incorrectly emitted by the join.  Therefore, we artificially
00533  * OR the minimum-relids of such an outer join into the required_relids of
00534  * clauses appearing above it.  This forces those clauses to be delayed until
00535  * application of the outer join (or maybe even higher in the join tree).
00536  */
00537 List *
00538 deconstruct_jointree(PlannerInfo *root)
00539 {
00540     Relids      qualscope;
00541     Relids      inner_join_rels;
00542 
00543     /* Start recursion at top of jointree */
00544     Assert(root->parse->jointree != NULL &&
00545            IsA(root->parse->jointree, FromExpr));
00546 
00547     return deconstruct_recurse(root, (Node *) root->parse->jointree, false,
00548                                &qualscope, &inner_join_rels);
00549 }
00550 
00551 /*
00552  * deconstruct_recurse
00553  *    One recursion level of deconstruct_jointree processing.
00554  *
00555  * Inputs:
00556  *  jtnode is the jointree node to examine
00557  *  below_outer_join is TRUE if this node is within the nullable side of a
00558  *      higher-level outer join
00559  * Outputs:
00560  *  *qualscope gets the set of base Relids syntactically included in this
00561  *      jointree node (do not modify or free this, as it may also be pointed
00562  *      to by RestrictInfo and SpecialJoinInfo nodes)
00563  *  *inner_join_rels gets the set of base Relids syntactically included in
00564  *      inner joins appearing at or below this jointree node (do not modify
00565  *      or free this, either)
00566  *  Return value is the appropriate joinlist for this jointree node
00567  *
00568  * In addition, entries will be added to root->join_info_list for outer joins.
00569  */
00570 static List *
00571 deconstruct_recurse(PlannerInfo *root, Node *jtnode, bool below_outer_join,
00572                     Relids *qualscope, Relids *inner_join_rels)
00573 {
00574     List       *joinlist;
00575 
00576     if (jtnode == NULL)
00577     {
00578         *qualscope = NULL;
00579         *inner_join_rels = NULL;
00580         return NIL;
00581     }
00582     if (IsA(jtnode, RangeTblRef))
00583     {
00584         int         varno = ((RangeTblRef *) jtnode)->rtindex;
00585 
00586         /* No quals to deal with, just return correct result */
00587         *qualscope = bms_make_singleton(varno);
00588         /* A single baserel does not create an inner join */
00589         *inner_join_rels = NULL;
00590         joinlist = list_make1(jtnode);
00591     }
00592     else if (IsA(jtnode, FromExpr))
00593     {
00594         FromExpr   *f = (FromExpr *) jtnode;
00595         int         remaining;
00596         ListCell   *l;
00597 
00598         /*
00599          * First, recurse to handle child joins.  We collapse subproblems into
00600          * a single joinlist whenever the resulting joinlist wouldn't exceed
00601          * from_collapse_limit members.  Also, always collapse one-element
00602          * subproblems, since that won't lengthen the joinlist anyway.
00603          */
00604         *qualscope = NULL;
00605         *inner_join_rels = NULL;
00606         joinlist = NIL;
00607         remaining = list_length(f->fromlist);
00608         foreach(l, f->fromlist)
00609         {
00610             Relids      sub_qualscope;
00611             List       *sub_joinlist;
00612             int         sub_members;
00613 
00614             sub_joinlist = deconstruct_recurse(root, lfirst(l),
00615                                                below_outer_join,
00616                                                &sub_qualscope,
00617                                                inner_join_rels);
00618             *qualscope = bms_add_members(*qualscope, sub_qualscope);
00619             sub_members = list_length(sub_joinlist);
00620             remaining--;
00621             if (sub_members <= 1 ||
00622                 list_length(joinlist) + sub_members + remaining <= from_collapse_limit)
00623                 joinlist = list_concat(joinlist, sub_joinlist);
00624             else
00625                 joinlist = lappend(joinlist, sub_joinlist);
00626         }
00627 
00628         /*
00629          * A FROM with more than one list element is an inner join subsuming
00630          * all below it, so we should report inner_join_rels = qualscope. If
00631          * there was exactly one element, we should (and already did) report
00632          * whatever its inner_join_rels were.  If there were no elements (is
00633          * that possible?) the initialization before the loop fixed it.
00634          */
00635         if (list_length(f->fromlist) > 1)
00636             *inner_join_rels = *qualscope;
00637 
00638         /*
00639          * Now process the top-level quals.
00640          */
00641         foreach(l, (List *) f->quals)
00642         {
00643             Node       *qual = (Node *) lfirst(l);
00644 
00645             distribute_qual_to_rels(root, qual,
00646                                     false, below_outer_join, JOIN_INNER,
00647                                     *qualscope, NULL, NULL, NULL);
00648         }
00649     }
00650     else if (IsA(jtnode, JoinExpr))
00651     {
00652         JoinExpr   *j = (JoinExpr *) jtnode;
00653         Relids      leftids,
00654                     rightids,
00655                     left_inners,
00656                     right_inners,
00657                     nonnullable_rels,
00658                     ojscope;
00659         List       *leftjoinlist,
00660                    *rightjoinlist;
00661         SpecialJoinInfo *sjinfo;
00662         ListCell   *l;
00663 
00664         /*
00665          * Order of operations here is subtle and critical.  First we recurse
00666          * to handle sub-JOINs.  Their join quals will be placed without
00667          * regard for whether this level is an outer join, which is correct.
00668          * Then we place our own join quals, which are restricted by lower
00669          * outer joins in any case, and are forced to this level if this is an
00670          * outer join and they mention the outer side.  Finally, if this is an
00671          * outer join, we create a join_info_list entry for the join.  This
00672          * will prevent quals above us in the join tree that use those rels
00673          * from being pushed down below this level.  (It's okay for upper
00674          * quals to be pushed down to the outer side, however.)
00675          */
00676         switch (j->jointype)
00677         {
00678             case JOIN_INNER:
00679                 leftjoinlist = deconstruct_recurse(root, j->larg,
00680                                                    below_outer_join,
00681                                                    &leftids, &left_inners);
00682                 rightjoinlist = deconstruct_recurse(root, j->rarg,
00683                                                     below_outer_join,
00684                                                     &rightids, &right_inners);
00685                 *qualscope = bms_union(leftids, rightids);
00686                 *inner_join_rels = *qualscope;
00687                 /* Inner join adds no restrictions for quals */
00688                 nonnullable_rels = NULL;
00689                 break;
00690             case JOIN_LEFT:
00691             case JOIN_ANTI:
00692                 leftjoinlist = deconstruct_recurse(root, j->larg,
00693                                                    below_outer_join,
00694                                                    &leftids, &left_inners);
00695                 rightjoinlist = deconstruct_recurse(root, j->rarg,
00696                                                     true,
00697                                                     &rightids, &right_inners);
00698                 *qualscope = bms_union(leftids, rightids);
00699                 *inner_join_rels = bms_union(left_inners, right_inners);
00700                 nonnullable_rels = leftids;
00701                 break;
00702             case JOIN_SEMI:
00703                 leftjoinlist = deconstruct_recurse(root, j->larg,
00704                                                    below_outer_join,
00705                                                    &leftids, &left_inners);
00706                 rightjoinlist = deconstruct_recurse(root, j->rarg,
00707                                                     below_outer_join,
00708                                                     &rightids, &right_inners);
00709                 *qualscope = bms_union(leftids, rightids);
00710                 *inner_join_rels = bms_union(left_inners, right_inners);
00711                 /* Semi join adds no restrictions for quals */
00712                 nonnullable_rels = NULL;
00713                 break;
00714             case JOIN_FULL:
00715                 leftjoinlist = deconstruct_recurse(root, j->larg,
00716                                                    true,
00717                                                    &leftids, &left_inners);
00718                 rightjoinlist = deconstruct_recurse(root, j->rarg,
00719                                                     true,
00720                                                     &rightids, &right_inners);
00721                 *qualscope = bms_union(leftids, rightids);
00722                 *inner_join_rels = bms_union(left_inners, right_inners);
00723                 /* each side is both outer and inner */
00724                 nonnullable_rels = *qualscope;
00725                 break;
00726             default:
00727                 /* JOIN_RIGHT was eliminated during reduce_outer_joins() */
00728                 elog(ERROR, "unrecognized join type: %d",
00729                      (int) j->jointype);
00730                 nonnullable_rels = NULL;        /* keep compiler quiet */
00731                 leftjoinlist = rightjoinlist = NIL;
00732                 break;
00733         }
00734 
00735         /*
00736          * For an OJ, form the SpecialJoinInfo now, because we need the OJ's
00737          * semantic scope (ojscope) to pass to distribute_qual_to_rels.  But
00738          * we mustn't add it to join_info_list just yet, because we don't want
00739          * distribute_qual_to_rels to think it is an outer join below us.
00740          *
00741          * Semijoins are a bit of a hybrid: we build a SpecialJoinInfo, but we
00742          * want ojscope = NULL for distribute_qual_to_rels.
00743          */
00744         if (j->jointype != JOIN_INNER)
00745         {
00746             sjinfo = make_outerjoininfo(root,
00747                                         leftids, rightids,
00748                                         *inner_join_rels,
00749                                         j->jointype,
00750                                         (List *) j->quals);
00751             if (j->jointype == JOIN_SEMI)
00752                 ojscope = NULL;
00753             else
00754                 ojscope = bms_union(sjinfo->min_lefthand,
00755                                     sjinfo->min_righthand);
00756         }
00757         else
00758         {
00759             sjinfo = NULL;
00760             ojscope = NULL;
00761         }
00762 
00763         /* Process the qual clauses */
00764         foreach(l, (List *) j->quals)
00765         {
00766             Node       *qual = (Node *) lfirst(l);
00767 
00768             distribute_qual_to_rels(root, qual,
00769                                     false, below_outer_join, j->jointype,
00770                                     *qualscope,
00771                                     ojscope, nonnullable_rels, NULL);
00772         }
00773 
00774         /* Now we can add the SpecialJoinInfo to join_info_list */
00775         if (sjinfo)
00776         {
00777             root->join_info_list = lappend(root->join_info_list, sjinfo);
00778             /* Each time we do that, recheck placeholder eval levels */
00779             update_placeholder_eval_levels(root, sjinfo);
00780         }
00781 
00782         /*
00783          * Finally, compute the output joinlist.  We fold subproblems together
00784          * except at a FULL JOIN or where join_collapse_limit would be
00785          * exceeded.
00786          */
00787         if (j->jointype == JOIN_FULL)
00788         {
00789             /* force the join order exactly at this node */
00790             joinlist = list_make1(list_make2(leftjoinlist, rightjoinlist));
00791         }
00792         else if (list_length(leftjoinlist) + list_length(rightjoinlist) <=
00793                  join_collapse_limit)
00794         {
00795             /* OK to combine subproblems */
00796             joinlist = list_concat(leftjoinlist, rightjoinlist);
00797         }
00798         else
00799         {
00800             /* can't combine, but needn't force join order above here */
00801             Node       *leftpart,
00802                        *rightpart;
00803 
00804             /* avoid creating useless 1-element sublists */
00805             if (list_length(leftjoinlist) == 1)
00806                 leftpart = (Node *) linitial(leftjoinlist);
00807             else
00808                 leftpart = (Node *) leftjoinlist;
00809             if (list_length(rightjoinlist) == 1)
00810                 rightpart = (Node *) linitial(rightjoinlist);
00811             else
00812                 rightpart = (Node *) rightjoinlist;
00813             joinlist = list_make2(leftpart, rightpart);
00814         }
00815     }
00816     else
00817     {
00818         elog(ERROR, "unrecognized node type: %d",
00819              (int) nodeTag(jtnode));
00820         joinlist = NIL;         /* keep compiler quiet */
00821     }
00822     return joinlist;
00823 }
00824 
00825 /*
00826  * make_outerjoininfo
00827  *    Build a SpecialJoinInfo for the current outer join
00828  *
00829  * Inputs:
00830  *  left_rels: the base Relids syntactically on outer side of join
00831  *  right_rels: the base Relids syntactically on inner side of join
00832  *  inner_join_rels: base Relids participating in inner joins below this one
00833  *  jointype: what it says (must always be LEFT, FULL, SEMI, or ANTI)
00834  *  clause: the outer join's join condition (in implicit-AND format)
00835  *
00836  * The node should eventually be appended to root->join_info_list, but we
00837  * do not do that here.
00838  *
00839  * Note: we assume that this function is invoked bottom-up, so that
00840  * root->join_info_list already contains entries for all outer joins that are
00841  * syntactically below this one.
00842  */
00843 static SpecialJoinInfo *
00844 make_outerjoininfo(PlannerInfo *root,
00845                    Relids left_rels, Relids right_rels,
00846                    Relids inner_join_rels,
00847                    JoinType jointype, List *clause)
00848 {
00849     SpecialJoinInfo *sjinfo = makeNode(SpecialJoinInfo);
00850     Relids      clause_relids;
00851     Relids      strict_relids;
00852     Relids      min_lefthand;
00853     Relids      min_righthand;
00854     ListCell   *l;
00855 
00856     /*
00857      * We should not see RIGHT JOIN here because left/right were switched
00858      * earlier
00859      */
00860     Assert(jointype != JOIN_INNER);
00861     Assert(jointype != JOIN_RIGHT);
00862 
00863     /*
00864      * Presently the executor cannot support FOR [KEY] UPDATE/SHARE marking of rels
00865      * appearing on the nullable side of an outer join. (It's somewhat unclear
00866      * what that would mean, anyway: what should we mark when a result row is
00867      * generated from no element of the nullable relation?)  So, complain if
00868      * any nullable rel is FOR [KEY] UPDATE/SHARE.
00869      *
00870      * You might be wondering why this test isn't made far upstream in the
00871      * parser.  It's because the parser hasn't got enough info --- consider
00872      * FOR UPDATE applied to a view.  Only after rewriting and flattening do
00873      * we know whether the view contains an outer join.
00874      *
00875      * We use the original RowMarkClause list here; the PlanRowMark list would
00876      * list everything.
00877      */
00878     foreach(l, root->parse->rowMarks)
00879     {
00880         RowMarkClause *rc = (RowMarkClause *) lfirst(l);
00881 
00882         if (bms_is_member(rc->rti, right_rels) ||
00883             (jointype == JOIN_FULL && bms_is_member(rc->rti, left_rels)))
00884             ereport(ERROR,
00885                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00886                      errmsg("row-level locks cannot be applied to the nullable side of an outer join")));
00887     }
00888 
00889     sjinfo->syn_lefthand = left_rels;
00890     sjinfo->syn_righthand = right_rels;
00891     sjinfo->jointype = jointype;
00892     /* this always starts out false */
00893     sjinfo->delay_upper_joins = false;
00894     sjinfo->join_quals = clause;
00895 
00896     /* If it's a full join, no need to be very smart */
00897     if (jointype == JOIN_FULL)
00898     {
00899         sjinfo->min_lefthand = bms_copy(left_rels);
00900         sjinfo->min_righthand = bms_copy(right_rels);
00901         sjinfo->lhs_strict = false;     /* don't care about this */
00902         return sjinfo;
00903     }
00904 
00905     /*
00906      * Retrieve all relids mentioned within the join clause.
00907      */
00908     clause_relids = pull_varnos((Node *) clause);
00909 
00910     /*
00911      * For which relids is the clause strict, ie, it cannot succeed if the
00912      * rel's columns are all NULL?
00913      */
00914     strict_relids = find_nonnullable_rels((Node *) clause);
00915 
00916     /* Remember whether the clause is strict for any LHS relations */
00917     sjinfo->lhs_strict = bms_overlap(strict_relids, left_rels);
00918 
00919     /*
00920      * Required LHS always includes the LHS rels mentioned in the clause. We
00921      * may have to add more rels based on lower outer joins; see below.
00922      */
00923     min_lefthand = bms_intersect(clause_relids, left_rels);
00924 
00925     /*
00926      * Similarly for required RHS.  But here, we must also include any lower
00927      * inner joins, to ensure we don't try to commute with any of them.
00928      */
00929     min_righthand = bms_int_members(bms_union(clause_relids, inner_join_rels),
00930                                     right_rels);
00931 
00932     foreach(l, root->join_info_list)
00933     {
00934         SpecialJoinInfo *otherinfo = (SpecialJoinInfo *) lfirst(l);
00935 
00936         /* ignore full joins --- other mechanisms preserve their ordering */
00937         if (otherinfo->jointype == JOIN_FULL)
00938             continue;
00939 
00940         /*
00941          * For a lower OJ in our LHS, if our join condition uses the lower
00942          * join's RHS and is not strict for that rel, we must preserve the
00943          * ordering of the two OJs, so add lower OJ's full syntactic relset to
00944          * min_lefthand.  (We must use its full syntactic relset, not just its
00945          * min_lefthand + min_righthand.  This is because there might be other
00946          * OJs below this one that this one can commute with, but we cannot
00947          * commute with them if we don't with this one.)  Also, if the current
00948          * join is a semijoin or antijoin, we must preserve ordering
00949          * regardless of strictness.
00950          *
00951          * Note: I believe we have to insist on being strict for at least one
00952          * rel in the lower OJ's min_righthand, not its whole syn_righthand.
00953          */
00954         if (bms_overlap(left_rels, otherinfo->syn_righthand))
00955         {
00956             if (bms_overlap(clause_relids, otherinfo->syn_righthand) &&
00957                 (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
00958                  !bms_overlap(strict_relids, otherinfo->min_righthand)))
00959             {
00960                 min_lefthand = bms_add_members(min_lefthand,
00961                                                otherinfo->syn_lefthand);
00962                 min_lefthand = bms_add_members(min_lefthand,
00963                                                otherinfo->syn_righthand);
00964             }
00965         }
00966 
00967         /*
00968          * For a lower OJ in our RHS, if our join condition does not use the
00969          * lower join's RHS and the lower OJ's join condition is strict, we
00970          * can interchange the ordering of the two OJs; otherwise we must add
00971          * lower OJ's full syntactic relset to min_righthand.  Here, we must
00972          * preserve ordering anyway if either the current join is a semijoin,
00973          * or the lower OJ is either a semijoin or an antijoin.
00974          *
00975          * Here, we have to consider that "our join condition" includes any
00976          * clauses that syntactically appeared above the lower OJ and below
00977          * ours; those are equivalent to degenerate clauses in our OJ and must
00978          * be treated as such.  Such clauses obviously can't reference our
00979          * LHS, and they must be non-strict for the lower OJ's RHS (else
00980          * reduce_outer_joins would have reduced the lower OJ to a plain
00981          * join).  Hence the other ways in which we handle clauses within our
00982          * join condition are not affected by them.  The net effect is
00983          * therefore sufficiently represented by the delay_upper_joins flag
00984          * saved for us by check_outerjoin_delay.
00985          */
00986         if (bms_overlap(right_rels, otherinfo->syn_righthand))
00987         {
00988             if (bms_overlap(clause_relids, otherinfo->syn_righthand) ||
00989                 jointype == JOIN_SEMI ||
00990                 otherinfo->jointype == JOIN_SEMI ||
00991                 otherinfo->jointype == JOIN_ANTI ||
00992                 !otherinfo->lhs_strict || otherinfo->delay_upper_joins)
00993             {
00994                 min_righthand = bms_add_members(min_righthand,
00995                                                 otherinfo->syn_lefthand);
00996                 min_righthand = bms_add_members(min_righthand,
00997                                                 otherinfo->syn_righthand);
00998             }
00999         }
01000     }
01001 
01002     /*
01003      * Examine PlaceHolderVars.  If a PHV is supposed to be evaluated within
01004      * this join's nullable side, and it may get used above this join, then
01005      * ensure that min_righthand contains the full eval_at set of the PHV.
01006      * This ensures that the PHV actually can be evaluated within the RHS.
01007      * Note that this works only because we should already have determined the
01008      * final eval_at level for any PHV syntactically within this join.
01009      */
01010     foreach(l, root->placeholder_list)
01011     {
01012         PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l);
01013         Relids      ph_syn_level = phinfo->ph_var->phrels;
01014 
01015         /* Ignore placeholder if it didn't syntactically come from RHS */
01016         if (!bms_is_subset(ph_syn_level, right_rels))
01017             continue;
01018 
01019         /* We can also ignore it if it's certainly not used above this join */
01020         /* XXX this test is probably overly conservative */
01021         if (bms_is_subset(phinfo->ph_may_need, min_righthand))
01022             continue;
01023 
01024         /* Else, prevent join from being formed before we eval the PHV */
01025         min_righthand = bms_add_members(min_righthand, phinfo->ph_eval_at);
01026     }
01027 
01028     /*
01029      * If we found nothing to put in min_lefthand, punt and make it the full
01030      * LHS, to avoid having an empty min_lefthand which will confuse later
01031      * processing. (We don't try to be smart about such cases, just correct.)
01032      * Likewise for min_righthand.
01033      */
01034     if (bms_is_empty(min_lefthand))
01035         min_lefthand = bms_copy(left_rels);
01036     if (bms_is_empty(min_righthand))
01037         min_righthand = bms_copy(right_rels);
01038 
01039     /* Now they'd better be nonempty */
01040     Assert(!bms_is_empty(min_lefthand));
01041     Assert(!bms_is_empty(min_righthand));
01042     /* Shouldn't overlap either */
01043     Assert(!bms_overlap(min_lefthand, min_righthand));
01044 
01045     sjinfo->min_lefthand = min_lefthand;
01046     sjinfo->min_righthand = min_righthand;
01047 
01048     return sjinfo;
01049 }
01050 
01051 
01052 /*****************************************************************************
01053  *
01054  *    QUALIFICATIONS
01055  *
01056  *****************************************************************************/
01057 
01058 /*
01059  * distribute_qual_to_rels
01060  *    Add clause information to either the baserestrictinfo or joininfo list
01061  *    (depending on whether the clause is a join) of each base relation
01062  *    mentioned in the clause.  A RestrictInfo node is created and added to
01063  *    the appropriate list for each rel.  Alternatively, if the clause uses a
01064  *    mergejoinable operator and is not delayed by outer-join rules, enter
01065  *    the left- and right-side expressions into the query's list of
01066  *    EquivalenceClasses.
01067  *
01068  * 'clause': the qual clause to be distributed
01069  * 'is_deduced': TRUE if the qual came from implied-equality deduction
01070  * 'below_outer_join': TRUE if the qual is from a JOIN/ON that is below the
01071  *      nullable side of a higher-level outer join
01072  * 'jointype': type of join the qual is from (JOIN_INNER for a WHERE clause)
01073  * 'qualscope': set of baserels the qual's syntactic scope covers
01074  * 'ojscope': NULL if not an outer-join qual, else the minimum set of baserels
01075  *      needed to form this join
01076  * 'outerjoin_nonnullable': NULL if not an outer-join qual, else the set of
01077  *      baserels appearing on the outer (nonnullable) side of the join
01078  *      (for FULL JOIN this includes both sides of the join, and must in fact
01079  *      equal qualscope)
01080  * 'deduced_nullable_relids': if is_deduced is TRUE, the nullable relids to
01081  *      impute to the clause; otherwise NULL
01082  *
01083  * 'qualscope' identifies what level of JOIN the qual came from syntactically.
01084  * 'ojscope' is needed if we decide to force the qual up to the outer-join
01085  * level, which will be ojscope not necessarily qualscope.
01086  *
01087  * In normal use (when is_deduced is FALSE), at the time this is called,
01088  * root->join_info_list must contain entries for all and only those special
01089  * joins that are syntactically below this qual.  But when is_deduced is TRUE,
01090  * we are adding new deduced clauses after completion of deconstruct_jointree,
01091  * so it cannot be assumed that root->join_info_list has anything to do with
01092  * qual placement.
01093  */
01094 static void
01095 distribute_qual_to_rels(PlannerInfo *root, Node *clause,
01096                         bool is_deduced,
01097                         bool below_outer_join,
01098                         JoinType jointype,
01099                         Relids qualscope,
01100                         Relids ojscope,
01101                         Relids outerjoin_nonnullable,
01102                         Relids deduced_nullable_relids)
01103 {
01104     Relids      relids;
01105     bool        is_pushed_down;
01106     bool        outerjoin_delayed;
01107     bool        pseudoconstant = false;
01108     bool        maybe_equivalence;
01109     bool        maybe_outer_join;
01110     Relids      nullable_relids;
01111     RestrictInfo *restrictinfo;
01112 
01113     /*
01114      * Retrieve all relids mentioned within the clause.
01115      */
01116     relids = pull_varnos(clause);
01117 
01118     /*
01119      * Normally relids is a subset of qualscope, and we like to check that
01120      * here as a crosscheck on the parser and rewriter.  That need not be the
01121      * case when there are LATERAL RTEs, however: the clause could contain
01122      * references to rels outside its syntactic scope as a consequence of
01123      * pull-up of such references from a LATERAL subquery below it.  So, only
01124      * check if the query contains no LATERAL RTEs.
01125      *
01126      * However, if it's an outer-join clause, we always insist that relids be
01127      * a subset of ojscope.  This is safe because is_simple_subquery()
01128      * disallows pullup of LATERAL subqueries that could cause the restriction
01129      * to be violated.
01130      */
01131     if (!root->hasLateralRTEs && !bms_is_subset(relids, qualscope))
01132         elog(ERROR, "JOIN qualification cannot refer to other relations");
01133     if (ojscope && !bms_is_subset(relids, ojscope))
01134         elog(ERROR, "JOIN qualification cannot refer to other relations");
01135 
01136     /*
01137      * If the clause is variable-free, our normal heuristic for pushing it
01138      * down to just the mentioned rels doesn't work, because there are none.
01139      *
01140      * If the clause is an outer-join clause, we must force it to the OJ's
01141      * semantic level to preserve semantics.
01142      *
01143      * Otherwise, when the clause contains volatile functions, we force it to
01144      * be evaluated at its original syntactic level.  This preserves the
01145      * expected semantics.
01146      *
01147      * When the clause contains no volatile functions either, it is actually a
01148      * pseudoconstant clause that will not change value during any one
01149      * execution of the plan, and hence can be used as a one-time qual in a
01150      * gating Result plan node.  We put such a clause into the regular
01151      * RestrictInfo lists for the moment, but eventually createplan.c will
01152      * pull it out and make a gating Result node immediately above whatever
01153      * plan node the pseudoconstant clause is assigned to.  It's usually best
01154      * to put a gating node as high in the plan tree as possible. If we are
01155      * not below an outer join, we can actually push the pseudoconstant qual
01156      * all the way to the top of the tree.  If we are below an outer join, we
01157      * leave the qual at its original syntactic level (we could push it up to
01158      * just below the outer join, but that seems more complex than it's
01159      * worth).
01160      */
01161     if (bms_is_empty(relids))
01162     {
01163         if (ojscope)
01164         {
01165             /* clause is attached to outer join, eval it there */
01166             relids = bms_copy(ojscope);
01167             /* mustn't use as gating qual, so don't mark pseudoconstant */
01168         }
01169         else
01170         {
01171             /* eval at original syntactic level */
01172             relids = bms_copy(qualscope);
01173             if (!contain_volatile_functions(clause))
01174             {
01175                 /* mark as gating qual */
01176                 pseudoconstant = true;
01177                 /* tell createplan.c to check for gating quals */
01178                 root->hasPseudoConstantQuals = true;
01179                 /* if not below outer join, push it to top of tree */
01180                 if (!below_outer_join)
01181                 {
01182                     relids =
01183                         get_relids_in_jointree((Node *) root->parse->jointree,
01184                                                false);
01185                     qualscope = bms_copy(relids);
01186                 }
01187             }
01188         }
01189     }
01190 
01191     /*----------
01192      * Check to see if clause application must be delayed by outer-join
01193      * considerations.
01194      *
01195      * A word about is_pushed_down: we mark the qual as "pushed down" if
01196      * it is (potentially) applicable at a level different from its original
01197      * syntactic level.  This flag is used to distinguish OUTER JOIN ON quals
01198      * from other quals pushed down to the same joinrel.  The rules are:
01199      *      WHERE quals and INNER JOIN quals: is_pushed_down = true.
01200      *      Non-degenerate OUTER JOIN quals: is_pushed_down = false.
01201      *      Degenerate OUTER JOIN quals: is_pushed_down = true.
01202      * A "degenerate" OUTER JOIN qual is one that doesn't mention the
01203      * non-nullable side, and hence can be pushed down into the nullable side
01204      * without changing the join result.  It is correct to treat it as a
01205      * regular filter condition at the level where it is evaluated.
01206      *
01207      * Note: it is not immediately obvious that a simple boolean is enough
01208      * for this: if for some reason we were to attach a degenerate qual to
01209      * its original join level, it would need to be treated as an outer join
01210      * qual there.  However, this cannot happen, because all the rels the
01211      * clause mentions must be in the outer join's min_righthand, therefore
01212      * the join it needs must be formed before the outer join; and we always
01213      * attach quals to the lowest level where they can be evaluated.  But
01214      * if we were ever to re-introduce a mechanism for delaying evaluation
01215      * of "expensive" quals, this area would need work.
01216      *----------
01217      */
01218     if (is_deduced)
01219     {
01220         /*
01221          * If the qual came from implied-equality deduction, it should not be
01222          * outerjoin-delayed, else deducer blew it.  But we can't check this
01223          * because the join_info_list may now contain OJs above where the qual
01224          * belongs.  For the same reason, we must rely on caller to supply the
01225          * correct nullable_relids set.
01226          */
01227         Assert(!ojscope);
01228         is_pushed_down = true;
01229         outerjoin_delayed = false;
01230         nullable_relids = deduced_nullable_relids;
01231         /* Don't feed it back for more deductions */
01232         maybe_equivalence = false;
01233         maybe_outer_join = false;
01234     }
01235     else if (bms_overlap(relids, outerjoin_nonnullable))
01236     {
01237         /*
01238          * The qual is attached to an outer join and mentions (some of the)
01239          * rels on the nonnullable side, so it's not degenerate.
01240          *
01241          * We can't use such a clause to deduce equivalence (the left and
01242          * right sides might be unequal above the join because one of them has
01243          * gone to NULL) ... but we might be able to use it for more limited
01244          * deductions, if it is mergejoinable.  So consider adding it to the
01245          * lists of set-aside outer-join clauses.
01246          */
01247         is_pushed_down = false;
01248         maybe_equivalence = false;
01249         maybe_outer_join = true;
01250 
01251         /* Check to see if must be delayed by lower outer join */
01252         outerjoin_delayed = check_outerjoin_delay(root,
01253                                                   &relids,
01254                                                   &nullable_relids,
01255                                                   false);
01256 
01257         /*
01258          * Now force the qual to be evaluated exactly at the level of joining
01259          * corresponding to the outer join.  We cannot let it get pushed down
01260          * into the nonnullable side, since then we'd produce no output rows,
01261          * rather than the intended single null-extended row, for any
01262          * nonnullable-side rows failing the qual.
01263          *
01264          * (Do this step after calling check_outerjoin_delay, because that
01265          * trashes relids.)
01266          */
01267         Assert(ojscope);
01268         relids = ojscope;
01269         Assert(!pseudoconstant);
01270     }
01271     else
01272     {
01273         /*
01274          * Normal qual clause or degenerate outer-join clause.  Either way, we
01275          * can mark it as pushed-down.
01276          */
01277         is_pushed_down = true;
01278 
01279         /* Check to see if must be delayed by lower outer join */
01280         outerjoin_delayed = check_outerjoin_delay(root,
01281                                                   &relids,
01282                                                   &nullable_relids,
01283                                                   true);
01284 
01285         if (outerjoin_delayed)
01286         {
01287             /* Should still be a subset of current scope ... */
01288             Assert(root->hasLateralRTEs || bms_is_subset(relids, qualscope));
01289             Assert(ojscope == NULL || bms_is_subset(relids, ojscope));
01290 
01291             /*
01292              * Because application of the qual will be delayed by outer join,
01293              * we mustn't assume its vars are equal everywhere.
01294              */
01295             maybe_equivalence = false;
01296 
01297             /*
01298              * It's possible that this is an IS NULL clause that's redundant
01299              * with a lower antijoin; if so we can just discard it.  We need
01300              * not test in any of the other cases, because this will only be
01301              * possible for pushed-down, delayed clauses.
01302              */
01303             if (check_redundant_nullability_qual(root, clause))
01304                 return;
01305         }
01306         else
01307         {
01308             /*
01309              * Qual is not delayed by any lower outer-join restriction, so we
01310              * can consider feeding it to the equivalence machinery. However,
01311              * if it's itself within an outer-join clause, treat it as though
01312              * it appeared below that outer join (note that we can only get
01313              * here when the clause references only nullable-side rels).
01314              */
01315             maybe_equivalence = true;
01316             if (outerjoin_nonnullable != NULL)
01317                 below_outer_join = true;
01318         }
01319 
01320         /*
01321          * Since it doesn't mention the LHS, it's certainly not useful as a
01322          * set-aside OJ clause, even if it's in an OJ.
01323          */
01324         maybe_outer_join = false;
01325     }
01326 
01327     /*
01328      * Build the RestrictInfo node itself.
01329      */
01330     restrictinfo = make_restrictinfo((Expr *) clause,
01331                                      is_pushed_down,
01332                                      outerjoin_delayed,
01333                                      pseudoconstant,
01334                                      relids,
01335                                      outerjoin_nonnullable,
01336                                      nullable_relids);
01337 
01338     /*
01339      * If it's a join clause (either naturally, or because delayed by
01340      * outer-join rules), add vars used in the clause to targetlists of their
01341      * relations, so that they will be emitted by the plan nodes that scan
01342      * those relations (else they won't be available at the join node!).
01343      *
01344      * Note: if the clause gets absorbed into an EquivalenceClass then this
01345      * may be unnecessary, but for now we have to do it to cover the case
01346      * where the EC becomes ec_broken and we end up reinserting the original
01347      * clauses into the plan.
01348      */
01349     if (bms_membership(relids) == BMS_MULTIPLE)
01350     {
01351         List       *vars = pull_var_clause(clause,
01352                                            PVC_RECURSE_AGGREGATES,
01353                                            PVC_INCLUDE_PLACEHOLDERS);
01354 
01355         add_vars_to_targetlist(root, vars, relids, false);
01356         list_free(vars);
01357     }
01358 
01359     /*
01360      * We check "mergejoinability" of every clause, not only join clauses,
01361      * because we want to know about equivalences between vars of the same
01362      * relation, or between vars and consts.
01363      */
01364     check_mergejoinable(restrictinfo);
01365 
01366     /*
01367      * If it is a true equivalence clause, send it to the EquivalenceClass
01368      * machinery.  We do *not* attach it directly to any restriction or join
01369      * lists.  The EC code will propagate it to the appropriate places later.
01370      *
01371      * If the clause has a mergejoinable operator and is not
01372      * outerjoin-delayed, yet isn't an equivalence because it is an outer-join
01373      * clause, the EC code may yet be able to do something with it.  We add it
01374      * to appropriate lists for further consideration later.  Specifically:
01375      *
01376      * If it is a left or right outer-join qualification that relates the two
01377      * sides of the outer join (no funny business like leftvar1 = leftvar2 +
01378      * rightvar), we add it to root->left_join_clauses or
01379      * root->right_join_clauses according to which side the nonnullable
01380      * variable appears on.
01381      *
01382      * If it is a full outer-join qualification, we add it to
01383      * root->full_join_clauses.  (Ideally we'd discard cases that aren't
01384      * leftvar = rightvar, as we do for left/right joins, but this routine
01385      * doesn't have the info needed to do that; and the current usage of the
01386      * full_join_clauses list doesn't require that, so it's not currently
01387      * worth complicating this routine's API to make it possible.)
01388      *
01389      * If none of the above hold, pass it off to
01390      * distribute_restrictinfo_to_rels().
01391      *
01392      * In all cases, it's important to initialize the left_ec and right_ec
01393      * fields of a mergejoinable clause, so that all possibly mergejoinable
01394      * expressions have representations in EquivalenceClasses.  If
01395      * process_equivalence is successful, it will take care of that;
01396      * otherwise, we have to call initialize_mergeclause_eclasses to do it.
01397      */
01398     if (restrictinfo->mergeopfamilies)
01399     {
01400         if (maybe_equivalence)
01401         {
01402             if (check_equivalence_delay(root, restrictinfo) &&
01403                 process_equivalence(root, restrictinfo, below_outer_join))
01404                 return;
01405             /* EC rejected it, so set left_ec/right_ec the hard way ... */
01406             initialize_mergeclause_eclasses(root, restrictinfo);
01407             /* ... and fall through to distribute_restrictinfo_to_rels */
01408         }
01409         else if (maybe_outer_join && restrictinfo->can_join)
01410         {
01411             /* we need to set up left_ec/right_ec the hard way */
01412             initialize_mergeclause_eclasses(root, restrictinfo);
01413             /* now see if it should go to any outer-join lists */
01414             if (bms_is_subset(restrictinfo->left_relids,
01415                               outerjoin_nonnullable) &&
01416                 !bms_overlap(restrictinfo->right_relids,
01417                              outerjoin_nonnullable))
01418             {
01419                 /* we have outervar = innervar */
01420                 root->left_join_clauses = lappend(root->left_join_clauses,
01421                                                   restrictinfo);
01422                 return;
01423             }
01424             if (bms_is_subset(restrictinfo->right_relids,
01425                               outerjoin_nonnullable) &&
01426                 !bms_overlap(restrictinfo->left_relids,
01427                              outerjoin_nonnullable))
01428             {
01429                 /* we have innervar = outervar */
01430                 root->right_join_clauses = lappend(root->right_join_clauses,
01431                                                    restrictinfo);
01432                 return;
01433             }
01434             if (jointype == JOIN_FULL)
01435             {
01436                 /* FULL JOIN (above tests cannot match in this case) */
01437                 root->full_join_clauses = lappend(root->full_join_clauses,
01438                                                   restrictinfo);
01439                 return;
01440             }
01441             /* nope, so fall through to distribute_restrictinfo_to_rels */
01442         }
01443         else
01444         {
01445             /* we still need to set up left_ec/right_ec */
01446             initialize_mergeclause_eclasses(root, restrictinfo);
01447         }
01448     }
01449 
01450     /* No EC special case applies, so push it into the clause lists */
01451     distribute_restrictinfo_to_rels(root, restrictinfo);
01452 }
01453 
01454 /*
01455  * check_outerjoin_delay
01456  *      Detect whether a qual referencing the given relids must be delayed
01457  *      in application due to the presence of a lower outer join, and/or
01458  *      may force extra delay of higher-level outer joins.
01459  *
01460  * If the qual must be delayed, add relids to *relids_p to reflect the lowest
01461  * safe level for evaluating the qual, and return TRUE.  Any extra delay for
01462  * higher-level joins is reflected by setting delay_upper_joins to TRUE in
01463  * SpecialJoinInfo structs.  We also compute nullable_relids, the set of
01464  * referenced relids that are nullable by lower outer joins (note that this
01465  * can be nonempty even for a non-delayed qual).
01466  *
01467  * For an is_pushed_down qual, we can evaluate the qual as soon as (1) we have
01468  * all the rels it mentions, and (2) we are at or above any outer joins that
01469  * can null any of these rels and are below the syntactic location of the
01470  * given qual.  We must enforce (2) because pushing down such a clause below
01471  * the OJ might cause the OJ to emit null-extended rows that should not have
01472  * been formed, or that should have been rejected by the clause.  (This is
01473  * only an issue for non-strict quals, since if we can prove a qual mentioning
01474  * only nullable rels is strict, we'd have reduced the outer join to an inner
01475  * join in reduce_outer_joins().)
01476  *
01477  * To enforce (2), scan the join_info_list and merge the required-relid sets of
01478  * any such OJs into the clause's own reference list.  At the time we are
01479  * called, the join_info_list contains only outer joins below this qual.  We
01480  * have to repeat the scan until no new relids get added; this ensures that
01481  * the qual is suitably delayed regardless of the order in which OJs get
01482  * executed.  As an example, if we have one OJ with LHS=A, RHS=B, and one with
01483  * LHS=B, RHS=C, it is implied that these can be done in either order; if the
01484  * B/C join is done first then the join to A can null C, so a qual actually
01485  * mentioning only C cannot be applied below the join to A.
01486  *
01487  * For a non-pushed-down qual, this isn't going to determine where we place the
01488  * qual, but we need to determine outerjoin_delayed and nullable_relids anyway
01489  * for use later in the planning process.
01490  *
01491  * Lastly, a pushed-down qual that references the nullable side of any current
01492  * join_info_list member and has to be evaluated above that OJ (because its
01493  * required relids overlap the LHS too) causes that OJ's delay_upper_joins
01494  * flag to be set TRUE.  This will prevent any higher-level OJs from
01495  * being interchanged with that OJ, which would result in not having any
01496  * correct place to evaluate the qual.  (The case we care about here is a
01497  * sub-select WHERE clause within the RHS of some outer join.  The WHERE
01498  * clause must effectively be treated as a degenerate clause of that outer
01499  * join's condition.  Rather than trying to match such clauses with joins
01500  * directly, we set delay_upper_joins here, and when the upper outer join
01501  * is processed by make_outerjoininfo, it will refrain from allowing the
01502  * two OJs to commute.)
01503  */
01504 static bool
01505 check_outerjoin_delay(PlannerInfo *root,
01506                       Relids *relids_p, /* in/out parameter */
01507                       Relids *nullable_relids_p,        /* output parameter */
01508                       bool is_pushed_down)
01509 {
01510     Relids      relids;
01511     Relids      nullable_relids;
01512     bool        outerjoin_delayed;
01513     bool        found_some;
01514 
01515     /* fast path if no special joins */
01516     if (root->join_info_list == NIL)
01517     {
01518         *nullable_relids_p = NULL;
01519         return false;
01520     }
01521 
01522     /* must copy relids because we need the original value at the end */
01523     relids = bms_copy(*relids_p);
01524     nullable_relids = NULL;
01525     outerjoin_delayed = false;
01526     do
01527     {
01528         ListCell   *l;
01529 
01530         found_some = false;
01531         foreach(l, root->join_info_list)
01532         {
01533             SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
01534 
01535             /* do we reference any nullable rels of this OJ? */
01536             if (bms_overlap(relids, sjinfo->min_righthand) ||
01537                 (sjinfo->jointype == JOIN_FULL &&
01538                  bms_overlap(relids, sjinfo->min_lefthand)))
01539             {
01540                 /* yes; have we included all its rels in relids? */
01541                 if (!bms_is_subset(sjinfo->min_lefthand, relids) ||
01542                     !bms_is_subset(sjinfo->min_righthand, relids))
01543                 {
01544                     /* no, so add them in */
01545                     relids = bms_add_members(relids, sjinfo->min_lefthand);
01546                     relids = bms_add_members(relids, sjinfo->min_righthand);
01547                     outerjoin_delayed = true;
01548                     /* we'll need another iteration */
01549                     found_some = true;
01550                 }
01551                 /* track all the nullable rels of relevant OJs */
01552                 nullable_relids = bms_add_members(nullable_relids,
01553                                                   sjinfo->min_righthand);
01554                 if (sjinfo->jointype == JOIN_FULL)
01555                     nullable_relids = bms_add_members(nullable_relids,
01556                                                       sjinfo->min_lefthand);
01557                 /* set delay_upper_joins if needed */
01558                 if (is_pushed_down && sjinfo->jointype != JOIN_FULL &&
01559                     bms_overlap(relids, sjinfo->min_lefthand))
01560                     sjinfo->delay_upper_joins = true;
01561             }
01562         }
01563     } while (found_some);
01564 
01565     /* identify just the actually-referenced nullable rels */
01566     nullable_relids = bms_int_members(nullable_relids, *relids_p);
01567 
01568     /* replace *relids_p, and return nullable_relids */
01569     bms_free(*relids_p);
01570     *relids_p = relids;
01571     *nullable_relids_p = nullable_relids;
01572     return outerjoin_delayed;
01573 }
01574 
01575 /*
01576  * check_equivalence_delay
01577  *      Detect whether a potential equivalence clause is rendered unsafe
01578  *      by outer-join-delay considerations.  Return TRUE if it's safe.
01579  *
01580  * The initial tests in distribute_qual_to_rels will consider a mergejoinable
01581  * clause to be a potential equivalence clause if it is not outerjoin_delayed.
01582  * But since the point of equivalence processing is that we will recombine the
01583  * two sides of the clause with others, we have to check that each side
01584  * satisfies the not-outerjoin_delayed condition on its own; otherwise it might
01585  * not be safe to evaluate everywhere we could place a derived equivalence
01586  * condition.
01587  */
01588 static bool
01589 check_equivalence_delay(PlannerInfo *root,
01590                         RestrictInfo *restrictinfo)
01591 {
01592     Relids      relids;
01593     Relids      nullable_relids;
01594 
01595     /* fast path if no special joins */
01596     if (root->join_info_list == NIL)
01597         return true;
01598 
01599     /* must copy restrictinfo's relids to avoid changing it */
01600     relids = bms_copy(restrictinfo->left_relids);
01601     /* check left side does not need delay */
01602     if (check_outerjoin_delay(root, &relids, &nullable_relids, true))
01603         return false;
01604 
01605     /* and similarly for the right side */
01606     relids = bms_copy(restrictinfo->right_relids);
01607     if (check_outerjoin_delay(root, &relids, &nullable_relids, true))
01608         return false;
01609 
01610     return true;
01611 }
01612 
01613 /*
01614  * check_redundant_nullability_qual
01615  *    Check to see if the qual is an IS NULL qual that is redundant with
01616  *    a lower JOIN_ANTI join.
01617  *
01618  * We want to suppress redundant IS NULL quals, not so much to save cycles
01619  * as to avoid generating bogus selectivity estimates for them.  So if
01620  * redundancy is detected here, distribute_qual_to_rels() just throws away
01621  * the qual.
01622  */
01623 static bool
01624 check_redundant_nullability_qual(PlannerInfo *root, Node *clause)
01625 {
01626     Var        *forced_null_var;
01627     Index       forced_null_rel;
01628     ListCell   *lc;
01629 
01630     /* Check for IS NULL, and identify the Var forced to NULL */
01631     forced_null_var = find_forced_null_var(clause);
01632     if (forced_null_var == NULL)
01633         return false;
01634     forced_null_rel = forced_null_var->varno;
01635 
01636     /*
01637      * If the Var comes from the nullable side of a lower antijoin, the IS
01638      * NULL condition is necessarily true.
01639      */
01640     foreach(lc, root->join_info_list)
01641     {
01642         SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
01643 
01644         if (sjinfo->jointype == JOIN_ANTI &&
01645             bms_is_member(forced_null_rel, sjinfo->syn_righthand))
01646             return true;
01647     }
01648 
01649     return false;
01650 }
01651 
01652 /*
01653  * distribute_restrictinfo_to_rels
01654  *    Push a completed RestrictInfo into the proper restriction or join
01655  *    clause list(s).
01656  *
01657  * This is the last step of distribute_qual_to_rels() for ordinary qual
01658  * clauses.  Clauses that are interesting for equivalence-class processing
01659  * are diverted to the EC machinery, but may ultimately get fed back here.
01660  */
01661 void
01662 distribute_restrictinfo_to_rels(PlannerInfo *root,
01663                                 RestrictInfo *restrictinfo)
01664 {
01665     Relids      relids = restrictinfo->required_relids;
01666     RelOptInfo *rel;
01667 
01668     switch (bms_membership(relids))
01669     {
01670         case BMS_SINGLETON:
01671 
01672             /*
01673              * There is only one relation participating in the clause, so it
01674              * is a restriction clause for that relation.
01675              */
01676             rel = find_base_rel(root, bms_singleton_member(relids));
01677 
01678             /* Add clause to rel's restriction list */
01679             rel->baserestrictinfo = lappend(rel->baserestrictinfo,
01680                                             restrictinfo);
01681             break;
01682         case BMS_MULTIPLE:
01683 
01684             /*
01685              * The clause is a join clause, since there is more than one rel
01686              * in its relid set.
01687              */
01688 
01689             /*
01690              * Check for hashjoinable operators.  (We don't bother setting the
01691              * hashjoin info except in true join clauses.)
01692              */
01693             check_hashjoinable(restrictinfo);
01694 
01695             /*
01696              * Add clause to the join lists of all the relevant relations.
01697              */
01698             add_join_clause_to_rels(root, restrictinfo, relids);
01699             break;
01700         default:
01701 
01702             /*
01703              * clause references no rels, and therefore we have no place to
01704              * attach it.  Shouldn't get here if callers are working properly.
01705              */
01706             elog(ERROR, "cannot cope with variable-free clause");
01707             break;
01708     }
01709 }
01710 
01711 /*
01712  * process_implied_equality
01713  *    Create a restrictinfo item that says "item1 op item2", and push it
01714  *    into the appropriate lists.  (In practice opno is always a btree
01715  *    equality operator.)
01716  *
01717  * "qualscope" is the nominal syntactic level to impute to the restrictinfo.
01718  * This must contain at least all the rels used in the expressions, but it
01719  * is used only to set the qual application level when both exprs are
01720  * variable-free.  Otherwise the qual is applied at the lowest join level
01721  * that provides all its variables.
01722  *
01723  * "nullable_relids" is the set of relids used in the expressions that are
01724  * potentially nullable below the expressions.  (This has to be supplied by
01725  * caller because this function is used after deconstruct_jointree, so we
01726  * don't have knowledge of where the clause items came from.)
01727  *
01728  * "both_const" indicates whether both items are known pseudo-constant;
01729  * in this case it is worth applying eval_const_expressions() in case we
01730  * can produce constant TRUE or constant FALSE.  (Otherwise it's not,
01731  * because the expressions went through eval_const_expressions already.)
01732  *
01733  * Note: this function will copy item1 and item2, but it is caller's
01734  * responsibility to make sure that the Relids parameters are fresh copies
01735  * not shared with other uses.
01736  *
01737  * This is currently used only when an EquivalenceClass is found to
01738  * contain pseudoconstants.  See path/pathkeys.c for more details.
01739  */
01740 void
01741 process_implied_equality(PlannerInfo *root,
01742                          Oid opno,
01743                          Oid collation,
01744                          Expr *item1,
01745                          Expr *item2,
01746                          Relids qualscope,
01747                          Relids nullable_relids,
01748                          bool below_outer_join,
01749                          bool both_const)
01750 {
01751     Expr       *clause;
01752 
01753     /*
01754      * Build the new clause.  Copy to ensure it shares no substructure with
01755      * original (this is necessary in case there are subselects in there...)
01756      */
01757     clause = make_opclause(opno,
01758                            BOOLOID,     /* opresulttype */
01759                            false,       /* opretset */
01760                            (Expr *) copyObject(item1),
01761                            (Expr *) copyObject(item2),
01762                            InvalidOid,
01763                            collation);
01764 
01765     /* If both constant, try to reduce to a boolean constant. */
01766     if (both_const)
01767     {
01768         clause = (Expr *) eval_const_expressions(root, (Node *) clause);
01769 
01770         /* If we produced const TRUE, just drop the clause */
01771         if (clause && IsA(clause, Const))
01772         {
01773             Const      *cclause = (Const *) clause;
01774 
01775             Assert(cclause->consttype == BOOLOID);
01776             if (!cclause->constisnull && DatumGetBool(cclause->constvalue))
01777                 return;
01778         }
01779     }
01780 
01781     /*
01782      * Push the new clause into all the appropriate restrictinfo lists.
01783      */
01784     distribute_qual_to_rels(root, (Node *) clause,
01785                             true, below_outer_join, JOIN_INNER,
01786                             qualscope, NULL, NULL, nullable_relids);
01787 }
01788 
01789 /*
01790  * build_implied_join_equality --- build a RestrictInfo for a derived equality
01791  *
01792  * This overlaps the functionality of process_implied_equality(), but we
01793  * must return the RestrictInfo, not push it into the joininfo tree.
01794  *
01795  * Note: this function will copy item1 and item2, but it is caller's
01796  * responsibility to make sure that the Relids parameters are fresh copies
01797  * not shared with other uses.
01798  *
01799  * Note: we do not do initialize_mergeclause_eclasses() here.  It is
01800  * caller's responsibility that left_ec/right_ec be set as necessary.
01801  */
01802 RestrictInfo *
01803 build_implied_join_equality(Oid opno,
01804                             Oid collation,
01805                             Expr *item1,
01806                             Expr *item2,
01807                             Relids qualscope,
01808                             Relids nullable_relids)
01809 {
01810     RestrictInfo *restrictinfo;
01811     Expr       *clause;
01812 
01813     /*
01814      * Build the new clause.  Copy to ensure it shares no substructure with
01815      * original (this is necessary in case there are subselects in there...)
01816      */
01817     clause = make_opclause(opno,
01818                            BOOLOID,     /* opresulttype */
01819                            false,       /* opretset */
01820                            (Expr *) copyObject(item1),
01821                            (Expr *) copyObject(item2),
01822                            InvalidOid,
01823                            collation);
01824 
01825     /*
01826      * Build the RestrictInfo node itself.
01827      */
01828     restrictinfo = make_restrictinfo(clause,
01829                                      true,      /* is_pushed_down */
01830                                      false,     /* outerjoin_delayed */
01831                                      false,     /* pseudoconstant */
01832                                      qualscope, /* required_relids */
01833                                      NULL,      /* outer_relids */
01834                                      nullable_relids);  /* nullable_relids */
01835 
01836     /* Set mergejoinability/hashjoinability flags */
01837     check_mergejoinable(restrictinfo);
01838     check_hashjoinable(restrictinfo);
01839 
01840     return restrictinfo;
01841 }
01842 
01843 
01844 /*****************************************************************************
01845  *
01846  *   CHECKS FOR MERGEJOINABLE AND HASHJOINABLE CLAUSES
01847  *
01848  *****************************************************************************/
01849 
01850 /*
01851  * check_mergejoinable
01852  *    If the restrictinfo's clause is mergejoinable, set the mergejoin
01853  *    info fields in the restrictinfo.
01854  *
01855  *    Currently, we support mergejoin for binary opclauses where
01856  *    the operator is a mergejoinable operator.  The arguments can be
01857  *    anything --- as long as there are no volatile functions in them.
01858  */
01859 static void
01860 check_mergejoinable(RestrictInfo *restrictinfo)
01861 {
01862     Expr       *clause = restrictinfo->clause;
01863     Oid         opno;
01864     Node       *leftarg;
01865 
01866     if (restrictinfo->pseudoconstant)
01867         return;
01868     if (!is_opclause(clause))
01869         return;
01870     if (list_length(((OpExpr *) clause)->args) != 2)
01871         return;
01872 
01873     opno = ((OpExpr *) clause)->opno;
01874     leftarg = linitial(((OpExpr *) clause)->args);
01875 
01876     if (op_mergejoinable(opno, exprType(leftarg)) &&
01877         !contain_volatile_functions((Node *) clause))
01878         restrictinfo->mergeopfamilies = get_mergejoin_opfamilies(opno);
01879 
01880     /*
01881      * Note: op_mergejoinable is just a hint; if we fail to find the operator
01882      * in any btree opfamilies, mergeopfamilies remains NIL and so the clause
01883      * is not treated as mergejoinable.
01884      */
01885 }
01886 
01887 /*
01888  * check_hashjoinable
01889  *    If the restrictinfo's clause is hashjoinable, set the hashjoin
01890  *    info fields in the restrictinfo.
01891  *
01892  *    Currently, we support hashjoin for binary opclauses where
01893  *    the operator is a hashjoinable operator.  The arguments can be
01894  *    anything --- as long as there are no volatile functions in them.
01895  */
01896 static void
01897 check_hashjoinable(RestrictInfo *restrictinfo)
01898 {
01899     Expr       *clause = restrictinfo->clause;
01900     Oid         opno;
01901     Node       *leftarg;
01902 
01903     if (restrictinfo->pseudoconstant)
01904         return;
01905     if (!is_opclause(clause))
01906         return;
01907     if (list_length(((OpExpr *) clause)->args) != 2)
01908         return;
01909 
01910     opno = ((OpExpr *) clause)->opno;
01911     leftarg = linitial(((OpExpr *) clause)->args);
01912 
01913     if (op_hashjoinable(opno, exprType(leftarg)) &&
01914         !contain_volatile_functions((Node *) clause))
01915         restrictinfo->hashjoinoperator = opno;
01916 }