]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/equivclass.c
Revise collation derivation method and expression-tree representation.
[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/cost.h"
25 #include "optimizer/paths.h"
26 #include "optimizer/planmain.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/var.h"
29 #include "utils/lsyscache.h"
30
31
32 static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
33                           Expr *expr, Relids relids,
34                           bool is_child, Oid datatype);
35 static void generate_base_implied_equalities_const(PlannerInfo *root,
36                                                                            EquivalenceClass *ec);
37 static void generate_base_implied_equalities_no_const(PlannerInfo *root,
38                                                                                   EquivalenceClass *ec);
39 static void generate_base_implied_equalities_broken(PlannerInfo *root,
40                                                                                 EquivalenceClass *ec);
41 static List *generate_join_implied_equalities_normal(PlannerInfo *root,
42                                                                                 EquivalenceClass *ec,
43                                                                                 RelOptInfo *joinrel,
44                                                                                 RelOptInfo *outer_rel,
45                                                                                 RelOptInfo *inner_rel);
46 static List *generate_join_implied_equalities_broken(PlannerInfo *root,
47                                                                                 EquivalenceClass *ec,
48                                                                                 RelOptInfo *joinrel,
49                                                                                 RelOptInfo *outer_rel,
50                                                                                 RelOptInfo *inner_rel);
51 static Oid select_equality_operator(EquivalenceClass *ec,
52                                                  Oid lefttype, Oid righttype);
53 static RestrictInfo *create_join_clause(PlannerInfo *root,
54                                    EquivalenceClass *ec, Oid opno,
55                                    EquivalenceMember *leftem,
56                                    EquivalenceMember *rightem,
57                                    EquivalenceClass *parent_ec);
58 static bool reconsider_outer_join_clause(PlannerInfo *root,
59                                                          RestrictInfo *rinfo,
60                                                          bool outer_on_left);
61 static bool reconsider_full_join_clause(PlannerInfo *root,
62                                                         RestrictInfo *rinfo);
63
64
65 /*
66  * process_equivalence
67  *        The given clause has a mergejoinable operator and can be applied without
68  *        any delay by an outer join, so its two sides can be considered equal
69  *        anywhere they are both computable; moreover that equality can be
70  *        extended transitively.  Record this knowledge in the EquivalenceClass
71  *        data structure.  Returns TRUE if successful, FALSE if not (in which
72  *        case caller should treat the clause as ordinary, not an equivalence).
73  *
74  * If below_outer_join is true, then the clause was found below the nullable
75  * side of an outer join, so its sides might validly be both NULL rather than
76  * strictly equal.      We can still deduce equalities in such cases, but we take
77  * care to mark an EquivalenceClass if it came from any such clauses.  Also,
78  * we have to check that both sides are either pseudo-constants or strict
79  * functions of Vars, else they might not both go to NULL above the outer
80  * join.  (This is the reason why we need a failure return.  It's more
81  * convenient to check this case here than at the call sites...)
82  *
83  * On success return, we have also initialized the clause's left_ec/right_ec
84  * fields to point to the EquivalenceClass representing it.  This saves lookup
85  * effort later.
86  *
87  * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
88  * problem, for which there exist better data structures than simple lists.
89  * If this code ever proves to be a bottleneck then it could be sped up ---
90  * but for now, simple is beautiful.
91  *
92  * Note: this is only called during planner startup, not during GEQO
93  * exploration, so we need not worry about whether we're in the right
94  * memory context.
95  */
96 bool
97 process_equivalence(PlannerInfo *root, RestrictInfo *restrictinfo,
98                                         bool below_outer_join)
99 {
100         Expr       *clause = restrictinfo->clause;
101         Oid                     opno,
102                                 collation,
103                                 item1_type,
104                                 item2_type;
105         Expr       *item1;
106         Expr       *item2;
107         Relids          item1_relids,
108                                 item2_relids;
109         List       *opfamilies;
110         EquivalenceClass *ec1,
111                            *ec2;
112         EquivalenceMember *em1,
113                            *em2;
114         ListCell   *lc1;
115
116         /* Should not already be marked as having generated an eclass */
117         Assert(restrictinfo->left_ec == NULL);
118         Assert(restrictinfo->right_ec == NULL);
119
120         /* Extract info from given clause */
121         Assert(is_opclause(clause));
122         opno = ((OpExpr *) clause)->opno;
123         collation = ((OpExpr *) clause)->inputcollid;
124         item1 = (Expr *) get_leftop(clause);
125         item2 = (Expr *) get_rightop(clause);
126         item1_relids = restrictinfo->left_relids;
127         item2_relids = restrictinfo->right_relids;
128
129         /*
130          * Ensure both input expressions expose the desired collation (their types
131          * should be OK already); see comments for canonicalize_ec_expression.
132          */
133         item1 = canonicalize_ec_expression(item1,
134                                                                            exprType((Node *) item1),
135                                                                            collation);
136         item2 = canonicalize_ec_expression(item2,
137                                                                            exprType((Node *) item2),
138                                                                            collation);
139
140         /*
141          * Reject clauses of the form X=X.      These are not as redundant as they
142          * might seem at first glance: assuming the operator is strict, this is
143          * really an expensive way to write X IS NOT NULL.      So we must not risk
144          * just losing the clause, which would be possible if there is already a
145          * single-element EquivalenceClass containing X.  The case is not common
146          * enough to be worth contorting the EC machinery for, so just reject the
147          * clause and let it be processed as a normal restriction clause.
148          */
149         if (equal(item1, item2))
150                 return false;                   /* X=X is not a useful equivalence */
151
152         /*
153          * If below outer join, check for strictness, else reject.
154          */
155         if (below_outer_join)
156         {
157                 if (!bms_is_empty(item1_relids) &&
158                         contain_nonstrict_functions((Node *) item1))
159                         return false;           /* LHS is non-strict but not constant */
160                 if (!bms_is_empty(item2_relids) &&
161                         contain_nonstrict_functions((Node *) item2))
162                         return false;           /* RHS is non-strict but not constant */
163         }
164
165         /*
166          * We use the declared input types of the operator, not exprType() of the
167          * inputs, as the nominal datatypes for opfamily lookup.  This presumes
168          * that btree operators are always registered with amoplefttype and
169          * amoprighttype equal to their declared input types.  We will need this
170          * info anyway to build EquivalenceMember nodes, and by extracting it now
171          * we can use type comparisons to short-circuit some equal() tests.
172          */
173         op_input_types(opno, &item1_type, &item2_type);
174
175         opfamilies = restrictinfo->mergeopfamilies;
176
177         /*
178          * Sweep through the existing EquivalenceClasses looking for matches to
179          * item1 and item2.  These are the possible outcomes:
180          *
181          * 1. We find both in the same EC.      The equivalence is already known, so
182          * there's nothing to do.
183          *
184          * 2. We find both in different ECs.  Merge the two ECs together.
185          *
186          * 3. We find just one.  Add the other to its EC.
187          *
188          * 4. We find neither.  Make a new, two-entry EC.
189          *
190          * Note: since all ECs are built through this process or the similar
191          * search in get_eclass_for_sort_expr(), it's impossible that we'd match
192          * an item in more than one existing nonvolatile EC.  So it's okay to stop
193          * at the first match.
194          */
195         ec1 = ec2 = NULL;
196         em1 = em2 = NULL;
197         foreach(lc1, root->eq_classes)
198         {
199                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
200                 ListCell   *lc2;
201
202                 /* Never match to a volatile EC */
203                 if (cur_ec->ec_has_volatile)
204                         continue;
205
206                 /*
207                  * The collation has to match; check this first since it's cheaper
208                  * than the opfamily comparison.
209                  */
210                 if (collation != cur_ec->ec_collation)
211                         continue;
212
213                 /*
214                  * A "match" requires matching sets of btree opfamilies.  Use of
215                  * equal() for this test has implications discussed in the comments
216                  * for get_mergejoin_opfamilies().
217                  */
218                 if (!equal(opfamilies, cur_ec->ec_opfamilies))
219                         continue;
220
221                 foreach(lc2, cur_ec->ec_members)
222                 {
223                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
224
225                         Assert(!cur_em->em_is_child);           /* no children yet */
226
227                         /*
228                          * If below an outer join, don't match constants: they're not as
229                          * constant as they look.
230                          */
231                         if ((below_outer_join || cur_ec->ec_below_outer_join) &&
232                                 cur_em->em_is_const)
233                                 continue;
234
235                         if (!ec1 &&
236                                 item1_type == cur_em->em_datatype &&
237                                 equal(item1, cur_em->em_expr))
238                         {
239                                 ec1 = cur_ec;
240                                 em1 = cur_em;
241                                 if (ec2)
242                                         break;
243                         }
244
245                         if (!ec2 &&
246                                 item2_type == cur_em->em_datatype &&
247                                 equal(item2, cur_em->em_expr))
248                         {
249                                 ec2 = cur_ec;
250                                 em2 = cur_em;
251                                 if (ec1)
252                                         break;
253                         }
254                 }
255
256                 if (ec1 && ec2)
257                         break;
258         }
259
260         /* Sweep finished, what did we find? */
261
262         if (ec1 && ec2)
263         {
264                 /* If case 1, nothing to do, except add to sources */
265                 if (ec1 == ec2)
266                 {
267                         ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
268                         ec1->ec_below_outer_join |= below_outer_join;
269                         /* mark the RI as associated with this eclass */
270                         restrictinfo->left_ec = ec1;
271                         restrictinfo->right_ec = ec1;
272                         /* mark the RI as usable with this pair of EMs */
273                         restrictinfo->left_em = em1;
274                         restrictinfo->right_em = em2;
275                         return true;
276                 }
277
278                 /*
279                  * Case 2: need to merge ec1 and ec2.  We add ec2's items to ec1, then
280                  * set ec2's ec_merged link to point to ec1 and remove ec2 from the
281                  * eq_classes list.  We cannot simply delete ec2 because that could
282                  * leave dangling pointers in existing PathKeys.  We leave it behind
283                  * with a link so that the merged EC can be found.
284                  */
285                 ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
286                 ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
287                 ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
288                 ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
289                 ec1->ec_has_const |= ec2->ec_has_const;
290                 /* can't need to set has_volatile */
291                 ec1->ec_below_outer_join |= ec2->ec_below_outer_join;
292                 ec2->ec_merged = ec1;
293                 root->eq_classes = list_delete_ptr(root->eq_classes, ec2);
294                 /* just to avoid debugging confusion w/ dangling pointers: */
295                 ec2->ec_members = NIL;
296                 ec2->ec_sources = NIL;
297                 ec2->ec_derives = NIL;
298                 ec2->ec_relids = NULL;
299                 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
300                 ec1->ec_below_outer_join |= below_outer_join;
301                 /* mark the RI as associated with this eclass */
302                 restrictinfo->left_ec = ec1;
303                 restrictinfo->right_ec = ec1;
304                 /* mark the RI as usable with this pair of EMs */
305                 restrictinfo->left_em = em1;
306                 restrictinfo->right_em = em2;
307         }
308         else if (ec1)
309         {
310                 /* Case 3: add item2 to ec1 */
311                 em2 = add_eq_member(ec1, item2, item2_relids, false, item2_type);
312                 ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
313                 ec1->ec_below_outer_join |= below_outer_join;
314                 /* mark the RI as associated with this eclass */
315                 restrictinfo->left_ec = ec1;
316                 restrictinfo->right_ec = ec1;
317                 /* mark the RI as usable with this pair of EMs */
318                 restrictinfo->left_em = em1;
319                 restrictinfo->right_em = em2;
320         }
321         else if (ec2)
322         {
323                 /* Case 3: add item1 to ec2 */
324                 em1 = add_eq_member(ec2, item1, item1_relids, false, item1_type);
325                 ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
326                 ec2->ec_below_outer_join |= below_outer_join;
327                 /* mark the RI as associated with this eclass */
328                 restrictinfo->left_ec = ec2;
329                 restrictinfo->right_ec = ec2;
330                 /* mark the RI as usable with this pair of EMs */
331                 restrictinfo->left_em = em1;
332                 restrictinfo->right_em = em2;
333         }
334         else
335         {
336                 /* Case 4: make a new, two-entry EC */
337                 EquivalenceClass *ec = makeNode(EquivalenceClass);
338
339                 ec->ec_opfamilies = opfamilies;
340                 ec->ec_collation = collation;
341                 ec->ec_members = NIL;
342                 ec->ec_sources = list_make1(restrictinfo);
343                 ec->ec_derives = NIL;
344                 ec->ec_relids = NULL;
345                 ec->ec_has_const = false;
346                 ec->ec_has_volatile = false;
347                 ec->ec_below_outer_join = below_outer_join;
348                 ec->ec_broken = false;
349                 ec->ec_sortref = 0;
350                 ec->ec_merged = NULL;
351                 em1 = add_eq_member(ec, item1, item1_relids, false, item1_type);
352                 em2 = add_eq_member(ec, item2, item2_relids, false, item2_type);
353
354                 root->eq_classes = lappend(root->eq_classes, ec);
355
356                 /* mark the RI as associated with this eclass */
357                 restrictinfo->left_ec = ec;
358                 restrictinfo->right_ec = ec;
359                 /* mark the RI as usable with this pair of EMs */
360                 restrictinfo->left_em = em1;
361                 restrictinfo->right_em = em2;
362         }
363
364         return true;
365 }
366
367 /*
368  * canonicalize_ec_expression
369  *
370  * This function ensures that the expression exposes the expected type and
371  * collation, so that it will be equal() to other equivalence-class expressions
372  * that it ought to be equal() to.
373  *
374  * The rule for datatypes is that the exposed type should match what it would
375  * be for an input to an operator of the EC's opfamilies; which is usually
376  * the declared input type of the operator, but in the case of polymorphic
377  * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
378  * Expressions coming in from quals will generally have the right type
379  * already, but expressions coming from indexkeys may not (because they are
380  * represented without any explicit relabel in pg_index), and the same problem
381  * occurs for sort expressions (because the parser is likewise cavalier about
382  * putting relabels on them).  Such cases will be binary-compatible with the
383  * real operators, so adding a RelabelType is sufficient.
384  *
385  * Also, the expression's exposed collation must match the EC's collation.
386  * This is important because in comparisons like "foo < bar COLLATE baz",
387  * only one of the expressions has the correct exposed collation as we receive
388  * it from the parser.  Forcing both of them to have it ensures that all
389  * variant spellings of such a construct behave the same.  Again, we can
390  * stick on a RelabelType to force the right exposed collation.  (It might
391  * work to not label the collation at all in EC members, but this is risky
392  * since some parts of the system expect exprCollation() to deliver the
393  * right answer for a sort key.)
394  *
395  * Note this code assumes that the expression has already been through
396  * eval_const_expressions, so there are no CollateExprs and no redundant
397  * RelabelTypes.
398  */
399 Expr *
400 canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
401 {
402         Oid                     expr_type = exprType((Node *) expr);
403
404         /*
405          * For a polymorphic-input-type opclass, just keep the same exposed type.
406          */
407         if (IsPolymorphicType(req_type))
408                 req_type = expr_type;
409
410         /*
411          * No work if the expression exposes the right type/collation already.
412          */
413         if (expr_type != req_type ||
414                 exprCollation((Node *) expr) != req_collation)
415         {
416                 /*
417                  * Strip any existing RelabelType, then add a new one if needed.
418                  * This is to preserve the invariant of no redundant RelabelTypes.
419                  *
420                  * If we have to change the exposed type of the stripped expression,
421                  * set typmod to -1 (since the new type may not have the same typmod
422                  * interpretation).  If we only have to change collation, preserve
423                  * the exposed typmod.
424                  */
425                 while (expr && IsA(expr, RelabelType))
426                         expr = (Expr *) ((RelabelType *) expr)->arg;
427
428                 if (exprType((Node *) expr) != req_type)
429                         expr = (Expr *) makeRelabelType(expr,
430                                                                                         req_type,
431                                                                                         -1,
432                                                                                         req_collation,
433                                                                                         COERCE_DONTCARE);
434                 else if (exprCollation((Node *) expr) != req_collation)
435                         expr = (Expr *) makeRelabelType(expr,
436                                                                                         req_type,
437                                                                                         exprTypmod((Node *) expr),
438                                                                                         req_collation,
439                                                                                         COERCE_DONTCARE);
440         }
441
442         return expr;
443 }
444
445 /*
446  * add_eq_member - build a new EquivalenceMember and add it to an EC
447  */
448 static EquivalenceMember *
449 add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
450                           bool is_child, Oid datatype)
451 {
452         EquivalenceMember *em = makeNode(EquivalenceMember);
453
454         em->em_expr = expr;
455         em->em_relids = relids;
456         em->em_is_const = false;
457         em->em_is_child = is_child;
458         em->em_datatype = datatype;
459
460         if (bms_is_empty(relids))
461         {
462                 /*
463                  * No Vars, assume it's a pseudoconstant.  This is correct for entries
464                  * generated from process_equivalence(), because a WHERE clause can't
465                  * contain aggregates or SRFs, and non-volatility was checked before
466                  * process_equivalence() ever got called.  But
467                  * get_eclass_for_sort_expr() has to work harder.  We put the tests
468                  * there not here to save cycles in the equivalence case.
469                  */
470                 Assert(!is_child);
471                 em->em_is_const = true;
472                 ec->ec_has_const = true;
473                 /* it can't affect ec_relids */
474         }
475         else if (!is_child)                     /* child members don't add to ec_relids */
476         {
477                 ec->ec_relids = bms_add_members(ec->ec_relids, relids);
478         }
479         ec->ec_members = lappend(ec->ec_members, em);
480
481         return em;
482 }
483
484
485 /*
486  * get_eclass_for_sort_expr
487  *        Given an expression and opfamily/collation info, find an existing
488  *        equivalence class it is a member of; if none, optionally build a new
489  *        single-member EquivalenceClass for it.
490  *
491  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
492  * or zero if not.      (It should never be zero if the expression is volatile!)
493  *
494  * If create_it is TRUE, we'll build a new EquivalenceClass when there is no
495  * match.  If create_it is FALSE, we just return NULL when no match.
496  *
497  * This can be used safely both before and after EquivalenceClass merging;
498  * since it never causes merging it does not invalidate any existing ECs
499  * or PathKeys.  However, ECs added after path generation has begun are
500  * of limited usefulness, so usually it's best to create them beforehand.
501  *
502  * Note: opfamilies must be chosen consistently with the way
503  * process_equivalence() would do; that is, generated from a mergejoinable
504  * equality operator.  Else we might fail to detect valid equivalences,
505  * generating poor (but not incorrect) plans.
506  */
507 EquivalenceClass *
508 get_eclass_for_sort_expr(PlannerInfo *root,
509                                                  Expr *expr,
510                                                  List *opfamilies,
511                                                  Oid opcintype,
512                                                  Oid collation,
513                                                  Index sortref,
514                                                  bool create_it)
515 {
516         EquivalenceClass *newec;
517         EquivalenceMember *newem;
518         ListCell   *lc1;
519         MemoryContext oldcontext;
520
521         /*
522          * Ensure the expression exposes the correct type and collation.
523          */
524         expr = canonicalize_ec_expression(expr, opcintype, collation);
525
526         /*
527          * Scan through the existing EquivalenceClasses for a match
528          */
529         foreach(lc1, root->eq_classes)
530         {
531                 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
532                 ListCell   *lc2;
533
534                 /*
535                  * Never match to a volatile EC, except when we are looking at another
536                  * reference to the same volatile SortGroupClause.
537                  */
538                 if (cur_ec->ec_has_volatile &&
539                         (sortref == 0 || sortref != cur_ec->ec_sortref))
540                         continue;
541
542                 if (collation != cur_ec->ec_collation)
543                         continue;
544                 if (!equal(opfamilies, cur_ec->ec_opfamilies))
545                         continue;
546
547                 foreach(lc2, cur_ec->ec_members)
548                 {
549                         EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
550
551                         /*
552                          * If below an outer join, don't match constants: they're not as
553                          * constant as they look.
554                          */
555                         if (cur_ec->ec_below_outer_join &&
556                                 cur_em->em_is_const)
557                                 continue;
558
559                         if (opcintype == cur_em->em_datatype &&
560                                 equal(expr, cur_em->em_expr))
561                                 return cur_ec;  /* Match! */
562                 }
563         }
564
565         /* No match; does caller want a NULL result? */
566         if (!create_it)
567                 return NULL;
568
569         /*
570          * OK, build a new single-member EC
571          *
572          * Here, we must be sure that we construct the EC in the right context.
573          */
574         oldcontext = MemoryContextSwitchTo(root->planner_cxt);
575
576         newec = makeNode(EquivalenceClass);
577         newec->ec_opfamilies = list_copy(opfamilies);
578         newec->ec_collation = collation;
579         newec->ec_members = NIL;
580         newec->ec_sources = NIL;
581         newec->ec_derives = NIL;
582         newec->ec_relids = NULL;
583         newec->ec_has_const = false;
584         newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
585         newec->ec_below_outer_join = false;
586         newec->ec_broken = false;
587         newec->ec_sortref = sortref;
588         newec->ec_merged = NULL;
589
590         if (newec->ec_has_volatile && sortref == 0) /* should not happen */
591                 elog(ERROR, "volatile EquivalenceClass has no sortref");
592
593         newem = add_eq_member(newec, copyObject(expr), pull_varnos((Node *) expr),
594                                                   false, opcintype);
595
596         /*
597          * add_eq_member doesn't check for volatile functions, set-returning
598          * functions, aggregates, or window functions, but such could appear in
599          * sort expressions; so we have to check whether its const-marking was
600          * correct.
601          */
602         if (newec->ec_has_const)
603         {
604                 if (newec->ec_has_volatile ||
605                         expression_returns_set((Node *) expr) ||
606                         contain_agg_clause((Node *) expr) ||
607                         contain_window_function((Node *) expr))
608                 {
609                         newec->ec_has_const = false;
610                         newem->em_is_const = false;
611                 }
612         }
613
614         root->eq_classes = lappend(root->eq_classes, newec);
615
616         MemoryContextSwitchTo(oldcontext);
617
618         return newec;
619 }
620
621
622 /*
623  * generate_base_implied_equalities
624  *        Generate any restriction clauses that we can deduce from equivalence
625  *        classes.
626  *
627  * When an EC contains pseudoconstants, our strategy is to generate
628  * "member = const1" clauses where const1 is the first constant member, for
629  * every other member (including other constants).      If we are able to do this
630  * then we don't need any "var = var" comparisons because we've successfully
631  * constrained all the vars at their points of creation.  If we fail to
632  * generate any of these clauses due to lack of cross-type operators, we fall
633  * back to the "ec_broken" strategy described below.  (XXX if there are
634  * multiple constants of different types, it's possible that we might succeed
635  * in forming all the required clauses if we started from a different const
636  * member; but this seems a sufficiently hokey corner case to not be worth
637  * spending lots of cycles on.)
638  *
639  * For ECs that contain no pseudoconstants, we generate derived clauses
640  * "member1 = member2" for each pair of members belonging to the same base
641  * relation (actually, if there are more than two for the same base relation,
642  * we only need enough clauses to link each to each other).  This provides
643  * the base case for the recursion: each row emitted by a base relation scan
644  * will constrain all computable members of the EC to be equal.  As each
645  * join path is formed, we'll add additional derived clauses on-the-fly
646  * to maintain this invariant (see generate_join_implied_equalities).
647  *
648  * If the opfamilies used by the EC do not provide complete sets of cross-type
649  * equality operators, it is possible that we will fail to generate a clause
650  * that must be generated to maintain the invariant.  (An example: given
651  * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
652  * generate "a.x = a.z" as a restriction clause for A.)  In this case we mark
653  * the EC "ec_broken" and fall back to regurgitating its original source
654  * RestrictInfos at appropriate times.  We do not try to retract any derived
655  * clauses already generated from the broken EC, so the resulting plan could
656  * be poor due to bad selectivity estimates caused by redundant clauses.  But
657  * the correct solution to that is to fix the opfamilies ...
658  *
659  * Equality clauses derived by this function are passed off to
660  * process_implied_equality (in plan/initsplan.c) to be inserted into the
661  * restrictinfo datastructures.  Note that this must be called after initial
662  * scanning of the quals and before Path construction begins.
663  *
664  * We make no attempt to avoid generating duplicate RestrictInfos here: we
665  * don't search ec_sources for matches, nor put the created RestrictInfos
666  * into ec_derives.  Doing so would require some slightly ugly changes in
667  * initsplan.c's API, and there's no real advantage, because the clauses
668  * generated here can't duplicate anything we will generate for joins anyway.
669  */
670 void
671 generate_base_implied_equalities(PlannerInfo *root)
672 {
673         ListCell   *lc;
674         Index           rti;
675
676         foreach(lc, root->eq_classes)
677         {
678                 EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
679
680                 Assert(ec->ec_merged == NULL);  /* else shouldn't be in list */
681                 Assert(!ec->ec_broken); /* not yet anyway... */
682
683                 /* Single-member ECs won't generate any deductions */
684                 if (list_length(ec->ec_members) <= 1)
685                         continue;
686
687                 if (ec->ec_has_const)
688                         generate_base_implied_equalities_const(root, ec);
689                 else
690                         generate_base_implied_equalities_no_const(root, ec);
691
692                 /* Recover if we failed to generate required derived clauses */
693                 if (ec->ec_broken)
694                         generate_base_implied_equalities_broken(root, ec);
695         }
696
697         /*
698          * This is also a handy place to mark base rels (which should all exist by
699          * now) with flags showing whether they have pending eclass joins.
700          */
701         for (rti = 1; rti < root->simple_rel_array_size; rti++)
702         {
703                 RelOptInfo *brel = root->simple_rel_array[rti];
704
705                 if (brel == NULL)
706                         continue;
707
708                 brel->has_eclass_joins = has_relevant_eclass_joinclause(root, brel);
709         }
710 }
711
712 /*
713  * generate_base_implied_equalities when EC contains pseudoconstant(s)
714  */
715 static void
716 generate_base_implied_equalities_const(PlannerInfo *root,
717                                                                            EquivalenceClass *ec)
718 {
719         EquivalenceMember *const_em = NULL;
720         ListCell   *lc;
721
722         /*
723          * In the trivial case where we just had one "var = const" clause, push
724          * the original clause back into the main planner machinery.  There is
725          * nothing to be gained by doing it differently, and we save the effort to
726          * re-build and re-analyze an equality clause that will be exactly
727          * equivalent to the old one.
728          */
729         if (list_length(ec->ec_members) == 2 &&
730                 list_length(ec->ec_sources) == 1)
731         {
732                 RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
733
734                 if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
735                 {
736                         distribute_restrictinfo_to_rels(root, restrictinfo);
737                         return;
738                 }
739         }
740
741         /* Find the constant member to use */
742         foreach(lc, ec->ec_members)
743         {
744                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
745
746                 if (cur_em->em_is_const)
747                 {
748                         const_em = cur_em;
749                         break;
750                 }
751         }
752         Assert(const_em != NULL);
753
754         /* Generate a derived equality against each other member */
755         foreach(lc, ec->ec_members)
756         {
757                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
758                 Oid                     eq_op;
759
760                 Assert(!cur_em->em_is_child);   /* no children yet */
761                 if (cur_em == const_em)
762                         continue;
763                 eq_op = select_equality_operator(ec,
764                                                                                  cur_em->em_datatype,
765                                                                                  const_em->em_datatype);
766                 if (!OidIsValid(eq_op))
767                 {
768                         /* failed... */
769                         ec->ec_broken = true;
770                         break;
771                 }
772                 process_implied_equality(root, eq_op, ec->ec_collation,
773                                                                  cur_em->em_expr, const_em->em_expr,
774                                                                  ec->ec_relids,
775                                                                  ec->ec_below_outer_join,
776                                                                  cur_em->em_is_const);
777         }
778 }
779
780 /*
781  * generate_base_implied_equalities when EC contains no pseudoconstants
782  */
783 static void
784 generate_base_implied_equalities_no_const(PlannerInfo *root,
785                                                                                   EquivalenceClass *ec)
786 {
787         EquivalenceMember **prev_ems;
788         ListCell   *lc;
789
790         /*
791          * We scan the EC members once and track the last-seen member for each
792          * base relation.  When we see another member of the same base relation,
793          * we generate "prev_mem = cur_mem".  This results in the minimum number
794          * of derived clauses, but it's possible that it will fail when a
795          * different ordering would succeed.  XXX FIXME: use a UNION-FIND
796          * algorithm similar to the way we build merged ECs.  (Use a list-of-lists
797          * for each rel.)
798          */
799         prev_ems = (EquivalenceMember **)
800                 palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
801
802         foreach(lc, ec->ec_members)
803         {
804                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
805                 int                     relid;
806
807                 Assert(!cur_em->em_is_child);   /* no children yet */
808                 if (bms_membership(cur_em->em_relids) != BMS_SINGLETON)
809                         continue;
810                 relid = bms_singleton_member(cur_em->em_relids);
811                 Assert(relid < root->simple_rel_array_size);
812
813                 if (prev_ems[relid] != NULL)
814                 {
815                         EquivalenceMember *prev_em = prev_ems[relid];
816                         Oid                     eq_op;
817
818                         eq_op = select_equality_operator(ec,
819                                                                                          prev_em->em_datatype,
820                                                                                          cur_em->em_datatype);
821                         if (!OidIsValid(eq_op))
822                         {
823                                 /* failed... */
824                                 ec->ec_broken = true;
825                                 break;
826                         }
827                         process_implied_equality(root, eq_op, ec->ec_collation,
828                                                                          prev_em->em_expr, cur_em->em_expr,
829                                                                          ec->ec_relids,
830                                                                          ec->ec_below_outer_join,
831                                                                          false);
832                 }
833                 prev_ems[relid] = cur_em;
834         }
835
836         pfree(prev_ems);
837
838         /*
839          * We also have to make sure that all the Vars used in the member clauses
840          * will be available at any join node we might try to reference them at.
841          * For the moment we force all the Vars to be available at all join nodes
842          * for this eclass.  Perhaps this could be improved by doing some
843          * pre-analysis of which members we prefer to join, but it's no worse than
844          * what happened in the pre-8.3 code.
845          */
846         foreach(lc, ec->ec_members)
847         {
848                 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
849                 List       *vars = pull_var_clause((Node *) cur_em->em_expr,
850                                                                                    PVC_INCLUDE_PLACEHOLDERS);
851
852                 add_vars_to_targetlist(root, vars, ec->ec_relids);
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
1788                  * or 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 }