Age Owner Branch data TLA 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
3315 tgl@sss.pgh.pa.us 180 :CBC 241721 : process_equivalence(PlannerInfo *root,
181 : : RestrictInfo **p_restrictinfo,
182 : : JoinDomain *jdomain)
183 : : {
184 : 241721 : RestrictInfo *restrictinfo = *p_restrictinfo;
7229 185 : 241721 : 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 */
5851 203 [ - + ]: 241721 : Assert(restrictinfo->left_ec == NULL);
204 [ - + ]: 241721 : Assert(restrictinfo->right_ec == NULL);
205 : :
206 : : /* Reject if it is potentially postponable by security considerations */
3578 207 [ + + + + ]: 241721 : if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
208 : 172 : return false;
209 : :
210 : : /* Extract info from given clause */
7229 211 [ - + ]: 241549 : Assert(is_opclause(clause));
212 : 241549 : opno = ((OpExpr *) clause)->opno;
5710 213 : 241549 : collation = ((OpExpr *) clause)->inputcollid;
7229 214 : 241549 : item1 = (Expr *) get_leftop(clause);
215 : 241549 : item2 = (Expr *) get_rightop(clause);
216 : 241549 : item1_relids = restrictinfo->left_relids;
217 : 241549 : 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 : : */
5710 223 : 241549 : item1 = canonicalize_ec_expression(item1,
224 : : exprType((Node *) item1),
225 : : collation);
226 : 241549 : 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 : : */
6246 236 [ + + ]: 241549 : 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 : : */
3315 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 =
2114 259 : 45 : make_restrictinfo(root,
260 : : (Expr *) ntest,
3315 261 : 45 : restrictinfo->is_pushed_down,
1260 262 : 45 : restrictinfo->has_clone,
263 : 45 : restrictinfo->is_clone,
3315 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 : : */
7229 281 : 241504 : op_input_types(opno, &item1_type, &item2_type);
282 : :
283 : 241504 : 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 : 241504 : ec1 = ec2 = NULL;
7227 304 : 241504 : em1 = em2 = NULL;
2205 drowley@postgresql.o 305 : 241504 : ec2_idx = -1;
7229 tgl@sss.pgh.pa.us 306 [ + + + + : 416042 : foreach(lc1, root->eq_classes)
+ + ]
307 : : {
308 : 174616 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
309 : : ListCell *lc2;
310 : :
311 : : /* Never match to a volatile EC */
312 [ - + ]: 174616 : if (cur_ec->ec_has_volatile)
7229 tgl@sss.pgh.pa.us 313 :UBC 0 : continue;
314 : :
315 : : /*
316 : : * The collation has to match; check this first since it's cheaper
317 : : * than the opfamily comparison.
318 : : */
5710 tgl@sss.pgh.pa.us 319 [ + + ]:CBC 174616 : if (collation != cur_ec->ec_collation)
320 : 17708 : 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 : : */
7229 327 [ + + ]: 156908 : if (!equal(opfamilies, cur_ec->ec_opfamilies))
328 : 42620 : continue;
329 : :
330 : : /* We don't expect any children yet */
576 drowley@postgresql.o 331 [ - + ]: 114288 : Assert(cur_ec->ec_childmembers == NULL);
332 : :
7229 tgl@sss.pgh.pa.us 333 [ + - + + : 339847 : foreach(lc2, cur_ec->ec_members)
+ + ]
334 : : {
335 : 225637 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
336 : :
337 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 338 [ - + ]: 225637 : Assert(!cur_em->em_is_child);
339 : :
340 : : /*
341 : : * Match constants only within the same JoinDomain (see
342 : : * optimizer/README).
343 : : */
1375 tgl@sss.pgh.pa.us 344 [ + + + + ]: 225637 : if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
7229 345 : 3144 : continue;
346 : :
347 [ + + ]: 222493 : if (!ec1 &&
348 [ + + + + ]: 428456 : item1_type == cur_em->em_datatype &&
349 : 214060 : equal(item1, cur_em->em_expr))
350 : : {
351 : 12927 : ec1 = cur_ec;
7227 352 : 12927 : em1 = cur_em;
7229 353 [ + + ]: 12927 : if (ec2)
354 : 60 : break;
355 : : }
356 : :
357 [ + + ]: 222433 : if (!ec2 &&
358 [ + + + + ]: 440259 : item2_type == cur_em->em_datatype &&
359 : 219809 : equal(item2, cur_em->em_expr))
360 : : {
361 : 2988 : ec2 = cur_ec;
2205 drowley@postgresql.o 362 : 2988 : ec2_idx = foreach_current_index(lc1);
7227 tgl@sss.pgh.pa.us 363 : 2988 : em2 = cur_em;
7229 364 [ + + ]: 2988 : if (ec1)
365 : 18 : break;
366 : : }
367 : : }
368 : :
369 [ + + + + ]: 114288 : if (ec1 && ec2)
370 : 78 : break;
371 : : }
372 : :
373 : : /* Sweep finished, what did we find? */
374 : :
375 [ + + + + ]: 241504 : 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);
3578 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 */
5851 386 : 45 : restrictinfo->left_ec = ec1;
387 : 45 : restrictinfo->right_ec = ec1;
388 : : /* mark the RI as usable with this pair of EMs */
7227 389 : 45 : restrictinfo->left_em = em1;
390 : 45 : restrictinfo->right_em = em2;
7229 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 : : */
2664 drowley@postgresql.o 400 [ - + ]: 33 : if (root->ec_merging_done)
4938 tgl@sss.pgh.pa.us 401 [ # # ]:UBC 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 : : */
7229 tgl@sss.pgh.pa.us 410 :CBC 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 : : */
580 amitlan@postgresql.o 417 : 33 : ec_add_derived_clauses(ec1, ec2->ec_derives_list);
7229 tgl@sss.pgh.pa.us 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 */
3578 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);
7229 425 : 33 : ec2->ec_merged = ec1;
2205 drowley@postgresql.o 426 : 33 : root->eq_classes = list_delete_nth_cell(root->eq_classes, ec2_idx);
427 : : /* just to avoid debugging confusion w/ dangling pointers: */
7229 tgl@sss.pgh.pa.us 428 : 33 : ec2->ec_members = NIL;
429 : 33 : ec2->ec_sources = NIL;
580 amitlan@postgresql.o 430 : 33 : ec_clear_derived_clauses(ec2);
7229 tgl@sss.pgh.pa.us 431 : 33 : ec2->ec_relids = NULL;
432 : 33 : ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
3578 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 */
5851 438 : 33 : restrictinfo->left_ec = ec1;
439 : 33 : restrictinfo->right_ec = ec1;
440 : : /* mark the RI as usable with this pair of EMs */
7227 441 : 33 : restrictinfo->left_em = em1;
442 : 33 : restrictinfo->right_em = em2;
443 : : }
7229 444 [ + + ]: 241426 : else if (ec1)
445 : : {
446 : : /* Case 3: add item2 to ec1 */
1375 447 : 12849 : em2 = add_eq_member(ec1, item2, item2_relids,
448 : : jdomain, item2_type);
7229 449 : 12849 : ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
3578 450 : 12849 : ec1->ec_min_security = Min(ec1->ec_min_security,
451 : : restrictinfo->security_level);
452 : 12849 : ec1->ec_max_security = Max(ec1->ec_max_security,
453 : : restrictinfo->security_level);
454 : : /* mark the RI as associated with this eclass */
5851 455 : 12849 : restrictinfo->left_ec = ec1;
456 : 12849 : restrictinfo->right_ec = ec1;
457 : : /* mark the RI as usable with this pair of EMs */
7227 458 : 12849 : restrictinfo->left_em = em1;
459 : 12849 : restrictinfo->right_em = em2;
460 : : }
7229 461 [ + + ]: 228577 : else if (ec2)
462 : : {
463 : : /* Case 3: add item1 to ec2 */
1375 464 : 2910 : em1 = add_eq_member(ec2, item1, item1_relids,
465 : : jdomain, item1_type);
7229 466 : 2910 : ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
3578 467 : 2910 : ec2->ec_min_security = Min(ec2->ec_min_security,
468 : : restrictinfo->security_level);
469 : 2910 : ec2->ec_max_security = Max(ec2->ec_max_security,
470 : : restrictinfo->security_level);
471 : : /* mark the RI as associated with this eclass */
5851 472 : 2910 : restrictinfo->left_ec = ec2;
473 : 2910 : restrictinfo->right_ec = ec2;
474 : : /* mark the RI as usable with this pair of EMs */
7227 475 : 2910 : restrictinfo->left_em = em1;
476 : 2910 : restrictinfo->right_em = em2;
477 : : }
478 : : else
479 : : {
480 : : /* Case 4: make a new, two-entry EC */
7229 481 : 225667 : EquivalenceClass *ec = makeNode(EquivalenceClass);
482 : :
483 : 225667 : ec->ec_opfamilies = opfamilies;
5710 484 : 225667 : ec->ec_collation = collation;
576 drowley@postgresql.o 485 : 225667 : ec->ec_childmembers_size = 0;
7229 tgl@sss.pgh.pa.us 486 : 225667 : ec->ec_members = NIL;
576 drowley@postgresql.o 487 : 225667 : ec->ec_childmembers = NULL;
7229 tgl@sss.pgh.pa.us 488 : 225667 : ec->ec_sources = list_make1(restrictinfo);
580 amitlan@postgresql.o 489 : 225667 : ec->ec_derives_list = NIL;
490 : 225667 : ec->ec_derives_hash = NULL;
7229 tgl@sss.pgh.pa.us 491 : 225667 : ec->ec_relids = NULL;
492 : 225667 : ec->ec_has_const = false;
493 : 225667 : ec->ec_has_volatile = false;
494 : 225667 : ec->ec_broken = false;
6937 495 : 225667 : ec->ec_sortref = 0;
3578 496 : 225667 : ec->ec_min_security = restrictinfo->security_level;
497 : 225667 : ec->ec_max_security = restrictinfo->security_level;
7229 498 : 225667 : ec->ec_merged = NULL;
1375 499 : 225667 : em1 = add_eq_member(ec, item1, item1_relids,
500 : : jdomain, item1_type);
501 : 225667 : em2 = add_eq_member(ec, item2, item2_relids,
502 : : jdomain, item2_type);
503 : :
7229 504 : 225667 : root->eq_classes = lappend(root->eq_classes, ec);
505 : :
506 : : /* mark the RI as associated with this eclass */
5851 507 : 225667 : restrictinfo->left_ec = ec;
508 : 225667 : restrictinfo->right_ec = ec;
509 : : /* mark the RI as usable with this pair of EMs */
7227 510 : 225667 : restrictinfo->left_em = em1;
511 : 225667 : restrictinfo->right_em = em2;
512 : : }
513 : :
7229 514 : 241459 : 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 *
5710 546 : 2685172 : canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
547 : : {
548 : 2685172 : 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 : : */
3095 554 [ + - + + : 2685172 : if (IsPolymorphicType(req_type) || req_type == RECORDOID)
+ - + + +
+ + + + -
+ - + - +
- + - +
+ ]
5710 555 : 9674 : req_type = expr_type;
556 : :
557 : : /*
558 : : * No work if the expression exposes the right type/collation already.
559 : : */
560 [ + + + + ]: 5289027 : if (expr_type != req_type ||
561 : 2603855 : 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 : :
2269 570 [ + + ]: 83575 : if (expr_type != req_type)
571 : 81317 : req_typmod = -1;
572 : : else
573 : 2258 : 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 : 83575 : expr = (Expr *) applyRelabelType((Node *) expr,
580 : : req_type, req_typmod, req_collation,
581 : : COERCE_IMPLICIT_CAST, -1, false);
582 : : }
583 : :
5710 584 : 2685172 : 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 *
576 drowley@postgresql.o 593 : 776648 : make_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
594 : : JoinDomain *jdomain, EquivalenceMember *parent, Oid datatype)
595 : : {
7229 tgl@sss.pgh.pa.us 596 : 776648 : EquivalenceMember *em = makeNode(EquivalenceMember);
597 : :
598 : 776648 : em->em_expr = expr;
599 : 776648 : em->em_relids = relids;
600 : 776648 : em->em_is_const = false;
1375 601 : 776648 : em->em_is_child = (parent != NULL);
7229 602 : 776648 : em->em_datatype = datatype;
1375 603 : 776648 : em->em_jdomain = jdomain;
604 : 776648 : em->em_parent = parent;
605 : :
7229 606 [ + + ]: 776648 : 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 : : */
1375 616 [ - + ]: 172054 : Assert(!parent);
7229 617 : 172054 : em->em_is_const = true;
618 : 172054 : ec->ec_has_const = true;
619 : : /* it can't affect ec_relids */
620 : : }
621 : :
576 drowley@postgresql.o 622 : 776648 : 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 : 688974 : add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids,
630 : : JoinDomain *jdomain, Oid datatype)
631 : : {
632 : 688974 : EquivalenceMember *em = make_eq_member(ec, expr, relids, jdomain,
633 : : NULL, datatype);
634 : :
635 : : /* add to the members list */
636 : 688974 : ec->ec_members = lappend(ec->ec_members, em);
637 : :
638 : : /* record the relids for parent members */
639 : 688974 : ec->ec_relids = bms_add_members(ec->ec_relids, relids);
640 : :
641 : 688974 : 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 : 87674 : 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 [ - + ]: 87674 : 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 [ + + ]: 87674 : if (unlikely(ec->ec_childmembers_size < root->simple_rel_array_size))
676 : : {
677 [ + - ]: 23915 : if (ec->ec_childmembers == NULL)
678 : 23915 : ec->ec_childmembers = palloc0_array(List *, root->simple_rel_array_size);
679 : : else
576 drowley@postgresql.o 680 :UBC 0 : ec->ec_childmembers = repalloc0_array(ec->ec_childmembers, List *,
681 : : ec->ec_childmembers_size,
682 : : root->simple_rel_array_size);
683 : :
576 drowley@postgresql.o 684 :CBC 23915 : ec->ec_childmembers_size = root->simple_rel_array_size;
685 : : }
686 : :
687 : 87674 : 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 : 87674 : ec->ec_childmembers[child_relid] = lappend(ec->ec_childmembers[child_relid], em);
691 : :
692 : : /* Record this EC index for the child rel */
693 [ + + ]: 87674 : if (ec_index >= 0)
694 : : {
695 : 50039 : RelOptInfo *child_rel = root->simple_rel_array[child_relid];
696 : :
697 : 50039 : child_rel->eclass_indexes =
698 : 50039 : bms_add_member(child_rel->eclass_indexes, ec_index);
699 : : }
700 : :
7227 tgl@sss.pgh.pa.us 701 : 87674 : 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 *
7229 737 : 1749000 : 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 : : */
5710 756 : 1749000 : 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 : : */
1375 762 : 1749000 : jdomain = linitial_node(JoinDomain, root->join_domains);
763 : :
764 : : /*
765 : : * Scan through the existing EquivalenceClasses for a match
766 : : */
7229 767 [ + + + + : 5810871 : foreach(lc1, root->eq_classes)
+ + ]
768 : : {
769 : 5076178 : 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 : : */
6263 777 [ + + + + ]: 5076178 : if (cur_ec->ec_has_volatile &&
778 [ + + ]: 28 : (sortref == 0 || sortref != cur_ec->ec_sortref))
6937 779 : 2185082 : continue;
780 : :
5710 781 [ + + ]: 5075668 : if (collation != cur_ec->ec_collation)
782 : 1418797 : continue;
7229 783 [ + + ]: 3656871 : if (!equal(opfamilies, cur_ec->ec_opfamilies))
784 : 765775 : continue;
785 : :
58 peter@eisentraut.org 786 :GNC 2891096 : setup_eclass_member_iterator(&it, cur_ec, relids);
576 drowley@postgresql.o 787 [ + + ]:CBC 6422348 : while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
788 : : {
789 : : /*
790 : : * Ignore child members unless they match the request.
791 : : */
5347 tgl@sss.pgh.pa.us 792 [ + + ]: 4545559 : if (cur_em->em_is_child &&
58 peter@eisentraut.org 793 [ - + ]:GNC 91163 : !bms_equal(cur_em->em_relids, relids))
5347 tgl@sss.pgh.pa.us 794 :UBC 0 : continue;
795 : :
796 : : /*
797 : : * Match constants only within the same JoinDomain (see
798 : : * optimizer/README).
799 : : */
1375 tgl@sss.pgh.pa.us 800 [ + + + + ]:CBC 4545559 : if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
7229 801 : 57552 : continue;
802 : :
5710 803 [ + + + + ]: 8940274 : if (opcintype == cur_em->em_datatype &&
7229 804 : 4452267 : equal(expr, cur_em->em_expr))
882 akorotkov@postgresql 805 : 1014307 : return cur_ec; /* Match! */
806 : : }
807 : : }
808 : :
809 : : /* No match; does caller want a NULL result? */
5851 tgl@sss.pgh.pa.us 810 [ + + ]: 734693 : if (!create_it)
811 : 512812 : 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 : : */
7229 818 : 221881 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
819 : :
820 : 221881 : newec = makeNode(EquivalenceClass);
821 : 221881 : newec->ec_opfamilies = list_copy(opfamilies);
5710 822 : 221881 : newec->ec_collation = collation;
576 drowley@postgresql.o 823 : 221881 : newec->ec_childmembers_size = 0;
7229 tgl@sss.pgh.pa.us 824 : 221881 : newec->ec_members = NIL;
576 drowley@postgresql.o 825 : 221881 : newec->ec_childmembers = NULL;
7229 tgl@sss.pgh.pa.us 826 : 221881 : newec->ec_sources = NIL;
580 amitlan@postgresql.o 827 : 221881 : newec->ec_derives_list = NIL;
828 : 221881 : newec->ec_derives_hash = NULL;
7229 tgl@sss.pgh.pa.us 829 : 221881 : newec->ec_relids = NULL;
830 : 221881 : newec->ec_has_const = false;
831 : 221881 : newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
832 : 221881 : newec->ec_broken = false;
6937 833 : 221881 : newec->ec_sortref = sortref;
3578 834 : 221881 : newec->ec_min_security = UINT_MAX;
835 : 221881 : newec->ec_max_security = 0;
7229 836 : 221881 : newec->ec_merged = NULL;
837 : :
6096 bruce@momjian.us 838 [ + + - + ]: 221881 : if (newec->ec_has_volatile && sortref == 0) /* should not happen */
6263 tgl@sss.pgh.pa.us 839 [ # # ]:UBC 0 : elog(ERROR, "volatile EquivalenceClass has no sortref");
840 : :
841 : : /*
842 : : * Get the precise set of relids appearing in the expression.
843 : : */
2114 tgl@sss.pgh.pa.us 844 :CBC 221881 : expr_relids = pull_varnos(root, (Node *) expr);
845 : :
4738 846 : 221881 : 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 : : */
7229 855 [ + + ]: 221881 : if (newec->ec_has_const)
856 : : {
7061 857 [ + + + + ]: 15448 : if (newec->ec_has_volatile ||
858 [ + + ]: 15224 : expression_returns_set((Node *) expr) ||
6521 859 [ + + ]: 14953 : contain_agg_clause((Node *) expr) ||
860 : 7401 : contain_window_function((Node *) expr))
861 : : {
7229 862 : 380 : newec->ec_has_const = false;
7227 863 : 380 : newem->em_is_const = false;
864 : : }
865 : : }
866 : :
7229 867 : 221881 : 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 : : */
2664 drowley@postgresql.o 873 [ + + ]: 221881 : if (root->ec_merging_done)
874 : : {
875 : 127667 : int ec_index = list_length(root->eq_classes) - 1;
876 : 127667 : int i = -1;
877 : :
878 [ + + ]: 245518 : while ((i = bms_next_member(newec->ec_relids, i)) > 0)
879 : : {
880 : 117851 : RelOptInfo *rel = root->simple_rel_array[i];
881 : :
882 : : /* ignore the RTE_GROUP RTE */
786 rguo@postgresql.org 883 [ + + ]: 117851 : if (i == root->group_rtindex)
884 : 584 : continue;
885 : :
1375 tgl@sss.pgh.pa.us 886 [ + + ]: 117267 : if (rel == NULL) /* must be an outer join */
887 : : {
888 [ - + ]: 5351 : Assert(bms_is_member(i, root->outer_join_rels));
889 : 5351 : continue;
890 : : }
891 : :
1361 892 [ - + ]: 111916 : Assert(rel->reloptkind == RELOPT_BASEREL);
893 : :
2664 drowley@postgresql.o 894 : 111916 : rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
895 : : ec_index);
896 : : }
897 : : }
898 : :
7229 tgl@sss.pgh.pa.us 899 : 221881 : MemoryContextSwitchTo(oldcontext);
900 : :
901 : 221881 : 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 *
2025 917 : 265836 : 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 [ + - + + ]: 286710 : while (expr && IsA(expr, RelabelType))
926 : 20874 : expr = ((RelabelType *) expr)->arg;
927 : :
576 drowley@postgresql.o 928 : 265836 : setup_eclass_member_iterator(&it, ec, relids);
929 [ + + ]: 447349 : 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 : : */
2025 tgl@sss.pgh.pa.us 937 [ - + ]: 297957 : if (em->em_is_const)
2025 tgl@sss.pgh.pa.us 938 :UBC 0 : continue;
939 : :
940 : : /*
941 : : * Ignore child members unless they belong to the requested rel.
942 : : */
2025 tgl@sss.pgh.pa.us 943 [ + + ]:CBC 297957 : if (em->em_is_child &&
944 [ + + ]: 9738 : !bms_is_subset(em->em_relids, relids))
945 : 2866 : continue;
946 : :
947 : : /*
948 : : * Match if same expression (after stripping relabel).
949 : : */
950 : 295091 : emexpr = em->em_expr;
951 [ + - + + ]: 305647 : while (emexpr && IsA(emexpr, RelabelType))
952 : 10556 : emexpr = ((RelabelType *) emexpr)->arg;
953 : :
954 [ + + ]: 295091 : if (equal(emexpr, expr))
955 : 116444 : return em;
956 : : }
957 : :
958 : 149392 : return NULL;
959 : : }
960 : :
961 : : /*
962 : : * find_computable_ec_member
963 : : * Locate an EquivalenceClass member that can be computed from the
964 : : * expressions appearing in "exprs"; return NULL if no match.
965 : : *
966 : : * "exprs" can be either a list of bare expression trees, or a list of
967 : : * TargetEntry nodes. Typically it will contain Vars and possibly Aggrefs
968 : : * and WindowFuncs; however, when considering an appendrel member the list
969 : : * could contain arbitrary expressions. We consider an EC member to be
970 : : * computable if all the Vars, PlaceHolderVars, Aggrefs, and WindowFuncs
971 : : * it needs are present in "exprs".
972 : : *
973 : : * There is some subtlety in that definition: for example, if an EC member is
974 : : * Var_A + 1 while what is in "exprs" is Var_A + 2, it's still computable.
975 : : * This works because in the final plan tree, the EC member's expression will
976 : : * be computed as part of the same plan node targetlist that is currently
977 : : * represented by "exprs". So if we have Var_A available for the existing
978 : : * tlist member, it must be OK to use it in the EC expression too.
979 : : *
980 : : * Unlike find_ec_member_matching_expr, there's no special provision here
981 : : * for binary-compatible relabeling. This is intentional: if we have to
982 : : * compute an expression in this way, setrefs.c is going to insist on exact
983 : : * matches of Vars to the source tlist.
984 : : *
985 : : * If 'relids' is given, EC members are ignored unless they belong to it. If
986 : : * 'relids' is NULL, all child members are ignored.
987 : : * Also, non-parallel-safe expressions are ignored if 'require_parallel_safe'.
988 : : *
989 : : * Note: some callers pass root == NULL for notational reasons. This is OK
990 : : * when require_parallel_safe is false.
991 : : */
992 : : EquivalenceMember *
993 : 5853 : find_computable_ec_member(PlannerInfo *root,
994 : : EquivalenceClass *ec,
995 : : List *exprs,
996 : : Relids relids,
997 : : bool require_parallel_safe)
998 : : {
999 : : List *exprvars;
1000 : : EquivalenceMemberIterator it;
1001 : : EquivalenceMember *em;
1002 : :
1003 : : /*
1004 : : * Pull out the Vars and quasi-Vars present in "exprs". In the typical
1005 : : * non-appendrel case, this is just another representation of the same
1006 : : * list. However, it does remove the distinction between the case of a
1007 : : * list of plain expressions and a list of TargetEntrys.
1008 : : */
754 1009 : 5853 : exprvars = pull_var_clause((Node *) exprs,
1010 : : PVC_INCLUDE_AGGREGATES |
1011 : : PVC_INCLUDE_WINDOWFUNCS |
1012 : : PVC_INCLUDE_PLACEHOLDERS);
1013 : :
576 drowley@postgresql.o 1014 : 5853 : setup_eclass_member_iterator(&it, ec, relids);
1015 [ + + ]: 11803 : while ((em = eclass_member_iterator_next(&it)) != NULL)
1016 : : {
1017 : : List *emvars;
1018 : : ListCell *lc2;
1019 : :
1020 : : /*
1021 : : * We shouldn't be trying to sort by an equivalence class that
1022 : : * contains a constant, so no need to consider such cases any further.
1023 : : */
2025 tgl@sss.pgh.pa.us 1024 [ - + ]: 6398 : if (em->em_is_const)
2025 tgl@sss.pgh.pa.us 1025 :UBC 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 : : */
15 rguo@postgresql.org 1034 [ + + + + ]:CBC 6398 : if ((em->em_is_child || relids != NULL) &&
2025 tgl@sss.pgh.pa.us 1035 [ + + ]: 6344 : !bms_is_subset(em->em_relids, relids))
1036 : 5774 : continue;
1037 : :
1038 : : /*
1039 : : * Match if all Vars and quasi-Vars are present in "exprs".
1040 : : */
754 1041 : 624 : emvars = pull_var_clause((Node *) em->em_expr,
1042 : : PVC_INCLUDE_AGGREGATES |
1043 : : PVC_INCLUDE_WINDOWFUNCS |
1044 : : PVC_INCLUDE_PLACEHOLDERS);
1045 [ + + + + : 1342 : foreach(lc2, emvars)
+ + ]
1046 : : {
1047 [ + + ]: 858 : if (!list_member(exprvars, lfirst(lc2)))
2025 1048 : 140 : break;
1049 : : }
754 1050 : 624 : list_free(emvars);
2025 1051 [ + + ]: 624 : if (lc2)
1052 : 140 : continue; /* we hit a non-available Var */
1053 : :
1054 : : /*
1055 : : * If requested, reject expressions that are not parallel-safe. We
1056 : : * check this last because it's a rather expensive test.
1057 : : */
1058 [ + + ]: 484 : if (require_parallel_safe &&
1059 [ + + ]: 115 : !is_parallel_safe(root, (Node *) em->em_expr))
1060 : 36 : continue;
1061 : :
1062 : 448 : return em; /* found usable expression */
1063 : : }
1064 : :
1065 : 5405 : return NULL;
1066 : : }
1067 : :
1068 : : /*
1069 : : * relation_can_be_sorted_early
1070 : : * Can this relation be sorted on this EC before the final output step?
1071 : : *
1072 : : * To succeed, we must find an EC member that prepare_sort_from_pathkeys knows
1073 : : * how to sort on, given the rel's reltarget as input. There are also a few
1074 : : * additional constraints based on the fact that the desired sort will be done
1075 : : * "early", within the scan/join part of the plan. Also, non-parallel-safe
1076 : : * expressions are ignored if 'require_parallel_safe'.
1077 : : *
1078 : : * At some point we might want to return the identified EquivalenceMember,
1079 : : * but for now, callers only want to know if there is one.
1080 : : */
1081 : : bool
1082 : 16244 : relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel,
1083 : : EquivalenceClass *ec, bool require_parallel_safe)
1084 : : {
1085 : 16244 : 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 [ + + ]: 16244 : if (ec->ec_has_volatile)
1093 : 60 : return false;
1094 : :
1095 : : /*
1096 : : * Try to find an EM directly matching some reltarget member.
1097 : : */
1098 [ + + + + : 35266 : foreach(lc, target->exprs)
+ + ]
1099 : : {
1100 : 29782 : Expr *targetexpr = (Expr *) lfirst(lc);
1101 : :
1102 : 29782 : em = find_ec_member_matching_expr(ec, targetexpr, rel->relids);
1103 [ + + ]: 29782 : if (!em)
2193 tomas.vondra@postgre 1104 : 19082 : continue;
1105 : :
1106 : : /*
1107 : : * Reject expressions involving set-returning functions, as those
1108 : : * can't be computed early either. (Note: this test and the following
1109 : : * one are effectively checking properties of targetexpr, so there's
1110 : : * no point in asking whether some other EC member would be better.)
1111 : : */
1555 tgl@sss.pgh.pa.us 1112 [ - + ]: 10700 : if (expression_returns_set((Node *) em->em_expr))
2145 tomas.vondra@postgre 1113 :UBC 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 : : */
2025 tgl@sss.pgh.pa.us 1119 [ + - ]:CBC 10700 : if (require_parallel_safe &&
1120 [ - + ]: 10700 : !is_parallel_safe(root, (Node *) em->em_expr))
2145 tomas.vondra@postgre 1121 :UBC 0 : continue;
1122 : :
2025 tgl@sss.pgh.pa.us 1123 :CBC 10700 : 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 : : */
1555 1140 [ + + ]: 79 : if (expression_returns_set((Node *) em->em_expr))
2025 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
7229 1193 : 255622 : 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 : : */
2664 drowley@postgresql.o 1205 : 255622 : root->ec_merging_done = true;
1206 : :
1207 : 255622 : ec_index = 0;
7229 tgl@sss.pgh.pa.us 1208 [ + + + + : 575470 : foreach(lc, root->eq_classes)
+ + ]
1209 : : {
1210 : 319848 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
2664 drowley@postgresql.o 1211 : 319848 : bool can_generate_joinclause = false;
1212 : : int i;
1213 : :
6930 bruce@momjian.us 1214 [ - + ]: 319848 : Assert(ec->ec_merged == NULL); /* else shouldn't be in list */
1215 [ - + ]: 319848 : 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 : : */
2664 drowley@postgresql.o 1222 [ + + ]: 319848 : if (list_length(ec->ec_members) > 1)
1223 : : {
1224 [ + + ]: 227384 : if (ec->ec_has_const)
1225 : 164138 : generate_base_implied_equalities_const(root, ec);
1226 : : else
1227 : 63246 : generate_base_implied_equalities_no_const(root, ec);
1228 : :
1229 : : /* Recover if we failed to generate required derived clauses */
1230 [ + + ]: 227384 : if (ec->ec_broken)
1231 : 25 : generate_base_implied_equalities_broken(root, ec);
1232 : :
1233 : : /* Detect whether this EC might generate join clauses */
1234 : 227384 : can_generate_joinclause =
1235 : 227384 : (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 : 319848 : i = -1;
1246 [ + + ]: 718352 : while ((i = bms_next_member(ec->ec_relids, i)) > 0)
1247 : : {
1248 : 398504 : RelOptInfo *rel = root->simple_rel_array[i];
1249 : :
1250 : : /* ignore the RTE_GROUP RTE */
786 rguo@postgresql.org 1251 [ - + ]: 398504 : if (i == root->group_rtindex)
786 rguo@postgresql.org 1252 :UBC 0 : continue;
1253 : :
1375 tgl@sss.pgh.pa.us 1254 [ + + ]:CBC 398504 : if (rel == NULL) /* must be an outer join */
1255 : : {
1256 [ - + ]: 3558 : Assert(bms_is_member(i, root->outer_join_rels));
1257 : 3558 : continue;
1258 : : }
1259 : :
2664 drowley@postgresql.o 1260 [ - + ]: 394946 : Assert(rel->reloptkind == RELOPT_BASEREL);
1261 : :
1262 : 394946 : rel->eclass_indexes = bms_add_member(rel->eclass_indexes,
1263 : : ec_index);
1264 : :
1265 [ + + ]: 394946 : if (can_generate_joinclause)
1266 : 149535 : rel->has_eclass_joins = true;
1267 : : }
1268 : :
1269 : 319848 : ec_index++;
1270 : : }
7229 tgl@sss.pgh.pa.us 1271 : 255622 : }
1272 : :
1273 : : /*
1274 : : * generate_base_implied_equalities when EC contains pseudoconstant(s)
1275 : : */
1276 : : static void
1277 : 164138 : generate_base_implied_equalities_const(PlannerInfo *root,
1278 : : EquivalenceClass *ec)
1279 : : {
1280 : 164138 : 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 : : */
6922 1290 [ + + + + ]: 316239 : if (list_length(ec->ec_members) == 2 &&
1291 : 152101 : list_length(ec->ec_sources) == 1)
1292 : : {
1293 : 152066 : RestrictInfo *restrictinfo = (RestrictInfo *) linitial(ec->ec_sources);
1294 : :
1375 1295 : 152066 : distribute_restrictinfo_to_rels(root, restrictinfo);
1296 : 152066 : return;
1297 : : }
1298 : :
1299 : : /* We don't expect any children yet */
576 drowley@postgresql.o 1300 [ - + ]: 12072 : 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 : : */
7229 tgl@sss.pgh.pa.us 1308 [ + - + + : 29161 : foreach(lc, ec->ec_members)
+ + ]
1309 : : {
1310 : 29067 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1311 : :
1312 [ + + ]: 29067 : if (cur_em->em_is_const)
1313 : : {
1314 : 12077 : const_em = cur_em;
5123 1315 [ + + ]: 12077 : if (IsA(cur_em->em_expr, Const))
1316 : 11978 : break;
1317 : : }
1318 : : }
7229 1319 [ - + ]: 12072 : Assert(const_em != NULL);
1320 : :
1321 : : /* Generate a derived equality against each other member */
1322 [ + - + + : 48369 : foreach(lc, ec->ec_members)
+ + ]
1323 : : {
1324 : 36322 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1325 : : Oid eq_op;
1326 : : RestrictInfo *rinfo;
1327 : :
1328 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 1329 [ - + ]: 36322 : Assert(!cur_em->em_is_child);
7229 tgl@sss.pgh.pa.us 1330 [ + + ]: 36322 : if (cur_em == const_em)
1331 : 12052 : continue;
1332 : 24270 : eq_op = select_equality_operator(ec,
1333 : : cur_em->em_datatype,
1334 : : const_em->em_datatype);
1335 [ + + ]: 24270 : 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 : : */
2199 1347 : 24245 : rinfo = process_implied_equality(root, eq_op, ec->ec_collation,
1348 : : cur_em->em_expr, const_em->em_expr,
1375 1349 : 24245 : const_em->em_jdomain->jd_relids,
1350 : : ec->ec_min_security,
2199 1351 : 24245 : 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 [ + - + + ]: 24245 : if (rinfo && rinfo->mergeopfamilies)
1362 : : {
1363 : : /* it's not redundant, so don't set parent_ec */
1364 : 24110 : rinfo->left_ec = rinfo->right_ec = ec;
1365 : 24110 : rinfo->left_em = cur_em;
1366 : 24110 : rinfo->right_em = const_em;
580 amitlan@postgresql.o 1367 : 24110 : 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
7229 tgl@sss.pgh.pa.us 1376 : 63246 : 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 : : */
80 michael@paquier.xyz 1390 :GNC 63246 : prev_ems = palloc0_array(EquivalenceMember *, root->simple_rel_array_size);
1391 : :
1392 : : /* We don't expect any children yet */
576 drowley@postgresql.o 1393 [ - + ]:CBC 63246 : Assert(ec->ec_childmembers == NULL);
1394 : :
7229 tgl@sss.pgh.pa.us 1395 [ + - + + : 191600 : foreach(lc, ec->ec_members)
+ + ]
1396 : : {
1397 : 128354 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
1398 : : int relid;
1399 : :
1400 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 1401 [ - + ]: 128354 : Assert(!cur_em->em_is_child);
1402 : :
4360 tgl@sss.pgh.pa.us 1403 [ + + ]: 128354 : if (!bms_get_singleton_member(cur_em->em_relids, &relid))
7229 1404 : 275 : continue;
1405 [ - + ]: 128079 : Assert(relid < root->simple_rel_array_size);
1406 : :
1407 [ + + ]: 128079 : 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... */
7229 tgl@sss.pgh.pa.us 1419 :UBC 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 : : */
2199 tgl@sss.pgh.pa.us 1428 :CBC 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 : : }
7229 1449 : 128079 : prev_ems[relid] = cur_em;
1450 : : }
1451 : :
1452 : 63246 : 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 [ + - + + : 191600 : foreach(lc, ec->ec_members)
+ + ]
1463 : : {
1464 : 128354 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
6409 1465 : 128354 : List *vars = pull_var_clause((Node *) cur_em->em_expr,
1466 : : PVC_RECURSE_AGGREGATES |
1467 : : PVC_RECURSE_WINDOWFUNCS |
1468 : : PVC_INCLUDE_PLACEHOLDERS);
1469 : :
1541 1470 : 128354 : add_vars_to_targetlist(root, vars, ec->ec_relids);
7229 1471 : 128354 : list_free(vars);
1472 : : }
1473 : 63246 : }
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 : :
5313 1499 [ - + - - ]: 55 : if (ec->ec_has_const ||
5313 tgl@sss.pgh.pa.us 1500 :UBC 0 : bms_membership(restrictinfo->required_relids) != BMS_MULTIPLE)
7229 tgl@sss.pgh.pa.us 1501 :CBC 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 : 443981 : generate_join_implied_equalities(PlannerInfo *root,
1554 : : Relids join_relids,
1555 : : Relids outer_relids,
1556 : : RelOptInfo *inner_rel,
1557 : : SpecialJoinInfo *sjinfo)
1558 : : {
2664 drowley@postgresql.o 1559 : 443981 : List *result = NIL;
1560 : 443981 : 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 [ + + + + : 443981 : if (IS_OTHER_REL(inner_rel))
- + ]
1568 : : {
1569 [ - + ]: 9653 : Assert(!bms_is_empty(inner_rel->top_parent_relids));
1570 : :
1571 : : /* Fetch relid set for the topmost parent rel */
1572 : 9653 : nominal_inner_relids = inner_rel->top_parent_relids;
1573 : : /* ECs will be marked with the parent's relid, not the child's */
1574 : 9653 : nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1268 tgl@sss.pgh.pa.us 1575 : 9653 : nominal_join_relids = add_outer_joins_to_relids(root,
1576 : : nominal_join_relids,
1577 : : sjinfo,
1578 : : NULL);
1579 : : }
1580 : : else
1581 : : {
2664 drowley@postgresql.o 1582 : 434328 : nominal_inner_relids = inner_relids;
1583 : 434328 : 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 : : */
1268 tgl@sss.pgh.pa.us 1599 [ + + + + ]: 443981 : if (sjinfo && sjinfo->ojrelid != 0)
1351 1600 : 74465 : matching_ecs = get_eclass_indexes_for_relids(root, nominal_join_relids);
1601 : : else
1602 : 369516 : matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
1603 : : outer_relids);
1604 : :
2664 drowley@postgresql.o 1605 : 443981 : i = -1;
1606 [ + + ]: 1238346 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
1607 : : {
1608 : 794365 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
1609 : 794365 : List *sublist = NIL;
1610 : :
1611 : : /* ECs containing consts do not need any further enforcement */
1612 [ + + ]: 794365 : if (ec->ec_has_const)
1613 : 98381 : continue;
1614 : :
1615 : : /* Single-member ECs won't generate any deductions */
1616 [ + + ]: 695984 : if (list_length(ec->ec_members) <= 1)
1617 : 345948 : continue;
1618 : :
1619 : : /* Sanity check that this eclass overlaps the join */
1620 [ - + ]: 350036 : Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
1621 : :
1622 [ + + ]: 350036 : if (!ec->ec_broken)
1623 : 349766 : 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 [ + + ]: 350036 : 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 : 350036 : result = list_concat(result, sublist);
1639 : : }
1640 : :
1641 : 443981 : 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 *
3842 tgl@sss.pgh.pa.us 1653 : 8723 : generate_join_implied_equalities_for_ecs(PlannerInfo *root,
1654 : : List *eclasses,
1655 : : Relids join_relids,
1656 : : Relids outer_relids,
1657 : : RelOptInfo *inner_rel)
1658 : : {
7229 1659 : 8723 : List *result = NIL;
5313 1660 : 8723 : 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 */
3503 rhaas@postgresql.org 1666 [ + + + - : 8723 : if (IS_OTHER_REL(inner_rel))
- + ]
1667 : : {
1668 [ - + ]: 2390 : 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 */
5313 tgl@sss.pgh.pa.us 1673 : 2390 : nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1674 : : }
1675 : : else
1676 : : {
1677 : 6333 : nominal_inner_relids = inner_relids;
1678 : 6333 : nominal_join_relids = join_relids;
1679 : : }
1680 : :
3842 1681 [ + - + + : 17885 : foreach(lc, eclasses)
+ + ]
1682 : : {
7229 1683 : 9162 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc);
6930 bruce@momjian.us 1684 : 9162 : List *sublist = NIL;
1685 : :
1686 : : /* ECs containing consts do not need any further enforcement */
7229 tgl@sss.pgh.pa.us 1687 [ - + ]: 9162 : if (ec->ec_has_const)
7229 tgl@sss.pgh.pa.us 1688 :UBC 0 : continue;
1689 : :
1690 : : /* Single-member ECs won't generate any deductions */
7229 tgl@sss.pgh.pa.us 1691 [ - + ]:CBC 9162 : if (list_length(ec->ec_members) <= 1)
7229 tgl@sss.pgh.pa.us 1692 :UBC 0 : continue;
1693 : :
1694 : : /* We can quickly ignore any that don't overlap the join, too */
5313 tgl@sss.pgh.pa.us 1695 [ - + ]:CBC 9162 : if (!bms_overlap(ec->ec_relids, nominal_join_relids))
7229 tgl@sss.pgh.pa.us 1696 :UBC 0 : continue;
1697 : :
7229 tgl@sss.pgh.pa.us 1698 [ + - ]:CBC 9162 : if (!ec->ec_broken)
1699 : 9162 : 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 [ - + ]: 9162 : if (ec->ec_broken)
7229 tgl@sss.pgh.pa.us 1707 :UBC 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 : :
7229 tgl@sss.pgh.pa.us 1714 :CBC 9162 : result = list_concat(result, sublist);
1715 : : }
1716 : :
1717 : 8723 : return result;
1718 : : }
1719 : :
1720 : : /*
1721 : : * generate_join_implied_equalities for a still-valid EC
1722 : : */
1723 : : static List *
1724 : 358928 : generate_join_implied_equalities_normal(PlannerInfo *root,
1725 : : EquivalenceClass *ec,
1726 : : Relids join_relids,
1727 : : Relids outer_relids,
1728 : : Relids inner_relids)
1729 : : {
1730 : 358928 : List *result = NIL;
1731 : 358928 : List *new_members = NIL;
1732 : 358928 : List *outer_members = NIL;
1733 : 358928 : 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 : : */
576 drowley@postgresql.o 1746 : 358928 : setup_eclass_member_iterator(&it, ec, join_relids);
1747 [ + + ]: 1277819 : 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 : : */
5313 tgl@sss.pgh.pa.us 1754 [ + + ]: 918891 : if (!bms_is_subset(cur_em->em_relids, join_relids))
1755 : 206503 : continue; /* not computable yet, or wrong child */
1756 : :
1757 [ + + ]: 712388 : if (bms_is_subset(cur_em->em_relids, outer_relids))
7229 1758 : 397972 : outer_members = lappend(outer_members, cur_em);
5313 1759 [ + + ]: 314416 : else if (bms_is_subset(cur_em->em_relids, inner_relids))
7229 1760 : 309230 : inner_members = lappend(inner_members, cur_em);
1761 : : else
1762 : 5186 : new_members = lappend(new_members, cur_em);
1763 : : }
1764 : :
1765 : : /*
1766 : : * First, select the joinclause if needed. We can equate any one outer
1767 : : * member to any one inner member, but we have to find a datatype
1768 : : * combination for which an opfamily member operator exists. If we have
1769 : : * choices, we prefer simple Var members (possibly with RelabelType) since
1770 : : * these are (a) cheapest to compute at runtime and (b) most likely to
1771 : : * have useful statistics. Also, prefer operators that are also
1772 : : * hashjoinable.
1773 : : */
1774 [ + + + + ]: 358928 : if (outer_members && inner_members)
1775 : : {
1776 : 290923 : EquivalenceMember *best_outer_em = NULL;
1777 : 290923 : EquivalenceMember *best_inner_em = NULL;
6930 bruce@momjian.us 1778 : 290923 : Oid best_eq_op = InvalidOid;
1779 : 290923 : int best_score = -1;
1780 : : RestrictInfo *rinfo;
1781 : : ListCell *lc1;
1782 : :
7229 tgl@sss.pgh.pa.us 1783 [ + - + + : 304242 : foreach(lc1, outer_members)
+ + ]
1784 : : {
1785 : 290988 : EquivalenceMember *outer_em = (EquivalenceMember *) lfirst(lc1);
1786 : : ListCell *lc2;
1787 : :
1788 [ + - + + : 304327 : foreach(lc2, inner_members)
+ + ]
1789 : : {
1790 : 291008 : EquivalenceMember *inner_em = (EquivalenceMember *) lfirst(lc2);
1791 : : Oid eq_op;
1792 : : int score;
1793 : :
1794 : 291008 : eq_op = select_equality_operator(ec,
1795 : : outer_em->em_datatype,
1796 : : inner_em->em_datatype);
1797 [ + + ]: 291008 : if (!OidIsValid(eq_op))
1798 : 30 : continue;
1799 : 290978 : score = 0;
1800 [ + + ]: 290978 : if (IsA(outer_em->em_expr, Var) ||
1801 [ + + ]: 14718 : (IsA(outer_em->em_expr, RelabelType) &&
1802 [ + + ]: 4019 : IsA(((RelabelType *) outer_em->em_expr)->arg, Var)))
1803 : 279728 : score++;
1804 [ + + ]: 290978 : if (IsA(inner_em->em_expr, Var) ||
1805 [ + + ]: 10188 : (IsA(inner_em->em_expr, RelabelType) &&
1806 [ + + ]: 7922 : IsA(((RelabelType *) inner_em->em_expr)->arg, Var)))
1807 : 288576 : score++;
5789 1808 [ + + ]: 290978 : if (op_hashjoinable(eq_op,
5850 1809 : 290978 : exprType((Node *) outer_em->em_expr)))
7229 1810 : 290919 : score++;
1811 [ + + ]: 290978 : if (score > best_score)
1812 : : {
1813 : 290893 : best_outer_em = outer_em;
1814 : 290893 : best_inner_em = inner_em;
1815 : 290893 : best_eq_op = eq_op;
1816 : 290893 : best_score = score;
1817 [ + + ]: 290893 : if (best_score == 3)
6930 bruce@momjian.us 1818 : 277669 : break; /* no need to look further */
1819 : : }
1820 : : }
7229 tgl@sss.pgh.pa.us 1821 [ + + ]: 290988 : if (best_score == 3)
6930 bruce@momjian.us 1822 : 277669 : break; /* no need to look further */
1823 : : }
7229 tgl@sss.pgh.pa.us 1824 [ + + ]: 290923 : 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 : : */
7227 1835 : 290893 : rinfo = create_join_clause(root, ec, best_eq_op,
1836 : : best_outer_em, best_inner_em,
1837 : : ec);
1838 : :
7229 1839 : 290893 : 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 [ + + ]: 358898 : if (new_members)
1852 : : {
1853 : 5156 : List *old_members = list_concat(outer_members, inner_members);
1854 : 5156 : EquivalenceMember *prev_em = NULL;
1855 : : RestrictInfo *rinfo;
1856 : : ListCell *lc1;
1857 : :
1858 : : /* For now, arbitrarily take the first old_member as the one to use */
1859 [ + + ]: 5156 : if (old_members)
1860 : 3563 : new_members = lappend(new_members, linitial(old_members));
1861 : :
1862 [ + - + + : 13905 : foreach(lc1, new_members)
+ + ]
1863 : : {
576 drowley@postgresql.o 1864 : 8749 : cur_em = (EquivalenceMember *) lfirst(lc1);
1865 : :
7229 tgl@sss.pgh.pa.us 1866 [ + + ]: 8749 : if (prev_em != NULL)
1867 : : {
1868 : : Oid eq_op;
1869 : :
1870 : 3593 : eq_op = select_equality_operator(ec,
1871 : : prev_em->em_datatype,
1872 : : cur_em->em_datatype);
1873 [ - + ]: 3593 : if (!OidIsValid(eq_op))
1874 : : {
1875 : : /* failed... */
7229 tgl@sss.pgh.pa.us 1876 :UBC 0 : ec->ec_broken = true;
1877 : 0 : return NIL;
1878 : : }
1879 : : /* do NOT set parent_ec, this qual is not redundant! */
7227 tgl@sss.pgh.pa.us 1880 :CBC 3593 : rinfo = create_join_clause(root, ec, eq_op,
1881 : : prev_em, cur_em,
1882 : : NULL);
1883 : :
7229 1884 : 3593 : result = lappend(result, rinfo);
1885 : : }
1886 : 8749 : prev_em = cur_em;
1887 : : }
1888 : : }
1889 : :
1890 : 358898 : 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);
5313 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))
7229 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 : : */
3503 rhaas@postgresql.org 1934 [ + + + - : 300 : if (IS_OTHER_REL(inner_rel) && result != NIL)
- + + + ]
4418 tgl@sss.pgh.pa.us 1935 : 135 : result = (List *) adjust_appendrel_attrs_multilevel(root,
1936 : : (Node *) result,
1937 : : inner_rel,
1540 1938 : 135 : inner_rel->top_parent);
1939 : :
7229 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
6930 bruce@momjian.us 1951 : 422508 : select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
1952 : : {
1953 : : ListCell *lc;
1954 : :
7229 tgl@sss.pgh.pa.us 1955 [ + - + + : 422563 : foreach(lc, ec->ec_opfamilies)
+ + ]
1956 : : {
6930 bruce@momjian.us 1957 : 422508 : Oid opfamily = lfirst_oid(lc);
1958 : : Oid opno;
1959 : :
578 peter@eisentraut.org 1960 : 422508 : opno = get_opfamily_member_for_cmptype(opfamily, lefttype, righttype, COMPARE_EQ);
3578 tgl@sss.pgh.pa.us 1961 [ + + ]: 422508 : if (!OidIsValid(opno))
1962 : 55 : continue;
1963 : : /* If no barrier quals in query, don't worry about leaky operators */
1964 [ + + ]: 422453 : if (ec->ec_max_security == 0)
1965 : 422453 : return opno;
1966 : : /* Otherwise, insist that selected operators be leakproof */
1967 [ + - ]: 509 : if (get_func_leakproof(get_opcode(opno)))
7229 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 *
7227 1986 : 400482 : create_join_clause(PlannerInfo *root,
1987 : : EquivalenceClass *ec, Oid opno,
1988 : : EquivalenceMember *leftem,
1989 : : EquivalenceMember *rightem,
1990 : : EquivalenceClass *parent_ec)
1991 : : {
1992 : : RestrictInfo *rinfo;
1375 1993 : 400482 : RestrictInfo *parent_rinfo = NULL;
1994 : : MemoryContext oldcontext;
1995 : :
580 amitlan@postgresql.o 1996 : 400482 : rinfo = ec_search_clause_for_ems(root, ec, leftem, rightem, parent_ec);
1997 [ + + ]: 400482 : if (rinfo)
1998 : 333036 : 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 : : */
7227 tgl@sss.pgh.pa.us 2004 : 67446 : 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 : : */
1375 2010 [ + + + + ]: 67446 : 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 : :
2114 2020 : 67446 : rinfo = build_implied_join_equality(root,
2021 : : opno,
2022 : : ec->ec_collation,
2023 : : leftem->em_expr,
2024 : : rightem->em_expr,
6922 2025 : 67446 : bms_union(leftem->em_relids,
5131 2026 : 67446 : 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 : : */
31 rguo@postgresql.org 2038 [ + + + + ]: 67446 : 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 */
1375 tgl@sss.pgh.pa.us 2053 [ + + ]: 67446 : 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 : : */
56 rguo@postgresql.org 2065 [ + + ]: 62932 : counterpart = ec_search_clause_for_ems(root, ec, leftem, rightem,
2066 : : parent_ec ? NULL : ec);
2067 [ + + ]: 62932 : if (counterpart)
2068 : 61132 : rinfo->rinfo_serial = counterpart->rinfo_serial;
2069 : : }
2070 : :
2071 : : /* Mark the clause as redundant, or not */
7227 tgl@sss.pgh.pa.us 2072 : 67446 : 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 : 67446 : rinfo->left_ec = ec;
2079 : 67446 : rinfo->right_ec = ec;
2080 : :
2081 : : /* Mark it as usable with these EMs */
2082 : 67446 : rinfo->left_em = leftem;
2083 : 67446 : rinfo->right_em = rightem;
2084 : : /* and save it for possible re-use */
580 amitlan@postgresql.o 2085 : 67446 : ec_add_derived_clause(ec, rinfo);
2086 : :
7227 tgl@sss.pgh.pa.us 2087 : 67446 : MemoryContextSwitchTo(oldcontext);
2088 : :
2089 : 67446 : 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
7229 2167 : 255622 : 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 : : {
6875 2175 : 257312 : found = false;
2176 : :
2177 : : /* Process the LEFT JOIN clauses */
2670 2178 [ + + + + : 280365 : foreach(cell, root->left_join_clauses)
+ + ]
2179 : : {
1375 2180 : 23053 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2181 : :
2182 [ + + ]: 23053 : if (reconsider_outer_join_clause(root, ojcinfo, true))
2183 : : {
2184 : 571 : RestrictInfo *rinfo = ojcinfo->rinfo;
2185 : :
6875 2186 : 571 : found = true;
2187 : : /* remove it from the list */
2188 : 571 : root->left_join_clauses =
2670 2189 : 571 : foreach_delete_current(root->left_join_clauses, cell);
2190 : : /* throw back a clone as-is (see notes above) */
7 rguo@postgresql.org 2191 [ + + - + ]: 571 : 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) */
1375 tgl@sss.pgh.pa.us 2200 : 511 : rinfo = make_restrictinfo(root,
2201 : 511 : (Expr *) makeBoolConst(true, false),
1260 2202 : 511 : rinfo->is_pushed_down,
2203 : 511 : rinfo->has_clone,
2204 : 511 : rinfo->is_clone,
2205 : : false, /* pseudoconstant */
2206 : : 0, /* security_level */
2207 : : rinfo->required_relids,
2208 : : rinfo->incompatible_relids,
2209 : : rinfo->outer_relids);
6875 2210 : 511 : distribute_restrictinfo_to_rels(root, rinfo);
2211 : : }
2212 : : }
2213 : :
2214 : : /* Process the RIGHT JOIN clauses */
2670 2215 [ + + + + : 286359 : foreach(cell, root->right_join_clauses)
+ + ]
2216 : : {
1375 2217 : 29047 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2218 : :
2219 [ + + ]: 29047 : if (reconsider_outer_join_clause(root, ojcinfo, false))
2220 : : {
2221 : 1144 : RestrictInfo *rinfo = ojcinfo->rinfo;
2222 : :
6875 2223 : 1144 : found = true;
2224 : : /* remove it from the list */
2225 : 1144 : root->right_join_clauses =
2670 2226 : 1144 : foreach_delete_current(root->right_join_clauses, cell);
2227 : : /* throw back a clone as-is (see notes above) */
7 rguo@postgresql.org 2228 [ + - - + ]: 1144 : if (rinfo->has_clone || rinfo->is_clone)
2229 : : {
2230 : : /* but the thrown-back clause has no extra selectivity */
7 rguo@postgresql.org 2231 :UBC 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) */
1375 tgl@sss.pgh.pa.us 2237 :CBC 1144 : rinfo = make_restrictinfo(root,
2238 : 1144 : (Expr *) makeBoolConst(true, false),
1260 2239 : 1144 : rinfo->is_pushed_down,
2240 : 1144 : rinfo->has_clone,
2241 : 1144 : rinfo->is_clone,
2242 : : false, /* pseudoconstant */
2243 : : 0, /* security_level */
2244 : : rinfo->required_relids,
2245 : : rinfo->incompatible_relids,
2246 : : rinfo->outer_relids);
6875 2247 : 1144 : distribute_restrictinfo_to_rels(root, rinfo);
2248 : : }
2249 : : }
2250 : :
2251 : : /* Process the FULL JOIN clauses */
2670 2252 [ + + + + : 258396 : foreach(cell, root->full_join_clauses)
+ + ]
2253 : : {
1375 2254 : 1084 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2255 : :
2256 [ + + ]: 1084 : if (reconsider_full_join_clause(root, ojcinfo))
2257 : : {
2258 : 5 : RestrictInfo *rinfo = ojcinfo->rinfo;
2259 : :
6875 2260 : 5 : found = true;
2261 : : /* remove it from the list */
2262 : 5 : root->full_join_clauses =
2670 2263 : 5 : foreach_delete_current(root->full_join_clauses, cell);
2264 : : /* throw back a dummy replacement clause (see notes above) */
1375 2265 : 5 : rinfo = make_restrictinfo(root,
2266 : 5 : (Expr *) makeBoolConst(true, false),
1260 2267 : 5 : rinfo->is_pushed_down,
2268 : 5 : rinfo->has_clone,
2269 : 5 : rinfo->is_clone,
2270 : : false, /* pseudoconstant */
2271 : : 0, /* security_level */
2272 : : rinfo->required_relids,
2273 : : rinfo->incompatible_relids,
2274 : : rinfo->outer_relids);
6875 2275 : 5 : distribute_restrictinfo_to_rels(root, rinfo);
2276 : : }
2277 : : }
2278 [ + + ]: 257312 : } while (found);
2279 : :
2280 : : /* Now, any remaining clauses have to be thrown back */
2281 [ + + + + : 277714 : foreach(cell, root->left_join_clauses)
+ + ]
2282 : : {
1375 2283 : 22092 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2284 : :
2285 : 22092 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2286 : : }
6875 2287 [ + + + + : 282338 : foreach(cell, root->right_join_clauses)
+ + ]
2288 : : {
1375 2289 : 26716 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2290 : :
2291 : 26716 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2292 : : }
6875 2293 [ + + + + : 256701 : foreach(cell, root->full_join_clauses)
+ + ]
2294 : : {
1375 2295 : 1079 : OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2296 : :
2297 : 1079 : distribute_restrictinfo_to_rels(root, ojcinfo->rinfo);
2298 : : }
7229 2299 : 255622 : }
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
1375 2307 : 52100 : reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
2308 : : bool outer_on_left)
2309 : : {
2310 : 52100 : RestrictInfo *rinfo = ojcinfo->rinfo;
2311 : 52100 : 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 : :
7229 2322 [ - + ]: 52100 : Assert(is_opclause(rinfo->clause));
6875 2323 : 52100 : opno = ((OpExpr *) rinfo->clause)->opno;
5710 2324 : 52100 : collation = ((OpExpr *) rinfo->clause)->inputcollid;
2325 : :
2326 : : /* Extract needed info from the clause */
6875 2327 : 52100 : op_input_types(opno, &left_type, &right_type);
7229 2328 [ + + ]: 52100 : if (outer_on_left)
2329 : : {
2330 : 23053 : outervar = (Expr *) get_leftop(rinfo->clause);
2331 : 23053 : innervar = (Expr *) get_rightop(rinfo->clause);
2332 : 23053 : inner_datatype = right_type;
6922 2333 : 23053 : inner_relids = rinfo->right_relids;
2334 : : }
2335 : : else
2336 : : {
7229 2337 : 29047 : outervar = (Expr *) get_rightop(rinfo->clause);
2338 : 29047 : innervar = (Expr *) get_leftop(rinfo->clause);
2339 : 29047 : inner_datatype = left_type;
6922 2340 : 29047 : inner_relids = rinfo->left_relids;
2341 : : }
2342 : :
2343 : : /* Scan EquivalenceClasses for a match to outervar */
7229 2344 [ + - + + : 317376 : foreach(lc1, root->eq_classes)
+ + ]
2345 : : {
2346 : 266991 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2347 : : bool match;
2348 : : ListCell *lc2;
2349 : :
2350 : : /* We don't expect any children yet */
576 drowley@postgresql.o 2351 [ - + ]: 266991 : Assert(cur_ec->ec_childmembers == NULL);
2352 : :
2353 : : /* Ignore EC unless it contains pseudoconstants */
7229 tgl@sss.pgh.pa.us 2354 [ + + ]: 266991 : if (!cur_ec->ec_has_const)
2355 : 207384 : continue;
2356 : : /* Never match to a volatile EC */
2357 [ - + ]: 59607 : if (cur_ec->ec_has_volatile)
7229 tgl@sss.pgh.pa.us 2358 :UBC 0 : continue;
2359 : : /* It has to match the outer-join clause as to semantics, too */
5710 tgl@sss.pgh.pa.us 2360 [ + + ]:CBC 59607 : if (collation != cur_ec->ec_collation)
2361 : 4011 : continue;
7229 2362 [ + + ]: 55596 : if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
2363 : 10173 : continue;
2364 : : /* Does it contain a match to outervar? */
2365 : 45423 : match = false;
2366 [ + - + + : 144408 : foreach(lc2, cur_ec->ec_members)
+ + ]
2367 : : {
2368 : 100700 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2369 : :
2370 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 2371 [ - + ]: 100700 : Assert(!cur_em->em_is_child);
7229 tgl@sss.pgh.pa.us 2372 [ + + ]: 100700 : if (equal(outervar, cur_em->em_expr))
2373 : : {
2374 : 1715 : match = true;
2375 : 1715 : break;
2376 : : }
2377 : : }
2378 [ + + ]: 45423 : if (!match)
2379 : 43708 : 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 : 1715 : match = false;
2387 [ + - + + : 6038 : foreach(lc2, cur_ec->ec_members)
+ + ]
2388 : : {
2389 : 4323 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2390 : : Oid eq_op;
2391 : : RestrictInfo *newrinfo;
2392 : : JoinDomain *jdomain;
2393 : :
2394 [ + + ]: 4323 : if (!cur_em->em_is_const)
2395 : 2573 : continue; /* ignore non-const members */
2396 : 1750 : eq_op = select_equality_operator(cur_ec,
2397 : : inner_datatype,
2398 : : cur_em->em_datatype);
2399 [ - + ]: 1750 : if (!OidIsValid(eq_op))
7229 tgl@sss.pgh.pa.us 2400 :UBC 0 : continue; /* can't generate equality */
2114 tgl@sss.pgh.pa.us 2401 :CBC 1750 : 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 */
1375 2409 : 1750 : jdomain = find_join_domain(root, sjinfo->syn_righthand);
2410 [ + - ]: 1750 : if (process_equivalence(root, &newrinfo, jdomain))
7229 2411 : 1750 : 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 [ + - ]: 1715 : if (match)
6875 2420 : 1715 : return true;
2421 : : else
7229 tgl@sss.pgh.pa.us 2422 :UBC 0 : break;
2423 : : }
2424 : :
6875 tgl@sss.pgh.pa.us 2425 :CBC 50385 : 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
1375 2434 : 1084 : reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
2435 : : {
2436 : 1084 : RestrictInfo *rinfo = ojcinfo->rinfo;
2437 : 1084 : SpecialJoinInfo *sjinfo = ojcinfo->sjinfo;
2438 : 1084 : 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 : : ListCell *lc1;
2448 : :
2449 : : /* Extract needed info from the clause */
7229 2450 [ - + ]: 1084 : Assert(is_opclause(rinfo->clause));
6875 2451 : 1084 : opno = ((OpExpr *) rinfo->clause)->opno;
5710 2452 : 1084 : collation = ((OpExpr *) rinfo->clause)->inputcollid;
6875 2453 : 1084 : op_input_types(opno, &left_type, &right_type);
7229 2454 : 1084 : leftvar = (Expr *) get_leftop(rinfo->clause);
2455 : 1084 : rightvar = (Expr *) get_rightop(rinfo->clause);
6922 2456 : 1084 : left_relids = rinfo->left_relids;
2457 : 1084 : right_relids = rinfo->right_relids;
2458 : :
7229 2459 [ + - + + : 5434 : foreach(lc1, root->eq_classes)
+ + ]
2460 : : {
2461 : 4355 : EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
2462 : 4355 : EquivalenceMember *coal_em = NULL;
2463 : : bool match;
2464 : : bool matchleft;
2465 : : bool matchright;
2466 : : ListCell *lc2;
2205 drowley@postgresql.o 2467 : 4355 : int coal_idx = -1;
2468 : :
2469 : : /* We don't expect any children yet */
576 2470 [ - + ]: 4355 : Assert(cur_ec->ec_childmembers == NULL);
2471 : :
2472 : : /* Ignore EC unless it contains pseudoconstants */
7229 tgl@sss.pgh.pa.us 2473 [ + + ]: 4355 : if (!cur_ec->ec_has_const)
2474 : 4105 : continue;
2475 : : /* Never match to a volatile EC */
2476 [ - + ]: 250 : if (cur_ec->ec_has_volatile)
7229 tgl@sss.pgh.pa.us 2477 :UBC 0 : continue;
2478 : : /* It has to match the outer-join clause as to semantics, too */
5710 tgl@sss.pgh.pa.us 2479 [ + + ]:CBC 250 : if (collation != cur_ec->ec_collation)
2480 : 30 : continue;
7229 2481 [ - + ]: 220 : if (!equal(rinfo->mergeopfamilies, cur_ec->ec_opfamilies))
7229 tgl@sss.pgh.pa.us 2482 :UBC 0 : continue;
2483 : :
2484 : : /*
2485 : : * Does it contain a COALESCE(leftvar, rightvar) construct?
2486 : : *
2487 : : * We can assume the COALESCE() inputs are in the same order as the
2488 : : * join clause, since both were automatically generated in the cases
2489 : : * we care about.
2490 : : *
2491 : : * XXX currently this may fail to match in cross-type cases because
2492 : : * the COALESCE will contain typecast operations while the join clause
2493 : : * may not (if there is a cross-type mergejoin operator available for
2494 : : * the two column types). Is it OK to strip implicit coercions from
2495 : : * the COALESCE arguments?
2496 : : */
7229 tgl@sss.pgh.pa.us 2497 :CBC 220 : match = false;
2498 [ + - + + : 645 : foreach(lc2, cur_ec->ec_members)
+ + ]
2499 : : {
2500 : 430 : coal_em = (EquivalenceMember *) lfirst(lc2);
2501 : :
2502 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 2503 [ - + ]: 430 : Assert(!coal_em->em_is_child);
7229 tgl@sss.pgh.pa.us 2504 [ + + ]: 430 : if (IsA(coal_em->em_expr, CoalesceExpr))
2505 : : {
2506 : 15 : CoalesceExpr *cexpr = (CoalesceExpr *) coal_em->em_expr;
2507 : : Node *cfirst;
2508 : : Node *csecond;
2509 : :
2510 [ - + ]: 15 : if (list_length(cexpr->args) != 2)
7229 tgl@sss.pgh.pa.us 2511 :UBC 0 : continue;
7229 tgl@sss.pgh.pa.us 2512 :CBC 15 : cfirst = (Node *) linitial(cexpr->args);
2513 : 15 : csecond = (Node *) lsecond(cexpr->args);
2514 : :
2515 : : /*
2516 : : * The COALESCE arguments will be marked as possibly nulled by
2517 : : * the full join, while we wish to generate clauses that apply
2518 : : * to the join's inputs. So we must strip the join from the
2519 : : * nullingrels fields of cfirst/csecond before comparing them
2520 : : * to leftvar/rightvar. (Perhaps with a less hokey
2521 : : * representation for FULL JOIN USING output columns, this
2522 : : * wouldn't be needed?)
2523 : : */
1375 2524 : 15 : cfirst = remove_nulling_relids(cfirst, fjrelids, NULL);
2525 : 15 : csecond = remove_nulling_relids(csecond, fjrelids, NULL);
2526 : :
7229 2527 [ + + + - ]: 15 : if (equal(leftvar, cfirst) && equal(rightvar, csecond))
2528 : : {
2205 drowley@postgresql.o 2529 : 5 : coal_idx = foreach_current_index(lc2);
7229 tgl@sss.pgh.pa.us 2530 : 5 : match = true;
2531 : 5 : break;
2532 : : }
2533 : : }
2534 : : }
2535 [ + + ]: 220 : if (!match)
2536 : 215 : continue; /* no match, so ignore this EC */
2537 : :
2538 : : /*
2539 : : * Yes it does! Try to generate clauses LEFTVAR = CONSTANT and
2540 : : * RIGHTVAR = CONSTANT for each CONSTANT in the EC. Note that we must
2541 : : * succeed with at least one constant for each var before we can
2542 : : * decide to throw away the outer-join clause.
2543 : : */
2544 : 5 : matchleft = matchright = false;
2545 [ + - + + : 15 : foreach(lc2, cur_ec->ec_members)
+ + ]
2546 : : {
2547 : 10 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
2548 : : Oid eq_op;
2549 : : RestrictInfo *newrinfo;
2550 : : JoinDomain *jdomain;
2551 : :
2552 [ + + ]: 10 : if (!cur_em->em_is_const)
2553 : 5 : continue; /* ignore non-const members */
2554 : 5 : eq_op = select_equality_operator(cur_ec,
2555 : : left_type,
2556 : : cur_em->em_datatype);
2557 [ + - ]: 5 : if (OidIsValid(eq_op))
2558 : : {
2114 2559 : 5 : newrinfo = build_implied_join_equality(root,
2560 : : eq_op,
2561 : : cur_ec->ec_collation,
2562 : : leftvar,
2563 : : cur_em->em_expr,
2564 : : bms_copy(left_relids),
2565 : : cur_ec->ec_min_security);
2566 : : /* This equality holds within the lefthand child JoinDomain */
1375 2567 : 5 : jdomain = find_join_domain(root, sjinfo->syn_lefthand);
2568 [ + - ]: 5 : if (process_equivalence(root, &newrinfo, jdomain))
7229 2569 : 5 : matchleft = true;
2570 : : }
2571 : 5 : eq_op = select_equality_operator(cur_ec,
2572 : : right_type,
2573 : : cur_em->em_datatype);
2574 [ + - ]: 5 : if (OidIsValid(eq_op))
2575 : : {
2114 2576 : 5 : newrinfo = build_implied_join_equality(root,
2577 : : eq_op,
2578 : : cur_ec->ec_collation,
2579 : : rightvar,
2580 : : cur_em->em_expr,
2581 : : bms_copy(right_relids),
2582 : : cur_ec->ec_min_security);
2583 : : /* This equality holds within the righthand child JoinDomain */
1375 2584 : 5 : jdomain = find_join_domain(root, sjinfo->syn_righthand);
2585 [ + - ]: 5 : if (process_equivalence(root, &newrinfo, jdomain))
7229 2586 : 5 : matchright = true;
2587 : : }
2588 : : }
2589 : :
2590 : : /*
2591 : : * If we were able to equate both vars to constants, we're done, and
2592 : : * we can throw away the full-join clause as redundant. Moreover, we
2593 : : * can remove the COALESCE entry from the EC, since the added
2594 : : * restrictions ensure it will always have the expected value. (We
2595 : : * don't bother trying to update ec_relids or ec_sources.)
2596 : : */
2597 [ + - + - ]: 5 : if (matchleft && matchright)
2598 : : {
2205 drowley@postgresql.o 2599 : 5 : cur_ec->ec_members = list_delete_nth_cell(cur_ec->ec_members, coal_idx);
6875 tgl@sss.pgh.pa.us 2600 : 5 : return true;
2601 : : }
2602 : :
2603 : : /*
2604 : : * Otherwise, fall out of the search loop, since we know the COALESCE
2605 : : * appears in at most one EC (XXX might stop being true if we allow
2606 : : * stripping of coercions above?)
2607 : : */
7229 tgl@sss.pgh.pa.us 2608 :UBC 0 : break;
2609 : : }
2610 : :
6875 tgl@sss.pgh.pa.us 2611 :CBC 1079 : return false; /* failed to make any deduction */
2612 : : }
2613 : :
2614 : : /*
2615 : : * find_join_domain
2616 : : * Find the highest JoinDomain enclosed within the given relid set.
2617 : : *
2618 : : * (We could avoid this search at the cost of complicating APIs elsewhere,
2619 : : * which doesn't seem worth it.)
2620 : : */
2621 : : static JoinDomain *
1375 2622 : 1760 : find_join_domain(PlannerInfo *root, Relids relids)
2623 : : {
2624 : : ListCell *lc;
2625 : :
2626 [ + - + - : 3657 : foreach(lc, root->join_domains)
+ - ]
2627 : : {
2628 : 3657 : JoinDomain *jdomain = (JoinDomain *) lfirst(lc);
2629 : :
2630 [ + + ]: 3657 : if (bms_is_subset(jdomain->jd_relids, relids))
2631 : 1760 : return jdomain;
2632 : : }
1375 tgl@sss.pgh.pa.us 2633 [ # # ]:UBC 0 : elog(ERROR, "failed to find appropriate JoinDomain");
2634 : : return NULL; /* keep compiler quiet */
2635 : : }
2636 : :
2637 : :
2638 : : /*
2639 : : * exprs_known_equal
2640 : : * Detect whether two expressions are known equal due to equivalence
2641 : : * relationships.
2642 : : *
2643 : : * If opfamily is given, the expressions must be known equal per the semantics
2644 : : * of that opfamily (note it has to be a btree opfamily, since those are the
2645 : : * only opfamilies equivclass.c deals with). If opfamily is InvalidOid, we'll
2646 : : * return true if they're equal according to any opfamily, which is fuzzy but
2647 : : * OK for estimation purposes.
2648 : : *
2649 : : * Note: does not bother to check for "equal(item1, item2)"; caller must
2650 : : * check that case if it's possible to pass identical items.
2651 : : */
2652 : : bool
828 rguo@postgresql.org 2653 :CBC 32555 : exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
2654 : : {
2655 : : ListCell *lc1;
2656 : :
7229 tgl@sss.pgh.pa.us 2657 [ + + + + : 224757 : foreach(lc1, root->eq_classes)
+ + ]
2658 : : {
2659 : 195028 : EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2660 : 195028 : bool item1member = false;
2661 : 195028 : bool item2member = false;
2662 : : ListCell *lc2;
2663 : :
2664 : : /* Never match to a volatile EC */
2665 [ - + ]: 195028 : if (ec->ec_has_volatile)
7229 tgl@sss.pgh.pa.us 2666 :UBC 0 : continue;
2667 : :
2668 : : /*
2669 : : * It's okay to consider ec_broken ECs here. Brokenness just means we
2670 : : * couldn't derive all the implied clauses we'd have liked to; it does
2671 : : * not invalidate our knowledge that the members are equal.
2672 : : */
2673 : :
2674 : : /* Ignore if this EC doesn't use specified opfamily */
828 rguo@postgresql.org 2675 [ + + ]:CBC 195028 : if (OidIsValid(opfamily) &&
2676 [ + + ]: 590 : !list_member_oid(ec->ec_opfamilies, opfamily))
2677 : 190 : continue;
2678 : :
2679 : : /* Ignore children here */
7229 tgl@sss.pgh.pa.us 2680 [ + - + + : 484870 : foreach(lc2, ec->ec_members)
+ + ]
2681 : : {
2682 : 292858 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
2683 : :
2684 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 2685 [ - + ]: 292858 : Assert(!em->em_is_child);
7229 tgl@sss.pgh.pa.us 2686 [ + + ]: 292858 : if (equal(item1, em->em_expr))
2687 : 13367 : item1member = true;
2688 [ + + ]: 279491 : else if (equal(item2, em->em_expr))
2689 : 24674 : item2member = true;
2690 : : /* Exit as soon as equality is proven */
2691 [ + + + + ]: 292858 : if (item1member && item2member)
2692 : 2826 : return true;
2693 : : }
2694 : : }
2695 : 29729 : return false;
2696 : : }
2697 : :
2698 : :
2699 : : /*
2700 : : * match_eclasses_to_foreign_key_col
2701 : : * See whether a foreign key column match is proven by any eclass.
2702 : : *
2703 : : * If the referenced and referencing Vars of the fkey's colno'th column are
2704 : : * known equal due to any eclass, return that eclass; otherwise return NULL.
2705 : : * (In principle there might be more than one matching eclass if multiple
2706 : : * collations are involved, but since collation doesn't matter for equality,
2707 : : * we ignore that fine point here.) This is much like exprs_known_equal,
2708 : : * except for the format of the input.
2709 : : *
2710 : : * On success, we also set fkinfo->eclass[colno] to the matching eclass,
2711 : : * and set fkinfo->fk_eclass_member[colno] to the eclass member for the
2712 : : * referencing Var.
2713 : : */
2714 : : EquivalenceClass *
3792 2715 : 1943 : match_eclasses_to_foreign_key_col(PlannerInfo *root,
2716 : : ForeignKeyOptInfo *fkinfo,
2717 : : int colno)
2718 : : {
2719 : 1943 : Index var1varno = fkinfo->con_relid;
2720 : 1943 : AttrNumber var1attno = fkinfo->conkey[colno];
2721 : 1943 : Index var2varno = fkinfo->ref_relid;
2722 : 1943 : AttrNumber var2attno = fkinfo->confkey[colno];
2723 : 1943 : Oid eqop = fkinfo->conpfeqop[colno];
2664 drowley@postgresql.o 2724 : 1943 : RelOptInfo *rel1 = root->simple_rel_array[var1varno];
2725 : 1943 : RelOptInfo *rel2 = root->simple_rel_array[var2varno];
3424 tgl@sss.pgh.pa.us 2726 : 1943 : List *opfamilies = NIL; /* compute only if needed */
2727 : : Bitmapset *matching_ecs;
2728 : : int i;
2729 : :
2730 : : /* Consider only eclasses mentioning both relations */
2664 drowley@postgresql.o 2731 [ - + ]: 1943 : Assert(root->ec_merging_done);
2732 [ - + - - ]: 1943 : Assert(IS_SIMPLE_REL(rel1));
2733 [ - + - - ]: 1943 : Assert(IS_SIMPLE_REL(rel2));
2734 : 1943 : matching_ecs = bms_intersect(rel1->eclass_indexes,
2735 : 1943 : rel2->eclass_indexes);
2736 : :
2737 : 1943 : i = -1;
2738 [ + + ]: 2023 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
2739 : : {
2740 : 425 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
2741 : : i);
2199 tgl@sss.pgh.pa.us 2742 : 425 : EquivalenceMember *item1_em = NULL;
2743 : 425 : EquivalenceMember *item2_em = NULL;
2744 : : ListCell *lc2;
2745 : :
2746 : : /* Never match to a volatile EC */
3792 2747 [ - + ]: 425 : if (ec->ec_has_volatile)
3792 tgl@sss.pgh.pa.us 2748 :UBC 0 : continue;
2749 : :
2750 : : /*
2751 : : * It's okay to consider "broken" ECs here, see exprs_known_equal.
2752 : : * Ignore children here.
2753 : : */
3792 tgl@sss.pgh.pa.us 2754 [ + - + + :CBC 1015 : foreach(lc2, ec->ec_members)
+ + ]
2755 : : {
2756 : 935 : EquivalenceMember *em = (EquivalenceMember *) lfirst(lc2);
2757 : : Var *var;
2758 : :
2759 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 2760 [ - + ]: 935 : Assert(!em->em_is_child);
2761 : :
2762 : : /* EM must be a Var, possibly with RelabelType */
3792 tgl@sss.pgh.pa.us 2763 : 935 : var = (Var *) em->em_expr;
2764 [ + - - + ]: 935 : while (var && IsA(var, RelabelType))
3792 tgl@sss.pgh.pa.us 2765 :UBC 0 : var = (Var *) ((RelabelType *) var)->arg;
3792 tgl@sss.pgh.pa.us 2766 [ + - + + ]:CBC 935 : if (!(var && IsA(var, Var)))
2767 : 5 : continue;
2768 : :
2769 : : /* Match? */
2770 [ + + + + ]: 930 : if (var->varno == var1varno && var->varattno == var1attno)
2199 2771 : 345 : item1_em = em;
3792 2772 [ + + + + ]: 585 : else if (var->varno == var2varno && var->varattno == var2attno)
2199 2773 : 345 : item2_em = em;
2774 : :
2775 : : /* Have we found both PK and FK column in this EC? */
2776 [ + + + + ]: 930 : if (item1_em && item2_em)
2777 : : {
2778 : : /*
2779 : : * Succeed if eqop matches EC's opfamilies. We could test
2780 : : * this before scanning the members, but it's probably cheaper
2781 : : * to test for member matches first.
2782 : : */
3792 2783 [ + - ]: 345 : if (opfamilies == NIL) /* compute if we didn't already */
2784 : 345 : opfamilies = get_mergejoin_opfamilies(eqop);
2785 [ + - ]: 345 : if (equal(opfamilies, ec->ec_opfamilies))
2786 : : {
2199 2787 : 345 : fkinfo->eclass[colno] = ec;
2788 : 345 : fkinfo->fk_eclass_member[colno] = item2_em;
3792 2789 : 345 : return ec;
2790 : : }
2791 : : /* Otherwise, done with this EC, move on to the next */
3792 tgl@sss.pgh.pa.us 2792 :UBC 0 : break;
2793 : : }
2794 : : }
2795 : : }
3792 tgl@sss.pgh.pa.us 2796 :CBC 1598 : return NULL;
2797 : : }
2798 : :
2799 : : /*
2800 : : * find_derived_clause_for_ec_member
2801 : : * Search for a previously-derived clause mentioning the given EM.
2802 : : *
2803 : : * The eclass should be an ec_has_const EC, of which the EM is a non-const
2804 : : * member. This should ensure there is just one derived clause mentioning
2805 : : * the EM (and equating it to a constant).
2806 : : * Returns NULL if no such clause can be found.
2807 : : */
2808 : : RestrictInfo *
580 amitlan@postgresql.o 2809 : 5 : find_derived_clause_for_ec_member(PlannerInfo *root,
2810 : : EquivalenceClass *ec,
2811 : : EquivalenceMember *em)
2812 : : {
2199 tgl@sss.pgh.pa.us 2813 [ - + ]: 5 : Assert(ec->ec_has_const);
2814 [ - + ]: 5 : Assert(!em->em_is_const);
2815 : :
580 amitlan@postgresql.o 2816 : 5 : return ec_search_derived_clause_for_ems(root, ec, em, NULL, NULL);
2817 : : }
2818 : :
2819 : :
2820 : : /*
2821 : : * add_child_rel_equivalences
2822 : : * Search for EC members that reference the root parent of child_rel, and
2823 : : * add transformed members referencing the child_rel.
2824 : : *
2825 : : * Note that this function won't be called at all unless we have at least some
2826 : : * reason to believe that the EC members it generates will be useful.
2827 : : *
2828 : : * parent_rel and child_rel could be derived from appinfo, but since the
2829 : : * caller has already computed them, we might as well just pass them in.
2830 : : *
2831 : : * The passed-in AppendRelInfo is not used when the parent_rel is not a
2832 : : * top-level baserel, since it shows the mapping from the parent_rel but
2833 : : * we need to translate EC expressions that refer to the top-level parent.
2834 : : * Using it is faster than using adjust_appendrel_attrs_multilevel(), though,
2835 : : * so we prefer it when we can.
2836 : : */
2837 : : void
7229 tgl@sss.pgh.pa.us 2838 : 28470 : add_child_rel_equivalences(PlannerInfo *root,
2839 : : AppendRelInfo *appinfo,
2840 : : RelOptInfo *parent_rel,
2841 : : RelOptInfo *child_rel)
2842 : : {
2557 2843 : 28470 : Relids top_parent_relids = child_rel->top_parent_relids;
2844 : 28470 : Relids child_relids = child_rel->relids;
2845 : : int i;
2846 : :
2847 : : /*
2848 : : * EC merging should be complete already, so we can use the parent rel's
2849 : : * eclass_indexes to avoid searching all of root->eq_classes.
2850 : : */
2664 drowley@postgresql.o 2851 [ - + ]: 28470 : Assert(root->ec_merging_done);
2852 [ + + - + ]: 28470 : Assert(IS_SIMPLE_REL(parent_rel));
2853 : :
2854 : 28470 : i = -1;
2855 [ + + ]: 80588 : while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
2856 : : {
2857 : 52118 : EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2858 : :
2859 : : /*
2860 : : * If this EC contains a volatile expression, then generating child
2861 : : * EMs would be downright dangerous, so skip it. We rely on a
2862 : : * volatile EC having only one EM.
2863 : : */
5361 tgl@sss.pgh.pa.us 2864 [ - + ]: 52118 : if (cur_ec->ec_has_volatile)
7229 tgl@sss.pgh.pa.us 2865 :UBC 0 : continue;
2866 : :
2867 : : /* Sanity check eclass_indexes only contain ECs for parent_rel */
2557 tgl@sss.pgh.pa.us 2868 [ - + ]:CBC 52118 : Assert(bms_is_subset(top_parent_relids, cur_ec->ec_relids));
2869 : :
576 drowley@postgresql.o 2870 [ + - + + : 179730 : foreach_node(EquivalenceMember, cur_em, cur_ec->ec_members)
+ + ]
2871 : : {
4605 tgl@sss.pgh.pa.us 2872 [ + + ]: 75494 : if (cur_em->em_is_const)
2873 : 2882 : continue; /* ignore consts here */
2874 : :
2875 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 2876 [ - + ]: 72612 : Assert(!cur_em->em_is_child);
2877 : :
2878 : : /*
2879 : : * Consider only members that reference and can be computed at
2880 : : * child's topmost parent rel. In particular we want to exclude
2881 : : * parent-rel Vars that have nonempty varnullingrels. Translating
2882 : : * those might fail, if the transformed expression wouldn't be a
2883 : : * simple Var; and in any case it wouldn't produce a member that
2884 : : * has any use in creating plans for the child rel.
2885 : : */
1375 tgl@sss.pgh.pa.us 2886 [ + + ]: 72612 : if (bms_is_subset(cur_em->em_relids, top_parent_relids) &&
2887 [ + - ]: 50039 : !bms_is_empty(cur_em->em_relids))
2888 : : {
2889 : : /* OK, generate transformed child version */
2890 : : Expr *child_expr;
2891 : :
2702 2892 [ + + ]: 50039 : if (parent_rel->reloptkind == RELOPT_BASEREL)
2893 : : {
2894 : : /* Simple single-level transformation */
2895 : : child_expr = (Expr *)
2896 : 42842 : adjust_appendrel_attrs(root,
2897 : 42842 : (Node *) cur_em->em_expr,
2898 : : 1, &appinfo);
2899 : : }
2900 : : else
2901 : : {
2902 : : /* Must do multi-level transformation */
2903 : : child_expr = (Expr *)
2904 : 7197 : adjust_appendrel_attrs_multilevel(root,
2905 : 7197 : (Node *) cur_em->em_expr,
2906 : : child_rel,
1540 2907 : 7197 : child_rel->top_parent);
2908 : : }
2909 : :
2910 : : /*
2911 : : * The member's relids are all within the parent, so the child
2912 : : * version's relids are just the child's. Note we do *not* do
2913 : : * pull_varnos(child_expr) here, as for example the
2914 : : * transformation might have substituted a constant, but we
2915 : : * don't want the child member to be marked as constant.
2916 : : */
576 drowley@postgresql.o 2917 : 50039 : add_child_eq_member(root,
2918 : : cur_ec,
2919 : : i,
2920 : : child_expr,
2921 : : bms_copy(child_relids),
2922 : : cur_em->em_jdomain,
2923 : : cur_em,
2924 : : cur_em->em_datatype,
2925 : : child_rel->relid);
2926 : : }
2927 : : }
2928 : : }
7229 tgl@sss.pgh.pa.us 2929 : 28470 : }
2930 : :
2931 : : /*
2932 : : * add_child_join_rel_equivalences
2933 : : * Like add_child_rel_equivalences(), but for joinrels
2934 : : *
2935 : : * Here we find the ECs relevant to the top parent joinrel and add transformed
2936 : : * member expressions that refer to this child joinrel.
2937 : : *
2938 : : * Note that this function won't be called at all unless we have at least some
2939 : : * reason to believe that the EC members it generates will be useful.
2940 : : */
2941 : : void
2557 2942 : 21365 : add_child_join_rel_equivalences(PlannerInfo *root,
2943 : : int nappinfos, AppendRelInfo **appinfos,
2944 : : RelOptInfo *parent_joinrel,
2945 : : RelOptInfo *child_joinrel)
2946 : : {
2947 : 21365 : Relids top_parent_relids = child_joinrel->top_parent_relids;
2948 : 21365 : Relids child_relids = child_joinrel->relids;
2949 : : Bitmapset *matching_ecs;
2950 : : MemoryContext oldcontext;
2951 : : int i;
2952 : :
2953 [ + - + - : 21365 : Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
+ + - + ]
2954 : :
2955 : : /* We need consider only ECs that mention the parent joinrel */
2956 : 21365 : matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
2957 : :
2958 : : /*
2959 : : * If we're being called during GEQO join planning, we still have to
2960 : : * create any new EC members in the main planner context, to avoid having
2961 : : * a corrupt EC data structure after the GEQO context is reset. This is
2962 : : * problematic since we'll leak memory across repeated GEQO cycles. For
2963 : : * now, though, bloat is better than crash. If it becomes a real issue
2964 : : * we'll have to do something to avoid generating duplicate EC members.
2965 : : */
2221 2966 : 21365 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2967 : :
2557 2968 : 21365 : i = -1;
2969 [ + + ]: 64761 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
2970 : : {
2971 : 43396 : EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2972 : :
2973 : : /*
2974 : : * If this EC contains a volatile expression, then generating child
2975 : : * EMs would be downright dangerous, so skip it. We rely on a
2976 : : * volatile EC having only one EM.
2977 : : */
2978 [ - + ]: 43396 : if (cur_ec->ec_has_volatile)
2557 tgl@sss.pgh.pa.us 2979 :UBC 0 : continue;
2980 : :
2981 : : /* Sanity check on get_eclass_indexes_for_relids result */
2557 tgl@sss.pgh.pa.us 2982 [ - + ]:CBC 43396 : Assert(bms_overlap(top_parent_relids, cur_ec->ec_relids));
2983 : :
576 drowley@postgresql.o 2984 [ + - + + : 172602 : foreach_node(EquivalenceMember, cur_em, cur_ec->ec_members)
+ + ]
2985 : : {
2557 tgl@sss.pgh.pa.us 2986 [ + + ]: 85810 : if (cur_em->em_is_const)
2987 : 7298 : continue; /* ignore consts here */
2988 : :
2989 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 2990 [ - + ]: 78512 : Assert(!cur_em->em_is_child);
2991 : :
2992 : : /*
2993 : : * We may ignore expressions that reference a single baserel,
2994 : : * because add_child_rel_equivalences should have handled them.
2995 : : */
2557 tgl@sss.pgh.pa.us 2996 [ + + ]: 78512 : if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
2997 : 69975 : continue;
2998 : :
2999 : : /*
3000 : : * Consider only members that can be computed at child's topmost
3001 : : * parent joinrel, as in add_child_rel_equivalences.
3002 : : */
10 rguo@postgresql.org 3003 [ + + ]: 8537 : if (bms_is_subset(cur_em->em_relids, top_parent_relids))
3004 : : {
3005 : : /* OK, generate transformed child version */
3006 : : Expr *child_expr;
3007 : :
2557 tgl@sss.pgh.pa.us 3008 [ + + ]: 5687 : if (parent_joinrel->reloptkind == RELOPT_JOINREL)
3009 : : {
3010 : : /* Simple single-level transformation */
3011 : : child_expr = (Expr *)
3012 : 5607 : adjust_appendrel_attrs(root,
3013 : 5607 : (Node *) cur_em->em_expr,
3014 : : nappinfos, appinfos);
3015 : : }
3016 : : else
3017 : : {
3018 : : /* Must do multi-level transformation */
3019 [ - + ]: 80 : Assert(parent_joinrel->reloptkind == RELOPT_OTHER_JOINREL);
3020 : : child_expr = (Expr *)
3021 : 80 : adjust_appendrel_attrs_multilevel(root,
3022 : 80 : (Node *) cur_em->em_expr,
3023 : : child_joinrel,
1540 3024 : 80 : child_joinrel->top_parent);
3025 : : }
3026 : :
3027 : : /*
3028 : : * Add new child member to the EquivalenceClass. Because this
3029 : : * is a RELOPT_OTHER_JOINREL which has multiple component
3030 : : * relids, there is no ideal place to store these members in
3031 : : * the class. Ordinarily, child members are stored in the
3032 : : * ec_childmembers[] array element corresponding to their
3033 : : * relid, however, here we have multiple component relids, so
3034 : : * there's no single ec_childmembers[] array element to store
3035 : : * this member. So that we still correctly find this member
3036 : : * in loops iterating over an EquivalenceMemberIterator, we
3037 : : * opt to store the member in the ec_childmembers array in
3038 : : * only the first component relid slot of the array. This
3039 : : * allows the member to be found, providing callers of
3040 : : * setup_eclass_member_iterator() specify all the component
3041 : : * relids for the RELOPT_OTHER_JOINREL, which they do. If we
3042 : : * opted to store the member in each ec_childmembers[] element
3043 : : * for all the component relids, then that would just result
3044 : : * in eclass_member_iterator_next() finding the member
3045 : : * multiple times, which is a waste of effort.
3046 : : *
3047 : : * As in add_child_rel_equivalences, the child member's relids
3048 : : * are just the child's.
3049 : : */
576 drowley@postgresql.o 3050 : 5687 : add_child_eq_member(root,
3051 : : cur_ec,
3052 : : -1,
3053 : : child_expr,
3054 : : bms_copy(child_relids),
3055 : : cur_em->em_jdomain,
3056 : : cur_em,
3057 : : cur_em->em_datatype,
3058 : 5687 : bms_next_member(child_joinrel->relids, -1));
3059 : : }
3060 : : }
3061 : : }
3062 : :
2221 tgl@sss.pgh.pa.us 3063 : 21365 : MemoryContextSwitchTo(oldcontext);
2557 3064 : 21365 : }
3065 : :
3066 : : /*
3067 : : * add_child_rel_pathkey_equivalences
3068 : : * Make sure the ECs of the given pathkeys have members for child_rel.
3069 : : *
3070 : : * An EC created after its relations' children were processed has no child
3071 : : * members, so child_rel could not be sorted by it. Add them here.
3072 : : */
3073 : : void
30 rguo@postgresql.org 3074 : 590 : add_child_rel_pathkey_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
3075 : : List *pathkeys)
3076 : : {
3077 : 590 : Relids top_parent_relids = child_rel->top_parent_relids;
3078 : : MemoryContext oldcontext;
3079 : : ListCell *lc;
3080 : :
3081 [ + + - + : 590 : Assert(IS_OTHER_REL(child_rel));
- - ]
3082 : :
3083 : : /* As in add_child_join_rel_equivalences, new members must survive GEQO */
3084 : 590 : oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3085 : :
3086 [ + - + + : 1340 : foreach(lc, pathkeys)
+ + ]
3087 : : {
3088 : 750 : EquivalenceClass *ec = lfirst_node(PathKey, lc)->pk_eclass;
3089 : :
3090 [ - + ]: 750 : if (ec->ec_has_volatile)
30 rguo@postgresql.org 3091 :UBC 0 : continue;
3092 : :
30 rguo@postgresql.org 3093 [ + - + + :CBC 3040 : foreach_node(EquivalenceMember, cur_em, ec->ec_members)
+ + ]
3094 : : {
3095 : : EquivalenceMemberIterator it;
3096 : : EquivalenceMember *em;
3097 : : Expr *child_expr;
3098 : : Relids new_relids;
3099 : : int child_relid;
3100 : :
3101 : : /* Consider only members computable at the topmost parent */
3102 [ + - ]: 1540 : if (cur_em->em_is_const ||
3103 [ + + ]: 1540 : !bms_is_subset(cur_em->em_relids, top_parent_relids))
3104 : 1480 : continue;
3105 : :
3106 : : /* Skip members that already have a child version for this rel */
3107 : 950 : setup_eclass_member_iterator(&it, ec, child_rel->relids);
3108 [ + + ]: 4240 : while ((em = eclass_member_iterator_next(&it)) != NULL)
3109 : : {
3110 [ + + + - ]: 4120 : if (em->em_parent == cur_em &&
3111 : 890 : bms_is_subset(em->em_relids, child_rel->relids))
3112 : 890 : break;
3113 : : }
3114 [ + + ]: 950 : if (em != NULL)
3115 : 890 : continue;
3116 : :
3117 : 60 : new_relids = adjust_child_relids_multilevel(root,
3118 : : cur_em->em_relids,
3119 : : child_rel,
3120 : 60 : child_rel->top_parent);
3121 : :
3122 : : /* Store the member under one of its child relations */
3123 : 60 : child_relid = bms_next_member(bms_difference(new_relids,
3124 : : top_parent_relids),
3125 : : -1);
3126 [ - + ]: 60 : if (child_relid < 0)
30 rguo@postgresql.org 3127 :UBC 0 : continue;
3128 : :
3129 : : child_expr = (Expr *)
30 rguo@postgresql.org 3130 :CBC 60 : adjust_appendrel_attrs_multilevel(root,
3131 : 60 : (Node *) cur_em->em_expr,
3132 : : child_rel,
3133 : 60 : child_rel->top_parent);
3134 : :
3135 : 60 : add_child_eq_member(root, ec, -1, child_expr, new_relids,
3136 : : cur_em->em_jdomain, cur_em,
3137 : : cur_em->em_datatype, child_relid);
3138 : : }
3139 : : }
3140 : :
3141 : 590 : MemoryContextSwitchTo(oldcontext);
3142 : 590 : }
3143 : :
3144 : : /*
3145 : : * add_setop_child_rel_equivalences
3146 : : * Add equivalence members for each non-resjunk target in 'child_tlist'
3147 : : * to the EquivalenceClass in the corresponding setop_pathkey's pk_eclass.
3148 : : *
3149 : : * 'root' is the PlannerInfo belonging to the top-level set operation.
3150 : : * 'child_rel' is the RelOptInfo of the child relation we're adding
3151 : : * EquivalenceMembers for.
3152 : : * 'child_tlist' is the target list for the setop child relation. The target
3153 : : * list expressions are what we add as EquivalenceMembers.
3154 : : * 'setop_pathkeys' is a list of PathKeys which must contain an entry for each
3155 : : * non-resjunk target in 'child_tlist'.
3156 : : */
3157 : : void
898 rhaas@postgresql.org 3158 : 10400 : add_setop_child_rel_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
3159 : : List *child_tlist, List *setop_pathkeys)
3160 : : {
3161 : : ListCell *lc;
3162 : 10400 : ListCell *lc2 = list_head(setop_pathkeys);
3163 : :
3164 [ + - + + : 42288 : foreach(lc, child_tlist)
+ + ]
3165 : : {
3166 : 31888 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
3167 : : EquivalenceMember *parent_em;
3168 : : PathKey *pk;
3169 : :
3170 [ - + ]: 31888 : if (tle->resjunk)
898 rhaas@postgresql.org 3171 :UBC 0 : continue;
3172 : :
898 rhaas@postgresql.org 3173 [ - + ]:CBC 31888 : if (lc2 == NULL)
898 rhaas@postgresql.org 3174 [ # # ]:UBC 0 : elog(ERROR, "too few pathkeys for set operation");
3175 : :
898 rhaas@postgresql.org 3176 :CBC 31888 : pk = lfirst_node(PathKey, lc2);
3177 : 31888 : parent_em = linitial(pk->pk_eclass->ec_members);
3178 : :
3179 : : /*
3180 : : * We can safely pass the parent member as the first member in the
3181 : : * ec_members list as this is added first in generate_union_paths,
3182 : : * likewise, the JoinDomain can be that of the initial member of the
3183 : : * Pathkey's EquivalenceClass. We pass -1 for ec_index since we
3184 : : * maintain the eclass_indexes for the child_rel after the loop.
3185 : : */
576 drowley@postgresql.o 3186 : 31888 : add_child_eq_member(root,
3187 : : pk->pk_eclass,
3188 : : -1,
3189 : : tle->expr,
3190 : : child_rel->relids,
3191 : : parent_em->em_jdomain,
3192 : : parent_em,
3193 : 31888 : exprType((Node *) tle->expr),
3194 : : child_rel->relid);
3195 : :
898 rhaas@postgresql.org 3196 : 31888 : lc2 = lnext(setop_pathkeys, lc2);
3197 : : }
3198 : :
3199 : : /*
3200 : : * transformSetOperationStmt() ensures that the targetlist never contains
3201 : : * any resjunk columns, so all eclasses that exist in 'root' must have
3202 : : * received a new member in the loop above. Add them to the child_rel's
3203 : : * eclass_indexes.
3204 : : */
3205 : 10400 : child_rel->eclass_indexes = bms_add_range(child_rel->eclass_indexes, 0,
3206 : 10400 : list_length(root->eq_classes) - 1);
3207 : 10400 : }
3208 : :
3209 : : /*
3210 : : * setup_eclass_member_iterator
3211 : : * Setup an EquivalenceMemberIterator 'it' to iterate over all parent
3212 : : * EquivalenceMembers and child members belonging to the given 'ec'.
3213 : : *
3214 : : * This iterator returns:
3215 : : * - All parent members stored directly in ec_members for 'ec', and;
3216 : : * - Any child member added to the given ec by add_child_eq_member() where
3217 : : * the child_relid specified in the add_child_eq_member() call is a member
3218 : : * of the 'child_relids' parameter.
3219 : : *
3220 : : * Note:
3221 : : * The given 'child_relids' must remain allocated and not be changed for the
3222 : : * lifetime of the iterator.
3223 : : *
3224 : : * Parameters:
3225 : : * 'it' is a pointer to the iterator to set up. Normally stack allocated.
3226 : : * 'ec' is the EquivalenceClass from which to iterate members for.
3227 : : * 'child_relids' is the relids to return child members for.
3228 : : */
3229 : : void
576 drowley@postgresql.o 3230 : 3986446 : setup_eclass_member_iterator(EquivalenceMemberIterator *it,
3231 : : EquivalenceClass *ec, Relids child_relids)
3232 : : {
3233 : 3986446 : it->ec = ec;
3234 : : /* no need to set this if the class has no child members array set */
3235 [ + + ]: 3986446 : it->child_relids = ec->ec_childmembers != NULL ? child_relids : NULL;
3236 : 3986446 : it->current_relid = -1;
3237 : 3986446 : it->current_list = ec->ec_members;
3238 : 3986446 : it->current_cell = list_head(it->current_list);
3239 : 3986446 : }
3240 : :
3241 : : /*
3242 : : * eclass_member_iterator_next
3243 : : * Get the next EquivalenceMember from the EquivalenceMemberIterator 'it',
3244 : : * as setup by setup_eclass_member_iterator(). NULL is returned if there
3245 : : * are no members left, after which callers must not call
3246 : : * eclass_member_iterator_next() again for the given iterator.
3247 : : */
3248 : : EquivalenceMember *
3249 : 9440179 : eclass_member_iterator_next(EquivalenceMemberIterator *it)
3250 : : {
3251 [ + - ]: 9440179 : while (it->current_list != NULL)
3252 : : {
3253 [ + + ]: 9440179 : while (it->current_cell != NULL)
3254 : : {
3255 : : EquivalenceMember *em;
3256 : :
3257 : 6555638 : nextcell:
3258 : 6684007 : em = lfirst_node(EquivalenceMember, it->current_cell);
3259 : 6684007 : it->current_cell = lnext(it->current_list, it->current_cell);
3260 : 6684007 : return em;
3261 : : }
3262 : :
3263 : : /* Search for the next list to return members from */
3264 [ + + ]: 3024410 : while ((it->current_relid = bms_next_member(it->child_relids, it->current_relid)) > 0)
3265 : : {
3266 : : /*
3267 : : * Be paranoid in case we're given relids above what we've sized
3268 : : * the ec_childmembers array to.
3269 : : */
3270 [ - + ]: 268238 : if (it->current_relid >= it->ec->ec_childmembers_size)
576 drowley@postgresql.o 3271 :UBC 0 : return NULL;
3272 : :
576 drowley@postgresql.o 3273 :CBC 268238 : it->current_list = it->ec->ec_childmembers[it->current_relid];
3274 : :
3275 : : /* If there are members in this list, use it. */
3276 [ + + ]: 268238 : if (it->current_list != NIL)
3277 : : {
3278 : : /* point current_cell to the head of this list */
3279 : 128369 : it->current_cell = list_head(it->current_list);
3280 : 128369 : goto nextcell;
3281 : : }
3282 : : }
3283 : 2756172 : return NULL;
3284 : : }
3285 : :
576 drowley@postgresql.o 3286 :UBC 0 : return NULL;
3287 : : }
3288 : :
3289 : : /*
3290 : : * generate_implied_equalities_for_column
3291 : : * Create EC-derived joinclauses usable with a specific column.
3292 : : *
3293 : : * This is used by indxpath.c to extract potentially indexable joinclauses
3294 : : * from ECs, and can be used by foreign data wrappers for similar purposes.
3295 : : * We assume that only expressions in Vars of a single table are of interest,
3296 : : * but the caller provides a callback function to identify exactly which
3297 : : * such expressions it would like to know about.
3298 : : *
3299 : : * We assume that any given table/index column could appear in only one EC.
3300 : : * (This should be true in all but the most pathological cases, and if it
3301 : : * isn't, we stop on the first match anyway.) Therefore, what we return
3302 : : * is a redundant list of clauses equating the table/index column to each of
3303 : : * the other-relation values it is known to be equal to. Any one of
3304 : : * these clauses can be used to create a parameterized path, and there
3305 : : * is no value in using more than one. (But it *is* worthwhile to create
3306 : : * a separate parameterized path for each one, since that leads to different
3307 : : * join orders.)
3308 : : *
3309 : : * The caller can pass a Relids set of rels we aren't interested in joining
3310 : : * to, so as to save the work of creating useless clauses.
3311 : : */
3312 : : List *
4977 tgl@sss.pgh.pa.us 3313 :CBC 465563 : generate_implied_equalities_for_column(PlannerInfo *root,
3314 : : RelOptInfo *rel,
3315 : : ec_matches_callback_type callback,
3316 : : void *callback_arg,
3317 : : Relids prohibited_rels)
3318 : : {
7229 3319 : 465563 : List *result = NIL;
3320 : 465563 : bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
3321 : : Relids parent_relids;
3322 : : int i;
3323 : :
3324 : : /* Should be OK to rely on eclass_indexes */
2664 drowley@postgresql.o 3325 [ - + ]: 465563 : Assert(root->ec_merging_done);
3326 : :
3327 : : /* Indexes are available only on base or "other" member relations. */
3503 rhaas@postgresql.org 3328 [ + + - + ]: 465563 : Assert(IS_SIMPLE_REL(rel));
3329 : :
3330 : : /* If it's a child rel, we'll need to know what its parent(s) are */
5396 tgl@sss.pgh.pa.us 3331 [ + + ]: 465563 : if (is_child_rel)
4418 3332 : 10696 : parent_relids = find_childrel_parents(root, rel);
3333 : : else
3334 : 454867 : parent_relids = NULL; /* not used, but keep compiler quiet */
3335 : :
2664 drowley@postgresql.o 3336 : 465563 : i = -1;
3337 [ + + ]: 1339877 : while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
3338 : : {
3339 : 970374 : EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
3340 : : EquivalenceMemberIterator it;
3341 : : EquivalenceMember *cur_em;
3342 : : ListCell *lc2;
3343 : :
3344 : : /* Sanity check eclass_indexes only contain ECs for rel */
3345 [ + + - + ]: 970374 : Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
3346 : :
3347 : : /*
3348 : : * Won't generate joinclauses if const or single-member (the latter
3349 : : * test covers the volatile case too)
3350 : : */
7229 tgl@sss.pgh.pa.us 3351 [ + + + + ]: 970374 : if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
3352 : 874154 : continue;
3353 : :
3354 : : /*
3355 : : * Scan members, looking for a match to the target column. Note that
3356 : : * child EC members are considered, but only when they belong to the
3357 : : * target relation. (Unlike regular members, the same expression
3358 : : * could be a child member of more than one EC. Therefore, it's
3359 : : * potentially order-dependent which EC a child relation's target
3360 : : * column gets matched to. This is annoying but it only happens in
3361 : : * corner cases, so for now we live with just reporting the first
3362 : : * match. See also get_eclass_for_sort_expr.)
3363 : : */
576 drowley@postgresql.o 3364 : 461081 : setup_eclass_member_iterator(&it, cur_ec, rel->relids);
3365 [ + + ]: 1734232 : while ((cur_em = eclass_member_iterator_next(&it)) != NULL)
3366 : : {
5396 tgl@sss.pgh.pa.us 3367 [ + + + + ]: 1369409 : if (bms_equal(cur_em->em_relids, rel->relids) &&
4977 3368 : 461119 : callback(root, rel, cur_ec, cur_em, callback_arg))
5396 3369 : 96220 : break;
3370 : : }
3371 : :
3372 [ + + ]: 461081 : if (!cur_em)
7229 3373 : 364861 : continue;
3374 : :
3375 : : /*
3376 : : * Found our match. Scan the other EC members and attempt to generate
3377 : : * joinclauses. Ignore children here.
3378 : : */
3379 [ + - + + : 294267 : foreach(lc2, cur_ec->ec_members)
+ + ]
3380 : : {
5396 3381 : 198047 : EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
3382 : : Oid eq_op;
3383 : : RestrictInfo *rinfo;
3384 : :
3385 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 3386 [ - + ]: 198047 : Assert(!other_em->em_is_child);
3387 : :
3388 : : /* Make sure it'll be a join to a different rel */
5396 tgl@sss.pgh.pa.us 3389 [ + + + + ]: 303066 : if (other_em == cur_em ||
3390 : 105019 : bms_overlap(other_em->em_relids, rel->relids))
7229 3391 : 93113 : continue;
3392 : :
3393 : : /* Forget it if caller doesn't want joins to this rel */
5180 3394 [ + + ]: 104934 : if (bms_overlap(other_em->em_relids, prohibited_rels))
3395 : 130 : continue;
3396 : :
3397 : : /*
3398 : : * Also, if this is a child rel, avoid generating a useless join
3399 : : * to its parent rel(s).
3400 : : */
5396 3401 [ + + + + ]: 112135 : if (is_child_rel &&
4418 3402 : 7331 : bms_overlap(parent_relids, other_em->em_relids))
5396 3403 : 3322 : continue;
3404 : :
3405 : 101482 : eq_op = select_equality_operator(cur_ec,
3406 : : cur_em->em_datatype,
3407 : : other_em->em_datatype);
3408 [ - + ]: 101482 : if (!OidIsValid(eq_op))
5396 tgl@sss.pgh.pa.us 3409 :UBC 0 : continue;
3410 : :
3411 : : /* set parent_ec to mark as redundant with other joinclauses */
5396 tgl@sss.pgh.pa.us 3412 :CBC 101482 : rinfo = create_join_clause(root, cur_ec, eq_op,
3413 : : cur_em, other_em,
3414 : : cur_ec);
3415 : :
3416 : 101482 : result = lappend(result, rinfo);
3417 : : }
3418 : :
3419 : : /*
3420 : : * If somehow we failed to create any join clauses, we might as well
3421 : : * keep scanning the ECs for another match. But if we did make any,
3422 : : * we're done, because we don't want to return non-redundant clauses.
3423 : : */
3424 [ + + ]: 96220 : if (result)
3425 : 96060 : break;
3426 : : }
3427 : :
7229 3428 : 465563 : return result;
3429 : : }
3430 : :
3431 : : /*
3432 : : * have_relevant_eclass_joinclause
3433 : : * Detect whether there is an EquivalenceClass that could produce
3434 : : * a joinclause involving the two given relations.
3435 : : *
3436 : : * This is essentially a very cut-down version of
3437 : : * generate_join_implied_equalities(). Note it's OK to occasionally say "yes"
3438 : : * incorrectly. Hence we don't bother with details like whether the lack of a
3439 : : * cross-type operator might prevent the clause from actually being generated.
3440 : : * False negatives are not always fatal either: they will discourage, but not
3441 : : * completely prevent, investigation of particular join pathways.
3442 : : */
3443 : : bool
3444 : 155419 : have_relevant_eclass_joinclause(PlannerInfo *root,
3445 : : RelOptInfo *rel1, RelOptInfo *rel2)
3446 : : {
3447 : : Bitmapset *matching_ecs;
3448 : : int i;
3449 : :
3450 : : /*
3451 : : * Examine only eclasses mentioning both rel1 and rel2.
3452 : : *
3453 : : * Note that we do not consider the possibility of an eclass generating
3454 : : * "join" clauses that mention just one of the rels plus an outer join
3455 : : * that could be formed from them. Although such clauses must be
3456 : : * correctly enforced when we form the outer join, they don't seem like
3457 : : * sufficient reason to prioritize this join over other ones. The join
3458 : : * ordering rules will force the join to be made when necessary.
3459 : : */
2664 drowley@postgresql.o 3460 : 155419 : matching_ecs = get_common_eclass_indexes(root, rel1->relids,
3461 : : rel2->relids);
3462 : :
3463 : 155419 : i = -1;
3464 [ + + ]: 155479 : while ((i = bms_next_member(matching_ecs, i)) >= 0)
3465 : : {
3466 : 132954 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
3467 : : i);
3468 : :
3469 : : /*
3470 : : * Sanity check that get_common_eclass_indexes gave only ECs
3471 : : * containing both rels.
3472 : : */
3473 [ - + ]: 132954 : Assert(bms_overlap(rel1->relids, ec->ec_relids));
3474 [ - + ]: 132954 : Assert(bms_overlap(rel2->relids, ec->ec_relids));
3475 : :
3476 : : /*
3477 : : * Won't generate joinclauses if single-member (this test covers the
3478 : : * volatile case too)
3479 : : */
6875 tgl@sss.pgh.pa.us 3480 [ + + ]: 132954 : if (list_length(ec->ec_members) <= 1)
7229 3481 : 60 : continue;
3482 : :
3483 : : /*
3484 : : * We do not need to examine the individual members of the EC, because
3485 : : * all that we care about is whether each rel overlaps the relids of
3486 : : * at least one member, and get_common_eclass_indexes() and the single
3487 : : * member check above are sufficient to prove that. (As with
3488 : : * have_relevant_joinclause(), it is not necessary that the EC be able
3489 : : * to form a joinclause relating exactly the two given rels, only that
3490 : : * it be able to form a joinclause mentioning both, and this will
3491 : : * surely be true if both of them overlap ec_relids.)
3492 : : *
3493 : : * Note we don't test ec_broken; if we did, we'd need a separate code
3494 : : * path to look through ec_sources. Checking the membership anyway is
3495 : : * OK as a possibly-overoptimistic heuristic.
3496 : : *
3497 : : * We don't test ec_has_const either, even though a const eclass won't
3498 : : * generate real join clauses. This is because if we had "WHERE a.x =
3499 : : * b.y and a.x = 42", it is worth considering a join between a and b,
3500 : : * since the join result is likely to be small even though it'll end
3501 : : * up being an unqualified nestloop.
3502 : : */
3503 : :
2664 drowley@postgresql.o 3504 : 132894 : return true;
3505 : : }
3506 : :
7229 tgl@sss.pgh.pa.us 3507 : 22525 : return false;
3508 : : }
3509 : :
3510 : :
3511 : : /*
3512 : : * has_relevant_eclass_joinclause
3513 : : * Detect whether there is an EquivalenceClass that could produce
3514 : : * a joinclause involving the given relation and anything else.
3515 : : *
3516 : : * This is the same as have_relevant_eclass_joinclause with the other rel
3517 : : * implicitly defined as "everything else in the query".
3518 : : */
3519 : : bool
3520 : 176560 : has_relevant_eclass_joinclause(PlannerInfo *root, RelOptInfo *rel1)
3521 : : {
3522 : : Bitmapset *matched_ecs;
3523 : : int i;
3524 : :
3525 : : /* Examine only eclasses mentioning rel1 */
2664 drowley@postgresql.o 3526 : 176560 : matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
3527 : :
3528 : 176560 : i = -1;
3529 [ + + ]: 604183 : while ((i = bms_next_member(matched_ecs, i)) >= 0)
3530 : : {
3531 : 495026 : EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
3532 : : i);
3533 : :
3534 : : /*
3535 : : * Won't generate joinclauses if single-member (this test covers the
3536 : : * volatile case too)
3537 : : */
6875 tgl@sss.pgh.pa.us 3538 [ + + ]: 495026 : if (list_length(ec->ec_members) <= 1)
7229 3539 : 218607 : continue;
3540 : :
3541 : : /*
3542 : : * Per the comment in have_relevant_eclass_joinclause, it's sufficient
3543 : : * to find an EC that mentions both this rel and some other rel.
3544 : : */
2664 drowley@postgresql.o 3545 [ + + ]: 276419 : if (!bms_is_subset(ec->ec_relids, rel1->relids))
7229 tgl@sss.pgh.pa.us 3546 : 67403 : return true;
3547 : : }
3548 : :
3549 : 109157 : return false;
3550 : : }
3551 : :
3552 : :
3553 : : /*
3554 : : * eclass_useful_for_merging
3555 : : * Detect whether the EC could produce any mergejoinable join clauses
3556 : : * against the specified relation.
3557 : : *
3558 : : * This is just a heuristic test and doesn't have to be exact; it's better
3559 : : * to say "yes" incorrectly than "no". Hence we don't bother with details
3560 : : * like whether the lack of a cross-type operator might prevent the clause
3561 : : * from actually being generated.
3562 : : */
3563 : : bool
4109 3564 : 583320 : eclass_useful_for_merging(PlannerInfo *root,
3565 : : EquivalenceClass *eclass,
3566 : : RelOptInfo *rel)
3567 : : {
3568 : : Relids relids;
3569 : : ListCell *lc;
3570 : :
7229 3571 [ - + ]: 583320 : Assert(!eclass->ec_merged);
3572 : :
3573 : : /*
3574 : : * Won't generate joinclauses if const or single-member (the latter test
3575 : : * covers the volatile case too)
3576 : : */
3577 [ + + + + ]: 583320 : if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
3578 : 30783 : return false;
3579 : :
3580 : : /*
3581 : : * Note we don't test ec_broken; if we did, we'd need a separate code path
3582 : : * to look through ec_sources. Checking the members anyway is OK as a
3583 : : * possibly-overoptimistic heuristic.
3584 : : */
3585 : :
3586 : : /* If specified rel is a child, we must consider the topmost parent rel */
3503 rhaas@postgresql.org 3587 [ + + + + : 552537 : if (IS_OTHER_REL(rel))
- + ]
3588 : : {
3589 [ - + ]: 14421 : Assert(!bms_is_empty(rel->top_parent_relids));
3590 : 14421 : relids = rel->top_parent_relids;
3591 : : }
3592 : : else
4109 tgl@sss.pgh.pa.us 3593 : 538116 : relids = rel->relids;
3594 : :
3595 : : /* If rel already includes all members of eclass, no point in searching */
3596 [ + + ]: 552537 : if (bms_is_subset(eclass->ec_relids, relids))
7229 3597 : 197847 : return false;
3598 : :
3599 : : /*
3600 : : * To join, we need a member not in the given rel. Ignore children here.
3601 : : */
3602 [ + - + + : 565466 : foreach(lc, eclass->ec_members)
+ + ]
3603 : : {
3604 : 555275 : EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
3605 : :
3606 : : /* Child members should not exist in ec_members */
576 drowley@postgresql.o 3607 [ - + ]: 555275 : Assert(!cur_em->em_is_child);
3608 : :
4109 tgl@sss.pgh.pa.us 3609 [ + + ]: 555275 : if (!bms_overlap(cur_em->em_relids, relids))
7229 3610 : 344499 : return true;
3611 : : }
3612 : :
3613 : 10191 : return false;
3614 : : }
3615 : :
3616 : :
3617 : : /*
3618 : : * is_redundant_derived_clause
3619 : : * Test whether rinfo is derived from same EC as any clause in clauselist;
3620 : : * if so, it can be presumed to represent a condition that's redundant
3621 : : * with that member of the list.
3622 : : */
3623 : : bool
5313 3624 : 70 : is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
3625 : : {
3626 : 70 : EquivalenceClass *parent_ec = rinfo->parent_ec;
3627 : : ListCell *lc;
3628 : :
3629 : : /* Fail if it's not a potentially-redundant clause from some EC */
3630 [ + - ]: 70 : if (parent_ec == NULL)
3631 : 70 : return false;
3632 : :
5313 tgl@sss.pgh.pa.us 3633 [ # # # # :UBC 0 : foreach(lc, clauselist)
# # ]
3634 : : {
3635 : 0 : RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
3636 : :
3637 [ # # ]: 0 : if (otherrinfo->parent_ec == parent_ec)
3638 : 0 : return true;
3639 : : }
3640 : :
3641 : 0 : return false;
3642 : : }
3643 : :
3644 : : /*
3645 : : * is_redundant_with_indexclauses
3646 : : * Test whether rinfo is redundant with any clause in the IndexClause
3647 : : * list. Here, for convenience, we test both simple identity and
3648 : : * whether it is derived from the same EC as any member of the list.
3649 : : */
3650 : : bool
2826 tgl@sss.pgh.pa.us 3651 :CBC 1141560 : is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
3652 : : {
3653 : 1141560 : EquivalenceClass *parent_ec = rinfo->parent_ec;
3654 : : ListCell *lc;
3655 : :
3656 [ + + + + : 1590010 : foreach(lc, indexclauses)
+ + ]
3657 : : {
3658 : 1155814 : IndexClause *iclause = lfirst_node(IndexClause, lc);
3659 : 1155814 : RestrictInfo *otherrinfo = iclause->rinfo;
3660 : :
3661 : : /* If indexclause is lossy, it won't enforce the condition exactly */
3662 [ + + ]: 1155814 : if (iclause->lossy)
3663 : 32494 : continue;
3664 : :
3665 : : /* Match if it's same clause (pointer equality should be enough) */
3666 [ + + ]: 1123320 : if (rinfo == otherrinfo)
3667 : 707364 : return true;
3668 : : /* Match if derived from same EC */
3669 [ + + + + ]: 416440 : if (parent_ec && otherrinfo->parent_ec == parent_ec)
3670 : 484 : return true;
3671 : :
3672 : : /*
3673 : : * No need to look at the derived clauses in iclause->indexquals; they
3674 : : * couldn't match if the parent clause didn't.
3675 : : */
3676 : : }
3677 : :
3678 : 434196 : return false;
3679 : : }
3680 : :
3681 : : /*
3682 : : * get_eclass_indexes_for_relids
3683 : : * Build and return a Bitmapset containing the indexes into root's
3684 : : * eq_classes list for all eclasses that mention any of these relids
3685 : : */
3686 : : static Bitmapset *
2664 drowley@postgresql.o 3687 : 913480 : get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
3688 : : {
3689 : 913480 : Bitmapset *ec_indexes = NULL;
3690 : 913480 : int i = -1;
3691 : :
3692 : : /* Should be OK to rely on eclass_indexes */
3693 [ - + ]: 913480 : Assert(root->ec_merging_done);
3694 : :
3695 [ + + ]: 2863590 : while ((i = bms_next_member(relids, i)) > 0)
3696 : : {
3697 : 1950110 : RelOptInfo *rel = root->simple_rel_array[i];
3698 : :
3699 : : /* ignore the RTE_GROUP RTE */
786 rguo@postgresql.org 3700 [ - + ]: 1950110 : if (i == root->group_rtindex)
786 rguo@postgresql.org 3701 :UBC 0 : continue;
3702 : :
1375 tgl@sss.pgh.pa.us 3703 [ + + ]:CBC 1950110 : if (rel == NULL) /* must be an outer join */
3704 : : {
3705 [ - + ]: 246362 : Assert(bms_is_member(i, root->outer_join_rels));
3706 : 246362 : continue;
3707 : : }
3708 : :
2664 drowley@postgresql.o 3709 : 1703748 : ec_indexes = bms_add_members(ec_indexes, rel->eclass_indexes);
3710 : : }
3711 : 913480 : return ec_indexes;
3712 : : }
3713 : :
3714 : : /*
3715 : : * get_common_eclass_indexes
3716 : : * Build and return a Bitmapset containing the indexes into root's
3717 : : * eq_classes list for all eclasses that mention rels in both
3718 : : * relids1 and relids2.
3719 : : */
3720 : : static Bitmapset *
3721 : 524935 : get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
3722 : : {
3723 : : Bitmapset *rel1ecs;
3724 : : Bitmapset *rel2ecs;
3725 : : int relid;
3726 : :
3727 : 524935 : rel1ecs = get_eclass_indexes_for_relids(root, relids1);
3728 : :
3729 : : /*
3730 : : * We can get away with just using the relation's eclass_indexes directly
3731 : : * when relids2 is a singleton set.
3732 : : */
3733 [ + + ]: 524935 : if (bms_get_singleton_member(relids2, &relid))
3734 : 408780 : rel2ecs = root->simple_rel_array[relid]->eclass_indexes;
3735 : : else
3736 : 116155 : rel2ecs = get_eclass_indexes_for_relids(root, relids2);
3737 : :
3738 : : /* Calculate and return the common EC indexes, recycling the left input. */
3739 : 524935 : return bms_int_members(rel1ecs, rel2ecs);
3740 : : }
3741 : :
3742 : : /*
3743 : : * ec_build_derives_hash
3744 : : * Construct the auxiliary hash table for derived clause lookups.
3745 : : */
3746 : : static void
580 amitlan@postgresql.o 3747 :UBC 0 : ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec)
3748 : : {
3749 [ # # ]: 0 : Assert(!ec->ec_derives_hash);
3750 : :
3751 : : /*
3752 : : * Create the hash table.
3753 : : *
3754 : : * We pass list_length(ec->ec_derives_list) as the initial size.
3755 : : * Simplehash will divide this by the fillfactor (typically 0.9) and round
3756 : : * up to the next power of two, so this will usually give us at least 64
3757 : : * buckets around the threshold. That avoids immediate resizing without
3758 : : * hardcoding a specific size.
3759 : : */
3760 : 0 : ec->ec_derives_hash = derives_create(root->planner_cxt,
3761 : 0 : list_length(ec->ec_derives_list),
3762 : : NULL);
3763 : :
3764 [ # # # # : 0 : foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
# # ]
3765 : 0 : ec_add_clause_to_derives_hash(ec, rinfo);
3766 : 0 : }
3767 : :
3768 : : /*
3769 : : * ec_add_derived_clause
3770 : : * Add a clause to the set of derived clauses for the given
3771 : : * EquivalenceClass. Always appends to ec_derives_list; also adds
3772 : : * to ec_derives_hash if it exists.
3773 : : *
3774 : : * Also asserts expected invariants of derived clauses.
3775 : : */
3776 : : static void
580 amitlan@postgresql.o 3777 :CBC 91556 : ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause)
3778 : : {
3779 : : /*
3780 : : * Constant, if present, is always placed on the RHS; see
3781 : : * generate_base_implied_equalities_const(). LHS is never a constant.
3782 : : */
3783 [ - + ]: 91556 : Assert(!clause->left_em->em_is_const);
3784 : :
3785 : : /*
3786 : : * Clauses containing a constant are never considered redundant, so
3787 : : * parent_ec is not set.
3788 : : */
3789 [ + + - + ]: 91556 : Assert(!clause->parent_ec || !clause->right_em->em_is_const);
3790 : :
3791 : 91556 : ec->ec_derives_list = lappend(ec->ec_derives_list, clause);
3792 [ - + ]: 91556 : if (ec->ec_derives_hash)
580 amitlan@postgresql.o 3793 :UBC 0 : ec_add_clause_to_derives_hash(ec, clause);
580 amitlan@postgresql.o 3794 :CBC 91556 : }
3795 : :
3796 : : /*
3797 : : * ec_add_derived_clauses
3798 : : * Add a list of clauses to the set of clauses derived from the given
3799 : : * EquivalenceClass; adding to the list and hash table if needed.
3800 : : *
3801 : : * This function is similar to ec_add_derived_clause() but optimized for adding
3802 : : * multiple clauses at a time to the ec_derives_list. The assertions from
3803 : : * ec_add_derived_clause() are not repeated here, as the input clauses are
3804 : : * assumed to have already been validated.
3805 : : */
3806 : : static void
3807 : 33 : ec_add_derived_clauses(EquivalenceClass *ec, List *clauses)
3808 : : {
3809 : 33 : ec->ec_derives_list = list_concat(ec->ec_derives_list, clauses);
3810 [ - + ]: 33 : if (ec->ec_derives_hash)
580 amitlan@postgresql.o 3811 [ # # # # :UBC 0 : foreach_node(RestrictInfo, rinfo, clauses)
# # ]
3812 : 0 : ec_add_clause_to_derives_hash(ec, rinfo);
580 amitlan@postgresql.o 3813 :CBC 33 : }
3814 : :
3815 : : /*
3816 : : * fill_ec_derives_key
3817 : : * Compute a canonical key for ec_derives_hash lookup or insertion.
3818 : : *
3819 : : * Derived clauses are looked up using a pair of EquivalenceMembers and a
3820 : : * parent EquivalenceClass. To avoid storing or searching for both EM orderings,
3821 : : * we canonicalize the key:
3822 : : *
3823 : : * - For clauses involving two non-constant EMs, em1 is set to the EM with lower
3824 : : * memory address and em2 is set to the other one.
3825 : : * - For clauses involving a constant EM, the caller must pass the non-constant
3826 : : * EM as leftem and NULL as rightem; we then set em1 = NULL and em2 = leftem.
3827 : : */
3828 : : static inline void
580 amitlan@postgresql.o 3829 :UBC 0 : fill_ec_derives_key(ECDerivesKey *key,
3830 : : EquivalenceMember *leftem,
3831 : : EquivalenceMember *rightem,
3832 : : EquivalenceClass *parent_ec)
3833 : : {
3834 [ # # ]: 0 : Assert(leftem); /* Always required for lookup or insertion */
3835 : :
3836 [ # # ]: 0 : if (rightem == NULL)
3837 : : {
3838 : 0 : key->em1 = NULL;
3839 : 0 : key->em2 = leftem;
3840 : : }
3841 [ # # ]: 0 : else if (leftem < rightem)
3842 : : {
3843 : 0 : key->em1 = leftem;
3844 : 0 : key->em2 = rightem;
3845 : : }
3846 : : else
3847 : : {
3848 : 0 : key->em1 = rightem;
3849 : 0 : key->em2 = leftem;
3850 : : }
3851 : 0 : key->parent_ec = parent_ec;
3852 : 0 : }
3853 : :
3854 : : /*
3855 : : * ec_add_clause_to_derives_hash
3856 : : * Add a derived clause to ec_derives_hash in the given EquivalenceClass.
3857 : : *
3858 : : * Each clause is associated with a canonicalized key. For constant-containing
3859 : : * clauses, only the non-constant EM is used for lookup; see comments in
3860 : : * fill_ec_derives_key().
3861 : : */
3862 : : static void
3863 : 0 : ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo)
3864 : : {
3865 : : ECDerivesKey key;
3866 : : ECDerivesEntry *entry;
3867 : : bool found;
3868 : :
3869 : : /*
3870 : : * Constants are always placed on the RHS; see
3871 : : * generate_base_implied_equalities_const().
3872 : : */
3873 [ # # ]: 0 : Assert(!rinfo->left_em->em_is_const);
3874 : :
3875 : : /*
3876 : : * Clauses containing a constant are never considered redundant, so
3877 : : * parent_ec is not set.
3878 : : */
3879 [ # # # # ]: 0 : Assert(!rinfo->parent_ec || !rinfo->right_em->em_is_const);
3880 : :
3881 : : /*
3882 : : * See fill_ec_derives_key() for details: we use a canonicalized key to
3883 : : * avoid storing both EM orderings. For constant EMs, only the
3884 : : * non-constant EM is included in the key.
3885 : : */
3886 : 0 : fill_ec_derives_key(&key,
3887 : : rinfo->left_em,
3888 [ # # ]: 0 : rinfo->right_em->em_is_const ? NULL : rinfo->right_em,
3889 : : rinfo->parent_ec);
3890 : 0 : entry = derives_insert(ec->ec_derives_hash, key, &found);
3891 [ # # ]: 0 : Assert(!found);
3892 : 0 : entry->rinfo = rinfo;
3893 : 0 : }
3894 : :
3895 : : /*
3896 : : * ec_clear_derived_clauses
3897 : : * Reset ec_derives_list and ec_derives_hash.
3898 : : *
3899 : : * We destroy the hash table explicitly, since it may consume significant
3900 : : * space. The list holds the same set of entries and can become equally large
3901 : : * when thousands of partitions are involved, so we free it as well -- even
3902 : : * though we do not typically free lists.
3903 : : */
3904 : : static void
580 amitlan@postgresql.o 3905 :CBC 33 : ec_clear_derived_clauses(EquivalenceClass *ec)
3906 : : {
3907 : 33 : list_free(ec->ec_derives_list);
3908 : 33 : ec->ec_derives_list = NIL;
3909 : :
3910 [ - + ]: 33 : if (ec->ec_derives_hash)
3911 : : {
580 amitlan@postgresql.o 3912 :UBC 0 : derives_destroy(ec->ec_derives_hash);
3913 : 0 : ec->ec_derives_hash = NULL;
3914 : : }
580 amitlan@postgresql.o 3915 :CBC 33 : }
3916 : :
3917 : : /*
3918 : : * ec_search_clause_for_ems
3919 : : * Search for an existing RestrictInfo that equates the given pair
3920 : : * of EquivalenceMembers, either from ec_sources or ec_derives.
3921 : : *
3922 : : * Returns a clause with matching operands in either given order or commuted
3923 : : * order. We used to require matching operator OIDs, but dropped that since any
3924 : : * semantically different operator here would indicate a broken operator family.
3925 : : *
3926 : : * Returns NULL if no matching clause is found.
3927 : : */
3928 : : static RestrictInfo *
3929 : 463414 : ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
3930 : : EquivalenceMember *leftem, EquivalenceMember *rightem,
3931 : : EquivalenceClass *parent_ec)
3932 : : {
3933 : : /* Check original source clauses */
3934 [ + - + + : 1334193 : foreach_node(RestrictInfo, rinfo, ec->ec_sources)
+ + ]
3935 : : {
3936 [ + + ]: 536247 : if (rinfo->left_em == leftem &&
3937 [ + + ]: 265915 : rinfo->right_em == rightem &&
3938 [ + + ]: 238394 : rinfo->parent_ec == parent_ec)
3939 : 64441 : return rinfo;
3940 [ + + ]: 492540 : if (rinfo->left_em == rightem &&
3941 [ + + ]: 214963 : rinfo->right_em == leftem &&
3942 [ + + ]: 195759 : rinfo->parent_ec == parent_ec)
3943 : 20734 : return rinfo;
3944 : : }
3945 : :
3946 : : /* Not found in ec_sources; search derived clauses */
3947 : 398973 : return ec_search_derived_clause_for_ems(root, ec, leftem, rightem,
3948 : : parent_ec);
3949 : : }
3950 : :
3951 : : /*
3952 : : * ec_search_derived_clause_for_ems
3953 : : * Search for an existing derived clause between two EquivalenceMembers.
3954 : : *
3955 : : * If the number of derived clauses exceeds a threshold, switch to hash table
3956 : : * lookup; otherwise, scan ec_derives_list linearly.
3957 : : *
3958 : : * Clauses involving constants are looked up by passing the non-constant EM
3959 : : * as leftem and setting rightem to NULL. In that case, we expect to find a
3960 : : * clause with a constant on the RHS.
3961 : : *
3962 : : * While searching the list, we compare each given EM with both sides of each
3963 : : * clause. But for hash table lookups, we construct a canonicalized key and
3964 : : * perform a single lookup.
3965 : : */
3966 : : static RestrictInfo *
3967 : 398978 : ec_search_derived_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec,
3968 : : EquivalenceMember *leftem,
3969 : : EquivalenceMember *rightem,
3970 : : EquivalenceClass *parent_ec)
3971 : : {
3972 : : /* Switch to using hash lookup when list grows "too long". */
3973 [ + - - + ]: 797956 : if (!ec->ec_derives_hash &&
3974 : 398978 : list_length(ec->ec_derives_list) >= EC_DERIVES_HASH_THRESHOLD)
580 amitlan@postgresql.o 3975 :UBC 0 : ec_build_derives_hash(root, ec);
3976 : :
3977 : : /* Perform hash table lookup if available */
580 amitlan@postgresql.o 3978 [ - + ]:CBC 398978 : if (ec->ec_derives_hash)
3979 : : {
3980 : : ECDerivesKey key;
3981 : : RestrictInfo *rinfo;
3982 : : ECDerivesEntry *entry;
3983 : :
580 amitlan@postgresql.o 3984 :UBC 0 : fill_ec_derives_key(&key, leftem, rightem, parent_ec);
3985 : 0 : entry = derives_lookup(ec->ec_derives_hash, key);
3986 [ # # ]: 0 : if (entry)
3987 : : {
3988 : 0 : rinfo = entry->rinfo;
3989 [ # # ]: 0 : Assert(rinfo);
3990 [ # # # # ]: 0 : Assert(rightem || rinfo->right_em->em_is_const);
3991 : 0 : return rinfo;
3992 : : }
3993 : : }
3994 : : else
3995 : : {
3996 : : /* Fallback to linear search over ec_derives_list */
580 amitlan@postgresql.o 3997 [ + + + + :CBC 646830 : foreach_node(RestrictInfo, rinfo, ec->ec_derives_list)
+ + ]
3998 : : {
3999 : : /* Handle special case: lookup by non-const EM alone */
4000 [ + + ]: 508338 : if (!rightem &&
4001 [ + - ]: 5 : rinfo->left_em == leftem)
4002 : : {
4003 [ - + ]: 5 : Assert(rinfo->right_em->em_is_const);
4004 : 329732 : return rinfo;
4005 : : }
4006 [ + + ]: 508333 : if (rinfo->left_em == leftem &&
4007 [ + + ]: 176658 : rinfo->right_em == rightem &&
4008 [ + + ]: 157966 : rinfo->parent_ec == parent_ec)
4009 : 157956 : return rinfo;
4010 [ + + ]: 350377 : if (rinfo->left_em == rightem &&
4011 [ + + ]: 182861 : rinfo->right_em == leftem &&
4012 [ + - ]: 171771 : rinfo->parent_ec == parent_ec)
4013 : 171771 : return rinfo;
4014 : : }
4015 : : }
4016 : :
4017 : 69246 : return NULL;
4018 : : }
|