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