Line data Source code
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 :
36 : static EquivalenceMember *add_eq_member(EquivalenceClass *ec,
37 : Expr *expr, Relids relids,
38 : JoinDomain *jdomain,
39 : EquivalenceMember *parent,
40 : Oid datatype);
41 : static void generate_base_implied_equalities_const(PlannerInfo *root,
42 : EquivalenceClass *ec);
43 : static void generate_base_implied_equalities_no_const(PlannerInfo *root,
44 : EquivalenceClass *ec);
45 : static void generate_base_implied_equalities_broken(PlannerInfo *root,
46 : EquivalenceClass *ec);
47 : static List *generate_join_implied_equalities_normal(PlannerInfo *root,
48 : EquivalenceClass *ec,
49 : Relids join_relids,
50 : Relids outer_relids,
51 : Relids inner_relids);
52 : static List *generate_join_implied_equalities_broken(PlannerInfo *root,
53 : EquivalenceClass *ec,
54 : Relids nominal_join_relids,
55 : Relids outer_relids,
56 : Relids nominal_inner_relids,
57 : RelOptInfo *inner_rel);
58 : static Oid select_equality_operator(EquivalenceClass *ec,
59 : Oid lefttype, Oid righttype);
60 : static RestrictInfo *create_join_clause(PlannerInfo *root,
61 : EquivalenceClass *ec, Oid opno,
62 : EquivalenceMember *leftem,
63 : EquivalenceMember *rightem,
64 : EquivalenceClass *parent_ec);
65 : static bool reconsider_outer_join_clause(PlannerInfo *root,
66 : OuterJoinClauseInfo *ojcinfo,
67 : bool outer_on_left);
68 : static bool reconsider_full_join_clause(PlannerInfo *root,
69 : OuterJoinClauseInfo *ojcinfo);
70 : static JoinDomain *find_join_domain(PlannerInfo *root, Relids relids);
71 : static Bitmapset *get_eclass_indexes_for_relids(PlannerInfo *root,
72 : Relids relids);
73 : static Bitmapset *get_common_eclass_indexes(PlannerInfo *root, Relids relids1,
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
117 269064 : process_equivalence(PlannerInfo *root,
118 : RestrictInfo **p_restrictinfo,
119 : JoinDomain *jdomain)
120 : {
121 269064 : RestrictInfo *restrictinfo = *p_restrictinfo;
122 269064 : 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 269064 : if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
145 202 : return false;
146 :
147 : /* Extract info from given clause */
148 : Assert(is_opclause(clause));
149 268862 : opno = ((OpExpr *) clause)->opno;
150 268862 : collation = ((OpExpr *) clause)->inputcollid;
151 268862 : item1 = (Expr *) get_leftop(clause);
152 268862 : item2 = (Expr *) get_rightop(clause);
153 268862 : item1_relids = restrictinfo->left_relids;
154 268862 : 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 268862 : item1 = canonicalize_ec_expression(item1,
161 : exprType((Node *) item1),
162 : collation);
163 268862 : 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 268862 : 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 54 : set_opfuncid((OpExpr *) clause);
186 54 : if (func_strict(((OpExpr *) clause)->opfuncid))
187 : {
188 54 : NullTest *ntest = makeNode(NullTest);
189 :
190 54 : ntest->arg = item1;
191 54 : ntest->nulltesttype = IS_NOT_NULL;
192 54 : ntest->argisrow = false; /* correct even if composite arg */
193 54 : ntest->location = -1;
194 :
195 54 : *p_restrictinfo =
196 54 : make_restrictinfo(root,
197 : (Expr *) ntest,
198 54 : restrictinfo->is_pushed_down,
199 54 : restrictinfo->has_clone,
200 54 : restrictinfo->is_clone,
201 54 : restrictinfo->pseudoconstant,
202 : restrictinfo->security_level,
203 : NULL,
204 : restrictinfo->incompatible_relids,
205 : restrictinfo->outer_relids);
206 : }
207 54 : 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 268808 : op_input_types(opno, &item1_type, &item2_type);
219 :
220 268808 : 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 268808 : ec1 = ec2 = NULL;
241 268808 : em1 = em2 = NULL;
242 268808 : ec2_idx = -1;
243 440424 : foreach(lc1, root->eq_classes)
244 : {
245 171652 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
246 : ListCell *lc2;
247 :
248 : /* Never match to a volatile EC */
249 171652 : if (cur_ec->ec_has_volatile)
250 0 : continue;
251 :
252 : /*
253 : * The collation has to match; check this first since it's cheaper
254 : * than the opfamily comparison.
255 : */
256 171652 : if (collation != cur_ec->ec_collation)
257 11988 : 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 159664 : if (!equal(opfamilies, cur_ec->ec_opfamilies))
265 35066 : continue;
266 :
267 375834 : foreach(lc2, cur_ec->ec_members)
268 : {
269 251272 : 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 251272 : if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
278 3672 : continue;
279 :
280 247600 : if (!ec1 &&
281 469936 : item1_type == cur_em->em_datatype &&
282 234842 : equal(item1, cur_em->em_expr))
283 : {
284 17870 : ec1 = cur_ec;
285 17870 : em1 = cur_em;
286 17870 : if (ec2)
287 18 : break;
288 : }
289 :
290 247582 : if (!ec2 &&
291 490076 : item2_type == cur_em->em_datatype &&
292 244858 : equal(item2, cur_em->em_expr))
293 : {
294 4100 : ec2 = cur_ec;
295 4100 : ec2_idx = foreach_current_index(lc1);
296 4100 : em2 = cur_em;
297 4100 : if (ec1)
298 18 : break;
299 : }
300 : }
301 :
302 124598 : if (ec1 && ec2)
303 36 : break;
304 : }
305 :
306 : /* Sweep finished, what did we find? */
307 :
308 268808 : if (ec1 && ec2)
309 : {
310 : /* If case 1, nothing to do, except add to sources */
311 36 : if (ec1 == ec2)
312 : {
313 12 : ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
314 12 : ec1->ec_min_security = Min(ec1->ec_min_security,
315 : restrictinfo->security_level);
316 12 : ec1->ec_max_security = Max(ec1->ec_max_security,
317 : restrictinfo->security_level);
318 : /* mark the RI as associated with this eclass */
319 12 : restrictinfo->left_ec = ec1;
320 12 : restrictinfo->right_ec = ec1;
321 : /* mark the RI as usable with this pair of EMs */
322 12 : restrictinfo->left_em = em1;
323 12 : restrictinfo->right_em = em2;
324 12 : 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 24 : if (root->ec_merging_done)
334 0 : 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 24 : ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
344 24 : ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
345 24 : ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
346 24 : ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
347 24 : ec1->ec_has_const |= ec2->ec_has_const;
348 : /* can't need to set has_volatile */
349 24 : ec1->ec_min_security = Min(ec1->ec_min_security,
350 : ec2->ec_min_security);
351 24 : ec1->ec_max_security = Max(ec1->ec_max_security,
352 : ec2->ec_max_security);
353 24 : ec2->ec_merged = ec1;
354 24 : root->eq_classes = list_delete_nth_cell(root->eq_classes, ec2_idx);
355 : /* just to avoid debugging confusion w/ dangling pointers: */
356 24 : ec2->ec_members = NIL;
357 24 : ec2->ec_sources = NIL;
358 24 : ec2->ec_derives = NIL;
359 24 : ec2->ec_relids = NULL;
360 24 : ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
361 24 : ec1->ec_min_security = Min(ec1->ec_min_security,
362 : restrictinfo->security_level);
363 24 : ec1->ec_max_security = Max(ec1->ec_max_security,
364 : restrictinfo->security_level);
365 : /* mark the RI as associated with this eclass */
366 24 : restrictinfo->left_ec = ec1;
367 24 : restrictinfo->right_ec = ec1;
368 : /* mark the RI as usable with this pair of EMs */
369 24 : restrictinfo->left_em = em1;
370 24 : restrictinfo->right_em = em2;
371 : }
372 268772 : else if (ec1)
373 : {
374 : /* Case 3: add item2 to ec1 */
375 17834 : em2 = add_eq_member(ec1, item2, item2_relids,
376 : jdomain, NULL, item2_type);
377 17834 : ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
378 17834 : ec1->ec_min_security = Min(ec1->ec_min_security,
379 : restrictinfo->security_level);
380 17834 : ec1->ec_max_security = Max(ec1->ec_max_security,
381 : restrictinfo->security_level);
382 : /* mark the RI as associated with this eclass */
383 17834 : restrictinfo->left_ec = ec1;
384 17834 : restrictinfo->right_ec = ec1;
385 : /* mark the RI as usable with this pair of EMs */
386 17834 : restrictinfo->left_em = em1;
387 17834 : restrictinfo->right_em = em2;
388 : }
389 250938 : else if (ec2)
390 : {
391 : /* Case 3: add item1 to ec2 */
392 4064 : em1 = add_eq_member(ec2, item1, item1_relids,
393 : jdomain, NULL, item1_type);
394 4064 : ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
395 4064 : ec2->ec_min_security = Min(ec2->ec_min_security,
396 : restrictinfo->security_level);
397 4064 : ec2->ec_max_security = Max(ec2->ec_max_security,
398 : restrictinfo->security_level);
399 : /* mark the RI as associated with this eclass */
400 4064 : restrictinfo->left_ec = ec2;
401 4064 : restrictinfo->right_ec = ec2;
402 : /* mark the RI as usable with this pair of EMs */
403 4064 : restrictinfo->left_em = em1;
404 4064 : restrictinfo->right_em = em2;
405 : }
406 : else
407 : {
408 : /* Case 4: make a new, two-entry EC */
409 246874 : EquivalenceClass *ec = makeNode(EquivalenceClass);
410 :
411 246874 : ec->ec_opfamilies = opfamilies;
412 246874 : ec->ec_collation = collation;
413 246874 : ec->ec_members = NIL;
414 246874 : ec->ec_sources = list_make1(restrictinfo);
415 246874 : ec->ec_derives = NIL;
416 246874 : ec->ec_relids = NULL;
417 246874 : ec->ec_has_const = false;
418 246874 : ec->ec_has_volatile = false;
419 246874 : ec->ec_broken = false;
420 246874 : ec->ec_sortref = 0;
421 246874 : ec->ec_min_security = restrictinfo->security_level;
422 246874 : ec->ec_max_security = restrictinfo->security_level;
423 246874 : ec->ec_merged = NULL;
424 246874 : em1 = add_eq_member(ec, item1, item1_relids,
425 : jdomain, NULL, item1_type);
426 246874 : em2 = add_eq_member(ec, item2, item2_relids,
427 : jdomain, NULL, item2_type);
428 :
429 246874 : root->eq_classes = lappend(root->eq_classes, ec);
430 :
431 : /* mark the RI as associated with this eclass */
432 246874 : restrictinfo->left_ec = ec;
433 246874 : restrictinfo->right_ec = ec;
434 : /* mark the RI as usable with this pair of EMs */
435 246874 : restrictinfo->left_em = em1;
436 246874 : restrictinfo->right_em = em2;
437 : }
438 :
439 268796 : 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 2355366 : canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
472 : {
473 2355366 : 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 2355366 : if (IsPolymorphicType(req_type) || req_type == RECORDOID)
480 4338 : req_type = expr_type;
481 :
482 : /*
483 : * No work if the expression exposes the right type/collation already.
484 : */
485 4674808 : if (expr_type != req_type ||
486 2319442 : 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 37134 : if (expr_type != req_type)
496 35924 : req_typmod = -1;
497 : else
498 1210 : 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 37134 : expr = (Expr *) applyRelabelType((Node *) expr,
505 : req_type, req_typmod, req_collation,
506 : COERCE_IMPLICIT_CAST, -1, false);
507 : }
508 :
509 2355366 : return expr;
510 : }
511 :
512 : /*
513 : * add_eq_member - build a new EquivalenceMember and add it to an EC
514 : */
515 : static EquivalenceMember *
516 805448 : add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
517 : JoinDomain *jdomain, EquivalenceMember *parent, Oid datatype)
518 : {
519 805448 : EquivalenceMember *em = makeNode(EquivalenceMember);
520 :
521 805448 : em->em_expr = expr;
522 805448 : em->em_relids = relids;
523 805448 : em->em_is_const = false;
524 805448 : em->em_is_child = (parent != NULL);
525 805448 : em->em_datatype = datatype;
526 805448 : em->em_jdomain = jdomain;
527 805448 : em->em_parent = parent;
528 :
529 805448 : 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 203406 : em->em_is_const = true;
541 203406 : ec->ec_has_const = true;
542 : /* it can't affect ec_relids */
543 : }
544 602042 : else if (!parent) /* child members don't add to ec_relids */
545 : {
546 528456 : ec->ec_relids = bms_add_members(ec->ec_relids, relids);
547 : }
548 805448 : ec->ec_members = lappend(ec->ec_members, em);
549 :
550 805448 : 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 : */
585 : EquivalenceClass *
586 1741654 : get_eclass_for_sort_expr(PlannerInfo *root,
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 1741654 : 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 1741654 : jdomain = linitial_node(JoinDomain, root->join_domains);
612 :
613 : /*
614 : * Scan through the existing EquivalenceClasses for a match
615 : */
616 5684470 : foreach(lc1, root->eq_classes)
617 : {
618 4924856 : 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 4924856 : if (cur_ec->ec_has_volatile &&
626 36 : (sortref == 0 || sortref != cur_ec->ec_sortref))
627 524 : continue;
628 :
629 4924332 : if (collation != cur_ec->ec_collation)
630 1258462 : continue;
631 3665870 : if (!equal(opfamilies, cur_ec->ec_opfamilies))
632 789006 : continue;
633 :
634 6645232 : foreach(lc2, cur_ec->ec_members)
635 : {
636 4750408 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
637 :
638 : /*
639 : * Ignore child members unless they match the request.
640 : */
641 4750408 : if (cur_em->em_is_child &&
642 302912 : !bms_equal(cur_em->em_relids, rel))
643 227932 : continue;
644 :
645 : /*
646 : * Match constants only within the same JoinDomain (see
647 : * optimizer/README).
648 : */
649 4522476 : if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
650 77070 : continue;
651 :
652 8845610 : if (opcintype == cur_em->em_datatype &&
653 4400204 : equal(expr, cur_em->em_expr))
654 982040 : return cur_ec; /* Match! */
655 : }
656 : }
657 :
658 : /* No match; does caller want a NULL result? */
659 759614 : if (!create_it)
660 543398 : 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 216216 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
668 :
669 216216 : newec = makeNode(EquivalenceClass);
670 216216 : newec->ec_opfamilies = list_copy(opfamilies);
671 216216 : newec->ec_collation = collation;
672 216216 : newec->ec_members = NIL;
673 216216 : newec->ec_sources = NIL;
674 216216 : newec->ec_derives = NIL;
675 216216 : newec->ec_relids = NULL;
676 216216 : newec->ec_has_const = false;
677 216216 : newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
678 216216 : newec->ec_broken = false;
679 216216 : newec->ec_sortref = sortref;
680 216216 : newec->ec_min_security = UINT_MAX;
681 216216 : newec->ec_max_security = 0;
682 216216 : newec->ec_merged = NULL;
683 :
684 216216 : if (newec->ec_has_volatile && sortref == 0) /* should not happen */
685 0 : elog(ERROR, "volatile EquivalenceClass has no sortref");
686 :
687 : /*
688 : * Get the precise set of relids appearing in the expression.
689 : */
690 216216 : expr_relids = pull_varnos(root, (Node *) expr);
691 :
692 216216 : 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 216216 : if (newec->ec_has_const)
702 : {
703 18188 : if (newec->ec_has_volatile ||
704 17914 : expression_returns_set((Node *) expr) ||
705 17588 : contain_agg_clause((Node *) expr) ||
706 8706 : contain_window_function((Node *) expr))
707 : {
708 456 : newec->ec_has_const = false;
709 456 : newem->em_is_const = false;
710 : }
711 : }
712 :
713 216216 : 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 216216 : if (root->ec_merging_done)
720 : {
721 124694 : int ec_index = list_length(root->eq_classes) - 1;
722 124694 : int i = -1;
723 :
724 240348 : while ((i = bms_next_member(newec->ec_relids, i)) > 0)
725 : {
726 115654 : RelOptInfo *rel = root->simple_rel_array[i];
727 :
728 : /* ignore the RTE_GROUP RTE */
729 115654 : if (i == root->group_rtindex)
730 580 : continue;
731 :
732 115074 : if (rel == NULL) /* must be an outer join */
733 : {
734 : Assert(bms_is_member(i, root->outer_join_rels));
735 5908 : continue;
736 : }
737 :
738 : Assert(rel->reloptkind == RELOPT_BASEREL);
739 :
740 109166 : rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
741 : ec_index);
742 : }
743 : }
744 :
745 216216 : MemoryContextSwitchTo(oldcontext);
746 :
747 216216 : 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 : */
762 : EquivalenceMember *
763 279778 : find_ec_member_matching_expr(EquivalenceClass *ec,
764 : Expr *expr,
765 : Relids relids)
766 : {
767 : ListCell *lc;
768 :
769 : /* We ignore binary-compatible relabeling on both ends */
770 300238 : while (expr && IsA(expr, RelabelType))
771 20460 : expr = ((RelabelType *) expr)->arg;
772 :
773 600956 : foreach(lc, ec->ec_members)
774 : {
775 445056 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
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 445056 : if (em->em_is_const)
783 0 : continue;
784 :
785 : /*
786 : * Ignore child members unless they belong to the requested rel.
787 : */
788 445056 : if (em->em_is_child &&
789 146804 : !bms_is_subset(em->em_relids, relids))
790 140866 : continue;
791 :
792 : /*
793 : * Match if same expression (after stripping relabel).
794 : */
795 304190 : emexpr = em->em_expr;
796 309368 : while (emexpr && IsA(emexpr, RelabelType))
797 5178 : emexpr = ((RelabelType *) emexpr)->arg;
798 :
799 304190 : if (equal(emexpr, expr))
800 123878 : return em;
801 : }
802 :
803 155900 : 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 : */
836 : EquivalenceMember *
837 2406 : find_computable_ec_member(PlannerInfo *root,
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 2406 : exprvars = pull_var_clause((Node *) exprs,
853 : PVC_INCLUDE_AGGREGATES |
854 : PVC_INCLUDE_WINDOWFUNCS |
855 : PVC_INCLUDE_PLACEHOLDERS);
856 :
857 7558 : foreach(lc, ec->ec_members)
858 : {
859 5602 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
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 5602 : if (em->em_is_const)
868 0 : continue;
869 :
870 : /*
871 : * Ignore child members unless they belong to the requested rel.
872 : */
873 5602 : if (em->em_is_child &&
874 2970 : !bms_is_subset(em->em_relids, relids))
875 2778 : continue;
876 :
877 : /*
878 : * Match if all Vars and quasi-Vars are present in "exprs".
879 : */
880 2824 : emvars = pull_var_clause((Node *) em->em_expr,
881 : PVC_INCLUDE_AGGREGATES |
882 : PVC_INCLUDE_WINDOWFUNCS |
883 : PVC_INCLUDE_PLACEHOLDERS);
884 3426 : foreach(lc2, emvars)
885 : {
886 2952 : if (!list_member(exprvars, lfirst(lc2)))
887 2350 : break;
888 : }
889 2824 : list_free(emvars);
890 2824 : if (lc2)
891 2350 : 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 474 : if (require_parallel_safe &&
898 122 : !is_parallel_safe(root, (Node *) em->em_expr))
899 24 : continue;
900 :
901 450 : return em; /* found usable expression */
902 : }
903 :
904 1956 : 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
921 10082 : relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel,
922 : EquivalenceClass *ec, bool require_parallel_safe)
923 : {
924 10082 : 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 10082 : if (ec->ec_has_volatile)
932 72 : return false;
933 :
934 : /*
935 : * Try to find an EM directly matching some reltarget member.
936 : */
937 20388 : foreach(lc, target->exprs)
938 : {
939 18334 : Expr *targetexpr = (Expr *) lfirst(lc);
940 :
941 18334 : em = find_ec_member_matching_expr(ec, targetexpr, rel->relids);
942 18334 : if (!em)
943 10378 : 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 7956 : if (expression_returns_set((Node *) em->em_expr))
952 0 : 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 7956 : if (require_parallel_safe &&
959 7956 : !is_parallel_safe(root, (Node *) em->em_expr))
960 0 : continue;
961 :
962 7956 : return true;
963 : }
964 :
965 : /*
966 : * Try to find an expression computable from the reltarget.
967 : */
968 2054 : em = find_computable_ec_member(root, ec, target->exprs, rel->relids,
969 : require_parallel_safe);
970 2054 : if (!em)
971 1956 : 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 98 : if (expression_returns_set((Node *) em->em_expr))
980 12 : return false;
981 :
982 86 : 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
1032 291860 : generate_base_implied_equalities(PlannerInfo *root)
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 291860 : root->ec_merging_done = true;
1045 :
1046 291860 : ec_index = 0;
1047 630232 : foreach(lc, root->eq_classes)
1048 : {
1049 338372 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
1050 338372 : 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 338372 : if (list_length(ec->ec_members) > 1)
1062 : {
1063 248542 : if (ec->ec_has_const)
1064 194118 : generate_base_implied_equalities_const(root, ec);
1065 : else
1066 54424 : generate_base_implied_equalities_no_const(root, ec);
1067 :
1068 : /* Recover if we failed to generate required derived clauses */
1069 248542 : if (ec->ec_broken)
1070 30 : generate_base_implied_equalities_broken(root, ec);
1071 :
1072 : /* Detect whether this EC might generate join clauses */
1073 248542 : can_generate_joinclause =
1074 248542 : (bms_membership(ec->ec_relids) == BMS_MULTIPLE);
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 338372 : i = -1;
1085 753710 : while ((i = bms_next_member(ec->ec_relids, i)) > 0)
1086 : {
1087 415338 : RelOptInfo *rel = root->simple_rel_array[i];
1088 :
1089 : /* ignore the RTE_GROUP RTE */
1090 415338 : if (i == root->group_rtindex)
1091 0 : continue;
1092 :
1093 415338 : if (rel == NULL) /* must be an outer join */
1094 : {
1095 : Assert(bms_is_member(i, root->outer_join_rels));
1096 4866 : continue;
1097 : }
1098 :
1099 : Assert(rel->reloptkind == RELOPT_BASEREL);
1100 :
1101 410472 : rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
1102 : ec_index);
1103 :
1104 410472 : if (can_generate_joinclause)
1105 143960 : rel->has_eclass_joins = true;
1106 : }
1107 :
1108 338372 : ec_index++;
1109 : }
1110 291860 : }
1111 :
1112 : /*
1113 : * generate_base_implied_equalities when EC contains pseudoconstant(s)
1114 : */
1115 : static void
1116 194118 : generate_base_implied_equalities_const(PlannerInfo *root,
1117 : EquivalenceClass *ec)
1118 : {
1119 194118 : 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 369818 : if (list_length(ec->ec_members) == 2 &&
1130 175700 : list_length(ec->ec_sources) == 1)
1131 : {
1132 175700 : RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
1133 :
1134 175700 : distribute_restrictinfo_to_rels(root, restrictinfo);
1135 175700 : 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 42320 : foreach(lc, ec->ec_members)
1145 : {
1146 42300 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1147 :
1148 42300 : if (cur_em->em_is_const)
1149 : {
1150 18418 : const_em = cur_em;
1151 18418 : if (IsA(cur_em->em_expr, Const))
1152 18398 : break;
1153 : }
1154 : }
1155 : Assert(const_em != NULL);
1156 :
1157 : /* Generate a derived equality against each other member */
1158 73792 : foreach(lc, ec->ec_members)
1159 : {
1160 55404 : 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 55404 : if (cur_em == const_em)
1166 18394 : continue;
1167 37010 : eq_op = select_equality_operator(ec,
1168 : cur_em->em_datatype,
1169 : const_em->em_datatype);
1170 37010 : if (!OidIsValid(eq_op))
1171 : {
1172 : /* failed... */
1173 30 : ec->ec_broken = true;
1174 30 : 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 36980 : rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
1183 : cur_em->em_expr, const_em->em_expr,
1184 36980 : const_em->em_jdomain->jd_relids,
1185 : ec->ec_min_security,
1186 36980 : 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 36980 : if (rinfo && rinfo->mergeopfamilies)
1197 : {
1198 : /* it's not redundant, so don't set parent_ec */
1199 36854 : rinfo->left_ec = rinfo->right_ec = ec;
1200 36854 : rinfo->left_em = cur_em;
1201 36854 : rinfo->right_em = const_em;
1202 36854 : 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
1211 54424 : generate_base_implied_equalities_no_const(PlannerInfo *root,
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 54424 : palloc0(root->simple_rel_array_size * sizeof(EquivalenceMember *));
1227 :
1228 164916 : foreach(lc, ec->ec_members)
1229 : {
1230 110492 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1231 : int relid;
1232 :
1233 : Assert(!cur_em->em_is_child); /* no children yet */
1234 110492 : if (!bms_get_singleton_member(cur_em->em_relids, &relid))
1235 162 : continue;
1236 : Assert(relid < root->simple_rel_array_size);
1237 :
1238 110330 : if (prev_ems[relid] != NULL)
1239 : {
1240 400 : EquivalenceMember *prev_em = prev_ems[relid];
1241 : Oid eq_op;
1242 : RestrictInfo *rinfo;
1243 :
1244 400 : eq_op = select_equality_operator(ec,
1245 : prev_em->em_datatype,
1246 : cur_em->em_datatype);
1247 400 : if (!OidIsValid(eq_op))
1248 : {
1249 : /* failed... */
1250 0 : ec->ec_broken = true;
1251 0 : 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 400 : 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 400 : if (rinfo && rinfo->mergeopfamilies)
1273 : {
1274 : /* it's not redundant, so don't set parent_ec */
1275 400 : rinfo->left_ec = rinfo->right_ec = ec;
1276 400 : rinfo->left_em = prev_em;
1277 400 : rinfo->right_em = cur_em;
1278 : }
1279 : }
1280 110330 : prev_ems[relid] = cur_em;
1281 : }
1282 :
1283 54424 : 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 164916 : foreach(lc, ec->ec_members)
1295 : {
1296 110492 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1297 110492 : List *vars = pull_var_clause((Node *) cur_em->em_expr,
1298 : PVC_RECURSE_AGGREGATES |
1299 : PVC_RECURSE_WINDOWFUNCS |
1300 : PVC_INCLUDE_PLACEHOLDERS);
1301 :
1302 110492 : add_vars_to_targetlist(root, vars, ec->ec_relids);
1303 110492 : list_free(vars);
1304 : }
1305 54424 : }
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
1322 30 : generate_base_implied_equalities_broken(PlannerInfo *root,
1323 : EquivalenceClass *ec)
1324 : {
1325 : ListCell *lc;
1326 :
1327 96 : foreach(lc, ec->ec_sources)
1328 : {
1329 66 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
1330 :
1331 66 : if (ec->ec_has_const ||
1332 0 : bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
1333 66 : distribute_restrictinfo_to_rels(root, restrictinfo);
1334 : }
1335 30 : }
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 *
1385 433470 : generate_join_implied_equalities(PlannerInfo *root,
1386 : Relids join_relids,
1387 : Relids outer_relids,
1388 : RelOptInfo *inner_rel,
1389 : SpecialJoinInfo *sjinfo)
1390 : {
1391 433470 : List *result = NIL;
1392 433470 : 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 433470 : 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 6880 : nominal_inner_relids = inner_rel->top_parent_relids;
1405 : /* ECs will be marked with the parent's relid, not the child's */
1406 6880 : nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1407 6880 : nominal_join_relids = add_outer_joins_to_relids(root,
1408 : nominal_join_relids,
1409 : sjinfo,
1410 : NULL);
1411 : }
1412 : else
1413 : {
1414 426590 : nominal_inner_relids = inner_relids;
1415 426590 : 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 433470 : if (sjinfo && sjinfo->ojrelid != 0)
1432 81762 : matching_ecs = get_eclass_indexes_for_relids(root, nominal_join_relids);
1433 : else
1434 351708 : matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
1435 : outer_relids);
1436 :
1437 433470 : i = -1;
1438 1237990 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
1439 : {
1440 804520 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
1441 804520 : List *sublist = NIL;
1442 :
1443 : /* ECs containing consts do not need any further enforcement */
1444 804520 : if (ec->ec_has_const)
1445 117826 : continue;
1446 :
1447 : /* Single-member ECs won't generate any deductions */
1448 686694 : if (list_length(ec->ec_members) <= 1)
1449 375720 : continue;
1450 :
1451 : /* Sanity check that this eclass overlaps the join */
1452 : Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
1453 :
1454 310974 : if (!ec->ec_broken)
1455 310650 : sublist = generate_join_implied_equalities_normal(root,
1456 : ec,
1457 : join_relids,
1458 : outer_relids,
1459 : inner_relids);
1460 :
1461 : /* Recover if we failed to generate required derived clauses */
1462 310974 : if (ec->ec_broken)
1463 354 : sublist = generate_join_implied_equalities_broken(root,
1464 : ec,
1465 : nominal_join_relids,
1466 : outer_relids,
1467 : nominal_inner_relids,
1468 : inner_rel);
1469 :
1470 310974 : result = list_concat(result, sublist);
1471 : }
1472 :
1473 433470 : 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 *
1485 900 : generate_join_implied_equalities_for_ecs(PlannerInfo *root,
1486 : List *eclasses,
1487 : Relids join_relids,
1488 : Relids outer_relids,
1489 : RelOptInfo *inner_rel)
1490 : {
1491 900 : List *result = NIL;
1492 900 : 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 900 : 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 0 : nominal_inner_relids = inner_rel->top_parent_relids;
1504 : /* ECs will be marked with the parent's relid, not the child's */
1505 0 : nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1506 : }
1507 : else
1508 : {
1509 900 : nominal_inner_relids = inner_relids;
1510 900 : nominal_join_relids = join_relids;
1511 : }
1512 :
1513 1848 : foreach(lc, eclasses)
1514 : {
1515 948 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
1516 948 : List *sublist = NIL;
1517 :
1518 : /* ECs containing consts do not need any further enforcement */
1519 948 : if (ec->ec_has_const)
1520 0 : continue;
1521 :
1522 : /* Single-member ECs won't generate any deductions */
1523 948 : if (list_length(ec->ec_members) <= 1)
1524 0 : continue;
1525 :
1526 : /* We can quickly ignore any that don't overlap the join, too */
1527 948 : if (!bms_overlap(ec->ec_relids, nominal_join_relids))
1528 0 : continue;
1529 :
1530 948 : if (!ec->ec_broken)
1531 948 : sublist = generate_join_implied_equalities_normal(root,
1532 : ec,
1533 : join_relids,
1534 : outer_relids,
1535 : inner_relids);
1536 :
1537 : /* Recover if we failed to generate required derived clauses */
1538 948 : if (ec->ec_broken)
1539 0 : sublist = generate_join_implied_equalities_broken(root,
1540 : ec,
1541 : nominal_join_relids,
1542 : outer_relids,
1543 : nominal_inner_relids,
1544 : inner_rel);
1545 :
1546 948 : result = list_concat(result, sublist);
1547 : }
1548 :
1549 900 : return result;
1550 : }
1551 :
1552 : /*
1553 : * generate_join_implied_equalities for a still-valid EC
1554 : */
1555 : static List *
1556 311598 : generate_join_implied_equalities_normal(PlannerInfo *root,
1557 : EquivalenceClass *ec,
1558 : Relids join_relids,
1559 : Relids outer_relids,
1560 : Relids inner_relids)
1561 : {
1562 311598 : List *result = NIL;
1563 311598 : List *new_members = NIL;
1564 311598 : List *outer_members = NIL;
1565 311598 : 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 1061580 : foreach(lc1, ec->ec_members)
1578 : {
1579 749982 : 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 749982 : if (!bms_is_subset(cur_em->em_relids, join_relids))
1587 131400 : continue; /* not computable yet, or wrong child */
1588 :
1589 618582 : if (bms_is_subset(cur_em->em_relids, outer_relids))
1590 358564 : outer_members = lappend(outer_members, cur_em);
1591 260018 : else if (bms_is_subset(cur_em->em_relids, inner_relids))
1592 258458 : inner_members = lappend(inner_members, cur_em);
1593 : else
1594 1560 : 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 311598 : if (outer_members && inner_members)
1607 : {
1608 247358 : EquivalenceMember *best_outer_em = NULL;
1609 247358 : EquivalenceMember *best_inner_em = NULL;
1610 247358 : Oid best_eq_op = InvalidOid;
1611 247358 : int best_score = -1;
1612 : RestrictInfo *rinfo;
1613 :
1614 261482 : foreach(lc1, outer_members)
1615 : {
1616 247430 : EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
1617 : ListCell *lc2;
1618 :
1619 261566 : foreach(lc2, inner_members)
1620 : {
1621 247442 : EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
1622 : Oid eq_op;
1623 : int score;
1624 :
1625 247442 : eq_op = select_equality_operator(ec,
1626 : outer_em->em_datatype,
1627 : inner_em->em_datatype);
1628 247442 : if (!OidIsValid(eq_op))
1629 30 : continue;
1630 247412 : score = 0;
1631 247412 : if (IsA(outer_em->em_expr, Var) ||
1632 15422 : (IsA(outer_em->em_expr, RelabelType) &&
1633 3444 : IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1634 235386 : score++;
1635 247412 : if (IsA(inner_em->em_expr, Var) ||
1636 5490 : (IsA(inner_em->em_expr, RelabelType) &&
1637 3062 : IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
1638 244966 : score++;
1639 247412 : if (op_hashjoinable(eq_op,
1640 247412 : exprType((Node *) outer_em->em_expr)))
1641 247340 : score++;
1642 247412 : if (score > best_score)
1643 : {
1644 247328 : best_outer_em = outer_em;
1645 247328 : best_inner_em = inner_em;
1646 247328 : best_eq_op = eq_op;
1647 247328 : best_score = score;
1648 247328 : if (best_score == 3)
1649 233306 : break; /* no need to look further */
1650 : }
1651 : }
1652 247430 : if (best_score == 3)
1653 233306 : break; /* no need to look further */
1654 : }
1655 247358 : if (best_score < 0)
1656 : {
1657 : /* failed... */
1658 30 : ec->ec_broken = true;
1659 30 : return NIL;
1660 : }
1661 :
1662 : /*
1663 : * Create clause, setting parent_ec to mark it as redundant with other
1664 : * joinclauses
1665 : */
1666 247328 : rinfo = create_join_clause(root, ec, best_eq_op,
1667 : best_outer_em, best_inner_em,
1668 : ec);
1669 :
1670 247328 : 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 311568 : if (new_members)
1683 : {
1684 1524 : List *old_members = list_concat(outer_members, inner_members);
1685 1524 : EquivalenceMember *prev_em = NULL;
1686 : RestrictInfo *rinfo;
1687 :
1688 : /* For now, arbitrarily take the first old_member as the one to use */
1689 1524 : if (old_members)
1690 1104 : new_members = lappend(new_members, linitial(old_members));
1691 :
1692 4188 : foreach(lc1, new_members)
1693 : {
1694 2664 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc1);
1695 :
1696 2664 : if (prev_em != NULL)
1697 : {
1698 : Oid eq_op;
1699 :
1700 1140 : eq_op = select_equality_operator(ec,
1701 : prev_em->em_datatype,
1702 : cur_em->em_datatype);
1703 1140 : if (!OidIsValid(eq_op))
1704 : {
1705 : /* failed... */
1706 0 : ec->ec_broken = true;
1707 0 : return NIL;
1708 : }
1709 : /* do NOT set parent_ec, this qual is not redundant! */
1710 1140 : rinfo = create_join_clause(root, ec, eq_op,
1711 : prev_em, cur_em,
1712 : NULL);
1713 :
1714 1140 : result = lappend(result, rinfo);
1715 : }
1716 2664 : prev_em = cur_em;
1717 : }
1718 : }
1719 :
1720 311568 : 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 *
1732 354 : generate_join_implied_equalities_broken(PlannerInfo *root,
1733 : EquivalenceClass *ec,
1734 : Relids nominal_join_relids,
1735 : Relids outer_relids,
1736 : Relids nominal_inner_relids,
1737 : RelOptInfo *inner_rel)
1738 : {
1739 354 : List *result = NIL;
1740 : ListCell *lc;
1741 :
1742 972 : foreach(lc, ec->ec_sources)
1743 : {
1744 618 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(lc);
1745 618 : Relids clause_relids = restrictinfo->required_relids;
1746 :
1747 618 : if (bms_is_subset(clause_relids, nominal_join_relids) &&
1748 330 : !bms_is_subset(clause_relids, outer_relids) &&
1749 306 : !bms_is_subset(clause_relids, nominal_inner_relids))
1750 306 : 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 354 : if (IS_OTHER_REL(inner_rel) && result != NIL)
1765 162 : result = (List *) adjust_appendrel_attrs_multilevel(root,
1766 : (Node *) result,
1767 : inner_rel,
1768 162 : inner_rel->top_parent);
1769 :
1770 354 : 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
1781 380546 : select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
1782 : {
1783 : ListCell *lc;
1784 :
1785 380606 : foreach(lc, ec->ec_opfamilies)
1786 : {
1787 380546 : Oid opfamily = lfirst_oid(lc);
1788 : Oid opno;
1789 :
1790 380546 : opno = get_opfamily_member(opfamily, lefttype, righttype,
1791 : BTEqualStrategyNumber);
1792 380546 : if (!OidIsValid(opno))
1793 60 : continue;
1794 : /* If no barrier quals in query, don't worry about leaky operators */
1795 380486 : if (ec->ec_max_security == 0)
1796 380486 : return opno;
1797 : /* Otherwise, insist that selected operators be leakproof */
1798 428 : if (get_func_leakproof(get_opcode(opno)))
1799 428 : return opno;
1800 : }
1801 60 : 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 *
1817 345132 : create_join_clause(PlannerInfo *root,
1818 : EquivalenceClass *ec, Oid opno,
1819 : EquivalenceMember *leftem,
1820 : EquivalenceMember *rightem,
1821 : EquivalenceClass *parent_ec)
1822 : {
1823 : RestrictInfo *rinfo;
1824 345132 : 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 744488 : foreach(lc, ec->ec_sources)
1838 : {
1839 400334 : rinfo = (RestrictInfo *) lfirst(lc);
1840 400334 : if (rinfo->left_em == leftem &&
1841 180948 : rinfo->right_em == rightem &&
1842 160910 : rinfo->parent_ec == parent_ec)
1843 978 : return rinfo;
1844 400226 : if (rinfo->left_em == rightem &&
1845 180260 : rinfo->right_em == leftem &&
1846 164360 : rinfo->parent_ec == parent_ec)
1847 870 : return rinfo;
1848 : }
1849 :
1850 435196 : foreach(lc, ec->ec_derives)
1851 : {
1852 374154 : rinfo = (RestrictInfo *) lfirst(lc);
1853 374154 : if (rinfo->left_em == leftem &&
1854 148768 : rinfo->right_em == rightem &&
1855 134642 : rinfo->parent_ec == parent_ec)
1856 283112 : return rinfo;
1857 239518 : if (rinfo->left_em == rightem &&
1858 156098 : rinfo->right_em == leftem &&
1859 148476 : rinfo->parent_ec == parent_ec)
1860 148476 : 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 61042 : 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 61042 : if (leftem->em_is_child || rightem->em_is_child)
1874 : {
1875 3838 : EquivalenceMember *leftp = leftem->em_parent ? leftem->em_parent : leftem;
1876 3838 : EquivalenceMember *rightp = rightem->em_parent ? rightem->em_parent : rightem;
1877 :
1878 3838 : parent_rinfo = create_join_clause(root, ec, opno,
1879 : leftp, rightp,
1880 : parent_ec);
1881 : }
1882 :
1883 61042 : rinfo = build_implied_join_equality(root,
1884 : opno,
1885 : ec->ec_collation,
1886 : leftem->em_expr,
1887 : rightem->em_expr,
1888 61042 : bms_union(leftem->em_relids,
1889 61042 : 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 61042 : if (leftem->em_is_child)
1901 3298 : rinfo->clause_relids = bms_add_members(rinfo->clause_relids,
1902 3298 : leftem->em_relids);
1903 61042 : if (rightem->em_is_child)
1904 540 : rinfo->clause_relids = bms_add_members(rinfo->clause_relids,
1905 540 : rightem->em_relids);
1906 :
1907 : /* If it's a child clause, copy the parent's rinfo_serial */
1908 61042 : if (parent_rinfo)
1909 3838 : rinfo->rinfo_serial = parent_rinfo->rinfo_serial;
1910 :
1911 : /* Mark the clause as redundant, or not */
1912 61042 : 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 61042 : rinfo->left_ec = ec;
1919 61042 : rinfo->right_ec = ec;
1920 :
1921 : /* Mark it as usable with these EMs */
1922 61042 : rinfo->left_em = leftem;
1923 61042 : rinfo->right_em = rightem;
1924 : /* and save it for possible re-use */
1925 61042 : ec->ec_derives = lappend(ec->ec_derives, rinfo);
1926 :
1927 61042 : MemoryContextSwitchTo(oldcontext);
1928 :
1929 61042 : 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
2001 293528 : reconsider_outer_join_clauses(PlannerInfo *root)
2002 : {
2003 : bool found;
2004 : ListCell *cell;
2005 :
2006 : /* Outer loop repeats until we find no more deductions */
2007 : do
2008 : {
2009 293528 : found = false;
2010 :
2011 : /* Process the LEFT JOIN clauses */
2012 317326 : foreach(cell, root->left_join_clauses)
2013 : {
2014 23798 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2015 :
2016 23798 : if (reconsider_outer_join_clause(root, ojcinfo, true))
2017 : {
2018 716 : RestrictInfo *rinfo = ojcinfo->rinfo;
2019 :
2020 716 : found = true;
2021 : /* remove it from the list */
2022 716 : root->left_join_clauses =
2023 716 : foreach_delete_current(root->left_join_clauses, cell);
2024 : /* throw back a dummy replacement clause (see notes above) */
2025 716 : rinfo = make_restrictinfo(root,
2026 716 : (Expr *) makeBoolConst(true, false),
2027 716 : rinfo->is_pushed_down,
2028 716 : rinfo->has_clone,
2029 716 : rinfo->is_clone,
2030 : false, /* pseudoconstant */
2031 : 0, /* security_level */
2032 : rinfo->required_relids,
2033 : rinfo->incompatible_relids,
2034 : rinfo->outer_relids);
2035 716 : distribute_restrictinfo_to_rels(root, rinfo);
2036 : }
2037 : }
2038 :
2039 : /* Process the RIGHT JOIN clauses */
2040 319786 : foreach(cell, root->right_join_clauses)
2041 : {
2042 26258 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2043 :
2044 26258 : if (reconsider_outer_join_clause(root, ojcinfo, false))
2045 : {
2046 958 : RestrictInfo *rinfo = ojcinfo->rinfo;
2047 :
2048 958 : found = true;
2049 : /* remove it from the list */
2050 958 : root->right_join_clauses =
2051 958 : foreach_delete_current(root->right_join_clauses, cell);
2052 : /* throw back a dummy replacement clause (see notes above) */
2053 958 : rinfo = make_restrictinfo(root,
2054 958 : (Expr *) makeBoolConst(true, false),
2055 958 : rinfo->is_pushed_down,
2056 958 : rinfo->has_clone,
2057 958 : rinfo->is_clone,
2058 : false, /* pseudoconstant */
2059 : 0, /* security_level */
2060 : rinfo->required_relids,
2061 : rinfo->incompatible_relids,
2062 : rinfo->outer_relids);
2063 958 : distribute_restrictinfo_to_rels(root, rinfo);
2064 : }
2065 : }
2066 :
2067 : /* Process the FULL JOIN clauses */
2068 294762 : foreach(cell, root->full_join_clauses)
2069 : {
2070 1234 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2071 :
2072 1234 : if (reconsider_full_join_clause(root, ojcinfo))
2073 : {
2074 6 : RestrictInfo *rinfo = ojcinfo->rinfo;
2075 :
2076 6 : found = true;
2077 : /* remove it from the list */
2078 6 : root->full_join_clauses =
2079 6 : foreach_delete_current(root->full_join_clauses, cell);
2080 : /* throw back a dummy replacement clause (see notes above) */
2081 6 : rinfo = make_restrictinfo(root,
2082 6 : (Expr *) makeBoolConst(true, false),
2083 6 : rinfo->is_pushed_down,
2084 6 : rinfo->has_clone,
2085 6 : rinfo->is_clone,
2086 : false, /* pseudoconstant */
2087 : 0, /* security_level */
2088 : rinfo->required_relids,
2089 : rinfo->incompatible_relids,
2090 : rinfo->outer_relids);
2091 6 : distribute_restrictinfo_to_rels(root, rinfo);
2092 : }
2093 : }
2094 293528 : } while (found);
2095 :
2096 : /* Now, any remaining clauses have to be thrown back */
2097 314408 : foreach(cell, root->left_join_clauses)
2098 : {
2099 22548 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2100 :
2101 22548 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2102 : }
2103 316154 : foreach(cell, root->right_join_clauses)
2104 : {
2105 24294 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2106 :
2107 24294 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2108 : }
2109 293088 : foreach(cell, root->full_join_clauses)
2110 : {
2111 1228 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2112 :
2113 1228 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2114 : }
2115 291860 : }
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
2123 50056 : reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
2124 : bool outer_on_left)
2125 : {
2126 50056 : RestrictInfo *rinfo = ojcinfo->rinfo;
2127 50056 : 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 50056 : opno = ((OpExpr *) rinfo->clause)->opno;
2140 50056 : collation = ((OpExpr *) rinfo->clause)->inputcollid;
2141 :
2142 : /* Extract needed info from the clause */
2143 50056 : op_input_types(opno, &left_type, &right_type);
2144 50056 : if (outer_on_left)
2145 : {
2146 23798 : outervar = (Expr *) get_leftop(rinfo->clause);
2147 23798 : innervar = (Expr *) get_rightop(rinfo->clause);
2148 23798 : inner_datatype = right_type;
2149 23798 : inner_relids = rinfo->right_relids;
2150 : }
2151 : else
2152 : {
2153 26258 : outervar = (Expr *) get_rightop(rinfo->clause);
2154 26258 : innervar = (Expr *) get_leftop(rinfo->clause);
2155 26258 : inner_datatype = left_type;
2156 26258 : inner_relids = rinfo->left_relids;
2157 : }
2158 :
2159 : /* Scan EquivalenceClasses for a match to outervar */
2160 318738 : foreach(lc1, root->eq_classes)
2161 : {
2162 270356 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2163 : bool match;
2164 : ListCell *lc2;
2165 :
2166 : /* Ignore EC unless it contains pseudoconstants */
2167 270356 : if (!cur_ec->ec_has_const)
2168 203548 : continue;
2169 : /* Never match to a volatile EC */
2170 66808 : if (cur_ec->ec_has_volatile)
2171 0 : continue;
2172 : /* It has to match the outer-join clause as to semantics, too */
2173 66808 : if (collation != cur_ec->ec_collation)
2174 2398 : continue;
2175 64410 : if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
2176 12270 : continue;
2177 : /* Does it contain a match to outervar? */
2178 52140 : match = false;
2179 161862 : foreach(lc2, cur_ec->ec_members)
2180 : {
2181 111396 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2182 :
2183 : Assert(!cur_em->em_is_child); /* no children yet */
2184 111396 : if (equal(outervar, cur_em->em_expr))
2185 : {
2186 1674 : match = true;
2187 1674 : break;
2188 : }
2189 : }
2190 52140 : if (!match)
2191 50466 : 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 1674 : match = false;
2199 6028 : foreach(lc2, cur_ec->ec_members)
2200 : {
2201 4354 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2202 : Oid eq_op;
2203 : RestrictInfo *newrinfo;
2204 : JoinDomain *jdomain;
2205 :
2206 4354 : if (!cur_em->em_is_const)
2207 2638 : continue; /* ignore non-const members */
2208 1716 : eq_op = select_equality_operator(cur_ec,
2209 : inner_datatype,
2210 : cur_em->em_datatype);
2211 1716 : if (!OidIsValid(eq_op))
2212 0 : continue; /* can't generate equality */
2213 1716 : 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 1716 : jdomain = find_join_domain(root, sjinfo->syn_righthand);
2222 1716 : if (process_equivalence(root, &newrinfo, jdomain))
2223 1716 : 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 1674 : if (match)
2232 1674 : return true;
2233 : else
2234 0 : break;
2235 : }
2236 :
2237 48382 : 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
2246 1234 : reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
2247 : {
2248 1234 : RestrictInfo *rinfo = ojcinfo->rinfo;
2249 1234 : SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
2250 1234 : 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 1234 : opno = ((OpExpr *) rinfo->clause)->opno;
2264 1234 : collation = ((OpExpr *) rinfo->clause)->inputcollid;
2265 1234 : op_input_types(opno, &left_type, &right_type);
2266 1234 : leftvar = (Expr *) get_leftop(rinfo->clause);
2267 1234 : rightvar = (Expr *) get_rightop(rinfo->clause);
2268 1234 : left_relids = rinfo->left_relids;
2269 1234 : right_relids = rinfo->right_relids;
2270 :
2271 6282 : foreach(lc1, root->eq_classes)
2272 : {
2273 5054 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2274 5054 : EquivalenceMember *coal_em = NULL;
2275 : bool match;
2276 : bool matchleft;
2277 : bool matchright;
2278 : ListCell *lc2;
2279 5054 : int coal_idx = -1;
2280 :
2281 : /* Ignore EC unless it contains pseudoconstants */
2282 5054 : if (!cur_ec->ec_has_const)
2283 4758 : continue;
2284 : /* Never match to a volatile EC */
2285 296 : if (cur_ec->ec_has_volatile)
2286 0 : continue;
2287 : /* It has to match the outer-join clause as to semantics, too */
2288 296 : if (collation != cur_ec->ec_collation)
2289 36 : continue;
2290 260 : if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
2291 0 : 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 260 : match = false;
2307 762 : foreach(lc2, cur_ec->ec_members)
2308 : {
2309 508 : coal_em = (EquivalenceMember *) lfirst(lc2);
2310 : Assert(!coal_em->em_is_child); /* no children yet */
2311 508 : if (IsA(coal_em->em_expr, CoalesceExpr))
2312 : {
2313 18 : CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
2314 : Node *cfirst;
2315 : Node *csecond;
2316 :
2317 18 : if (list_length(cexpr->args) != 2)
2318 12 : continue;
2319 6 : cfirst = (Node *) linitial(cexpr->args);
2320 6 : 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 6 : cfirst = remove_nulling_relids(cfirst, fjrelids, NULL);
2332 6 : csecond = remove_nulling_relids(csecond, fjrelids, NULL);
2333 :
2334 6 : if (equal(leftvar, cfirst) && equal(rightvar, csecond))
2335 : {
2336 6 : coal_idx = foreach_current_index(lc2);
2337 6 : match = true;
2338 6 : break;
2339 : }
2340 : }
2341 : }
2342 260 : if (!match)
2343 254 : 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 6 : matchleft = matchright = false;
2352 18 : foreach(lc2, cur_ec->ec_members)
2353 : {
2354 12 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2355 : Oid eq_op;
2356 : RestrictInfo *newrinfo;
2357 : JoinDomain *jdomain;
2358 :
2359 12 : if (!cur_em->em_is_const)
2360 6 : continue; /* ignore non-const members */
2361 6 : eq_op = select_equality_operator(cur_ec,
2362 : left_type,
2363 : cur_em->em_datatype);
2364 6 : if (OidIsValid(eq_op))
2365 : {
2366 6 : 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 6 : jdomain = find_join_domain(root, sjinfo->syn_lefthand);
2375 6 : if (process_equivalence(root, &newrinfo, jdomain))
2376 6 : matchleft = true;
2377 : }
2378 6 : eq_op = select_equality_operator(cur_ec,
2379 : right_type,
2380 : cur_em->em_datatype);
2381 6 : if (OidIsValid(eq_op))
2382 : {
2383 6 : 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 6 : jdomain = find_join_domain(root, sjinfo->syn_righthand);
2392 6 : if (process_equivalence(root, &newrinfo, jdomain))
2393 6 : 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 6 : if (matchleft && matchright)
2405 : {
2406 6 : cur_ec->ec_members = list_delete_nth_cell(cur_ec->ec_members, coal_idx);
2407 6 : 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 0 : break;
2416 : }
2417 :
2418 1228 : 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
2431 9496 : rebuild_eclass_attr_needed(PlannerInfo *root)
2432 : {
2433 : ListCell *lc;
2434 :
2435 52144 : foreach(lc, root->eq_classes)
2436 : {
2437 42648 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
2438 :
2439 : /* Need do anything only for a multi-member, no-const EC. */
2440 42648 : if (list_length(ec->ec_members) > 1 && !ec->ec_has_const)
2441 : {
2442 : ListCell *lc2;
2443 :
2444 9950 : foreach(lc2, ec->ec_members)
2445 : {
2446 6642 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2447 6642 : List *vars = pull_var_clause((Node *) cur_em->em_expr,
2448 : PVC_RECURSE_AGGREGATES |
2449 : PVC_RECURSE_WINDOWFUNCS |
2450 : PVC_INCLUDE_PLACEHOLDERS);
2451 :
2452 6642 : add_vars_to_attr_needed(root, vars, ec->ec_relids);
2453 6642 : list_free(vars);
2454 : }
2455 : }
2456 : }
2457 9496 : }
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 *
2467 1728 : find_join_domain(PlannerInfo *root, Relids relids)
2468 : {
2469 : ListCell *lc;
2470 :
2471 3546 : foreach(lc, root->join_domains)
2472 : {
2473 3546 : JoinDomain *jdomain = (JoinDomain *) lfirst(lc);
2474 :
2475 3546 : if (bms_is_subset(jdomain->jd_relids, relids))
2476 1728 : return jdomain;
2477 : }
2478 0 : 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 6042 : exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
2499 : {
2500 : ListCell *lc1;
2501 :
2502 27694 : foreach(lc1, root->eq_classes)
2503 : {
2504 21826 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2505 21826 : bool item1member = false;
2506 21826 : bool item2member = false;
2507 : ListCell *lc2;
2508 :
2509 : /* Never match to a volatile EC */
2510 21826 : if (ec->ec_has_volatile)
2511 0 : 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 21826 : if (OidIsValid(opfamily) &&
2521 648 : !list_member_oid(ec->ec_opfamilies, opfamily))
2522 228 : continue;
2523 :
2524 70984 : foreach(lc2, ec->ec_members)
2525 : {
2526 49560 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
2527 :
2528 49560 : if (em->em_is_child)
2529 12444 : continue; /* ignore children here */
2530 37116 : if (equal(item1, em->em_expr))
2531 1738 : item1member = true;
2532 35378 : else if (equal(item2, em->em_expr))
2533 1876 : item2member = true;
2534 : /* Exit as soon as equality is proven */
2535 37116 : if (item1member && item2member)
2536 174 : return true;
2537 : }
2538 : }
2539 5868 : 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 : */
2558 : EquivalenceClass *
2559 2180 : match_eclasses_to_foreign_key_col(PlannerInfo *root,
2560 : ForeignKeyOptInfo *fkinfo,
2561 : int colno)
2562 : {
2563 2180 : Index var1varno = fkinfo->con_relid;
2564 2180 : AttrNumber var1attno = fkinfo->conkey[colno];
2565 2180 : Index var2varno = fkinfo->ref_relid;
2566 2180 : AttrNumber var2attno = fkinfo->confkey[colno];
2567 2180 : Oid eqop = fkinfo->conpfeqop[colno];
2568 2180 : RelOptInfo *rel1 = root->simple_rel_array[var1varno];
2569 2180 : RelOptInfo *rel2 = root->simple_rel_array[var2varno];
2570 2180 : 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 2180 : matching_ecs = bms_intersect(rel1->eclass_indexes,
2579 2180 : rel2->eclass_indexes);
2580 :
2581 2180 : i = -1;
2582 2276 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
2583 : {
2584 438 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
2585 : i);
2586 438 : EquivalenceMember *item1_em = NULL;
2587 438 : EquivalenceMember *item2_em = NULL;
2588 : ListCell *lc2;
2589 :
2590 : /* Never match to a volatile EC */
2591 438 : if (ec->ec_has_volatile)
2592 0 : continue;
2593 : /* It's okay to consider "broken" ECs here, see exprs_known_equal */
2594 :
2595 1074 : foreach(lc2, ec->ec_members)
2596 : {
2597 978 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
2598 : Var *var;
2599 :
2600 978 : if (em->em_is_child)
2601 0 : continue; /* ignore children here */
2602 :
2603 : /* EM must be a Var, possibly with RelabelType */
2604 978 : var = (Var *) em->em_expr;
2605 978 : while (var && IsA(var, RelabelType))
2606 0 : var = (Var *) ((RelabelType *) var)->arg;
2607 978 : if (!(var && IsA(var, Var)))
2608 6 : continue;
2609 :
2610 : /* Match? */
2611 972 : if (var->varno == var1varno && var->varattno == var1attno)
2612 342 : item1_em = em;
2613 630 : else if (var->varno == var2varno && var->varattno == var2attno)
2614 342 : item2_em = em;
2615 :
2616 : /* Have we found both PK and FK column in this EC? */
2617 972 : 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 342 : if (opfamilies == NIL) /* compute if we didn't already */
2625 342 : opfamilies = get_mergejoin_opfamilies(eqop);
2626 342 : if (equal(opfamilies, ec->ec_opfamilies))
2627 : {
2628 342 : fkinfo->eclass[colno] = ec;
2629 342 : fkinfo->fk_eclass_member[colno] = item2_em;
2630 342 : return ec;
2631 : }
2632 : /* Otherwise, done with this EC, move on to the next */
2633 0 : break;
2634 : }
2635 : }
2636 : }
2637 1838 : 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 *
2650 6 : find_derived_clause_for_ec_member(EquivalenceClass *ec,
2651 : EquivalenceMember *em)
2652 : {
2653 : ListCell *lc;
2654 :
2655 : Assert(ec->ec_has_const);
2656 : Assert(!em->em_is_const);
2657 6 : foreach(lc, ec->ec_derives)
2658 : {
2659 6 : 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 6 : if (rinfo->left_em == em)
2666 6 : return rinfo;
2667 : }
2668 0 : 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
2690 22330 : add_child_rel_equivalences(PlannerInfo *root,
2691 : AppendRelInfo *appinfo,
2692 : RelOptInfo *parent_rel,
2693 : RelOptInfo *child_rel)
2694 : {
2695 22330 : Relids top_parent_relids = child_rel->top_parent_relids;
2696 22330 : 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 22330 : i = -1;
2707 65938 : while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
2708 : {
2709 43608 : 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 43608 : if (cur_ec->ec_has_volatile)
2718 0 : 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 43608 : num_members = list_length(cur_ec->ec_members);
2729 205958 : for (int pos = 0; pos < num_members; pos++)
2730 : {
2731 162350 : EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
2732 :
2733 162350 : if (cur_em->em_is_const)
2734 3168 : 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 159182 : if (cur_em->em_is_child)
2745 100930 : 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 58252 : if (bms_is_subset(cur_em->em_relids, top_parent_relids) &&
2756 41346 : !bms_is_empty(cur_em->em_relids))
2757 : {
2758 : /* OK, generate transformed child version */
2759 : Expr *child_expr;
2760 : Relids new_relids;
2761 :
2762 41346 : if (parent_rel->reloptkind == RELOPT_BASEREL)
2763 : {
2764 : /* Simple single-level transformation */
2765 : child_expr = (Expr *)
2766 33480 : adjust_appendrel_attrs(root,
2767 33480 : (Node *) cur_em->em_expr,
2768 : 1, &appinfo);
2769 : }
2770 : else
2771 : {
2772 : /* Must do multi-level transformation */
2773 : child_expr = (Expr *)
2774 7866 : adjust_appendrel_attrs_multilevel(root,
2775 7866 : (Node *) cur_em->em_expr,
2776 : child_rel,
2777 7866 : 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 41346 : new_relids = bms_difference(cur_em->em_relids,
2787 : top_parent_relids);
2788 41346 : new_relids = bms_add_members(new_relids, child_relids);
2789 :
2790 41346 : (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 41346 : child_rel->eclass_indexes = bms_add_member(child_rel->eclass_indexes, i);
2796 : }
2797 : }
2798 : }
2799 22330 : }
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
2812 4324 : add_child_join_rel_equivalences(PlannerInfo *root,
2813 : int nappinfos, AppendRelInfo **appinfos,
2814 : RelOptInfo *parent_joinrel,
2815 : RelOptInfo *child_joinrel)
2816 : {
2817 4324 : Relids top_parent_relids = child_joinrel->top_parent_relids;
2818 4324 : 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 4324 : 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 4324 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2837 :
2838 4324 : i = -1;
2839 20058 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
2840 : {
2841 15734 : 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 15734 : if (cur_ec->ec_has_volatile)
2850 0 : 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 15734 : num_members = list_length(cur_ec->ec_members);
2861 106934 : for (int pos = 0; pos < num_members; pos++)
2862 : {
2863 91200 : EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
2864 :
2865 91200 : if (cur_em->em_is_const)
2866 2232 : continue; /* ignore consts here */
2867 :
2868 : /*
2869 : * We consider only original EC members here, not
2870 : * already-transformed child members.
2871 : */
2872 88968 : if (cur_em->em_is_child)
2873 68786 : 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 20182 : if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
2880 17560 : continue;
2881 :
2882 : /* Does this member reference child's topmost parent rel? */
2883 2622 : 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 2622 : if (parent_joinrel->reloptkind == RELOPT_JOINREL)
2890 : {
2891 : /* Simple single-level transformation */
2892 : child_expr = (Expr *)
2893 2526 : adjust_appendrel_attrs(root,
2894 2526 : (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 *)
2902 96 : adjust_appendrel_attrs_multilevel(root,
2903 96 : (Node *) cur_em->em_expr,
2904 : child_joinrel,
2905 96 : 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 2622 : new_relids = bms_difference(cur_em->em_relids,
2915 : top_parent_relids);
2916 2622 : new_relids = bms_add_members(new_relids, child_relids);
2917 :
2918 2622 : (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 4324 : MemoryContextSwitchTo(oldcontext);
2926 4324 : }
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
2942 9926 : add_setop_child_rel_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
2943 : List *child_tlist, List *setop_pathkeys)
2944 : {
2945 : ListCell *lc;
2946 9926 : ListCell *lc2 = list_head(setop_pathkeys);
2947 :
2948 39544 : foreach(lc, child_tlist)
2949 : {
2950 29618 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
2951 : EquivalenceMember *parent_em;
2952 : PathKey *pk;
2953 :
2954 29618 : if (tle->resjunk)
2955 0 : continue;
2956 :
2957 29618 : if (lc2 == NULL)
2958 0 : elog(ERROR, "too few pathkeys for set operation");
2959 :
2960 29618 : pk = lfirst_node(PathKey, lc2);
2961 29618 : 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 29618 : add_eq_member(pk->pk_eclass,
2970 : tle->expr,
2971 : child_rel->relids,
2972 : parent_em->em_jdomain,
2973 : parent_em,
2974 29618 : exprType((Node *) tle->expr));
2975 :
2976 29618 : 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 9926 : child_rel->eclass_indexes = bms_add_range(child_rel->eclass_indexes, 0,
2986 9926 : list_length(root->eq_classes) - 1);
2987 9926 : }
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 *
3014 526510 : generate_implied_equalities_for_column(PlannerInfo *root,
3015 : RelOptInfo *rel,
3016 : ec_matches_callback_type callback,
3017 : void *callback_arg,
3018 : Relids prohibited_rels)
3019 : {
3020 526510 : List *result = NIL;
3021 526510 : 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 526510 : if (is_child_rel)
3033 11126 : parent_relids = find_childrel_parents(root, rel);
3034 : else
3035 515384 : parent_relids = NULL; /* not used, but keep compiler quiet */
3036 :
3037 526510 : i = -1;
3038 1489062 : while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
3039 : {
3040 1051048 : 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 1051048 : if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
3052 598818 : 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 452230 : cur_em = NULL;
3065 1348188 : foreach(lc2, cur_ec->ec_members)
3066 : {
3067 984660 : cur_em = (EquivalenceMember *) lfirst(lc2);
3068 1437124 : if (bms_equal(cur_em->em_relids, rel->relids) &&
3069 452464 : callback(root, rel, cur_ec, cur_em, callback_arg))
3070 88702 : break;
3071 895958 : cur_em = NULL;
3072 : }
3073 :
3074 452230 : if (!cur_em)
3075 363528 : continue;
3076 :
3077 : /*
3078 : * Found our match. Scan the other EC members and attempt to generate
3079 : * joinclauses.
3080 : */
3081 291568 : foreach(lc2, cur_ec->ec_members)
3082 : {
3083 202866 : EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
3084 : Oid eq_op;
3085 : RestrictInfo *rinfo;
3086 :
3087 202866 : if (other_em->em_is_child)
3088 21056 : continue; /* ignore children here */
3089 :
3090 : /* Make sure it'll be a join to a different rel */
3091 277854 : if (other_em == cur_em ||
3092 96044 : bms_overlap(other_em->em_relids, rel->relids))
3093 85826 : continue;
3094 :
3095 : /* Forget it if caller doesn't want joins to this rel */
3096 95984 : if (bms_overlap(other_em->em_relids, prohibited_rels))
3097 138 : continue;
3098 :
3099 : /*
3100 : * Also, if this is a child rel, avoid generating a useless join
3101 : * to its parent rel(s).
3102 : */
3103 102248 : if (is_child_rel &&
3104 6402 : bms_overlap(parent_relids, other_em->em_relids))
3105 3020 : continue;
3106 :
3107 92826 : eq_op = select_equality_operator(cur_ec,
3108 : cur_em->em_datatype,
3109 : other_em->em_datatype);
3110 92826 : if (!OidIsValid(eq_op))
3111 0 : continue;
3112 :
3113 : /* set parent_ec to mark as redundant with other joinclauses */
3114 92826 : rinfo = create_join_clause(root, cur_ec, eq_op,
3115 : cur_em, other_em,
3116 : cur_ec);
3117 :
3118 92826 : 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 88702 : if (result)
3127 88496 : break;
3128 : }
3129 :
3130 526510 : 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
3146 153056 : have_relevant_eclass_joinclause(PlannerInfo *root,
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 153056 : matching_ecs = get_common_eclass_indexes(root, rel1->relids,
3163 : rel2->relids);
3164 :
3165 153056 : i = -1;
3166 153056 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
3167 : {
3168 128702 : 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 128702 : if (list_length(ec->ec_members) <= 1)
3183 0 : 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 128702 : return true;
3207 : }
3208 :
3209 24354 : 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
3222 180344 : has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
3223 : {
3224 : Bitmapset *matched_ecs;
3225 : int i;
3226 :
3227 : /* Examine only eclasses mentioning rel1 */
3228 180344 : matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
3229 :
3230 180344 : i = -1;
3231 636336 : while ((i = bms_next_member(matched_ecs, i)) >= 0)
3232 : {
3233 518998 : 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 518998 : if (list_length(ec->ec_members) <= 1)
3241 236288 : 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 282710 : if (!bms_is_subset(ec->ec_relids, rel1->relids))
3248 63006 : return true;
3249 : }
3250 :
3251 117338 : 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
3266 658762 : eclass_useful_for_merging(PlannerInfo *root,
3267 : EquivalenceClass *eclass,
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 658762 : if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
3280 64292 : 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 594470 : if (IS_OTHER_REL(rel))
3290 : {
3291 : Assert(!bms_is_empty(rel->top_parent_relids));
3292 10578 : relids = rel->top_parent_relids;
3293 : }
3294 : else
3295 583892 : relids = rel->relids;
3296 :
3297 : /* If rel already includes all members of eclass, no point in searching */
3298 594470 : if (bms_is_subset(eclass->ec_relids, relids))
3299 220242 : return false;
3300 :
3301 : /* To join, we need a member not in the given rel */
3302 579332 : foreach(lc, eclass->ec_members)
3303 : {
3304 578810 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
3305 :
3306 578810 : if (cur_em->em_is_child)
3307 0 : continue; /* ignore children here */
3308 :
3309 578810 : if (!bms_overlap(cur_em->em_relids, relids))
3310 373706 : return true;
3311 : }
3312 :
3313 522 : 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
3324 84 : is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
3325 : {
3326 84 : EquivalenceClass *parent_ec = rinfo->parent_ec;
3327 : ListCell *lc;
3328 :
3329 : /* Fail if it's not a potentially-redundant clause from some EC */
3330 84 : if (parent_ec == NULL)
3331 84 : return false;
3332 :
3333 0 : foreach(lc, clauselist)
3334 : {
3335 0 : RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
3336 :
3337 0 : if (otherrinfo->parent_ec == parent_ec)
3338 0 : return true;
3339 : }
3340 :
3341 0 : 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
3351 1240404 : is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
3352 : {
3353 1240404 : EquivalenceClass *parent_ec = rinfo->parent_ec;
3354 : ListCell *lc;
3355 :
3356 1739174 : foreach(lc, indexclauses)
3357 : {
3358 1303078 : IndexClause *iclause = lfirst_node(IndexClause, lc);
3359 1303078 : RestrictInfo *otherrinfo = iclause->rinfo;
3360 :
3361 : /* If indexclause is lossy, it won't enforce the condition exactly */
3362 1303078 : if (iclause->lossy)
3363 37266 : continue;
3364 :
3365 : /* Match if it's same clause (pointer equality should be enough) */
3366 1265812 : if (rinfo == otherrinfo)
3367 804308 : return true;
3368 : /* Match if derived from same EC */
3369 461798 : if (parent_ec && otherrinfo->parent_ec == parent_ec)
3370 294 : 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 436096 : 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 *
3387 877606 : get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
3388 : {
3389 877606 : Bitmapset *ec_indexes = NULL;
3390 877606 : int i = -1;
3391 :
3392 : /* Should be OK to rely on eclass_indexes */
3393 : Assert(root->ec_merging_done);
3394 :
3395 2784482 : while ((i = bms_next_member(relids, i)) > 0)
3396 : {
3397 1906876 : RelOptInfo *rel = root->simple_rel_array[i];
3398 :
3399 : /* ignore the RTE_GROUP RTE */
3400 1906876 : if (i == root->group_rtindex)
3401 0 : continue;
3402 :
3403 1906876 : if (rel == NULL) /* must be an outer join */
3404 : {
3405 : Assert(bms_is_member(i, root->outer_join_rels));
3406 274904 : continue;
3407 : }
3408 :
3409 1631972 : ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
3410 : }
3411 877606 : 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 *
3421 504764 : get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
3422 : {
3423 : Bitmapset *rel1ecs;
3424 : Bitmapset *rel2ecs;
3425 : int relid;
3426 :
3427 504764 : 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 504764 : if (bms_get_singleton_member(relids2, &relid))
3434 398352 : rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
3435 : else
3436 106412 : rel2ecs = get_eclass_indexes_for_relids(root, relids2);
3437 :
3438 : /* Calculate and return the common EC indexes, recycling the left input. */
3439 504764 : return bms_int_members(rel1ecs, rel2ecs);
3440 : }
|