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