]> granicus.if.org Git - postgresql/blobdiff - src/backend/optimizer/plan/initsplan.c
Remove planner's private fields from Query struct, and put them into
[postgresql] / src / backend / optimizer / plan / initsplan.c
index afcb4528326b6912073d31732b45fbc858a265fd..c5b027637988da2cf87f702aa38540dc1610dd1d 100644 (file)
@@ -3,12 +3,12 @@
  * initsplan.c
  *       Target list, qualification, joininfo initialization routines
  *
- * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
  * IDENTIFICATION
- *       $Header: /cvsroot/pgsql/src/backend/optimizer/plan/initsplan.c,v 1.88 2003/07/28 00:09:15 tgl Exp $
+ *       $PostgreSQL: pgsql/src/backend/optimizer/plan/initsplan.c,v 1.106 2005/06/05 22:32:55 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -23,6 +23,7 @@
 #include "optimizer/pathnode.h"
 #include "optimizer/paths.h"
 #include "optimizer/planmain.h"
+#include "optimizer/restrictinfo.h"
 #include "optimizer/tlist.h"
 #include "optimizer/var.h"
 #include "parser/parsetree.h"
 #include "utils/syscache.h"
 
 
-static void mark_baserels_for_outer_join(Query *root, Relids rels,
+static void mark_baserels_for_outer_join(PlannerInfo *root, Relids rels,
                                                         Relids outerrels);
-static void distribute_qual_to_rels(Query *root, Node *clause,
-                                                                       bool ispusheddown,
-                                                                       bool isdeduced,
-                                                                       Relids outerjoin_nonnullable,
-                                                                       Relids qualscope);
-static void add_vars_to_targetlist(Query *root, List *vars,
-                                                                  Relids where_needed);
-static bool qual_is_redundant(Query *root, RestrictInfo *restrictinfo,
+static void distribute_qual_to_rels(PlannerInfo *root, Node *clause,
+                                               bool is_pushed_down,
+                                               bool isdeduced,
+                                               Relids outerjoin_nonnullable,
+                                               Relids qualscope);
+static void add_vars_to_targetlist(PlannerInfo *root, List *vars,
+                                          Relids where_needed);
+static bool qual_is_redundant(PlannerInfo *root, RestrictInfo *restrictinfo,
                                  List *restrictlist);
 static void check_mergejoinable(RestrictInfo *restrictinfo);
 static void check_hashjoinable(RestrictInfo *restrictinfo);
@@ -67,7 +68,7 @@ static void check_hashjoinable(RestrictInfo *restrictinfo);
  * will be used later to build rels for inheritance children.
  */
 void
-add_base_rels_to_query(Query *root, Node *jtnode)
+add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
 {
        if (jtnode == NULL)
                return;
@@ -80,12 +81,10 @@ add_base_rels_to_query(Query *root, Node *jtnode)
        else if (IsA(jtnode, FromExpr))
        {
                FromExpr   *f = (FromExpr *) jtnode;
-               List       *l;
+               ListCell   *l;
 
                foreach(l, f->fromlist)
-               {
                        add_base_rels_to_query(root, lfirst(l));
-               }
        }
        else if (IsA(jtnode, JoinExpr))
        {
@@ -93,13 +92,6 @@ add_base_rels_to_query(Query *root, Node *jtnode)
 
                add_base_rels_to_query(root, j->larg);
                add_base_rels_to_query(root, j->rarg);
-               /*
-                * Safety check: join RTEs should not be SELECT FOR UPDATE targets
-                */
-               if (intMember(j->rtindex, root->rowMarks))
-                       ereport(ERROR,
-                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                        errmsg("SELECT FOR UPDATE cannot be applied to a join")));
        }
        else
                elog(ERROR, "unrecognized node type: %d",
@@ -122,14 +114,14 @@ add_base_rels_to_query(Query *root, Node *jtnode)
  * propagate up through all join plan steps.
  */
 void
-build_base_rel_tlists(Query *root, List *final_tlist)
+build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
 {
        List       *tlist_vars = pull_var_clause((Node *) final_tlist, false);
 
        if (tlist_vars != NIL)
        {
                add_vars_to_targetlist(root, tlist_vars, bms_make_singleton(0));
-               freeList(tlist_vars);
+               list_free(tlist_vars);
        }
 }
 
@@ -141,9 +133,9 @@ build_base_rel_tlists(Query *root, List *final_tlist)
  *       where_needed includes "relation 0").
  */
 static void
-add_vars_to_targetlist(Query *root, List *vars, Relids where_needed)
+add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed)
 {
-       List       *temp;
+       ListCell   *temp;
 
        Assert(!bms_is_empty(where_needed));
 
@@ -159,7 +151,7 @@ add_vars_to_targetlist(Query *root, List *vars, Relids where_needed)
                {
                        /* Variable not yet requested, so add to reltargetlist */
                        /* XXX is copyObject necessary here? */
-                       FastAppend(&rel->reltargetlist, copyObject(var));
+                       rel->reltargetlist = lappend(rel->reltargetlist, copyObject(var));
                }
                rel->attr_needed[attrno] = bms_add_members(rel->attr_needed[attrno],
                                                                                                   where_needed);
@@ -197,7 +189,7 @@ add_vars_to_targetlist(Query *root, List *vars, Relids where_needed)
  * internal convenience; no outside callers pay attention to the result.
  */
 Relids
-distribute_quals_to_rels(Query *root, Node *jtnode)
+distribute_quals_to_rels(PlannerInfo *root, Node *jtnode)
 {
        Relids          result = NULL;
 
@@ -213,8 +205,7 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
        else if (IsA(jtnode, FromExpr))
        {
                FromExpr   *f = (FromExpr *) jtnode;
-               List       *l;
-               List       *qual;
+               ListCell   *l;
 
                /*
                 * First, recurse to handle child joins.
@@ -230,8 +221,8 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
                 * Now process the top-level quals.  These are always marked as
                 * "pushed down", since they clearly didn't come from a JOIN expr.
                 */
-               foreach(qual, (List *) f->quals)
-                       distribute_qual_to_rels(root, (Node *) lfirst(qual),
+               foreach(l, (List *) f->quals)
+                       distribute_qual_to_rels(root, (Node *) lfirst(l),
                                                                        true, false, NULL, result);
        }
        else if (IsA(jtnode, JoinExpr))
@@ -241,20 +232,20 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
                                        rightids,
                                        nonnullable_rels,
                                        nullable_rels;
-               List       *qual;
+               ListCell   *qual;
 
                /*
                 * Order of operations here is subtle and critical.  First we
                 * recurse to handle sub-JOINs.  Their join quals will be placed
                 * without regard for whether this level is an outer join, which
-                * is correct.  Then we place our own join quals, which are restricted
-                * by lower outer joins in any case, and are forced to this level if
-                * this is an outer join and they mention the outer side.  Finally, if
-                * this is an outer join, we mark baserels contained within the inner
-                * side(s) with our own rel set; this will prevent quals above us in
-                * the join tree that use those rels from being pushed down below this
-                * level.  (It's okay for upper quals to be pushed down to the outer
-                * side, however.)
+                * is correct.  Then we place our own join quals, which are
+                * restricted by lower outer joins in any case, and are forced to
+                * this level if this is an outer join and they mention the outer
+                * side.  Finally, if this is an outer join, we mark baserels
+                * contained within the inner side(s) with our own rel set; this
+                * will prevent quals above us in the join tree that use those
+                * rels from being pushed down below this level.  (It's okay for
+                * upper quals to be pushed down to the outer side, however.)
                 */
                leftids = distribute_quals_to_rels(root, j->larg);
                rightids = distribute_quals_to_rels(root, j->rarg);
@@ -288,7 +279,7 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
                                 */
                                ereport(ERROR,
                                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                                errmsg("UNION JOIN is not implemented yet")));
+                                                errmsg("UNION JOIN is not implemented")));
                                break;
                        default:
                                elog(ERROR, "unrecognized join type: %d",
@@ -315,7 +306,7 @@ distribute_quals_to_rels(Query *root, Node *jtnode)
  *       Mark all base rels listed in 'rels' as having the given outerjoinset.
  */
 static void
-mark_baserels_for_outer_join(Query *root, Relids rels, Relids outerrels)
+mark_baserels_for_outer_join(PlannerInfo *root, Relids rels, Relids outerrels)
 {
        Relids          tmprelids;
        int                     relno;
@@ -332,20 +323,20 @@ mark_baserels_for_outer_join(Query *root, Relids rels, Relids outerrels)
                Assert(bms_is_subset(rel->outerjoinset, outerrels));
 
                /*
-                * Presently the executor cannot support FOR UPDATE marking of
+                * Presently the executor cannot support FOR UPDATE/SHARE marking of
                 * rels appearing on the nullable side of an outer join. (It's
                 * somewhat unclear what that would mean, anyway: what should we
                 * mark when a result row is generated from no element of the
-                * nullable relation?)  So, complain if target rel is FOR UPDATE.
+                * nullable relation?)  So, complain if target rel is FOR UPDATE/SHARE.
                 * It's sufficient to make this check once per rel, so do it only
                 * if rel wasn't already known nullable.
                 */
                if (rel->outerjoinset == NULL)
                {
-                       if (intMember(relno, root->rowMarks))
+                       if (list_member_int(root->parse->rowMarks, relno))
                                ereport(ERROR,
                                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                                errmsg("SELECT FOR UPDATE cannot be applied to the nullable side of an OUTER JOIN")));
+                                                errmsg("SELECT FOR UPDATE/SHARE cannot be applied to the nullable side of an outer join")));
                }
 
                rel->outerjoinset = outerrels;
