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 : 246506 : process_equivalence(PlannerInfo *root,
181 : : RestrictInfo **p_restrictinfo,
182 : : JoinDomain *jdomain)
183 : : {
184 : 246506 : RestrictInfo *restrictinfo = *p_restrictinfo;
185 : 246506 : 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 [ + + + + ]: 246506 : if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
208 : 172 : return false;
209 : :
210 : : /* Extract info from given clause */
211 : : Assert(is_opclause(clause));
212 : 246334 : opno = ((OpExpr *) clause)->opno;
213 : 246334 : collation = ((OpExpr *) clause)->inputcollid;
214 : 246334 : item1 = (Expr *) get_leftop(clause);
215 : 246334 : item2 = (Expr *) get_rightop(clause);
216 : 246334 : item1_relids = restrictinfo->left_relids;
217 : 246334 : 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 : 246334 : item1 = canonicalize_ec_expression(item1,
224 : : exprType((Node *) item1),
225 : : collation);
226 : 246334 : 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 [ + + ]: 246334 : 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 : 246289 : op_input_types(opno, &item1_type, &item2_type);
282 : :
283 : 246289 : 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 : 246289 : ec1 = ec2 = NULL;
304 : 246289 : em1 = em2 = NULL;
305 : 246289 : ec2_idx = -1;
306 [ + + + + : 424470 : foreach(lc1, root->eq_classes)
+ + ]
307 : : {
308 : 178259 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
309 : : ListCell *lc2;
310 : :
311 : : /* Never match to a volatile EC */
312 [ - + ]: 178259 : 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 [ + + ]: 178259 : if (collation != cur_ec->ec_collation)
320 : 17949 : 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 [ + + ]: 160310 : if (!equal(opfamilies, cur_ec->ec_opfamilies))
328 : 43877 : continue;
329 : :
330 : : /* We don't expect any children yet */
331 : : Assert(cur_ec->ec_childmembers == NULL);
332 : :
333 [ + - + + : 346020 : foreach(lc2, cur_ec->ec_members)
+ + ]
334 : : {
335 : 229665 : 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 [ + + + + ]: 229665 : if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
345 : 3423 : continue;
346 : :
347 [ + + ]: 226242 : if (!ec1 &&
348 [ + + + + ]: 435332 : item1_type == cur_em->em_datatype &&
349 : 217497 : equal(item1, cur_em->em_expr))
350 : : {
351 : 13120 : ec1 = cur_ec;
352 : 13120 : em1 = cur_em;
353 [ + + ]: 13120 : if (ec2)
354 : 60 : break;
355 : : }
356 : :
357 [ + + ]: 226182 : if (!ec2 &&
358 [ + + + + ]: 447667 : item2_type == cur_em->em_datatype &&
359 : 223512 : equal(item2, cur_em->em_expr))
360 : : {
361 : 3052 : ec2 = cur_ec;
362 : 3052 : ec2_idx = foreach_current_index(lc1);
363 : 3052 : em2 = cur_em;
364 [ + + ]: 3052 : if (ec1)
365 : 18 : break;
366 : : }
367 : : }
368 : :
369 [ + + + + ]: 116433 : if (ec1 && ec2)
370 : 78 : break;
371 : : }
372 : :
373 : : /* Sweep finished, what did we find? */
374 : :
375 [ + + + + ]: 246289 : 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 [ + + ]: 246211 : else if (ec1)
445 : : {
446 : : /* Case 3: add item2 to ec1 */
447 : 13042 : em2 = add_eq_member(ec1, item2, item2_relids,
448 : : jdomain, item2_type);
449 : 13042 : ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
450 : 13042 : ec1->ec_min_security = Min(ec1->ec_min_security,
451 : : restrictinfo->security_level);
452 : 13042 : ec1->ec_max_security = Max(ec1->ec_max_security,
453 : : restrictinfo->security_level);
454 : : /* mark the RI as associated with this eclass */
455 : 13042 : restrictinfo->left_ec = ec1;
456 : 13042 : restrictinfo->right_ec = ec1;
457 : : /* mark the RI as usable with this pair of EMs */
458 : 13042 : restrictinfo->left_em = em1;
459 : 13042 : restrictinfo->right_em = em2;
460 : : }
461 [ + + ]: 233169 : else if (ec2)
462 : : {
463 : : /* Case 3: add item1 to ec2 */
464 : 2974 : em1 = add_eq_member(ec2, item1, item1_relids,
465 : : jdomain, item1_type);
466 : 2974 : ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
467 : 2974 : ec2->ec_min_security = Min(ec2->ec_min_security,
468 : : restrictinfo->security_level);
469 : 2974 : ec2->ec_max_security = Max(ec2->ec_max_security,
470 : : restrictinfo->security_level);
471 : : /* mark the RI as associated with this eclass */
472 : 2974 : restrictinfo->left_ec = ec2;
473 : 2974 : restrictinfo->right_ec = ec2;
474 : : /* mark the RI as usable with this pair of EMs */
475 : 2974 : restrictinfo->left_em = em1;
476 : 2974 : restrictinfo->right_em = em2;
477 : : }
478 : : else
479 : : {
480 : : /* Case 4: make a new, two-entry EC */
481 : 230195 : EquivalenceClass *ec = makeNode(EquivalenceClass);
482 : :
483 : 230195 : ec->ec_opfamilies = opfamilies;
484 : 230195 : ec->ec_collation = collation;
485 : 230195 : ec->ec_childmembers_size = 0;
486 : 230195 : ec->ec_members = NIL;
487 : 230195 : ec->ec_childmembers = NULL;
488 : 230195 : ec->ec_sources = list_make1(restrictinfo);
489 : 230195 : ec->ec_derives_list = NIL;
490 : 230195 : ec->ec_derives_hash = NULL;
491 : 230195 : ec->ec_relids = NULL;
492 : 230195 : ec->ec_has_const = false;
493 : 230195 : ec->ec_has_volatile = false;
494 : 230195 : ec->ec_broken = false;
495 : 230195 : ec->ec_sortref = 0;
496 : 230195 : ec->ec_min_security = restrictinfo->security_level;
497 : 230195 : ec->ec_max_security = restrictinfo->security_level;
498 : 230195 : ec->ec_merged = NULL;
499 : 230195 : em1 = add_eq_member(ec, item1, item1_relids,
500 : : jdomain, item1_type);
501 : 230195 : em2 = add_eq_member(ec, item2, item2_relids,
502 : : jdomain, item2_type);
503 : :
504 : 230195 : root->eq_classes = lappend(root->eq_classes, ec);
505 : :
506 : : /* mark the RI as associated with this eclass */
507 : 230195 : restrictinfo->left_ec = ec;
508 : 230195 : restrictinfo->right_ec = ec;
509 : : /* mark the RI as usable with this pair of EMs */
510 : 230195 : restrictinfo->left_em = em1;
511 : 230195 : restrictinfo->right_em = em2;
512 : : }
513 : :
514 : 246244 : 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 : 2767704 : canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
547 : : {
548 : 2767704 : 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 [ + - + + : 2767704 : if (IsPolymorphicType(req_type) || req_type == RECORDOID)
+ - + + +
+ + + + -
+ - + - +
- + - +
+ ]
555 : 9766 : req_type = expr_type;
556 : :
557 : : /*
558 : : * No work if the expression exposes the right type/collation already.
559 : : */
560 [ + + + + ]: 5454070 : if (expr_type != req_type ||
561 : 2686366 : 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 [ + + ]: 83622 : if (expr_type != req_type)
571 : 81338 : req_typmod = -1;
572 : : else
573 : 2284 : 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 : 83622 : expr = (Expr *) applyRelabelType((Node *) expr,
580 : : req_type, req_typmod, req_collation,
581 : : COERCE_IMPLICIT_CAST, -1, false);
582 : : }
583 : :
584 : 2767704 : 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 : 789628 : make_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
594 : : JoinDomain *jdomain, EquivalenceMember *parent, Oid datatype)
595 : : {
596 : 789628 : EquivalenceMember *em = makeNode(EquivalenceMember);
597 : :
598 : 789628 : em->em_expr = expr;
599 : 789628 : em->em_relids = relids;
600 : 789628 : em->em_is_const = false;
601 : 789628 : em->em_is_child = (parent != NULL);
602 : 789628 : em->em_datatype = datatype;
603 : 789628 : em->em_jdomain = jdomain;
604 : 789628 : em->em_parent = parent;
605 : :
606 [ + + ]: 789628 : 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 : 175589 : em->em_is_const = true;
618 : 175589 : ec->ec_has_const = true;
619 : : /* it can't affect ec_relids */
620 : : }
621 : :
622 : 789628 : 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 : 700907 : add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
630 : : JoinDomain *jdomain, Oid datatype)
631 : : {
632 : 700907 : EquivalenceMember *em = make_eq_member(ec, expr, relids, jdomain,
633 : : NULL, datatype);
634 : :
635 : : /* add to the members list */
636 : 700907 : ec->ec_members = lappend(ec->ec_members, em);
637 : :
638 : : /* record the relids for parent members */
639 : 700907 : ec->ec_relids = bms_add_members(ec->ec_relids, relids);
640 : :
641 : 700907 : 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 : 88721 : 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 [ + + ]: 88721 : if (unlikely(ec->ec_childmembers_size < root->simple_rel_array_size))
676 : : {
677 [ + - ]: 24073 : if (ec->ec_childmembers == NULL)
678 : 24073 : 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 : 24073 : ec->ec_childmembers_size = root->simple_rel_array_size;
685 : : }
686 : :
687 : 88721 : 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 : 88721 : ec->ec_childmembers[child_relid] = lappend(ec->ec_childmembers[child_relid], em);
691 : :
692 : : /* Record this EC index for the child rel */
693 [ + + ]: 88721 : if (ec_index >= 0)
694 : : {
695 : 51082 : RelOptInfo *child_rel = root->simple_rel_array[child_relid];
696 : :
697 : 51082 : child_rel->eclass_indexes =
698 : 51082 : bms_add_member(child_rel->eclass_indexes, ec_index);
699 : : }
700 : :
701 : 88721 : 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 : 1802228 : 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 : 1802228 : 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 : 1802228 : jdomain = linitial_node(JoinDomain, root->join_domains);
763 : :
764 : : /*
765 : : * Scan through the existing EquivalenceClasses for a match
766 : : */
767 [ + + + + : 6014262 : foreach(lc1, root->eq_classes)
+ + ]
768 : : {
769 : 5254586 : 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 [ + + + + ]: 5254586 : if (cur_ec->ec_has_volatile &&
778 [ + + ]: 28 : (sortref == 0 || sortref != cur_ec->ec_sortref))
779 : 2264033 : continue;
780 : :
781 [ + + ]: 5254076 : if (collation != cur_ec->ec_collation)
782 : 1451793 : continue;
783 [ + + ]: 3802283 : if (!equal(opfamilies, cur_ec->ec_opfamilies))
784 : 811730 : continue;
785 : :
786 : 2990553 : setup_eclass_member_iterator(&it, cur_ec, relids);
787 [ + + ]: 6655537 : while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
788 : : {
789 : : /*
790 : : * Ignore child members unless they match the request.
791 : : */
792 [ + + ]: 4707536 : if (cur_em->em_is_child &&
793 [ - + ]: 91241 : !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 [ + + + + ]: 4707536 : if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
801 : 61556 : continue;
802 : :
803 [ + + + + ]: 9255868 : if (opcintype == cur_em->em_datatype &&
804 : 4609888 : equal(expr, cur_em->em_expr))
805 : 1042552 : return cur_ec; /* Match! */
806 : : }
807 : : }
808 : :
809 : : /* No match; does caller want a NULL result? */
810 [ + + ]: 759676 : if (!create_it)
811 : 535175 : 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 : 224501 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
819 : :
820 : 224501 : newec = makeNode(EquivalenceClass);
821 : 224501 : newec->ec_opfamilies = list_copy(opfamilies);
822 : 224501 : newec->ec_collation = collation;
823 : 224501 : newec->ec_childmembers_size = 0;
824 : 224501 : newec->ec_members = NIL;
825 : 224501 : newec->ec_childmembers = NULL;
826 : 224501 : newec->ec_sources = NIL;
827 : 224501 : newec->ec_derives_list = NIL;
828 : 224501 : newec->ec_derives_hash = NULL;
829 : 224501 : newec->ec_relids = NULL;
830 : 224501 : newec->ec_has_const = false;
831 : 224501 : newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
832 : 224501 : newec->ec_broken = false;
833 : 224501 : newec->ec_sortref = sortref;
834 : 224501 : newec->ec_min_security = UINT_MAX;
835 : 224501 : newec->ec_max_security = 0;
836 : 224501 : newec->ec_merged = NULL;
837 : :
838 [ + + - + ]: 224501 : 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 : 224501 : expr_relids = pull_varnos(root, (Node *) expr);
845 : :
846 : 224501 : 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 [ + + ]: 224501 : if (newec->ec_has_const)
856 : : {
857 [ + + + + ]: 15502 : if (newec->ec_has_volatile ||
858 [ + + ]: 15278 : expression_returns_set((Node *) expr) ||
859 [ + + ]: 15007 : contain_agg_clause((Node *) expr) ||
860 : 7428 : contain_window_function((Node *) expr))
861 : : {
862 : 380 : newec->ec_has_const = false;
863 : 380 : newem->em_is_const = false;
864 : : }
865 : : }
866 : :
867 : 224501 : 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 [ + + ]: 224501 : if (root->ec_merging_done)
874 : : {
875 : 128902 : int ec_index = list_length(root->eq_classes) - 1;
876 : 128902 : int i = -1;
877 : :
878 [ + + ]: 248001 : while ((i = bms_next_member(newec->ec_relids, i)) > 0)
879 : : {
880 : 119099 : RelOptInfo *rel = root->simple_rel_array[i];
881 : :
882 : : /* ignore the RTE_GROUP RTE */
883 [ + + ]: 119099 : if (i == root->group_rtindex)
884 : 584 : continue;
885 : :
886 [ + + ]: 118515 : if (rel == NULL) /* must be an outer join */
887 : : {
888 : : Assert(bms_is_member(i, root->outer_join_rels));
889 : 5411 : continue;
890 : : }
891 : :
892 : : Assert(rel->reloptkind == RELOPT_BASEREL);
893 : :
894 : 113104 : rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
895 : : ec_index);
896 : : }
897 : : }
898 : :
899 : 224501 : MemoryContextSwitchTo(oldcontext);
900 : :
901 : 224501 : 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 : 269404 : 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 [ + - + + ]: 290500 : while (expr && IsA(expr, RelabelType))
926 : 21096 : expr = ((RelabelType *) expr)->arg;
927 : :
928 : 269404 : setup_eclass_member_iterator(&it, ec, relids);
929 [ + + ]: 452534 : 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 [ - + ]: 301933 : if (em->em_is_const)
938 : 0 : continue;
939 : :
940 : : /*
941 : : * Ignore child members unless they belong to the requested rel.
942 : : */
943 [ + + ]: 301933 : if (em->em_is_child &&
944 [ + + ]: 9841 : !bms_is_subset(em->em_relids, relids))
945 : 2866 : continue;
946 : :
947 : : /*
948 : : * Match if same expression (after stripping relabel).
949 : : */
950 : 299067 : emexpr = em->em_expr;
951 [ + - + + ]: 309654 : while (emexpr && IsA(emexpr, RelabelType))
952 : 10587 : emexpr = ((RelabelType *) emexpr)->arg;
953 : :
954 [ + + ]: 299067 : if (equal(emexpr, expr))
955 : 118803 : return em;
956 : : }
957 : :
958 : 150601 : 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 : 5854 : 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 : 5854 : exprvars = pull_var_clause((Node *) exprs,
1010 : : PVC_INCLUDE_AGGREGATES |
1011 : : PVC_INCLUDE_WINDOWFUNCS |
1012 : : PVC_INCLUDE_PLACEHOLDERS);
1013 : :
1014 : 5854 : setup_eclass_member_iterator(&it, ec, relids);
1015 [ + + ]: 11804 : 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 [ - + ]: 6399 : 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 [ + + + + ]: 6399 : if ((em->em_is_child || relids != NULL) &&
1035 [ + + ]: 6345 : !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 : 625 : emvars = pull_var_clause((Node *) em->em_expr,
1042 : : PVC_INCLUDE_AGGREGATES |
1043 : : PVC_INCLUDE_WINDOWFUNCS |
1044 : : PVC_INCLUDE_PLACEHOLDERS);
1045 [ + + + + : 1344 : foreach(lc2, emvars)
+ + ]
1046 : : {
1047 [ + + ]: 859 : if (!list_member(exprvars, lfirst(lc2)))
1048 : 140 : break;
1049 : : }
1050 : 625 : list_free(emvars);
1051 [ + + ]: 625 : 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 [ + + ]: 485 : if (require_parallel_safe &&
1059 [ + + ]: 115 : !is_parallel_safe(root, (Node *) em->em_expr))
1060 : 36 : continue;
1061 : :
1062 : 449 : 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 : 16330 : relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel,
1083 : : EquivalenceClass *ec, bool require_parallel_safe)
1084 : : {
1085 : 16330 : 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 [ + + ]: 16330 : if (ec->ec_has_volatile)
1093 : 60 : return false;
1094 : :
1095 : : /*
1096 : : * Try to find an EM directly matching some reltarget member.
1097 : : */
1098 [ + + + + : 35555 : foreach(lc, target->exprs)
+ + ]
1099 : : {
1100 : 30071 : Expr *targetexpr = (Expr *) lfirst(lc);
1101 : :
1102 : 30071 : em = find_ec_member_matching_expr(ec, targetexpr, rel->relids);
1103 [ + + ]: 30071 : if (!em)
1104 : 19285 : 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 [ - + ]: 10786 : 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 [ + - ]: 10786 : if (require_parallel_safe &&
1120 [ - + ]: 10786 : !is_parallel_safe(root, (Node *) em->em_expr))
1121 : 0 : continue;
1122 : :
1123 : 10786 : 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 : 260794 : 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 : 260794 : root->ec_merging_done = true;
1206 : :
1207 : 260794 : ec_index = 0;
1208 [ + + + + : 586555 : foreach(lc, root->eq_classes)
+ + ]
1209 : : {
1210 : 325761 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
1211 : 325761 : 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 [ + + ]: 325761 : if (list_length(ec->ec_members) > 1)
1223 : : {
1224 [ + + ]: 231974 : if (ec->ec_has_const)
1225 : 167586 : generate_base_implied_equalities_const(root, ec);
1226 : : else
1227 : 64388 : generate_base_implied_equalities_no_const(root, ec);
1228 : :
1229 : : /* Recover if we failed to generate required derived clauses */
1230 [ + + ]: 231974 : if (ec->ec_broken)
1231 : 25 : generate_base_implied_equalities_broken(root, ec);
1232 : :
1233 : : /* Detect whether this EC might generate join clauses */
1234 : 231974 : can_generate_joinclause =
1235 : 231974 : (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 : 325761 : i = -1;
1246 [ + + ]: 731687 : while ((i = bms_next_member(ec->ec_relids, i)) > 0)
1247 : : {
1248 : 405926 : RelOptInfo *rel = root->simple_rel_array[i];
1249 : :
1250 : : /* ignore the RTE_GROUP RTE */
1251 [ - + ]: 405926 : if (i == root->group_rtindex)
1252 : 0 : continue;
1253 : :
1254 [ + + ]: 405926 : if (rel == NULL) /* must be an outer join */
1255 : : {
1256 : : Assert(bms_is_member(i, root->outer_join_rels));
1257 : 3740 : continue;
1258 : : }
1259 : :
1260 : : Assert(rel->reloptkind == RELOPT_BASEREL);
1261 : :
1262 : 402186 : rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
1263 : : ec_index);
1264 : :
1265 [ + + ]: 402186 : if (can_generate_joinclause)
1266 : 152052 : rel->has_eclass_joins = true;
1267 : : }
1268 : :
1269 : 325761 : ec_index++;
1270 : : }
1271 : 260794 : }
1272 : :
1273 : : /*
1274 : : * generate_base_implied_equalities when EC contains pseudoconstant(s)
1275 : : */
1276 : : static void
1277 : 167586 : generate_base_implied_equalities_const(PlannerInfo *root,
1278 : : EquivalenceClass *ec)
1279 : : {
1280 : 167586 : 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 [ + + + + ]: 323071 : if (list_length(ec->ec_members) == 2 &&
1291 : 155485 : list_length(ec->ec_sources) == 1)
1292 : : {
1293 : 155450 : RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
1294 : :
1295 : 155450 : distribute_restrictinfo_to_rels(root, restrictinfo);
1296 : 155450 : 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 [ + - + + : 29320 : foreach(lc, ec->ec_members)
+ + ]
1309 : : {
1310 : 29226 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1311 : :
1312 [ + + ]: 29226 : if (cur_em->em_is_const)
1313 : : {
1314 : 12151 : const_em = cur_em;
1315 [ + + ]: 12151 : if (IsA(cur_em->em_expr, Const))
1316 : 12042 : break;
1317 : : }
1318 : : }
1319 : : Assert(const_em != NULL);
1320 : :
1321 : : /* Generate a derived equality against each other member */
1322 [ + - + + : 48635 : foreach(lc, ec->ec_members)
+ + ]
1323 : : {
1324 : 36524 : 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 [ + + ]: 36524 : if (cur_em == const_em)
1331 : 12116 : continue;
1332 : 24408 : eq_op = select_equality_operator(ec,
1333 : : cur_em->em_datatype,
1334 : : const_em->em_datatype);
1335 [ + + ]: 24408 : 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 : 24383 : rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
1348 : : cur_em->em_expr, const_em->em_expr,
1349 : 24383 : const_em->em_jdomain->jd_relids,
1350 : : ec->ec_min_security,
1351 : 24383 : 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 [ + - + + ]: 24383 : if (rinfo && rinfo->mergeopfamilies)
1362 : : {
1363 : : /* it's not redundant, so don't set parent_ec */
1364 : 24238 : rinfo->left_ec = rinfo->right_ec = ec;
1365 : 24238 : rinfo->left_em = cur_em;
1366 : 24238 : rinfo->right_em = const_em;
1367 : 24238 : 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 : 64388 : 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 : 64388 : 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 [ + - + + : 195097 : foreach(lc, ec->ec_members)
+ + ]
1396 : : {
1397 : 130709 : 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 [ + + ]: 130709 : if (!bms_get_singleton_member(cur_em->em_relids, &relid))
1404 : 280 : continue;
1405 : : Assert(relid < root->simple_rel_array_size);
1406 : :
1407 [ + + ]: 130429 : 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 : 130429 : prev_ems[relid] = cur_em;
1450 : : }
1451 : :
1452 : 64388 : 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 [ + - + + : 195097 : foreach(lc, ec->ec_members)
+ + ]
1463 : : {
1464 : 130709 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1465 : 130709 : List *vars = pull_var_clause((Node *) cur_em->em_expr,
1466 : : PVC_RECURSE_AGGREGATES |
1467 : : PVC_RECURSE_WINDOWFUNCS |
1468 : : PVC_INCLUDE_PLACEHOLDERS);
1469 : :
1470 : 130709 : add_vars_to_targetlist(root, vars, ec->ec_relids);
1471 : 130709 : list_free(vars);
1472 : : }
1473 : 64388 : }
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 : 455761 : generate_join_implied_equalities(PlannerInfo *root,
1554 : : Relids join_relids,
1555 : : Relids outer_relids,
1556 : : RelOptInfo *inner_rel,
1557 : : SpecialJoinInfo *sjinfo)
1558 : : {
1559 : 455761 : List *result = NIL;
1560 : 455761 : 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 [ + + + + : 455761 : 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 : 9723 : nominal_inner_relids = inner_rel->top_parent_relids;
1573 : : /* ECs will be marked with the parent's relid, not the child's */
1574 : 9723 : nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1575 : 9723 : nominal_join_relids = add_outer_joins_to_relids(root,
1576 : : nominal_join_relids,
1577 : : sjinfo,
1578 : : NULL);
1579 : : }
1580 : : else
1581 : : {
1582 : 446038 : nominal_inner_relids = inner_relids;
1583 : 446038 : 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 [ + + + + ]: 455761 : if (sjinfo && sjinfo->ojrelid != 0)
1600 : 77043 : matching_ecs = get_eclass_indexes_for_relids(root, nominal_join_relids);
1601 : : else
1602 : 378718 : matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
1603 : : outer_relids);
1604 : :
1605 : 455761 : i = -1;
1606 [ + + ]: 1277461 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
1607 : : {
1608 : 821700 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
1609 : 821700 : List *sublist = NIL;
1610 : :
1611 : : /* ECs containing consts do not need any further enforcement */
1612 [ + + ]: 821700 : if (ec->ec_has_const)
1613 : 100985 : continue;
1614 : :
1615 : : /* Single-member ECs won't generate any deductions */
1616 [ + + ]: 720715 : if (list_length(ec->ec_members) <= 1)
1617 : 359457 : continue;
1618 : :
1619 : : /* Sanity check that this eclass overlaps the join */
1620 : : Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
1621 : :
1622 [ + + ]: 361258 : if (!ec->ec_broken)
1623 : 360988 : 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 [ + + ]: 361258 : 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 : 361258 : result = list_concat(result, sublist);
1639 : : }
1640 : :
1641 : 455761 : 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 : 7751 : 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 : 7751 : List *result = NIL;
1660 : 7751 : 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 [ + + + - : 7751 : 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 : 5361 : nominal_inner_relids = inner_relids;
1678 : 5361 : nominal_join_relids = join_relids;
1679 : : }
1680 : :
1681 [ + - + + : 15941 : foreach(lc, eclasses)
+ + ]
1682 : : {
1683 : 8190 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
1684 : 8190 : List *sublist = NIL;
1685 : :
1686 : : /* ECs containing consts do not need any further enforcement */
1687 [ - + ]: 8190 : if (ec->ec_has_const)
1688 : 0 : continue;
1689 : :
1690 : : /* Single-member ECs won't generate any deductions */
1691 [ - + ]: 8190 : 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 [ - + ]: 8190 : if (!bms_overlap(ec->ec_relids, nominal_join_relids))
1696 : 0 : continue;
1697 : :
1698 [ + - ]: 8190 : if (!ec->ec_broken)
1699 : 8190 : 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 [ - + ]: 8190 : 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 : 8190 : result = list_concat(result, sublist);
1715 : : }
1716 : :
1717 : 7751 : return result;
1718 : : }
1719 : :
1720 : : /*
1721 : : * generate_join_implied_equalities for a still-valid EC
1722 : : */
1723 : : static List *
1724 : 369178 : generate_join_implied_equalities_normal(PlannerInfo *root,
1725 : : EquivalenceClass *ec,
1726 : : Relids join_relids,
1727 : : Relids outer_relids,
1728 : : Relids inner_relids)
1729 : : {
1730 : 369178 : List *result = NIL;
1731 : 369178 : List *new_members = NIL;
1732 : 369178 : List *outer_members = NIL;
1733 : 369178 : 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 : 369178 : setup_eclass_member_iterator(&it, ec, join_relids);
1747 [ + + ]: 1311360 : 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 [ + + ]: 942182 : if (!bms_is_subset(cur_em->em_relids, join_relids))
1755 : 208108 : continue; /* not computable yet, or wrong child */
1756 : :
1757 [ + + ]: 734074 : if (bms_is_subset(cur_em->em_relids, outer_relids))
1758 : 410503 : outer_members = lappend(outer_members, cur_em);
1759 [ + + ]: 323571 : else if (bms_is_subset(cur_em->em_relids, inner_relids))
1760 : 318370 : inner_members = lappend(inner_members, cur_em);
1761 : : else
1762 : 5201 : 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 [ + + + + ]: 369178 : if (outer_members && inner_members)
1775 : : {
1776 : 300019 : EquivalenceMember *best_outer_em = NULL;
1777 : 300019 : EquivalenceMember *best_inner_em = NULL;
1778 : 300019 : Oid best_eq_op = InvalidOid;
1779 : 300019 : int best_score = -1;
1780 : : RestrictInfo *rinfo;
1781 : : ListCell *lc1;
1782 : :
1783 [ + - + + : 313407 : foreach(lc1, outer_members)
+ + ]
1784 : : {
1785 : 300084 : EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
1786 : : ListCell *lc2;
1787 : :
1788 [ + - + + : 313492 : foreach(lc2, inner_members)
+ + ]
1789 : : {
1790 : 300104 : EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
1791 : : Oid eq_op;
1792 : : int score;
1793 : :
1794 : 300104 : eq_op = select_equality_operator(ec,
1795 : : outer_em->em_datatype,
1796 : : inner_em->em_datatype);
1797 [ + + ]: 300104 : if (!OidIsValid(eq_op))
1798 : 30 : continue;
1799 : 300074 : score = 0;
1800 [ + + ]: 300074 : if (IsA(outer_em->em_expr, Var) ||
1801 [ + + ]: 17357 : (IsA(outer_em->em_expr, RelabelType) &&
1802 [ + + ]: 6589 : IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1803 : 288755 : score++;
1804 [ + + ]: 300074 : if (IsA(inner_em->em_expr, Var) ||
1805 [ + + ]: 10204 : (IsA(inner_em->em_expr, RelabelType) &&
1806 [ + + ]: 7938 : IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
1807 : 297672 : score++;
1808 [ + + ]: 300074 : if (op_hashjoinable(eq_op,
1809 : 300074 : exprType((Node *) outer_em->em_expr)))
1810 : 300015 : score++;
1811 [ + + ]: 300074 : if (score > best_score)
1812 : : {
1813 : 299989 : best_outer_em = outer_em;
1814 : 299989 : best_inner_em = inner_em;
1815 : 299989 : best_eq_op = eq_op;
1816 : 299989 : best_score = score;
1817 [ + + ]: 299989 : if (best_score == 3)
1818 : 286696 : break; /* no need to look further */
1819 : : }
1820 : : }
1821 [ + + ]: 300084 : if (best_score == 3)
1822 : 286696 : break; /* no need to look further */
1823 : : }
1824 [ + + ]: 300019 : 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 : 299989 : rinfo = create_join_clause(root, ec, best_eq_op,
1836 : : best_outer_em, best_inner_em,
1837 : : ec);
1838 : :
1839 : 299989 : 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 [ + + ]: 369148 : if (new_members)
1852 : : {
1853 : 5171 : List *old_members = list_concat(outer_members, inner_members);
1854 : 5171 : 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 [ + + ]: 5171 : if (old_members)
1860 : 3578 : new_members = lappend(new_members, linitial(old_members));
1861 : :
1862 [ + - + + : 13950 : foreach(lc1, new_members)
+ + ]
1863 : : {
1864 : 8779 : cur_em = (EquivalenceMember *) lfirst(lc1);
1865 : :
1866 [ + + ]: 8779 : if (prev_em != NULL)
1867 : : {
1868 : : Oid eq_op;
1869 : :
1870 : 3608 : eq_op = select_equality_operator(ec,
1871 : : prev_em->em_datatype,
1872 : : cur_em->em_datatype);
1873 [ - + ]: 3608 : 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 : 3608 : rinfo = create_join_clause(root, ec, eq_op,
1881 : : prev_em, cur_em,
1882 : : NULL);
1883 : :
1884 : 3608 : result = lappend(result, rinfo);
1885 : : }
1886 : 8779 : prev_em = cur_em;
1887 : : }
1888 : : }
1889 : :
1890 : 369148 : 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 : 437045 : select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
1952 : : {
1953 : : ListCell *lc;
1954 : :
1955 [ + - + + : 437100 : foreach(lc, ec->ec_opfamilies)
+ + ]
1956 : : {
1957 : 437045 : Oid opfamily = lfirst_oid(lc);
1958 : : Oid opno;
1959 : :
1960 : 437045 : opno = get_opfamily_member_for_cmptype(opfamily, lefttype, righttype, COMPARE_EQ);
1961 [ + + ]: 437045 : if (!OidIsValid(opno))
1962 : 55 : continue;
1963 : : /* If no barrier quals in query, don't worry about leaky operators */
1964 [ + + ]: 436990 : if (ec->ec_max_security == 0)
1965 : 436990 : 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 : 414749 : 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 : 414749 : RestrictInfo *parent_rinfo = NULL;
1994 : : MemoryContext oldcontext;
1995 : :
1996 : 414749 : rinfo = ec_search_clause_for_ems(root, ec, leftem, rightem, parent_ec);
1997 [ + + ]: 414749 : if (rinfo)
1998 : 345940 : 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 : 68809 : 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 [ + + + + ]: 68809 : if (leftem->em_is_child || rightem->em_is_child)
2011 : : {
2012 [ + + ]: 4514 : EquivalenceMember *leftp = leftem->em_parent ? leftem->em_parent : leftem;
2013 [ + + ]: 4514 : EquivalenceMember *rightp = rightem->em_parent ? rightem->em_parent : rightem;
2014 : :
2015 : 4514 : parent_rinfo = create_join_clause(root, ec, opno,
2016 : : leftp, rightp,
2017 : : parent_ec);
2018 : : }
2019 : :
2020 : 68809 : rinfo = build_implied_join_equality(root,
2021 : : opno,
2022 : : ec->ec_collation,
2023 : : leftem->em_expr,
2024 : : rightem->em_expr,
2025 : 68809 : bms_union(leftem->em_relids,
2026 : 68809 : 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 [ + + + + ]: 68809 : if (leftem->em_is_child || rightem->em_is_child)
2039 : : {
2040 : : Relids baserels;
2041 : :
2042 : 9028 : rinfo->clause_relids = bms_union(leftem->em_relids,
2043 : 4514 : rightem->em_relids);
2044 : :
2045 : : /* keep num_base_rels in sync, as in make_restrictinfo() */
2046 : 4514 : baserels = bms_difference(rinfo->clause_relids,
2047 : 4514 : root->outer_join_rels);
2048 : 4514 : rinfo->num_base_rels = bms_num_members(baserels);
2049 : 4514 : bms_free(baserels);
2050 : : }
2051 : :
2052 : : /* If it's a child clause, copy the parent's rinfo_serial */
2053 [ + + ]: 68809 : if (parent_rinfo)
2054 : 4514 : 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 [ + + ]: 64295 : counterpart = ec_search_clause_for_ems(root, ec, leftem, rightem,
2066 : : parent_ec ? NULL : ec);
2067 [ + + ]: 64295 : if (counterpart)
2068 : 62424 : rinfo->rinfo_serial = counterpart->rinfo_serial;
2069 : : }
2070 : :
2071 : : /* Mark the clause as redundant, or not */
2072 : 68809 : 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 : 68809 : rinfo->left_ec = ec;
2079 : 68809 : rinfo->right_ec = ec;
2080 : :
2081 : : /* Mark it as usable with these EMs */
2082 : 68809 : rinfo->left_em = leftem;
2083 : 68809 : rinfo->right_em = rightem;
2084 : : /* and save it for possible re-use */
2085 : 68809 : ec_add_derived_clause(ec, rinfo);
2086 : :
2087 : 68809 : MemoryContextSwitchTo(oldcontext);
2088 : :
2089 : 68809 : 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 : : * However, we can't do that for a clone clause, since it may be applied
2161 : : * above a commuted outer join that has already null-extended OUTERVAR but
2162 : : * whose relid has not yet been added to the joinrel. The original strict
2163 : : * clause is needed there to reject the null-extended rows, so we throw
2164 : : * back a clone as-is, marked redundant for selectivity estimation.
2165 : : */
2166 : : void
2167 : 260794 : reconsider_outer_join_clauses(PlannerInfo *root)
2168 : : {
2169 : : bool found;
2170 : : ListCell *cell;
2171 : :
2172 : : /* Outer loop repeats until we find no more deductions */
2173 : : do
2174 : : {
2175 : 262566 : found = false;
2176 : :
2177 : : /* Process the LEFT JOIN clauses */
2178 [ + + + + : 285997 : foreach(cell, root->left_join_clauses)
+ + ]
2179 : : {
2180 : 23431 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2181 : :
2182 [ + + ]: 23431 : if (reconsider_outer_join_clause(root, ojcinfo, true))
2183 : : {
2184 : 600 : RestrictInfo *rinfo = ojcinfo->rinfo;
2185 : :
2186 : 600 : found = true;
2187 : : /* remove it from the list */
2188 : 600 : root->left_join_clauses =
2189 : 600 : foreach_delete_current(root->left_join_clauses, cell);
2190 : : /* throw back a clone as-is (see notes above) */
2191 [ + + - + ]: 600 : if (rinfo->has_clone || rinfo->is_clone)
2192 : : {
2193 : : /* but the thrown-back clause has no extra selectivity */
2194 : 60 : rinfo->norm_selec = 2.0;
2195 : 60 : rinfo->outer_selec = 1.0;
2196 : 60 : distribute_restrictinfo_to_rels(root, rinfo);
2197 : 60 : continue;
2198 : : }
2199 : : /* throw back a dummy replacement clause (see notes above) */
2200 : 540 : rinfo = make_restrictinfo(root,
2201 : 540 : (Expr *) makeBoolConst(true, false),
2202 : 540 : rinfo->is_pushed_down,
2203 : 540 : rinfo->has_clone,
2204 : 540 : rinfo->is_clone,
2205 : : false, /* pseudoconstant */
2206 : : 0, /* security_level */
2207 : : rinfo->required_relids,
2208 : : rinfo->incompatible_relids,
2209 : : rinfo->outer_relids);
2210 : 540 : distribute_restrictinfo_to_rels(root, rinfo);
2211 : : }
2212 : : }
2213 : :
2214 : : /* Process the RIGHT JOIN clauses */
2215 [ + + + + : 291984 : foreach(cell, root->right_join_clauses)
+ + ]
2216 : : {
2217 : 29418 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2218 : :
2219 [ + + ]: 29418 : if (reconsider_outer_join_clause(root, ojcinfo, false))
2220 : : {
2221 : 1147 : RestrictInfo *rinfo = ojcinfo->rinfo;
2222 : :
2223 : 1147 : found = true;
2224 : : /* remove it from the list */
2225 : 1147 : root->right_join_clauses =
2226 : 1147 : foreach_delete_current(root->right_join_clauses, cell);
2227 : : /* throw back a clone as-is (see notes above) */
2228 [ + - - + ]: 1147 : if (rinfo->has_clone || rinfo->is_clone)
2229 : : {
2230 : : /* but the thrown-back clause has no extra selectivity */
2231 : 0 : rinfo->norm_selec = 2.0;
2232 : 0 : rinfo->outer_selec = 1.0;
2233 : 0 : distribute_restrictinfo_to_rels(root, rinfo);
2234 : 0 : continue;
2235 : : }
2236 : : /* throw back a dummy replacement clause (see notes above) */
2237 : 1147 : rinfo = make_restrictinfo(root,
2238 : 1147 : (Expr *) makeBoolConst(true, false),
2239 : 1147 : rinfo->is_pushed_down,
2240 : 1147 : rinfo->has_clone,
2241 : 1147 : rinfo->is_clone,
2242 : : false, /* pseudoconstant */
2243 : : 0, /* security_level */
2244 : : rinfo->required_relids,
2245 : : rinfo->incompatible_relids,
2246 : : rinfo->outer_relids);
2247 : 1147 : distribute_restrictinfo_to_rels(root, rinfo);
2248 : : }
2249 : : }
2250 : :
2251 : : /* Process the FULL JOIN clauses */
2252 [ + + + + : 263754 : foreach(cell, root->full_join_clauses)
+ + ]
2253 : : {
2254 : 1188 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2255 : :
2256 [ + + ]: 1188 : if (reconsider_full_join_clause(root, ojcinfo))
2257 : : {
2258 : 55 : RestrictInfo *rinfo = ojcinfo->rinfo;
2259 : :
2260 : 55 : found = true;
2261 : : /* remove it from the list */
2262 : 55 : root->full_join_clauses =
2263 : 55 : foreach_delete_current(root->full_join_clauses, cell);
2264 : : /* throw back a dummy replacement clause (see notes above) */
2265 : 55 : rinfo = make_restrictinfo(root,
2266 : 55 : (Expr *) makeBoolConst(true, false),
2267 : 55 : rinfo->is_pushed_down,
2268 : 55 : rinfo->has_clone,
2269 : 55 : rinfo->is_clone,
2270 : : false, /* pseudoconstant */
2271 : : 0, /* security_level */
2272 : : rinfo->required_relids,
2273 : : rinfo->incompatible_relids,
2274 : : rinfo->outer_relids);
2275 : 55 : distribute_restrictinfo_to_rels(root, rinfo);
2276 : : }
2277 : : }
2278 [ + + ]: 262566 : } while (found);
2279 : :
2280 : : /* Now, any remaining clauses have to be thrown back */
2281 [ + + + + : 283195 : foreach(cell, root->left_join_clauses)
+ + ]
2282 : : {
2283 : 22401 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2284 : :
2285 : 22401 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2286 : : }
2287 [ + + + + : 287867 : foreach(cell, root->right_join_clauses)
+ + ]
2288 : : {
2289 : 27073 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2290 : :
2291 : 27073 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2292 : : }
2293 [ + + + + : 261927 : foreach(cell, root->full_join_clauses)
+ + ]
2294 : : {
2295 : 1133 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2296 : :
2297 : 1133 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2298 : : }
2299 : 260794 : }
2300 : :
2301 : : /*
2302 : : * reconsider_outer_join_clauses for a single LEFT/RIGHT JOIN clause
2303 : : *
2304 : : * Returns true if we were able to propagate a constant through the clause.
2305 : : */
2306 : : static bool
2307 : 52849 : reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
2308 : : bool outer_on_left)
2309 : : {
2310 : 52849 : RestrictInfo *rinfo = ojcinfo->rinfo;
2311 : 52849 : SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
2312 : : Expr *outervar,
2313 : : *innervar;
2314 : : Oid opno,
2315 : : collation,
2316 : : left_type,
2317 : : right_type,
2318 : : inner_datatype;
2319 : : Relids inner_relids;
2320 : : ListCell *lc1;
2321 : :
2322 : : Assert(is_opclause(rinfo->clause));
2323 : 52849 : opno = ((OpExpr *) rinfo->clause)->opno;
2324 : 52849 : collation = ((OpExpr *) rinfo->clause)->inputcollid;
2325 : :
2326 : : /* Extract needed info from the clause */
2327 : 52849 : op_input_types(opno, &left_type, &right_type);
2328 [ + + ]: 52849 : if (outer_on_left)
2329 : : {
2330 : 23431 : outervar = (Expr *) get_leftop(rinfo->clause);
2331 : 23431 : innervar = (Expr *) get_rightop(rinfo->clause);
2332 : 23431 : inner_datatype = right_type;
2333 : 23431 : inner_relids = rinfo->right_relids;
2334 : : }
2335 : : else
2336 : : {
2337 : 29418 : outervar = (Expr *) get_rightop(rinfo->clause);
2338 : 29418 : innervar = (Expr *) get_leftop(rinfo->clause);
2339 : 29418 : inner_datatype = left_type;
2340 : 29418 : inner_relids = rinfo->left_relids;
2341 : : }
2342 : :
2343 : : /* Scan EquivalenceClasses for a match to outervar */
2344 [ + - + + : 323586 : foreach(lc1, root->eq_classes)
+ + ]
2345 : : {
2346 : 272484 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2347 : : bool match;
2348 : : ListCell *lc2;
2349 : :
2350 : : /* We don't expect any children yet */
2351 : : Assert(cur_ec->ec_childmembers == NULL);
2352 : :
2353 : : /* Ignore EC unless it contains pseudoconstants */
2354 [ + + ]: 272484 : if (!cur_ec->ec_has_const)
2355 : 211646 : continue;
2356 : : /* Never match to a volatile EC */
2357 [ - + ]: 60838 : if (cur_ec->ec_has_volatile)
2358 : 0 : continue;
2359 : : /* It has to match the outer-join clause as to semantics, too */
2360 [ + + ]: 60838 : if (collation != cur_ec->ec_collation)
2361 : 4015 : continue;
2362 [ + + ]: 56823 : if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
2363 : 10897 : continue;
2364 : : /* Does it contain a match to outervar? */
2365 : 45926 : match = false;
2366 [ + - + + : 145922 : foreach(lc2, cur_ec->ec_members)
+ + ]
2367 : : {
2368 : 101743 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2369 : :
2370 : : /* Child members should not exist in ec_members */
2371 : : Assert(!cur_em->em_is_child);
2372 [ + + ]: 101743 : if (equal(outervar, cur_em->em_expr))
2373 : : {
2374 : 1747 : match = true;
2375 : 1747 : break;
2376 : : }
2377 : : }
2378 [ + + ]: 45926 : if (!match)
2379 : 44179 : continue; /* no match, so ignore this EC */
2380 : :
2381 : : /*
2382 : : * Yes it does! Try to generate a clause INNERVAR = CONSTANT for each
2383 : : * CONSTANT in the EC. Note that we must succeed with at least one
2384 : : * constant before we can decide to throw away the outer-join clause.
2385 : : */
2386 : 1747 : match = false;
2387 [ + - + + : 6134 : foreach(lc2, cur_ec->ec_members)
+ + ]
2388 : : {
2389 : 4387 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2390 : : Oid eq_op;
2391 : : RestrictInfo *newrinfo;
2392 : : JoinDomain *jdomain;
2393 : :
2394 [ + + ]: 4387 : if (!cur_em->em_is_const)
2395 : 2605 : continue; /* ignore non-const members */
2396 : 1782 : eq_op = select_equality_operator(cur_ec,
2397 : : inner_datatype,
2398 : : cur_em->em_datatype);
2399 [ - + ]: 1782 : if (!OidIsValid(eq_op))
2400 : 0 : continue; /* can't generate equality */
2401 : 1782 : newrinfo = build_implied_join_equality(root,
2402 : : eq_op,
2403 : : cur_ec->ec_collation,
2404 : : innervar,
2405 : : cur_em->em_expr,
2406 : : bms_copy(inner_relids),
2407 : : cur_ec->ec_min_security);
2408 : : /* This equality holds within the OJ's child JoinDomain */
2409 : 1782 : jdomain = find_join_domain(root, sjinfo->syn_righthand);
2410 [ + - ]: 1782 : if (process_equivalence(root, &newrinfo, jdomain))
2411 : 1782 : match = true;
2412 : : }
2413 : :
2414 : : /*
2415 : : * If we were able to equate INNERVAR to any constant, report success.
2416 : : * Otherwise, fall out of the search loop, since we know the OUTERVAR
2417 : : * appears in at most one EC.
2418 : : */
2419 [ + - ]: 1747 : if (match)
2420 : 1747 : return true;
2421 : : else
2422 : 0 : break;
2423 : : }
2424 : :
2425 : 51102 : return false; /* failed to make any deduction */
2426 : : }
2427 : :
2428 : : /*
2429 : : * reconsider_outer_join_clauses for a single FULL JOIN clause
2430 : : *
2431 : : * Returns true if we were able to propagate a constant through the clause.
2432 : : */
2433 : : static bool
2434 : 1188 : reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
2435 : : {
2436 : 1188 : RestrictInfo *rinfo = ojcinfo->rinfo;
2437 : 1188 : SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
2438 : 1188 : Relids fjrelids = bms_make_singleton(sjinfo->ojrelid);
2439 : : Expr *leftvar;
2440 : : Expr *rightvar;
2441 : : Oid opno,
2442 : : collation,
2443 : : left_type,
2444 : : right_type;
2445 : : Relids left_relids,
2446 : : right_relids;
2447 : : JoinDomain *left_jdomain,
2448 : : *right_jdomain;
2449 : : ListCell *lc1;
2450 : :
2451 : : /* Extract needed info from the clause */
2452 : : Assert(is_opclause(rinfo->clause));
2453 : 1188 : opno = ((OpExpr *) rinfo->clause)->opno;
2454 : 1188 : collation = ((OpExpr *) rinfo->clause)->inputcollid;
2455 : 1188 : op_input_types(opno, &left_type, &right_type);
2456 : 1188 : leftvar = (Expr *) get_leftop(rinfo->clause);
2457 : 1188 : rightvar = (Expr *) get_rightop(rinfo->clause);
2458 : 1188 : left_relids = rinfo->left_relids;
2459 : 1188 : right_relids = rinfo->right_relids;
2460 : :
2461 : : /*
2462 : : * Identify the child JoinDomains within which LEFTVAR = CONSTANT and
2463 : : * RIGHTVAR = CONSTANT would hold. We mustn't assume that LEFTVAR comes
2464 : : * from the join's lefthand input, since the clause might have been
2465 : : * written as, say, "a FULL JOIN b ON b.y = a.x". If the clause doesn't
2466 : : * relate an expression of one input to an expression of the other, we
2467 : : * can't deduce anything from it.
2468 : : */
2469 [ + + + + ]: 2174 : if (bms_is_subset(left_relids, sjinfo->syn_lefthand) &&
2470 : 986 : bms_is_subset(right_relids, sjinfo->syn_righthand))
2471 : : {
2472 : 972 : left_jdomain = find_join_domain(root, sjinfo->syn_lefthand);
2473 : 972 : right_jdomain = find_join_domain(root, sjinfo->syn_righthand);
2474 : : }
2475 [ + + + - ]: 408 : else if (bms_is_subset(left_relids, sjinfo->syn_righthand) &&
2476 : 192 : bms_is_subset(right_relids, sjinfo->syn_lefthand))
2477 : : {
2478 : 192 : left_jdomain = find_join_domain(root, sjinfo->syn_righthand);
2479 : 192 : right_jdomain = find_join_domain(root, sjinfo->syn_lefthand);
2480 : : }
2481 : : else
2482 : 24 : return false;
2483 : :
2484 [ + - + + : 5724 : foreach(lc1, root->eq_classes)
+ + ]
2485 : : {
2486 : 4615 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2487 : 4615 : EquivalenceMember *coal_em = NULL;
2488 : : bool match;
2489 : : bool matchleft;
2490 : : bool matchright;
2491 : : ListCell *lc2;
2492 : 4615 : int coal_idx = -1;
2493 : :
2494 : : /* We don't expect any children yet */
2495 : : Assert(cur_ec->ec_childmembers == NULL);
2496 : :
2497 : : /* Ignore EC unless it contains pseudoconstants */
2498 [ + + ]: 4615 : if (!cur_ec->ec_has_const)
2499 : 4285 : continue;
2500 : : /* Never match to a volatile EC */
2501 [ - + ]: 330 : if (cur_ec->ec_has_volatile)
2502 : 0 : continue;
2503 : : /* It has to match the outer-join clause as to semantics, too */
2504 [ + + ]: 330 : if (collation != cur_ec->ec_collation)
2505 : 30 : continue;
2506 [ - + ]: 300 : if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
2507 : 0 : continue;
2508 : :
2509 : : /*
2510 : : * Does it contain a COALESCE(leftvar, rightvar) construct?
2511 : : *
2512 : : * We can assume the COALESCE() inputs are in the same order as the
2513 : : * join clause, since both were automatically generated in the cases
2514 : : * we care about.
2515 : : *
2516 : : * XXX currently this may fail to match in cross-type cases because
2517 : : * the COALESCE will contain typecast operations while the join clause
2518 : : * may not (if there is a cross-type mergejoin operator available for
2519 : : * the two column types). Is it OK to strip implicit coercions from
2520 : : * the COALESCE arguments?
2521 : : */
2522 : 300 : match = false;
2523 [ + - + + : 795 : foreach(lc2, cur_ec->ec_members)
+ + ]
2524 : : {
2525 : 550 : coal_em = (EquivalenceMember *) lfirst(lc2);
2526 : :
2527 : : /* Child members should not exist in ec_members */
2528 : : Assert(!coal_em->em_is_child);
2529 [ + + ]: 550 : if (IsA(coal_em->em_expr, CoalesceExpr))
2530 : : {
2531 : 85 : CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
2532 : : Node *cfirst;
2533 : : Node *csecond;
2534 : :
2535 [ - + ]: 85 : if (list_length(cexpr->args) != 2)
2536 : 0 : continue;
2537 : 85 : cfirst = (Node *) linitial(cexpr->args);
2538 : 85 : csecond = (Node *) lsecond(cexpr->args);
2539 : :
2540 : : /*
2541 : : * The COALESCE arguments will be marked as possibly nulled by
2542 : : * the full join, while we wish to generate clauses that apply
2543 : : * to the join's inputs. So we must strip the join from the
2544 : : * nullingrels fields of cfirst/csecond before comparing them
2545 : : * to leftvar/rightvar. (Perhaps with a less hokey
2546 : : * representation for FULL JOIN USING output columns, this
2547 : : * wouldn't be needed?)
2548 : : */
2549 : 85 : cfirst = remove_nulling_relids(cfirst, fjrelids, NULL);
2550 : 85 : csecond = remove_nulling_relids(csecond, fjrelids, NULL);
2551 : :
2552 [ + + + + ]: 85 : if (equal(leftvar, cfirst) && equal(rightvar, csecond))
2553 : : {
2554 : 55 : coal_idx = foreach_current_index(lc2);
2555 : 55 : match = true;
2556 : 55 : break;
2557 : : }
2558 : : }
2559 : : }
2560 [ + + ]: 300 : if (!match)
2561 : 245 : continue; /* no match, so ignore this EC */
2562 : :
2563 : : /*
2564 : : * Yes it does! Try to generate clauses LEFTVAR = CONSTANT and
2565 : : * RIGHTVAR = CONSTANT for each CONSTANT in the EC. Note that we must
2566 : : * succeed with at least one constant for each var before we can
2567 : : * decide to throw away the outer-join clause.
2568 : : */
2569 : 55 : matchleft = matchright = false;
2570 [ + - + + : 165 : foreach(lc2, cur_ec->ec_members)
+ + ]
2571 : : {
2572 : 110 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2573 : : Oid eq_op;
2574 : : RestrictInfo *newrinfo;
2575 : :
2576 [ + + ]: 110 : if (!cur_em->em_is_const)
2577 : 55 : continue; /* ignore non-const members */
2578 : 55 : eq_op = select_equality_operator(cur_ec,
2579 : : left_type,
2580 : : cur_em->em_datatype);
2581 [ + - ]: 55 : if (OidIsValid(eq_op))
2582 : : {
2583 : 55 : newrinfo = build_implied_join_equality(root,
2584 : : eq_op,
2585 : : cur_ec->ec_collation,
2586 : : leftvar,
2587 : : cur_em->em_expr,
2588 : : bms_copy(left_relids),
2589 : : cur_ec->ec_min_security);
2590 : : /* This equality holds within LEFTVAR's child JoinDomain */
2591 [ + - ]: 55 : if (process_equivalence(root, &newrinfo, left_jdomain))
2592 : 55 : matchleft = true;
2593 : : }
2594 : 55 : eq_op = select_equality_operator(cur_ec,
2595 : : right_type,
2596 : : cur_em->em_datatype);
2597 [ + - ]: 55 : if (OidIsValid(eq_op))
2598 : : {
2599 : 55 : newrinfo = build_implied_join_equality(root,
2600 : : eq_op,
2601 : : cur_ec->ec_collation,
2602 : : rightvar,
2603 : : cur_em->em_expr,
2604 : : bms_copy(right_relids),
2605 : : cur_ec->ec_min_security);
2606 : : /* This equality holds within RIGHTVAR's child JoinDomain */
2607 [ + - ]: 55 : if (process_equivalence(root, &newrinfo, right_jdomain))
2608 : 55 : matchright = true;
2609 : : }
2610 : : }
2611 : :
2612 : : /*
2613 : : * If we were able to equate both vars to constants, we're done, and
2614 : : * we can throw away the full-join clause as redundant. Moreover, we
2615 : : * can remove the COALESCE entry from the EC, since the added
2616 : : * restrictions ensure it will always have the expected value. (We
2617 : : * don't bother trying to update ec_relids or ec_sources.)
2618 : : */
2619 [ + - + - ]: 55 : if (matchleft && matchright)
2620 : : {
2621 : 55 : cur_ec->ec_members = list_delete_nth_cell(cur_ec->ec_members, coal_idx);
2622 : 55 : return true;
2623 : : }
2624 : :
2625 : : /*
2626 : : * Otherwise, fall out of the search loop, since we know the COALESCE
2627 : : * appears in at most one EC (XXX might stop being true if we allow
2628 : : * stripping of coercions above?)
2629 : : */
2630 : 0 : break;
2631 : : }
2632 : :
2633 : 1109 : return false; /* failed to make any deduction */
2634 : : }
2635 : :
2636 : : /*
2637 : : * find_join_domain
2638 : : * Find the highest JoinDomain enclosed within the given relid set.
2639 : : *
2640 : : * (We could avoid this search at the cost of complicating APIs elsewhere,
2641 : : * which doesn't seem worth it.)
2642 : : */
2643 : : static JoinDomain *
2644 : 4110 : find_join_domain(PlannerInfo *root, Relids relids)
2645 : : {
2646 : : ListCell *lc;
2647 : :
2648 [ + - + - : 12815 : foreach(lc, root->join_domains)
+ - ]
2649 : : {
2650 : 12815 : JoinDomain *jdomain = (JoinDomain *) lfirst(lc);
2651 : :
2652 [ + + ]: 12815 : if (bms_is_subset(jdomain->jd_relids, relids))
2653 : 4110 : return jdomain;
2654 : : }
2655 [ # # ]: 0 : elog(ERROR, "failed to find appropriate JoinDomain");
2656 : : return NULL; /* keep compiler quiet */
2657 : : }
2658 : :
2659 : :
2660 : : /*
2661 : : * exprs_known_equal
2662 : : * Detect whether two expressions are known equal due to equivalence
2663 : : * relationships.
2664 : : *
2665 : : * If opfamily is given, the expressions must be known equal per the semantics
2666 : : * of that opfamily (note it has to be a btree opfamily, since those are the
2667 : : * only opfamilies equivclass.c deals with). If opfamily is InvalidOid, we'll
2668 : : * return true if they're equal according to any opfamily, which is fuzzy but
2669 : : * OK for estimation purposes.
2670 : : *
2671 : : * Note: does not bother to check for "equal(item1, item2)"; caller must
2672 : : * check that case if it's possible to pass identical items.
2673 : : */
2674 : : bool
2675 : 31995 : exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
2676 : : {
2677 : : ListCell *lc1;
2678 : :
2679 [ + + + + : 219586 : foreach(lc1, root->eq_classes)
+ + ]
2680 : : {
2681 : 190417 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2682 : 190417 : bool item1member = false;
2683 : 190417 : bool item2member = false;
2684 : : ListCell *lc2;
2685 : :
2686 : : /* Never match to a volatile EC */
2687 [ - + ]: 190417 : if (ec->ec_has_volatile)
2688 : 0 : continue;
2689 : :
2690 : : /*
2691 : : * It's okay to consider ec_broken ECs here. Brokenness just means we
2692 : : * couldn't derive all the implied clauses we'd have liked to; it does
2693 : : * not invalidate our knowledge that the members are equal.
2694 : : */
2695 : :
2696 : : /* Ignore if this EC doesn't use specified opfamily */
2697 [ + + ]: 190417 : if (OidIsValid(opfamily) &&
2698 [ + + ]: 590 : !list_member_oid(ec->ec_opfamilies, opfamily))
2699 : 190 : continue;
2700 : :
2701 : : /* Ignore children here */
2702 [ + - + + : 473907 : foreach(lc2, ec->ec_members)
+ + ]
2703 : : {
2704 : 286506 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
2705 : :
2706 : : /* Child members should not exist in ec_members */
2707 : : Assert(!em->em_is_child);
2708 [ + + ]: 286506 : if (equal(item1, em->em_expr))
2709 : 12805 : item1member = true;
2710 [ + + ]: 273701 : else if (equal(item2, em->em_expr))
2711 : 24104 : item2member = true;
2712 : : /* Exit as soon as equality is proven */
2713 [ + + + + ]: 286506 : if (item1member && item2member)
2714 : 2826 : return true;
2715 : : }
2716 : : }
2717 : 29169 : return false;
2718 : : }
2719 : :
2720 : :
2721 : : /*
2722 : : * match_eclasses_to_foreign_key_col
2723 : : * See whether a foreign key column match is proven by any eclass.
2724 : : *
2725 : : * If the referenced and referencing Vars of the fkey's colno'th column are
2726 : : * known equal due to any eclass, return that eclass; otherwise return NULL.
2727 : : * (In principle there might be more than one matching eclass if multiple
2728 : : * collations are involved, but since collation doesn't matter for equality,
2729 : : * we ignore that fine point here.) This is much like exprs_known_equal,
2730 : : * except for the format of the input.
2731 : : *
2732 : : * On success, we also set fkinfo->eclass[colno] to the matching eclass,
2733 : : * and set fkinfo->fk_eclass_member[colno] to the eclass member for the
2734 : : * referencing Var.
2735 : : */
2736 : : EquivalenceClass *
2737 : 1943 : match_eclasses_to_foreign_key_col(PlannerInfo *root,
2738 : : ForeignKeyOptInfo *fkinfo,
2739 : : int colno)
2740 : : {
2741 : 1943 : Index var1varno = fkinfo->con_relid;
2742 : 1943 : AttrNumber var1attno = fkinfo->conkey[colno];
2743 : 1943 : Index var2varno = fkinfo->ref_relid;
2744 : 1943 : AttrNumber var2attno = fkinfo->confkey[colno];
2745 : 1943 : Oid eqop = fkinfo->conpfeqop[colno];
2746 : 1943 : RelOptInfo *rel1 = root->simple_rel_array[var1varno];
2747 : 1943 : RelOptInfo *rel2 = root->simple_rel_array[var2varno];
2748 : 1943 : List *opfamilies = NIL; /* compute only if needed */
2749 : : Bitmapset *matching_ecs;
2750 : : int i;
2751 : :
2752 : : /* Consider only eclasses mentioning both relations */
2753 : : Assert(root->ec_merging_done);
2754 : : Assert(IS_SIMPLE_REL(rel1));
2755 : : Assert(IS_SIMPLE_REL(rel2));
2756 : 1943 : matching_ecs = bms_intersect(rel1->eclass_indexes,
2757 : 1943 : rel2->eclass_indexes);
2758 : :
2759 : 1943 : i = -1;
2760 [ + + ]: 2023 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
2761 : : {
2762 : 425 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
2763 : : i);
2764 : 425 : EquivalenceMember *item1_em = NULL;
2765 : 425 : EquivalenceMember *item2_em = NULL;
2766 : : ListCell *lc2;
2767 : :
2768 : : /* Never match to a volatile EC */
2769 [ - + ]: 425 : if (ec->ec_has_volatile)
2770 : 0 : continue;
2771 : :
2772 : : /*
2773 : : * It's okay to consider "broken" ECs here, see exprs_known_equal.
2774 : : * Ignore children here.
2775 : : */
2776 [ + - + + : 1015 : foreach(lc2, ec->ec_members)
+ + ]
2777 : : {
2778 : 935 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
2779 : : Var *var;
2780 : :
2781 : : /* Child members should not exist in ec_members */
2782 : : Assert(!em->em_is_child);
2783 : :
2784 : : /* EM must be a Var, possibly with RelabelType */
2785 : 935 : var = (Var *) em->em_expr;
2786 [ + - - + ]: 935 : while (var && IsA(var, RelabelType))
2787 : 0 : var = (Var *) ((RelabelType *) var)->arg;
2788 [ + - + + ]: 935 : if (!(var && IsA(var, Var)))
2789 : 5 : continue;
2790 : :
2791 : : /* Match? */
2792 [ + + + + ]: 930 : if (var->varno == var1varno && var->varattno == var1attno)
2793 : 345 : item1_em = em;
2794 [ + + + + ]: 585 : else if (var->varno == var2varno && var->varattno == var2attno)
2795 : 345 : item2_em = em;
2796 : :
2797 : : /* Have we found both PK and FK column in this EC? */
2798 [ + + + + ]: 930 : if (item1_em && item2_em)
2799 : : {
2800 : : /*
2801 : : * Succeed if eqop matches EC's opfamilies. We could test
2802 : : * this before scanning the members, but it's probably cheaper
2803 : : * to test for member matches first.
2804 : : */
2805 [ + - ]: 345 : if (opfamilies == NIL) /* compute if we didn't already */
2806 : 345 : opfamilies = get_mergejoin_opfamilies(eqop);
2807 [ + - ]: 345 : if (equal(opfamilies, ec->ec_opfamilies))
2808 : : {
2809 : 345 : fkinfo->eclass[colno] = ec;
2810 : 345 : fkinfo->fk_eclass_member[colno] = item2_em;
2811 : 345 : return ec;
2812 : : }
2813 : : /* Otherwise, done with this EC, move on to the next */
2814 : 0 : break;
2815 : : }
2816 : : }
2817 : : }
2818 : 1598 : return NULL;
2819 : : }
2820 : :
2821 : : /*
2822 : : * find_derived_clause_for_ec_member
2823 : : * Search for a previously-derived clause mentioning the given EM.
2824 : : *
2825 : : * The eclass should be an ec_has_const EC, of which the EM is a non-const
2826 : : * member. This should ensure there is just one derived clause mentioning
2827 : : * the EM (and equating it to a constant).
2828 : : * Returns NULL if no such clause can be found.
2829 : : */
2830 : : RestrictInfo *
2831 : 5 : find_derived_clause_for_ec_member(PlannerInfo *root,
2832 : : EquivalenceClass *ec,
2833 : : EquivalenceMember *em)
2834 : : {
2835 : : Assert(ec->ec_has_const);
2836 : : Assert(!em->em_is_const);
2837 : :
2838 : 5 : return ec_search_derived_clause_for_ems(root, ec, em, NULL, NULL);
2839 : : }
2840 : :
2841 : :
2842 : : /*
2843 : : * add_child_rel_equivalences
2844 : : * Search for EC members that reference the root parent of child_rel, and
2845 : : * add transformed members referencing the child_rel.
2846 : : *
2847 : : * Note that this function won't be called at all unless we have at least some
2848 : : * reason to believe that the EC members it generates will be useful.
2849 : : *
2850 : : * parent_rel and child_rel could be derived from appinfo, but since the
2851 : : * caller has already computed them, we might as well just pass them in.
2852 : : *
2853 : : * The passed-in AppendRelInfo is not used when the parent_rel is not a
2854 : : * top-level baserel, since it shows the mapping from the parent_rel but
2855 : : * we need to translate EC expressions that refer to the top-level parent.
2856 : : * Using it is faster than using adjust_appendrel_attrs_multilevel(), though,
2857 : : * so we prefer it when we can.
2858 : : */
2859 : : void
2860 : 28916 : add_child_rel_equivalences(PlannerInfo *root,
2861 : : AppendRelInfo *appinfo,
2862 : : RelOptInfo *parent_rel,
2863 : : RelOptInfo *child_rel)
2864 : : {
2865 : 28916 : Relids top_parent_relids = child_rel->top_parent_relids;
2866 : 28916 : Relids child_relids = child_rel->relids;
2867 : : int i;
2868 : :
2869 : : /*
2870 : : * EC merging should be complete already, so we can use the parent rel's
2871 : : * eclass_indexes to avoid searching all of root->eq_classes.
2872 : : */
2873 : : Assert(root->ec_merging_done);
2874 : : Assert(IS_SIMPLE_REL(parent_rel));
2875 : :
2876 : 28916 : i = -1;
2877 [ + + ]: 82077 : while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
2878 : : {
2879 : 53161 : EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2880 : :
2881 : : /*
2882 : : * If this EC contains a volatile expression, then generating child
2883 : : * EMs would be downright dangerous, so skip it. We rely on a
2884 : : * volatile EC having only one EM.
2885 : : */
2886 [ - + ]: 53161 : if (cur_ec->ec_has_volatile)
2887 : 0 : continue;
2888 : :
2889 : : /* Sanity check eclass_indexes only contain ECs for parent_rel */
2890 : : Assert(bms_is_subset(top_parent_relids, cur_ec->ec_relids));
2891 : :
2892 [ + - + + : 182901 : foreach_node(EquivalenceMember, cur_em, cur_ec->ec_members)
+ + ]
2893 : : {
2894 [ + + ]: 76579 : if (cur_em->em_is_const)
2895 : 2886 : continue; /* ignore consts here */
2896 : :
2897 : : /* Child members should not exist in ec_members */
2898 : : Assert(!cur_em->em_is_child);
2899 : :
2900 : : /*
2901 : : * Consider only members that reference and can be computed at
2902 : : * child's topmost parent rel. In particular we want to exclude
2903 : : * parent-rel Vars that have nonempty varnullingrels. Translating
2904 : : * those might fail, if the transformed expression wouldn't be a
2905 : : * simple Var; and in any case it wouldn't produce a member that
2906 : : * has any use in creating plans for the child rel.
2907 : : */
2908 [ + + ]: 73693 : if (bms_is_subset(cur_em->em_relids, top_parent_relids) &&
2909 [ + - ]: 51082 : !bms_is_empty(cur_em->em_relids))
2910 : : {
2911 : : /* OK, generate transformed child version */
2912 : : Expr *child_expr;
2913 : :
2914 [ + + ]: 51082 : if (parent_rel->reloptkind == RELOPT_BASEREL)
2915 : : {
2916 : : /* Simple single-level transformation */
2917 : : child_expr = (Expr *)
2918 : 43885 : adjust_appendrel_attrs(root,
2919 : 43885 : (Node *) cur_em->em_expr,
2920 : : 1, &appinfo);
2921 : : }
2922 : : else
2923 : : {
2924 : : /* Must do multi-level transformation */
2925 : : child_expr = (Expr *)
2926 : 7197 : adjust_appendrel_attrs_multilevel(root,
2927 : 7197 : (Node *) cur_em->em_expr,
2928 : : child_rel,
2929 : 7197 : child_rel->top_parent);
2930 : : }
2931 : :
2932 : : /*
2933 : : * The member's relids are all within the parent, so the child
2934 : : * version's relids are just the child's. Note we do *not* do
2935 : : * pull_varnos(child_expr) here, as for example the
2936 : : * transformation might have substituted a constant, but we
2937 : : * don't want the child member to be marked as constant.
2938 : : */
2939 : 51082 : add_child_eq_member(root,
2940 : : cur_ec,
2941 : : i,
2942 : : child_expr,
2943 : : bms_copy(child_relids),
2944 : : cur_em->em_jdomain,
2945 : : cur_em,
2946 : : cur_em->em_datatype,
2947 : : child_rel->relid);
2948 : : }
2949 : : }
2950 : : }
2951 : 28916 : }
2952 : :
2953 : : /*
2954 : : * add_child_join_rel_equivalences
2955 : : * Like add_child_rel_equivalences(), but for joinrels
2956 : : *
2957 : : * Here we find the ECs relevant to the top parent joinrel and add transformed
2958 : : * member expressions that refer to this child joinrel.
2959 : : *
2960 : : * Note that this function won't be called at all unless we have at least some
2961 : : * reason to believe that the EC members it generates will be useful.
2962 : : */
2963 : : void
2964 : 21373 : add_child_join_rel_equivalences(PlannerInfo *root,
2965 : : int nappinfos, AppendRelInfo **appinfos,
2966 : : RelOptInfo *parent_joinrel,
2967 : : RelOptInfo *child_joinrel)
2968 : : {
2969 : 21373 : Relids top_parent_relids = child_joinrel->top_parent_relids;
2970 : 21373 : Relids child_relids = child_joinrel->relids;
2971 : : Bitmapset *matching_ecs;
2972 : : MemoryContext oldcontext;
2973 : : int i;
2974 : :
2975 : : Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
2976 : :
2977 : : /* We need consider only ECs that mention the parent joinrel */
2978 : 21373 : matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
2979 : :
2980 : : /*
2981 : : * If we're being called during GEQO join planning, we still have to
2982 : : * create any new EC members in the main planner context, to avoid having
2983 : : * a corrupt EC data structure after the GEQO context is reset. This is
2984 : : * problematic since we'll leak memory across repeated GEQO cycles. For
2985 : : * now, though, bloat is better than crash. If it becomes a real issue
2986 : : * we'll have to do something to avoid generating duplicate EC members.
2987 : : */
2988 : 21373 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2989 : :
2990 : 21373 : i = -1;
2991 [ + + ]: 64781 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
2992 : : {
2993 : 43408 : EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2994 : :
2995 : : /*
2996 : : * If this EC contains a volatile expression, then generating child
2997 : : * EMs would be downright dangerous, so skip it. We rely on a
2998 : : * volatile EC having only one EM.
2999 : : */
3000 [ - + ]: 43408 : if (cur_ec->ec_has_volatile)
3001 : 0 : continue;
3002 : :
3003 : : /* Sanity check on get_eclass_indexes_for_relids result */
3004 : : Assert(bms_overlap(top_parent_relids, cur_ec->ec_relids));
3005 : :
3006 [ + - + + : 172642 : foreach_node(EquivalenceMember, cur_em, cur_ec->ec_members)
+ + ]
3007 : : {
3008 [ + + ]: 85826 : if (cur_em->em_is_const)
3009 : 7298 : continue; /* ignore consts here */
3010 : :
3011 : : /* Child members should not exist in ec_members */
3012 : : Assert(!cur_em->em_is_child);
3013 : :
3014 : : /*
3015 : : * We may ignore expressions that reference a single baserel,
3016 : : * because add_child_rel_equivalences should have handled them.
3017 : : */
3018 [ + + ]: 78528 : if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
3019 : 69991 : continue;
3020 : :
3021 : : /*
3022 : : * Consider only members that can be computed at child's topmost
3023 : : * parent joinrel, as in add_child_rel_equivalences.
3024 : : */
3025 [ + + ]: 8537 : if (bms_is_subset(cur_em->em_relids, top_parent_relids))
3026 : : {
3027 : : /* OK, generate transformed child version */
3028 : : Expr *child_expr;
3029 : :
3030 [ + + ]: 5687 : if (parent_joinrel->reloptkind == RELOPT_JOINREL)
3031 : : {
3032 : : /* Simple single-level transformation */
3033 : : child_expr = (Expr *)
3034 : 5607 : adjust_appendrel_attrs(root,
3035 : 5607 : (Node *) cur_em->em_expr,
3036 : : nappinfos, appinfos);
3037 : : }
3038 : : else
3039 : : {
3040 : : /* Must do multi-level transformation */
3041 : : Assert(parent_joinrel->reloptkind == RELOPT_OTHER_JOINREL);
3042 : : child_expr = (Expr *)
3043 : 80 : adjust_appendrel_attrs_multilevel(root,
3044 : 80 : (Node *) cur_em->em_expr,
3045 : : child_joinrel,
3046 : 80 : child_joinrel->top_parent);
3047 : : }
3048 : :
3049 : : /*
3050 : : * Add new child member to the EquivalenceClass. Because this
3051 : : * is a RELOPT_OTHER_JOINREL which has multiple component
3052 : : * relids, there is no ideal place to store these members in
3053 : : * the class. Ordinarily, child members are stored in the
3054 : : * ec_childmembers[] array element corresponding to their
3055 : : * relid, however, here we have multiple component relids, so
3056 : : * there's no single ec_childmembers[] array element to store
3057 : : * this member. So that we still correctly find this member
3058 : : * in loops iterating over an EquivalenceMemberIterator, we
3059 : : * opt to store the member in the ec_childmembers array in
3060 : : * only the first component relid slot of the array. This
3061 : : * allows the member to be found, providing callers of
3062 : : * setup_eclass_member_iterator() specify all the component
3063 : : * relids for the RELOPT_OTHER_JOINREL, which they do. If we
3064 : : * opted to store the member in each ec_childmembers[] element
3065 : : * for all the component relids, then that would just result
3066 : : * in eclass_member_iterator_next() finding the member
3067 : : * multiple times, which is a waste of effort.
3068 : : *
3069 : : * As in add_child_rel_equivalences, the child member's relids
3070 : : * are just the child's.
3071 : : */
3072 : 5687 : add_child_eq_member(root,
3073 : : cur_ec,
3074 : : -1,
3075 : : child_expr,
3076 : : bms_copy(child_relids),
3077 : : cur_em->em_jdomain,
3078 : : cur_em,
3079 : : cur_em->em_datatype,
3080 : 5687 : bms_next_member(child_joinrel->relids, -1));
3081 : : }
3082 : : }
3083 : : }
3084 : :
3085 : 21373 : MemoryContextSwitchTo(oldcontext);
3086 : 21373 : }
3087 : :
3088 : : /*
3089 : : * add_child_rel_pathkey_equivalences
3090 : : * Make sure the ECs of the given pathkeys have members for child_rel.
3091 : : *
3092 : : * An EC created after its relations' children were processed has no child
3093 : : * members, so child_rel could not be sorted by it. Add them here.
3094 : : */
3095 : : void
3096 : 590 : add_child_rel_pathkey_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
3097 : : List *pathkeys)
3098 : : {
3099 : 590 : Relids top_parent_relids = child_rel->top_parent_relids;
3100 : : MemoryContext oldcontext;
3101 : : ListCell *lc;
3102 : :
3103 : : Assert(IS_OTHER_REL(child_rel));
3104 : :
3105 : : /* As in add_child_join_rel_equivalences, new members must survive GEQO */
3106 : 590 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3107 : :
3108 [ + - + + : 1340 : foreach(lc, pathkeys)
+ + ]
3109 : : {
3110 : 750 : EquivalenceClass *ec = lfirst_node(PathKey, lc)->pk_eclass;
3111 : :
3112 [ - + ]: 750 : if (ec->ec_has_volatile)
3113 : 0 : continue;
3114 : :
3115 [ + - + + : 3040 : foreach_node(EquivalenceMember, cur_em, ec->ec_members)
+ + ]
3116 : : {
3117 : : EquivalenceMemberIterator it;
3118 : : EquivalenceMember *em;
3119 : : Expr *child_expr;
3120 : : Relids new_relids;
3121 : : int child_relid;
3122 : :
3123 : : /* Consider only members computable at the topmost parent */
3124 [ + - ]: 1540 : if (cur_em->em_is_const ||
3125 [ + + ]: 1540 : !bms_is_subset(cur_em->em_relids, top_parent_relids))
3126 : 1480 : continue;
3127 : :
3128 : : /* Skip members that already have a child version for this rel */
3129 : 950 : setup_eclass_member_iterator(&it, ec, child_rel->relids);
3130 [ + + ]: 4240 : while ((em = eclass_member_iterator_next(&it)) != NULL)
3131 : : {
3132 [ + + + - ]: 4120 : if (em->em_parent == cur_em &&
3133 : 890 : bms_is_subset(em->em_relids, child_rel->relids))
3134 : 890 : break;
3135 : : }
3136 [ + + ]: 950 : if (em != NULL)
3137 : 890 : continue;
3138 : :
3139 : 60 : new_relids = adjust_child_relids_multilevel(root,
3140 : : cur_em->em_relids,
3141 : : child_rel,
3142 : 60 : child_rel->top_parent);
3143 : :
3144 : : /* Store the member under one of its child relations */
3145 : 60 : child_relid = bms_next_member(bms_difference(new_relids,
3146 : : top_parent_relids),
3147 : : -1);
3148 [ - + ]: 60 : if (child_relid < 0)
3149 : 0 : continue;
3150 : :
3151 : : child_expr = (Expr *)
3152 : 60 : adjust_appendrel_attrs_multilevel(root,
3153 : 60 : (Node *) cur_em->em_expr,
3154 : : child_rel,
3155 : 60 : child_rel->top_parent);
3156 : :
3157 : 60 : add_child_eq_member(root, ec, -1, child_expr, new_relids,
3158 : : cur_em->em_jdomain, cur_em,
3159 : : cur_em->em_datatype, child_relid);
3160 : : }
3161 : : }
3162 : :
3163 : 590 : MemoryContextSwitchTo(oldcontext);
3164 : 590 : }
3165 : :
3166 : : /*
3167 : : * add_setop_child_rel_equivalences
3168 : : * Add equivalence members for each non-resjunk target in 'child_tlist'
3169 : : * to the EquivalenceClass in the corresponding setop_pathkey's pk_eclass.
3170 : : *
3171 : : * 'root' is the PlannerInfo belonging to the top-level set operation.
3172 : : * 'child_rel' is the RelOptInfo of the child relation we're adding
3173 : : * EquivalenceMembers for.
3174 : : * 'child_tlist' is the target list for the setop child relation. The target
3175 : : * list expressions are what we add as EquivalenceMembers.
3176 : : * 'setop_pathkeys' is a list of PathKeys which must contain an entry for each
3177 : : * non-resjunk target in 'child_tlist'.
3178 : : */
3179 : : void
3180 : 10404 : add_setop_child_rel_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
3181 : : List *child_tlist, List *setop_pathkeys)
3182 : : {
3183 : : ListCell *lc;
3184 : 10404 : ListCell *lc2 = list_head(setop_pathkeys);
3185 : :
3186 [ + - + + : 42296 : foreach(lc, child_tlist)
+ + ]
3187 : : {
3188 : 31892 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
3189 : : EquivalenceMember *parent_em;
3190 : : PathKey *pk;
3191 : :
3192 [ - + ]: 31892 : if (tle->resjunk)
3193 : 0 : continue;
3194 : :
3195 [ - + ]: 31892 : if (lc2 == NULL)
3196 [ # # ]: 0 : elog(ERROR, "too few pathkeys for set operation");
3197 : :
3198 : 31892 : pk = lfirst_node(PathKey, lc2);
3199 : 31892 : parent_em = linitial(pk->pk_eclass->ec_members);
3200 : :
3201 : : /*
3202 : : * We can safely pass the parent member as the first member in the
3203 : : * ec_members list as this is added first in generate_union_paths,
3204 : : * likewise, the JoinDomain can be that of the initial member of the
3205 : : * Pathkey's EquivalenceClass. We pass -1 for ec_index since we
3206 : : * maintain the eclass_indexes for the child_rel after the loop.
3207 : : */
3208 : 31892 : add_child_eq_member(root,
3209 : : pk->pk_eclass,
3210 : : -1,
3211 : : tle->expr,
3212 : : child_rel->relids,
3213 : : parent_em->em_jdomain,
3214 : : parent_em,
3215 : 31892 : exprType((Node *) tle->expr),
3216 : : child_rel->relid);
3217 : :
3218 : 31892 : lc2 = lnext(setop_pathkeys, lc2);
3219 : : }
3220 : :
3221 : : /*
3222 : : * transformSetOperationStmt() ensures that the targetlist never contains
3223 : : * any resjunk columns, so all eclasses that exist in 'root' must have
3224 : : * received a new member in the loop above. Add them to the child_rel's
3225 : : * eclass_indexes.
3226 : : */
3227 : 10404 : child_rel->eclass_indexes = bms_add_range(child_rel->eclass_indexes, 0,
3228 : 10404 : list_length(root->eq_classes) - 1);
3229 : 10404 : }
3230 : :
3231 : : /*
3232 : : * setup_eclass_member_iterator
3233 : : * Setup an EquivalenceMemberIterator 'it' to iterate over all parent
3234 : : * EquivalenceMembers and child members belonging to the given 'ec'.
3235 : : *
3236 : : * This iterator returns:
3237 : : * - All parent members stored directly in ec_members for 'ec', and;
3238 : : * - Any child member added to the given ec by add_child_eq_member() where
3239 : : * the child_relid specified in the add_child_eq_member() call is a member
3240 : : * of the 'child_relids' parameter.
3241 : : *
3242 : : * Note:
3243 : : * The given 'child_relids' must remain allocated and not be changed for the
3244 : : * lifetime of the iterator.
3245 : : *
3246 : : * Parameters:
3247 : : * 'it' is a pointer to the iterator to set up. Normally stack allocated.
3248 : : * 'ec' is the EquivalenceClass from which to iterate members for.
3249 : : * 'child_relids' is the relids to return child members for.
3250 : : */
3251 : : void
3252 : 4115750 : setup_eclass_member_iterator(EquivalenceMemberIterator *it,
3253 : : EquivalenceClass *ec, Relids child_relids)
3254 : : {
3255 : 4115750 : it->ec = ec;
3256 : : /* no need to set this if the class has no child members array set */
3257 [ + + ]: 4115750 : it->child_relids = ec->ec_childmembers != NULL ? child_relids : NULL;
3258 : 4115750 : it->current_relid = -1;
3259 : 4115750 : it->current_list = ec->ec_members;
3260 : 4115750 : it->current_cell = list_head(it->current_list);
3261 : 4115750 : }
3262 : :
3263 : : /*
3264 : : * eclass_member_iterator_next
3265 : : * Get the next EquivalenceMember from the EquivalenceMemberIterator 'it',
3266 : : * as setup by setup_eclass_member_iterator(). NULL is returned if there
3267 : : * are no members left, after which callers must not call
3268 : : * eclass_member_iterator_next() again for the given iterator.
3269 : : */
3270 : : EquivalenceMember *
3271 : 9752225 : eclass_member_iterator_next(EquivalenceMemberIterator *it)
3272 : : {
3273 [ + - ]: 9752225 : while (it->current_list != NULL)
3274 : : {
3275 [ + + ]: 9752225 : while (it->current_cell != NULL)
3276 : : {
3277 : : EquivalenceMember *em;
3278 : :
3279 : 6773742 : nextcell:
3280 : 6902460 : em = lfirst_node(EquivalenceMember, it->current_cell);
3281 : 6902460 : it->current_cell = lnext(it->current_list, it->current_cell);
3282 : 6902460 : return em;
3283 : : }
3284 : :
3285 : : /* Search for the next list to return members from */
3286 [ + + ]: 3124136 : while ((it->current_relid = bms_next_member(it->child_relids, it->current_relid)) > 0)
3287 : : {
3288 : : /*
3289 : : * Be paranoid in case we're given relids above what we've sized
3290 : : * the ec_childmembers array to.
3291 : : */
3292 [ - + ]: 274371 : if (it->current_relid >= it->ec->ec_childmembers_size)
3293 : 0 : return NULL;
3294 : :
3295 : 274371 : it->current_list = it->ec->ec_childmembers[it->current_relid];
3296 : :
3297 : : /* If there are members in this list, use it. */
3298 [ + + ]: 274371 : if (it->current_list != NIL)
3299 : : {
3300 : : /* point current_cell to the head of this list */
3301 : 128718 : it->current_cell = list_head(it->current_list);
3302 : 128718 : goto nextcell;
3303 : : }
3304 : : }
3305 : 2849765 : return NULL;
3306 : : }
3307 : :
3308 : 0 : return NULL;
3309 : : }
3310 : :
3311 : : /*
3312 : : * generate_implied_equalities_for_column
3313 : : * Create EC-derived joinclauses usable with a specific column.
3314 : : *
3315 : : * This is used by indxpath.c to extract potentially indexable joinclauses
3316 : : * from ECs, and can be used by foreign data wrappers for similar purposes.
3317 : : * We assume that only expressions in Vars of a single table are of interest,
3318 : : * but the caller provides a callback function to identify exactly which
3319 : : * such expressions it would like to know about.
3320 : : *
3321 : : * We assume that any given table/index column could appear in only one EC.
3322 : : * (This should be true in all but the most pathological cases, and if it
3323 : : * isn't, we stop on the first match anyway.) Therefore, what we return
3324 : : * is a redundant list of clauses equating the table/index column to each of
3325 : : * the other-relation values it is known to be equal to. Any one of
3326 : : * these clauses can be used to create a parameterized path, and there
3327 : : * is no value in using more than one. (But it *is* worthwhile to create
3328 : : * a separate parameterized path for each one, since that leads to different
3329 : : * join orders.)
3330 : : *
3331 : : * The caller can pass a Relids set of rels we aren't interested in joining
3332 : : * to, so as to save the work of creating useless clauses.
3333 : : */
3334 : : List *
3335 : 478527 : generate_implied_equalities_for_column(PlannerInfo *root,
3336 : : RelOptInfo *rel,
3337 : : ec_matches_callback_type callback,
3338 : : void *callback_arg,
3339 : : Relids prohibited_rels)
3340 : : {
3341 : 478527 : List *result = NIL;
3342 : 478527 : bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
3343 : : Relids parent_relids;
3344 : : int i;
3345 : :
3346 : : /* Should be OK to rely on eclass_indexes */
3347 : : Assert(root->ec_merging_done);
3348 : :
3349 : : /* Indexes are available only on base or "other" member relations. */
3350 : : Assert(IS_SIMPLE_REL(rel));
3351 : :
3352 : : /* If it's a child rel, we'll need to know what its parent(s) are */
3353 [ + + ]: 478527 : if (is_child_rel)
3354 : 10696 : parent_relids = find_childrel_parents(root, rel);
3355 : : else
3356 : 467831 : parent_relids = NULL; /* not used, but keep compiler quiet */
3357 : :
3358 : 478527 : i = -1;
3359 [ + + ]: 1379396 : while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
3360 : : {
3361 : 1001865 : EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
3362 : : EquivalenceMemberIterator it;
3363 : : EquivalenceMember *cur_em;
3364 : : ListCell *lc2;
3365 : :
3366 : : /* Sanity check eclass_indexes only contain ECs for rel */
3367 : : Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
3368 : :
3369 : : /*
3370 : : * Won't generate joinclauses if const or single-member (the latter
3371 : : * test covers the volatile case too)
3372 : : */
3373 [ + + + + ]: 1001865 : if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
3374 : 900709 : continue;
3375 : :
3376 : : /*
3377 : : * Scan members, looking for a match to the target column. Note that
3378 : : * child EC members are considered, but only when they belong to the
3379 : : * target relation. (Unlike regular members, the same expression
3380 : : * could be a child member of more than one EC. Therefore, it's
3381 : : * potentially order-dependent which EC a child relation's target
3382 : : * column gets matched to. This is annoying but it only happens in
3383 : : * corner cases, so for now we live with just reporting the first
3384 : : * match. See also get_eclass_for_sort_expr.)
3385 : : */
3386 : 476935 : setup_eclass_member_iterator(&it, cur_ec, rel->relids);
3387 [ + + ]: 1789854 : while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
3388 : : {
3389 [ + + + + ]: 1414084 : if (bms_equal(cur_em->em_relids, rel->relids) &&
3390 : 476944 : callback(root, rel, cur_ec, cur_em, callback_arg))
3391 : 101156 : break;
3392 : : }
3393 : :
3394 [ + + ]: 476935 : if (!cur_em)
3395 : 375779 : continue;
3396 : :
3397 : : /*
3398 : : * Found our match. Scan the other EC members and attempt to generate
3399 : : * joinclauses. Ignore children here.
3400 : : */
3401 [ + - + + : 309295 : foreach(lc2, cur_ec->ec_members)
+ + ]
3402 : : {
3403 : 208139 : EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
3404 : : Oid eq_op;
3405 : : RestrictInfo *rinfo;
3406 : :
3407 : : /* Child members should not exist in ec_members */
3408 : : Assert(!other_em->em_is_child);
3409 : :
3410 : : /* Make sure it'll be a join to a different rel */
3411 [ + + + + ]: 318314 : if (other_em == cur_em ||
3412 : 110175 : bms_overlap(other_em->em_relids, rel->relids))
3413 : 98049 : continue;
3414 : :
3415 : : /* Forget it if caller doesn't want joins to this rel */
3416 [ + + ]: 110090 : if (bms_overlap(other_em->em_relids, prohibited_rels))
3417 : 130 : continue;
3418 : :
3419 : : /*
3420 : : * Also, if this is a child rel, avoid generating a useless join
3421 : : * to its parent rel(s).
3422 : : */
3423 [ + + + + ]: 117291 : if (is_child_rel &&
3424 : 7331 : bms_overlap(parent_relids, other_em->em_relids))
3425 : 3322 : continue;
3426 : :
3427 : 106638 : eq_op = select_equality_operator(cur_ec,
3428 : : cur_em->em_datatype,
3429 : : other_em->em_datatype);
3430 [ - + ]: 106638 : if (!OidIsValid(eq_op))
3431 : 0 : continue;
3432 : :
3433 : : /* set parent_ec to mark as redundant with other joinclauses */
3434 : 106638 : rinfo = create_join_clause(root, cur_ec, eq_op,
3435 : : cur_em, other_em,
3436 : : cur_ec);
3437 : :
3438 : 106638 : result = lappend(result, rinfo);
3439 : : }
3440 : :
3441 : : /*
3442 : : * If somehow we failed to create any join clauses, we might as well
3443 : : * keep scanning the ECs for another match. But if we did make any,
3444 : : * we're done, because we don't want to return non-redundant clauses.
3445 : : */
3446 [ + + ]: 101156 : if (result)
3447 : 100996 : break;
3448 : : }
3449 : :
3450 : 478527 : return result;
3451 : : }
3452 : :
3453 : : /*
3454 : : * have_relevant_eclass_joinclause
3455 : : * Detect whether there is an EquivalenceClass that could produce
3456 : : * a joinclause involving the two given relations.
3457 : : *
3458 : : * This is essentially a very cut-down version of
3459 : : * generate_join_implied_equalities(). Note it's OK to occasionally say "yes"
3460 : : * incorrectly. Hence we don't bother with details like whether the lack of a
3461 : : * cross-type operator might prevent the clause from actually being generated.
3462 : : * False negatives are not always fatal either: they will discourage, but not
3463 : : * completely prevent, investigation of particular join pathways.
3464 : : */
3465 : : bool
3466 : 159028 : have_relevant_eclass_joinclause(PlannerInfo *root,
3467 : : RelOptInfo *rel1, RelOptInfo *rel2)
3468 : : {
3469 : : Bitmapset *matching_ecs;
3470 : : int i;
3471 : :
3472 : : /*
3473 : : * Examine only eclasses mentioning both rel1 and rel2.
3474 : : *
3475 : : * Note that we do not consider the possibility of an eclass generating
3476 : : * "join" clauses that mention just one of the rels plus an outer join
3477 : : * that could be formed from them. Although such clauses must be
3478 : : * correctly enforced when we form the outer join, they don't seem like
3479 : : * sufficient reason to prioritize this join over other ones. The join
3480 : : * ordering rules will force the join to be made when necessary.
3481 : : */
3482 : 159028 : matching_ecs = get_common_eclass_indexes(root, rel1->relids,
3483 : : rel2->relids);
3484 : :
3485 : 159028 : i = -1;
3486 [ + + ]: 159088 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
3487 : : {
3488 : 136009 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
3489 : : i);
3490 : :
3491 : : /*
3492 : : * Sanity check that get_common_eclass_indexes gave only ECs
3493 : : * containing both rels.
3494 : : */
3495 : : Assert(bms_overlap(rel1->relids, ec->ec_relids));
3496 : : Assert(bms_overlap(rel2->relids, ec->ec_relids));
3497 : :
3498 : : /*
3499 : : * Won't generate joinclauses if single-member (this test covers the
3500 : : * volatile case too)
3501 : : */
3502 [ + + ]: 136009 : if (list_length(ec->ec_members) <= 1)
3503 : 60 : continue;
3504 : :
3505 : : /*
3506 : : * We do not need to examine the individual members of the EC, because
3507 : : * all that we care about is whether each rel overlaps the relids of
3508 : : * at least one member, and get_common_eclass_indexes() and the single
3509 : : * member check above are sufficient to prove that. (As with
3510 : : * have_relevant_joinclause(), it is not necessary that the EC be able
3511 : : * to form a joinclause relating exactly the two given rels, only that
3512 : : * it be able to form a joinclause mentioning both, and this will
3513 : : * surely be true if both of them overlap ec_relids.)
3514 : : *
3515 : : * Note we don't test ec_broken; if we did, we'd need a separate code
3516 : : * path to look through ec_sources. Checking the membership anyway is
3517 : : * OK as a possibly-overoptimistic heuristic.
3518 : : *
3519 : : * We don't test ec_has_const either, even though a const eclass won't
3520 : : * generate real join clauses. This is because if we had "WHERE a.x =
3521 : : * b.y and a.x = 42", it is worth considering a join between a and b,
3522 : : * since the join result is likely to be small even though it'll end
3523 : : * up being an unqualified nestloop.
3524 : : */
3525 : :
3526 : 135949 : return true;
3527 : : }
3528 : :
3529 : 23079 : return false;
3530 : : }
3531 : :
3532 : :
3533 : : /*
3534 : : * has_relevant_eclass_joinclause
3535 : : * Detect whether there is an EquivalenceClass that could produce
3536 : : * a joinclause involving the given relation and anything else.
3537 : : *
3538 : : * This is the same as have_relevant_eclass_joinclause with the other rel
3539 : : * implicitly defined as "everything else in the query".
3540 : : */
3541 : : bool
3542 : 180288 : has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
3543 : : {
3544 : : Bitmapset *matched_ecs;
3545 : : int i;
3546 : :
3547 : : /* Examine only eclasses mentioning rel1 */
3548 : 180288 : matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
3549 : :
3550 : 180288 : i = -1;
3551 [ + + ]: 617811 : while ((i = bms_next_member(matched_ecs, i)) >= 0)
3552 : : {
3553 : 506699 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
3554 : : i);
3555 : :
3556 : : /*
3557 : : * Won't generate joinclauses if single-member (this test covers the
3558 : : * volatile case too)
3559 : : */
3560 [ + + ]: 506699 : if (list_length(ec->ec_members) <= 1)
3561 : 224260 : continue;
3562 : :
3563 : : /*
3564 : : * Per the comment in have_relevant_eclass_joinclause, it's sufficient
3565 : : * to find an EC that mentions both this rel and some other rel.
3566 : : */
3567 [ + + ]: 282439 : if (!bms_is_subset(ec->ec_relids, rel1->relids))
3568 : 69176 : return true;
3569 : : }
3570 : :
3571 : 111112 : return false;
3572 : : }
3573 : :
3574 : :
3575 : : /*
3576 : : * eclass_useful_for_merging
3577 : : * Detect whether the EC could produce any mergejoinable join clauses
3578 : : * against the specified relation.
3579 : : *
3580 : : * This is just a heuristic test and doesn't have to be exact; it's better
3581 : : * to say "yes" incorrectly than "no". Hence we don't bother with details
3582 : : * like whether the lack of a cross-type operator might prevent the clause
3583 : : * from actually being generated.
3584 : : */
3585 : : bool
3586 : 608346 : eclass_useful_for_merging(PlannerInfo *root,
3587 : : EquivalenceClass *eclass,
3588 : : RelOptInfo *rel)
3589 : : {
3590 : : Relids relids;
3591 : : ListCell *lc;
3592 : :
3593 : : Assert(!eclass->ec_merged);
3594 : :
3595 : : /*
3596 : : * Won't generate joinclauses if const or single-member (the latter test
3597 : : * covers the volatile case too)
3598 : : */
3599 [ + + + + ]: 608346 : if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
3600 : 31592 : return false;
3601 : :
3602 : : /*
3603 : : * Note we don't test ec_broken; if we did, we'd need a separate code path
3604 : : * to look through ec_sources. Checking the members anyway is OK as a
3605 : : * possibly-overoptimistic heuristic.
3606 : : */
3607 : :
3608 : : /* If specified rel is a child, we must consider the topmost parent rel */
3609 [ + + + + : 576754 : if (IS_OTHER_REL(rel))
- + ]
3610 : : {
3611 : : Assert(!bms_is_empty(rel->top_parent_relids));
3612 : 14421 : relids = rel->top_parent_relids;
3613 : : }
3614 : : else
3615 : 562333 : relids = rel->relids;
3616 : :
3617 : : /* If rel already includes all members of eclass, no point in searching */
3618 [ + + ]: 576754 : if (bms_is_subset(eclass->ec_relids, relids))
3619 : 205156 : return false;
3620 : :
3621 : : /*
3622 : : * To join, we need a member not in the given rel. Ignore children here.
3623 : : */
3624 [ + - + + : 593672 : foreach(lc, eclass->ec_members)
+ + ]
3625 : : {
3626 : 583446 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
3627 : :
3628 : : /* Child members should not exist in ec_members */
3629 : : Assert(!cur_em->em_is_child);
3630 : :
3631 [ + + ]: 583446 : if (!bms_overlap(cur_em->em_relids, relids))
3632 : 361372 : return true;
3633 : : }
3634 : :
3635 : 10226 : return false;
3636 : : }
3637 : :
3638 : :
3639 : : /*
3640 : : * is_redundant_derived_clause
3641 : : * Test whether rinfo is derived from same EC as any clause in clauselist;
3642 : : * if so, it can be presumed to represent a condition that's redundant
3643 : : * with that member of the list.
3644 : : */
3645 : : bool
3646 : 70 : is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
3647 : : {
3648 : 70 : EquivalenceClass *parent_ec = rinfo->parent_ec;
3649 : : ListCell *lc;
3650 : :
3651 : : /* Fail if it's not a potentially-redundant clause from some EC */
3652 [ + - ]: 70 : if (parent_ec == NULL)
3653 : 70 : return false;
3654 : :
3655 [ # # # # : 0 : foreach(lc, clauselist)
# # ]
3656 : : {
3657 : 0 : RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
3658 : :
3659 [ # # ]: 0 : if (otherrinfo->parent_ec == parent_ec)
3660 : 0 : return true;
3661 : : }
3662 : :
3663 : 0 : return false;
3664 : : }
3665 : :
3666 : : /*
3667 : : * is_redundant_with_indexclauses
3668 : : * Test whether rinfo is redundant with any clause in the IndexClause
3669 : : * list. Here, for convenience, we test both simple identity and
3670 : : * whether it is derived from the same EC as any member of the list.
3671 : : */
3672 : : bool
3673 : 1179226 : is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
3674 : : {
3675 : 1179226 : EquivalenceClass *parent_ec = rinfo->parent_ec;
3676 : : ListCell *lc;
3677 : :
3678 [ + + + + : 1638335 : foreach(lc, indexclauses)
+ + ]
3679 : : {
3680 : 1183034 : IndexClause *iclause = lfirst_node(IndexClause, lc);
3681 : 1183034 : RestrictInfo *otherrinfo = iclause->rinfo;
3682 : :
3683 : : /* If indexclause is lossy, it won't enforce the condition exactly */
3684 [ + + ]: 1183034 : if (iclause->lossy)
3685 : 32504 : continue;
3686 : :
3687 : : /* Match if it's same clause (pointer equality should be enough) */
3688 [ + + ]: 1150530 : if (rinfo == otherrinfo)
3689 : 723925 : return true;
3690 : : /* Match if derived from same EC */
3691 [ + + + + ]: 427089 : if (parent_ec && otherrinfo->parent_ec == parent_ec)
3692 : 484 : return true;
3693 : :
3694 : : /*
3695 : : * No need to look at the derived clauses in iclause->indexquals; they
3696 : : * couldn't match if the parent clause didn't.
3697 : : */
3698 : : }
3699 : :
3700 : 455301 : return false;
3701 : : }
3702 : :
3703 : : /*
3704 : : * get_eclass_indexes_for_relids
3705 : : * Build and return a Bitmapset containing the indexes into root's
3706 : : * eq_classes list for all eclasses that mention any of these relids
3707 : : */
3708 : : static Bitmapset *
3709 : 935938 : get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
3710 : : {
3711 : 935938 : Bitmapset *ec_indexes = NULL;
3712 : 935938 : int i = -1;
3713 : :
3714 : : /* Should be OK to rely on eclass_indexes */
3715 : : Assert(root->ec_merging_done);
3716 : :
3717 [ + + ]: 2940228 : while ((i = bms_next_member(relids, i)) > 0)
3718 : : {
3719 : 2004290 : RelOptInfo *rel = root->simple_rel_array[i];
3720 : :
3721 : : /* ignore the RTE_GROUP RTE */
3722 [ - + ]: 2004290 : if (i == root->group_rtindex)
3723 : 0 : continue;
3724 : :
3725 [ + + ]: 2004290 : if (rel == NULL) /* must be an outer join */
3726 : : {
3727 : : Assert(bms_is_member(i, root->outer_join_rels));
3728 : 256548 : continue;
3729 : : }
3730 : :
3731 : 1747742 : ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
3732 : : }
3733 : 935938 : return ec_indexes;
3734 : : }
3735 : :
3736 : : /*
3737 : : * get_common_eclass_indexes
3738 : : * Build and return a Bitmapset containing the indexes into root's
3739 : : * eq_classes list for all eclasses that mention rels in both
3740 : : * relids1 and relids2.
3741 : : */
3742 : : static Bitmapset *
3743 : 537746 : get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
3744 : : {
3745 : : Bitmapset *rel1ecs;
3746 : : Bitmapset *rel2ecs;
3747 : : int relid;
3748 : :
3749 : 537746 : rel1ecs = get_eclass_indexes_for_relids(root, relids1);
3750 : :
3751 : : /*
3752 : : * We can get away with just using the relation's eclass_indexes directly
3753 : : * when relids2 is a singleton set.
3754 : : */
3755 [ + + ]: 537746 : if (bms_get_singleton_member(relids2, &relid))
3756 : 418258 : rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
3757 : : else
3758 : 119488 : rel2ecs = get_eclass_indexes_for_relids(root, relids2);
3759 : :
3760 : : /* Calculate and return the common EC indexes, recycling the left input. */
3761 : 537746 : return bms_int_members(rel1ecs, rel2ecs);
3762 : : }
3763 : :
3764 : : /*
3765 : : * ec_build_derives_hash
3766 : : * Construct the auxiliary hash table for derived clause lookups.
3767 : : */
3768 : : static void
3769 : 0 : ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec)
3770 : : {
3771 : : Assert(!ec->ec_derives_hash);
3772 : :
3773 : : /*
3774 : : * Create the hash table.
3775 : : *
3776 : : * We pass list_length(ec->ec_derives_list) as the initial size.
3777 : : * Simplehash will divide this by the fillfactor (typically 0.9) and round
3778 : : * up to the next power of two, so this will usually give us at least 64
3779 : : * buckets around the threshold. That avoids immediate resizing without
3780 : : * hardcoding a specific size.
3781 : : */
3782 : 0 : ec->ec_derives_hash = derives_create(root->planner_cxt,
3783 : 0 : list_length(ec->ec_derives_list),
3784 : : NULL);
3785 : :
3786 [ # # # # : 0 : foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
# # ]
3787 : 0 : ec_add_clause_to_derives_hash(ec, rinfo);
3788 : 0 : }
3789 : :
3790 : : /*
3791 : : * ec_add_derived_clause
3792 : : * Add a clause to the set of derived clauses for the given
3793 : : * EquivalenceClass. Always appends to ec_derives_list; also adds
3794 : : * to ec_derives_hash if it exists.
3795 : : *
3796 : : * Also asserts expected invariants of derived clauses.
3797 : : */
3798 : : static void
3799 : 93047 : ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause)
3800 : : {
3801 : : /*
3802 : : * Constant, if present, is always placed on the RHS; see
3803 : : * generate_base_implied_equalities_const(). LHS is never a constant.
3804 : : */
3805 : : Assert(!clause->left_em->em_is_const);
3806 : :
3807 : : /*
3808 : : * Clauses containing a constant are never considered redundant, so
3809 : : * parent_ec is not set.
3810 : : */
3811 : : Assert(!clause->parent_ec || !clause->right_em->em_is_const);
3812 : :
3813 : 93047 : ec->ec_derives_list = lappend(ec->ec_derives_list, clause);
3814 [ - + ]: 93047 : if (ec->ec_derives_hash)
3815 : 0 : ec_add_clause_to_derives_hash(ec, clause);
3816 : 93047 : }
3817 : :
3818 : : /*
3819 : : * ec_add_derived_clauses
3820 : : * Add a list of clauses to the set of clauses derived from the given
3821 : : * EquivalenceClass; adding to the list and hash table if needed.
3822 : : *
3823 : : * This function is similar to ec_add_derived_clause() but optimized for adding
3824 : : * multiple clauses at a time to the ec_derives_list. The assertions from
3825 : : * ec_add_derived_clause() are not repeated here, as the input clauses are
3826 : : * assumed to have already been validated.
3827 : : */
3828 : : static void
3829 : 33 : ec_add_derived_clauses(EquivalenceClass *ec, List *clauses)
3830 : : {
3831 : 33 : ec->ec_derives_list = list_concat(ec->ec_derives_list, clauses);
3832 [ - + ]: 33 : if (ec->ec_derives_hash)
3833 [ # # # # : 0 : foreach_node(RestrictInfo, rinfo, clauses)
# # ]
3834 : 0 : ec_add_clause_to_derives_hash(ec, rinfo);
3835 : 33 : }
3836 : :
3837 : : /*
3838 : : * fill_ec_derives_key
3839 : : * Compute a canonical key for ec_derives_hash lookup or insertion.
3840 : : *
3841 : : * Derived clauses are looked up using a pair of EquivalenceMembers and a
3842 : : * parent EquivalenceClass. To avoid storing or searching for both EM orderings,
3843 : : * we canonicalize the key:
3844 : : *
3845 : : * - For clauses involving two non-constant EMs, em1 is set to the EM with lower
3846 : : * memory address and em2 is set to the other one.
3847 : : * - For clauses involving a constant EM, the caller must pass the non-constant
3848 : : * EM as leftem and NULL as rightem; we then set em1 = NULL and em2 = leftem.
3849 : : */
3850 : : static inline void
3851 : 0 : fill_ec_derives_key(ECDerivesKey *key,
3852 : : EquivalenceMember *leftem,
3853 : : EquivalenceMember *rightem,
3854 : : EquivalenceClass *parent_ec)
3855 : : {
3856 : : Assert(leftem); /* Always required for lookup or insertion */
3857 : :
3858 [ # # ]: 0 : if (rightem == NULL)
3859 : : {
3860 : 0 : key->em1 = NULL;
3861 : 0 : key->em2 = leftem;
3862 : : }
3863 [ # # ]: 0 : else if (leftem < rightem)
3864 : : {
3865 : 0 : key->em1 = leftem;
3866 : 0 : key->em2 = rightem;
3867 : : }
3868 : : else
3869 : : {
3870 : 0 : key->em1 = rightem;
3871 : 0 : key->em2 = leftem;
3872 : : }
3873 : 0 : key->parent_ec = parent_ec;
3874 : 0 : }
3875 : :
3876 : : /*
3877 : : * ec_add_clause_to_derives_hash
3878 : : * Add a derived clause to ec_derives_hash in the given EquivalenceClass.
3879 : : *
3880 : : * Each clause is associated with a canonicalized key. For constant-containing
3881 : : * clauses, only the non-constant EM is used for lookup; see comments in
3882 : : * fill_ec_derives_key().
3883 : : */
3884 : : static void
3885 : 0 : ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo)
3886 : : {
3887 : : ECDerivesKey key;
3888 : : ECDerivesEntry *entry;
3889 : : bool found;
3890 : :
3891 : : /*
3892 : : * Constants are always placed on the RHS; see
3893 : : * generate_base_implied_equalities_const().
3894 : : */
3895 : : Assert(!rinfo->left_em->em_is_const);
3896 : :
3897 : : /*
3898 : : * Clauses containing a constant are never considered redundant, so
3899 : : * parent_ec is not set.
3900 : : */
3901 : : Assert(!rinfo->parent_ec || !rinfo->right_em->em_is_const);
3902 : :
3903 : : /*
3904 : : * See fill_ec_derives_key() for details: we use a canonicalized key to
3905 : : * avoid storing both EM orderings. For constant EMs, only the
3906 : : * non-constant EM is included in the key.
3907 : : */
3908 : 0 : fill_ec_derives_key(&key,
3909 : : rinfo->left_em,
3910 [ # # ]: 0 : rinfo->right_em->em_is_const ? NULL : rinfo->right_em,
3911 : : rinfo->parent_ec);
3912 : 0 : entry = derives_insert(ec->ec_derives_hash, key, &found);
3913 : : Assert(!found);
3914 : 0 : entry->rinfo = rinfo;
3915 : 0 : }
3916 : :
3917 : : /*
3918 : : * ec_clear_derived_clauses
3919 : : * Reset ec_derives_list and ec_derives_hash.
3920 : : *
3921 : : * We destroy the hash table explicitly, since it may consume significant
3922 : : * space. The list holds the same set of entries and can become equally large
3923 : : * when thousands of partitions are involved, so we free it as well -- even
3924 : : * though we do not typically free lists.
3925 : : */
3926 : : static void
3927 : 33 : ec_clear_derived_clauses(EquivalenceClass *ec)
3928 : : {
3929 : 33 : list_free(ec->ec_derives_list);
3930 : 33 : ec->ec_derives_list = NIL;
3931 : :
3932 [ - + ]: 33 : if (ec->ec_derives_hash)
3933 : : {
3934 : 0 : derives_destroy(ec->ec_derives_hash);
3935 : 0 : ec->ec_derives_hash = NULL;
3936 : : }
3937 : 33 : }
3938 : :
3939 : : /*
3940 : : * ec_search_clause_for_ems
3941 : : * Search for an existing RestrictInfo that equates the given pair
3942 : : * of EquivalenceMembers, either from ec_sources or ec_derives.
3943 : : *
3944 : : * Returns a clause with matching operands in either given order or commuted
3945 : : * order. We used to require matching operator OIDs, but dropped that since any
3946 : : * semantically different operator here would indicate a broken operator family.
3947 : : *
3948 : : * Returns NULL if no matching clause is found.
3949 : : */
3950 : : static RestrictInfo *
3951 : 479044 : ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
3952 : : EquivalenceMember *leftem, EquivalenceMember *rightem,
3953 : : EquivalenceClass *parent_ec)
3954 : : {
3955 : : /* Check original source clauses */
3956 [ + - + + : 1381134 : foreach_node(RestrictInfo, rinfo, ec->ec_sources)
+ + ]
3957 : : {
3958 [ + + ]: 554542 : if (rinfo->left_em == leftem &&
3959 [ + + ]: 273795 : rinfo->right_em == rightem &&
3960 [ + + ]: 245424 : rinfo->parent_ec == parent_ec)
3961 : 65748 : return rinfo;
3962 [ + + ]: 510110 : if (rinfo->left_em == rightem &&
3963 [ + + ]: 223548 : rinfo->right_em == leftem &&
3964 [ + + ]: 203588 : rinfo->parent_ec == parent_ec)
3965 : 21316 : return rinfo;
3966 : : }
3967 : :
3968 : : /* Not found in ec_sources; search derived clauses */
3969 : 413296 : return ec_search_derived_clause_for_ems(root, ec, leftem, rightem,
3970 : : parent_ec);
3971 : : }
3972 : :
3973 : : /*
3974 : : * ec_search_derived_clause_for_ems
3975 : : * Search for an existing derived clause between two EquivalenceMembers.
3976 : : *
3977 : : * If the number of derived clauses exceeds a threshold, switch to hash table
3978 : : * lookup; otherwise, scan ec_derives_list linearly.
3979 : : *
3980 : : * Clauses involving constants are looked up by passing the non-constant EM
3981 : : * as leftem and setting rightem to NULL. In that case, we expect to find a
3982 : : * clause with a constant on the RHS.
3983 : : *
3984 : : * While searching the list, we compare each given EM with both sides of each
3985 : : * clause. But for hash table lookups, we construct a canonicalized key and
3986 : : * perform a single lookup.
3987 : : */
3988 : : static RestrictInfo *
3989 : 413301 : ec_search_derived_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
3990 : : EquivalenceMember *leftem,
3991 : : EquivalenceMember *rightem,
3992 : : EquivalenceClass *parent_ec)
3993 : : {
3994 : : /* Switch to using hash lookup when list grows "too long". */
3995 [ + - - + ]: 826602 : if (!ec->ec_derives_hash &&
3996 : 413301 : list_length(ec->ec_derives_list) >= EC_DERIVES_HASH_THRESHOLD)
3997 : 0 : ec_build_derives_hash(root, ec);
3998 : :
3999 : : /* Perform hash table lookup if available */
4000 [ - + ]: 413301 : if (ec->ec_derives_hash)
4001 : : {
4002 : : ECDerivesKey key;
4003 : : RestrictInfo *rinfo;
4004 : : ECDerivesEntry *entry;
4005 : :
4006 : 0 : fill_ec_derives_key(&key, leftem, rightem, parent_ec);
4007 : 0 : entry = derives_lookup(ec->ec_derives_hash, key);
4008 [ # # ]: 0 : if (entry)
4009 : : {
4010 : 0 : rinfo = entry->rinfo;
4011 : : Assert(rinfo);
4012 : : Assert(rightem || rinfo->right_em->em_is_const);
4013 : 0 : return rinfo;
4014 : : }
4015 : : }
4016 : : else
4017 : : {
4018 : : /* Fallback to linear search over ec_derives_list */
4019 [ + + + + : 664760 : foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
+ + ]
4020 : : {
4021 : : /* Handle special case: lookup by non-const EM alone */
4022 [ + + ]: 523400 : if (!rightem &&
4023 [ + - ]: 5 : rinfo->left_em == leftem)
4024 : : {
4025 : : Assert(rinfo->right_em->em_is_const);
4026 : 342621 : return rinfo;
4027 : : }
4028 [ + + ]: 523395 : if (rinfo->left_em == leftem &&
4029 [ + + ]: 184357 : rinfo->right_em == rightem &&
4030 [ + + ]: 165185 : rinfo->parent_ec == parent_ec)
4031 : 165175 : return rinfo;
4032 [ + + ]: 358220 : if (rinfo->left_em == rightem &&
4033 [ + + ]: 188742 : rinfo->right_em == leftem &&
4034 [ + - ]: 177441 : rinfo->parent_ec == parent_ec)
4035 : 177441 : return rinfo;
4036 : : }
4037 : : }
4038 : :
4039 : 70680 : return NULL;
4040 : : }
|