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