@@ -364,7 +355,7 @@ mark_baserels_for_outer_join(Query *root, Relids rels, Relids outerrels)
  *       equijoined vars.
  *
  * 'clause': the qual clause to be distributed
- * 'ispusheddown': if TRUE, force the clause to be marked 'ispusheddown'
+ * 'is_pushed_down': if TRUE, force the clause to be marked 'is_pushed_down'
  *             (this indicates the clause came from a FromExpr, not a JoinExpr)
  * 'isdeduced': TRUE if the qual came from implied-equality deduction
  * 'outerjoin_nonnullable': NULL if not an outer-join qual, else the set of
@@ -373,43 +364,26 @@ mark_baserels_for_outer_join(Query *root, Relids rels, Relids outerrels)
  *
  * 'qualscope' identifies what level of JOIN the qual came from.  For a top
  * level qual (WHERE qual), qualscope lists all baserel ids and in addition
- * 'ispusheddown' will be TRUE.
+ * 'is_pushed_down' will be TRUE.
  */
 static void
-distribute_qual_to_rels(Query *root, Node *clause,
-                                               bool ispusheddown,
+distribute_qual_to_rels(PlannerInfo *root, Node *clause,
+                                               bool is_pushed_down,
                                                bool isdeduced,
                                                Relids outerjoin_nonnullable,
                                                Relids qualscope)
 {
-       RestrictInfo *restrictinfo = makeNode(RestrictInfo);
-       RelOptInfo *rel;
        Relids          relids;
-       List       *vars;
+       bool            valid_everywhere;
        bool            can_be_equijoin;
-
-       restrictinfo->clause = (Expr *) clause;
-       restrictinfo->subclauseindices = NIL;
-       restrictinfo->eval_cost.startup = -1; /* not computed until needed */
-       restrictinfo->this_selec = -1;          /* not computed until needed */
-       restrictinfo->left_relids = NULL; /* set below, if join clause */
-       restrictinfo->right_relids = NULL;
-       restrictinfo->mergejoinoperator = InvalidOid;
-       restrictinfo->left_sortop = InvalidOid;
-       restrictinfo->right_sortop = InvalidOid;
-       restrictinfo->left_pathkey = NIL;       /* not computable yet */
-       restrictinfo->right_pathkey = NIL;
-       restrictinfo->left_mergescansel = -1;           /* not computed until
-                                                                                                * needed */
-       restrictinfo->right_mergescansel = -1;
-       restrictinfo->hashjoinoperator = InvalidOid;
-       restrictinfo->left_bucketsize = -1; /* not computed until needed */
-       restrictinfo->right_bucketsize = -1;
+       RestrictInfo *restrictinfo;
+       RelOptInfo *rel;
+       List       *vars;
 
        /*
-        * Retrieve all relids and vars contained within the clause.
+        * Retrieve all relids mentioned within the clause.
         */
-       clause_get_relids_vars(clause, &relids, &vars);
+       relids = pull_varnos(clause);
 
        /*
         * Cross-check: clause should contain no relids not within its scope.
@@ -435,54 +409,67 @@ distribute_qual_to_rels(Query *root, Node *clause,
        if (isdeduced)
        {
                /*
-                * If the qual came from implied-equality deduction, we can evaluate
-                * the qual at its natural semantic level.  It is not affected by
-                * any outer-join rules (else we'd not have decided the vars were
-                * equal).
+                * If the qual came from implied-equality deduction, we can
+                * evaluate the qual at its natural semantic level.  It is not
+                * affected by any outer-join rules (else we'd not have decided
+                * the vars were equal).
                 */
                Assert(bms_equal(relids, qualscope));
+               valid_everywhere = true;
                can_be_equijoin = true;
        }
        else if (bms_overlap(relids, outerjoin_nonnullable))
        {
                /*
-                * The qual is attached to an outer join and mentions (some of the)
-                * rels on the nonnullable side.  Force the qual to be evaluated
-                * exactly at the level of joining corresponding to the outer join.
-                * We cannot let it get pushed down into the nonnullable side, since
-                * then we'd produce no output rows, rather than the intended single
-                * null-extended row, for any nonnullable-side rows failing the qual.
+                * The qual is attached to an outer join and mentions (some of
+                * the) rels on the nonnullable side.  Force the qual to be
+                * evaluated exactly at the level of joining corresponding to the
+                * outer join. We cannot let it get pushed down into the
+                * nonnullable side, since then we'd produce no output rows,
+                * rather than the intended single null-extended row, for any
+                * nonnullable-side rows failing the qual.
                 *
                 * Note: an outer-join qual that mentions only nullable-side rels can
                 * be pushed down into the nullable side without changing the join
                 * result, so we treat it the same as an ordinary inner-join qual.
                 */
                relids = qualscope;
+               valid_everywhere = false;
                can_be_equijoin = false;
        }
        else
        {
                /*
                 * For a non-outer-join qual, we can evaluate the qual as soon as
-                * (1) we have all the rels it mentions, and (2) we are at or above
-                * any outer joins that can null any of these rels and are below the
-                * syntactic location of the given qual. To enforce the latter, scan
-                * the base rels listed in relids, and merge their outer-join sets
-                * into the clause's own reference list.  At the time we are called,
-                * the outerjoinset of each baserel will show exactly those outer
-                * joins that are below the qual in the join tree.
+                * (1) we have all the rels it mentions, and (2) we are at or
+                * above any outer joins that can null any of these rels and are
+                * below the syntactic location of the given qual. To enforce the
+                * latter, scan the base rels listed in relids, and merge their
+                * outer-join sets into the clause's own reference list.  At the
+                * time we are called, the outerjoinset of each baserel will show
+                * exactly those outer joins that are below the qual in the join
+                * tree.
+                *
+                * We also need to determine whether the qual is "valid everywhere",
+                * which is true if the qual mentions no variables that are
+                * involved in lower-level outer joins (this may be an overly
+                * strong test).
                 */
                Relids          addrelids = NULL;
                Relids          tmprelids;
                int                     relno;
 
+               valid_everywhere = true;
                tmprelids = bms_copy(relids);
                while ((relno = bms_first_member(tmprelids)) >= 0)
                {
                        RelOptInfo *rel = find_base_rel(root, relno);
 
                        if (rel->outerjoinset != NULL)
+                       {
                                addrelids = bms_add_members(addrelids, rel->outerjoinset);
+                               valid_everywhere = false;
+                       }
                }
                bms_free(tmprelids);
 
@@ -496,9 +483,10 @@ distribute_qual_to_rels(Query *root, Node *clause,
                        relids = bms_union(relids, addrelids);
                        /* Should still be a subset of current scope ... */
                        Assert(bms_is_subset(relids, qualscope));
+
                        /*
-                        * Because application of the qual will be delayed by outer join,
-                        * we mustn't assume its vars are equal everywhere.
+                        * Because application of the qual will be delayed by outer
+                        * join, we mustn't assume its vars are equal everywhere.
                         */
                        can_be_equijoin = false;
                }
@@ -512,12 +500,23 @@ distribute_qual_to_rels(Query *root, Node *clause,
         * same joinrel. A qual originating from WHERE is always considered
         * "pushed down".
         */
-       restrictinfo->ispusheddown = ispusheddown || !bms_equal(relids,
-                                                                                                                       qualscope);
+       if (!is_pushed_down)
+               is_pushed_down = !bms_equal(relids, qualscope);
+
+       /*
+        * Build the RestrictInfo node itself.
+        */
+       restrictinfo = make_restrictinfo((Expr *) clause,
+                                                                        is_pushed_down,
+                                                                        valid_everywhere);
 
+       /*
+        * Figure out where to attach it.
+        */
        switch (bms_membership(relids))
        {
                case BMS_SINGLETON:
+
                        /*
                         * There is only one relation participating in 'clause', so
                         * 'clause' is a restriction clause for that relation.
@@ -525,28 +524,30 @@ distribute_qual_to_rels(Query *root, Node *clause,
                        rel = find_base_rel(root, bms_singleton_member(relids));
 
                        /*
-                        * Check for a "mergejoinable" clause even though it's not a join
-                        * clause.      This is so that we can recognize that "a.x = a.y"
-                        * makes x and y eligible to be considered equal, even when they
-                        * belong to the same rel.      Without this, we would not recognize
-                        * that "a.x = a.y AND a.x = b.z AND a.y = c.q" allows us to
-                        * consider z and q equal after their rels are joined.
+                        * Check for a "mergejoinable" clause even though it's not a
+                        * join clause.  This is so that we can recognize that "a.x =
+                        * a.y" makes x and y eligible to be considered equal, even
+                        * when they belong to the same rel.  Without this, we would
+                        * not recognize that "a.x = a.y AND a.x = b.z AND a.y = c.q"
+                        * allows us to consider z and q equal after their rels are
+                        * joined.
                         */
                        if (can_be_equijoin)
                                check_mergejoinable(restrictinfo);
 
                        /*
-                        * If the clause was deduced from implied equality, check to see
-                        * whether it is redundant with restriction clauses we already
-                        * have for this rel.  Note we cannot apply this check to
-                        * user-written clauses, since we haven't found the canonical
-                        * pathkey sets yet while processing user clauses.      (NB: no
-                        * comparable check is done in the join-clause case; redundancy
-                        * will be detected when the join clause is moved into a join
-                        * rel's restriction list.)
+                        * If the clause was deduced from implied equality, check to
+                        * see whether it is redundant with restriction clauses we
+                        * already have for this rel.  Note we cannot apply this check
+                        * to user-written clauses, since we haven't found the
+                        * canonical pathkey sets yet while processing user clauses.
+                        * (NB: no comparable check is done in the join-clause case;
+                        * redundancy will be detected when the join clause is moved
+                        * into a join rel's restriction list.)
                         */
                        if (!isdeduced ||
-                               !qual_is_redundant(root, restrictinfo, rel->baserestrictinfo))
+                               !qual_is_redundant(root, restrictinfo,
+                                                                  rel->baserestrictinfo))
                        {
                                /* Add clause to rel's restriction list */
                                rel->baserestrictinfo = lappend(rel->baserestrictinfo,
@@ -554,37 +555,19 @@ distribute_qual_to_rels(Query *root, Node *clause,
                        }
                        break;
                case BMS_MULTIPLE:
+
                        /*
-                        * 'clause' is a join clause, since there is more than one rel in
-                        * the relid set.       Set additional RestrictInfo fields for
-                        * joining.  First, does it look like a normal join clause, i.e.,
-                        * a binary operator relating expressions that come from distinct
-                        * relations?  If so we might be able to use it in a join
-                        * algorithm.
+                        * 'clause' is a join clause, since there is more than one rel
+                        * in the relid set.
                         */
-                       if (is_opclause(clause) && length(((OpExpr *) clause)->args) == 2)
-                       {
-                               Relids          left_relids;
-                               Relids          right_relids;
-
-                               left_relids = pull_varnos(get_leftop((Expr *) clause));
-                               right_relids = pull_varnos(get_rightop((Expr *) clause));
-                               if (!bms_is_empty(left_relids) &&
-                                       !bms_is_empty(right_relids) &&
-                                       !bms_overlap(left_relids, right_relids))
-                               {
-                                       restrictinfo->left_relids = left_relids;
-                                       restrictinfo->right_relids = right_relids;
-                               }
-                       }
 
                        /*
-                        * Now check for hash or mergejoinable operators.
+                        * Check for hash or mergejoinable operators.
                         *
                         * We don't bother setting the hashjoin info if we're not going
-                        * to need it.  We do want to know about mergejoinable ops in all
-                        * cases, however, because we use mergejoinable ops for other
-                        * purposes such as detecting redundant clauses.
+                        * to need it.  We do want to know about mergejoinable ops in
+                        * all cases, however, because we use mergejoinable ops for
+                        * other purposes such as detecting redundant clauses.
                         */
                        check_mergejoinable(restrictinfo);
                        if (enable_hashjoin)
@@ -597,16 +580,20 @@ distribute_qual_to_rels(Query *root, Node *clause,
 
                        /*
                         * Add vars used in the join clause to targetlists of their
-                        * relations, so that they will be emitted by the plan nodes that
-                        * scan those relations (else they won't be available at the join
-                        * node!).
+                        * relations, so that they will be emitted by the plan nodes
+                        * that scan those relations (else they won't be available at
+                        * the join node!).
                         */
+                       vars = pull_var_clause(clause, false);
                        add_vars_to_targetlist(root, vars, relids);
+                       list_free(vars);
                        break;
                default:
+
                        /*
-                        * 'clause' references no rels, and therefore we have no place to
-                        * attach it.  Shouldn't get here if callers are working properly.
+                        * 'clause' references no rels, and therefore we have no place
+                        * to attach it.  Shouldn't get here if callers are working
+                        * properly.
                         */
                        elog(ERROR, "cannot cope with variable-free clause");
                        break;
@@ -621,7 +608,8 @@ distribute_qual_to_rels(Query *root, Node *clause,
         * equivalence for future use.  (We can skip this for a deduced
         * clause, since the keys are already known equivalent in that case.)
         */
-       if (can_be_equijoin && restrictinfo->mergejoinoperator != InvalidOid &&
+       if (can_be_equijoin &&
+               restrictinfo->mergejoinoperator != InvalidOid &&
                !isdeduced)
                add_equijoined_keys(root, restrictinfo);
 }
@@ -634,11 +622,11 @@ distribute_qual_to_rels(Query *root, Node *clause,
  *
  * This processing is a consequence of transitivity of mergejoin equality:
  * if we have mergejoinable clauses A = B and B = C, we can deduce A = C
- * (where = is an appropriate mergejoinable operator).  See path/pathkeys.c
+ * (where = is an appropriate mergejoinable operator). See path/pathkeys.c
  * for more details.
  */
 void
-process_implied_equality(Query *root,
+process_implied_equality(PlannerInfo *root,
                                                 Node *item1, Node *item2,
                                                 Oid sortop1, Oid sortop2,
                                                 Relids item1_relids, Relids item2_relids,
@@ -648,7 +636,7 @@ process_implied_equality(Query *root,
        BMS_Membership membership;
        RelOptInfo *rel1;
        List       *restrictlist;
-       List       *itm;
+       ListCell   *itm;
        Oid                     ltype,
                                rtype;
        Operator        eq_operator;
@@ -695,8 +683,8 @@ process_implied_equality(Query *root,
        }
 
        /*
-        * Scan to see if equality is already known.  If so, we're done in
-        * the add case, and done after removing it in the delete case.
+        * Scan to see if equality is already known.  If so, we're done in the
+        * add case, and done after removing it in the delete case.
         */
        foreach(itm, restrictlist)
        {
@@ -718,8 +706,8 @@ process_implied_equality(Query *root,
                                if (membership == BMS_SINGLETON)
                                {
                                        /* delete it from local restrictinfo list */
-                                       rel1->baserestrictinfo = lremove(restrictinfo,
-                                                                                                        rel1->baserestrictinfo);
+                                       rel1->baserestrictinfo = list_delete_ptr(rel1->baserestrictinfo,
+                                                                                                                  restrictinfo);
                                }
                                else
                                {
@@ -741,7 +729,7 @@ process_implied_equality(Query *root,
         */
        ltype = exprType(item1);
        rtype = exprType(item2);
-       eq_operator = compatible_oper(makeList1(makeString("=")),
+       eq_operator = compatible_oper(list_make1(makeString("=")),
                                                                  ltype, rtype, true);
        if (!HeapTupleIsValid(eq_operator))
        {
@@ -765,14 +753,19 @@ process_implied_equality(Query *root,
                pgopform->oprresult != BOOLOID)
                ereport(ERROR,
                                (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
-                                errmsg("equality operator for types %s and %s should be mergejoinable, but isn't",
+                                errmsg("equality operator for types %s and %s should be merge-joinable, but isn't",
                                                format_type_be(ltype), format_type_be(rtype))));
 
-       clause = make_opclause(oprid(eq_operator), /* opno */
-                                                  BOOLOID,     /* opresulttype */
-                                                  false, /* opretset */
-                                                  (Expr *) item1,
-                                                  (Expr *) item2);
+       /*
+        * Now we can build the new clause.  Copy to ensure it shares no
+        * substructure with original (this is necessary in case there are
+        * subselects in there...)
+        */
+       clause = make_opclause(oprid(eq_operator),      /* opno */
+                                                  BOOLOID,             /* opresulttype */
+                                                  false,               /* opretset */
+                                                  (Expr *) copyObject(item1),
+                                                  (Expr *) copyObject(item2));
 
        ReleaseSysCache(eq_operator);
 
@@ -797,30 +790,31 @@ process_implied_equality(Query *root,
  *       too-small selectivity, not to mention wasting time at execution.
  *
  * Note: quals of the form "var = const" are never considered redundant,
- * only those of the form "var = var".  This is needed because when we
+ * only those of the form "var = var". This is needed because when we
  * have constants in an implied-equality set, we use a different strategy
- * that suppresses all "var = var" deductions.  We must therefore keep
+ * that suppresses all "var = var" deductions. We must therefore keep
  * all the "var = const" quals.
  */
 static bool
-qual_is_redundant(Query *root,
+qual_is_redundant(PlannerInfo *root,
                                  RestrictInfo *restrictinfo,
                                  List *restrictlist)
 {
        Node       *newleft;
        Node       *newright;
        List       *oldquals;
-       List       *olditem;
+       ListCell   *olditem;
        List       *equalexprs;
        bool            someadded;
 
-       newleft = get_leftop(restrictinfo->clause);
-       newright = get_rightop(restrictinfo->clause);
-
        /* Never redundant unless vars appear on both sides */
-       if (!contain_var_clause(newleft) || !contain_var_clause(newright))
+       if (bms_is_empty(restrictinfo->left_relids) ||
+               bms_is_empty(restrictinfo->right_relids))
                return false;
 
+       newleft = get_leftop(restrictinfo->clause);
+       newright = get_rightop(restrictinfo->clause);
+
        /*
         * Set cached pathkeys.  NB: it is okay to do this now because this
         * routine is only invoked while we are generating implied equalities.
@@ -858,14 +852,15 @@ qual_is_redundant(Query *root,
         * left side of the new qual.  We traverse the old-quals list
         * repeatedly to transitively expand the exprs list.  If at any point
         * we find we can reach the right-side expr of the new qual, we are
-        * done.  We give up when we can't expand the equalexprs list any more.
+        * done.  We give up when we can't expand the equalexprs list any
+        * more.
         */
-       equalexprs = makeList1(newleft);
+       equalexprs = list_make1(newleft);
        do
        {
                someadded = false;
-               /* cannot use foreach here because of possible lremove */
-               olditem = oldquals;
+               /* cannot use foreach here because of possible list_delete */
+               olditem = list_head(oldquals);
                while (olditem)
                {
                        RestrictInfo *oldrinfo = (RestrictInfo *) lfirst(olditem);
@@ -873,12 +868,12 @@ qual_is_redundant(Query *root,
                        Node       *oldright = get_rightop(oldrinfo->clause);
                        Node       *newguy = NULL;
 
-                       /* must advance olditem before lremove possibly pfree's it */
+                       /* must advance olditem before list_delete possibly pfree's it */
                        olditem = lnext(olditem);
 
-                       if (member(oldleft, equalexprs))
+                       if (list_member(equalexprs, oldleft))
                                newguy = oldright;
-                       else if (member(oldright, equalexprs))
+                       else if (list_member(equalexprs, oldright))
                                newguy = oldleft;
                        else
                                continue;
@@ -890,7 +885,7 @@ qual_is_redundant(Query *root,
                        /*
                         * Remove this qual from list, since we don't need it anymore.
                         */
-                       oldquals = lremove(oldrinfo, oldquals);
+                       oldquals = list_delete_ptr(oldquals, oldrinfo);
                }
        } while (someadded);
 
@@ -923,7 +918,7 @@ check_mergejoinable(RestrictInfo *restrictinfo)
 
        if (!is_opclause(clause))
                return;
-       if (length(((OpExpr *) clause)->args) != 2)
+       if (list_length(((OpExpr *) clause)->args) != 2)
                return;
 
        opno = ((OpExpr *) clause)->opno;
@@ -945,7 +940,7 @@ check_mergejoinable(RestrictInfo *restrictinfo)
  *       info fields in the restrictinfo.
  *
  *       Currently, we support hashjoin for binary opclauses where
- *       the operator is a hashjoinable operator.  The arguments can be
+ *       the operator is a hashjoinable operator.      The arguments can be
  *       anything --- as long as there are no volatile functions in them.
  */
 static void
@@ -956,7 +951,7 @@ check_hashjoinable(RestrictInfo *restrictinfo)
 
        if (!is_opclause(clause))
                return;
-       if (length(((OpExpr *) clause)->args) != 2)
+       if (list_length(((OpExpr *) clause)->args) != 2)
                return;
 
        opno = ((OpExpr *) clause)->opno;