PostgreSQL Source Code  git master
equivclass.c
Go to the documentation of this file.
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-2021, 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 <limits.h>
20 
21 #include "access/stratnum.h"
22 #include "catalog/pg_type.h"
23 #include "nodes/makefuncs.h"
24 #include "nodes/nodeFuncs.h"
25 #include "optimizer/appendinfo.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/optimizer.h"
28 #include "optimizer/pathnode.h"
29 #include "optimizer/paths.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/restrictinfo.h"
32 #include "utils/lsyscache.h"
33 
34 
36  Expr *expr, Relids relids, Relids nullable_relids,
37  bool is_child, Oid datatype);
39  EquivalenceClass *ec);
41  EquivalenceClass *ec);
43  EquivalenceClass *ec);
45  EquivalenceClass *ec,
46  Relids join_relids,
47  Relids outer_relids,
48  Relids inner_relids);
50  EquivalenceClass *ec,
51  Relids nominal_join_relids,
52  Relids outer_relids,
53  Relids nominal_inner_relids,
54  RelOptInfo *inner_rel);
56  Oid lefttype, Oid righttype);
58  EquivalenceClass *ec, Oid opno,
59  EquivalenceMember *leftem,
60  EquivalenceMember *rightem,
61  EquivalenceClass *parent_ec);
63  RestrictInfo *rinfo,
64  bool outer_on_left);
66  RestrictInfo *rinfo);
68  Relids relids);
70  Relids relids2);
71 
72 
73 /*
74  * process_equivalence
75  * The given clause has a mergejoinable operator and can be applied without
76  * any delay by an outer join, so its two sides can be considered equal
77  * anywhere they are both computable; moreover that equality can be
78  * extended transitively. Record this knowledge in the EquivalenceClass
79  * data structure, if applicable. Returns true if successful, false if not
80  * (in which case caller should treat the clause as ordinary, not an
81  * equivalence).
82  *
83  * In some cases, although we cannot convert a clause into EquivalenceClass
84  * knowledge, we can still modify it to a more useful form than the original.
85  * Then, *p_restrictinfo will be replaced by a new RestrictInfo, which is what
86  * the caller should use for further processing.
87  *
88  * If below_outer_join is true, then the clause was found below the nullable
89  * side of an outer join, so its sides might validly be both NULL rather than
90  * strictly equal. We can still deduce equalities in such cases, but we take
91  * care to mark an EquivalenceClass if it came from any such clauses. Also,
92  * we have to check that both sides are either pseudo-constants or strict
93  * functions of Vars, else they might not both go to NULL above the outer
94  * join. (This is the main reason why we need a failure return. It's more
95  * convenient to check this case here than at the call sites...)
96  *
97  * We also reject proposed equivalence clauses if they contain leaky functions
98  * and have security_level above zero. The EC evaluation rules require us to
99  * apply certain tests at certain joining levels, and we can't tolerate
100  * delaying any test on security_level grounds. By rejecting candidate clauses
101  * that might require security delays, we ensure it's safe to apply an EC
102  * clause as soon as it's supposed to be applied.
103  *
104  * On success return, we have also initialized the clause's left_ec/right_ec
105  * fields to point to the EquivalenceClass representing it. This saves lookup
106  * effort later.
107  *
108  * Note: constructing merged EquivalenceClasses is a standard UNION-FIND
109  * problem, for which there exist better data structures than simple lists.
110  * If this code ever proves to be a bottleneck then it could be sped up ---
111  * but for now, simple is beautiful.
112  *
113  * Note: this is only called during planner startup, not during GEQO
114  * exploration, so we need not worry about whether we're in the right
115  * memory context.
116  */
117 bool
119  RestrictInfo **p_restrictinfo,
120  bool below_outer_join)
121 {
122  RestrictInfo *restrictinfo = *p_restrictinfo;
123  Expr *clause = restrictinfo->clause;
124  Oid opno,
125  collation,
126  item1_type,
127  item2_type;
128  Expr *item1;
129  Expr *item2;
130  Relids item1_relids,
131  item2_relids,
132  item1_nullable_relids,
133  item2_nullable_relids;
134  List *opfamilies;
135  EquivalenceClass *ec1,
136  *ec2;
137  EquivalenceMember *em1,
138  *em2;
139  ListCell *lc1;
140  int ec2_idx;
141 
142  /* Should not already be marked as having generated an eclass */
143  Assert(restrictinfo->left_ec == NULL);
144  Assert(restrictinfo->right_ec == NULL);
145 
146  /* Reject if it is potentially postponable by security considerations */
147  if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
148  return false;
149 
150  /* Extract info from given clause */
151  Assert(is_opclause(clause));
152  opno = ((OpExpr *) clause)->opno;
153  collation = ((OpExpr *) clause)->inputcollid;
154  item1 = (Expr *) get_leftop(clause);
155  item2 = (Expr *) get_rightop(clause);
156  item1_relids = restrictinfo->left_relids;
157  item2_relids = restrictinfo->right_relids;
158 
159  /*
160  * Ensure both input expressions expose the desired collation (their types
161  * should be OK already); see comments for canonicalize_ec_expression.
162  */
163  item1 = canonicalize_ec_expression(item1,
164  exprType((Node *) item1),
165  collation);
166  item2 = canonicalize_ec_expression(item2,
167  exprType((Node *) item2),
168  collation);
169 
170  /*
171  * Clauses of the form X=X cannot be translated into EquivalenceClasses.
172  * We'd either end up with a single-entry EC, losing the knowledge that
173  * the clause was present at all, or else make an EC with duplicate
174  * entries, causing other issues.
175  */
176  if (equal(item1, item2))
177  {
178  /*
179  * If the operator is strict, then the clause can be treated as just
180  * "X IS NOT NULL". (Since we know we are considering a top-level
181  * qual, we can ignore the difference between FALSE and NULL results.)
182  * It's worth making the conversion because we'll typically get a much
183  * better selectivity estimate than we would for X=X.
184  *
185  * If the operator is not strict, we can't be sure what it will do
186  * with NULLs, so don't attempt to optimize it.
187  */
188  set_opfuncid((OpExpr *) clause);
189  if (func_strict(((OpExpr *) clause)->opfuncid))
190  {
191  NullTest *ntest = makeNode(NullTest);
192 
193  ntest->arg = item1;
194  ntest->nulltesttype = IS_NOT_NULL;
195  ntest->argisrow = false; /* correct even if composite arg */
196  ntest->location = -1;
197 
198  *p_restrictinfo =
199  make_restrictinfo((Expr *) ntest,
200  restrictinfo->is_pushed_down,
201  restrictinfo->outerjoin_delayed,
202  restrictinfo->pseudoconstant,
203  restrictinfo->security_level,
204  NULL,
205  restrictinfo->outer_relids,
206  restrictinfo->nullable_relids);
207  }
208  return false;
209  }
210 
211  /*
212  * If below outer join, check for strictness, else reject.
213  */
214  if (below_outer_join)
215  {
216  if (!bms_is_empty(item1_relids) &&
218  return false; /* LHS is non-strict but not constant */
219  if (!bms_is_empty(item2_relids) &&
221  return false; /* RHS is non-strict but not constant */
222  }
223 
224  /* Calculate nullable-relid sets for each side of the clause */
225  item1_nullable_relids = bms_intersect(item1_relids,
226  restrictinfo->nullable_relids);
227  item2_nullable_relids = bms_intersect(item2_relids,
228  restrictinfo->nullable_relids);
229 
230  /*
231  * We use the declared input types of the operator, not exprType() of the
232  * inputs, as the nominal datatypes for opfamily lookup. This presumes
233  * that btree operators are always registered with amoplefttype and
234  * amoprighttype equal to their declared input types. We will need this
235  * info anyway to build EquivalenceMember nodes, and by extracting it now
236  * we can use type comparisons to short-circuit some equal() tests.
237  */
238  op_input_types(opno, &item1_type, &item2_type);
239 
240  opfamilies = restrictinfo->mergeopfamilies;
241 
242  /*
243  * Sweep through the existing EquivalenceClasses looking for matches to
244  * item1 and item2. These are the possible outcomes:
245  *
246  * 1. We find both in the same EC. The equivalence is already known, so
247  * there's nothing to do.
248  *
249  * 2. We find both in different ECs. Merge the two ECs together.
250  *
251  * 3. We find just one. Add the other to its EC.
252  *
253  * 4. We find neither. Make a new, two-entry EC.
254  *
255  * Note: since all ECs are built through this process or the similar
256  * search in get_eclass_for_sort_expr(), it's impossible that we'd match
257  * an item in more than one existing nonvolatile EC. So it's okay to stop
258  * at the first match.
259  */
260  ec1 = ec2 = NULL;
261  em1 = em2 = NULL;
262  ec2_idx = -1;
263  foreach(lc1, root->eq_classes)
264  {
265  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
266  ListCell *lc2;
267 
268  /* Never match to a volatile EC */
269  if (cur_ec->ec_has_volatile)
270  continue;
271 
272  /*
273  * The collation has to match; check this first since it's cheaper
274  * than the opfamily comparison.
275  */
276  if (collation != cur_ec->ec_collation)
277  continue;
278 
279  /*
280  * A "match" requires matching sets of btree opfamilies. Use of
281  * equal() for this test has implications discussed in the comments
282  * for get_mergejoin_opfamilies().
283  */
284  if (!equal(opfamilies, cur_ec->ec_opfamilies))
285  continue;
286 
287  foreach(lc2, cur_ec->ec_members)
288  {
289  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
290 
291  Assert(!cur_em->em_is_child); /* no children yet */
292 
293  /*
294  * If below an outer join, don't match constants: they're not as
295  * constant as they look.
296  */
297  if ((below_outer_join || cur_ec->ec_below_outer_join) &&
298  cur_em->em_is_const)
299  continue;
300 
301  if (!ec1 &&
302  item1_type == cur_em->em_datatype &&
303  equal(item1, cur_em->em_expr))
304  {
305  ec1 = cur_ec;
306  em1 = cur_em;
307  if (ec2)
308  break;
309  }
310 
311  if (!ec2 &&
312  item2_type == cur_em->em_datatype &&
313  equal(item2, cur_em->em_expr))
314  {
315  ec2 = cur_ec;
316  ec2_idx = foreach_current_index(lc1);
317  em2 = cur_em;
318  if (ec1)
319  break;
320  }
321  }
322 
323  if (ec1 && ec2)
324  break;
325  }
326 
327  /* Sweep finished, what did we find? */
328 
329  if (ec1 && ec2)
330  {
331  /* If case 1, nothing to do, except add to sources */
332  if (ec1 == ec2)
333  {
334  ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
335  ec1->ec_below_outer_join |= below_outer_join;
336  ec1->ec_min_security = Min(ec1->ec_min_security,
337  restrictinfo->security_level);
338  ec1->ec_max_security = Max(ec1->ec_max_security,
339  restrictinfo->security_level);
340  /* mark the RI as associated with this eclass */
341  restrictinfo->left_ec = ec1;
342  restrictinfo->right_ec = ec1;
343  /* mark the RI as usable with this pair of EMs */
344  restrictinfo->left_em = em1;
345  restrictinfo->right_em = em2;
346  return true;
347  }
348 
349  /*
350  * Case 2: need to merge ec1 and ec2. This should never happen after
351  * the ECs have reached canonical state; otherwise, pathkeys could be
352  * rendered non-canonical by the merge, and relation eclass indexes
353  * would get broken by removal of an eq_classes list entry.
354  */
355  if (root->ec_merging_done)
356  elog(ERROR, "too late to merge equivalence classes");
357 
358  /*
359  * We add ec2's items to ec1, then set ec2's ec_merged link to point
360  * to ec1 and remove ec2 from the eq_classes list. We cannot simply
361  * delete ec2 because that could leave dangling pointers in existing
362  * PathKeys. We leave it behind with a link so that the merged EC can
363  * be found.
364  */
365  ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
366  ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
367  ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
368  ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
369  ec1->ec_has_const |= ec2->ec_has_const;
370  /* can't need to set has_volatile */
372  ec1->ec_min_security = Min(ec1->ec_min_security,
373  ec2->ec_min_security);
374  ec1->ec_max_security = Max(ec1->ec_max_security,
375  ec2->ec_max_security);
376  ec2->ec_merged = ec1;
377  root->eq_classes = list_delete_nth_cell(root->eq_classes, ec2_idx);
378  /* just to avoid debugging confusion w/ dangling pointers: */
379  ec2->ec_members = NIL;
380  ec2->ec_sources = NIL;
381  ec2->ec_derives = NIL;
382  ec2->ec_relids = NULL;
383  ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
384  ec1->ec_below_outer_join |= below_outer_join;
385  ec1->ec_min_security = Min(ec1->ec_min_security,
386  restrictinfo->security_level);
387  ec1->ec_max_security = Max(ec1->ec_max_security,
388  restrictinfo->security_level);
389  /* mark the RI as associated with this eclass */
390  restrictinfo->left_ec = ec1;
391  restrictinfo->right_ec = ec1;
392  /* mark the RI as usable with this pair of EMs */
393  restrictinfo->left_em = em1;
394  restrictinfo->right_em = em2;
395  }
396  else if (ec1)
397  {
398  /* Case 3: add item2 to ec1 */
399  em2 = add_eq_member(ec1, item2, item2_relids, item2_nullable_relids,
400  false, item2_type);
401  ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
402  ec1->ec_below_outer_join |= below_outer_join;
403  ec1->ec_min_security = Min(ec1->ec_min_security,
404  restrictinfo->security_level);
405  ec1->ec_max_security = Max(ec1->ec_max_security,
406  restrictinfo->security_level);
407  /* mark the RI as associated with this eclass */
408  restrictinfo->left_ec = ec1;
409  restrictinfo->right_ec = ec1;
410  /* mark the RI as usable with this pair of EMs */
411  restrictinfo->left_em = em1;
412  restrictinfo->right_em = em2;
413  }
414  else if (ec2)
415  {
416  /* Case 3: add item1 to ec2 */
417  em1 = add_eq_member(ec2, item1, item1_relids, item1_nullable_relids,
418  false, item1_type);
419  ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
420  ec2->ec_below_outer_join |= below_outer_join;
421  ec2->ec_min_security = Min(ec2->ec_min_security,
422  restrictinfo->security_level);
423  ec2->ec_max_security = Max(ec2->ec_max_security,
424  restrictinfo->security_level);
425  /* mark the RI as associated with this eclass */
426  restrictinfo->left_ec = ec2;
427  restrictinfo->right_ec = ec2;
428  /* mark the RI as usable with this pair of EMs */
429  restrictinfo->left_em = em1;
430  restrictinfo->right_em = em2;
431  }
432  else
433  {
434  /* Case 4: make a new, two-entry EC */
436 
437  ec->ec_opfamilies = opfamilies;
438  ec->ec_collation = collation;
439  ec->ec_members = NIL;
440  ec->ec_sources = list_make1(restrictinfo);
441  ec->ec_derives = NIL;
442  ec->ec_relids = NULL;
443  ec->ec_has_const = false;
444  ec->ec_has_volatile = false;
445  ec->ec_below_outer_join = below_outer_join;
446  ec->ec_broken = false;
447  ec->ec_sortref = 0;
448  ec->ec_min_security = restrictinfo->security_level;
449  ec->ec_max_security = restrictinfo->security_level;
450  ec->ec_merged = NULL;
451  em1 = add_eq_member(ec, item1, item1_relids, item1_nullable_relids,
452  false, item1_type);
453  em2 = add_eq_member(ec, item2, item2_relids, item2_nullable_relids,
454  false, item2_type);
455 
456  root->eq_classes = lappend(root->eq_classes, ec);
457 
458  /* mark the RI as associated with this eclass */
459  restrictinfo->left_ec = ec;
460  restrictinfo->right_ec = ec;
461  /* mark the RI as usable with this pair of EMs */
462  restrictinfo->left_em = em1;
463  restrictinfo->right_em = em2;
464  }
465 
466  return true;
467 }
468 
469 /*
470  * canonicalize_ec_expression
471  *
472  * This function ensures that the expression exposes the expected type and
473  * collation, so that it will be equal() to other equivalence-class expressions
474  * that it ought to be equal() to.
475  *
476  * The rule for datatypes is that the exposed type should match what it would
477  * be for an input to an operator of the EC's opfamilies; which is usually
478  * the declared input type of the operator, but in the case of polymorphic
479  * operators no relabeling is wanted (compare the behavior of parse_coerce.c).
480  * Expressions coming in from quals will generally have the right type
481  * already, but expressions coming from indexkeys may not (because they are
482  * represented without any explicit relabel in pg_index), and the same problem
483  * occurs for sort expressions (because the parser is likewise cavalier about
484  * putting relabels on them). Such cases will be binary-compatible with the
485  * real operators, so adding a RelabelType is sufficient.
486  *
487  * Also, the expression's exposed collation must match the EC's collation.
488  * This is important because in comparisons like "foo < bar COLLATE baz",
489  * only one of the expressions has the correct exposed collation as we receive
490  * it from the parser. Forcing both of them to have it ensures that all
491  * variant spellings of such a construct behave the same. Again, we can
492  * stick on a RelabelType to force the right exposed collation. (It might
493  * work to not label the collation at all in EC members, but this is risky
494  * since some parts of the system expect exprCollation() to deliver the
495  * right answer for a sort key.)
496  */
497 Expr *
498 canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
499 {
500  Oid expr_type = exprType((Node *) expr);
501 
502  /*
503  * For a polymorphic-input-type opclass, just keep the same exposed type.
504  * RECORD opclasses work like polymorphic-type ones for this purpose.
505  */
506  if (IsPolymorphicType(req_type) || req_type == RECORDOID)
507  req_type = expr_type;
508 
509  /*
510  * No work if the expression exposes the right type/collation already.
511  */
512  if (expr_type != req_type ||
513  exprCollation((Node *) expr) != req_collation)
514  {
515  /*
516  * If we have to change the type of the expression, set typmod to -1,
517  * since the new type may not have the same typmod interpretation.
518  * When we only have to change collation, preserve the exposed typmod.
519  */
520  int32 req_typmod;
521 
522  if (expr_type != req_type)
523  req_typmod = -1;
524  else
525  req_typmod = exprTypmod((Node *) expr);
526 
527  /*
528  * Use applyRelabelType so that we preserve const-flatness. This is
529  * important since eval_const_expressions has already been applied.
530  */
531  expr = (Expr *) applyRelabelType((Node *) expr,
532  req_type, req_typmod, req_collation,
533  COERCE_IMPLICIT_CAST, -1, false);
534  }
535 
536  return expr;
537 }
538 
539 /*
540  * add_eq_member - build a new EquivalenceMember and add it to an EC
541  */
542 static EquivalenceMember *
544  Relids nullable_relids, bool is_child, Oid datatype)
545 {
547 
548  em->em_expr = expr;
549  em->em_relids = relids;
550  em->em_nullable_relids = nullable_relids;
551  em->em_is_const = false;
552  em->em_is_child = is_child;
553  em->em_datatype = datatype;
554 
555  if (bms_is_empty(relids))
556  {
557  /*
558  * No Vars, assume it's a pseudoconstant. This is correct for entries
559  * generated from process_equivalence(), because a WHERE clause can't
560  * contain aggregates or SRFs, and non-volatility was checked before
561  * process_equivalence() ever got called. But
562  * get_eclass_for_sort_expr() has to work harder. We put the tests
563  * there not here to save cycles in the equivalence case.
564  */
565  Assert(!is_child);
566  em->em_is_const = true;
567  ec->ec_has_const = true;
568  /* it can't affect ec_relids */
569  }
570  else if (!is_child) /* child members don't add to ec_relids */
571  {
572  ec->ec_relids = bms_add_members(ec->ec_relids, relids);
573  }
574  ec->ec_members = lappend(ec->ec_members, em);
575 
576  return em;
577 }
578 
579 
580 /*
581  * get_eclass_for_sort_expr
582  * Given an expression and opfamily/collation info, find an existing
583  * equivalence class it is a member of; if none, optionally build a new
584  * single-member EquivalenceClass for it.
585  *
586  * expr is the expression, and nullable_relids is the set of base relids
587  * that are potentially nullable below it. We actually only care about
588  * the set of such relids that are used in the expression; but for caller
589  * convenience, we perform that intersection step here. The caller need
590  * only be sure that nullable_relids doesn't omit any nullable rels that
591  * might appear in the expr.
592  *
593  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
594  * or zero if not. (It should never be zero if the expression is volatile!)
595  *
596  * If rel is not NULL, it identifies a specific relation we're considering
597  * a path for, and indicates that child EC members for that relation can be
598  * considered. Otherwise child members are ignored. (Note: since child EC
599  * members aren't guaranteed unique, a non-NULL value means that there could
600  * be more than one EC that matches the expression; if so it's order-dependent
601  * which one you get. This is annoying but it only happens in corner cases,
602  * so for now we live with just reporting the first match. See also
603  * generate_implied_equalities_for_column and match_pathkeys_to_index.)
604  *
605  * If create_it is true, we'll build a new EquivalenceClass when there is no
606  * match. If create_it is false, we just return NULL when no match.
607  *
608  * This can be used safely both before and after EquivalenceClass merging;
609  * since it never causes merging it does not invalidate any existing ECs
610  * or PathKeys. However, ECs added after path generation has begun are
611  * of limited usefulness, so usually it's best to create them beforehand.
612  *
613  * Note: opfamilies must be chosen consistently with the way
614  * process_equivalence() would do; that is, generated from a mergejoinable
615  * equality operator. Else we might fail to detect valid equivalences,
616  * generating poor (but not incorrect) plans.
617  */
620  Expr *expr,
621  Relids nullable_relids,
622  List *opfamilies,
623  Oid opcintype,
624  Oid collation,
625  Index sortref,
626  Relids rel,
627  bool create_it)
628 {
629  Relids expr_relids;
630  EquivalenceClass *newec;
631  EquivalenceMember *newem;
632  ListCell *lc1;
633  MemoryContext oldcontext;
634 
635  /*
636  * Ensure the expression exposes the correct type and collation.
637  */
638  expr = canonicalize_ec_expression(expr, opcintype, collation);
639 
640  /*
641  * Scan through the existing EquivalenceClasses for a match
642  */
643  foreach(lc1, root->eq_classes)
644  {
645  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
646  ListCell *lc2;
647 
648  /*
649  * Never match to a volatile EC, except when we are looking at another
650  * reference to the same volatile SortGroupClause.
651  */
652  if (cur_ec->ec_has_volatile &&
653  (sortref == 0 || sortref != cur_ec->ec_sortref))
654  continue;
655 
656  if (collation != cur_ec->ec_collation)
657  continue;
658  if (!equal(opfamilies, cur_ec->ec_opfamilies))
659  continue;
660 
661  foreach(lc2, cur_ec->ec_members)
662  {
663  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
664 
665  /*
666  * Ignore child members unless they match the request.
667  */
668  if (cur_em->em_is_child &&
669  !bms_equal(cur_em->em_relids, rel))
670  continue;
671 
672  /*
673  * If below an outer join, don't match constants: they're not as
674  * constant as they look.
675  */
676  if (cur_ec->ec_below_outer_join &&
677  cur_em->em_is_const)
678  continue;
679 
680  if (opcintype == cur_em->em_datatype &&
681  equal(expr, cur_em->em_expr))
682  return cur_ec; /* Match! */
683  }
684  }
685 
686  /* No match; does caller want a NULL result? */
687  if (!create_it)
688  return NULL;
689 
690  /*
691  * OK, build a new single-member EC
692  *
693  * Here, we must be sure that we construct the EC in the right context.
694  */
695  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
696 
697  newec = makeNode(EquivalenceClass);
698  newec->ec_opfamilies = list_copy(opfamilies);
699  newec->ec_collation = collation;
700  newec->ec_members = NIL;
701  newec->ec_sources = NIL;
702  newec->ec_derives = NIL;
703  newec->ec_relids = NULL;
704  newec->ec_has_const = false;
706  newec->ec_below_outer_join = false;
707  newec->ec_broken = false;
708  newec->ec_sortref = sortref;
709  newec->ec_min_security = UINT_MAX;
710  newec->ec_max_security = 0;
711  newec->ec_merged = NULL;
712 
713  if (newec->ec_has_volatile && sortref == 0) /* should not happen */
714  elog(ERROR, "volatile EquivalenceClass has no sortref");
715 
716  /*
717  * Get the precise set of nullable relids appearing in the expression.
718  */
719  expr_relids = pull_varnos((Node *) expr);
720  nullable_relids = bms_intersect(nullable_relids, expr_relids);
721 
722  newem = add_eq_member(newec, copyObject(expr), expr_relids,
723  nullable_relids, false, opcintype);
724 
725  /*
726  * add_eq_member doesn't check for volatile functions, set-returning
727  * functions, aggregates, or window functions, but such could appear in
728  * sort expressions; so we have to check whether its const-marking was
729  * correct.
730  */
731  if (newec->ec_has_const)
732  {
733  if (newec->ec_has_volatile ||
734  expression_returns_set((Node *) expr) ||
735  contain_agg_clause((Node *) expr) ||
736  contain_window_function((Node *) expr))
737  {
738  newec->ec_has_const = false;
739  newem->em_is_const = false;
740  }
741  }
742 
743  root->eq_classes = lappend(root->eq_classes, newec);
744 
745  /*
746  * If EC merging is already complete, we have to mop up by adding the new
747  * EC to the eclass_indexes of the relation(s) mentioned in it.
748  */
749  if (root->ec_merging_done)
750  {
751  int ec_index = list_length(root->eq_classes) - 1;
752  int i = -1;
753 
754  while ((i = bms_next_member(newec->ec_relids, i)) > 0)
755  {
756  RelOptInfo *rel = root->simple_rel_array[i];
757 
758  Assert(rel->reloptkind == RELOPT_BASEREL ||
759  rel->reloptkind == RELOPT_DEADREL);
760 
762  ec_index);
763  }
764  }
765 
766  MemoryContextSwitchTo(oldcontext);
767 
768  return newec;
769 }
770 
771 /*
772  * Find an equivalence class member expression, all of whose Vars, come from
773  * the indicated relation.
774  */
775 Expr *
777 {
778  ListCell *lc_em;
779 
780  foreach(lc_em, ec->ec_members)
781  {
782  EquivalenceMember *em = lfirst(lc_em);
783 
784  if (bms_is_subset(em->em_relids, rel->relids) &&
785  !bms_is_empty(em->em_relids))
786  {
787  /*
788  * If there is more than one equivalence member whose Vars are
789  * taken entirely from this relation, we'll be content to choose
790  * any one of those.
791  */
792  return em->em_expr;
793  }
794  }
795 
796  /* We didn't find any suitable equivalence class expression */
797  return NULL;
798 }
799 
800 /*
801  * Find an equivalence class member expression that can be safely used to build
802  * a sort node using the provided relation. The rules are a subset of those
803  * applied in prepare_sort_from_pathkeys since that function deals with sorts
804  * that must be delayed until the last stages of query execution, while here
805  * we only care about proactive sorts.
806  */
807 Expr *
809  RelOptInfo *rel, bool require_parallel_safe)
810 {
811  ListCell *lc_em;
812 
813  /*
814  * If there is more than one equivalence member matching these
815  * requirements we'll be content to choose any one of them.
816  */
817  foreach(lc_em, ec->ec_members)
818  {
819  EquivalenceMember *em = lfirst(lc_em);
820  Expr *em_expr = em->em_expr;
821 
822  /*
823  * We shouldn't be trying to sort by an equivalence class that
824  * contains a constant, so no need to consider such cases any further.
825  */
826  if (em->em_is_const)
827  continue;
828 
829  /*
830  * Any Vars in the equivalence class member need to come from this
831  * relation. This is a superset of prepare_sort_from_pathkeys ignoring
832  * child members unless they belong to the rel being sorted.
833  */
834  if (!bms_is_subset(em->em_relids, rel->relids))
835  continue;
836 
837  /*
838  * If requested, reject expressions that are not parallel-safe.
839  */
840  if (require_parallel_safe && !is_parallel_safe(root, (Node *) em_expr))
841  continue;
842 
843  /*
844  * Disallow SRFs so that all of them can be evaluated at the correct
845  * time as determined by make_sort_input_target.
846  */
847  if (IS_SRF_CALL((Node *) em_expr))
848  continue;
849 
850  /*
851  * As long as the expression isn't volatile then
852  * prepare_sort_from_pathkeys is able to generate a new target entry,
853  * so there's no need to verify that one already exists.
854  *
855  * While prepare_sort_from_pathkeys has to be concerned about matching
856  * up a volatile expression to the proper tlist entry, it doesn't seem
857  * valuable here to expend the work trying to find a match in the
858  * target's exprs since such a sort will have to be postponed anyway.
859  */
860  if (!ec->ec_has_volatile)
861  return em->em_expr;
862  }
863 
864  /* We didn't find any suitable equivalence class expression */
865  return NULL;
866 }
867 
868 /*
869  * generate_base_implied_equalities
870  * Generate any restriction clauses that we can deduce from equivalence
871  * classes.
872  *
873  * When an EC contains pseudoconstants, our strategy is to generate
874  * "member = const1" clauses where const1 is the first constant member, for
875  * every other member (including other constants). If we are able to do this
876  * then we don't need any "var = var" comparisons because we've successfully
877  * constrained all the vars at their points of creation. If we fail to
878  * generate any of these clauses due to lack of cross-type operators, we fall
879  * back to the "ec_broken" strategy described below. (XXX if there are
880  * multiple constants of different types, it's possible that we might succeed
881  * in forming all the required clauses if we started from a different const
882  * member; but this seems a sufficiently hokey corner case to not be worth
883  * spending lots of cycles on.)
884  *
885  * For ECs that contain no pseudoconstants, we generate derived clauses
886  * "member1 = member2" for each pair of members belonging to the same base
887  * relation (actually, if there are more than two for the same base relation,
888  * we only need enough clauses to link each to each other). This provides
889  * the base case for the recursion: each row emitted by a base relation scan
890  * will constrain all computable members of the EC to be equal. As each
891  * join path is formed, we'll add additional derived clauses on-the-fly
892  * to maintain this invariant (see generate_join_implied_equalities).
893  *
894  * If the opfamilies used by the EC do not provide complete sets of cross-type
895  * equality operators, it is possible that we will fail to generate a clause
896  * that must be generated to maintain the invariant. (An example: given
897  * "WHERE a.x = b.y AND b.y = a.z", the scheme breaks down if we cannot
898  * generate "a.x = a.z" as a restriction clause for A.) In this case we mark
899  * the EC "ec_broken" and fall back to regurgitating its original source
900  * RestrictInfos at appropriate times. We do not try to retract any derived
901  * clauses already generated from the broken EC, so the resulting plan could
902  * be poor due to bad selectivity estimates caused by redundant clauses. But
903  * the correct solution to that is to fix the opfamilies ...
904  *
905  * Equality clauses derived by this function are passed off to
906  * process_implied_equality (in plan/initsplan.c) to be inserted into the
907  * restrictinfo datastructures. Note that this must be called after initial
908  * scanning of the quals and before Path construction begins.
909  *
910  * We make no attempt to avoid generating duplicate RestrictInfos here: we
911  * don't search ec_sources or ec_derives for matches. It doesn't really
912  * seem worth the trouble to do so.
913  */
914 void
916 {
917  int ec_index;
918  ListCell *lc;
919 
920  /*
921  * At this point, we're done absorbing knowledge of equivalences in the
922  * query, so no further EC merging should happen, and ECs remaining in the
923  * eq_classes list can be considered canonical. (But note that it's still
924  * possible for new single-member ECs to be added through
925  * get_eclass_for_sort_expr().)
926  */
927  root->ec_merging_done = true;
928 
929  ec_index = 0;
930  foreach(lc, root->eq_classes)
931  {
933  bool can_generate_joinclause = false;
934  int i;
935 
936  Assert(ec->ec_merged == NULL); /* else shouldn't be in list */
937  Assert(!ec->ec_broken); /* not yet anyway... */
938 
939  /*
940  * Generate implied equalities that are restriction clauses.
941  * Single-member ECs won't generate any deductions, either here or at
942  * the join level.
943  */
944  if (list_length(ec->ec_members) > 1)
945  {
946  if (ec->ec_has_const)
948  else
950 
951  /* Recover if we failed to generate required derived clauses */
952  if (ec->ec_broken)
954 
955  /* Detect whether this EC might generate join clauses */
956  can_generate_joinclause =
958  }
959 
960  /*
961  * Mark the base rels cited in each eclass (which should all exist by
962  * now) with the eq_classes indexes of all eclasses mentioning them.
963  * This will let us avoid searching in subsequent lookups. While
964  * we're at it, we can mark base rels that have pending eclass joins;
965  * this is a cheap version of has_relevant_eclass_joinclause().
966  */
967  i = -1;
968  while ((i = bms_next_member(ec->ec_relids, i)) > 0)
969  {
970  RelOptInfo *rel = root->simple_rel_array[i];
971 
973 
975  ec_index);
976 
977  if (can_generate_joinclause)
978  rel->has_eclass_joins = true;
979  }
980 
981  ec_index++;
982  }
983 }
984 
985 /*
986  * generate_base_implied_equalities when EC contains pseudoconstant(s)
987  */
988 static void
990  EquivalenceClass *ec)
991 {
992  EquivalenceMember *const_em = NULL;
993  ListCell *lc;
994 
995  /*
996  * In the trivial case where we just had one "var = const" clause, push
997  * the original clause back into the main planner machinery. There is
998  * nothing to be gained by doing it differently, and we save the effort to
999  * re-build and re-analyze an equality clause that will be exactly
1000  * equivalent to the old one.
1001  */
1002  if (list_length(ec->ec_members) == 2 &&
1003  list_length(ec->ec_sources) == 1)
1004  {
1005  RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
1006 
1007  if (bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
1008  {
1009  distribute_restrictinfo_to_rels(root, restrictinfo);
1010  return;
1011  }
1012  }
1013 
1014  /*
1015  * Find the constant member to use. We prefer an actual constant to
1016  * pseudo-constants (such as Params), because the constraint exclusion
1017  * machinery might be able to exclude relations on the basis of generated
1018  * "var = const" equalities, but "var = param" won't work for that.
1019  */
1020  foreach(lc, ec->ec_members)
1021  {
1022  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1023 
1024  if (cur_em->em_is_const)
1025  {
1026  const_em = cur_em;
1027  if (IsA(cur_em->em_expr, Const))
1028  break;
1029  }
1030  }
1031  Assert(const_em != NULL);
1032 
1033  /* Generate a derived equality against each other member */
1034  foreach(lc, ec->ec_members)
1035  {
1036  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1037  Oid eq_op;
1038  RestrictInfo *rinfo;
1039 
1040  Assert(!cur_em->em_is_child); /* no children yet */
1041  if (cur_em == const_em)
1042  continue;
1043  eq_op = select_equality_operator(ec,
1044  cur_em->em_datatype,
1045  const_em->em_datatype);
1046  if (!OidIsValid(eq_op))
1047  {
1048  /* failed... */
1049  ec->ec_broken = true;
1050  break;
1051  }
1052  rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
1053  cur_em->em_expr, const_em->em_expr,
1054  bms_copy(ec->ec_relids),
1055  bms_union(cur_em->em_nullable_relids,
1056  const_em->em_nullable_relids),
1057  ec->ec_min_security,
1058  ec->ec_below_outer_join,
1059  cur_em->em_is_const);
1060 
1061  /*
1062  * If the clause didn't degenerate to a constant, fill in the correct
1063  * markings for a mergejoinable clause, and save it in ec_derives. (We
1064  * will not re-use such clauses directly, but selectivity estimation
1065  * may consult the list later. Note that this use of ec_derives does
1066  * not overlap with its use for join clauses, since we never generate
1067  * join clauses from an ec_has_const eclass.)
1068  */
1069  if (rinfo && rinfo->mergeopfamilies)
1070  {
1071  /* it's not redundant, so don't set parent_ec */
1072  rinfo->left_ec = rinfo->right_ec = ec;
1073  rinfo->left_em = cur_em;
1074  rinfo->right_em = const_em;
1075  ec->ec_derives = lappend(ec->ec_derives, rinfo);
1076  }
1077  }
1078 }
1079 
1080 /*
1081  * generate_base_implied_equalities when EC contains no pseudoconstants
1082  */
1083 static void
1085  EquivalenceClass *ec)
1086 {
1087  EquivalenceMember **prev_ems;
1088  ListCell *lc;
1089 
1090  /*
1091  * We scan the EC members once and track the last-seen member for each
1092  * base relation. When we see another member of the same base relation,
1093  * we generate "prev_em = cur_em". This results in the minimum number of
1094  * derived clauses, but it's possible that it will fail when a different
1095  * ordering would succeed. XXX FIXME: use a UNION-FIND algorithm similar
1096  * to the way we build merged ECs. (Use a list-of-lists for each rel.)
1097  */
1098  prev_ems = (EquivalenceMember **)
1099  palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
1100 
1101  foreach(lc, ec->ec_members)
1102  {
1103  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1104  int relid;
1105 
1106  Assert(!cur_em->em_is_child); /* no children yet */
1107  if (!bms_get_singleton_member(cur_em->em_relids, &relid))
1108  continue;
1109  Assert(relid < root->simple_rel_array_size);
1110 
1111  if (prev_ems[relid] != NULL)
1112  {
1113  EquivalenceMember *prev_em = prev_ems[relid];
1114  Oid eq_op;
1115  RestrictInfo *rinfo;
1116 
1117  eq_op = select_equality_operator(ec,
1118  prev_em->em_datatype,
1119  cur_em->em_datatype);
1120  if (!OidIsValid(eq_op))
1121  {
1122  /* failed... */
1123  ec->ec_broken = true;
1124  break;
1125  }
1126  rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
1127  prev_em->em_expr, cur_em->em_expr,
1128  bms_copy(ec->ec_relids),
1129  bms_union(prev_em->em_nullable_relids,
1130  cur_em->em_nullable_relids),
1131  ec->ec_min_security,
1132  ec->ec_below_outer_join,
1133  false);
1134 
1135  /*
1136  * If the clause didn't degenerate to a constant, fill in the
1137  * correct markings for a mergejoinable clause. We don't put it
1138  * in ec_derives however; we don't currently need to re-find such
1139  * clauses, and we don't want to clutter that list with non-join
1140  * clauses.
1141  */
1142  if (rinfo && rinfo->mergeopfamilies)
1143  {
1144  /* it's not redundant, so don't set parent_ec */
1145  rinfo->left_ec = rinfo->right_ec = ec;
1146  rinfo->left_em = prev_em;
1147  rinfo->right_em = cur_em;
1148  }
1149  }
1150  prev_ems[relid] = cur_em;
1151  }
1152 
1153  pfree(prev_ems);
1154 
1155  /*
1156  * We also have to make sure that all the Vars used in the member clauses
1157  * will be available at any join node we might try to reference them at.
1158  * For the moment we force all the Vars to be available at all join nodes
1159  * for this eclass. Perhaps this could be improved by doing some
1160  * pre-analysis of which members we prefer to join, but it's no worse than
1161  * what happened in the pre-8.3 code.
1162  */
1163  foreach(lc, ec->ec_members)
1164  {
1165  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1166  List *vars = pull_var_clause((Node *) cur_em->em_expr,
1170 
1171  add_vars_to_targetlist(root, vars, ec->ec_relids, false);
1172  list_free(vars);
1173  }
1174 }
1175 
1176 /*
1177  * generate_base_implied_equalities cleanup after failure
1178  *
1179  * What we must do here is push any zero- or one-relation source RestrictInfos
1180  * of the EC back into the main restrictinfo datastructures. Multi-relation
1181  * clauses will be regurgitated later by generate_join_implied_equalities().
1182  * (We do it this way to maintain continuity with the case that ec_broken
1183  * becomes set only after we've gone up a join level or two.) However, for
1184  * an EC that contains constants, we can adopt a simpler strategy and just
1185  * throw back all the source RestrictInfos immediately; that works because
1186  * we know that such an EC can't become broken later. (This rule justifies
1187  * ignoring ec_has_const ECs in generate_join_implied_equalities, even when
1188  * they are broken.)
1189  */
1190 static void
1192  EquivalenceClass *ec)
1193 {
1194  ListCell *lc;
1195 
1196  foreach(lc, ec->ec_sources)
1197  {
1198  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
1199 
1200  if (ec->ec_has_const ||
1201  bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
1202  distribute_restrictinfo_to_rels(root, restrictinfo);
1203  }
1204 }
1205 
1206 
1207 /*
1208  * generate_join_implied_equalities
1209  * Generate any join clauses that we can deduce from equivalence classes.
1210  *
1211  * At a join node, we must enforce restriction clauses sufficient to ensure
1212  * that all equivalence-class members computable at that node are equal.
1213  * Since the set of clauses to enforce can vary depending on which subset
1214  * relations are the inputs, we have to compute this afresh for each join
1215  * relation pair. Hence a fresh List of RestrictInfo nodes is built and
1216  * passed back on each call.
1217  *
1218  * In addition to its use at join nodes, this can be applied to generate
1219  * eclass-based join clauses for use in a parameterized scan of a base rel.
1220  * The reason for the asymmetry of specifying the inner rel as a RelOptInfo
1221  * and the outer rel by Relids is that this usage occurs before we have
1222  * built any join RelOptInfos.
1223  *
1224  * An annoying special case for parameterized scans is that the inner rel can
1225  * be an appendrel child (an "other rel"). In this case we must generate
1226  * appropriate clauses using child EC members. add_child_rel_equivalences
1227  * must already have been done for the child rel.
1228  *
1229  * The results are sufficient for use in merge, hash, and plain nestloop join
1230  * methods. We do not worry here about selecting clauses that are optimal
1231  * for use in a parameterized indexscan. indxpath.c makes its own selections
1232  * of clauses to use, and if the ones we pick here are redundant with those,
1233  * the extras will be eliminated at createplan time, using the parent_ec
1234  * markers that we provide (see is_redundant_derived_clause()).
1235  *
1236  * Because the same join clauses are likely to be needed multiple times as
1237  * we consider different join paths, we avoid generating multiple copies:
1238  * whenever we select a particular pair of EquivalenceMembers to join,
1239  * we check to see if the pair matches any original clause (in ec_sources)
1240  * or previously-built clause (in ec_derives). This saves memory and allows
1241  * re-use of information cached in RestrictInfos.
1242  *
1243  * join_relids should always equal bms_union(outer_relids, inner_rel->relids).
1244  * We could simplify this function's API by computing it internally, but in
1245  * most current uses, the caller has the value at hand anyway.
1246  */
1247 List *
1249  Relids join_relids,
1250  Relids outer_relids,
1251  RelOptInfo *inner_rel)
1252 {
1253  List *result = NIL;
1254  Relids inner_relids = inner_rel->relids;
1255  Relids nominal_inner_relids;
1256  Relids nominal_join_relids;
1257  Bitmapset *matching_ecs;
1258  int i;
1259 
1260  /* If inner rel is a child, extra setup work is needed */
1261  if (IS_OTHER_REL(inner_rel))
1262  {
1263  Assert(!bms_is_empty(inner_rel->top_parent_relids));
1264 
1265  /* Fetch relid set for the topmost parent rel */
1266  nominal_inner_relids = inner_rel->top_parent_relids;
1267  /* ECs will be marked with the parent's relid, not the child's */
1268  nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1269  }
1270  else
1271  {
1272  nominal_inner_relids = inner_relids;
1273  nominal_join_relids = join_relids;
1274  }
1275 
1276  /*
1277  * Get all eclasses that mention both inner and outer sides of the join
1278  */
1279  matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
1280  outer_relids);
1281 
1282  i = -1;
1283  while ((i = bms_next_member(matching_ecs, i)) >= 0)
1284  {
1286  List *sublist = NIL;
1287 
1288  /* ECs containing consts do not need any further enforcement */
1289  if (ec->ec_has_const)
1290  continue;
1291 
1292  /* Single-member ECs won't generate any deductions */
1293  if (list_length(ec->ec_members) <= 1)
1294  continue;
1295 
1296  /* Sanity check that this eclass overlaps the join */
1297  Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
1298 
1299  if (!ec->ec_broken)
1301  ec,
1302  join_relids,
1303  outer_relids,
1304  inner_relids);
1305 
1306  /* Recover if we failed to generate required derived clauses */
1307  if (ec->ec_broken)
1309  ec,
1310  nominal_join_relids,
1311  outer_relids,
1312  nominal_inner_relids,
1313  inner_rel);
1314 
1315  result = list_concat(result, sublist);
1316  }
1317 
1318  return result;
1319 }
1320 
1321 /*
1322  * generate_join_implied_equalities_for_ecs
1323  * As above, but consider only the listed ECs.
1324  */
1325 List *
1327  List *eclasses,
1328  Relids join_relids,
1329  Relids outer_relids,
1330  RelOptInfo *inner_rel)
1331 {
1332  List *result = NIL;
1333  Relids inner_relids = inner_rel->relids;
1334  Relids nominal_inner_relids;
1335  Relids nominal_join_relids;
1336  ListCell *lc;
1337 
1338  /* If inner rel is a child, extra setup work is needed */
1339  if (IS_OTHER_REL(inner_rel))
1340  {
1341  Assert(!bms_is_empty(inner_rel->top_parent_relids));
1342 
1343  /* Fetch relid set for the topmost parent rel */
1344  nominal_inner_relids = inner_rel->top_parent_relids;
1345  /* ECs will be marked with the parent's relid, not the child's */
1346  nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1347  }
1348  else
1349  {
1350  nominal_inner_relids = inner_relids;
1351  nominal_join_relids = join_relids;
1352  }
1353 
1354  foreach(lc, eclasses)
1355  {
1357  List *sublist = NIL;
1358 
1359  /* ECs containing consts do not need any further enforcement */
1360  if (ec->ec_has_const)
1361  continue;
1362 
1363  /* Single-member ECs won't generate any deductions */
1364  if (list_length(ec->ec_members) <= 1)
1365  continue;
1366 
1367  /* We can quickly ignore any that don't overlap the join, too */
1368  if (!bms_overlap(ec->ec_relids, nominal_join_relids))
1369  continue;
1370 
1371  if (!ec->ec_broken)
1373  ec,
1374  join_relids,
1375  outer_relids,
1376  inner_relids);
1377 
1378  /* Recover if we failed to generate required derived clauses */
1379  if (ec->ec_broken)
1381  ec,
1382  nominal_join_relids,
1383  outer_relids,
1384  nominal_inner_relids,
1385  inner_rel);
1386 
1387  result = list_concat(result, sublist);
1388  }
1389 
1390  return result;
1391 }
1392 
1393 /*
1394  * generate_join_implied_equalities for a still-valid EC
1395  */
1396 static List *
1398  EquivalenceClass *ec,
1399  Relids join_relids,
1400  Relids outer_relids,
1401  Relids inner_relids)
1402 {
1403  List *result = NIL;
1404  List *new_members = NIL;
1405  List *outer_members = NIL;
1406  List *inner_members = NIL;
1407  ListCell *lc1;
1408 
1409  /*
1410  * First, scan the EC to identify member values that are computable at the
1411  * outer rel, at the inner rel, or at this relation but not in either
1412  * input rel. The outer-rel members should already be enforced equal,
1413  * likewise for the inner-rel members. We'll need to create clauses to
1414  * enforce that any newly computable members are all equal to each other
1415  * as well as to at least one input member, plus enforce at least one
1416  * outer-rel member equal to at least one inner-rel member.
1417  */
1418  foreach(lc1, ec->ec_members)
1419  {
1420  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
1421 
1422  /*
1423  * We don't need to check explicitly for child EC members. This test
1424  * against join_relids will cause them to be ignored except when
1425  * considering a child inner rel, which is what we want.
1426  */
1427  if (!bms_is_subset(cur_em->em_relids, join_relids))
1428  continue; /* not computable yet, or wrong child */
1429 
1430  if (bms_is_subset(cur_em->em_relids, outer_relids))
1431  outer_members = lappend(outer_members, cur_em);
1432  else if (bms_is_subset(cur_em->em_relids, inner_relids))
1433  inner_members = lappend(inner_members, cur_em);
1434  else
1435  new_members = lappend(new_members, cur_em);
1436  }
1437 
1438  /*
1439  * First, select the joinclause if needed. We can equate any one outer
1440  * member to any one inner member, but we have to find a datatype
1441  * combination for which an opfamily member operator exists. If we have
1442  * choices, we prefer simple Var members (possibly with RelabelType) since
1443  * these are (a) cheapest to compute at runtime and (b) most likely to
1444  * have useful statistics. Also, prefer operators that are also
1445  * hashjoinable.
1446  */
1447  if (outer_members && inner_members)
1448  {
1449  EquivalenceMember *best_outer_em = NULL;
1450  EquivalenceMember *best_inner_em = NULL;
1451  Oid best_eq_op = InvalidOid;
1452  int best_score = -1;
1453  RestrictInfo *rinfo;
1454 
1455  foreach(lc1, outer_members)
1456  {
1457  EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
1458  ListCell *lc2;
1459 
1460  foreach(lc2, inner_members)
1461  {
1462  EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
1463  Oid eq_op;
1464  int score;
1465 
1466  eq_op = select_equality_operator(ec,
1467  outer_em->em_datatype,
1468  inner_em->em_datatype);
1469  if (!OidIsValid(eq_op))
1470  continue;
1471  score = 0;
1472  if (IsA(outer_em->em_expr, Var) ||
1473  (IsA(outer_em->em_expr, RelabelType) &&
1474  IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1475  score++;
1476  if (IsA(inner_em->em_expr, Var) ||
1477  (IsA(inner_em->em_expr, RelabelType) &&
1478  IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
1479  score++;
1480  if (op_hashjoinable(eq_op,
1481  exprType((Node *) outer_em->em_expr)))
1482  score++;
1483  if (score > best_score)
1484  {
1485  best_outer_em = outer_em;
1486  best_inner_em = inner_em;
1487  best_eq_op = eq_op;
1488  best_score = score;
1489  if (best_score == 3)
1490  break; /* no need to look further */
1491  }
1492  }
1493  if (best_score == 3)
1494  break; /* no need to look further */
1495  }
1496  if (best_score < 0)
1497  {
1498  /* failed... */
1499  ec->ec_broken = true;
1500  return NIL;
1501  }
1502 
1503  /*
1504  * Create clause, setting parent_ec to mark it as redundant with other
1505  * joinclauses
1506  */
1507  rinfo = create_join_clause(root, ec, best_eq_op,
1508  best_outer_em, best_inner_em,
1509  ec);
1510 
1511  result = lappend(result, rinfo);
1512  }
1513 
1514  /*
1515  * Now deal with building restrictions for any expressions that involve
1516  * Vars from both sides of the join. We have to equate all of these to
1517  * each other as well as to at least one old member (if any).
1518  *
1519  * XXX as in generate_base_implied_equalities_no_const, we could be a lot
1520  * smarter here to avoid unnecessary failures in cross-type situations.
1521  * For now, use the same left-to-right method used there.
1522  */
1523  if (new_members)
1524  {
1525  List *old_members = list_concat(outer_members, inner_members);
1526  EquivalenceMember *prev_em = NULL;
1527  RestrictInfo *rinfo;
1528 
1529  /* For now, arbitrarily take the first old_member as the one to use */
1530  if (old_members)
1531  new_members = lappend(new_members, linitial(old_members));
1532 
1533  foreach(lc1, new_members)
1534  {
1535  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
1536 
1537  if (prev_em != NULL)
1538  {
1539  Oid eq_op;
1540 
1541  eq_op = select_equality_operator(ec,
1542  prev_em->em_datatype,
1543  cur_em->em_datatype);
1544  if (!OidIsValid(eq_op))
1545  {
1546  /* failed... */
1547  ec->ec_broken = true;
1548  return NIL;
1549  }
1550  /* do NOT set parent_ec, this qual is not redundant! */
1551  rinfo = create_join_clause(root, ec, eq_op,
1552  prev_em, cur_em,
1553  NULL);
1554 
1555  result = lappend(result, rinfo);
1556  }
1557  prev_em = cur_em;
1558  }
1559  }
1560 
1561  return result;
1562 }
1563 
1564 /*
1565  * generate_join_implied_equalities cleanup after failure
1566  *
1567  * Return any original RestrictInfos that are enforceable at this join.
1568  *
1569  * In the case of a child inner relation, we have to translate the
1570  * original RestrictInfos from parent to child Vars.
1571  */
1572 static List *
1574  EquivalenceClass *ec,
1575  Relids nominal_join_relids,
1576  Relids outer_relids,
1577  Relids nominal_inner_relids,
1578  RelOptInfo *inner_rel)
1579 {
1580  List *result = NIL;
1581  ListCell *lc;
1582 
1583  foreach(lc, ec->ec_sources)
1584  {
1585  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
1586  Relids clause_relids = restrictinfo->required_relids;
1587 
1588  if (bms_is_subset(clause_relids, nominal_join_relids) &&
1589  !bms_is_subset(clause_relids, outer_relids) &&
1590  !bms_is_subset(clause_relids, nominal_inner_relids))
1591  result = lappend(result, restrictinfo);
1592  }
1593 
1594  /*
1595  * If we have to translate, just brute-force apply adjust_appendrel_attrs
1596  * to all the RestrictInfos at once. This will result in returning
1597  * RestrictInfos that are not listed in ec_derives, but there shouldn't be
1598  * any duplication, and it's a sufficiently narrow corner case that we
1599  * shouldn't sweat too much over it anyway.
1600  *
1601  * Since inner_rel might be an indirect descendant of the baserel
1602  * mentioned in the ec_sources clauses, we have to be prepared to apply
1603  * multiple levels of Var translation.
1604  */
1605  if (IS_OTHER_REL(inner_rel) && result != NIL)
1606  result = (List *) adjust_appendrel_attrs_multilevel(root,
1607  (Node *) result,
1608  inner_rel->relids,
1609  inner_rel->top_parent_relids);
1610 
1611  return result;
1612 }
1613 
1614 
1615 /*
1616  * select_equality_operator
1617  * Select a suitable equality operator for comparing two EC members
1618  *
1619  * Returns InvalidOid if no operator can be found for this datatype combination
1620  */
1621 static Oid
1623 {
1624  ListCell *lc;
1625 
1626  foreach(lc, ec->ec_opfamilies)
1627  {
1628  Oid opfamily = lfirst_oid(lc);
1629  Oid opno;
1630 
1631  opno = get_opfamily_member(opfamily, lefttype, righttype,
1633  if (!OidIsValid(opno))
1634  continue;
1635  /* If no barrier quals in query, don't worry about leaky operators */
1636  if (ec->ec_max_security == 0)
1637  return opno;
1638  /* Otherwise, insist that selected operators be leakproof */
1639  if (get_func_leakproof(get_opcode(opno)))
1640  return opno;
1641  }
1642  return InvalidOid;
1643 }
1644 
1645 
1646 /*
1647  * create_join_clause
1648  * Find or make a RestrictInfo comparing the two given EC members
1649  * with the given operator.
1650  *
1651  * parent_ec is either equal to ec (if the clause is a potentially-redundant
1652  * join clause) or NULL (if not). We have to treat this as part of the
1653  * match requirements --- it's possible that a clause comparing the same two
1654  * EMs is a join clause in one join path and a restriction clause in another.
1655  */
1656 static RestrictInfo *
1658  EquivalenceClass *ec, Oid opno,
1659  EquivalenceMember *leftem,
1660  EquivalenceMember *rightem,
1661  EquivalenceClass *parent_ec)
1662 {
1663  RestrictInfo *rinfo;
1664  ListCell *lc;
1665  MemoryContext oldcontext;
1666 
1667  /*
1668  * Search to see if we already built a RestrictInfo for this pair of
1669  * EquivalenceMembers. We can use either original source clauses or
1670  * previously-derived clauses. The check on opno is probably redundant,
1671  * but be safe ...
1672  */
1673  foreach(lc, ec->ec_sources)
1674  {
1675  rinfo = (RestrictInfo *) lfirst(lc);
1676  if (rinfo->left_em == leftem &&
1677  rinfo->right_em == rightem &&
1678  rinfo->parent_ec == parent_ec &&
1679  opno == ((OpExpr *) rinfo->clause)->opno)
1680  return rinfo;
1681  }
1682 
1683  foreach(lc, ec->ec_derives)
1684  {
1685  rinfo = (RestrictInfo *) lfirst(lc);
1686  if (rinfo->left_em == leftem &&
1687  rinfo->right_em == rightem &&
1688  rinfo->parent_ec == parent_ec &&
1689  opno == ((OpExpr *) rinfo->clause)->opno)
1690  return rinfo;
1691  }
1692 
1693  /*
1694  * Not there, so build it, in planner context so we can re-use it. (Not
1695  * important in normal planning, but definitely so in GEQO.)
1696  */
1697  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1698 
1699  rinfo = build_implied_join_equality(opno,
1700  ec->ec_collation,
1701  leftem->em_expr,
1702  rightem->em_expr,
1703  bms_union(leftem->em_relids,
1704  rightem->em_relids),
1705  bms_union(leftem->em_nullable_relids,
1706  rightem->em_nullable_relids),
1707  ec->ec_min_security);
1708 
1709  /* Mark the clause as redundant, or not */
1710  rinfo->parent_ec = parent_ec;
1711 
1712  /*
1713  * We know the correct values for left_ec/right_ec, ie this particular EC,
1714  * so we can just set them directly instead of forcing another lookup.
1715  */
1716  rinfo->left_ec = ec;
1717  rinfo->right_ec = ec;
1718 
1719  /* Mark it as usable with these EMs */
1720  rinfo->left_em = leftem;
1721  rinfo->right_em = rightem;
1722  /* and save it for possible re-use */
1723  ec->ec_derives = lappend(ec->ec_derives, rinfo);
1724 
1725  MemoryContextSwitchTo(oldcontext);
1726 
1727  return rinfo;
1728 }
1729 
1730 
1731 /*
1732  * reconsider_outer_join_clauses
1733  * Re-examine any outer-join clauses that were set aside by
1734  * distribute_qual_to_rels(), and see if we can derive any
1735  * EquivalenceClasses from them. Then, if they were not made
1736  * redundant, push them out into the regular join-clause lists.
1737  *
1738  * When we have mergejoinable clauses A = B that are outer-join clauses,
1739  * we can't blindly combine them with other clauses A = C to deduce B = C,
1740  * since in fact the "equality" A = B won't necessarily hold above the
1741  * outer join (one of the variables might be NULL instead). Nonetheless
1742  * there are cases where we can add qual clauses using transitivity.
1743  *
1744  * One case that we look for here is an outer-join clause OUTERVAR = INNERVAR
1745  * for which there is also an equivalence clause OUTERVAR = CONSTANT.
1746  * It is safe and useful to push a clause INNERVAR = CONSTANT into the
1747  * evaluation of the inner (nullable) relation, because any inner rows not
1748  * meeting this condition will not contribute to the outer-join result anyway.
1749  * (Any outer rows they could join to will be eliminated by the pushed-down
1750  * equivalence clause.)
1751  *
1752  * Note that the above rule does not work for full outer joins; nor is it
1753  * very interesting to consider cases where the generated equivalence clause
1754  * would involve relations outside the outer join, since such clauses couldn't
1755  * be pushed into the inner side's scan anyway. So the restriction to
1756  * outervar = pseudoconstant is not really giving up anything.
1757  *
1758  * For full-join cases, we can only do something useful if it's a FULL JOIN
1759  * USING and a merged column has an equivalence MERGEDVAR = CONSTANT.
1760  * By the time it gets here, the merged column will look like
1761  * COALESCE(LEFTVAR, RIGHTVAR)
1762  * and we will have a full-join clause LEFTVAR = RIGHTVAR that we can match
1763  * the COALESCE expression to. In this situation we can push LEFTVAR = CONSTANT
1764  * and RIGHTVAR = CONSTANT into the input relations, since any rows not
1765  * meeting these conditions cannot contribute to the join result.
1766  *
1767  * Again, there isn't any traction to be gained by trying to deal with
1768  * clauses comparing a mergedvar to a non-pseudoconstant. So we can make
1769  * use of the EquivalenceClasses to search for matching variables that were
1770  * equivalenced to constants. The interesting outer-join clauses were
1771  * accumulated for us by distribute_qual_to_rels.
1772  *
1773  * When we find one of these cases, we implement the changes we want by
1774  * generating a new equivalence clause INNERVAR = CONSTANT (or LEFTVAR, etc)
1775  * and pushing it into the EquivalenceClass structures. This is because we
1776  * may already know that INNERVAR is equivalenced to some other var(s), and
1777  * we'd like the constant to propagate to them too. Note that it would be
1778  * unsafe to merge any existing EC for INNERVAR with the OUTERVAR's EC ---
1779  * that could result in propagating constant restrictions from
1780  * INNERVAR to OUTERVAR, which would be very wrong.
1781  *
1782  * It's possible that the INNERVAR is also an OUTERVAR for some other
1783  * outer-join clause, in which case the process can be repeated. So we repeat
1784  * looping over the lists of clauses until no further deductions can be made.
1785  * Whenever we do make a deduction, we remove the generating clause from the
1786  * lists, since we don't want to make the same deduction twice.
1787  *
1788  * If we don't find any match for a set-aside outer join clause, we must
1789  * throw it back into the regular joinclause processing by passing it to
1790  * distribute_restrictinfo_to_rels(). If we do generate a derived clause,
1791  * however, the outer-join clause is redundant. We still throw it back,
1792  * because otherwise the join will be seen as a clauseless join and avoided
1793  * during join order searching; but we mark it as redundant to keep from
1794  * messing up the joinrel's size estimate. (This behavior means that the
1795  * API for this routine is uselessly complex: we could have just put all
1796  * the clauses into the regular processing initially. We keep it because
1797  * someday we might want to do something else, such as inserting "dummy"
1798  * joinclauses instead of real ones.)
1799  *
1800  * Outer join clauses that are marked outerjoin_delayed are special: this
1801  * condition means that one or both VARs might go to null due to a lower
1802  * outer join. We can still push a constant through the clause, but only
1803  * if its operator is strict; and we *have to* throw the clause back into
1804  * regular joinclause processing. By keeping the strict join clause,
1805  * we ensure that any null-extended rows that are mistakenly generated due
1806  * to suppressing rows not matching the constant will be rejected at the
1807  * upper outer join. (This doesn't work for full-join clauses.)
1808  */
1809 void
1811 {
1812  bool found;
1813  ListCell *cell;
1814 
1815  /* Outer loop repeats until we find no more deductions */
1816  do
1817  {
1818  found = false;
1819 
1820  /* Process the LEFT JOIN clauses */
1821  foreach(cell, root->left_join_clauses)
1822  {
1823  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1824 
1825  if (reconsider_outer_join_clause(root, rinfo, true))
1826  {
1827  found = true;
1828  /* remove it from the list */
1829  root->left_join_clauses =
1831  /* we throw it back anyway (see notes above) */
1832  /* but the thrown-back clause has no extra selectivity */
1833  rinfo->norm_selec = 2.0;
1834  rinfo->outer_selec = 1.0;
1835  distribute_restrictinfo_to_rels(root, rinfo);
1836  }
1837  }
1838 
1839  /* Process the RIGHT JOIN clauses */
1840  foreach(cell, root->right_join_clauses)
1841  {
1842  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1843 
1844  if (reconsider_outer_join_clause(root, rinfo, false))
1845  {
1846  found = true;
1847  /* remove it from the list */
1848  root->right_join_clauses =
1850  /* we throw it back anyway (see notes above) */
1851  /* but the thrown-back clause has no extra selectivity */
1852  rinfo->norm_selec = 2.0;
1853  rinfo->outer_selec = 1.0;
1854  distribute_restrictinfo_to_rels(root, rinfo);
1855  }
1856  }
1857 
1858  /* Process the FULL JOIN clauses */
1859  foreach(cell, root->full_join_clauses)
1860  {
1861  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1862 
1863  if (reconsider_full_join_clause(root, rinfo))
1864  {
1865  found = true;
1866  /* remove it from the list */
1867  root->full_join_clauses =
1869  /* we throw it back anyway (see notes above) */
1870  /* but the thrown-back clause has no extra selectivity */
1871  rinfo->norm_selec = 2.0;
1872  rinfo->outer_selec = 1.0;
1873  distribute_restrictinfo_to_rels(root, rinfo);
1874  }
1875  }
1876  } while (found);
1877 
1878  /* Now, any remaining clauses have to be thrown back */
1879  foreach(cell, root->left_join_clauses)
1880  {
1881  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1882 
1883  distribute_restrictinfo_to_rels(root, rinfo);
1884  }
1885  foreach(cell, root->right_join_clauses)
1886  {
1887  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1888 
1889  distribute_restrictinfo_to_rels(root, rinfo);
1890  }
1891  foreach(cell, root->full_join_clauses)
1892  {
1893  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
1894 
1895  distribute_restrictinfo_to_rels(root, rinfo);
1896  }
1897 }
1898 
1899 /*
1900  * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
1901  *
1902  * Returns true if we were able to propagate a constant through the clause.
1903  */
1904 static bool
1906  bool outer_on_left)
1907 {
1908  Expr *outervar,
1909  *innervar;
1910  Oid opno,
1911  collation,
1912  left_type,
1913  right_type,
1914  inner_datatype;
1915  Relids inner_relids,
1916  inner_nullable_relids;
1917  ListCell *lc1;
1918 
1919  Assert(is_opclause(rinfo->clause));
1920  opno = ((OpExpr *) rinfo->clause)->opno;
1921  collation = ((OpExpr *) rinfo->clause)->inputcollid;
1922 
1923  /* If clause is outerjoin_delayed, operator must be strict */
1924  if (rinfo->outerjoin_delayed && !op_strict(opno))
1925  return false;
1926 
1927  /* Extract needed info from the clause */
1928  op_input_types(opno, &left_type, &right_type);
1929  if (outer_on_left)
1930  {
1931  outervar = (Expr *) get_leftop(rinfo->clause);
1932  innervar = (Expr *) get_rightop(rinfo->clause);
1933  inner_datatype = right_type;
1934  inner_relids = rinfo->right_relids;
1935  }
1936  else
1937  {
1938  outervar = (Expr *) get_rightop(rinfo->clause);
1939  innervar = (Expr *) get_leftop(rinfo->clause);
1940  inner_datatype = left_type;
1941  inner_relids = rinfo->left_relids;
1942  }
1943  inner_nullable_relids = bms_intersect(inner_relids,
1944  rinfo->nullable_relids);
1945 
1946  /* Scan EquivalenceClasses for a match to outervar */
1947  foreach(lc1, root->eq_classes)
1948  {
1949  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1950  bool match;
1951  ListCell *lc2;
1952 
1953  /* Ignore EC unless it contains pseudoconstants */
1954  if (!cur_ec->ec_has_const)
1955  continue;
1956  /* Never match to a volatile EC */
1957  if (cur_ec->ec_has_volatile)
1958  continue;
1959  /* It has to match the outer-join clause as to semantics, too */
1960  if (collation != cur_ec->ec_collation)
1961  continue;
1962  if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
1963  continue;
1964  /* Does it contain a match to outervar? */
1965  match = false;
1966  foreach(lc2, cur_ec->ec_members)
1967  {
1968  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1969 
1970  Assert(!cur_em->em_is_child); /* no children yet */
1971  if (equal(outervar, cur_em->em_expr))
1972  {
1973  match = true;
1974  break;
1975  }
1976  }
1977  if (!match)
1978  continue; /* no match, so ignore this EC */
1979 
1980  /*
1981  * Yes it does! Try to generate a clause INNERVAR = CONSTANT for each
1982  * CONSTANT in the EC. Note that we must succeed with at least one
1983  * constant before we can decide to throw away the outer-join clause.
1984  */
1985  match = false;
1986  foreach(lc2, cur_ec->ec_members)
1987  {
1988  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1989  Oid eq_op;
1990  RestrictInfo *newrinfo;
1991 
1992  if (!cur_em->em_is_const)
1993  continue; /* ignore non-const members */
1994  eq_op = select_equality_operator(cur_ec,
1995  inner_datatype,
1996  cur_em->em_datatype);
1997  if (!OidIsValid(eq_op))
1998  continue; /* can't generate equality */
1999  newrinfo = build_implied_join_equality(eq_op,
2000  cur_ec->ec_collation,
2001  innervar,
2002  cur_em->em_expr,
2003  bms_copy(inner_relids),
2004  bms_copy(inner_nullable_relids),
2005  cur_ec->ec_min_security);
2006  if (process_equivalence(root, &newrinfo, true))
2007  match = true;
2008  }
2009 
2010  /*
2011  * If we were able to equate INNERVAR to any constant, report success.
2012  * Otherwise, fall out of the search loop, since we know the OUTERVAR
2013  * appears in at most one EC.
2014  */
2015  if (match)
2016  return true;
2017  else
2018  break;
2019  }
2020 
2021  return false; /* failed to make any deduction */
2022 }
2023 
2024 /*
2025  * reconsider_outer_join_clauses for a single FULL JOIN clause
2026  *
2027  * Returns true if we were able to propagate a constant through the clause.
2028  */
2029 static bool
2031 {
2032  Expr *leftvar;
2033  Expr *rightvar;
2034  Oid opno,
2035  collation,
2036  left_type,
2037  right_type;
2038  Relids left_relids,
2039  right_relids,
2040  left_nullable_relids,
2041  right_nullable_relids;
2042  ListCell *lc1;
2043 
2044  /* Can't use an outerjoin_delayed clause here */
2045  if (rinfo->outerjoin_delayed)
2046  return false;
2047 
2048  /* Extract needed info from the clause */
2049  Assert(is_opclause(rinfo->clause));
2050  opno = ((OpExpr *) rinfo->clause)->opno;
2051  collation = ((OpExpr *) rinfo->clause)->inputcollid;
2052  op_input_types(opno, &left_type, &right_type);
2053  leftvar = (Expr *) get_leftop(rinfo->clause);
2054  rightvar = (Expr *) get_rightop(rinfo->clause);
2055  left_relids = rinfo->left_relids;
2056  right_relids = rinfo->right_relids;
2057  left_nullable_relids = bms_intersect(left_relids,
2058  rinfo->nullable_relids);
2059  right_nullable_relids = bms_intersect(right_relids,
2060  rinfo->nullable_relids);
2061 
2062  foreach(lc1, root->eq_classes)
2063  {
2064  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2065  EquivalenceMember *coal_em = NULL;
2066  bool match;
2067  bool matchleft;
2068  bool matchright;
2069  ListCell *lc2;
2070  int coal_idx = -1;
2071 
2072  /* Ignore EC unless it contains pseudoconstants */
2073  if (!cur_ec->ec_has_const)
2074  continue;
2075  /* Never match to a volatile EC */
2076  if (cur_ec->ec_has_volatile)
2077  continue;
2078  /* It has to match the outer-join clause as to semantics, too */
2079  if (collation != cur_ec->ec_collation)
2080  continue;
2081  if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
2082  continue;
2083 
2084  /*
2085  * Does it contain a COALESCE(leftvar, rightvar) construct?
2086  *
2087  * We can assume the COALESCE() inputs are in the same order as the
2088  * join clause, since both were automatically generated in the cases
2089  * we care about.
2090  *
2091  * XXX currently this may fail to match in cross-type cases because
2092  * the COALESCE will contain typecast operations while the join clause
2093  * may not (if there is a cross-type mergejoin operator available for
2094  * the two column types). Is it OK to strip implicit coercions from
2095  * the COALESCE arguments?
2096  */
2097  match = false;
2098  foreach(lc2, cur_ec->ec_members)
2099  {
2100  coal_em = (EquivalenceMember *) lfirst(lc2);
2101  Assert(!coal_em->em_is_child); /* no children yet */
2102  if (IsA(coal_em->em_expr, CoalesceExpr))
2103  {
2104  CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
2105  Node *cfirst;
2106  Node *csecond;
2107 
2108  if (list_length(cexpr->args) != 2)
2109  continue;
2110  cfirst = (Node *) linitial(cexpr->args);
2111  csecond = (Node *) lsecond(cexpr->args);
2112 
2113  if (equal(leftvar, cfirst) && equal(rightvar, csecond))
2114  {
2115  coal_idx = foreach_current_index(lc2);
2116  match = true;
2117  break;
2118  }
2119  }
2120  }
2121  if (!match)
2122  continue; /* no match, so ignore this EC */
2123 
2124  /*
2125  * Yes it does! Try to generate clauses LEFTVAR = CONSTANT and
2126  * RIGHTVAR = CONSTANT for each CONSTANT in the EC. Note that we must
2127  * succeed with at least one constant for each var before we can
2128  * decide to throw away the outer-join clause.
2129  */
2130  matchleft = matchright = false;
2131  foreach(lc2, cur_ec->ec_members)
2132  {
2133  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2134  Oid eq_op;
2135  RestrictInfo *newrinfo;
2136 
2137  if (!cur_em->em_is_const)
2138  continue; /* ignore non-const members */
2139  eq_op = select_equality_operator(cur_ec,
2140  left_type,
2141  cur_em->em_datatype);
2142  if (OidIsValid(eq_op))
2143  {
2144  newrinfo = build_implied_join_equality(eq_op,
2145  cur_ec->ec_collation,
2146  leftvar,
2147  cur_em->em_expr,
2148  bms_copy(left_relids),
2149  bms_copy(left_nullable_relids),
2150  cur_ec->ec_min_security);
2151  if (process_equivalence(root, &newrinfo, true))
2152  matchleft = true;
2153  }
2154  eq_op = select_equality_operator(cur_ec,
2155  right_type,
2156  cur_em->em_datatype);
2157  if (OidIsValid(eq_op))
2158  {
2159  newrinfo = build_implied_join_equality(eq_op,
2160  cur_ec->ec_collation,
2161  rightvar,
2162  cur_em->em_expr,
2163  bms_copy(right_relids),
2164  bms_copy(right_nullable_relids),
2165  cur_ec->ec_min_security);
2166  if (process_equivalence(root, &newrinfo, true))
2167  matchright = true;
2168  }
2169  }
2170 
2171  /*
2172  * If we were able to equate both vars to constants, we're done, and
2173  * we can throw away the full-join clause as redundant. Moreover, we
2174  * can remove the COALESCE entry from the EC, since the added
2175  * restrictions ensure it will always have the expected value. (We
2176  * don't bother trying to update ec_relids or ec_sources.)
2177  */
2178  if (matchleft && matchright)
2179  {
2180  cur_ec->ec_members = list_delete_nth_cell(cur_ec->ec_members, coal_idx);
2181  return true;
2182  }
2183 
2184  /*
2185  * Otherwise, fall out of the search loop, since we know the COALESCE
2186  * appears in at most one EC (XXX might stop being true if we allow
2187  * stripping of coercions above?)
2188  */
2189  break;
2190  }
2191 
2192  return false; /* failed to make any deduction */
2193 }
2194 
2195 
2196 /*
2197  * exprs_known_equal
2198  * Detect whether two expressions are known equal due to equivalence
2199  * relationships.
2200  *
2201  * Actually, this only shows that the expressions are equal according
2202  * to some opfamily's notion of equality --- but we only use it for
2203  * selectivity estimation, so a fuzzy idea of equality is OK.
2204  *
2205  * Note: does not bother to check for "equal(item1, item2)"; caller must
2206  * check that case if it's possible to pass identical items.
2207  */
2208 bool
2209 exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
2210 {
2211  ListCell *lc1;
2212 
2213  foreach(lc1, root->eq_classes)
2214  {
2215  EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2216  bool item1member = false;
2217  bool item2member = false;
2218  ListCell *lc2;
2219 
2220  /* Never match to a volatile EC */
2221  if (ec->ec_has_volatile)
2222  continue;
2223 
2224  foreach(lc2, ec->ec_members)
2225  {
2227 
2228  if (em->em_is_child)
2229  continue; /* ignore children here */
2230  if (equal(item1, em->em_expr))
2231  item1member = true;
2232  else if (equal(item2, em->em_expr))
2233  item2member = true;
2234  /* Exit as soon as equality is proven */
2235  if (item1member && item2member)
2236  return true;
2237  }
2238  }
2239  return false;
2240 }
2241 
2242 
2243 /*
2244  * match_eclasses_to_foreign_key_col
2245  * See whether a foreign key column match is proven by any eclass.
2246  *
2247  * If the referenced and referencing Vars of the fkey's colno'th column are
2248  * known equal due to any eclass, return that eclass; otherwise return NULL.
2249  * (In principle there might be more than one matching eclass if multiple
2250  * collations are involved, but since collation doesn't matter for equality,
2251  * we ignore that fine point here.) This is much like exprs_known_equal,
2252  * except that we insist on the comparison operator matching the eclass, so
2253  * that the result is definite not approximate.
2254  *
2255  * On success, we also set fkinfo->eclass[colno] to the matching eclass,
2256  * and set fkinfo->fk_eclass_member[colno] to the eclass member for the
2257  * referencing Var.
2258  */
2261  ForeignKeyOptInfo *fkinfo,
2262  int colno)
2263 {
2264  Index var1varno = fkinfo->con_relid;
2265  AttrNumber var1attno = fkinfo->conkey[colno];
2266  Index var2varno = fkinfo->ref_relid;
2267  AttrNumber var2attno = fkinfo->confkey[colno];
2268  Oid eqop = fkinfo->conpfeqop[colno];
2269  RelOptInfo *rel1 = root->simple_rel_array[var1varno];
2270  RelOptInfo *rel2 = root->simple_rel_array[var2varno];
2271  List *opfamilies = NIL; /* compute only if needed */
2272  Bitmapset *matching_ecs;
2273  int i;
2274 
2275  /* Consider only eclasses mentioning both relations */
2276  Assert(root->ec_merging_done);
2277  Assert(IS_SIMPLE_REL(rel1));
2278  Assert(IS_SIMPLE_REL(rel2));
2279  matching_ecs = bms_intersect(rel1->eclass_indexes,
2280  rel2->eclass_indexes);
2281 
2282  i = -1;
2283  while ((i = bms_next_member(matching_ecs, i)) >= 0)
2284  {
2286  i);
2287  EquivalenceMember *item1_em = NULL;
2288  EquivalenceMember *item2_em = NULL;
2289  ListCell *lc2;
2290 
2291  /* Never match to a volatile EC */
2292  if (ec->ec_has_volatile)
2293  continue;
2294  /* Note: it seems okay to match to "broken" eclasses here */
2295 
2296  foreach(lc2, ec->ec_members)
2297  {
2299  Var *var;
2300 
2301  if (em->em_is_child)
2302  continue; /* ignore children here */
2303 
2304  /* EM must be a Var, possibly with RelabelType */
2305  var = (Var *) em->em_expr;
2306  while (var && IsA(var, RelabelType))
2307  var = (Var *) ((RelabelType *) var)->arg;
2308  if (!(var && IsA(var, Var)))
2309  continue;
2310 
2311  /* Match? */
2312  if (var->varno == var1varno && var->varattno == var1attno)
2313  item1_em = em;
2314  else if (var->varno == var2varno && var->varattno == var2attno)
2315  item2_em = em;
2316 
2317  /* Have we found both PK and FK column in this EC? */
2318  if (item1_em && item2_em)
2319  {
2320  /*
2321  * Succeed if eqop matches EC's opfamilies. We could test
2322  * this before scanning the members, but it's probably cheaper
2323  * to test for member matches first.
2324  */
2325  if (opfamilies == NIL) /* compute if we didn't already */
2326  opfamilies = get_mergejoin_opfamilies(eqop);
2327  if (equal(opfamilies, ec->ec_opfamilies))
2328  {
2329  fkinfo->eclass[colno] = ec;
2330  fkinfo->fk_eclass_member[colno] = item2_em;
2331  return ec;
2332  }
2333  /* Otherwise, done with this EC, move on to the next */
2334  break;
2335  }
2336  }
2337  }
2338  return NULL;
2339 }
2340 
2341 /*
2342  * find_derived_clause_for_ec_member
2343  * Search for a previously-derived clause mentioning the given EM.
2344  *
2345  * The eclass should be an ec_has_const EC, of which the EM is a non-const
2346  * member. This should ensure there is just one derived clause mentioning
2347  * the EM (and equating it to a constant).
2348  * Returns NULL if no such clause can be found.
2349  */
2350 RestrictInfo *
2352  EquivalenceMember *em)
2353 {
2354  ListCell *lc;
2355 
2356  Assert(ec->ec_has_const);
2357  Assert(!em->em_is_const);
2358  foreach(lc, ec->ec_derives)
2359  {
2360  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2361 
2362  /*
2363  * generate_base_implied_equalities_const will have put non-const
2364  * members on the left side of derived clauses.
2365  */
2366  if (rinfo->left_em == em)
2367  return rinfo;
2368  }
2369  return NULL;
2370 }
2371 
2372 
2373 /*
2374  * add_child_rel_equivalences
2375  * Search for EC members that reference the root parent of child_rel, and
2376  * add transformed members referencing the child_rel.
2377  *
2378  * Note that this function won't be called at all unless we have at least some
2379  * reason to believe that the EC members it generates will be useful.
2380  *
2381  * parent_rel and child_rel could be derived from appinfo, but since the
2382  * caller has already computed them, we might as well just pass them in.
2383  *
2384  * The passed-in AppendRelInfo is not used when the parent_rel is not a
2385  * top-level baserel, since it shows the mapping from the parent_rel but
2386  * we need to translate EC expressions that refer to the top-level parent.
2387  * Using it is faster than using adjust_appendrel_attrs_multilevel(), though,
2388  * so we prefer it when we can.
2389  */
2390 void
2392  AppendRelInfo *appinfo,
2393  RelOptInfo *parent_rel,
2394  RelOptInfo *child_rel)
2395 {
2396  Relids top_parent_relids = child_rel->top_parent_relids;
2397  Relids child_relids = child_rel->relids;
2398  int i;
2399 
2400  /*
2401  * EC merging should be complete already, so we can use the parent rel's
2402  * eclass_indexes to avoid searching all of root->eq_classes.
2403  */
2404  Assert(root->ec_merging_done);
2405  Assert(IS_SIMPLE_REL(parent_rel));
2406 
2407  i = -1;
2408  while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
2409  {
2410  EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2411  int num_members;
2412 
2413  /*
2414  * If this EC contains a volatile expression, then generating child
2415  * EMs would be downright dangerous, so skip it. We rely on a
2416  * volatile EC having only one EM.
2417  */
2418  if (cur_ec->ec_has_volatile)
2419  continue;
2420 
2421  /* Sanity check eclass_indexes only contain ECs for parent_rel */
2422  Assert(bms_is_subset(top_parent_relids, cur_ec->ec_relids));
2423 
2424  /*
2425  * We don't use foreach() here because there's no point in scanning
2426  * newly-added child members, so we can stop after the last
2427  * pre-existing EC member.
2428  */
2429  num_members = list_length(cur_ec->ec_members);
2430  for (int pos = 0; pos < num_members; pos++)
2431  {
2432  EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
2433 
2434  if (cur_em->em_is_const)
2435  continue; /* ignore consts here */
2436 
2437  /*
2438  * We consider only original EC members here, not
2439  * already-transformed child members. Otherwise, if some original
2440  * member expression references more than one appendrel, we'd get
2441  * an O(N^2) explosion of useless derived expressions for
2442  * combinations of children. (But add_child_join_rel_equivalences
2443  * may add targeted combinations for partitionwise-join purposes.)
2444  */
2445  if (cur_em->em_is_child)
2446  continue; /* ignore children here */
2447 
2448  /* Does this member reference child's topmost parent rel? */
2449  if (bms_overlap(cur_em->em_relids, top_parent_relids))
2450  {
2451  /* Yes, generate transformed child version */
2452  Expr *child_expr;
2453  Relids new_relids;
2454  Relids new_nullable_relids;
2455 
2456  if (parent_rel->reloptkind == RELOPT_BASEREL)
2457  {
2458  /* Simple single-level transformation */
2459  child_expr = (Expr *)
2461  (Node *) cur_em->em_expr,
2462  1, &appinfo);
2463  }
2464  else
2465  {
2466  /* Must do multi-level transformation */
2467  child_expr = (Expr *)
2469  (Node *) cur_em->em_expr,
2470  child_relids,
2471  top_parent_relids);
2472  }
2473 
2474  /*
2475  * Transform em_relids to match. Note we do *not* do
2476  * pull_varnos(child_expr) here, as for example the
2477  * transformation might have substituted a constant, but we
2478  * don't want the child member to be marked as constant.
2479  */
2480  new_relids = bms_difference(cur_em->em_relids,
2481  top_parent_relids);
2482  new_relids = bms_add_members(new_relids, child_relids);
2483 
2484  /*
2485  * And likewise for nullable_relids. Note this code assumes
2486  * parent and child relids are singletons.
2487  */
2488  new_nullable_relids = cur_em->em_nullable_relids;
2489  if (bms_overlap(new_nullable_relids, top_parent_relids))
2490  {
2491  new_nullable_relids = bms_difference(new_nullable_relids,
2492  top_parent_relids);
2493  new_nullable_relids = bms_add_members(new_nullable_relids,
2494  child_relids);
2495  }
2496 
2497  (void) add_eq_member(cur_ec, child_expr,
2498  new_relids, new_nullable_relids,
2499  true, cur_em->em_datatype);
2500 
2501  /* Record this EC index for the child rel */
2502  child_rel->eclass_indexes = bms_add_member(child_rel->eclass_indexes, i);
2503  }
2504  }
2505  }
2506 }
2507 
2508 /*
2509  * add_child_join_rel_equivalences
2510  * Like add_child_rel_equivalences(), but for joinrels
2511  *
2512  * Here we find the ECs relevant to the top parent joinrel and add transformed
2513  * member expressions that refer to this child joinrel.
2514  *
2515  * Note that this function won't be called at all unless we have at least some
2516  * reason to believe that the EC members it generates will be useful.
2517  */
2518 void
2520  int nappinfos, AppendRelInfo **appinfos,
2521  RelOptInfo *parent_joinrel,
2522  RelOptInfo *child_joinrel)
2523 {
2524  Relids top_parent_relids = child_joinrel->top_parent_relids;
2525  Relids child_relids = child_joinrel->relids;
2526  Bitmapset *matching_ecs;
2527  MemoryContext oldcontext;
2528  int i;
2529 
2530  Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
2531 
2532  /* We need consider only ECs that mention the parent joinrel */
2533  matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
2534 
2535  /*
2536  * If we're being called during GEQO join planning, we still have to
2537  * create any new EC members in the main planner context, to avoid having
2538  * a corrupt EC data structure after the GEQO context is reset. This is
2539  * problematic since we'll leak memory across repeated GEQO cycles. For
2540  * now, though, bloat is better than crash. If it becomes a real issue
2541  * we'll have to do something to avoid generating duplicate EC members.
2542  */
2543  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2544 
2545  i = -1;
2546  while ((i = bms_next_member(matching_ecs, i)) >= 0)
2547  {
2548  EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2549  int num_members;
2550 
2551  /*
2552  * If this EC contains a volatile expression, then generating child
2553  * EMs would be downright dangerous, so skip it. We rely on a
2554  * volatile EC having only one EM.
2555  */
2556  if (cur_ec->ec_has_volatile)
2557  continue;
2558 
2559  /* Sanity check on get_eclass_indexes_for_relids result */
2560  Assert(bms_overlap(top_parent_relids, cur_ec->ec_relids));
2561 
2562  /*
2563  * We don't use foreach() here because there's no point in scanning
2564  * newly-added child members, so we can stop after the last
2565  * pre-existing EC member.
2566  */
2567  num_members = list_length(cur_ec->ec_members);
2568  for (int pos = 0; pos < num_members; pos++)
2569  {
2570  EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
2571 
2572  if (cur_em->em_is_const)
2573  continue; /* ignore consts here */
2574 
2575  /*
2576  * We consider only original EC members here, not
2577  * already-transformed child members.
2578  */
2579  if (cur_em->em_is_child)
2580  continue; /* ignore children here */
2581 
2582  /*
2583  * We may ignore expressions that reference a single baserel,
2584  * because add_child_rel_equivalences should have handled them.
2585  */
2586  if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
2587  continue;
2588 
2589  /* Does this member reference child's topmost parent rel? */
2590  if (bms_overlap(cur_em->em_relids, top_parent_relids))
2591  {
2592  /* Yes, generate transformed child version */
2593  Expr *child_expr;
2594  Relids new_relids;
2595  Relids new_nullable_relids;
2596 
2597  if (parent_joinrel->reloptkind == RELOPT_JOINREL)
2598  {
2599  /* Simple single-level transformation */
2600  child_expr = (Expr *)
2602  (Node *) cur_em->em_expr,
2603  nappinfos, appinfos);
2604  }
2605  else
2606  {
2607  /* Must do multi-level transformation */
2608  Assert(parent_joinrel->reloptkind == RELOPT_OTHER_JOINREL);
2609  child_expr = (Expr *)
2611  (Node *) cur_em->em_expr,
2612  child_relids,
2613  top_parent_relids);
2614  }
2615 
2616  /*
2617  * Transform em_relids to match. Note we do *not* do
2618  * pull_varnos(child_expr) here, as for example the
2619  * transformation might have substituted a constant, but we
2620  * don't want the child member to be marked as constant.
2621  */
2622  new_relids = bms_difference(cur_em->em_relids,
2623  top_parent_relids);
2624  new_relids = bms_add_members(new_relids, child_relids);
2625 
2626  /*
2627  * For nullable_relids, we must selectively replace parent
2628  * nullable relids with child ones.
2629  */
2630  new_nullable_relids = cur_em->em_nullable_relids;
2631  if (bms_overlap(new_nullable_relids, top_parent_relids))
2632  new_nullable_relids =
2634  new_nullable_relids,
2635  child_relids,
2636  top_parent_relids);
2637 
2638  (void) add_eq_member(cur_ec, child_expr,
2639  new_relids, new_nullable_relids,
2640  true, cur_em->em_datatype);
2641  }
2642  }
2643  }
2644 
2645  MemoryContextSwitchTo(oldcontext);
2646 }
2647 
2648 
2649 /*
2650  * generate_implied_equalities_for_column
2651  * Create EC-derived joinclauses usable with a specific column.
2652  *
2653  * This is used by indxpath.c to extract potentially indexable joinclauses
2654  * from ECs, and can be used by foreign data wrappers for similar purposes.
2655  * We assume that only expressions in Vars of a single table are of interest,
2656  * but the caller provides a callback function to identify exactly which
2657  * such expressions it would like to know about.
2658  *
2659  * We assume that any given table/index column could appear in only one EC.
2660  * (This should be true in all but the most pathological cases, and if it
2661  * isn't, we stop on the first match anyway.) Therefore, what we return
2662  * is a redundant list of clauses equating the table/index column to each of
2663  * the other-relation values it is known to be equal to. Any one of
2664  * these clauses can be used to create a parameterized path, and there
2665  * is no value in using more than one. (But it *is* worthwhile to create
2666  * a separate parameterized path for each one, since that leads to different
2667  * join orders.)
2668  *
2669  * The caller can pass a Relids set of rels we aren't interested in joining
2670  * to, so as to save the work of creating useless clauses.
2671  */
2672 List *
2674  RelOptInfo *rel,
2676  void *callback_arg,
2677  Relids prohibited_rels)
2678 {
2679  List *result = NIL;
2680  bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
2681  Relids parent_relids;
2682  int i;
2683 
2684  /* Should be OK to rely on eclass_indexes */
2685  Assert(root->ec_merging_done);
2686 
2687  /* Indexes are available only on base or "other" member relations. */
2688  Assert(IS_SIMPLE_REL(rel));
2689 
2690  /* If it's a child rel, we'll need to know what its parent(s) are */
2691  if (is_child_rel)
2692  parent_relids = find_childrel_parents(root, rel);
2693  else
2694  parent_relids = NULL; /* not used, but keep compiler quiet */
2695 
2696  i = -1;
2697  while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
2698  {
2699  EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2700  EquivalenceMember *cur_em;
2701  ListCell *lc2;
2702 
2703  /* Sanity check eclass_indexes only contain ECs for rel */
2704  Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
2705 
2706  /*
2707  * Won't generate joinclauses if const or single-member (the latter
2708  * test covers the volatile case too)
2709  */
2710  if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
2711  continue;
2712 
2713  /*
2714  * Scan members, looking for a match to the target column. Note that
2715  * child EC members are considered, but only when they belong to the
2716  * target relation. (Unlike regular members, the same expression
2717  * could be a child member of more than one EC. Therefore, it's
2718  * potentially order-dependent which EC a child relation's target
2719  * column gets matched to. This is annoying but it only happens in
2720  * corner cases, so for now we live with just reporting the first
2721  * match. See also get_eclass_for_sort_expr.)
2722  */
2723  cur_em = NULL;
2724  foreach(lc2, cur_ec->ec_members)
2725  {
2726  cur_em = (EquivalenceMember *) lfirst(lc2);
2727  if (bms_equal(cur_em->em_relids, rel->relids) &&
2728  callback(root, rel, cur_ec, cur_em, callback_arg))
2729  break;
2730  cur_em = NULL;
2731  }
2732 
2733  if (!cur_em)
2734  continue;
2735 
2736  /*
2737  * Found our match. Scan the other EC members and attempt to generate
2738  * joinclauses.
2739  */
2740  foreach(lc2, cur_ec->ec_members)
2741  {
2742  EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
2743  Oid eq_op;
2744  RestrictInfo *rinfo;
2745 
2746  if (other_em->em_is_child)
2747  continue; /* ignore children here */
2748 
2749  /* Make sure it'll be a join to a different rel */
2750  if (other_em == cur_em ||
2751  bms_overlap(other_em->em_relids, rel->relids))
2752  continue;
2753 
2754  /* Forget it if caller doesn't want joins to this rel */
2755  if (bms_overlap(other_em->em_relids, prohibited_rels))
2756  continue;
2757 
2758  /*
2759  * Also, if this is a child rel, avoid generating a useless join
2760  * to its parent rel(s).
2761  */
2762  if (is_child_rel &&
2763  bms_overlap(parent_relids, other_em->em_relids))
2764  continue;
2765 
2766  eq_op = select_equality_operator(cur_ec,
2767  cur_em->em_datatype,
2768  other_em->em_datatype);
2769  if (!OidIsValid(eq_op))
2770  continue;
2771 
2772  /* set parent_ec to mark as redundant with other joinclauses */
2773  rinfo = create_join_clause(root, cur_ec, eq_op,
2774  cur_em, other_em,
2775  cur_ec);
2776 
2777  result = lappend(result, rinfo);
2778  }
2779 
2780  /*
2781  * If somehow we failed to create any join clauses, we might as well
2782  * keep scanning the ECs for another match. But if we did make any,
2783  * we're done, because we don't want to return non-redundant clauses.
2784  */
2785  if (result)
2786  break;
2787  }
2788 
2789  return result;
2790 }
2791 
2792 /*
2793  * have_relevant_eclass_joinclause
2794  * Detect whether there is an EquivalenceClass that could produce
2795  * a joinclause involving the two given relations.
2796  *
2797  * This is essentially a very cut-down version of
2798  * generate_join_implied_equalities(). Note it's OK to occasionally say "yes"
2799  * incorrectly. Hence we don't bother with details like whether the lack of a
2800  * cross-type operator might prevent the clause from actually being generated.
2801  */
2802 bool
2804  RelOptInfo *rel1, RelOptInfo *rel2)
2805 {
2806  Bitmapset *matching_ecs;
2807  int i;
2808 
2809  /* Examine only eclasses mentioning both rel1 and rel2 */
2810  matching_ecs = get_common_eclass_indexes(root, rel1->relids,
2811  rel2->relids);
2812 
2813  i = -1;
2814  while ((i = bms_next_member(matching_ecs, i)) >= 0)
2815  {
2817  i);
2818 
2819  /*
2820  * Sanity check that get_common_eclass_indexes gave only ECs
2821  * containing both rels.
2822  */
2823  Assert(bms_overlap(rel1->relids, ec->ec_relids));
2824  Assert(bms_overlap(rel2->relids, ec->ec_relids));
2825 
2826  /*
2827  * Won't generate joinclauses if single-member (this test covers the
2828  * volatile case too)
2829  */
2830  if (list_length(ec->ec_members) <= 1)
2831  continue;
2832 
2833  /*
2834  * We do not need to examine the individual members of the EC, because
2835  * all that we care about is whether each rel overlaps the relids of
2836  * at least one member, and get_common_eclass_indexes() and the single
2837  * member check above are sufficient to prove that. (As with
2838  * have_relevant_joinclause(), it is not necessary that the EC be able
2839  * to form a joinclause relating exactly the two given rels, only that
2840  * it be able to form a joinclause mentioning both, and this will
2841  * surely be true if both of them overlap ec_relids.)
2842  *
2843  * Note we don't test ec_broken; if we did, we'd need a separate code
2844  * path to look through ec_sources. Checking the membership anyway is
2845  * OK as a possibly-overoptimistic heuristic.
2846  *
2847  * We don't test ec_has_const either, even though a const eclass won't
2848  * generate real join clauses. This is because if we had "WHERE a.x =
2849  * b.y and a.x = 42", it is worth considering a join between a and b,
2850  * since the join result is likely to be small even though it'll end
2851  * up being an unqualified nestloop.
2852  */
2853 
2854  return true;
2855  }
2856 
2857  return false;
2858 }
2859 
2860 
2861 /*
2862  * has_relevant_eclass_joinclause
2863  * Detect whether there is an EquivalenceClass that could produce
2864  * a joinclause involving the given relation and anything else.
2865  *
2866  * This is the same as have_relevant_eclass_joinclause with the other rel
2867  * implicitly defined as "everything else in the query".
2868  */
2869 bool
2871 {
2872  Bitmapset *matched_ecs;
2873  int i;
2874 
2875  /* Examine only eclasses mentioning rel1 */
2876  matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
2877 
2878  i = -1;
2879  while ((i = bms_next_member(matched_ecs, i)) >= 0)
2880  {
2882  i);
2883 
2884  /*
2885  * Won't generate joinclauses if single-member (this test covers the
2886  * volatile case too)
2887  */
2888  if (list_length(ec->ec_members) <= 1)
2889  continue;
2890 
2891  /*
2892  * Per the comment in have_relevant_eclass_joinclause, it's sufficient
2893  * to find an EC that mentions both this rel and some other rel.
2894  */
2895  if (!bms_is_subset(ec->ec_relids, rel1->relids))
2896  return true;
2897  }
2898 
2899  return false;
2900 }
2901 
2902 
2903 /*
2904  * eclass_useful_for_merging
2905  * Detect whether the EC could produce any mergejoinable join clauses
2906  * against the specified relation.
2907  *
2908  * This is just a heuristic test and doesn't have to be exact; it's better
2909  * to say "yes" incorrectly than "no". Hence we don't bother with details
2910  * like whether the lack of a cross-type operator might prevent the clause
2911  * from actually being generated.
2912  */
2913 bool
2916  RelOptInfo *rel)
2917 {
2918  Relids relids;
2919  ListCell *lc;
2920 
2921  Assert(!eclass->ec_merged);
2922 
2923  /*
2924  * Won't generate joinclauses if const or single-member (the latter test
2925  * covers the volatile case too)
2926  */
2927  if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
2928  return false;
2929 
2930  /*
2931  * Note we don't test ec_broken; if we did, we'd need a separate code path
2932  * to look through ec_sources. Checking the members anyway is OK as a
2933  * possibly-overoptimistic heuristic.
2934  */
2935 
2936  /* If specified rel is a child, we must consider the topmost parent rel */
2937  if (IS_OTHER_REL(rel))
2938  {
2940  relids = rel->top_parent_relids;
2941  }
2942  else
2943  relids = rel->relids;
2944 
2945  /* If rel already includes all members of eclass, no point in searching */
2946  if (bms_is_subset(eclass->ec_relids, relids))
2947  return false;
2948 
2949  /* To join, we need a member not in the given rel */
2950  foreach(lc, eclass->ec_members)
2951  {
2952  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
2953 
2954  if (cur_em->em_is_child)
2955  continue; /* ignore children here */
2956 
2957  if (!bms_overlap(cur_em->em_relids, relids))
2958  return true;
2959  }
2960 
2961  return false;
2962 }
2963 
2964 
2965 /*
2966  * is_redundant_derived_clause
2967  * Test whether rinfo is derived from same EC as any clause in clauselist;
2968  * if so, it can be presumed to represent a condition that's redundant
2969  * with that member of the list.
2970  */
2971 bool
2973 {
2974  EquivalenceClass *parent_ec = rinfo->parent_ec;
2975  ListCell *lc;
2976 
2977  /* Fail if it's not a potentially-redundant clause from some EC */
2978  if (parent_ec == NULL)
2979  return false;
2980 
2981  foreach(lc, clauselist)
2982  {
2983  RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
2984 
2985  if (otherrinfo->parent_ec == parent_ec)
2986  return true;
2987  }
2988 
2989  return false;
2990 }
2991 
2992 /*
2993  * is_redundant_with_indexclauses
2994  * Test whether rinfo is redundant with any clause in the IndexClause
2995  * list. Here, for convenience, we test both simple identity and
2996  * whether it is derived from the same EC as any member of the list.
2997  */
2998 bool
3000 {
3001  EquivalenceClass *parent_ec = rinfo->parent_ec;
3002  ListCell *lc;
3003 
3004  foreach(lc, indexclauses)
3005  {
3006  IndexClause *iclause = lfirst_node(IndexClause, lc);
3007  RestrictInfo *otherrinfo = iclause->rinfo;
3008 
3009  /* If indexclause is lossy, it won't enforce the condition exactly */
3010  if (iclause->lossy)
3011  continue;
3012 
3013  /* Match if it's same clause (pointer equality should be enough) */
3014  if (rinfo == otherrinfo)
3015  return true;
3016  /* Match if derived from same EC */
3017  if (parent_ec && otherrinfo->parent_ec == parent_ec)
3018  return true;
3019 
3020  /*
3021  * No need to look at the derived clauses in iclause->indexquals; they
3022  * couldn't match if the parent clause didn't.
3023  */
3024  }
3025 
3026  return false;
3027 }
3028 
3029 /*
3030  * get_eclass_indexes_for_relids
3031  * Build and return a Bitmapset containing the indexes into root's
3032  * eq_classes list for all eclasses that mention any of these relids
3033  */
3034 static Bitmapset *
3036 {
3037  Bitmapset *ec_indexes = NULL;
3038  int i = -1;
3039 
3040  /* Should be OK to rely on eclass_indexes */
3041  Assert(root->ec_merging_done);
3042 
3043  while ((i = bms_next_member(relids, i)) > 0)
3044  {
3045  RelOptInfo *rel = root->simple_rel_array[i];
3046 
3047  ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
3048  }
3049  return ec_indexes;
3050 }
3051 
3052 /*
3053  * get_common_eclass_indexes
3054  * Build and return a Bitmapset containing the indexes into root's
3055  * eq_classes list for all eclasses that mention rels in both
3056  * relids1 and relids2.
3057  */
3058 static Bitmapset *
3060 {
3061  Bitmapset *rel1ecs;
3062  Bitmapset *rel2ecs;
3063  int relid;
3064 
3065  rel1ecs = get_eclass_indexes_for_relids(root, relids1);
3066 
3067  /*
3068  * We can get away with just using the relation's eclass_indexes directly
3069  * when relids2 is a singleton set.
3070  */
3071  if (bms_get_singleton_member(relids2, &relid))
3072  rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
3073  else
3074  rel2ecs = get_eclass_indexes_for_relids(root, relids2);
3075 
3076  /* Calculate and return the common EC indexes, recycling the left input. */
3077  return bms_int_members(rel1ecs, rel2ecs);
3078 }
bool has_eclass_joins
Definition: pathnodes.h:734
#define NIL
Definition: pg_list.h:65
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:2209
static bool reconsider_full_join_clause(PlannerInfo *root, RestrictInfo *rinfo)
Definition: equivclass.c:2030
static void generate_base_implied_equalities_no_const(PlannerInfo *root, EquivalenceClass *ec)
Definition: equivclass.c:1084
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1781
bool op_strict(Oid opno)
Definition: lsyscache.c:1421
static RestrictInfo * create_join_clause(PlannerInfo *root, EquivalenceClass *ec, Oid opno, EquivalenceMember *leftem, EquivalenceMember *rightem, EquivalenceClass *parent_ec)
Definition: equivclass.c:1657
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Index security_level
Definition: pathnodes.h:2006
bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
Definition: equivclass.c:2972
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
RelOptKind reloptkind
Definition: pathnodes.h:663
RestrictInfo * make_restrictinfo(Expr *clause, bool is_pushed_down, bool outerjoin_delayed, bool pseudoconstant, Index security_level, Relids required_relids, Relids outer_relids, Relids nullable_relids)
Definition: restrictinfo.c:59
bool ec_merging_done
Definition: pathnodes.h:262
Relids required_relids
Definition: pathnodes.h:2012
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3042
bool leakproof
Definition: pathnodes.h:2004
Index ec_min_security
Definition: pathnodes.h:978
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
Definition: nodeFuncs.c:582
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:654
bool eclass_useful_for_merging(PlannerInfo *root, EquivalenceClass *eclass, RelOptInfo *rel)
Definition: equivclass.c:2914
Relids em_nullable_relids
Definition: pathnodes.h:1018
List * ec_derives
Definition: pathnodes.h:970
List * get_mergejoin_opfamilies(Oid opno)
Definition: lsyscache.c:364
#define Min(x, y)
Definition: c.h:974
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:709
EquivalenceClass * get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, Relids nullable_relids, List *opfamilies, Oid opcintype, Oid collation, Index sortref, Relids rel, bool create_it)
Definition: equivclass.c:619
bool pseudoconstant
Definition: pathnodes.h:2002
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:291
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void generate_base_implied_equalities_broken(PlannerInfo *root, EquivalenceClass *ec)
Definition: equivclass.c:1191
List * list_copy(const List *oldlist)
Definition: list.c:1403
Definition: nodes.h:528
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:644
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
Relids left_relids
Definition: pathnodes.h:2021
AttrNumber varattno
Definition: primnodes.h:186
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:615
bool ec_below_outer_join
Definition: pathnodes.h:975
Relids adjust_child_relids_multilevel(PlannerInfo *root, Relids relids, Relids child_relids, Relids top_parent_relids)
Definition: appendinfo.c:576
EquivalenceClass * right_ec
Definition: pathnodes.h:2043
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
static bool reconsider_outer_join_clause(PlannerInfo *root, RestrictInfo *rinfo, bool outer_on_left)
Definition: equivclass.c:1905
void add_child_rel_equivalences(PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
Definition: equivclass.c:2391
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:437
Index ec_max_security
Definition: pathnodes.h:979
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
#define OidIsValid(objectId)
Definition: c.h:698
List * mergeopfamilies
Definition: pathnodes.h:2039
#define lsecond(l)
Definition: pg_list.h:179
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:639
Relids outer_relids
Definition: pathnodes.h:2015
signed int int32
Definition: c.h:417
static struct cvec * eclass(struct vars *v, chr c, int cases)
Definition: regc_locale.c:508
Selectivity norm_selec
Definition: pathnodes.h:2032
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:197
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, Relids child_relids, Relids top_parent_relids)
Definition: appendinfo.c:502
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:357
void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed, bool create_new_ph)
Definition: initsplan.c:227
#define list_make1(x1)
Definition: pg_list.h:206
void add_child_join_rel_equivalences(PlannerInfo *root, int nappinfos, AppendRelInfo **appinfos, RelOptInfo *parent_joinrel, RelOptInfo *child_joinrel)
Definition: equivclass.c:2519
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:567
void pfree(void *pointer)
Definition: mcxt.c:1057
void distribute_restrictinfo_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo)
Definition: initsplan.c:2173
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1381
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:45
bool process_equivalence(PlannerInfo *root, RestrictInfo **p_restrictinfo, bool below_outer_join)
Definition: equivclass.c:118
static void * list_nth(const List *list, int n)
Definition: pg_list.h:266
List * generate_join_implied_equalities(PlannerInfo *root, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1248
EquivalenceMember * left_em
Definition: pathnodes.h:2044
List * args
Definition: primnodes.h:1110
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:949
static Bitmapset * get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
Definition: equivclass.c:3035
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: pathnodes.h:890
EquivalenceClass * parent_ec
Definition: pathnodes.h:2028
Expr * arg
Definition: primnodes.h:1243
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:2999
Expr * canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
Definition: equivclass.c:498
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
bool outerjoin_delayed
Definition: pathnodes.h:1998
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static Oid select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
Definition: equivclass.c:1622
List * ec_sources
Definition: pathnodes.h:969
Expr * find_em_expr_usable_for_sorting_rel(PlannerInfo *root, EquivalenceClass *ec, RelOptInfo *rel, bool require_parallel_safe)
Definition: equivclass.c:808
static List * generate_join_implied_equalities_broken(PlannerInfo *root, EquivalenceClass *ec, Relids nominal_join_relids, Relids outer_relids, Relids nominal_inner_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1573
struct RestrictInfo * rinfo
Definition: pathnodes.h:1257
Relids ec_relids
Definition: pathnodes.h:971
List * left_join_clauses
Definition: pathnodes.h:266
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
List * full_join_clauses
Definition: pathnodes.h:274
Relids relids
Definition: pathnodes.h:666
Selectivity outer_selec
Definition: pathnodes.h:2035
Expr * find_em_expr_for_rel(EquivalenceClass *ec, RelOptInfo *rel)
Definition: equivclass.c:776
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1302
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:73
bool has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
Definition: equivclass.c:2870
static List * generate_join_implied_equalities_normal(PlannerInfo *root, EquivalenceClass *ec, Relids join_relids, Relids outer_relids, Relids inner_relids)
Definition: equivclass.c:1397
int simple_rel_array_size
Definition: pathnodes.h:198
Relids pull_varnos(Node *node)
Definition: var.c:95
bool contain_window_function(Node *clause)
Definition: clauses.c:207
List * lappend(List *list, void *datum)
Definition: list.c:321
EquivalenceMember * right_em
Definition: pathnodes.h:2045
Expr * clause
Definition: pathnodes.h:1994
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:898
Index varno
Definition: primnodes.h:184
List * ec_opfamilies
Definition: pathnodes.h:966
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:186
Relids nullable_relids
Definition: pathnodes.h:2018
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:900
void * palloc0(Size size)
Definition: mcxt.c:981
List * generate_join_implied_equalities_for_ecs(PlannerInfo *root, List *eclasses, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1326
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: pathnodes.h:888
static Bitmapset * get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
Definition: equivclass.c:3059
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:259
void generate_base_implied_equalities(PlannerInfo *root)
Definition: equivclass.c:915
bool have_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
Definition: equivclass.c:2803
unsigned int Index
Definition: c.h:537
NullTestType nulltesttype
Definition: primnodes.h:1244
Relids find_childrel_parents(PlannerInfo *root, RelOptInfo *rel)
Definition: relnode.c:1239
EquivalenceClass * match_eclasses_to_foreign_key_col(PlannerInfo *root, ForeignKeyOptInfo *fkinfo, int colno)
Definition: equivclass.c:2260
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:85
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1229
bool is_pushed_down
Definition: pathnodes.h:1996
void reconsider_outer_join_clauses(PlannerInfo *root)
Definition: equivclass.c:1810
#define Max(x, y)
Definition: c.h:968
#define makeNode(_type_)
Definition: nodes.h:576
Relids right_relids
Definition: pathnodes.h:2022
bool(* ec_matches_callback_type)(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, EquivalenceMember *em, void *arg)
Definition: paths.h:116
#define Assert(condition)
Definition: c.h:792
#define lfirst(lc)
Definition: pg_list.h:169
List * eq_classes
Definition: pathnodes.h:260
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
int location
Definition: primnodes.h:1246
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
bool ec_has_volatile
Definition: pathnodes.h:974
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
RestrictInfo * build_implied_join_equality(Oid opno, Oid collation, Expr *item1, Expr *item2, Relids qualscope, Relids nullable_relids, Index security_level)
Definition: initsplan.c:2410
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
bool func_strict(Oid funcid)
Definition: lsyscache.c:1705
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
bool contain_agg_clause(Node *clause)
Definition: clauses.c:170
EquivalenceClass * left_ec
Definition: pathnodes.h:2042
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1658
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:185
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:228
int i
RestrictInfo * find_derived_clause_for_ec_member(EquivalenceClass *ec, EquivalenceMember *em)
Definition: equivclass.c:2351
static EquivalenceMember * add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids, Relids nullable_relids, bool is_child, Oid datatype)
Definition: equivclass.c:543
#define IS_SRF_CALL(node)
Definition: optimizer.h:28
bool argisrow
Definition: primnodes.h:1245
static void generate_base_implied_equalities_const(PlannerInfo *root, EquivalenceClass *ec)
Definition: equivclass.c:989
MemoryContext planner_cxt
Definition: pathnodes.h:325
List * right_join_clauses
Definition: pathnodes.h:270
bool contain_nonstrict_functions(Node *clause)
Definition: clauses.c:807
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
#define copyObject(obj)
Definition: nodes.h:644
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:696
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:902
Definition: regcomp.c:224
Definition: pg_list.h:50
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: pathnodes.h:889
int16 AttrNumber
Definition: attnum.h:21
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:183
Bitmapset * eclass_indexes
Definition: pathnodes.h:708
struct EquivalenceClass * ec_merged
Definition: pathnodes.h:980
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define foreach_current_index(cell)
Definition: pg_list.h:370
List * ec_members
Definition: pathnodes.h:968
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:194
Relids top_parent_relids
Definition: pathnodes.h:739
List * generate_implied_equalities_for_column(PlannerInfo *root, RelOptInfo *rel, ec_matches_callback_type callback, void *callback_arg, Relids prohibited_rels)
Definition: equivclass.c:2673
RestrictInfo * process_implied_equality(PlannerInfo *root, Oid opno, Oid collation, Expr *item1, Expr *item2, Relids qualscope, Relids nullable_relids, Index security_level, bool below_outer_join, bool both_const)
Definition: initsplan.c:2261