]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/equivclass.c
Remove unnecessary #include references, per pgrminclude script.
[postgresql] / src / backend / optimizer / path / equivclass.c
1 /*-------------------------------------------------------------------------
2  *
3  * equivclass.c
4  *        Routines for managing EquivalenceClasses
5  *
6  * See src/backend/optimizer/README for discussion of EquivalenceClasses.
7  *
8  *
9  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  * IDENTIFICATION
13  *        src/backend/optimizer/path/equivclass.c
14  *
15  *-------------------------------------------------------------------------
16  */
17 #include "postgres.h"
18
19 #include "access/skey.h"
20 #include "catalog/pg_type.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/clauses.h"
24 #include "optimizer/paths.h"
25 #include "optimizer/planmain.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/var.h"
28 #include "utils/lsyscache.h"
29
30
31 static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
32                           Expr *expr, Relids relids,
33                           bool is_child, Oid datatype);
34 static void generate_base_implied_equalities_const(PlannerInfo *root,
35                                                                            EquivalenceClass *ec);
36 static void generate_base_implied_equalities_no_const(PlannerInfo *root,
37                                                                                   EquivalenceClass *ec);
38 static void generate_base_implied_equalities_broken(PlannerInfo *root,
39                                                                                 EquivalenceClass *ec);
40 static List *generate_join_implied_equalities_normal(PlannerInfo *root,
41                                                                                 EquivalenceClass *ec,
42                                                                                 RelOptInfo *joinrel,
43                                                                                 RelOptInfo *outer_rel,
44                                                                                 RelOptInfo *inner_rel);
45 static List *generate_join_implied_equalities_broken(PlannerInfo *root,
46                                                                                 EquivalenceClass *ec,
47                                                                                 RelOptInfo *joinrel,
48                                                                                 RelOptInfo *outer_rel,
49                                                                                 RelOptInfo *inner_rel);
50 static Oid select_equality_operator(EquivalenceClass *ec,
51                                                  Oid lefttype, Oid righttype);
52 static RestrictInfo *create_join_clause(PlannerInfo *root,
53                                    EquivalenceClass *ec, Oid opno,
54                                    EquivalenceMember *leftem,
55                                    EquivalenceMember *rightem,
56                                    EquivalenceClass *parent_ec);
57 static bool reconsider_outer_join_clause(PlannerInfo *root,
58                                                          RestrictInfo *rinfo,
59                                                          bool outer_on_left);
60 static bool reconsider_full_join_clause(PlannerInfo *root,
61                                                         RestrictInfo *rinfo);
62
63
64 /*
65  * process_equivalence
66  *        The given clause has a mergejoinable operator and can be applied without
67  *        any delay by an outer join, so its two sides can be considered equal
68  *        anywhere they are both computable; moreover that equality can be
69  *        extended transitively.  Record this knowledge in the EquivalenceClass
70  *        data structure.  Returns TRUE if successful, FALSE if not (in which
71  *        case caller should treat the clause as ordinary, not an equivalence).
72  *
73  * If below_outer_join is true, then the clause was found below the nullable
74  * side of an outer join, so its sides might validly be both NULL rather than
75  * strictly equal.      We can still deduce equalities in such cases, but we take
76  * care to mark an EquivalenceClass if it came from any such clauses.  Also,
77  * we have to check that both sides are either pseudo-constants or strict
78  * functions of Vars, else they might not both go to NULL above the outer
79  * join.  (This is the reason why we need a failure return.  It's more
80  * convenient to check this case here than at the call sites...)
81  *
82  * On success return, we have also initialized the clause's left_ec/right_ec
83  * fields to point to the EquivalenceClass representing it.  This saves lookup
84  * effort later.
85  *
86  * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
87  * problem, for which there exist better data structures than simple lists.
88  * If this code ever proves to be a bottleneck then it could be sped up ---
89  * but for now, simple is beautiful.
90  *
91  * Note: this is only called during planner startup, not during GEQO
92  * exploration, so we need not worry about whether we're in the right
93  * memory context.
94  */
95 bool
96 process_equivalence(PlannerInfo *root, RestrictInfo *restrictinfo,
97                                         bool below_outer_join)
98 {
99         Expr       *clause = restrictinfo->clause;
100         Oid                     opno,
101                                 collation,
102                                 item1_type,
103                                 item2_type;
104         Expr       *item1;
105         Expr       *item2;
106         Relids          item1_relids,
107                                 item2_relids;
108         List       *opfamilies;
109         EquivalenceClass *ec1,
110                            *ec2;
111         EquivalenceMember *em1,
112                            *em2;
113         ListCell   *lc1;
114
115         /* Should not already be marked as having generated an eclass */
116         Assert(restrictinfo->left_ec == NULL);
117         Assert(restrictinfo->right_ec == NULL);
118
119         /* Extract info from given clause */
120         Assert(is_opclause(clause));
121         opno = ((OpExpr *) clause)->opno;
122         collation = ((OpExpr *) clause)->inputcollid;
123         item1 = (Expr *) get_leftop(clause);
124         item2 = (Expr *) get_rightop(clause);
125         item1_relids = restrictinfo->left_relids;
126         item2_relids = restrictinfo->right_relids;
127
128         /*
129          * Ensure both input expressions expose the desired collation (their types
130          * should be OK already); see comments for canonicalize_ec_expression.
131          */
132         item1 = canonicalize_ec_expression(item1,
133                                                                            exprType((Node *) item1),
134                                                                            collation);
135         item2 = canonicalize_ec_expression(item2,
136                                                                            exprType((Node *) item2),
137                                                                            collation);
138
139         /*
140          * Reject clauses of the form X=X.      These are not as redundant as they
141          * might seem at first glance: assuming the operator is strict, this is
142          * really an expensive way to write X IS NOT NULL.      So we must not risk
143          * just losing the clause, which would be possible if there is already a
144          * single-element EquivalenceClass containing X.  The case is not common
145          * enough to be worth contorting the EC machinery for, so just reject the
146          * clause and let it be processed as a normal restriction clause.
147          */
148         if (equal(item1, item2))
149                 return false;                   /* X=X is not a useful equivalence */
150
151         /*
152          * If below outer join, check for strictness, else reject.
153          */
154         if (below_outer_join)
155         {
156                 if (!bms_is_empty(item1_relids) &&
157                         contain_nonstrict_functions((Node *) item1))
158                         return false;           /* LHS is non-strict but not constant */
159                 if (!bms_is_empty(item2_relids) &&
160                         contain_nonstrict_functions((Node *) item2))
161                         return false;           /* RHS is non-strict but not constant */
162         }
163
164         /*
165          * We use the declared input types of the operator, not exprType() of the
166          * inputs, as the nominal datatypes for opfamily lookup.  This presumes
167          * that btree operators are always registered with amoplefttype and
168          * amoprighttype equal to their declared input types.  We will need this
169          * info anyway to build EquivalenceMember nodes, and by extracting it now
170          * we can use type comparisons to short-circuit some equal() tests.
171          */
172         op_input_types(opno, &item1_type, &item2_type);
173
174         opfamilies = restrictinfo->mergeopfamilies;
175
176         /*
177          * Sweep through the existing EquivalenceClasses looking for matches to
178          * item1 and item2.  These are the possible outcomes:
179          *
180          * 1. We find both in the same EC.      The equivalence is already known, so
181          * there's nothing to do.
182          *
183          * 2. We find both in different ECs.  Merge the two ECs together.
184          *
185          * 3. We find just one.  Add the other to its EC.
186          *
187          * 4. We find neither.  Make a new, two-entry EC.
188          *
189          * Note: since all ECs are built through this process or the similar
190          * search in get_eclass_for_sort_expr(), it's impossible that we'd match
191          * an item in more than one existing nonvolatile EC.  So it's okay to stop
192          * at the first match.
193          */
194         ec1 = ec2 = NULL;
195         em1 = em2 = NULL;
196         foreach(lc1, root->eq_classes)
197         {
198                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
199                 ListCell   *lc2;
200
201                 /* Never match to a volatile EC */
202                 if (cur_ec->ec_has_volatile)
203                         continue;
204
205                 /*
206                  * The collation has to match; check this first since it's cheaper
207                  * than the opfamily comparison.
208                  */
209                 if (collation != cur_ec->ec_collation)
210                         continue;
211
212                 /*
213                  * A "match" requires matching sets of btree opfamilies.  Use of
214                  * equal() for this test has implications discussed in the comments
215                  * for get_mergejoin_opfamilies().
216                  */
217                 if (!equal(opfamilies, cur_ec->ec_opfamilies))
218                         continue;
219
220                 foreach(lc2, cur_ec->ec_members)
221                 {
222                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
223
224                         Assert(!cur_em->em_is_child);           /* no children yet */
225
226                         /*
227                          * If below an outer join, don't match constants: they're not as
228                          * constant as they look.
229                          */
230                         if ((below_outer_join || cur_ec->ec_below_outer_join) &&
231                                 cur_em->em_is_const)
232                                 continue;
233
234                         if (!ec1 &&
235                                 item1_type == cur_em->em_datatype &&
236                                 equal(item1, cur_em->em_expr))
237                         {
238                                 ec1 = cur_ec;
239                                 em1 = cur_em;
240                                 if (ec2)
241                                         break;
242                         }
243
244                         if (!ec2 &&
245                                 item2_type == cur_em->em_datatype &&
246                                 equal(item2, cur_em->em_expr))
247                         {
248                                 ec2 = cur_ec;
249                                 em2 = cur_em;
250                                 if (ec1)
251                                         break;
252                         }
253                 }
254
255                 if (ec1 && ec2)
256                         break;
257         }
258
259         /* Sweep finished, what did we find? */
260
261         if (ec1 && ec2)
262         {
263                 /* If case 1, nothing to do, except add to sources */
264                 if (ec1 == ec2)
265                 {
266                         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
267                         ec1->ec_below_outer_join |= below_outer_join;
268                         /* mark the RI as associated with this eclass */
269                         restrictinfo->left_ec = ec1;
270                         restrictinfo->right_ec = ec1;
271                         /* mark the RI as usable with this pair of EMs */
272                         restrictinfo->left_em = em1;
273                         restrictinfo->right_em = em2;
274                         return true;
275                 }
276
277                 /*
278                  * Case 2: need to merge ec1 and ec2.  We add ec2's items to ec1, then
279                  * set ec2's ec_merged link to point to ec1 and remove ec2 from the
280                  * eq_classes list.  We cannot simply delete ec2 because that could
281                  * leave dangling pointers in existing PathKeys.  We leave it behind
282                  * with a link so that the merged EC can be found.
283                  */
284                 ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
285                 ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
286                 ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
287                 ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
288                 ec1->ec_has_const |= ec2->ec_has_const;
289                 /* can't need to set has_volatile */
290                 ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
291                 ec2->ec_merged = ec1;
292                 root->eq_classes = list_delete_ptr(root->eq_classes, ec2);
293                 /* just to avoid debugging confusion w/ dangling pointers: */
294                 ec2->ec_members = NIL;
295                 ec2->ec_sources = NIL;
296                 ec2->ec_derives = NIL;
297                 ec2->ec_relids = NULL;
298                 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
299                 ec1->ec_below_outer_join |= below_outer_join;
300                 /* mark the RI as associated with this eclass */
301                 restrictinfo->left_ec = ec1;
302                 restrictinfo->right_ec = ec1;
303                 /* mark the RI as usable with this pair of EMs */
304                 restrictinfo->left_em = em1;
305                 restrictinfo->right_em = em2;
306         }
307         else if (ec1)
308         {
309                 /* Case 3: add item2 to ec1 */
310                 em2 = add_eq_member(ec1, item2, item2_relids, false, item2_type);
311                 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
312                 ec1->ec_below_outer_join |= below_outer_join;
313                 /* mark the RI as associated with this eclass */
314                 restrictinfo->left_ec = ec1;
315                 restrictinfo->right_ec = ec1;
316                 /* mark the RI as usable with this pair of EMs */
317                 restrictinfo->left_em = em1;
318                 restrictinfo->right_em = em2;
319         }
320         else if (ec2)
321         {
322                 /* Case 3: add item1 to ec2 */
323                 em1 = add_eq_member(ec2, item1, item1_relids, false, item1_type);
324                 ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
325                 ec2->ec_below_outer_join |= below_outer_join;
326                 /* mark the RI as associated with this eclass */
327                 restrictinfo->left_ec = ec2;
328                 restrictinfo->right_ec = ec2;
329                 /* mark the RI as usable with this pair of EMs */
330                 restrictinfo->left_em = em1;
331                 restrictinfo->right_em = em2;
332         }
333         else
334         {
335                 /* Case 4: make a new, two-entry EC */
336                 EquivalenceClass *ec = makeNode(EquivalenceClass);
337
338                 ec->ec_opfamilies = opfamilies;
339                 ec->ec_collation = collation;
340                 ec->ec_members = NIL;
341                 ec->ec_sources = list_make1(restrictinfo);
342                 ec->ec_derives = NIL;
343                 ec->ec_relids = NULL;
344                 ec->ec_has_const = false;
345                 ec->ec_has_volatile = false;
346                 ec->ec_below_outer_join = below_outer_join;
347                 ec->ec_broken = false;
348                 ec->ec_sortref = 0;
349                 ec->ec_merged = NULL;
350                 em1 = add_eq_member(ec, item1, item1_relids, false, item1_type);
351                 em2 = add_eq_member(ec, item2, item2_relids, false, item2_type);
352
353                 root->eq_classes = lappend(root->eq_classes, ec);
354
355                 /* mark the RI as associated with this eclass */
356                 restrictinfo->left_ec = ec;
357                 restrictinfo->right_ec = ec;
358                 /* mark the RI as usable with this pair of EMs */
359                 restrictinfo->left_em = em1;
360                 restrictinfo->right_em = em2;
361         }
362
363         return true;
364 }
365
366 /*
367  * canonicalize_ec_expression
368  *
369  * This function ensures that the expression exposes the expected type and
370  * collation, so that it will be equal() to other equivalence-class expressions
371  * that it ought to be equal() to.
372  *
373  * The rule for datatypes is that the exposed type should match what it would
374  * be for an input to an operator of the EC's opfamilies; which is usually
375  * the declared input type of the operator, but in the case of polymorphic
376  * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
377  * Expressions coming in from quals will generally have the right type
378  * already, but expressions coming from indexkeys may not (because they are
379  * represented without any explicit relabel in pg_index), and the same problem
380  * occurs for sort expressions (because the parser is likewise cavalier about
381  * putting relabels on them).  Such cases will be binary-compatible with the
382  * real operators, so adding a RelabelType is sufficient.
383  *
384  * Also, the expression's exposed collation must match the EC's collation.
385  * This is important because in comparisons like "foo < bar COLLATE baz",
386  * only one of the expressions has the correct exposed collation as we receive
387  * it from the parser.  Forcing both of them to have it ensures that all
388  * variant spellings of such a construct behave the same.  Again, we can
389  * stick on a RelabelType to force the right exposed collation.  (It might
390  * work to not label the collation at all in EC members, but this is risky
391  * since some parts of the system expect exprCollation() to deliver the
392  * right answer for a sort key.)
393  *
394  * Note this code assumes that the expression has already been through
395  * eval_const_expressions, so there are no CollateExprs and no redundant
396  * RelabelTypes.
397  */
398 Expr *
399 canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
400 {
401         Oid                     expr_type = exprType((Node *) expr);
402
403         /*
404          * For a polymorphic-input-type opclass, just keep the same exposed type.
405          */
406         if (IsPolymorphicType(req_type))
407                 req_type = expr_type;
408
409         /*
410          * No work if the expression exposes the right type/collation already.
411          */
412         if (expr_type != req_type ||
413                 exprCollation((Node *) expr) != req_collation)
414         {
415                 /*
416                  * Strip any existing RelabelType, then add a new one if needed. This
417                  * is to preserve the invariant of no redundant RelabelTypes.
418                  *
419                  * If we have to change the exposed type of the stripped expression,
420                  * set typmod to -1 (since the new type may not have the same typmod
421                  * interpretation).  If we only have to change collation, preserve the
422                  * exposed typmod.
423                  */
424                 while (expr && IsA(expr, RelabelType))
425                         expr = (Expr *) ((RelabelType *) expr)->arg;
426
427                 if (exprType((Node *) expr) != req_type)
428                         expr = (Expr *) makeRelabelType(expr,
429                                                                                         req_type,
430                                                                                         -1,
431                                                                                         req_collation,
432                                                                                         COERCE_DONTCARE);
433                 else if (exprCollation((Node *) expr) != req_collation)
434                         expr = (Expr *) makeRelabelType(expr,
435                                                                                         req_type,
436                                                                                         exprTypmod((Node *) expr),
437                                                                                         req_collation,
438                                                                                         COERCE_DONTCARE);
439         }
440
441         return expr;
442 }
443
444 /*
445  * add_eq_member - build a new EquivalenceMember and add it to an EC
446  */
447 static EquivalenceMember *
448 add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
449                           bool is_child, Oid datatype)
450 {
451         EquivalenceMember *em = makeNode(EquivalenceMember);
452
453         em->em_expr = expr;
454         em->em_relids = relids;
455         em->em_is_const = false;
456         em->em_is_child = is_child;
457         em->em_datatype = datatype;
458
459         if (bms_is_empty(relids))
460         {
461                 /*
462                  * No Vars, assume it's a pseudoconstant.  This is correct for entries
463                  * generated from process_equivalence(), because a WHERE clause can't
464                  * contain aggregates or SRFs, and non-volatility was checked before
465                  * process_equivalence() ever got called.  But
466                  * get_eclass_for_sort_expr() has to work harder.  We put the tests
467                  * there not here to save cycles in the equivalence case.
468                  */
469                 Assert(!is_child);
470                 em->em_is_const = true;
471                 ec->ec_has_const = true;
472                 /* it can't affect ec_relids */
473         }
474         else if (!is_child)                     /* child members don't add to ec_relids */
475         {
476                 ec->ec_relids = bms_add_members(ec->ec_relids, relids);
477         }
478         ec->ec_members = lappend(ec->ec_members, em);
479
480         return em;
481 }
482
483
484 /*
485  * get_eclass_for_sort_expr
486  *        Given an expression and opfamily/collation info, find an existing
487  *        equivalence class it is a member of; if none, optionally build a new
488  *        single-member EquivalenceClass for it.
489  *
490  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
491  * or zero if not.      (It should never be zero if the expression is volatile!)
492  *
493  * If create_it is TRUE, we'll build a new EquivalenceClass when there is no
494  * match.  If create_it is FALSE, we just return NULL when no match.
495  *
496  * This can be used safely both before and after EquivalenceClass merging;
497  * since it never causes merging it does not invalidate any existing ECs
498  * or PathKeys.  However, ECs added after path generation has begun are
499  * of limited usefulness, so usually it's best to create them beforehand.
500  *
501  * Note: opfamilies must be chosen consistently with the way
502  * process_equivalence() would do; that is, generated from a mergejoinable
503  * equality operator.  Else we might fail to detect valid equivalences,
504  * generating poor (but not incorrect) plans.
505  */
506 EquivalenceClass *
507 get_eclass_for_sort_expr(PlannerInfo *root,
508                                                  Expr *expr,
509                                                  List *opfamilies,
510                                                  Oid opcintype,
511                                                  Oid collation,
512                                                  Index sortref,
513                                                  bool create_it)
514 {
515         EquivalenceClass *newec;
516         EquivalenceMember *newem;
517         ListCell   *lc1;
518         MemoryContext oldcontext;
519
520         /*
521          * Ensure the expression exposes the correct type and collation.
522          */
523         expr = canonicalize_ec_expression(expr, opcintype, collation);
524
525         /*
526          * Scan through the existing EquivalenceClasses for a match
527          */
528         foreach(lc1, root->eq_classes)
529         {
530                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
531                 ListCell   *lc2;
532
533                 /*
534                  * Never match to a volatile EC, except when we are looking at another
535                  * reference to the same volatile SortGroupClause.
536                  */
537                 if (cur_ec->ec_has_volatile &&
538                         (sortref == 0 || sortref != cur_ec->ec_sortref))
539                         continue;
540
541                 if (collation != cur_ec->ec_collation)
542                         continue;
543                 if (!equal(opfamilies, cur_ec->ec_opfamilies))
544                         continue;
545
546                 foreach(lc2, cur_ec->ec_members)
547                 {
548                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
549
550                         /*
551                          * If below an outer join, don't match constants: they're not as
552                          * constant as they look.
553                          */
554                         if (cur_ec->ec_below_outer_join &&
555                                 cur_em->em_is_const)
556                                 continue;
557
558                         if (opcintype == cur_em->em_datatype &&
559                                 equal(expr, cur_em->em_expr))
560                                 return cur_ec;  /* Match! */
561                 }
562         }
563
564         /* No match; does caller want a NULL result? */
565         if (!create_it)
566                 return NULL;
567
568         /*
569          * OK, build a new single-member EC
570          *
571          * Here, we must be sure that we construct the EC in the right context.
572          */
573         oldcontext = MemoryContextSwitchTo(root->planner_cxt);
574
575         newec = makeNode(EquivalenceClass);
576         newec->ec_opfamilies = list_copy(opfamilies);
577         newec->ec_collation = collation;
578         newec->ec_members = NIL;
579         newec->ec_sources = NIL;
580         newec->ec_derives = NIL;
581         newec->ec_relids = NULL;
582         newec->ec_has_const = false;
583         newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
584         newec->ec_below_outer_join = false;
585         newec->ec_broken = false;
586         newec->ec_sortref = sortref;
587         newec->ec_merged = NULL;
588
589         if (newec->ec_has_volatile && sortref == 0) /* should not happen */
590                 elog(ERROR, "volatile EquivalenceClass has no sortref");
591
592         newem = add_eq_member(newec, copyObject(expr), pull_varnos((Node *) expr),
593                                                   false, opcintype);
594
595         /*
596          * add_eq_member doesn't check for volatile functions, set-returning
597          * functions, aggregates, or window functions, but such could appear in
598          * sort expressions; so we have to check whether its const-marking was
599          * correct.
600          */
601         if (newec->ec_has_const)
602         {
603                 if (newec->ec_has_volatile ||
604                         expression_returns_set((Node *) expr) ||
605                         contain_agg_clause((Node *) expr) ||
606                         contain_window_function((Node *) expr))
607                 {
608                         newec->ec_has_const = false;
609                         newem->em_is_const = false;
610                 }
611         }
612
613         root->eq_classes = lappend(root->eq_classes, newec);
614
615         MemoryContextSwitchTo(oldcontext);
616
617         return newec;
618 }
619
620
621 /*
622  * generate_base_implied_equalities
623  *        Generate any restriction clauses that we can deduce from equivalence
624  *        classes.
625  *
626  * When an EC contains pseudoconstants, our strategy is to generate
627  * "member = const1" clauses where const1 is the first constant member, for
628  * every other member (including other constants).      If we are able to do this
629  * then we don't need any "var = var" comparisons because we've successfully
630  * constrained all the vars at their points of creation.  If we fail to
631  * generate any of these clauses due to lack of cross-type operators, we fall
632  * back to the "ec_broken" strategy described below.  (XXX if there are
633  * multiple constants of different types, it's possible that we might succeed
634  * in forming all the required clauses if we started from a different const
635  * member; but this seems a sufficiently hokey corner case to not be worth
636  * spending lots of cycles on.)
637  *
638  * For ECs that contain no pseudoconstants, we generate derived clauses
639  * "member1 = member2" for each pair of members belonging to the same base
640  * relation (actually, if there are more than two for the same base relation,
641  * we only need enough clauses to link each to each other).  This provides
642  * the base case for the recursion: each row emitted by a base relation scan
643  * will constrain all computable members of the EC to be equal.  As each
644  * join path is formed, we'll add additional derived clauses on-the-fly
645  * to maintain this invariant (see generate_join_implied_equalities).
646  *
647  * If the opfamilies used by the EC do not provide complete sets of cross-type
648  * equality operators, it is possible that we will fail to generate a clause
649  * that must be generated to maintain the invariant.  (An example: given
650  * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
651  * generate "a.x = a.z" as a restriction clause for A.)  In this case we mark
652  * the EC "ec_broken" and fall back to regurgitating its original source
653  * RestrictInfos at appropriate times.  We do not try to retract any derived
654  * clauses already generated from the broken EC, so the resulting plan could
655  * be poor due to bad selectivity estimates caused by redundant clauses.  But
656  * the correct solution to that is to fix the opfamilies ...
657  *
658  * Equality clauses derived by this function are passed off to
659  * process_implied_equality (in plan/initsplan.c) to be inserted into the
660  * restrictinfo datastructures.  Note that this must be called after initial
661  * scanning of the quals and before Path construction begins.
662  *
663  * We make no attempt to avoid generating duplicate RestrictInfos here: we
664  * don't search ec_sources for matches, nor put the created RestrictInfos
665  * into ec_derives.  Doing so would require some slightly ugly changes in
666  * initsplan.c's API, and there's no real advantage, because the clauses
667  * generated here can't duplicate anything we will generate for joins anyway.
668  */
669 void
670 generate_base_implied_equalities(PlannerInfo *root)
671 {
672         ListCell   *lc;
673         Index           rti;
674
675         foreach(lc, root->eq_classes)
676         {
677                 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
678
679                 Assert(ec->ec_merged == NULL);  /* else shouldn't be in list */
680                 Assert(!ec->ec_broken); /* not yet anyway... */
681
682                 /* Single-member ECs won't generate any deductions */
683                 if (list_length(ec->ec_members) <= 1)
684                         continue;
685
686                 if (ec->ec_has_const)
687                         generate_base_implied_equalities_const(root, ec);
688                 else
689                         generate_base_implied_equalities_no_const(root, ec);
690
691                 /* Recover if we failed to generate required derived clauses */
692                 if (ec->ec_broken)
693                         generate_base_implied_equalities_broken(root, ec);
694         }
695
696         /*
697          * This is also a handy place to mark base rels (which should all exist by
698          * now) with flags showing whether they have pending eclass joins.
699          */
700         for (rti = 1; rti < root->simple_rel_array_size; rti++)
701         {
702                 RelOptInfo *brel = root->simple_rel_array[rti];
703
704                 if (brel == NULL)
705                         continue;
706
707                 brel->has_eclass_joins = has_relevant_eclass_joinclause(root, brel);
708         }
709 }
710
711 /*
712  * generate_base_implied_equalities when EC contains pseudoconstant(s)
713  */
714 static void
715 generate_base_implied_equalities_const(PlannerInfo *root,
716                                                                            EquivalenceClass *ec)
717 {
718         EquivalenceMember *const_em = NULL;
719         ListCell   *lc;
720
721         /*
722          * In the trivial case where we just had one "var = const" clause, push
723          * the original clause back into the main planner machinery.  There is
724          * nothing to be gained by doing it differently, and we save the effort to
725          * re-build and re-analyze an equality clause that will be exactly
726          * equivalent to the old one.
727          */
728         if (list_length(ec->ec_members) == 2 &&
729                 list_length(ec->ec_sources) == 1)
730         {
731                 RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
732
733                 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
734                 {
735                         distribute_restrictinfo_to_rels(root, restrictinfo);
736                         return;
737                 }
738         }
739
740         /* Find the constant member to use */
741         foreach(lc, ec->ec_members)
742         {
743                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
744
745                 if (cur_em->em_is_const)
746                 {
747                         const_em = cur_em;
748                         break;
749                 }
750         }
751         Assert(const_em != NULL);
752
753         /* Generate a derived equality against each other member */
754         foreach(lc, ec->ec_members)
755         {
756                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
757                 Oid                     eq_op;
758
759                 Assert(!cur_em->em_is_child);   /* no children yet */
760                 if (cur_em == const_em)
761                         continue;
762                 eq_op = select_equality_operator(ec,
763                                                                                  cur_em->em_datatype,
764                                                                                  const_em->em_datatype);
765                 if (!OidIsValid(eq_op))
766                 {
767                         /* failed... */
768                         ec->ec_broken = true;
769                         break;
770                 }
771                 process_implied_equality(root, eq_op, ec->ec_collation,
772                                                                  cur_em->em_expr, const_em->em_expr,
773                                                                  ec->ec_relids,
774                                                                  ec->ec_below_outer_join,
775                                                                  cur_em->em_is_const);
776         }
777 }
778
779 /*
780  * generate_base_implied_equalities when EC contains no pseudoconstants
781  */
782 static void
783 generate_base_implied_equalities_no_const(PlannerInfo *root,
784                                                                                   EquivalenceClass *ec)
785 {
786         EquivalenceMember **prev_ems;
787         ListCell   *lc;
788
789         /*
790          * We scan the EC members once and track the last-seen member for each
791          * base relation.  When we see another member of the same base relation,
792          * we generate "prev_mem = cur_mem".  This results in the minimum number
793          * of derived clauses, but it's possible that it will fail when a
794          * different ordering would succeed.  XXX FIXME: use a UNION-FIND
795          * algorithm similar to the way we build merged ECs.  (Use a list-of-lists
796          * for each rel.)
797          */
798         prev_ems = (EquivalenceMember **)
799                 palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
800
801         foreach(lc, ec->ec_members)
802         {
803                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
804                 int                     relid;
805
806                 Assert(!cur_em->em_is_child);   /* no children yet */
807                 if (bms_membership(cur_em->em_relids) != BMS_SINGLETON)
808                         continue;
809                 relid = bms_singleton_member(cur_em->em_relids);
810                 Assert(relid < root->simple_rel_array_size);
811
812                 if (prev_ems[relid] != NULL)
813                 {
814                         EquivalenceMember *prev_em = prev_ems[relid];
815                         Oid                     eq_op;
816
817                         eq_op = select_equality_operator(ec,
818                                                                                          prev_em->em_datatype,
819                                                                                          cur_em->em_datatype);
820                         if (!OidIsValid(eq_op))
821                         {
822                                 /* failed... */
823                                 ec->ec_broken = true;
824                                 break;
825                         }
826                         process_implied_equality(root, eq_op, ec->ec_collation,
827                                                                          prev_em->em_expr, cur_em->em_expr,
828                                                                          ec->ec_relids,
829                                                                          ec->ec_below_outer_join,
830                                                                          false);
831                 }
832                 prev_ems[relid] = cur_em;
833         }
834
835         pfree(prev_ems);
836
837         /*
838          * We also have to make sure that all the Vars used in the member clauses
839          * will be available at any join node we might try to reference them at.
840          * For the moment we force all the Vars to be available at all join nodes
841          * for this eclass.  Perhaps this could be improved by doing some
842          * pre-analysis of which members we prefer to join, but it's no worse than
843          * what happened in the pre-8.3 code.
844          */
845         foreach(lc, ec->ec_members)
846         {
847                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
848                 List       *vars = pull_var_clause((Node *) cur_em->em_expr,
849                                                                                    PVC_RECURSE_AGGREGATES,
850                                                                                    PVC_INCLUDE_PLACEHOLDERS);
851
852                 add_vars_to_targetlist(root, vars, ec->ec_relids, false);
853                 list_free(vars);
854         }
855 }
856
857 /*
858  * generate_base_implied_equalities cleanup after failure
859  *
860  * What we must do here is push any zero- or one-relation source RestrictInfos
861  * of the EC back into the main restrictinfo datastructures.  Multi-relation
862  * clauses will be regurgitated later by generate_join_implied_equalities().
863  * (We do it this way to maintain continuity with the case that ec_broken
864  * becomes set only after we've gone up a join level or two.)
865  */
866 static void
867 generate_base_implied_equalities_broken(PlannerInfo *root,
868                                                                                 EquivalenceClass *ec)
869 {
870         ListCell   *lc;
871
872         foreach(lc, ec->ec_sources)
873         {
874                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
875
876                 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
877                         distribute_restrictinfo_to_rels(root, restrictinfo);
878         }
879 }
880
881
882 /*
883  * generate_join_implied_equalities
884  *        Generate any join clauses that we can deduce from equivalence classes.
885  *
886  * At a join node, we must enforce restriction clauses sufficient to ensure
887  * that all equivalence-class members computable at that node are equal.
888  * Since the set of clauses to enforce can vary depending on which subset
889  * relations are the inputs, we have to compute this afresh for each join
890  * path pair.  Hence a fresh List of RestrictInfo nodes is built and passed
891  * back on each call.
892  *
893  * The results are sufficient for use in merge, hash, and plain nestloop join
894  * methods.  We do not worry here about selecting clauses that are optimal
895  * for use in a nestloop-with-inner-indexscan join, however.  indxpath.c makes
896  * its own selections of clauses to use, and if the ones we pick here are
897  * redundant with those, the extras will be eliminated in createplan.c.
898  *
899  * Because the same join clauses are likely to be needed multiple times as
900  * we consider different join paths, we avoid generating multiple copies:
901  * whenever we select a particular pair of EquivalenceMembers to join,
902  * we check to see if the pair matches any original clause (in ec_sources)
903  * or previously-built clause (in ec_derives).  This saves memory and allows
904  * re-use of information cached in RestrictInfos.
905  */
906 List *
907 generate_join_implied_equalities(PlannerInfo *root,
908                                                                  RelOptInfo *joinrel,
909                                                                  RelOptInfo *outer_rel,
910                                                                  RelOptInfo *inner_rel)
911 {
912         List       *result = NIL;
913         ListCell   *lc;
914
915         foreach(lc, root->eq_classes)
916         {
917                 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
918                 List       *sublist = NIL;
919
920                 /* ECs containing consts do not need any further enforcement */
921                 if (ec->ec_has_const)
922                         continue;
923
924                 /* Single-member ECs won't generate any deductions */
925                 if (list_length(ec->ec_members) <= 1)
926                         continue;
927
928                 /* We can quickly ignore any that don't overlap the join, too */
929                 if (!bms_overlap(ec->ec_relids, joinrel->relids))
930                         continue;
931
932                 if (!ec->ec_broken)
933                         sublist = generate_join_implied_equalities_normal(root,
934                                                                                                                           ec,
935                                                                                                                           joinrel,
936                                                                                                                           outer_rel,
937                                                                                                                           inner_rel);
938
939                 /* Recover if we failed to generate required derived clauses */
940                 if (ec->ec_broken)
941                         sublist = generate_join_implied_equalities_broken(root,
942                                                                                                                           ec,
943                                                                                                                           joinrel,
944                                                                                                                           outer_rel,
945                                                                                                                           inner_rel);
946
947                 result = list_concat(result, sublist);
948         }
949
950         return result;
951 }
952
953 /*
954  * generate_join_implied_equalities for a still-valid EC
955  */
956 static List *
957 generate_join_implied_equalities_normal(PlannerInfo *root,
958                                                                                 EquivalenceClass *ec,
959                                                                                 RelOptInfo *joinrel,
960                                                                                 RelOptInfo *outer_rel,
961                                                                                 RelOptInfo *inner_rel)
962 {
963         List       *result = NIL;
964         List       *new_members = NIL;
965         List       *outer_members = NIL;
966         List       *inner_members = NIL;
967         ListCell   *lc1;
968
969         /*
970          * First, scan the EC to identify member values that are computable at the
971          * outer rel, at the inner rel, or at this relation but not in either
972          * input rel.  The outer-rel members should already be enforced equal,
973          * likewise for the inner-rel members.  We'll need to create clauses to
974          * enforce that any newly computable members are all equal to each other
975          * as well as to at least one input member, plus enforce at least one
976          * outer-rel member equal to at least one inner-rel member.
977          */
978         foreach(lc1, ec->ec_members)
979         {
980                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
981
982                 if (cur_em->em_is_child)
983                         continue;                       /* ignore children here */
984                 if (!bms_is_subset(cur_em->em_relids, joinrel->relids))
985                         continue;                       /* ignore --- not computable yet */
986
987                 if (bms_is_subset(cur_em->em_relids, outer_rel->relids))
988                         outer_members = lappend(outer_members, cur_em);
989                 else if (bms_is_subset(cur_em->em_relids, inner_rel->relids))
990                         inner_members = lappend(inner_members, cur_em);
991                 else
992                         new_members = lappend(new_members, cur_em);
993         }
994
995         /*
996          * First, select the joinclause if needed.      We can equate any one outer
997          * member to any one inner member, but we have to find a datatype
998          * combination for which an opfamily member operator exists.  If we have
999          * choices, we prefer simple Var members (possibly with RelabelType) since
1000          * these are (a) cheapest to compute at runtime and (b) most likely to
1001          * have useful statistics. Also, prefer operators that are also
1002          * hashjoinable.
1003          */
1004         if (outer_members && inner_members)
1005         {
1006                 EquivalenceMember *best_outer_em = NULL;
1007                 EquivalenceMember *best_inner_em = NULL;
1008                 Oid                     best_eq_op = InvalidOid;
1009                 int                     best_score = -1;
1010                 RestrictInfo *rinfo;
1011
1012                 foreach(lc1, outer_members)
1013                 {
1014                         EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
1015                         ListCell   *lc2;
1016
1017                         foreach(lc2, inner_members)
1018                         {
1019                                 EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
1020                                 Oid                     eq_op;
1021                                 int                     score;
1022
1023                                 eq_op = select_equality_operator(ec,
1024                                                                                                  outer_em->em_datatype,
1025                                                                                                  inner_em->em_datatype);
1026                                 if (!OidIsValid(eq_op))
1027                                         continue;
1028                                 score = 0;
1029                                 if (IsA(outer_em->em_expr, Var) ||
1030                                         (IsA(outer_em->em_expr, RelabelType) &&
1031                                          IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1032                                         score++;
1033                                 if (IsA(inner_em->em_expr, Var) ||
1034                                         (IsA(inner_em->em_expr, RelabelType) &&
1035                                          IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
1036                                         score++;
1037                                 if (op_hashjoinable(eq_op,
1038                                                                         exprType((Node *) outer_em->em_expr)))
1039                                         score++;
1040                                 if (score > best_score)
1041                                 {
1042                                         best_outer_em = outer_em;
1043                                         best_inner_em = inner_em;
1044                                         best_eq_op = eq_op;
1045                                         best_score = score;
1046                                         if (best_score == 3)
1047                                                 break;  /* no need to look further */
1048                                 }
1049                         }
1050                         if (best_score == 3)
1051                                 break;                  /* no need to look further */
1052                 }
1053                 if (best_score < 0)
1054                 {
1055                         /* failed... */
1056                         ec->ec_broken = true;
1057                         return NIL;
1058                 }
1059
1060                 /*
1061                  * Create clause, setting parent_ec to mark it as redundant with other
1062                  * joinclauses
1063                  */
1064                 rinfo = create_join_clause(root, ec, best_eq_op,
1065                                                                    best_outer_em, best_inner_em,
1066                                                                    ec);
1067
1068                 result = lappend(result, rinfo);
1069         }
1070
1071         /*
1072          * Now deal with building restrictions for any expressions that involve
1073          * Vars from both sides of the join.  We have to equate all of these to
1074          * each other as well as to at least one old member (if any).
1075          *
1076          * XXX as in generate_base_implied_equalities_no_const, we could be a lot
1077          * smarter here to avoid unnecessary failures in cross-type situations.
1078          * For now, use the same left-to-right method used there.
1079          */
1080         if (new_members)
1081         {
1082                 List       *old_members = list_concat(outer_members, inner_members);
1083                 EquivalenceMember *prev_em = NULL;
1084                 RestrictInfo *rinfo;
1085
1086                 /* For now, arbitrarily take the first old_member as the one to use */
1087                 if (old_members)
1088                         new_members = lappend(new_members, linitial(old_members));
1089
1090                 foreach(lc1, new_members)
1091                 {
1092                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
1093
1094                         if (prev_em != NULL)
1095                         {
1096                                 Oid                     eq_op;
1097
1098                                 eq_op = select_equality_operator(ec,
1099                                                                                                  prev_em->em_datatype,
1100                                                                                                  cur_em->em_datatype);
1101                                 if (!OidIsValid(eq_op))
1102                                 {
1103                                         /* failed... */
1104                                         ec->ec_broken = true;
1105                                         return NIL;
1106                                 }
1107                                 /* do NOT set parent_ec, this qual is not redundant! */
1108                                 rinfo = create_join_clause(root, ec, eq_op,
1109                                                                                    prev_em, cur_em,
1110                                                                                    NULL);
1111
1112                                 result = lappend(result, rinfo);
1113                         }
1114                         prev_em = cur_em;
1115                 }
1116         }
1117
1118         return result;
1119 }
1120
1121 /*
1122  * generate_join_implied_equalities cleanup after failure
1123  *
1124  * Return any original RestrictInfos that are enforceable at this join.
1125  */
1126 static List *
1127 generate_join_implied_equalities_broken(PlannerInfo *root,
1128                                                                                 EquivalenceClass *ec,
1129                                                                                 RelOptInfo *joinrel,
1130                                                                                 RelOptInfo *outer_rel,
1131                                                                                 RelOptInfo *inner_rel)
1132 {
1133         List       *result = NIL;
1134         ListCell   *lc;
1135
1136         foreach(lc, ec->ec_sources)
1137         {
1138                 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
1139
1140                 if (bms_is_subset(restrictinfo->required_relids, joinrel->relids) &&
1141                   !bms_is_subset(restrictinfo->required_relids, outer_rel->relids) &&
1142                         !bms_is_subset(restrictinfo->required_relids, inner_rel->relids))
1143                         result = lappend(result, restrictinfo);
1144         }
1145
1146         return result;
1147 }
1148
1149
1150 /*
1151  * select_equality_operator
1152  *        Select a suitable equality operator for comparing two EC members
1153  *
1154  * Returns InvalidOid if no operator can be found for this datatype combination
1155  */
1156 static Oid
1157 select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
1158 {
1159         ListCell   *lc;
1160
1161         foreach(lc, ec->ec_opfamilies)
1162         {
1163                 Oid                     opfamily = lfirst_oid(lc);
1164                 Oid                     opno;
1165
1166                 opno = get_opfamily_member(opfamily, lefttype, righttype,
1167                                                                    BTEqualStrategyNumber);
1168                 if (OidIsValid(opno))
1169                         return opno;
1170         }
1171         return InvalidOid;
1172 }
1173
1174
1175 /*
1176  * create_join_clause
1177  *        Find or make a RestrictInfo comparing the two given EC members
1178  *        with the given operator.
1179  *
1180  * parent_ec is either equal to ec (if the clause is a potentially-redundant
1181  * join clause) or NULL (if not).  We have to treat this as part of the
1182  * match requirements --- it's possible that a clause comparing the same two
1183  * EMs is a join clause in one join path and a restriction clause in another.
1184  */
1185 static RestrictInfo *
1186 create_join_clause(PlannerInfo *root,
1187                                    EquivalenceClass *ec, Oid opno,
1188                                    EquivalenceMember *leftem,
1189                                    EquivalenceMember *rightem,
1190                                    EquivalenceClass *parent_ec)
1191 {
1192         RestrictInfo *rinfo;
1193         ListCell   *lc;
1194         MemoryContext oldcontext;
1195
1196         /*
1197          * Search to see if we already built a RestrictInfo for this pair of
1198          * EquivalenceMembers.  We can use either original source clauses or
1199          * previously-derived clauses.  The check on opno is probably redundant,
1200          * but be safe ...
1201          */
1202         foreach(lc, ec->ec_sources)
1203         {
1204                 rinfo = (RestrictInfo *) lfirst(lc);
1205                 if (rinfo->left_em == leftem &&
1206                         rinfo->right_em == rightem &&
1207                         rinfo->parent_ec == parent_ec &&
1208                         opno == ((OpExpr *) rinfo->clause)->opno)
1209                         return rinfo;
1210         }
1211
1212         foreach(lc, ec->ec_derives)
1213         {
1214                 rinfo = (RestrictInfo *) lfirst(lc);
1215                 if (rinfo->left_em == leftem &&
1216                         rinfo->right_em == rightem &&
1217                         rinfo->parent_ec == parent_ec &&
1218                         opno == ((OpExpr *) rinfo->clause)->opno)
1219                         return rinfo;
1220         }
1221
1222         /*
1223          * Not there, so build it, in planner context so we can re-use it. (Not
1224          * important in normal planning, but definitely so in GEQO.)
1225          */
1226         oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1227
1228         rinfo = build_implied_join_equality(opno,
1229                                                                                 ec->ec_collation,
1230                                                                                 leftem->em_expr,
1231                                                                                 rightem->em_expr,
1232                                                                                 bms_union(leftem->em_relids,
1233                                                                                                   rightem->em_relids));
1234
1235         /* Mark the clause as redundant, or not */
1236         rinfo->parent_ec = parent_ec;
1237
1238         /*
1239          * We know the correct values for left_ec/right_ec, ie this particular EC,
1240          * so we can just set them directly instead of forcing another lookup.
1241          */
1242         rinfo->left_ec = ec;
1243         rinfo->right_ec = ec;
1244
1245         /* Mark it as usable with these EMs */
1246         rinfo->left_em = leftem;
1247         rinfo->right_em = rightem;
1248         /* and save it for possible re-use */
1249         ec->ec_derives = lappend(ec->ec_derives, rinfo);
1250
1251         MemoryContextSwitchTo(oldcontext);
1252
1253         return rinfo;
1254 }
1255
1256
1257 /*
1258  * reconsider_outer_join_clauses
1259  *        Re-examine any outer-join clauses that were set aside by
1260  *        distribute_qual_to_rels(), and see if we can derive any
1261  *        EquivalenceClasses from them.  Then, if they were not made
1262  *        redundant, push them out into the regular join-clause lists.
1263  *
1264  * When we have mergejoinable clauses A = B that are outer-join clauses,
1265  * we can't blindly combine them with other clauses A = C to deduce B = C,
1266  * since in fact the "equality" A = B won't necessarily hold above the
1267  * outer join (one of the variables might be NULL instead).  Nonetheless
1268  * there are cases where we can add qual clauses using transitivity.
1269  *
1270  * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
1271  * for which there is also an equivalence clause OUTERVAR = CONSTANT.
1272  * It is safe and useful to push a clause INNERVAR = CONSTANT into the
1273  * evaluation of the inner (nullable) relation, because any inner rows not
1274  * meeting this condition will not contribute to the outer-join result anyway.
1275  * (Any outer rows they could join to will be eliminated by the pushed-down
1276  * equivalence clause.)
1277  *
1278  * Note that the above rule does not work for full outer joins; nor is it
1279  * very interesting to consider cases where the generated equivalence clause
1280  * would involve relations outside the outer join, since such clauses couldn't
1281  * be pushed into the inner side's scan anyway.  So the restriction to
1282  * outervar = pseudoconstant is not really giving up anything.
1283  *
1284  * For full-join cases, we can only do something useful if it's a FULL JOIN
1285  * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
1286  * By the time it gets here, the merged column will look like
1287  *              COALESCE(LEFTVAR, RIGHTVAR)
1288  * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
1289  * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
1290  * and RIGHTVAR = CONSTANT into the input relations, since any rows not
1291  * meeting these conditions cannot contribute to the join result.
1292  *
1293  * Again, there isn't any traction to be gained by trying to deal with
1294  * clauses comparing a mergedvar to a non-pseudoconstant.  So we can make
1295  * use of the EquivalenceClasses to search for matching variables that were
1296  * equivalenced to constants.  The interesting outer-join clauses were
1297  * accumulated for us by distribute_qual_to_rels.
1298  *
1299  * When we find one of these cases, we implement the changes we want by
1300  * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
1301  * and pushing it into the EquivalenceClass structures.  This is because we
1302  * may already know that INNERVAR is equivalenced to some other var(s), and
1303  * we'd like the constant to propagate to them too.  Note that it would be
1304  * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
1305  * that could result in propagating constant restrictions from
1306  * INNERVAR to OUTERVAR, which would be very wrong.
1307  *
1308  * It's possible that the INNERVAR is also an OUTERVAR for some other
1309  * outer-join clause, in which case the process can be repeated.  So we repeat
1310  * looping over the lists of clauses until no further deductions can be made.
1311  * Whenever we do make a deduction, we remove the generating clause from the
1312  * lists, since we don't want to make the same deduction twice.
1313  *
1314  * If we don't find any match for a set-aside outer join clause, we must
1315  * throw it back into the regular joinclause processing by passing it to
1316  * distribute_restrictinfo_to_rels().  If we do generate a derived clause,
1317  * however, the outer-join clause is redundant.  We still throw it back,
1318  * because otherwise the join will be seen as a clauseless join and avoided
1319  * during join order searching; but we mark it as redundant to keep from
1320  * messing up the joinrel's size estimate.  (This behavior means that the
1321  * API for this routine is uselessly complex: we could have just put all
1322  * the clauses into the regular processing initially.  We keep it because
1323  * someday we might want to do something else, such as inserting "dummy"
1324  * joinclauses instead of real ones.)
1325  *
1326  * Outer join clauses that are marked outerjoin_delayed are special: this
1327  * condition means that one or both VARs might go to null due to a lower
1328  * outer join.  We can still push a constant through the clause, but only
1329  * if its operator is strict; and we *have to* throw the clause back into
1330  * regular joinclause processing.  By keeping the strict join clause,
1331  * we ensure that any null-extended rows that are mistakenly generated due
1332  * to suppressing rows not matching the constant will be rejected at the
1333  * upper outer join.  (This doesn't work for full-join clauses.)
1334  */
1335 void
1336 reconsider_outer_join_clauses(PlannerInfo *root)
1337 {
1338         bool            found;
1339         ListCell   *cell;
1340         ListCell   *prev;
1341         ListCell   *next;
1342
1343         /* Outer loop repeats until we find no more deductions */
1344         do
1345         {
1346                 found = false;
1347
1348                 /* Process the LEFT JOIN clauses */
1349                 prev = NULL;
1350                 for (cell = list_head(root->left_join_clauses); cell; cell = next)
1351                 {
1352                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1353
1354                         next = lnext(cell);
1355                         if (reconsider_outer_join_clause(root, rinfo, true))
1356                         {
1357                                 found = true;
1358                                 /* remove it from the list */
1359                                 root->left_join_clauses =
1360                                         list_delete_cell(root->left_join_clauses, cell, prev);
1361                                 /* we throw it back anyway (see notes above) */
1362                                 /* but the thrown-back clause has no extra selectivity */
1363                                 rinfo->norm_selec = 2.0;
1364                                 rinfo->outer_selec = 1.0;
1365                                 distribute_restrictinfo_to_rels(root, rinfo);
1366                         }
1367                         else
1368                                 prev = cell;
1369                 }
1370
1371                 /* Process the RIGHT JOIN clauses */
1372                 prev = NULL;
1373                 for (cell = list_head(root->right_join_clauses); cell; cell = next)
1374                 {
1375                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1376
1377                         next = lnext(cell);
1378                         if (reconsider_outer_join_clause(root, rinfo, false))
1379                         {
1380                                 found = true;
1381                                 /* remove it from the list */
1382                                 root->right_join_clauses =
1383                                         list_delete_cell(root->right_join_clauses, cell, prev);
1384                                 /* we throw it back anyway (see notes above) */
1385                                 /* but the thrown-back clause has no extra selectivity */
1386                                 rinfo->norm_selec = 2.0;
1387                                 rinfo->outer_selec = 1.0;
1388                                 distribute_restrictinfo_to_rels(root, rinfo);
1389                         }
1390                         else
1391                                 prev = cell;
1392                 }
1393
1394                 /* Process the FULL JOIN clauses */
1395                 prev = NULL;
1396                 for (cell = list_head(root->full_join_clauses); cell; cell = next)
1397                 {
1398                         RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1399
1400                         next = lnext(cell);
1401                         if (reconsider_full_join_clause(root, rinfo))
1402                         {
1403                                 found = true;
1404                                 /* remove it from the list */
1405                                 root->full_join_clauses =
1406                                         list_delete_cell(root->full_join_clauses, cell, prev);
1407                                 /* we throw it back anyway (see notes above) */
1408                                 /* but the thrown-back clause has no extra selectivity */
1409                                 rinfo->norm_selec = 2.0;
1410                                 rinfo->outer_selec = 1.0;
1411                                 distribute_restrictinfo_to_rels(root, rinfo);
1412                         }
1413                         else
1414                                 prev = cell;
1415                 }
1416         } while (found);
1417
1418         /* Now, any remaining clauses have to be thrown back */
1419         foreach(cell, root->left_join_clauses)
1420         {
1421                 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1422
1423                 distribute_restrictinfo_to_rels(root, rinfo);
1424         }
1425         foreach(cell, root->right_join_clauses)
1426         {
1427                 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1428
1429                 distribute_restrictinfo_to_rels(root, rinfo);
1430         }
1431         foreach(cell, root->full_join_clauses)
1432         {
1433                 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1434
1435                 distribute_restrictinfo_to_rels(root, rinfo);
1436         }
1437 }
1438
1439 /*
1440  * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
1441  *
1442  * Returns TRUE if we were able to propagate a constant through the clause.
1443  */
1444 static bool
1445 reconsider_outer_join_clause(PlannerInfo *root, RestrictInfo *rinfo,
1446                                                          bool outer_on_left)
1447 {
1448         Expr       *outervar,
1449                            *innervar;
1450         Oid                     opno,
1451                                 collation,
1452                                 left_type,
1453                                 right_type,
1454                                 inner_datatype;
1455         Relids          inner_relids;
1456         ListCell   *lc1;
1457
1458         Assert(is_opclause(rinfo->clause));
1459         opno = ((OpExpr *) rinfo->clause)->opno;
1460         collation = ((OpExpr *) rinfo->clause)->inputcollid;
1461
1462         /* If clause is outerjoin_delayed, operator must be strict */
1463         if (rinfo->outerjoin_delayed && !op_strict(opno))
1464                 return false;
1465
1466         /* Extract needed info from the clause */
1467         op_input_types(opno, &left_type, &right_type);
1468         if (outer_on_left)
1469         {
1470                 outervar = (Expr *) get_leftop(rinfo->clause);
1471                 innervar = (Expr *) get_rightop(rinfo->clause);
1472                 inner_datatype = right_type;
1473                 inner_relids = rinfo->right_relids;
1474         }
1475         else
1476         {
1477                 outervar = (Expr *) get_rightop(rinfo->clause);
1478                 innervar = (Expr *) get_leftop(rinfo->clause);
1479                 inner_datatype = left_type;
1480                 inner_relids = rinfo->left_relids;
1481         }
1482
1483         /* Scan EquivalenceClasses for a match to outervar */
1484         foreach(lc1, root->eq_classes)
1485         {
1486                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1487                 bool            match;
1488                 ListCell   *lc2;
1489
1490                 /* Ignore EC unless it contains pseudoconstants */
1491                 if (!cur_ec->ec_has_const)
1492                         continue;
1493                 /* Never match to a volatile EC */
1494                 if (cur_ec->ec_has_volatile)
1495                         continue;
1496                 /* It has to match the outer-join clause as to semantics, too */
1497                 if (collation != cur_ec->ec_collation)
1498                         continue;
1499                 if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1500                         continue;
1501                 /* Does it contain a match to outervar? */
1502                 match = false;
1503                 foreach(lc2, cur_ec->ec_members)
1504                 {
1505                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1506
1507                         if (equal(outervar, cur_em->em_expr))
1508                         {
1509                                 match = true;
1510                                 break;
1511                         }
1512                 }
1513                 if (!match)
1514                         continue;                       /* no match, so ignore this EC */
1515
1516                 /*
1517                  * Yes it does!  Try to generate a clause INNERVAR = CONSTANT for each
1518                  * CONSTANT in the EC.  Note that we must succeed with at least one
1519                  * constant before we can decide to throw away the outer-join clause.
1520                  */
1521                 match = false;
1522                 foreach(lc2, cur_ec->ec_members)
1523                 {
1524                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1525                         Oid                     eq_op;
1526                         RestrictInfo *newrinfo;
1527
1528                         if (!cur_em->em_is_const)
1529                                 continue;               /* ignore non-const members */
1530                         eq_op = select_equality_operator(cur_ec,
1531                                                                                          inner_datatype,
1532                                                                                          cur_em->em_datatype);
1533                         if (!OidIsValid(eq_op))
1534                                 continue;               /* can't generate equality */
1535                         newrinfo = build_implied_join_equality(eq_op,
1536                                                                                                    cur_ec->ec_collation,
1537                                                                                                    innervar,
1538                                                                                                    cur_em->em_expr,
1539                                                                                                    inner_relids);
1540                         if (process_equivalence(root, newrinfo, true))
1541                                 match = true;
1542                 }
1543
1544                 /*
1545                  * If we were able to equate INNERVAR to any constant, report success.
1546                  * Otherwise, fall out of the search loop, since we know the OUTERVAR
1547                  * appears in at most one EC.
1548                  */
1549                 if (match)
1550                         return true;
1551                 else
1552                         break;
1553         }
1554
1555         return false;                           /* failed to make any deduction */
1556 }
1557
1558 /*
1559  * reconsider_outer_join_clauses for a single FULL JOIN clause
1560  *
1561  * Returns TRUE if we were able to propagate a constant through the clause.
1562  */
1563 static bool
1564 reconsider_full_join_clause(PlannerInfo *root, RestrictInfo *rinfo)
1565 {
1566         Expr       *leftvar;
1567         Expr       *rightvar;
1568         Oid                     opno,
1569                                 collation,
1570                                 left_type,
1571                                 right_type;
1572         Relids          left_relids,
1573                                 right_relids;
1574         ListCell   *lc1;
1575
1576         /* Can't use an outerjoin_delayed clause here */
1577         if (rinfo->outerjoin_delayed)
1578                 return false;
1579
1580         /* Extract needed info from the clause */
1581         Assert(is_opclause(rinfo->clause));
1582         opno = ((OpExpr *) rinfo->clause)->opno;
1583         collation = ((OpExpr *) rinfo->clause)->inputcollid;
1584         op_input_types(opno, &left_type, &right_type);
1585         leftvar = (Expr *) get_leftop(rinfo->clause);
1586         rightvar = (Expr *) get_rightop(rinfo->clause);
1587         left_relids = rinfo->left_relids;
1588         right_relids = rinfo->right_relids;
1589
1590         foreach(lc1, root->eq_classes)
1591         {
1592                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1593                 EquivalenceMember *coal_em = NULL;
1594                 bool            match;
1595                 bool            matchleft;
1596                 bool            matchright;
1597                 ListCell   *lc2;
1598
1599                 /* Ignore EC unless it contains pseudoconstants */
1600                 if (!cur_ec->ec_has_const)
1601                         continue;
1602                 /* Never match to a volatile EC */
1603                 if (cur_ec->ec_has_volatile)
1604                         continue;
1605                 /* It has to match the outer-join clause as to semantics, too */
1606                 if (collation != cur_ec->ec_collation)
1607                         continue;
1608                 if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1609                         continue;
1610
1611                 /*
1612                  * Does it contain a COALESCE(leftvar, rightvar) construct?
1613                  *
1614                  * We can assume the COALESCE() inputs are in the same order as the
1615                  * join clause, since both were automatically generated in the cases
1616                  * we care about.
1617                  *
1618                  * XXX currently this may fail to match in cross-type cases because
1619                  * the COALESCE will contain typecast operations while the join clause
1620                  * may not (if there is a cross-type mergejoin operator available for
1621                  * the two column types). Is it OK to strip implicit coercions from
1622                  * the COALESCE arguments?
1623                  */
1624                 match = false;
1625                 foreach(lc2, cur_ec->ec_members)
1626                 {
1627                         coal_em = (EquivalenceMember *) lfirst(lc2);
1628                         if (IsA(coal_em->em_expr, CoalesceExpr))
1629                         {
1630                                 CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
1631                                 Node       *cfirst;
1632                                 Node       *csecond;
1633
1634                                 if (list_length(cexpr->args) != 2)
1635                                         continue;
1636                                 cfirst = (Node *) linitial(cexpr->args);
1637                                 csecond = (Node *) lsecond(cexpr->args);
1638
1639                                 if (equal(leftvar, cfirst) && equal(rightvar, csecond))
1640                                 {
1641                                         match = true;
1642                                         break;
1643                                 }
1644                         }
1645                 }
1646                 if (!match)
1647                         continue;                       /* no match, so ignore this EC */
1648
1649                 /*
1650                  * Yes it does!  Try to generate clauses LEFTVAR = CONSTANT and
1651                  * RIGHTVAR = CONSTANT for each CONSTANT in the EC.  Note that we must
1652                  * succeed with at least one constant for each var before we can
1653                  * decide to throw away the outer-join clause.
1654                  */
1655                 matchleft = matchright = false;
1656                 foreach(lc2, cur_ec->ec_members)
1657                 {
1658                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1659                         Oid                     eq_op;
1660                         RestrictInfo *newrinfo;
1661
1662                         if (!cur_em->em_is_const)
1663                                 continue;               /* ignore non-const members */
1664                         eq_op = select_equality_operator(cur_ec,
1665                                                                                          left_type,
1666                                                                                          cur_em->em_datatype);
1667                         if (OidIsValid(eq_op))
1668                         {
1669                                 newrinfo = build_implied_join_equality(eq_op,
1670                                                                                                            cur_ec->ec_collation,
1671                                                                                                            leftvar,
1672                                                                                                            cur_em->em_expr,
1673                                                                                                            left_relids);
1674                                 if (process_equivalence(root, newrinfo, true))
1675                                         matchleft = true;
1676                         }
1677                         eq_op = select_equality_operator(cur_ec,
1678                                                                                          right_type,
1679                                                                                          cur_em->em_datatype);
1680                         if (OidIsValid(eq_op))
1681                         {
1682                                 newrinfo = build_implied_join_equality(eq_op,
1683                                                                                                            cur_ec->ec_collation,
1684                                                                                                            rightvar,
1685                                                                                                            cur_em->em_expr,
1686                                                                                                            right_relids);
1687                                 if (process_equivalence(root, newrinfo, true))
1688                                         matchright = true;
1689                         }
1690                 }
1691
1692                 /*
1693                  * If we were able to equate both vars to constants, we're done, and
1694                  * we can throw away the full-join clause as redundant.  Moreover, we
1695                  * can remove the COALESCE entry from the EC, since the added
1696                  * restrictions ensure it will always have the expected value. (We
1697                  * don't bother trying to update ec_relids or ec_sources.)
1698                  */
1699                 if (matchleft && matchright)
1700                 {
1701                         cur_ec->ec_members = list_delete_ptr(cur_ec->ec_members, coal_em);
1702                         return true;
1703                 }
1704
1705                 /*
1706                  * Otherwise, fall out of the search loop, since we know the COALESCE
1707                  * appears in at most one EC (XXX might stop being true if we allow
1708                  * stripping of coercions above?)
1709                  */
1710                 break;
1711         }
1712
1713         return false;                           /* failed to make any deduction */
1714 }
1715
1716
1717 /*
1718  * exprs_known_equal
1719  *        Detect whether two expressions are known equal due to equivalence
1720  *        relationships.
1721  *
1722  * Actually, this only shows that the expressions are equal according
1723  * to some opfamily's notion of equality --- but we only use it for
1724  * selectivity estimation, so a fuzzy idea of equality is OK.
1725  *
1726  * Note: does not bother to check for "equal(item1, item2)"; caller must
1727  * check that case if it's possible to pass identical items.
1728  */
1729 bool
1730 exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
1731 {
1732         ListCell   *lc1;
1733
1734         foreach(lc1, root->eq_classes)
1735         {
1736                 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1737                 bool            item1member = false;
1738                 bool            item2member = false;
1739                 ListCell   *lc2;
1740
1741                 /* Never match to a volatile EC */
1742                 if (ec->ec_has_volatile)
1743                         continue;
1744
1745                 foreach(lc2, ec->ec_members)
1746                 {
1747                         EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
1748
1749                         if (equal(item1, em->em_expr))
1750                                 item1member = true;
1751                         else if (equal(item2, em->em_expr))
1752                                 item2member = true;
1753                         /* Exit as soon as equality is proven */
1754                         if (item1member && item2member)
1755                                 return true;
1756                 }
1757         }
1758         return false;
1759 }
1760
1761
1762 /*
1763  * add_child_rel_equivalences
1764  *        Search for EC members that reference (only) the parent_rel, and
1765  *        add transformed members referencing the child_rel.
1766  *
1767  * Note that this function won't be called at all unless we have at least some
1768  * reason to believe that the EC members it generates will be useful.
1769  *
1770  * parent_rel and child_rel could be derived from appinfo, but since the
1771  * caller has already computed them, we might as well just pass them in.
1772  */
1773 void
1774 add_child_rel_equivalences(PlannerInfo *root,
1775                                                    AppendRelInfo *appinfo,
1776                                                    RelOptInfo *parent_rel,
1777                                                    RelOptInfo *child_rel)
1778 {
1779         ListCell   *lc1;
1780
1781         foreach(lc1, root->eq_classes)
1782         {
1783                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1784                 ListCell   *lc2;
1785
1786                 /*
1787                  * If this EC contains a constant, then it's not useful for sorting or
1788                  * driving an inner index-scan, so we skip generating child EMs.
1789                  *
1790                  * If this EC contains a volatile expression, then generating child
1791                  * EMs would be downright dangerous.  We rely on a volatile EC having
1792                  * only one EM.
1793                  */
1794                 if (cur_ec->ec_has_const || cur_ec->ec_has_volatile)
1795                         continue;
1796
1797                 /* No point in searching if parent rel not mentioned in eclass */
1798                 if (!bms_is_subset(parent_rel->relids, cur_ec->ec_relids))
1799                         continue;
1800
1801                 foreach(lc2, cur_ec->ec_members)
1802                 {
1803                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1804
1805                         /* Does it reference (only) parent_rel? */
1806                         if (bms_equal(cur_em->em_relids, parent_rel->relids))
1807                         {
1808                                 /* Yes, generate transformed child version */
1809                                 Expr       *child_expr;
1810
1811                                 child_expr = (Expr *)
1812                                         adjust_appendrel_attrs((Node *) cur_em->em_expr,
1813                                                                                    appinfo);
1814                                 (void) add_eq_member(cur_ec, child_expr, child_rel->relids,
1815                                                                          true, cur_em->em_datatype);
1816                         }
1817                 }
1818         }
1819 }
1820
1821
1822 /*
1823  * mutate_eclass_expressions
1824  *        Apply an expression tree mutator to all expressions stored in
1825  *        equivalence classes.
1826  *
1827  * This is a bit of a hack ... it's currently needed only by planagg.c,
1828  * which needs to do a global search-and-replace of MIN/MAX Aggrefs
1829  * after eclasses are already set up.  Without changing the eclasses too,
1830  * subsequent matching of ORDER BY clauses would fail.
1831  *
1832  * Note that we assume the mutation won't affect relation membership or any
1833  * other properties we keep track of (which is a bit bogus, but by the time
1834  * planagg.c runs, it no longer matters).  Also we must be called in the
1835  * main planner memory context.
1836  */
1837 void
1838 mutate_eclass_expressions(PlannerInfo *root,
1839                                                   Node *(*mutator) (),
1840                                                   void *context)
1841 {
1842         ListCell   *lc1;
1843
1844         foreach(lc1, root->eq_classes)
1845         {
1846                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1847                 ListCell   *lc2;
1848
1849                 foreach(lc2, cur_ec->ec_members)
1850                 {
1851                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1852
1853                         cur_em->em_expr = (Expr *)
1854                                 mutator((Node *) cur_em->em_expr, context);
1855                 }
1856         }
1857 }
1858
1859
1860 /*
1861  * find_eclass_clauses_for_index_join
1862  *        Create joinclauses usable for a nestloop-with-inner-indexscan
1863  *        scanning the given inner rel with the specified set of outer rels.
1864  */
1865 List *
1866 find_eclass_clauses_for_index_join(PlannerInfo *root, RelOptInfo *rel,
1867                                                                    Relids outer_relids)
1868 {
1869         List       *result = NIL;
1870         bool            is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1871         ListCell   *lc1;
1872
1873         foreach(lc1, root->eq_classes)
1874         {
1875                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1876                 ListCell   *lc2;
1877
1878                 /*
1879                  * Won't generate joinclauses if const or single-member (the latter
1880                  * test covers the volatile case too)
1881                  */
1882                 if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
1883                         continue;
1884
1885                 /*
1886                  * No point in searching if rel not mentioned in eclass (but we can't
1887                  * tell that for a child rel).
1888                  */
1889                 if (!is_child_rel &&
1890                         !bms_is_subset(rel->relids, cur_ec->ec_relids))
1891                         continue;
1892                 /* ... nor if no overlap with outer_relids */
1893                 if (!bms_overlap(outer_relids, cur_ec->ec_relids))
1894                         continue;
1895
1896                 /* Scan members, looking for indexable columns */
1897                 foreach(lc2, cur_ec->ec_members)
1898                 {
1899                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1900                         EquivalenceMember *best_outer_em = NULL;
1901                         Oid                     best_eq_op = InvalidOid;
1902                         ListCell   *lc3;
1903
1904                         if (!bms_equal(cur_em->em_relids, rel->relids) ||
1905                                 !eclass_matches_any_index(cur_ec, cur_em, rel))
1906                                 continue;
1907
1908                         /*
1909                          * Found one, so try to generate a join clause.  This is like
1910                          * generate_join_implied_equalities_normal, except simpler since
1911                          * our only preference item is to pick a Var on the outer side. We
1912                          * only need one join clause per index col.
1913                          */
1914                         foreach(lc3, cur_ec->ec_members)
1915                         {
1916                                 EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc3);
1917                                 Oid                     eq_op;
1918
1919                                 if (!bms_is_subset(outer_em->em_relids, outer_relids))
1920                                         continue;
1921                                 eq_op = select_equality_operator(cur_ec,
1922                                                                                                  cur_em->em_datatype,
1923                                                                                                  outer_em->em_datatype);
1924                                 if (!OidIsValid(eq_op))
1925                                         continue;
1926                                 best_outer_em = outer_em;
1927                                 best_eq_op = eq_op;
1928                                 if (IsA(outer_em->em_expr, Var) ||
1929                                         (IsA(outer_em->em_expr, RelabelType) &&
1930                                          IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1931                                         break;          /* no need to look further */
1932                         }
1933
1934                         if (best_outer_em)
1935                         {
1936                                 /* Found a suitable joinclause */
1937                                 RestrictInfo *rinfo;
1938
1939                                 /* set parent_ec to mark as redundant with other joinclauses */
1940                                 rinfo = create_join_clause(root, cur_ec, best_eq_op,
1941                                                                                    cur_em, best_outer_em,
1942                                                                                    cur_ec);
1943
1944                                 result = lappend(result, rinfo);
1945
1946                                 /*
1947                                  * Note: we keep scanning here because we want to provide a
1948                                  * clause for every possible indexcol.
1949                                  */
1950                         }
1951                 }
1952         }
1953
1954         return result;
1955 }
1956
1957
1958 /*
1959  * have_relevant_eclass_joinclause
1960  *              Detect whether there is an EquivalenceClass that could produce
1961  *              a joinclause between the two given relations.
1962  *
1963  * This is essentially a very cut-down version of
1964  * generate_join_implied_equalities().  Note it's OK to occasionally say "yes"
1965  * incorrectly.  Hence we don't bother with details like whether the lack of a
1966  * cross-type operator might prevent the clause from actually being generated.
1967  */
1968 bool
1969 have_relevant_eclass_joinclause(PlannerInfo *root,
1970                                                                 RelOptInfo *rel1, RelOptInfo *rel2)
1971 {
1972         ListCell   *lc1;
1973
1974         foreach(lc1, root->eq_classes)
1975         {
1976                 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
1977                 bool            has_rel1;
1978                 bool            has_rel2;
1979                 ListCell   *lc2;
1980
1981                 /*
1982                  * Won't generate joinclauses if single-member (this test covers the
1983                  * volatile case too)
1984                  */
1985                 if (list_length(ec->ec_members) <= 1)
1986                         continue;
1987
1988                 /*
1989                  * Note we don't test ec_broken; if we did, we'd need a separate code
1990                  * path to look through ec_sources.  Checking the members anyway is OK
1991                  * as a possibly-overoptimistic heuristic.
1992                  *
1993                  * We don't test ec_has_const either, even though a const eclass won't
1994                  * generate real join clauses.  This is because if we had "WHERE a.x =
1995                  * b.y and a.x = 42", it is worth considering a join between a and b,
1996                  * since the join result is likely to be small even though it'll end
1997                  * up being an unqualified nestloop.
1998                  */
1999
2000                 /* Needn't scan if it couldn't contain members from each rel */
2001                 if (!bms_overlap(rel1->relids, ec->ec_relids) ||
2002                         !bms_overlap(rel2->relids, ec->ec_relids))
2003                         continue;
2004
2005                 /* Scan the EC to see if it has member(s) in each rel */
2006                 has_rel1 = has_rel2 = false;
2007                 foreach(lc2, ec->ec_members)
2008                 {
2009                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2010
2011                         if (cur_em->em_is_const || cur_em->em_is_child)
2012                                 continue;               /* ignore consts and children here */
2013                         if (bms_is_subset(cur_em->em_relids, rel1->relids))
2014                         {
2015                                 has_rel1 = true;
2016                                 if (has_rel2)
2017                                         break;
2018                         }
2019                         if (bms_is_subset(cur_em->em_relids, rel2->relids))
2020                         {
2021                                 has_rel2 = true;
2022                                 if (has_rel1)
2023                                         break;
2024                         }
2025                 }
2026
2027                 if (has_rel1 && has_rel2)
2028                         return true;
2029         }
2030
2031         return false;
2032 }
2033
2034
2035 /*
2036  * has_relevant_eclass_joinclause
2037  *              Detect whether there is an EquivalenceClass that could produce
2038  *              a joinclause between the given relation and anything else.
2039  *
2040  * This is the same as have_relevant_eclass_joinclause with the other rel
2041  * implicitly defined as "everything else in the query".
2042  */
2043 bool
2044 has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
2045 {
2046         ListCell   *lc1;
2047
2048         foreach(lc1, root->eq_classes)
2049         {
2050                 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2051                 bool            has_rel1;
2052                 bool            has_rel2;
2053                 ListCell   *lc2;
2054
2055                 /*
2056                  * Won't generate joinclauses if single-member (this test covers the
2057                  * volatile case too)
2058                  */
2059                 if (list_length(ec->ec_members) <= 1)
2060                         continue;
2061
2062                 /*
2063                  * Note we don't test ec_broken; if we did, we'd need a separate code
2064                  * path to look through ec_sources.  Checking the members anyway is OK
2065                  * as a possibly-overoptimistic heuristic.
2066                  *
2067                  * We don't test ec_has_const either, even though a const eclass won't
2068                  * generate real join clauses.  This is because if we had "WHERE a.x =
2069                  * b.y and a.x = 42", it is worth considering a join between a and b,
2070                  * since the join result is likely to be small even though it'll end
2071                  * up being an unqualified nestloop.
2072                  */
2073
2074                 /* Needn't scan if it couldn't contain members from each rel */
2075                 if (!bms_overlap(rel1->relids, ec->ec_relids) ||
2076                         bms_is_subset(ec->ec_relids, rel1->relids))
2077                         continue;
2078
2079                 /* Scan the EC to see if it has member(s) in each rel */
2080                 has_rel1 = has_rel2 = false;
2081                 foreach(lc2, ec->ec_members)
2082                 {
2083                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2084
2085                         if (cur_em->em_is_const || cur_em->em_is_child)
2086                                 continue;               /* ignore consts and children here */
2087                         if (bms_is_subset(cur_em->em_relids, rel1->relids))
2088                         {
2089                                 has_rel1 = true;
2090                                 if (has_rel2)
2091                                         break;
2092                         }
2093                         if (!bms_overlap(cur_em->em_relids, rel1->relids))
2094                         {
2095                                 has_rel2 = true;
2096                                 if (has_rel1)
2097                                         break;
2098                         }
2099                 }
2100
2101                 if (has_rel1 && has_rel2)
2102                         return true;
2103         }
2104
2105         return false;
2106 }
2107
2108
2109 /*
2110  * eclass_useful_for_merging
2111  *        Detect whether the EC could produce any mergejoinable join clauses
2112  *        against the specified relation.
2113  *
2114  * This is just a heuristic test and doesn't have to be exact; it's better
2115  * to say "yes" incorrectly than "no".  Hence we don't bother with details
2116  * like whether the lack of a cross-type operator might prevent the clause
2117  * from actually being generated.
2118  */
2119 bool
2120 eclass_useful_for_merging(EquivalenceClass *eclass,
2121                                                   RelOptInfo *rel)
2122 {
2123         ListCell   *lc;
2124
2125         Assert(!eclass->ec_merged);
2126
2127         /*
2128          * Won't generate joinclauses if const or single-member (the latter test
2129          * covers the volatile case too)
2130          */
2131         if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
2132                 return false;
2133
2134         /*
2135          * Note we don't test ec_broken; if we did, we'd need a separate code path
2136          * to look through ec_sources.  Checking the members anyway is OK as a
2137          * possibly-overoptimistic heuristic.
2138          */
2139
2140         /* If rel already includes all members of eclass, no point in searching */
2141         if (bms_is_subset(eclass->ec_relids, rel->relids))
2142                 return false;
2143
2144         /* To join, we need a member not in the given rel */
2145         foreach(lc, eclass->ec_members)
2146         {
2147                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
2148
2149                 if (!cur_em->em_is_child &&
2150                         !bms_overlap(cur_em->em_relids, rel->relids))
2151                         return true;
2152         }
2153
2154         return false;
2155 }