Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * joinpath.c
4 : * Routines to find all possible paths for processing a set of joins
5 : *
6 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/optimizer/path/joinpath.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : #include "postgres.h"
16 :
17 : #include <math.h>
18 :
19 : #include "executor/executor.h"
20 : #include "foreign/fdwapi.h"
21 : #include "nodes/nodeFuncs.h"
22 : #include "optimizer/cost.h"
23 : #include "optimizer/optimizer.h"
24 : #include "optimizer/pathnode.h"
25 : #include "optimizer/paths.h"
26 : #include "optimizer/placeholder.h"
27 : #include "optimizer/planmain.h"
28 : #include "optimizer/restrictinfo.h"
29 : #include "utils/lsyscache.h"
30 : #include "utils/typcache.h"
31 :
32 : /* Hook for plugins to get control in add_paths_to_joinrel() */
33 : set_join_pathlist_hook_type set_join_pathlist_hook = NULL;
34 :
35 : /*
36 : * Paths parameterized by a parent rel can be considered to be parameterized
37 : * by any of its children, when we are performing partitionwise joins. These
38 : * macros simplify checking for such cases. Beware multiple eval of args.
39 : */
40 : #define PATH_PARAM_BY_PARENT(path, rel) \
41 : ((path)->param_info && bms_overlap(PATH_REQ_OUTER(path), \
42 : (rel)->top_parent_relids))
43 : #define PATH_PARAM_BY_REL_SELF(path, rel) \
44 : ((path)->param_info && bms_overlap(PATH_REQ_OUTER(path), (rel)->relids))
45 :
46 : #define PATH_PARAM_BY_REL(path, rel) \
47 : (PATH_PARAM_BY_REL_SELF(path, rel) || PATH_PARAM_BY_PARENT(path, rel))
48 :
49 : static void try_partial_mergejoin_path(PlannerInfo *root,
50 : RelOptInfo *joinrel,
51 : Path *outer_path,
52 : Path *inner_path,
53 : List *pathkeys,
54 : List *mergeclauses,
55 : List *outersortkeys,
56 : List *innersortkeys,
57 : JoinType jointype,
58 : JoinPathExtraData *extra);
59 : static void sort_inner_and_outer(PlannerInfo *root, RelOptInfo *joinrel,
60 : RelOptInfo *outerrel, RelOptInfo *innerrel,
61 : JoinType jointype, JoinPathExtraData *extra);
62 : static void match_unsorted_outer(PlannerInfo *root, RelOptInfo *joinrel,
63 : RelOptInfo *outerrel, RelOptInfo *innerrel,
64 : JoinType jointype, JoinPathExtraData *extra);
65 : static void consider_parallel_nestloop(PlannerInfo *root,
66 : RelOptInfo *joinrel,
67 : RelOptInfo *outerrel,
68 : RelOptInfo *innerrel,
69 : JoinType jointype,
70 : JoinPathExtraData *extra);
71 : static void consider_parallel_mergejoin(PlannerInfo *root,
72 : RelOptInfo *joinrel,
73 : RelOptInfo *outerrel,
74 : RelOptInfo *innerrel,
75 : JoinType jointype,
76 : JoinPathExtraData *extra,
77 : Path *inner_cheapest_total);
78 : static void hash_inner_and_outer(PlannerInfo *root, RelOptInfo *joinrel,
79 : RelOptInfo *outerrel, RelOptInfo *innerrel,
80 : JoinType jointype, JoinPathExtraData *extra);
81 : static List *select_mergejoin_clauses(PlannerInfo *root,
82 : RelOptInfo *joinrel,
83 : RelOptInfo *outerrel,
84 : RelOptInfo *innerrel,
85 : List *restrictlist,
86 : JoinType jointype,
87 : bool *mergejoin_allowed);
88 : static void generate_mergejoin_paths(PlannerInfo *root,
89 : RelOptInfo *joinrel,
90 : RelOptInfo *innerrel,
91 : Path *outerpath,
92 : JoinType jointype,
93 : JoinPathExtraData *extra,
94 : bool useallclauses,
95 : Path *inner_cheapest_total,
96 : List *merge_pathkeys,
97 : bool is_partial);
98 :
99 :
100 : /*
101 : * add_paths_to_joinrel
102 : * Given a join relation and two component rels from which it can be made,
103 : * consider all possible paths that use the two component rels as outer
104 : * and inner rel respectively. Add these paths to the join rel's pathlist
105 : * if they survive comparison with other paths (and remove any existing
106 : * paths that are dominated by these paths).
107 : *
108 : * Modifies the pathlist field of the joinrel node to contain the best
109 : * paths found so far.
110 : *
111 : * jointype is not necessarily the same as sjinfo->jointype; it might be
112 : * "flipped around" if we are considering joining the rels in the opposite
113 : * direction from what's indicated in sjinfo.
114 : *
115 : * Also, this routine and others in this module accept the special JoinTypes
116 : * JOIN_UNIQUE_OUTER and JOIN_UNIQUE_INNER to indicate that we should
117 : * unique-ify the outer or inner relation and then apply a regular inner
118 : * join. These values are not allowed to propagate outside this module,
119 : * however. Path cost estimation code may need to recognize that it's
120 : * dealing with such a case --- the combination of nominal jointype INNER
121 : * with sjinfo->jointype == JOIN_SEMI indicates that.
122 : */
123 : void
124 565924 : add_paths_to_joinrel(PlannerInfo *root,
125 : RelOptInfo *joinrel,
126 : RelOptInfo *outerrel,
127 : RelOptInfo *innerrel,
128 : JoinType jointype,
129 : SpecialJoinInfo *sjinfo,
130 : List *restrictlist)
131 : {
132 : JoinPathExtraData extra;
133 565924 : bool mergejoin_allowed = true;
134 : ListCell *lc;
135 : Relids joinrelids;
136 :
137 : /*
138 : * PlannerInfo doesn't contain the SpecialJoinInfos created for joins
139 : * between child relations, even if there is a SpecialJoinInfo node for
140 : * the join between the topmost parents. So, while calculating Relids set
141 : * representing the restriction, consider relids of topmost parent of
142 : * partitions.
143 : */
144 565924 : if (joinrel->reloptkind == RELOPT_OTHER_JOINREL)
145 11272 : joinrelids = joinrel->top_parent_relids;
146 : else
147 554652 : joinrelids = joinrel->relids;
148 :
149 565924 : extra.restrictlist = restrictlist;
150 565924 : extra.mergeclause_list = NIL;
151 565924 : extra.sjinfo = sjinfo;
152 565924 : extra.param_source_rels = NULL;
153 :
154 : /*
155 : * See if the inner relation is provably unique for this outer rel.
156 : *
157 : * We have some special cases: for JOIN_SEMI and JOIN_ANTI, it doesn't
158 : * matter since the executor can make the equivalent optimization anyway;
159 : * we need not expend planner cycles on proofs. For JOIN_UNIQUE_INNER, we
160 : * must be considering a semijoin whose inner side is not provably unique
161 : * (else reduce_unique_semijoins would've simplified it), so there's no
162 : * point in calling innerrel_is_unique. However, if the LHS covers all of
163 : * the semijoin's min_lefthand, then it's appropriate to set inner_unique
164 : * because the path produced by create_unique_path will be unique relative
165 : * to the LHS. (If we have an LHS that's only part of the min_lefthand,
166 : * that is *not* true.) For JOIN_UNIQUE_OUTER, pass JOIN_INNER to avoid
167 : * letting that value escape this module.
168 : */
169 565924 : switch (jointype)
170 : {
171 8842 : case JOIN_SEMI:
172 : case JOIN_ANTI:
173 :
174 : /*
175 : * XXX it may be worth proving this to allow a Memoize to be
176 : * considered for Nested Loop Semi/Anti Joins.
177 : */
178 8842 : extra.inner_unique = false; /* well, unproven */
179 8842 : break;
180 4328 : case JOIN_UNIQUE_INNER:
181 8656 : extra.inner_unique = bms_is_subset(sjinfo->min_lefthand,
182 4328 : outerrel->relids);
183 4328 : break;
184 4328 : case JOIN_UNIQUE_OUTER:
185 4328 : extra.inner_unique = innerrel_is_unique(root,
186 : joinrel->relids,
187 : outerrel->relids,
188 : innerrel,
189 : JOIN_INNER,
190 : restrictlist,
191 : false);
192 4328 : break;
193 548426 : default:
194 548426 : extra.inner_unique = innerrel_is_unique(root,
195 : joinrel->relids,
196 : outerrel->relids,
197 : innerrel,
198 : jointype,
199 : restrictlist,
200 : false);
201 548426 : break;
202 : }
203 :
204 : /*
205 : * Find potential mergejoin clauses. We can skip this if we are not
206 : * interested in doing a mergejoin. However, mergejoin may be our only
207 : * way of implementing a full outer join, so override enable_mergejoin if
208 : * it's a full join.
209 : */
210 565924 : if (enable_mergejoin || jointype == JOIN_FULL)
211 564396 : extra.mergeclause_list = select_mergejoin_clauses(root,
212 : joinrel,
213 : outerrel,
214 : innerrel,
215 : restrictlist,
216 : jointype,
217 : &mergejoin_allowed);
218 :
219 : /*
220 : * If it's SEMI, ANTI, or inner_unique join, compute correction factors
221 : * for cost estimation. These will be the same for all paths.
222 : */
223 565924 : if (jointype == JOIN_SEMI || jointype == JOIN_ANTI || extra.inner_unique)
224 175446 : compute_semi_anti_join_factors(root, joinrel, outerrel, innerrel,
225 : jointype, sjinfo, restrictlist,
226 : &extra.semifactors);
227 :
228 : /*
229 : * Decide whether it's sensible to generate parameterized paths for this
230 : * joinrel, and if so, which relations such paths should require. There
231 : * is usually no need to create a parameterized result path unless there
232 : * is a join order restriction that prevents joining one of our input rels
233 : * directly to the parameter source rel instead of joining to the other
234 : * input rel. (But see allow_star_schema_join().) This restriction
235 : * reduces the number of parameterized paths we have to deal with at
236 : * higher join levels, without compromising the quality of the resulting
237 : * plan. We express the restriction as a Relids set that must overlap the
238 : * parameterization of any proposed join path. Note: param_source_rels
239 : * should contain only baserels, not OJ relids, so starting from
240 : * all_baserels not all_query_rels is correct.
241 : */
242 1151600 : foreach(lc, root->join_info_list)
243 : {
244 585676 : SpecialJoinInfo *sjinfo2 = (SpecialJoinInfo *) lfirst(lc);
245 :
246 : /*
247 : * SJ is relevant to this join if we have some part of its RHS
248 : * (possibly not all of it), and haven't yet joined to its LHS. (This
249 : * test is pretty simplistic, but should be sufficient considering the
250 : * join has already been proven legal.) If the SJ is relevant, it
251 : * presents constraints for joining to anything not in its RHS.
252 : */
253 585676 : if (bms_overlap(joinrelids, sjinfo2->min_righthand) &&
254 390636 : !bms_overlap(joinrelids, sjinfo2->min_lefthand))
255 19732 : extra.param_source_rels = bms_join(extra.param_source_rels,
256 19732 : bms_difference(root->all_baserels,
257 19732 : sjinfo2->min_righthand));
258 :
259 : /* full joins constrain both sides symmetrically */
260 590532 : if (sjinfo2->jointype == JOIN_FULL &&
261 4856 : bms_overlap(joinrelids, sjinfo2->min_lefthand) &&
262 4800 : !bms_overlap(joinrelids, sjinfo2->min_righthand))
263 672 : extra.param_source_rels = bms_join(extra.param_source_rels,
264 672 : bms_difference(root->all_baserels,
265 672 : sjinfo2->min_lefthand));
266 : }
267 :
268 : /*
269 : * However, when a LATERAL subquery is involved, there will simply not be
270 : * any paths for the joinrel that aren't parameterized by whatever the
271 : * subquery is parameterized by, unless its parameterization is resolved
272 : * within the joinrel. So we might as well allow additional dependencies
273 : * on whatever residual lateral dependencies the joinrel will have.
274 : */
275 1131848 : extra.param_source_rels = bms_add_members(extra.param_source_rels,
276 565924 : joinrel->lateral_relids);
277 :
278 : /*
279 : * 1. Consider mergejoin paths where both relations must be explicitly
280 : * sorted. Skip this if we can't mergejoin.
281 : */
282 565924 : if (mergejoin_allowed)
283 554366 : sort_inner_and_outer(root, joinrel, outerrel, innerrel,
284 : jointype, &extra);
285 :
286 : /*
287 : * 2. Consider paths where the outer relation need not be explicitly
288 : * sorted. This includes both nestloops and mergejoins where the outer
289 : * path is already ordered. Again, skip this if we can't mergejoin.
290 : * (That's okay because we know that nestloop can't handle
291 : * right/right-anti/right-semi/full joins at all, so it wouldn't work in
292 : * the prohibited cases either.)
293 : */
294 565924 : if (mergejoin_allowed)
295 554366 : match_unsorted_outer(root, joinrel, outerrel, innerrel,
296 : jointype, &extra);
297 :
298 : #ifdef NOT_USED
299 :
300 : /*
301 : * 3. Consider paths where the inner relation need not be explicitly
302 : * sorted. This includes mergejoins only (nestloops were already built in
303 : * match_unsorted_outer).
304 : *
305 : * Diked out as redundant 2/13/2000 -- tgl. There isn't any really
306 : * significant difference between the inner and outer side of a mergejoin,
307 : * so match_unsorted_inner creates no paths that aren't equivalent to
308 : * those made by match_unsorted_outer when add_paths_to_joinrel() is
309 : * invoked with the two rels given in the other order.
310 : */
311 : if (mergejoin_allowed)
312 : match_unsorted_inner(root, joinrel, outerrel, innerrel,
313 : jointype, &extra);
314 : #endif
315 :
316 : /*
317 : * 4. Consider paths where both outer and inner relations must be hashed
318 : * before being joined. As above, disregard enable_hashjoin for full
319 : * joins, because there may be no other alternative.
320 : */
321 565924 : if (enable_hashjoin || jointype == JOIN_FULL)
322 562756 : hash_inner_and_outer(root, joinrel, outerrel, innerrel,
323 : jointype, &extra);
324 :
325 : /*
326 : * 5. If inner and outer relations are foreign tables (or joins) belonging
327 : * to the same server and assigned to the same user to check access
328 : * permissions as, give the FDW a chance to push down joins.
329 : */
330 565924 : if (joinrel->fdwroutine &&
331 2548 : joinrel->fdwroutine->GetForeignJoinPaths)
332 2544 : joinrel->fdwroutine->GetForeignJoinPaths(root, joinrel,
333 : outerrel, innerrel,
334 : jointype, &extra);
335 :
336 : /*
337 : * 6. Finally, give extensions a chance to manipulate the path list. They
338 : * could add new paths (such as CustomPaths) by calling add_path(), or
339 : * add_partial_path() if parallel aware. They could also delete or modify
340 : * paths added by the core code.
341 : */
342 565924 : if (set_join_pathlist_hook)
343 0 : set_join_pathlist_hook(root, joinrel, outerrel, innerrel,
344 : jointype, &extra);
345 565924 : }
346 :
347 : /*
348 : * We override the param_source_rels heuristic to accept nestloop paths in
349 : * which the outer rel satisfies some but not all of the inner path's
350 : * parameterization. This is necessary to get good plans for star-schema
351 : * scenarios, in which a parameterized path for a large table may require
352 : * parameters from multiple small tables that will not get joined directly to
353 : * each other. We can handle that by stacking nestloops that have the small
354 : * tables on the outside; but this breaks the rule the param_source_rels
355 : * heuristic is based on, namely that parameters should not be passed down
356 : * across joins unless there's a join-order-constraint-based reason to do so.
357 : * So we ignore the param_source_rels restriction when this case applies.
358 : *
359 : * allow_star_schema_join() returns true if the param_source_rels restriction
360 : * should be overridden, ie, it's okay to perform this join.
361 : */
362 : static inline bool
363 230094 : allow_star_schema_join(PlannerInfo *root,
364 : Relids outerrelids,
365 : Relids inner_paramrels)
366 : {
367 : /*
368 : * It's a star-schema case if the outer rel provides some but not all of
369 : * the inner rel's parameterization.
370 : */
371 268420 : return (bms_overlap(inner_paramrels, outerrelids) &&
372 38326 : bms_nonempty_difference(inner_paramrels, outerrelids));
373 : }
374 :
375 : /*
376 : * If the parameterization is only partly satisfied by the outer rel,
377 : * the unsatisfied part can't include any outer-join relids that could
378 : * null rels of the satisfied part. That would imply that we're trying
379 : * to use a clause involving a Var with nonempty varnullingrels at
380 : * a join level where that value isn't yet computable.
381 : *
382 : * In practice, this test never finds a problem because earlier join order
383 : * restrictions prevent us from attempting a join that would cause a problem.
384 : * (That's unsurprising, because the code worked before we ever added
385 : * outer-join relids to expression relids.) It still seems worth checking
386 : * as a backstop, but we only do so in assert-enabled builds.
387 : */
388 : #ifdef USE_ASSERT_CHECKING
389 : static inline bool
390 : have_unsafe_outer_join_ref(PlannerInfo *root,
391 : Relids outerrelids,
392 : Relids inner_paramrels)
393 : {
394 : bool result = false;
395 : Relids unsatisfied = bms_difference(inner_paramrels, outerrelids);
396 : Relids satisfied = bms_intersect(inner_paramrels, outerrelids);
397 :
398 : if (bms_overlap(unsatisfied, root->outer_join_rels))
399 : {
400 : ListCell *lc;
401 :
402 : foreach(lc, root->join_info_list)
403 : {
404 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
405 :
406 : if (!bms_is_member(sjinfo->ojrelid, unsatisfied))
407 : continue; /* not relevant */
408 : if (bms_overlap(satisfied, sjinfo->min_righthand) ||
409 : (sjinfo->jointype == JOIN_FULL &&
410 : bms_overlap(satisfied, sjinfo->min_lefthand)))
411 : {
412 : result = true; /* doesn't work */
413 : break;
414 : }
415 : }
416 : }
417 :
418 : /* Waste no memory when we reject a path here */
419 : bms_free(unsatisfied);
420 : bms_free(satisfied);
421 :
422 : return result;
423 : }
424 : #endif /* USE_ASSERT_CHECKING */
425 :
426 : /*
427 : * paraminfo_get_equal_hashops
428 : * Determine if the clauses in param_info and innerrel's lateral vars
429 : * can be hashed.
430 : * Returns true if hashing is possible, otherwise false.
431 : *
432 : * Additionally, on success we collect the outer expressions and the
433 : * appropriate equality operators for each hashable parameter to innerrel.
434 : * These are returned in parallel lists in *param_exprs and *operators.
435 : * We also set *binary_mode to indicate whether strict binary matching is
436 : * required.
437 : */
438 : static bool
439 334226 : paraminfo_get_equal_hashops(PlannerInfo *root, ParamPathInfo *param_info,
440 : RelOptInfo *outerrel, RelOptInfo *innerrel,
441 : List *ph_lateral_vars, List **param_exprs,
442 : List **operators, bool *binary_mode)
443 :
444 : {
445 : List *lateral_vars;
446 : ListCell *lc;
447 :
448 334226 : *param_exprs = NIL;
449 334226 : *operators = NIL;
450 334226 : *binary_mode = false;
451 :
452 : /* Add join clauses from param_info to the hash key */
453 334226 : if (param_info != NULL)
454 : {
455 334226 : List *clauses = param_info->ppi_clauses;
456 :
457 605610 : foreach(lc, clauses)
458 : {
459 357078 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
460 : OpExpr *opexpr;
461 : Node *expr;
462 : Oid hasheqoperator;
463 :
464 357078 : opexpr = (OpExpr *) rinfo->clause;
465 :
466 : /*
467 : * Bail if the rinfo is not compatible. We need a join OpExpr
468 : * with 2 args.
469 : */
470 357078 : if (!IsA(opexpr, OpExpr) || list_length(opexpr->args) != 2 ||
471 333366 : !clause_sides_match_join(rinfo, outerrel->relids,
472 : innerrel->relids))
473 : {
474 85538 : list_free(*operators);
475 85538 : list_free(*param_exprs);
476 85694 : return false;
477 : }
478 :
479 271540 : if (rinfo->outer_is_left)
480 : {
481 155362 : expr = (Node *) linitial(opexpr->args);
482 155362 : hasheqoperator = rinfo->left_hasheqoperator;
483 : }
484 : else
485 : {
486 116178 : expr = (Node *) lsecond(opexpr->args);
487 116178 : hasheqoperator = rinfo->right_hasheqoperator;
488 : }
489 :
490 : /* can't do memoize if we can't hash the outer type */
491 271540 : if (!OidIsValid(hasheqoperator))
492 : {
493 156 : list_free(*operators);
494 156 : list_free(*param_exprs);
495 156 : return false;
496 : }
497 :
498 : /*
499 : * 'expr' may already exist as a parameter from a previous item in
500 : * ppi_clauses. No need to include it again, however we'd better
501 : * ensure we do switch into binary mode if required. See below.
502 : */
503 271384 : if (!list_member(*param_exprs, expr))
504 : {
505 271378 : *operators = lappend_oid(*operators, hasheqoperator);
506 271378 : *param_exprs = lappend(*param_exprs, expr);
507 : }
508 :
509 : /*
510 : * When the join operator is not hashable then it's possible that
511 : * the operator will be able to distinguish something that the
512 : * hash equality operator could not. For example with floating
513 : * point types -0.0 and +0.0 are classed as equal by the hash
514 : * function and equality function, but some other operator may be
515 : * able to tell those values apart. This means that we must put
516 : * memoize into binary comparison mode so that it does bit-by-bit
517 : * comparisons rather than a "logical" comparison as it would
518 : * using the hash equality operator.
519 : */
520 271384 : if (!OidIsValid(rinfo->hashjoinoperator))
521 1070 : *binary_mode = true;
522 : }
523 : }
524 :
525 : /* Now add any lateral vars to the cache key too */
526 248532 : lateral_vars = list_concat(ph_lateral_vars, innerrel->lateral_vars);
527 252658 : foreach(lc, lateral_vars)
528 : {
529 4324 : Node *expr = (Node *) lfirst(lc);
530 : TypeCacheEntry *typentry;
531 :
532 : /* Reject if there are any volatile functions in lateral vars */
533 4324 : if (contain_volatile_functions(expr))
534 : {
535 0 : list_free(*operators);
536 0 : list_free(*param_exprs);
537 198 : return false;
538 : }
539 :
540 4324 : typentry = lookup_type_cache(exprType(expr),
541 : TYPECACHE_HASH_PROC | TYPECACHE_EQ_OPR);
542 :
543 : /* can't use memoize without a valid hash proc and equals operator */
544 4324 : if (!OidIsValid(typentry->hash_proc) || !OidIsValid(typentry->eq_opr))
545 : {
546 198 : list_free(*operators);
547 198 : list_free(*param_exprs);
548 198 : return false;
549 : }
550 :
551 : /*
552 : * 'expr' may already exist as a parameter from the ppi_clauses. No
553 : * need to include it again, however we'd better ensure we do switch
554 : * into binary mode.
555 : */
556 4126 : if (!list_member(*param_exprs, expr))
557 : {
558 3688 : *operators = lappend_oid(*operators, typentry->eq_opr);
559 3688 : *param_exprs = lappend(*param_exprs, expr);
560 : }
561 :
562 : /*
563 : * We must go into binary mode as we don't have too much of an idea of
564 : * how these lateral Vars are being used. See comment above when we
565 : * set *binary_mode for the non-lateral Var case. This could be
566 : * relaxed a bit if we had the RestrictInfos and knew the operators
567 : * being used, however for cases like Vars that are arguments to
568 : * functions we must operate in binary mode as we don't have
569 : * visibility into what the function is doing with the Vars.
570 : */
571 4126 : *binary_mode = true;
572 : }
573 :
574 : /* We're okay to use memoize */
575 248334 : return true;
576 : }
577 :
578 : /*
579 : * extract_lateral_vars_from_PHVs
580 : * Extract lateral references within PlaceHolderVars that are due to be
581 : * evaluated at 'innerrelids'.
582 : */
583 : static List *
584 991532 : extract_lateral_vars_from_PHVs(PlannerInfo *root, Relids innerrelids)
585 : {
586 991532 : List *ph_lateral_vars = NIL;
587 : ListCell *lc;
588 :
589 : /* Nothing would be found if the query contains no LATERAL RTEs */
590 991532 : if (!root->hasLateralRTEs)
591 972686 : return NIL;
592 :
593 : /*
594 : * No need to consider PHVs that are due to be evaluated at joinrels,
595 : * since we do not add Memoize nodes on top of joinrel paths.
596 : */
597 18846 : if (bms_membership(innerrelids) == BMS_MULTIPLE)
598 5734 : return NIL;
599 :
600 15256 : foreach(lc, root->placeholder_list)
601 : {
602 2144 : PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
603 : List *vars;
604 : ListCell *cell;
605 :
606 : /* PHV is uninteresting if no lateral refs */
607 2144 : if (phinfo->ph_lateral == NULL)
608 978 : continue;
609 :
610 : /* PHV is uninteresting if not due to be evaluated at innerrelids */
611 1166 : if (!bms_equal(phinfo->ph_eval_at, innerrelids))
612 970 : continue;
613 :
614 : /*
615 : * If the PHV does not reference any rels in innerrelids, use its
616 : * contained expression as a cache key rather than extracting the
617 : * Vars/PHVs from it and using those. This can be beneficial in cases
618 : * where the expression results in fewer distinct values to cache
619 : * tuples for.
620 : */
621 196 : if (!bms_overlap(pull_varnos(root, (Node *) phinfo->ph_var->phexpr),
622 : innerrelids))
623 : {
624 184 : ph_lateral_vars = lappend(ph_lateral_vars, phinfo->ph_var->phexpr);
625 184 : continue;
626 : }
627 :
628 : /* Fetch Vars and PHVs of lateral references within PlaceHolderVars */
629 12 : vars = pull_vars_of_level((Node *) phinfo->ph_var->phexpr, 0);
630 36 : foreach(cell, vars)
631 : {
632 24 : Node *node = (Node *) lfirst(cell);
633 :
634 24 : if (IsA(node, Var))
635 : {
636 12 : Var *var = (Var *) node;
637 :
638 : Assert(var->varlevelsup == 0);
639 :
640 12 : if (bms_is_member(var->varno, phinfo->ph_lateral))
641 0 : ph_lateral_vars = lappend(ph_lateral_vars, node);
642 : }
643 12 : else if (IsA(node, PlaceHolderVar))
644 : {
645 12 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
646 :
647 : Assert(phv->phlevelsup == 0);
648 :
649 12 : if (bms_is_subset(find_placeholder_info(root, phv)->ph_eval_at,
650 12 : phinfo->ph_lateral))
651 12 : ph_lateral_vars = lappend(ph_lateral_vars, node);
652 : }
653 : else
654 : Assert(false);
655 : }
656 :
657 12 : list_free(vars);
658 : }
659 :
660 13112 : return ph_lateral_vars;
661 : }
662 :
663 : /*
664 : * get_memoize_path
665 : * If possible, make and return a Memoize path atop of 'inner_path'.
666 : * Otherwise return NULL.
667 : *
668 : * Note that currently we do not add Memoize nodes on top of join relation
669 : * paths. This is because the ParamPathInfos for join relation paths do not
670 : * maintain ppi_clauses, as the set of relevant clauses varies depending on how
671 : * the join is formed. In addition, joinrels do not maintain lateral_vars. So
672 : * we do not have a way to extract cache keys from joinrels.
673 : */
674 : static Path *
675 1446164 : get_memoize_path(PlannerInfo *root, RelOptInfo *innerrel,
676 : RelOptInfo *outerrel, Path *inner_path,
677 : Path *outer_path, JoinType jointype,
678 : JoinPathExtraData *extra)
679 : {
680 : List *param_exprs;
681 : List *hash_operators;
682 : ListCell *lc;
683 : bool binary_mode;
684 : List *ph_lateral_vars;
685 :
686 : /* Obviously not if it's disabled */
687 1446164 : if (!enable_memoize)
688 388 : return NULL;
689 :
690 : /*
691 : * We can safely not bother with all this unless we expect to perform more
692 : * than one inner scan. The first scan is always going to be a cache
693 : * miss. This would likely fail later anyway based on costs, so this is
694 : * really just to save some wasted effort.
695 : */
696 1445776 : if (outer_path->parent->rows < 2)
697 454244 : return NULL;
698 :
699 : /*
700 : * Extract lateral Vars/PHVs within PlaceHolderVars that are due to be
701 : * evaluated at innerrel. These lateral Vars/PHVs could be used as
702 : * memoize cache keys.
703 : */
704 991532 : ph_lateral_vars = extract_lateral_vars_from_PHVs(root, innerrel->relids);
705 :
706 : /*
707 : * We can only have a memoize node when there's some kind of cache key,
708 : * either parameterized path clauses or lateral Vars. No cache key sounds
709 : * more like something a Materialize node might be more useful for.
710 : */
711 991532 : if ((inner_path->param_info == NULL ||
712 410672 : inner_path->param_info->ppi_clauses == NIL) &&
713 599128 : innerrel->lateral_vars == NIL &&
714 : ph_lateral_vars == NIL)
715 596176 : return NULL;
716 :
717 : /*
718 : * Currently we don't do this for SEMI and ANTI joins unless they're
719 : * marked as inner_unique. This is because nested loop SEMI/ANTI joins
720 : * don't scan the inner node to completion, which will mean memoize cannot
721 : * mark the cache entry as complete.
722 : *
723 : * XXX Currently we don't attempt to mark SEMI/ANTI joins as inner_unique
724 : * = true. Should we? See add_paths_to_joinrel()
725 : */
726 395356 : if (!extra->inner_unique && (jointype == JOIN_SEMI ||
727 : jointype == JOIN_ANTI))
728 8666 : return NULL;
729 :
730 : /*
731 : * Memoize normally marks cache entries as complete when it runs out of
732 : * tuples to read from its subplan. However, with unique joins, Nested
733 : * Loop will skip to the next outer tuple after finding the first matching
734 : * inner tuple. This means that we may not read the inner side of the
735 : * join to completion which leaves no opportunity to mark the cache entry
736 : * as complete. To work around that, when the join is unique we
737 : * automatically mark cache entries as complete after fetching the first
738 : * tuple. This works when the entire join condition is parameterized.
739 : * Otherwise, when the parameterization is only a subset of the join
740 : * condition, we can't be sure which part of it causes the join to be
741 : * unique. This means there are no guarantees that only 1 tuple will be
742 : * read. We cannot mark the cache entry as complete after reading the
743 : * first tuple without that guarantee. This means the scope of Memoize
744 : * node's usefulness is limited to only outer rows that have no join
745 : * partner as this is the only case where Nested Loop would exhaust the
746 : * inner scan of a unique join. Since the scope is limited to that, we
747 : * just don't bother making a memoize path in this case.
748 : *
749 : * Lateral vars needn't be considered here as they're not considered when
750 : * determining if the join is unique.
751 : *
752 : * XXX this could be enabled if the remaining join quals were made part of
753 : * the inner scan's filter instead of the join filter. Maybe it's worth
754 : * considering doing that?
755 : */
756 386690 : if (extra->inner_unique &&
757 468684 : (inner_path->param_info == NULL ||
758 234342 : bms_num_members(inner_path->param_info->ppi_serials) <
759 234342 : list_length(extra->restrictlist)))
760 52450 : return NULL;
761 :
762 : /*
763 : * We can't use a memoize node if there are volatile functions in the
764 : * inner rel's target list or restrict list. A cache hit could reduce the
765 : * number of calls to these functions.
766 : */
767 334240 : if (contain_volatile_functions((Node *) innerrel->reltarget))
768 0 : return NULL;
769 :
770 556522 : foreach(lc, innerrel->baserestrictinfo)
771 : {
772 222294 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
773 :
774 222294 : if (contain_volatile_functions((Node *) rinfo))
775 12 : return NULL;
776 : }
777 :
778 : /*
779 : * Also check the parameterized path restrictinfos for volatile functions.
780 : * Indexed functions must be immutable so shouldn't have any volatile
781 : * functions, however, with a lateral join the inner scan may not be an
782 : * index scan.
783 : */
784 334228 : if (inner_path->param_info != NULL)
785 : {
786 719468 : foreach(lc, inner_path->param_info->ppi_clauses)
787 : {
788 385242 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
789 :
790 385242 : if (contain_volatile_functions((Node *) rinfo))
791 2 : return NULL;
792 : }
793 : }
794 :
795 : /* Check if we have hash ops for each parameter to the path */
796 334226 : if (paraminfo_get_equal_hashops(root,
797 : inner_path->param_info,
798 334226 : outerrel->top_parent ?
799 : outerrel->top_parent : outerrel,
800 : innerrel,
801 : ph_lateral_vars,
802 : ¶m_exprs,
803 : &hash_operators,
804 : &binary_mode))
805 : {
806 248334 : return (Path *) create_memoize_path(root,
807 : innerrel,
808 : inner_path,
809 : param_exprs,
810 : hash_operators,
811 248334 : extra->inner_unique,
812 : binary_mode,
813 : outer_path->rows);
814 : }
815 :
816 85892 : return NULL;
817 : }
818 :
819 : /*
820 : * try_nestloop_path
821 : * Consider a nestloop join path; if it appears useful, push it into
822 : * the joinrel's pathlist via add_path().
823 : */
824 : static void
825 2502000 : try_nestloop_path(PlannerInfo *root,
826 : RelOptInfo *joinrel,
827 : Path *outer_path,
828 : Path *inner_path,
829 : List *pathkeys,
830 : JoinType jointype,
831 : JoinPathExtraData *extra)
832 : {
833 : Relids required_outer;
834 : JoinCostWorkspace workspace;
835 2502000 : RelOptInfo *innerrel = inner_path->parent;
836 2502000 : RelOptInfo *outerrel = outer_path->parent;
837 : Relids innerrelids;
838 : Relids outerrelids;
839 2502000 : Relids inner_paramrels = PATH_REQ_OUTER(inner_path);
840 2502000 : Relids outer_paramrels = PATH_REQ_OUTER(outer_path);
841 :
842 : /*
843 : * If we are forming an outer join at this join, it's nonsensical to use
844 : * an input path that uses the outer join as part of its parameterization.
845 : * (This can happen despite our join order restrictions, since those apply
846 : * to what is in an input relation not what its parameters are.)
847 : */
848 3055524 : if (extra->sjinfo->ojrelid != 0 &&
849 1107048 : (bms_is_member(extra->sjinfo->ojrelid, inner_paramrels) ||
850 553524 : bms_is_member(extra->sjinfo->ojrelid, outer_paramrels)))
851 229882 : return;
852 :
853 : /*
854 : * Any parameterization of the input paths refers to topmost parents of
855 : * the relevant relations, because reparameterize_path_by_child() hasn't
856 : * been called yet. So we must consider topmost parents of the relations
857 : * being joined, too, while determining parameterization of the result and
858 : * checking for disallowed parameterization cases.
859 : */
860 2501880 : if (innerrel->top_parent_relids)
861 34012 : innerrelids = innerrel->top_parent_relids;
862 : else
863 2467868 : innerrelids = innerrel->relids;
864 :
865 2501880 : if (outerrel->top_parent_relids)
866 34012 : outerrelids = outerrel->top_parent_relids;
867 : else
868 2467868 : outerrelids = outerrel->relids;
869 :
870 : /*
871 : * Check to see if proposed path is still parameterized, and reject if the
872 : * parameterization wouldn't be sensible --- unless allow_star_schema_join
873 : * says to allow it anyway. Also, we must reject if have_dangerous_phv
874 : * doesn't like the look of it, which could only happen if the nestloop is
875 : * still parameterized.
876 : */
877 2501880 : required_outer = calc_nestloop_required_outer(outerrelids, outer_paramrels,
878 : innerrelids, inner_paramrels);
879 2501880 : if (required_outer &&
880 261026 : ((!bms_overlap(required_outer, extra->param_source_rels) &&
881 261454 : !allow_star_schema_join(root, outerrelids, inner_paramrels)) ||
882 31360 : have_dangerous_phv(root, outerrelids, inner_paramrels)))
883 : {
884 : /* Waste no memory when we reject a path here */
885 229762 : bms_free(required_outer);
886 229762 : return;
887 : }
888 :
889 : /* If we got past that, we shouldn't have any unsafe outer-join refs */
890 : Assert(!have_unsafe_outer_join_ref(root, outerrelids, inner_paramrels));
891 :
892 : /*
893 : * If the inner path is parameterized, it is parameterized by the topmost
894 : * parent of the outer rel, not the outer rel itself. We will need to
895 : * translate the parameterization, if this path is chosen, during
896 : * create_plan(). Here we just check whether we will be able to perform
897 : * the translation, and if not avoid creating a nestloop path.
898 : */
899 2272118 : if (PATH_PARAM_BY_PARENT(inner_path, outer_path->parent) &&
900 10888 : !path_is_reparameterizable_by_child(inner_path, outer_path->parent))
901 : {
902 0 : bms_free(required_outer);
903 0 : return;
904 : }
905 :
906 : /*
907 : * Do a precheck to quickly eliminate obviously-inferior paths. We
908 : * calculate a cheap lower bound on the path's cost and then use
909 : * add_path_precheck() to see if the path is clearly going to be dominated
910 : * by some existing path for the joinrel. If not, do the full pushup with
911 : * creating a fully valid path structure and submitting it to add_path().
912 : * The latter two steps are expensive enough to make this two-phase
913 : * methodology worthwhile.
914 : */
915 2272118 : initial_cost_nestloop(root, &workspace, jointype,
916 : outer_path, inner_path, extra);
917 :
918 2272118 : if (add_path_precheck(joinrel, workspace.disabled_nodes,
919 : workspace.startup_cost, workspace.total_cost,
920 : pathkeys, required_outer))
921 : {
922 1129234 : add_path(joinrel, (Path *)
923 1129234 : create_nestloop_path(root,
924 : joinrel,
925 : jointype,
926 : &workspace,
927 : extra,
928 : outer_path,
929 : inner_path,
930 : extra->restrictlist,
931 : pathkeys,
932 : required_outer));
933 : }
934 : else
935 : {
936 : /* Waste no memory when we reject a path here */
937 1142884 : bms_free(required_outer);
938 : }
939 : }
940 :
941 : /*
942 : * try_partial_nestloop_path
943 : * Consider a partial nestloop join path; if it appears useful, push it into
944 : * the joinrel's partial_pathlist via add_partial_path().
945 : */
946 : static void
947 39826 : try_partial_nestloop_path(PlannerInfo *root,
948 : RelOptInfo *joinrel,
949 : Path *outer_path,
950 : Path *inner_path,
951 : List *pathkeys,
952 : JoinType jointype,
953 : JoinPathExtraData *extra)
954 : {
955 : JoinCostWorkspace workspace;
956 :
957 : /*
958 : * If the inner path is parameterized, the parameterization must be fully
959 : * satisfied by the proposed outer path. Parameterized partial paths are
960 : * not supported. The caller should already have verified that no lateral
961 : * rels are required here.
962 : */
963 : Assert(bms_is_empty(joinrel->lateral_relids));
964 : Assert(bms_is_empty(PATH_REQ_OUTER(outer_path)));
965 39826 : if (inner_path->param_info != NULL)
966 : {
967 13682 : Relids inner_paramrels = inner_path->param_info->ppi_req_outer;
968 13682 : RelOptInfo *outerrel = outer_path->parent;
969 : Relids outerrelids;
970 :
971 : /*
972 : * The inner and outer paths are parameterized, if at all, by the top
973 : * level parents, not the child relations, so we must use those relids
974 : * for our parameterization tests.
975 : */
976 13682 : if (outerrel->top_parent_relids)
977 10188 : outerrelids = outerrel->top_parent_relids;
978 : else
979 3494 : outerrelids = outerrel->relids;
980 :
981 13682 : if (!bms_is_subset(inner_paramrels, outerrelids))
982 27576 : return;
983 : }
984 :
985 : /*
986 : * If the inner path is parameterized, it is parameterized by the topmost
987 : * parent of the outer rel, not the outer rel itself. We will need to
988 : * translate the parameterization, if this path is chosen, during
989 : * create_plan(). Here we just check whether we will be able to perform
990 : * the translation, and if not avoid creating a nestloop path.
991 : */
992 38740 : if (PATH_PARAM_BY_PARENT(inner_path, outer_path->parent) &&
993 9396 : !path_is_reparameterizable_by_child(inner_path, outer_path->parent))
994 0 : return;
995 :
996 : /*
997 : * Before creating a path, get a quick lower bound on what it is likely to
998 : * cost. Bail out right away if it looks terrible.
999 : */
1000 38740 : initial_cost_nestloop(root, &workspace, jointype,
1001 : outer_path, inner_path, extra);
1002 38740 : if (!add_partial_path_precheck(joinrel, workspace.disabled_nodes,
1003 : workspace.total_cost, pathkeys))
1004 26490 : return;
1005 :
1006 : /* Might be good enough to be worth trying, so let's try it. */
1007 12250 : add_partial_path(joinrel, (Path *)
1008 12250 : create_nestloop_path(root,
1009 : joinrel,
1010 : jointype,
1011 : &workspace,
1012 : extra,
1013 : outer_path,
1014 : inner_path,
1015 : extra->restrictlist,
1016 : pathkeys,
1017 : NULL));
1018 : }
1019 :
1020 : /*
1021 : * try_mergejoin_path
1022 : * Consider a merge join path; if it appears useful, push it into
1023 : * the joinrel's pathlist via add_path().
1024 : */
1025 : static void
1026 1018452 : try_mergejoin_path(PlannerInfo *root,
1027 : RelOptInfo *joinrel,
1028 : Path *outer_path,
1029 : Path *inner_path,
1030 : List *pathkeys,
1031 : List *mergeclauses,
1032 : List *outersortkeys,
1033 : List *innersortkeys,
1034 : JoinType jointype,
1035 : JoinPathExtraData *extra,
1036 : bool is_partial)
1037 : {
1038 : Relids required_outer;
1039 : JoinCostWorkspace workspace;
1040 :
1041 1018452 : if (is_partial)
1042 : {
1043 6302 : try_partial_mergejoin_path(root,
1044 : joinrel,
1045 : outer_path,
1046 : inner_path,
1047 : pathkeys,
1048 : mergeclauses,
1049 : outersortkeys,
1050 : innersortkeys,
1051 : jointype,
1052 : extra);
1053 35076 : return;
1054 : }
1055 :
1056 : /*
1057 : * If we are forming an outer join at this join, it's nonsensical to use
1058 : * an input path that uses the outer join as part of its parameterization.
1059 : * (This can happen despite our join order restrictions, since those apply
1060 : * to what is in an input relation not what its parameters are.)
1061 : */
1062 1326576 : if (extra->sjinfo->ojrelid != 0 &&
1063 628852 : (bms_is_member(extra->sjinfo->ojrelid, PATH_REQ_OUTER(inner_path)) ||
1064 314426 : bms_is_member(extra->sjinfo->ojrelid, PATH_REQ_OUTER(outer_path))))
1065 12 : return;
1066 :
1067 : /*
1068 : * Check to see if proposed path is still parameterized, and reject if the
1069 : * parameterization wouldn't be sensible.
1070 : */
1071 1012138 : required_outer = calc_non_nestloop_required_outer(outer_path,
1072 : inner_path);
1073 1012138 : if (required_outer &&
1074 31246 : !bms_overlap(required_outer, extra->param_source_rels))
1075 : {
1076 : /* Waste no memory when we reject a path here */
1077 28762 : bms_free(required_outer);
1078 28762 : return;
1079 : }
1080 :
1081 : /*
1082 : * If the given paths are already well enough ordered, we can skip doing
1083 : * an explicit sort.
1084 : */
1085 1468932 : if (outersortkeys &&
1086 485556 : pathkeys_contained_in(outersortkeys, outer_path->pathkeys))
1087 20614 : outersortkeys = NIL;
1088 1785018 : if (innersortkeys &&
1089 801642 : pathkeys_contained_in(innersortkeys, inner_path->pathkeys))
1090 36844 : innersortkeys = NIL;
1091 :
1092 : /*
1093 : * See comments in try_nestloop_path().
1094 : */
1095 983376 : initial_cost_mergejoin(root, &workspace, jointype, mergeclauses,
1096 : outer_path, inner_path,
1097 : outersortkeys, innersortkeys,
1098 : extra);
1099 :
1100 983376 : if (add_path_precheck(joinrel, workspace.disabled_nodes,
1101 : workspace.startup_cost, workspace.total_cost,
1102 : pathkeys, required_outer))
1103 : {
1104 257748 : add_path(joinrel, (Path *)
1105 257748 : create_mergejoin_path(root,
1106 : joinrel,
1107 : jointype,
1108 : &workspace,
1109 : extra,
1110 : outer_path,
1111 : inner_path,
1112 : extra->restrictlist,
1113 : pathkeys,
1114 : required_outer,
1115 : mergeclauses,
1116 : outersortkeys,
1117 : innersortkeys));
1118 : }
1119 : else
1120 : {
1121 : /* Waste no memory when we reject a path here */
1122 725628 : bms_free(required_outer);
1123 : }
1124 : }
1125 :
1126 : /*
1127 : * try_partial_mergejoin_path
1128 : * Consider a partial merge join path; if it appears useful, push it into
1129 : * the joinrel's pathlist via add_partial_path().
1130 : */
1131 : static void
1132 19040 : try_partial_mergejoin_path(PlannerInfo *root,
1133 : RelOptInfo *joinrel,
1134 : Path *outer_path,
1135 : Path *inner_path,
1136 : List *pathkeys,
1137 : List *mergeclauses,
1138 : List *outersortkeys,
1139 : List *innersortkeys,
1140 : JoinType jointype,
1141 : JoinPathExtraData *extra)
1142 : {
1143 : JoinCostWorkspace workspace;
1144 :
1145 : /*
1146 : * See comments in try_partial_hashjoin_path().
1147 : */
1148 : Assert(bms_is_empty(joinrel->lateral_relids));
1149 : Assert(bms_is_empty(PATH_REQ_OUTER(outer_path)));
1150 19040 : if (!bms_is_empty(PATH_REQ_OUTER(inner_path)))
1151 9876 : return;
1152 :
1153 : /*
1154 : * If the given paths are already well enough ordered, we can skip doing
1155 : * an explicit sort.
1156 : */
1157 31778 : if (outersortkeys &&
1158 12738 : pathkeys_contained_in(outersortkeys, outer_path->pathkeys))
1159 132 : outersortkeys = NIL;
1160 35496 : if (innersortkeys &&
1161 16456 : pathkeys_contained_in(innersortkeys, inner_path->pathkeys))
1162 252 : innersortkeys = NIL;
1163 :
1164 : /*
1165 : * See comments in try_partial_nestloop_path().
1166 : */
1167 19040 : initial_cost_mergejoin(root, &workspace, jointype, mergeclauses,
1168 : outer_path, inner_path,
1169 : outersortkeys, innersortkeys,
1170 : extra);
1171 :
1172 19040 : if (!add_partial_path_precheck(joinrel, workspace.disabled_nodes,
1173 : workspace.total_cost, pathkeys))
1174 9876 : return;
1175 :
1176 : /* Might be good enough to be worth trying, so let's try it. */
1177 9164 : add_partial_path(joinrel, (Path *)
1178 9164 : create_mergejoin_path(root,
1179 : joinrel,
1180 : jointype,
1181 : &workspace,
1182 : extra,
1183 : outer_path,
1184 : inner_path,
1185 : extra->restrictlist,
1186 : pathkeys,
1187 : NULL,
1188 : mergeclauses,
1189 : outersortkeys,
1190 : innersortkeys));
1191 : }
1192 :
1193 : /*
1194 : * try_hashjoin_path
1195 : * Consider a hash join path; if it appears useful, push it into
1196 : * the joinrel's pathlist via add_path().
1197 : */
1198 : static void
1199 617684 : try_hashjoin_path(PlannerInfo *root,
1200 : RelOptInfo *joinrel,
1201 : Path *outer_path,
1202 : Path *inner_path,
1203 : List *hashclauses,
1204 : JoinType jointype,
1205 : JoinPathExtraData *extra)
1206 : {
1207 : Relids required_outer;
1208 : JoinCostWorkspace workspace;
1209 :
1210 : /*
1211 : * If we are forming an outer join at this join, it's nonsensical to use
1212 : * an input path that uses the outer join as part of its parameterization.
1213 : * (This can happen despite our join order restrictions, since those apply
1214 : * to what is in an input relation not what its parameters are.)
1215 : */
1216 833178 : if (extra->sjinfo->ojrelid != 0 &&
1217 430958 : (bms_is_member(extra->sjinfo->ojrelid, PATH_REQ_OUTER(inner_path)) ||
1218 215464 : bms_is_member(extra->sjinfo->ojrelid, PATH_REQ_OUTER(outer_path))))
1219 89612 : return;
1220 :
1221 : /*
1222 : * Check to see if proposed path is still parameterized, and reject if the
1223 : * parameterization wouldn't be sensible.
1224 : */
1225 617624 : required_outer = calc_non_nestloop_required_outer(outer_path,
1226 : inner_path);
1227 617624 : if (required_outer &&
1228 102010 : !bms_overlap(required_outer, extra->param_source_rels))
1229 : {
1230 : /* Waste no memory when we reject a path here */
1231 89552 : bms_free(required_outer);
1232 89552 : return;
1233 : }
1234 :
1235 : /*
1236 : * See comments in try_nestloop_path(). Also note that hashjoin paths
1237 : * never have any output pathkeys, per comments in create_hashjoin_path.
1238 : */
1239 528072 : initial_cost_hashjoin(root, &workspace, jointype, hashclauses,
1240 : outer_path, inner_path, extra, false);
1241 :
1242 528072 : if (add_path_precheck(joinrel, workspace.disabled_nodes,
1243 : workspace.startup_cost, workspace.total_cost,
1244 : NIL, required_outer))
1245 : {
1246 223846 : add_path(joinrel, (Path *)
1247 223846 : create_hashjoin_path(root,
1248 : joinrel,
1249 : jointype,
1250 : &workspace,
1251 : extra,
1252 : outer_path,
1253 : inner_path,
1254 : false, /* parallel_hash */
1255 : extra->restrictlist,
1256 : required_outer,
1257 : hashclauses));
1258 : }
1259 : else
1260 : {
1261 : /* Waste no memory when we reject a path here */
1262 304226 : bms_free(required_outer);
1263 : }
1264 : }
1265 :
1266 : /*
1267 : * try_partial_hashjoin_path
1268 : * Consider a partial hashjoin join path; if it appears useful, push it into
1269 : * the joinrel's partial_pathlist via add_partial_path().
1270 : * The outer side is partial. If parallel_hash is true, then the inner path
1271 : * must be partial and will be run in parallel to create one or more shared
1272 : * hash tables; otherwise the inner path must be complete and a copy of it
1273 : * is run in every process to create separate identical private hash tables.
1274 : */
1275 : static void
1276 21152 : try_partial_hashjoin_path(PlannerInfo *root,
1277 : RelOptInfo *joinrel,
1278 : Path *outer_path,
1279 : Path *inner_path,
1280 : List *hashclauses,
1281 : JoinType jointype,
1282 : JoinPathExtraData *extra,
1283 : bool parallel_hash)
1284 : {
1285 : JoinCostWorkspace workspace;
1286 :
1287 : /*
1288 : * If the inner path is parameterized, we can't use a partial hashjoin.
1289 : * Parameterized partial paths are not supported. The caller should
1290 : * already have verified that no lateral rels are required here.
1291 : */
1292 : Assert(bms_is_empty(joinrel->lateral_relids));
1293 : Assert(bms_is_empty(PATH_REQ_OUTER(outer_path)));
1294 21152 : if (!bms_is_empty(PATH_REQ_OUTER(inner_path)))
1295 10200 : return;
1296 :
1297 : /*
1298 : * Before creating a path, get a quick lower bound on what it is likely to
1299 : * cost. Bail out right away if it looks terrible.
1300 : */
1301 21152 : initial_cost_hashjoin(root, &workspace, jointype, hashclauses,
1302 : outer_path, inner_path, extra, parallel_hash);
1303 21152 : if (!add_partial_path_precheck(joinrel, workspace.disabled_nodes,
1304 : workspace.total_cost, NIL))
1305 10200 : return;
1306 :
1307 : /* Might be good enough to be worth trying, so let's try it. */
1308 10952 : add_partial_path(joinrel, (Path *)
1309 10952 : create_hashjoin_path(root,
1310 : joinrel,
1311 : jointype,
1312 : &workspace,
1313 : extra,
1314 : outer_path,
1315 : inner_path,
1316 : parallel_hash,
1317 : extra->restrictlist,
1318 : NULL,
1319 : hashclauses));
1320 : }
1321 :
1322 : /*
1323 : * sort_inner_and_outer
1324 : * Create mergejoin join paths by explicitly sorting both the outer and
1325 : * inner join relations on each available merge ordering.
1326 : *
1327 : * 'joinrel' is the join relation
1328 : * 'outerrel' is the outer join relation
1329 : * 'innerrel' is the inner join relation
1330 : * 'jointype' is the type of join to do
1331 : * 'extra' contains additional input values
1332 : */
1333 : static void
1334 554366 : sort_inner_and_outer(PlannerInfo *root,
1335 : RelOptInfo *joinrel,
1336 : RelOptInfo *outerrel,
1337 : RelOptInfo *innerrel,
1338 : JoinType jointype,
1339 : JoinPathExtraData *extra)
1340 : {
1341 554366 : JoinType save_jointype = jointype;
1342 : Path *outer_path;
1343 : Path *inner_path;
1344 554366 : Path *cheapest_partial_outer = NULL;
1345 554366 : Path *cheapest_safe_inner = NULL;
1346 : List *all_pathkeys;
1347 : ListCell *l;
1348 :
1349 : /* Nothing to do if there are no available mergejoin clauses */
1350 554366 : if (extra->mergeclause_list == NIL)
1351 111698 : return;
1352 :
1353 : /*
1354 : * We only consider the cheapest-total-cost input paths, since we are
1355 : * assuming here that a sort is required. We will consider
1356 : * cheapest-startup-cost input paths later, and only if they don't need a
1357 : * sort.
1358 : *
1359 : * This function intentionally does not consider parameterized input
1360 : * paths, except when the cheapest-total is parameterized. If we did so,
1361 : * we'd have a combinatorial explosion of mergejoin paths of dubious
1362 : * value. This interacts with decisions elsewhere that also discriminate
1363 : * against mergejoins with parameterized inputs; see comments in
1364 : * src/backend/optimizer/README.
1365 : */
1366 442668 : outer_path = outerrel->cheapest_total_path;
1367 442668 : inner_path = innerrel->cheapest_total_path;
1368 :
1369 : /*
1370 : * If either cheapest-total path is parameterized by the other rel, we
1371 : * can't use a mergejoin. (There's no use looking for alternative input
1372 : * paths, since these should already be the least-parameterized available
1373 : * paths.)
1374 : */
1375 442668 : if (PATH_PARAM_BY_REL(outer_path, innerrel) ||
1376 441980 : PATH_PARAM_BY_REL(inner_path, outerrel))
1377 1388 : return;
1378 :
1379 : /*
1380 : * If unique-ification is requested, do it and then handle as a plain
1381 : * inner join.
1382 : */
1383 441280 : if (jointype == JOIN_UNIQUE_OUTER)
1384 : {
1385 2732 : outer_path = (Path *) create_unique_path(root, outerrel,
1386 : outer_path, extra->sjinfo);
1387 : Assert(outer_path);
1388 2732 : jointype = JOIN_INNER;
1389 : }
1390 438548 : else if (jointype == JOIN_UNIQUE_INNER)
1391 : {
1392 2732 : inner_path = (Path *) create_unique_path(root, innerrel,
1393 : inner_path, extra->sjinfo);
1394 : Assert(inner_path);
1395 2732 : jointype = JOIN_INNER;
1396 : }
1397 :
1398 : /*
1399 : * If the joinrel is parallel-safe, we may be able to consider a partial
1400 : * merge join. However, we can't handle JOIN_UNIQUE_OUTER, because the
1401 : * outer path will be partial, and therefore we won't be able to properly
1402 : * guarantee uniqueness. Similarly, we can't handle JOIN_FULL, JOIN_RIGHT
1403 : * and JOIN_RIGHT_ANTI, because they can produce false null extended rows.
1404 : * Also, the resulting path must not be parameterized.
1405 : */
1406 441280 : if (joinrel->consider_parallel &&
1407 391360 : save_jointype != JOIN_UNIQUE_OUTER &&
1408 389016 : save_jointype != JOIN_FULL &&
1409 319686 : save_jointype != JOIN_RIGHT &&
1410 318384 : save_jointype != JOIN_RIGHT_ANTI &&
1411 318384 : outerrel->partial_pathlist != NIL &&
1412 9182 : bms_is_empty(joinrel->lateral_relids))
1413 : {
1414 9182 : cheapest_partial_outer = (Path *) linitial(outerrel->partial_pathlist);
1415 :
1416 9182 : if (inner_path->parallel_safe)
1417 9086 : cheapest_safe_inner = inner_path;
1418 96 : else if (save_jointype != JOIN_UNIQUE_INNER)
1419 : cheapest_safe_inner =
1420 90 : get_cheapest_parallel_safe_total_inner(innerrel->pathlist);
1421 : }
1422 :
1423 : /*
1424 : * Each possible ordering of the available mergejoin clauses will generate
1425 : * a differently-sorted result path at essentially the same cost. We have
1426 : * no basis for choosing one over another at this level of joining, but
1427 : * some sort orders may be more useful than others for higher-level
1428 : * mergejoins, so it's worth considering multiple orderings.
1429 : *
1430 : * Actually, it's not quite true that every mergeclause ordering will
1431 : * generate a different path order, because some of the clauses may be
1432 : * partially redundant (refer to the same EquivalenceClasses). Therefore,
1433 : * what we do is convert the mergeclause list to a list of canonical
1434 : * pathkeys, and then consider different orderings of the pathkeys.
1435 : *
1436 : * Generating a path for *every* permutation of the pathkeys doesn't seem
1437 : * like a winning strategy; the cost in planning time is too high. For
1438 : * now, we generate one path for each pathkey, listing that pathkey first
1439 : * and the rest in random order. This should allow at least a one-clause
1440 : * mergejoin without re-sorting against any other possible mergejoin
1441 : * partner path. But if we've not guessed the right ordering of secondary
1442 : * keys, we may end up evaluating clauses as qpquals when they could have
1443 : * been done as mergeclauses. (In practice, it's rare that there's more
1444 : * than two or three mergeclauses, so expending a huge amount of thought
1445 : * on that is probably not worth it.)
1446 : *
1447 : * The pathkey order returned by select_outer_pathkeys_for_merge() has
1448 : * some heuristics behind it (see that function), so be sure to try it
1449 : * exactly as-is as well as making variants.
1450 : */
1451 441280 : all_pathkeys = select_outer_pathkeys_for_merge(root,
1452 : extra->mergeclause_list,
1453 : joinrel);
1454 :
1455 926836 : foreach(l, all_pathkeys)
1456 : {
1457 485556 : PathKey *front_pathkey = (PathKey *) lfirst(l);
1458 : List *cur_mergeclauses;
1459 : List *outerkeys;
1460 : List *innerkeys;
1461 : List *merge_pathkeys;
1462 :
1463 : /* Make a pathkey list with this guy first */
1464 485556 : if (l != list_head(all_pathkeys))
1465 44276 : outerkeys = lcons(front_pathkey,
1466 : list_delete_nth_cell(list_copy(all_pathkeys),
1467 : foreach_current_index(l)));
1468 : else
1469 441280 : outerkeys = all_pathkeys; /* no work at first one... */
1470 :
1471 : /* Sort the mergeclauses into the corresponding ordering */
1472 : cur_mergeclauses =
1473 485556 : find_mergeclauses_for_outer_pathkeys(root,
1474 : outerkeys,
1475 : extra->mergeclause_list);
1476 :
1477 : /* Should have used them all... */
1478 : Assert(list_length(cur_mergeclauses) == list_length(extra->mergeclause_list));
1479 :
1480 : /* Build sort pathkeys for the inner side */
1481 485556 : innerkeys = make_inner_pathkeys_for_merge(root,
1482 : cur_mergeclauses,
1483 : outerkeys);
1484 :
1485 : /* Build pathkeys representing output sort order */
1486 485556 : merge_pathkeys = build_join_pathkeys(root, joinrel, jointype,
1487 : outerkeys);
1488 :
1489 : /*
1490 : * And now we can make the path.
1491 : *
1492 : * Note: it's possible that the cheapest paths will already be sorted
1493 : * properly. try_mergejoin_path will detect that case and suppress an
1494 : * explicit sort step, so we needn't do so here.
1495 : */
1496 485556 : try_mergejoin_path(root,
1497 : joinrel,
1498 : outer_path,
1499 : inner_path,
1500 : merge_pathkeys,
1501 : cur_mergeclauses,
1502 : outerkeys,
1503 : innerkeys,
1504 : jointype,
1505 : extra,
1506 : false);
1507 :
1508 : /*
1509 : * If we have partial outer and parallel safe inner path then try
1510 : * partial mergejoin path.
1511 : */
1512 485556 : if (cheapest_partial_outer && cheapest_safe_inner)
1513 12738 : try_partial_mergejoin_path(root,
1514 : joinrel,
1515 : cheapest_partial_outer,
1516 : cheapest_safe_inner,
1517 : merge_pathkeys,
1518 : cur_mergeclauses,
1519 : outerkeys,
1520 : innerkeys,
1521 : jointype,
1522 : extra);
1523 : }
1524 : }
1525 :
1526 : /*
1527 : * generate_mergejoin_paths
1528 : * Creates possible mergejoin paths for input outerpath.
1529 : *
1530 : * We generate mergejoins if mergejoin clauses are available. We have
1531 : * two ways to generate the inner path for a mergejoin: sort the cheapest
1532 : * inner path, or use an inner path that is already suitably ordered for the
1533 : * merge. If we have several mergeclauses, it could be that there is no inner
1534 : * path (or only a very expensive one) for the full list of mergeclauses, but
1535 : * better paths exist if we truncate the mergeclause list (thereby discarding
1536 : * some sort key requirements). So, we consider truncations of the
1537 : * mergeclause list as well as the full list. (Ideally we'd consider all
1538 : * subsets of the mergeclause list, but that seems way too expensive.)
1539 : */
1540 : static void
1541 1038756 : generate_mergejoin_paths(PlannerInfo *root,
1542 : RelOptInfo *joinrel,
1543 : RelOptInfo *innerrel,
1544 : Path *outerpath,
1545 : JoinType jointype,
1546 : JoinPathExtraData *extra,
1547 : bool useallclauses,
1548 : Path *inner_cheapest_total,
1549 : List *merge_pathkeys,
1550 : bool is_partial)
1551 : {
1552 : List *mergeclauses;
1553 : List *innersortkeys;
1554 : List *trialsortkeys;
1555 : Path *cheapest_startup_inner;
1556 : Path *cheapest_total_inner;
1557 1038756 : JoinType save_jointype = jointype;
1558 : int num_sortkeys;
1559 : int sortkeycnt;
1560 :
1561 1038756 : if (jointype == JOIN_UNIQUE_OUTER || jointype == JOIN_UNIQUE_INNER)
1562 8900 : jointype = JOIN_INNER;
1563 :
1564 : /* Look for useful mergeclauses (if any) */
1565 : mergeclauses =
1566 1038756 : find_mergeclauses_for_outer_pathkeys(root,
1567 : outerpath->pathkeys,
1568 : extra->mergeclause_list);
1569 :
1570 : /*
1571 : * Done with this outer path if no chance for a mergejoin.
1572 : *
1573 : * Special corner case: for "x FULL JOIN y ON true", there will be no join
1574 : * clauses at all. Ordinarily we'd generate a clauseless nestloop path,
1575 : * but since mergejoin is our only join type that supports FULL JOIN
1576 : * without any join clauses, it's necessary to generate a clauseless
1577 : * mergejoin path instead.
1578 : */
1579 1038756 : if (mergeclauses == NIL)
1580 : {
1581 694660 : if (jointype == JOIN_FULL)
1582 : /* okay to try for mergejoin */ ;
1583 : else
1584 691300 : return;
1585 : }
1586 422228 : if (useallclauses &&
1587 74772 : list_length(mergeclauses) != list_length(extra->mergeclause_list))
1588 10752 : return;
1589 :
1590 : /* Compute the required ordering of the inner path */
1591 336704 : innersortkeys = make_inner_pathkeys_for_merge(root,
1592 : mergeclauses,
1593 : outerpath->pathkeys);
1594 :
1595 : /*
1596 : * Generate a mergejoin on the basis of sorting the cheapest inner. Since
1597 : * a sort will be needed, only cheapest total cost matters. (But
1598 : * try_mergejoin_path will do the right thing if inner_cheapest_total is
1599 : * already correctly sorted.)
1600 : */
1601 336704 : try_mergejoin_path(root,
1602 : joinrel,
1603 : outerpath,
1604 : inner_cheapest_total,
1605 : merge_pathkeys,
1606 : mergeclauses,
1607 : NIL,
1608 : innersortkeys,
1609 : jointype,
1610 : extra,
1611 : is_partial);
1612 :
1613 : /* Can't do anything else if inner path needs to be unique'd */
1614 336704 : if (save_jointype == JOIN_UNIQUE_INNER)
1615 1798 : return;
1616 :
1617 : /*
1618 : * Look for presorted inner paths that satisfy the innersortkey list ---
1619 : * or any truncation thereof, if we are allowed to build a mergejoin using
1620 : * a subset of the merge clauses. Here, we consider both cheap startup
1621 : * cost and cheap total cost.
1622 : *
1623 : * Currently we do not consider parameterized inner paths here. This
1624 : * interacts with decisions elsewhere that also discriminate against
1625 : * mergejoins with parameterized inputs; see comments in
1626 : * src/backend/optimizer/README.
1627 : *
1628 : * As we shorten the sortkey list, we should consider only paths that are
1629 : * strictly cheaper than (in particular, not the same as) any path found
1630 : * in an earlier iteration. Otherwise we'd be intentionally using fewer
1631 : * merge keys than a given path allows (treating the rest as plain
1632 : * joinquals), which is unlikely to be a good idea. Also, eliminating
1633 : * paths here on the basis of compare_path_costs is a lot cheaper than
1634 : * building the mergejoin path only to throw it away.
1635 : *
1636 : * If inner_cheapest_total is well enough sorted to have not required a
1637 : * sort in the path made above, we shouldn't make a duplicate path with
1638 : * it, either. We handle that case with the same logic that handles the
1639 : * previous consideration, by initializing the variables that track
1640 : * cheapest-so-far properly. Note that we do NOT reject
1641 : * inner_cheapest_total if we find it matches some shorter set of
1642 : * pathkeys. That case corresponds to using fewer mergekeys to avoid
1643 : * sorting inner_cheapest_total, whereas we did sort it above, so the
1644 : * plans being considered are different.
1645 : */
1646 334906 : if (pathkeys_contained_in(innersortkeys,
1647 : inner_cheapest_total->pathkeys))
1648 : {
1649 : /* inner_cheapest_total didn't require a sort */
1650 17384 : cheapest_startup_inner = inner_cheapest_total;
1651 17384 : cheapest_total_inner = inner_cheapest_total;
1652 : }
1653 : else
1654 : {
1655 : /* it did require a sort, at least for the full set of keys */
1656 317522 : cheapest_startup_inner = NULL;
1657 317522 : cheapest_total_inner = NULL;
1658 : }
1659 334906 : num_sortkeys = list_length(innersortkeys);
1660 334906 : if (num_sortkeys > 1 && !useallclauses)
1661 11170 : trialsortkeys = list_copy(innersortkeys); /* need modifiable copy */
1662 : else
1663 323736 : trialsortkeys = innersortkeys; /* won't really truncate */
1664 :
1665 617098 : for (sortkeycnt = num_sortkeys; sortkeycnt > 0; sortkeycnt--)
1666 : {
1667 : Path *innerpath;
1668 346068 : List *newclauses = NIL;
1669 :
1670 : /*
1671 : * Look for an inner path ordered well enough for the first
1672 : * 'sortkeycnt' innersortkeys. NB: trialsortkeys list is modified
1673 : * destructively, which is why we made a copy...
1674 : */
1675 346068 : trialsortkeys = list_truncate(trialsortkeys, sortkeycnt);
1676 346068 : innerpath = get_cheapest_path_for_pathkeys(innerrel->pathlist,
1677 : trialsortkeys,
1678 : NULL,
1679 : TOTAL_COST,
1680 : is_partial);
1681 346068 : if (innerpath != NULL &&
1682 24094 : (cheapest_total_inner == NULL ||
1683 24094 : compare_path_costs(innerpath, cheapest_total_inner,
1684 : TOTAL_COST) < 0))
1685 : {
1686 : /* Found a cheap (or even-cheaper) sorted path */
1687 : /* Select the right mergeclauses, if we didn't already */
1688 194814 : if (sortkeycnt < num_sortkeys)
1689 : {
1690 : newclauses =
1691 3674 : trim_mergeclauses_for_inner_pathkeys(root,
1692 : mergeclauses,
1693 : trialsortkeys);
1694 : Assert(newclauses != NIL);
1695 : }
1696 : else
1697 191140 : newclauses = mergeclauses;
1698 194814 : try_mergejoin_path(root,
1699 : joinrel,
1700 : outerpath,
1701 : innerpath,
1702 : merge_pathkeys,
1703 : newclauses,
1704 : NIL,
1705 : NIL,
1706 : jointype,
1707 : extra,
1708 : is_partial);
1709 194814 : cheapest_total_inner = innerpath;
1710 : }
1711 : /* Same on the basis of cheapest startup cost ... */
1712 346068 : innerpath = get_cheapest_path_for_pathkeys(innerrel->pathlist,
1713 : trialsortkeys,
1714 : NULL,
1715 : STARTUP_COST,
1716 : is_partial);
1717 346068 : if (innerpath != NULL &&
1718 24094 : (cheapest_startup_inner == NULL ||
1719 24094 : compare_path_costs(innerpath, cheapest_startup_inner,
1720 : STARTUP_COST) < 0))
1721 : {
1722 : /* Found a cheap (or even-cheaper) sorted path */
1723 193194 : if (innerpath != cheapest_total_inner)
1724 : {
1725 : /*
1726 : * Avoid rebuilding clause list if we already made one; saves
1727 : * memory in big join trees...
1728 : */
1729 1378 : if (newclauses == NIL)
1730 : {
1731 52 : if (sortkeycnt < num_sortkeys)
1732 : {
1733 : newclauses =
1734 12 : trim_mergeclauses_for_inner_pathkeys(root,
1735 : mergeclauses,
1736 : trialsortkeys);
1737 : Assert(newclauses != NIL);
1738 : }
1739 : else
1740 40 : newclauses = mergeclauses;
1741 : }
1742 1378 : try_mergejoin_path(root,
1743 : joinrel,
1744 : outerpath,
1745 : innerpath,
1746 : merge_pathkeys,
1747 : newclauses,
1748 : NIL,
1749 : NIL,
1750 : jointype,
1751 : extra,
1752 : is_partial);
1753 : }
1754 193194 : cheapest_startup_inner = innerpath;
1755 : }
1756 :
1757 : /*
1758 : * Don't consider truncated sortkeys if we need all clauses.
1759 : */
1760 346068 : if (useallclauses)
1761 63876 : break;
1762 : }
1763 : }
1764 :
1765 : /*
1766 : * match_unsorted_outer
1767 : * Creates possible join paths for processing a single join relation
1768 : * 'joinrel' by employing either iterative substitution or
1769 : * mergejoining on each of its possible outer paths (considering
1770 : * only outer paths that are already ordered well enough for merging).
1771 : *
1772 : * We always generate a nestloop path for each available outer path.
1773 : * In fact we may generate as many as five: one on the cheapest-total-cost
1774 : * inner path, one on the same with materialization, one on the
1775 : * cheapest-startup-cost inner path (if different), one on the
1776 : * cheapest-total inner-indexscan path (if any), and one on the
1777 : * cheapest-startup inner-indexscan path (if different).
1778 : *
1779 : * We also consider mergejoins if mergejoin clauses are available. See
1780 : * detailed comments in generate_mergejoin_paths.
1781 : *
1782 : * 'joinrel' is the join relation
1783 : * 'outerrel' is the outer join relation
1784 : * 'innerrel' is the inner join relation
1785 : * 'jointype' is the type of join to do
1786 : * 'extra' contains additional input values
1787 : */
1788 : static void
1789 554366 : match_unsorted_outer(PlannerInfo *root,
1790 : RelOptInfo *joinrel,
1791 : RelOptInfo *outerrel,
1792 : RelOptInfo *innerrel,
1793 : JoinType jointype,
1794 : JoinPathExtraData *extra)
1795 : {
1796 554366 : JoinType save_jointype = jointype;
1797 : bool nestjoinOK;
1798 : bool useallclauses;
1799 554366 : Path *inner_cheapest_total = innerrel->cheapest_total_path;
1800 554366 : Path *matpath = NULL;
1801 : ListCell *lc1;
1802 :
1803 : /*
1804 : * For now we do not support RIGHT_SEMI join in mergejoin or nestloop
1805 : * join.
1806 : */
1807 554366 : if (jointype == JOIN_RIGHT_SEMI)
1808 0 : return;
1809 :
1810 : /*
1811 : * Nestloop only supports inner, left, semi, and anti joins. Also, if we
1812 : * are doing a right, right-anti or full mergejoin, we must use *all* the
1813 : * mergeclauses as join clauses, else we will not have a valid plan.
1814 : * (Although these two flags are currently inverses, keep them separate
1815 : * for clarity and possible future changes.)
1816 : */
1817 554366 : switch (jointype)
1818 : {
1819 463732 : case JOIN_INNER:
1820 : case JOIN_LEFT:
1821 : case JOIN_SEMI:
1822 : case JOIN_ANTI:
1823 463732 : nestjoinOK = true;
1824 463732 : useallclauses = false;
1825 463732 : break;
1826 81978 : case JOIN_RIGHT:
1827 : case JOIN_RIGHT_ANTI:
1828 : case JOIN_FULL:
1829 81978 : nestjoinOK = false;
1830 81978 : useallclauses = true;
1831 81978 : break;
1832 8656 : case JOIN_UNIQUE_OUTER:
1833 : case JOIN_UNIQUE_INNER:
1834 8656 : jointype = JOIN_INNER;
1835 8656 : nestjoinOK = true;
1836 8656 : useallclauses = false;
1837 8656 : break;
1838 0 : default:
1839 0 : elog(ERROR, "unrecognized join type: %d",
1840 : (int) jointype);
1841 : nestjoinOK = false; /* keep compiler quiet */
1842 : useallclauses = false;
1843 : break;
1844 : }
1845 :
1846 : /*
1847 : * If inner_cheapest_total is parameterized by the outer rel, ignore it;
1848 : * we will consider it below as a member of cheapest_parameterized_paths,
1849 : * but the other possibilities considered in this routine aren't usable.
1850 : */
1851 554366 : if (PATH_PARAM_BY_REL(inner_cheapest_total, outerrel))
1852 11662 : inner_cheapest_total = NULL;
1853 :
1854 : /*
1855 : * If we need to unique-ify the inner path, we will consider only the
1856 : * cheapest-total inner.
1857 : */
1858 554366 : if (save_jointype == JOIN_UNIQUE_INNER)
1859 : {
1860 : /* No way to do this with an inner path parameterized by outer rel */
1861 4328 : if (inner_cheapest_total == NULL)
1862 12 : return;
1863 : inner_cheapest_total = (Path *)
1864 4316 : create_unique_path(root, innerrel, inner_cheapest_total, extra->sjinfo);
1865 : Assert(inner_cheapest_total);
1866 : }
1867 550038 : else if (nestjoinOK)
1868 : {
1869 : /*
1870 : * Consider materializing the cheapest inner path, unless
1871 : * enable_material is off or the path in question materializes its
1872 : * output anyway.
1873 : */
1874 468060 : if (enable_material && inner_cheapest_total != NULL &&
1875 455976 : !ExecMaterializesOutput(inner_cheapest_total->pathtype))
1876 : matpath = (Path *)
1877 434820 : create_material_path(innerrel, inner_cheapest_total);
1878 : }
1879 :
1880 1807580 : foreach(lc1, outerrel->pathlist)
1881 : {
1882 1253226 : Path *outerpath = (Path *) lfirst(lc1);
1883 : List *merge_pathkeys;
1884 :
1885 : /*
1886 : * We cannot use an outer path that is parameterized by the inner rel.
1887 : */
1888 1253226 : if (PATH_PARAM_BY_REL(outerpath, innerrel))
1889 210876 : continue;
1890 :
1891 : /*
1892 : * If we need to unique-ify the outer path, it's pointless to consider
1893 : * any but the cheapest outer. (XXX we don't consider parameterized
1894 : * outers, nor inners, for unique-ified cases. Should we?)
1895 : */
1896 1042350 : if (save_jointype == JOIN_UNIQUE_OUTER)
1897 : {
1898 5002 : if (outerpath != outerrel->cheapest_total_path)
1899 686 : continue;
1900 4316 : outerpath = (Path *) create_unique_path(root, outerrel,
1901 : outerpath, extra->sjinfo);
1902 : Assert(outerpath);
1903 : }
1904 :
1905 : /*
1906 : * The result will have this sort order (even if it is implemented as
1907 : * a nestloop, and even if some of the mergeclauses are implemented by
1908 : * qpquals rather than as true mergeclauses):
1909 : */
1910 1041664 : merge_pathkeys = build_join_pathkeys(root, joinrel, jointype,
1911 : outerpath->pathkeys);
1912 :
1913 1041664 : if (save_jointype == JOIN_UNIQUE_INNER)
1914 : {
1915 : /*
1916 : * Consider nestloop join, but only with the unique-ified cheapest
1917 : * inner path
1918 : */
1919 8048 : try_nestloop_path(root,
1920 : joinrel,
1921 : outerpath,
1922 : inner_cheapest_total,
1923 : merge_pathkeys,
1924 : jointype,
1925 : extra);
1926 : }
1927 1033616 : else if (nestjoinOK)
1928 : {
1929 : /*
1930 : * Consider nestloop joins using this outer path and various
1931 : * available paths for the inner relation. We consider the
1932 : * cheapest-total paths for each available parameterization of the
1933 : * inner relation, including the unparameterized case.
1934 : */
1935 : ListCell *lc2;
1936 :
1937 2304744 : foreach(lc2, innerrel->cheapest_parameterized_paths)
1938 : {
1939 1424338 : Path *innerpath = (Path *) lfirst(lc2);
1940 : Path *mpath;
1941 :
1942 1424338 : try_nestloop_path(root,
1943 : joinrel,
1944 : outerpath,
1945 : innerpath,
1946 : merge_pathkeys,
1947 : jointype,
1948 : extra);
1949 :
1950 : /*
1951 : * Try generating a memoize path and see if that makes the
1952 : * nested loop any cheaper.
1953 : */
1954 1424338 : mpath = get_memoize_path(root, innerrel, outerrel,
1955 : innerpath, outerpath, jointype,
1956 : extra);
1957 1424338 : if (mpath != NULL)
1958 242926 : try_nestloop_path(root,
1959 : joinrel,
1960 : outerpath,
1961 : mpath,
1962 : merge_pathkeys,
1963 : jointype,
1964 : extra);
1965 : }
1966 :
1967 : /* Also consider materialized form of the cheapest inner path */
1968 880406 : if (matpath != NULL)
1969 826688 : try_nestloop_path(root,
1970 : joinrel,
1971 : outerpath,
1972 : matpath,
1973 : merge_pathkeys,
1974 : jointype,
1975 : extra);
1976 : }
1977 :
1978 : /* Can't do anything else if outer path needs to be unique'd */
1979 1041664 : if (save_jointype == JOIN_UNIQUE_OUTER)
1980 4316 : continue;
1981 :
1982 : /* Can't do anything else if inner rel is parameterized by outer */
1983 1037348 : if (inner_cheapest_total == NULL)
1984 12528 : continue;
1985 :
1986 : /* Generate merge join paths */
1987 1024820 : generate_mergejoin_paths(root, joinrel, innerrel, outerpath,
1988 : save_jointype, extra, useallclauses,
1989 : inner_cheapest_total, merge_pathkeys,
1990 : false);
1991 : }
1992 :
1993 : /*
1994 : * Consider partial nestloop and mergejoin plan if outerrel has any
1995 : * partial path and the joinrel is parallel-safe. However, we can't
1996 : * handle JOIN_UNIQUE_OUTER, because the outer path will be partial, and
1997 : * therefore we won't be able to properly guarantee uniqueness. Nor can
1998 : * we handle joins needing lateral rels, since partial paths must not be
1999 : * parameterized. Similarly, we can't handle JOIN_FULL, JOIN_RIGHT and
2000 : * JOIN_RIGHT_ANTI, because they can produce false null extended rows.
2001 : */
2002 554354 : if (joinrel->consider_parallel &&
2003 463784 : save_jointype != JOIN_UNIQUE_OUTER &&
2004 461320 : save_jointype != JOIN_FULL &&
2005 390502 : save_jointype != JOIN_RIGHT &&
2006 389200 : save_jointype != JOIN_RIGHT_ANTI &&
2007 389200 : outerrel->partial_pathlist != NIL &&
2008 10798 : bms_is_empty(joinrel->lateral_relids))
2009 : {
2010 10798 : if (nestjoinOK)
2011 10798 : consider_parallel_nestloop(root, joinrel, outerrel, innerrel,
2012 : save_jointype, extra);
2013 :
2014 : /*
2015 : * If inner_cheapest_total is NULL or non parallel-safe then find the
2016 : * cheapest total parallel safe path. If doing JOIN_UNIQUE_INNER, we
2017 : * can't use any alternative inner path.
2018 : */
2019 10798 : if (inner_cheapest_total == NULL ||
2020 10390 : !inner_cheapest_total->parallel_safe)
2021 : {
2022 780 : if (save_jointype == JOIN_UNIQUE_INNER)
2023 6 : return;
2024 :
2025 774 : inner_cheapest_total = get_cheapest_parallel_safe_total_inner(innerrel->pathlist);
2026 : }
2027 :
2028 10792 : if (inner_cheapest_total)
2029 10378 : consider_parallel_mergejoin(root, joinrel, outerrel, innerrel,
2030 : save_jointype, extra,
2031 : inner_cheapest_total);
2032 : }
2033 : }
2034 :
2035 : /*
2036 : * consider_parallel_mergejoin
2037 : * Try to build partial paths for a joinrel by joining a partial path
2038 : * for the outer relation to a complete path for the inner relation.
2039 : *
2040 : * 'joinrel' is the join relation
2041 : * 'outerrel' is the outer join relation
2042 : * 'innerrel' is the inner join relation
2043 : * 'jointype' is the type of join to do
2044 : * 'extra' contains additional input values
2045 : * 'inner_cheapest_total' cheapest total path for innerrel
2046 : */
2047 : static void
2048 10378 : consider_parallel_mergejoin(PlannerInfo *root,
2049 : RelOptInfo *joinrel,
2050 : RelOptInfo *outerrel,
2051 : RelOptInfo *innerrel,
2052 : JoinType jointype,
2053 : JoinPathExtraData *extra,
2054 : Path *inner_cheapest_total)
2055 : {
2056 : ListCell *lc1;
2057 :
2058 : /* generate merge join path for each partial outer path */
2059 24314 : foreach(lc1, outerrel->partial_pathlist)
2060 : {
2061 13936 : Path *outerpath = (Path *) lfirst(lc1);
2062 : List *merge_pathkeys;
2063 :
2064 : /*
2065 : * Figure out what useful ordering any paths we create will have.
2066 : */
2067 13936 : merge_pathkeys = build_join_pathkeys(root, joinrel, jointype,
2068 : outerpath->pathkeys);
2069 :
2070 13936 : generate_mergejoin_paths(root, joinrel, innerrel, outerpath, jointype,
2071 : extra, false, inner_cheapest_total,
2072 : merge_pathkeys, true);
2073 : }
2074 10378 : }
2075 :
2076 : /*
2077 : * consider_parallel_nestloop
2078 : * Try to build partial paths for a joinrel by joining a partial path for the
2079 : * outer relation to a complete path for the inner relation.
2080 : *
2081 : * 'joinrel' is the join relation
2082 : * 'outerrel' is the outer join relation
2083 : * 'innerrel' is the inner join relation
2084 : * 'jointype' is the type of join to do
2085 : * 'extra' contains additional input values
2086 : */
2087 : static void
2088 10798 : consider_parallel_nestloop(PlannerInfo *root,
2089 : RelOptInfo *joinrel,
2090 : RelOptInfo *outerrel,
2091 : RelOptInfo *innerrel,
2092 : JoinType jointype,
2093 : JoinPathExtraData *extra)
2094 : {
2095 10798 : JoinType save_jointype = jointype;
2096 10798 : Path *inner_cheapest_total = innerrel->cheapest_total_path;
2097 10798 : Path *matpath = NULL;
2098 : ListCell *lc1;
2099 :
2100 10798 : if (jointype == JOIN_UNIQUE_INNER)
2101 570 : jointype = JOIN_INNER;
2102 :
2103 : /*
2104 : * Consider materializing the cheapest inner path, unless: 1) we're doing
2105 : * JOIN_UNIQUE_INNER, because in this case we have to unique-ify the
2106 : * cheapest inner path, 2) enable_material is off, 3) the cheapest inner
2107 : * path is not parallel-safe, 4) the cheapest inner path is parameterized
2108 : * by the outer rel, or 5) the cheapest inner path materializes its output
2109 : * anyway.
2110 : */
2111 10798 : if (save_jointype != JOIN_UNIQUE_INNER &&
2112 10024 : enable_material && inner_cheapest_total->parallel_safe &&
2113 9832 : !PATH_PARAM_BY_REL(inner_cheapest_total, outerrel) &&
2114 9442 : !ExecMaterializesOutput(inner_cheapest_total->pathtype))
2115 : {
2116 : matpath = (Path *)
2117 9346 : create_material_path(innerrel, inner_cheapest_total);
2118 : Assert(matpath->parallel_safe);
2119 : }
2120 :
2121 25292 : foreach(lc1, outerrel->partial_pathlist)
2122 : {
2123 14494 : Path *outerpath = (Path *) lfirst(lc1);
2124 : List *pathkeys;
2125 : ListCell *lc2;
2126 :
2127 : /* Figure out what useful ordering any paths we create will have. */
2128 14494 : pathkeys = build_join_pathkeys(root, joinrel, jointype,
2129 : outerpath->pathkeys);
2130 :
2131 : /*
2132 : * Try the cheapest parameterized paths; only those which will produce
2133 : * an unparameterized path when joined to this outerrel will survive
2134 : * try_partial_nestloop_path. The cheapest unparameterized path is
2135 : * also in this list.
2136 : */
2137 37628 : foreach(lc2, innerrel->cheapest_parameterized_paths)
2138 : {
2139 23134 : Path *innerpath = (Path *) lfirst(lc2);
2140 : Path *mpath;
2141 :
2142 : /* Can't join to an inner path that is not parallel-safe */
2143 23134 : if (!innerpath->parallel_safe)
2144 426 : continue;
2145 :
2146 : /*
2147 : * If we're doing JOIN_UNIQUE_INNER, we can only use the inner's
2148 : * cheapest_total_path, and we have to unique-ify it. (We might
2149 : * be able to relax this to allow other safe, unparameterized
2150 : * inner paths, but right now create_unique_path is not on board
2151 : * with that.)
2152 : */
2153 22708 : if (save_jointype == JOIN_UNIQUE_INNER)
2154 : {
2155 1734 : if (innerpath != innerrel->cheapest_total_path)
2156 882 : continue;
2157 852 : innerpath = (Path *) create_unique_path(root, innerrel,
2158 : innerpath,
2159 : extra->sjinfo);
2160 : Assert(innerpath);
2161 : }
2162 :
2163 21826 : try_partial_nestloop_path(root, joinrel, outerpath, innerpath,
2164 : pathkeys, jointype, extra);
2165 :
2166 : /*
2167 : * Try generating a memoize path and see if that makes the nested
2168 : * loop any cheaper.
2169 : */
2170 21826 : mpath = get_memoize_path(root, innerrel, outerrel,
2171 : innerpath, outerpath, jointype,
2172 : extra);
2173 21826 : if (mpath != NULL)
2174 5408 : try_partial_nestloop_path(root, joinrel, outerpath, mpath,
2175 : pathkeys, jointype, extra);
2176 : }
2177 :
2178 : /* Also consider materialized form of the cheapest inner path */
2179 14494 : if (matpath != NULL)
2180 12592 : try_partial_nestloop_path(root, joinrel, outerpath, matpath,
2181 : pathkeys, jointype, extra);
2182 : }
2183 10798 : }
2184 :
2185 : /*
2186 : * hash_inner_and_outer
2187 : * Create hashjoin join paths by explicitly hashing both the outer and
2188 : * inner keys of each available hash clause.
2189 : *
2190 : * 'joinrel' is the join relation
2191 : * 'outerrel' is the outer join relation
2192 : * 'innerrel' is the inner join relation
2193 : * 'jointype' is the type of join to do
2194 : * 'extra' contains additional input values
2195 : */
2196 : static void
2197 562756 : hash_inner_and_outer(PlannerInfo *root,
2198 : RelOptInfo *joinrel,
2199 : RelOptInfo *outerrel,
2200 : RelOptInfo *innerrel,
2201 : JoinType jointype,
2202 : JoinPathExtraData *extra)
2203 : {
2204 562756 : JoinType save_jointype = jointype;
2205 562756 : bool isouterjoin = IS_OUTER_JOIN(jointype);
2206 : List *hashclauses;
2207 : ListCell *l;
2208 :
2209 : /*
2210 : * We need to build only one hashclauses list for any given pair of outer
2211 : * and inner relations; all of the hashable clauses will be used as keys.
2212 : *
2213 : * Scan the join's restrictinfo list to find hashjoinable clauses that are
2214 : * usable with this pair of sub-relations.
2215 : */
2216 562756 : hashclauses = NIL;
2217 1148824 : foreach(l, extra->restrictlist)
2218 : {
2219 586068 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
2220 :
2221 : /*
2222 : * If processing an outer join, only use its own join clauses for
2223 : * hashing. For inner joins we need not be so picky.
2224 : */
2225 586068 : if (isouterjoin && RINFO_IS_PUSHED_DOWN(restrictinfo, joinrel->relids))
2226 9052 : continue;
2227 :
2228 577016 : if (!restrictinfo->can_join ||
2229 511856 : restrictinfo->hashjoinoperator == InvalidOid)
2230 81840 : continue; /* not hashjoinable */
2231 :
2232 : /*
2233 : * Check if clause has the form "outer op inner" or "inner op outer".
2234 : */
2235 495176 : if (!clause_sides_match_join(restrictinfo, outerrel->relids,
2236 : innerrel->relids))
2237 144 : continue; /* no good for these input relations */
2238 :
2239 : /*
2240 : * If clause has the form "inner op outer", check if its operator has
2241 : * valid commutator. This is necessary because hashclauses in this
2242 : * form will get commuted in createplan.c to put the outer var on the
2243 : * left (see get_switched_clauses). This probably shouldn't ever
2244 : * fail, since hashable operators ought to have commutators, but be
2245 : * paranoid.
2246 : *
2247 : * The clause being hashjoinable indicates that it's an OpExpr.
2248 : */
2249 742548 : if (!restrictinfo->outer_is_left &&
2250 247516 : !OidIsValid(get_commutator(castNode(OpExpr, restrictinfo->clause)->opno)))
2251 6 : continue;
2252 :
2253 495026 : hashclauses = lappend(hashclauses, restrictinfo);
2254 : }
2255 :
2256 : /* If we found any usable hashclauses, make paths */
2257 562756 : if (hashclauses)
2258 : {
2259 : /*
2260 : * We consider both the cheapest-total-cost and cheapest-startup-cost
2261 : * outer paths. There's no need to consider any but the
2262 : * cheapest-total-cost inner path, however.
2263 : */
2264 449974 : Path *cheapest_startup_outer = outerrel->cheapest_startup_path;
2265 449974 : Path *cheapest_total_outer = outerrel->cheapest_total_path;
2266 449974 : Path *cheapest_total_inner = innerrel->cheapest_total_path;
2267 :
2268 : /*
2269 : * If either cheapest-total path is parameterized by the other rel, we
2270 : * can't use a hashjoin. (There's no use looking for alternative
2271 : * input paths, since these should already be the least-parameterized
2272 : * available paths.)
2273 : */
2274 449974 : if (PATH_PARAM_BY_REL(cheapest_total_outer, innerrel) ||
2275 449298 : PATH_PARAM_BY_REL(cheapest_total_inner, outerrel))
2276 1352 : return;
2277 :
2278 : /* Unique-ify if need be; we ignore parameterized possibilities */
2279 448622 : if (jointype == JOIN_UNIQUE_OUTER)
2280 : {
2281 : cheapest_total_outer = (Path *)
2282 2630 : create_unique_path(root, outerrel,
2283 : cheapest_total_outer, extra->sjinfo);
2284 : Assert(cheapest_total_outer);
2285 2630 : jointype = JOIN_INNER;
2286 2630 : try_hashjoin_path(root,
2287 : joinrel,
2288 : cheapest_total_outer,
2289 : cheapest_total_inner,
2290 : hashclauses,
2291 : jointype,
2292 : extra);
2293 : /* no possibility of cheap startup here */
2294 : }
2295 445992 : else if (jointype == JOIN_UNIQUE_INNER)
2296 : {
2297 : cheapest_total_inner = (Path *)
2298 2630 : create_unique_path(root, innerrel,
2299 : cheapest_total_inner, extra->sjinfo);
2300 : Assert(cheapest_total_inner);
2301 2630 : jointype = JOIN_INNER;
2302 2630 : try_hashjoin_path(root,
2303 : joinrel,
2304 : cheapest_total_outer,
2305 : cheapest_total_inner,
2306 : hashclauses,
2307 : jointype,
2308 : extra);
2309 2630 : if (cheapest_startup_outer != NULL &&
2310 : cheapest_startup_outer != cheapest_total_outer)
2311 330 : try_hashjoin_path(root,
2312 : joinrel,
2313 : cheapest_startup_outer,
2314 : cheapest_total_inner,
2315 : hashclauses,
2316 : jointype,
2317 : extra);
2318 : }
2319 : else
2320 : {
2321 : /*
2322 : * For other jointypes, we consider the cheapest startup outer
2323 : * together with the cheapest total inner, and then consider
2324 : * pairings of cheapest-total paths including parameterized ones.
2325 : * There is no use in generating parameterized paths on the basis
2326 : * of possibly cheap startup cost, so this is sufficient.
2327 : */
2328 : ListCell *lc1;
2329 : ListCell *lc2;
2330 :
2331 443362 : if (cheapest_startup_outer != NULL)
2332 442732 : try_hashjoin_path(root,
2333 : joinrel,
2334 : cheapest_startup_outer,
2335 : cheapest_total_inner,
2336 : hashclauses,
2337 : jointype,
2338 : extra);
2339 :
2340 1134222 : foreach(lc1, outerrel->cheapest_parameterized_paths)
2341 : {
2342 690860 : Path *outerpath = (Path *) lfirst(lc1);
2343 :
2344 : /*
2345 : * We cannot use an outer path that is parameterized by the
2346 : * inner rel.
2347 : */
2348 690860 : if (PATH_PARAM_BY_REL(outerpath, innerrel))
2349 202786 : continue;
2350 :
2351 1261800 : foreach(lc2, innerrel->cheapest_parameterized_paths)
2352 : {
2353 773726 : Path *innerpath = (Path *) lfirst(lc2);
2354 :
2355 : /*
2356 : * We cannot use an inner path that is parameterized by
2357 : * the outer rel, either.
2358 : */
2359 773726 : if (PATH_PARAM_BY_REL(innerpath, outerrel))
2360 229380 : continue;
2361 :
2362 544346 : if (outerpath == cheapest_startup_outer &&
2363 : innerpath == cheapest_total_inner)
2364 374984 : continue; /* already tried it */
2365 :
2366 169362 : try_hashjoin_path(root,
2367 : joinrel,
2368 : outerpath,
2369 : innerpath,
2370 : hashclauses,
2371 : jointype,
2372 : extra);
2373 : }
2374 : }
2375 : }
2376 :
2377 : /*
2378 : * If the joinrel is parallel-safe, we may be able to consider a
2379 : * partial hash join. However, we can't handle JOIN_UNIQUE_OUTER,
2380 : * because the outer path will be partial, and therefore we won't be
2381 : * able to properly guarantee uniqueness. Also, the resulting path
2382 : * must not be parameterized.
2383 : */
2384 448622 : if (joinrel->consider_parallel &&
2385 398668 : save_jointype != JOIN_UNIQUE_OUTER &&
2386 398668 : outerrel->partial_pathlist != NIL &&
2387 13998 : bms_is_empty(joinrel->lateral_relids))
2388 : {
2389 : Path *cheapest_partial_outer;
2390 13998 : Path *cheapest_partial_inner = NULL;
2391 13998 : Path *cheapest_safe_inner = NULL;
2392 :
2393 13998 : cheapest_partial_outer =
2394 13998 : (Path *) linitial(outerrel->partial_pathlist);
2395 :
2396 : /*
2397 : * Can we use a partial inner plan too, so that we can build a
2398 : * shared hash table in parallel? We can't handle
2399 : * JOIN_UNIQUE_INNER because we can't guarantee uniqueness.
2400 : */
2401 13998 : if (innerrel->partial_pathlist != NIL &&
2402 12540 : save_jointype != JOIN_UNIQUE_INNER &&
2403 : enable_parallel_hash)
2404 : {
2405 12264 : cheapest_partial_inner =
2406 12264 : (Path *) linitial(innerrel->partial_pathlist);
2407 12264 : try_partial_hashjoin_path(root, joinrel,
2408 : cheapest_partial_outer,
2409 : cheapest_partial_inner,
2410 : hashclauses, jointype, extra,
2411 : true /* parallel_hash */ );
2412 : }
2413 :
2414 : /*
2415 : * Normally, given that the joinrel is parallel-safe, the cheapest
2416 : * total inner path will also be parallel-safe, but if not, we'll
2417 : * have to search for the cheapest safe, unparameterized inner
2418 : * path. If doing JOIN_UNIQUE_INNER, we can't use any alternative
2419 : * inner path. If full, right, right-semi or right-anti join, we
2420 : * can't use parallelism (building the hash table in each backend)
2421 : * because no one process has all the match bits.
2422 : */
2423 13998 : if (save_jointype == JOIN_FULL ||
2424 10182 : save_jointype == JOIN_RIGHT ||
2425 9230 : save_jointype == JOIN_RIGHT_SEMI ||
2426 : save_jointype == JOIN_RIGHT_ANTI)
2427 5098 : cheapest_safe_inner = NULL;
2428 8900 : else if (cheapest_total_inner->parallel_safe)
2429 8672 : cheapest_safe_inner = cheapest_total_inner;
2430 228 : else if (save_jointype != JOIN_UNIQUE_INNER)
2431 : cheapest_safe_inner =
2432 222 : get_cheapest_parallel_safe_total_inner(innerrel->pathlist);
2433 :
2434 13998 : if (cheapest_safe_inner != NULL)
2435 8888 : try_partial_hashjoin_path(root, joinrel,
2436 : cheapest_partial_outer,
2437 : cheapest_safe_inner,
2438 : hashclauses, jointype, extra,
2439 : false /* parallel_hash */ );
2440 : }
2441 : }
2442 : }
2443 :
2444 : /*
2445 : * select_mergejoin_clauses
2446 : * Select mergejoin clauses that are usable for a particular join.
2447 : * Returns a list of RestrictInfo nodes for those clauses.
2448 : *
2449 : * *mergejoin_allowed is normally set to true, but it is set to false if
2450 : * this is a right-semi join, or this is a right/right-anti/full join and
2451 : * there are nonmergejoinable join clauses. The executor's mergejoin
2452 : * machinery cannot handle such cases, so we have to avoid generating a
2453 : * mergejoin plan. (Note that this flag does NOT consider whether there are
2454 : * actually any mergejoinable clauses. This is correct because in some
2455 : * cases we need to build a clauseless mergejoin. Simply returning NIL is
2456 : * therefore not enough to distinguish safe from unsafe cases.)
2457 : *
2458 : * We also mark each selected RestrictInfo to show which side is currently
2459 : * being considered as outer. These are transient markings that are only
2460 : * good for the duration of the current add_paths_to_joinrel() call!
2461 : *
2462 : * We examine each restrictinfo clause known for the join to see
2463 : * if it is mergejoinable and involves vars from the two sub-relations
2464 : * currently of interest.
2465 : */
2466 : static List *
2467 564396 : select_mergejoin_clauses(PlannerInfo *root,
2468 : RelOptInfo *joinrel,
2469 : RelOptInfo *outerrel,
2470 : RelOptInfo *innerrel,
2471 : List *restrictlist,
2472 : JoinType jointype,
2473 : bool *mergejoin_allowed)
2474 : {
2475 564396 : List *result_list = NIL;
2476 564396 : bool isouterjoin = IS_OUTER_JOIN(jointype);
2477 564396 : bool have_nonmergeable_joinclause = false;
2478 : ListCell *l;
2479 :
2480 : /*
2481 : * For now we do not support RIGHT_SEMI join in mergejoin: the benefit of
2482 : * swapping inputs tends to be small here.
2483 : */
2484 564396 : if (jointype == JOIN_RIGHT_SEMI)
2485 : {
2486 4216 : *mergejoin_allowed = false;
2487 4216 : return NIL;
2488 : }
2489 :
2490 1144958 : foreach(l, restrictlist)
2491 : {
2492 584778 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
2493 :
2494 : /*
2495 : * If processing an outer join, only use its own join clauses in the
2496 : * merge. For inner joins we can use pushed-down clauses too. (Note:
2497 : * we don't set have_nonmergeable_joinclause here because pushed-down
2498 : * clauses will become otherquals not joinquals.)
2499 : */
2500 584778 : if (isouterjoin && RINFO_IS_PUSHED_DOWN(restrictinfo, joinrel->relids))
2501 9076 : continue;
2502 :
2503 : /* Check that clause is a mergeable operator clause */
2504 575702 : if (!restrictinfo->can_join ||
2505 510560 : restrictinfo->mergeopfamilies == NIL)
2506 : {
2507 : /*
2508 : * The executor can handle extra joinquals that are constants, but
2509 : * not anything else, when doing right/right-anti/full merge join.
2510 : * (The reason to support constants is so we can do FULL JOIN ON
2511 : * FALSE.)
2512 : */
2513 80536 : if (!restrictinfo->clause || !IsA(restrictinfo->clause, Const))
2514 70988 : have_nonmergeable_joinclause = true;
2515 80536 : continue; /* not mergejoinable */
2516 : }
2517 :
2518 : /*
2519 : * Check if clause has the form "outer op inner" or "inner op outer".
2520 : */
2521 495166 : if (!clause_sides_match_join(restrictinfo, outerrel->relids,
2522 : innerrel->relids))
2523 : {
2524 768 : have_nonmergeable_joinclause = true;
2525 768 : continue; /* no good for these input relations */
2526 : }
2527 :
2528 : /*
2529 : * If clause has the form "inner op outer", check if its operator has
2530 : * valid commutator. This is necessary because mergejoin clauses in
2531 : * this form will get commuted in createplan.c to put the outer var on
2532 : * the left (see get_switched_clauses). This probably shouldn't ever
2533 : * fail, since mergejoinable operators ought to have commutators, but
2534 : * be paranoid.
2535 : *
2536 : * The clause being mergejoinable indicates that it's an OpExpr.
2537 : */
2538 740290 : if (!restrictinfo->outer_is_left &&
2539 245892 : !OidIsValid(get_commutator(castNode(OpExpr, restrictinfo->clause)->opno)))
2540 : {
2541 36 : have_nonmergeable_joinclause = true;
2542 36 : continue;
2543 : }
2544 :
2545 : /*
2546 : * Insist that each side have a non-redundant eclass. This
2547 : * restriction is needed because various bits of the planner expect
2548 : * that each clause in a merge be associable with some pathkey in a
2549 : * canonical pathkey list, but redundant eclasses can't appear in
2550 : * canonical sort orderings. (XXX it might be worth relaxing this,
2551 : * but not enough time to address it for 8.3.)
2552 : */
2553 494362 : update_mergeclause_eclasses(root, restrictinfo);
2554 :
2555 494362 : if (EC_MUST_BE_REDUNDANT(restrictinfo->left_ec) ||
2556 494314 : EC_MUST_BE_REDUNDANT(restrictinfo->right_ec))
2557 : {
2558 128 : have_nonmergeable_joinclause = true;
2559 128 : continue; /* can't handle redundant eclasses */
2560 : }
2561 :
2562 494234 : result_list = lappend(result_list, restrictinfo);
2563 : }
2564 :
2565 : /*
2566 : * Report whether mergejoin is allowed (see comment at top of function).
2567 : */
2568 560180 : switch (jointype)
2569 : {
2570 89212 : case JOIN_RIGHT:
2571 : case JOIN_RIGHT_ANTI:
2572 : case JOIN_FULL:
2573 89212 : *mergejoin_allowed = !have_nonmergeable_joinclause;
2574 89212 : break;
2575 470968 : default:
2576 470968 : *mergejoin_allowed = true;
2577 470968 : break;
2578 : }
2579 :
2580 560180 : return result_list;
2581 : }
|