Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * allpaths.c
4 : * Routines to find possible search paths for processing a query
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/optimizer/path/allpaths.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 :
16 : #include "postgres.h"
17 :
18 : #include <limits.h>
19 : #include <math.h>
20 :
21 : #include "access/sysattr.h"
22 : #include "access/tsmapi.h"
23 : #include "catalog/pg_class.h"
24 : #include "catalog/pg_operator.h"
25 : #include "catalog/pg_proc.h"
26 : #include "foreign/fdwapi.h"
27 : #include "miscadmin.h"
28 : #include "nodes/makefuncs.h"
29 : #include "nodes/nodeFuncs.h"
30 : #include "nodes/supportnodes.h"
31 : #ifdef OPTIMIZER_DEBUG
32 : #include "nodes/print.h"
33 : #endif
34 : #include "optimizer/appendinfo.h"
35 : #include "optimizer/clauses.h"
36 : #include "optimizer/cost.h"
37 : #include "optimizer/geqo.h"
38 : #include "optimizer/optimizer.h"
39 : #include "optimizer/pathnode.h"
40 : #include "optimizer/paths.h"
41 : #include "optimizer/plancat.h"
42 : #include "optimizer/planner.h"
43 : #include "optimizer/tlist.h"
44 : #include "parser/parse_clause.h"
45 : #include "parser/parsetree.h"
46 : #include "partitioning/partbounds.h"
47 : #include "port/pg_bitutils.h"
48 : #include "rewrite/rewriteManip.h"
49 : #include "utils/lsyscache.h"
50 :
51 :
52 : /* Bitmask flags for pushdown_safety_info.unsafeFlags */
53 : #define UNSAFE_HAS_VOLATILE_FUNC (1 << 0)
54 : #define UNSAFE_HAS_SET_FUNC (1 << 1)
55 : #define UNSAFE_NOTIN_DISTINCTON_CLAUSE (1 << 2)
56 : #define UNSAFE_NOTIN_PARTITIONBY_CLAUSE (1 << 3)
57 : #define UNSAFE_TYPE_MISMATCH (1 << 4)
58 :
59 : /* results of subquery_is_pushdown_safe */
60 : typedef struct pushdown_safety_info
61 : {
62 : unsigned char *unsafeFlags; /* bitmask of reasons why this target list
63 : * column is unsafe for qual pushdown, or 0 if
64 : * no reason. */
65 : bool unsafeVolatile; /* don't push down volatile quals */
66 : bool unsafeLeaky; /* don't push down leaky quals */
67 : } pushdown_safety_info;
68 :
69 : /* Return type for qual_is_pushdown_safe */
70 : typedef enum pushdown_safe_type
71 : {
72 : PUSHDOWN_UNSAFE, /* unsafe to push qual into subquery */
73 : PUSHDOWN_SAFE, /* safe to push qual into subquery */
74 : PUSHDOWN_WINDOWCLAUSE_RUNCOND, /* unsafe, but may work as WindowClause
75 : * run condition */
76 : } pushdown_safe_type;
77 :
78 : /* These parameters are set by GUC */
79 : bool enable_geqo = false; /* just in case GUC doesn't set it */
80 : int geqo_threshold;
81 : int min_parallel_table_scan_size;
82 : int min_parallel_index_scan_size;
83 :
84 : /* Hook for plugins to get control in set_rel_pathlist() */
85 : set_rel_pathlist_hook_type set_rel_pathlist_hook = NULL;
86 :
87 : /* Hook for plugins to replace standard_join_search() */
88 : join_search_hook_type join_search_hook = NULL;
89 :
90 :
91 : static void set_base_rel_consider_startup(PlannerInfo *root);
92 : static void set_base_rel_sizes(PlannerInfo *root);
93 : static void set_base_rel_pathlists(PlannerInfo *root);
94 : static void set_rel_size(PlannerInfo *root, RelOptInfo *rel,
95 : Index rti, RangeTblEntry *rte);
96 : static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
97 : Index rti, RangeTblEntry *rte);
98 : static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel,
99 : RangeTblEntry *rte);
100 : static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel);
101 : static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel,
102 : RangeTblEntry *rte);
103 : static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
104 : RangeTblEntry *rte);
105 : static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel,
106 : RangeTblEntry *rte);
107 : static void set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
108 : RangeTblEntry *rte);
109 : static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel,
110 : RangeTblEntry *rte);
111 : static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel,
112 : RangeTblEntry *rte);
113 : static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
114 : Index rti, RangeTblEntry *rte);
115 : static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
116 : Index rti, RangeTblEntry *rte);
117 : static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel,
118 : List *live_childrels,
119 : List *all_child_pathkeys);
120 : static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
121 : RelOptInfo *rel,
122 : Relids required_outer);
123 : static void accumulate_append_subpath(Path *path,
124 : List **subpaths,
125 : List **special_subpaths);
126 : static Path *get_singleton_append_subpath(Path *path);
127 : static void set_dummy_rel_pathlist(RelOptInfo *rel);
128 : static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
129 : Index rti, RangeTblEntry *rte);
130 : static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel,
131 : RangeTblEntry *rte);
132 : static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel,
133 : RangeTblEntry *rte);
134 : static void set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel,
135 : RangeTblEntry *rte);
136 : static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel,
137 : RangeTblEntry *rte);
138 : static void set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel,
139 : RangeTblEntry *rte);
140 : static void set_result_pathlist(PlannerInfo *root, RelOptInfo *rel,
141 : RangeTblEntry *rte);
142 : static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel,
143 : RangeTblEntry *rte);
144 : static RelOptInfo *make_rel_from_joinlist(PlannerInfo *root, List *joinlist);
145 : static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
146 : pushdown_safety_info *safetyInfo);
147 : static bool recurse_pushdown_safe(Node *setOp, Query *topquery,
148 : pushdown_safety_info *safetyInfo);
149 : static void check_output_expressions(Query *subquery,
150 : pushdown_safety_info *safetyInfo);
151 : static void compare_tlist_datatypes(List *tlist, List *colTypes,
152 : pushdown_safety_info *safetyInfo);
153 : static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query);
154 : static pushdown_safe_type qual_is_pushdown_safe(Query *subquery, Index rti,
155 : RestrictInfo *rinfo,
156 : pushdown_safety_info *safetyInfo);
157 : static void subquery_push_qual(Query *subquery,
158 : RangeTblEntry *rte, Index rti, Node *qual);
159 : static void recurse_push_qual(Node *setOp, Query *topquery,
160 : RangeTblEntry *rte, Index rti, Node *qual);
161 : static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel,
162 : Bitmapset *extra_used_attrs);
163 :
164 :
165 : /*
166 : * make_one_rel
167 : * Finds all possible access paths for executing a query, returning a
168 : * single rel that represents the join of all base rels in the query.
169 : */
170 : RelOptInfo *
171 336128 : make_one_rel(PlannerInfo *root, List *joinlist)
172 : {
173 : RelOptInfo *rel;
174 : Index rti;
175 : double total_pages;
176 :
177 : /* Mark base rels as to whether we care about fast-start plans */
178 336128 : set_base_rel_consider_startup(root);
179 :
180 : /*
181 : * Compute size estimates and consider_parallel flags for each base rel.
182 : */
183 336128 : set_base_rel_sizes(root);
184 :
185 : /*
186 : * We should now have size estimates for every actual table involved in
187 : * the query, and we also know which if any have been deleted from the
188 : * query by join removal, pruned by partition pruning, or eliminated by
189 : * constraint exclusion. So we can now compute total_table_pages.
190 : *
191 : * Note that appendrels are not double-counted here, even though we don't
192 : * bother to distinguish RelOptInfos for appendrel parents, because the
193 : * parents will have pages = 0.
194 : *
195 : * XXX if a table is self-joined, we will count it once per appearance,
196 : * which perhaps is the wrong thing ... but that's not completely clear,
197 : * and detecting self-joins here is difficult, so ignore it for now.
198 : */
199 336100 : total_pages = 0;
200 1121556 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
201 : {
202 785456 : RelOptInfo *brel = root->simple_rel_array[rti];
203 :
204 : /* there may be empty slots corresponding to non-baserel RTEs */
205 785456 : if (brel == NULL)
206 212616 : continue;
207 :
208 : Assert(brel->relid == rti); /* sanity check on array */
209 :
210 572840 : if (IS_DUMMY_REL(brel))
211 1156 : continue;
212 :
213 571684 : if (IS_SIMPLE_REL(brel))
214 571684 : total_pages += (double) brel->pages;
215 : }
216 336100 : root->total_table_pages = total_pages;
217 :
218 : /*
219 : * Generate access paths for each base rel.
220 : */
221 336100 : set_base_rel_pathlists(root);
222 :
223 : /*
224 : * Generate access paths for the entire join tree.
225 : */
226 336100 : rel = make_rel_from_joinlist(root, joinlist);
227 :
228 : /*
229 : * The result should join all and only the query's base + outer-join rels.
230 : */
231 : Assert(bms_equal(rel->relids, root->all_query_rels));
232 :
233 336100 : return rel;
234 : }
235 :
236 : /*
237 : * set_base_rel_consider_startup
238 : * Set the consider_[param_]startup flags for each base-relation entry.
239 : *
240 : * For the moment, we only deal with consider_param_startup here; because the
241 : * logic for consider_startup is pretty trivial and is the same for every base
242 : * relation, we just let build_simple_rel() initialize that flag correctly to
243 : * start with. If that logic ever gets more complicated it would probably
244 : * be better to move it here.
245 : */
246 : static void
247 336128 : set_base_rel_consider_startup(PlannerInfo *root)
248 : {
249 : /*
250 : * Since parameterized paths can only be used on the inside of a nestloop
251 : * join plan, there is usually little value in considering fast-start
252 : * plans for them. However, for relations that are on the RHS of a SEMI
253 : * or ANTI join, a fast-start plan can be useful because we're only going
254 : * to care about fetching one tuple anyway.
255 : *
256 : * To minimize growth of planning time, we currently restrict this to
257 : * cases where the RHS is a single base relation, not a join; there is no
258 : * provision for consider_param_startup to get set at all on joinrels.
259 : * Also we don't worry about appendrels. costsize.c's costing rules for
260 : * nestloop semi/antijoins don't consider such cases either.
261 : */
262 : ListCell *lc;
263 :
264 373004 : foreach(lc, root->join_info_list)
265 : {
266 36876 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
267 : int varno;
268 :
269 42214 : if ((sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) &&
270 5338 : bms_get_singleton_member(sjinfo->syn_righthand, &varno))
271 : {
272 5156 : RelOptInfo *rel = find_base_rel(root, varno);
273 :
274 5156 : rel->consider_param_startup = true;
275 : }
276 : }
277 336128 : }
278 :
279 : /*
280 : * set_base_rel_sizes
281 : * Set the size estimates (rows and widths) for each base-relation entry.
282 : * Also determine whether to consider parallel paths for base relations.
283 : *
284 : * We do this in a separate pass over the base rels so that rowcount
285 : * estimates are available for parameterized path generation, and also so
286 : * that each rel's consider_parallel flag is set correctly before we begin to
287 : * generate paths.
288 : */
289 : static void
290 336128 : set_base_rel_sizes(PlannerInfo *root)
291 : {
292 : Index rti;
293 :
294 1121586 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
295 : {
296 785486 : RelOptInfo *rel = root->simple_rel_array[rti];
297 : RangeTblEntry *rte;
298 :
299 : /* there may be empty slots corresponding to non-baserel RTEs */
300 785486 : if (rel == NULL)
301 212618 : continue;
302 :
303 : Assert(rel->relid == rti); /* sanity check on array */
304 :
305 : /* ignore RTEs that are "other rels" */
306 572868 : if (rel->reloptkind != RELOPT_BASEREL)
307 44068 : continue;
308 :
309 528800 : rte = root->simple_rte_array[rti];
310 :
311 : /*
312 : * If parallelism is allowable for this query in general, see whether
313 : * it's allowable for this rel in particular. We have to do this
314 : * before set_rel_size(), because (a) if this rel is an inheritance
315 : * parent, set_append_rel_size() will use and perhaps change the rel's
316 : * consider_parallel flag, and (b) for some RTE types, set_rel_size()
317 : * goes ahead and makes paths immediately.
318 : */
319 528800 : if (root->glob->parallelModeOK)
320 438130 : set_rel_consider_parallel(root, rel, rte);
321 :
322 528800 : set_rel_size(root, rel, rti, rte);
323 : }
324 336100 : }
325 :
326 : /*
327 : * set_base_rel_pathlists
328 : * Finds all paths available for scanning each base-relation entry.
329 : * Sequential scan and any available indices are considered.
330 : * Each useful path is attached to its relation's 'pathlist' field.
331 : */
332 : static void
333 336100 : set_base_rel_pathlists(PlannerInfo *root)
334 : {
335 : Index rti;
336 :
337 1121556 : for (rti = 1; rti < root->simple_rel_array_size; rti++)
338 : {
339 785456 : RelOptInfo *rel = root->simple_rel_array[rti];
340 :
341 : /* there may be empty slots corresponding to non-baserel RTEs */
342 785456 : if (rel == NULL)
343 212616 : continue;
344 :
345 : Assert(rel->relid == rti); /* sanity check on array */
346 :
347 : /* ignore RTEs that are "other rels" */
348 572840 : if (rel->reloptkind != RELOPT_BASEREL)
349 44068 : continue;
350 :
351 528772 : set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
352 : }
353 336100 : }
354 :
355 : /*
356 : * set_rel_size
357 : * Set size estimates for a base relation
358 : */
359 : static void
360 572648 : set_rel_size(PlannerInfo *root, RelOptInfo *rel,
361 : Index rti, RangeTblEntry *rte)
362 : {
363 1101448 : if (rel->reloptkind == RELOPT_BASEREL &&
364 528800 : relation_excluded_by_constraints(root, rel, rte))
365 : {
366 : /*
367 : * We proved we don't need to scan the rel via constraint exclusion,
368 : * so set up a single dummy path for it. Here we only check this for
369 : * regular baserels; if it's an otherrel, CE was already checked in
370 : * set_append_rel_size().
371 : *
372 : * In this case, we go ahead and set up the relation's path right away
373 : * instead of leaving it for set_rel_pathlist to do. This is because
374 : * we don't have a convention for marking a rel as dummy except by
375 : * assigning a dummy path to it.
376 : */
377 516 : set_dummy_rel_pathlist(rel);
378 : }
379 572132 : else if (rte->inh)
380 : {
381 : /* It's an "append relation", process accordingly */
382 21078 : set_append_rel_size(root, rel, rti, rte);
383 : }
384 : else
385 : {
386 551054 : switch (rel->rtekind)
387 : {
388 467820 : case RTE_RELATION:
389 467820 : if (rte->relkind == RELKIND_FOREIGN_TABLE)
390 : {
391 : /* Foreign table */
392 2392 : set_foreign_size(root, rel, rte);
393 : }
394 465428 : else if (rte->relkind == RELKIND_PARTITIONED_TABLE)
395 : {
396 : /*
397 : * We could get here if asked to scan a partitioned table
398 : * with ONLY. In that case we shouldn't scan any of the
399 : * partitions, so mark it as a dummy rel.
400 : */
401 40 : set_dummy_rel_pathlist(rel);
402 : }
403 465388 : else if (rte->tablesample != NULL)
404 : {
405 : /* Sampled relation */
406 306 : set_tablesample_rel_size(root, rel, rte);
407 : }
408 : else
409 : {
410 : /* Plain relation */
411 465082 : set_plain_rel_size(root, rel, rte);
412 : }
413 467792 : break;
414 20250 : case RTE_SUBQUERY:
415 :
416 : /*
417 : * Subqueries don't support making a choice between
418 : * parameterized and unparameterized paths, so just go ahead
419 : * and build their paths immediately.
420 : */
421 20250 : set_subquery_pathlist(root, rel, rti, rte);
422 20250 : break;
423 47988 : case RTE_FUNCTION:
424 47988 : set_function_size_estimates(root, rel);
425 47988 : break;
426 626 : case RTE_TABLEFUNC:
427 626 : set_tablefunc_size_estimates(root, rel);
428 626 : break;
429 8152 : case RTE_VALUES:
430 8152 : set_values_size_estimates(root, rel);
431 8152 : break;
432 4132 : case RTE_CTE:
433 :
434 : /*
435 : * CTEs don't support making a choice between parameterized
436 : * and unparameterized paths, so just go ahead and build their
437 : * paths immediately.
438 : */
439 4132 : if (rte->self_reference)
440 834 : set_worktable_pathlist(root, rel, rte);
441 : else
442 3298 : set_cte_pathlist(root, rel, rte);
443 4132 : break;
444 470 : case RTE_NAMEDTUPLESTORE:
445 : /* Might as well just build the path immediately */
446 470 : set_namedtuplestore_pathlist(root, rel, rte);
447 470 : break;
448 1616 : case RTE_RESULT:
449 : /* Might as well just build the path immediately */
450 1616 : set_result_pathlist(root, rel, rte);
451 1616 : break;
452 0 : default:
453 0 : elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
454 : break;
455 : }
456 : }
457 :
458 : /*
459 : * We insist that all non-dummy rels have a nonzero rowcount estimate.
460 : */
461 : Assert(rel->rows > 0 || IS_DUMMY_REL(rel));
462 572618 : }
463 :
464 : /*
465 : * set_rel_pathlist
466 : * Build access paths for a base relation
467 : */
468 : static void
469 572666 : set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
470 : Index rti, RangeTblEntry *rte)
471 : {
472 572666 : if (IS_DUMMY_REL(rel))
473 : {
474 : /* We already proved the relation empty, so nothing more to do */
475 : }
476 571648 : else if (rte->inh)
477 : {
478 : /* It's an "append relation", process accordingly */
479 20782 : set_append_rel_pathlist(root, rel, rti, rte);
480 : }
481 : else
482 : {
483 550866 : switch (rel->rtekind)
484 : {
485 467752 : case RTE_RELATION:
486 467752 : if (rte->relkind == RELKIND_FOREIGN_TABLE)
487 : {
488 : /* Foreign table */
489 2388 : set_foreign_pathlist(root, rel, rte);
490 : }
491 465364 : else if (rte->tablesample != NULL)
492 : {
493 : /* Sampled relation */
494 306 : set_tablesample_rel_pathlist(root, rel, rte);
495 : }
496 : else
497 : {
498 : /* Plain relation */
499 465058 : set_plain_rel_pathlist(root, rel, rte);
500 : }
501 467752 : break;
502 20130 : case RTE_SUBQUERY:
503 : /* Subquery --- fully handled during set_rel_size */
504 20130 : break;
505 47988 : case RTE_FUNCTION:
506 : /* RangeFunction */
507 47988 : set_function_pathlist(root, rel, rte);
508 47988 : break;
509 626 : case RTE_TABLEFUNC:
510 : /* Table Function */
511 626 : set_tablefunc_pathlist(root, rel, rte);
512 626 : break;
513 8152 : case RTE_VALUES:
514 : /* Values list */
515 8152 : set_values_pathlist(root, rel, rte);
516 8152 : break;
517 4132 : case RTE_CTE:
518 : /* CTE reference --- fully handled during set_rel_size */
519 4132 : break;
520 470 : case RTE_NAMEDTUPLESTORE:
521 : /* tuplestore reference --- fully handled during set_rel_size */
522 470 : break;
523 1616 : case RTE_RESULT:
524 : /* simple Result --- fully handled during set_rel_size */
525 1616 : break;
526 0 : default:
527 0 : elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
528 : break;
529 : }
530 : }
531 :
532 : /*
533 : * Allow a plugin to editorialize on the set of Paths for this base
534 : * relation. It could add new paths (such as CustomPaths) by calling
535 : * add_path(), or add_partial_path() if parallel aware. It could also
536 : * delete or modify paths added by the core code.
537 : */
538 572666 : if (set_rel_pathlist_hook)
539 0 : (*set_rel_pathlist_hook) (root, rel, rti, rte);
540 :
541 : /*
542 : * If this is a baserel, we should normally consider gathering any partial
543 : * paths we may have created for it. We have to do this after calling the
544 : * set_rel_pathlist_hook, else it cannot add partial paths to be included
545 : * here.
546 : *
547 : * However, if this is an inheritance child, skip it. Otherwise, we could
548 : * end up with a very large number of gather nodes, each trying to grab
549 : * its own pool of workers. Instead, we'll consider gathering partial
550 : * paths for the parent appendrel.
551 : *
552 : * Also, if this is the topmost scan/join rel, we postpone gathering until
553 : * the final scan/join targetlist is available (see grouping_planner).
554 : */
555 572666 : if (rel->reloptkind == RELOPT_BASEREL &&
556 528772 : !bms_equal(rel->relids, root->all_query_rels))
557 317094 : generate_useful_gather_paths(root, rel, false);
558 :
559 : /* Now find the cheapest of the paths for this rel */
560 572666 : set_cheapest(rel);
561 :
562 : #ifdef OPTIMIZER_DEBUG
563 : pprint(rel);
564 : #endif
565 572666 : }
566 :
567 : /*
568 : * set_plain_rel_size
569 : * Set size estimates for a plain relation (no subquery, no inheritance)
570 : */
571 : static void
572 465082 : set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
573 : {
574 : /*
575 : * Test any partial indexes of rel for applicability. We must do this
576 : * first since partial unique indexes can affect size estimates.
577 : */
578 465082 : check_index_predicates(root, rel);
579 :
580 : /* Mark rel with estimated output rows, width, etc */
581 465082 : set_baserel_size_estimates(root, rel);
582 465058 : }
583 :
584 : /*
585 : * If this relation could possibly be scanned from within a worker, then set
586 : * its consider_parallel flag.
587 : */
588 : static void
589 468688 : set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel,
590 : RangeTblEntry *rte)
591 : {
592 : /*
593 : * The flag has previously been initialized to false, so we can just
594 : * return if it becomes clear that we can't safely set it.
595 : */
596 : Assert(!rel->consider_parallel);
597 :
598 : /* Don't call this if parallelism is disallowed for the entire query. */
599 : Assert(root->glob->parallelModeOK);
600 :
601 : /* This should only be called for baserels and appendrel children. */
602 : Assert(IS_SIMPLE_REL(rel));
603 :
604 : /* Assorted checks based on rtekind. */
605 468688 : switch (rte->rtekind)
606 : {
607 417120 : case RTE_RELATION:
608 :
609 : /*
610 : * Currently, parallel workers can't access the leader's temporary
611 : * tables. We could possibly relax this if we wrote all of its
612 : * local buffers at the start of the query and made no changes
613 : * thereafter (maybe we could allow hint bit changes), and if we
614 : * taught the workers to read them. Writing a large number of
615 : * temporary buffers could be expensive, though, and we don't have
616 : * the rest of the necessary infrastructure right now anyway. So
617 : * for now, bail out if we see a temporary table.
618 : */
619 417120 : if (get_rel_persistence(rte->relid) == RELPERSISTENCE_TEMP)
620 7942 : return;
621 :
622 : /*
623 : * Table sampling can be pushed down to workers if the sample
624 : * function and its arguments are safe.
625 : */
626 409178 : if (rte->tablesample != NULL)
627 : {
628 330 : char proparallel = func_parallel(rte->tablesample->tsmhandler);
629 :
630 330 : if (proparallel != PROPARALLEL_SAFE)
631 36 : return;
632 294 : if (!is_parallel_safe(root, (Node *) rte->tablesample->args))
633 12 : return;
634 : }
635 :
636 : /*
637 : * Ask FDWs whether they can support performing a ForeignScan
638 : * within a worker. Most often, the answer will be no. For
639 : * example, if the nature of the FDW is such that it opens a TCP
640 : * connection with a remote server, each parallel worker would end
641 : * up with a separate connection, and these connections might not
642 : * be appropriately coordinated between workers and the leader.
643 : */
644 409130 : if (rte->relkind == RELKIND_FOREIGN_TABLE)
645 : {
646 : Assert(rel->fdwroutine);
647 1534 : if (!rel->fdwroutine->IsForeignScanParallelSafe)
648 1462 : return;
649 72 : if (!rel->fdwroutine->IsForeignScanParallelSafe(root, rel, rte))
650 0 : return;
651 : }
652 :
653 : /*
654 : * There are additional considerations for appendrels, which we'll
655 : * deal with in set_append_rel_size and set_append_rel_pathlist.
656 : * For now, just set consider_parallel based on the rel's own
657 : * quals and targetlist.
658 : */
659 407668 : break;
660 :
661 18684 : case RTE_SUBQUERY:
662 :
663 : /*
664 : * There's no intrinsic problem with scanning a subquery-in-FROM
665 : * (as distinct from a SubPlan or InitPlan) in a parallel worker.
666 : * If the subquery doesn't happen to have any parallel-safe paths,
667 : * then flagging it as consider_parallel won't change anything,
668 : * but that's true for plain tables, too. We must set
669 : * consider_parallel based on the rel's own quals and targetlist,
670 : * so that if a subquery path is parallel-safe but the quals and
671 : * projection we're sticking onto it are not, we correctly mark
672 : * the SubqueryScanPath as not parallel-safe. (Note that
673 : * set_subquery_pathlist() might push some of these quals down
674 : * into the subquery itself, but that doesn't change anything.)
675 : *
676 : * We can't push sub-select containing LIMIT/OFFSET to workers as
677 : * there is no guarantee that the row order will be fully
678 : * deterministic, and applying LIMIT/OFFSET will lead to
679 : * inconsistent results at the top-level. (In some cases, where
680 : * the result is ordered, we could relax this restriction. But it
681 : * doesn't currently seem worth expending extra effort to do so.)
682 : */
683 : {
684 18684 : Query *subquery = castNode(Query, rte->subquery);
685 :
686 18684 : if (limit_needed(subquery))
687 448 : return;
688 : }
689 18236 : break;
690 :
691 0 : case RTE_JOIN:
692 : /* Shouldn't happen; we're only considering baserels here. */
693 : Assert(false);
694 0 : return;
695 :
696 24394 : case RTE_FUNCTION:
697 : /* Check for parallel-restricted functions. */
698 24394 : if (!is_parallel_safe(root, (Node *) rte->functions))
699 11600 : return;
700 12794 : break;
701 :
702 626 : case RTE_TABLEFUNC:
703 : /* not parallel safe */
704 626 : return;
705 :
706 2808 : case RTE_VALUES:
707 : /* Check for parallel-restricted functions. */
708 2808 : if (!is_parallel_safe(root, (Node *) rte->values_lists))
709 6 : return;
710 2802 : break;
711 :
712 3386 : case RTE_CTE:
713 :
714 : /*
715 : * CTE tuplestores aren't shared among parallel workers, so we
716 : * force all CTE scans to happen in the leader. Also, populating
717 : * the CTE would require executing a subplan that's not available
718 : * in the worker, might be parallel-restricted, and must get
719 : * executed only once.
720 : */
721 3386 : return;
722 :
723 442 : case RTE_NAMEDTUPLESTORE:
724 :
725 : /*
726 : * tuplestore cannot be shared, at least without more
727 : * infrastructure to support that.
728 : */
729 442 : return;
730 :
731 1228 : case RTE_RESULT:
732 : /* RESULT RTEs, in themselves, are no problem. */
733 1228 : break;
734 0 : case RTE_GROUP:
735 : /* Shouldn't happen; we're only considering baserels here. */
736 : Assert(false);
737 0 : return;
738 : }
739 :
740 : /*
741 : * If there's anything in baserestrictinfo that's parallel-restricted, we
742 : * give up on parallelizing access to this relation. We could consider
743 : * instead postponing application of the restricted quals until we're
744 : * above all the parallelism in the plan tree, but it's not clear that
745 : * that would be a win in very many cases, and it might be tricky to make
746 : * outer join clauses work correctly. It would likely break equivalence
747 : * classes, too.
748 : */
749 442728 : if (!is_parallel_safe(root, (Node *) rel->baserestrictinfo))
750 25638 : return;
751 :
752 : /*
753 : * Likewise, if the relation's outputs are not parallel-safe, give up.
754 : * (Usually, they're just Vars, but sometimes they're not.)
755 : */
756 417090 : if (!is_parallel_safe(root, (Node *) rel->reltarget->exprs))
757 18 : return;
758 :
759 : /* We have a winner. */
760 417072 : rel->consider_parallel = true;
761 : }
762 :
763 : /*
764 : * set_plain_rel_pathlist
765 : * Build access paths for a plain relation (no subquery, no inheritance)
766 : */
767 : static void
768 465058 : set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
769 : {
770 : Relids required_outer;
771 :
772 : /*
773 : * We don't support pushing join clauses into the quals of a seqscan, but
774 : * it could still have required parameterization due to LATERAL refs in
775 : * its tlist.
776 : */
777 465058 : required_outer = rel->lateral_relids;
778 :
779 : /*
780 : * Consider TID scans.
781 : *
782 : * If create_tidscan_paths returns true, then a TID scan path is forced.
783 : * This happens when rel->baserestrictinfo contains CurrentOfExpr, because
784 : * the executor can't handle any other type of path for such queries.
785 : * Hence, we return without adding any other paths.
786 : */
787 465058 : if (create_tidscan_paths(root, rel))
788 404 : return;
789 :
790 : /* Consider sequential scan */
791 464654 : add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
792 :
793 : /* If appropriate, consider parallel sequential scan */
794 464654 : if (rel->consider_parallel && required_outer == NULL)
795 369088 : create_plain_partial_paths(root, rel);
796 :
797 : /* Consider index scans */
798 464654 : create_index_paths(root, rel);
799 : }
800 :
801 : /*
802 : * create_plain_partial_paths
803 : * Build partial access paths for parallel scan of a plain relation
804 : */
805 : static void
806 369088 : create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
807 : {
808 : int parallel_workers;
809 :
810 369088 : parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
811 : max_parallel_workers_per_gather);
812 :
813 : /* If any limit was set to zero, the user doesn't want a parallel scan. */
814 369088 : if (parallel_workers <= 0)
815 343060 : return;
816 :
817 : /* Add an unordered partial path based on a parallel sequential scan. */
818 26028 : add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
819 : }
820 :
821 : /*
822 : * set_tablesample_rel_size
823 : * Set size estimates for a sampled relation
824 : */
825 : static void
826 306 : set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
827 : {
828 306 : TableSampleClause *tsc = rte->tablesample;
829 : TsmRoutine *tsm;
830 : BlockNumber pages;
831 : double tuples;
832 :
833 : /*
834 : * Test any partial indexes of rel for applicability. We must do this
835 : * first since partial unique indexes can affect size estimates.
836 : */
837 306 : check_index_predicates(root, rel);
838 :
839 : /*
840 : * Call the sampling method's estimation function to estimate the number
841 : * of pages it will read and the number of tuples it will return. (Note:
842 : * we assume the function returns sane values.)
843 : */
844 306 : tsm = GetTsmRoutine(tsc->tsmhandler);
845 306 : tsm->SampleScanGetSampleSize(root, rel, tsc->args,
846 : &pages, &tuples);
847 :
848 : /*
849 : * For the moment, because we will only consider a SampleScan path for the
850 : * rel, it's okay to just overwrite the pages and tuples estimates for the
851 : * whole relation. If we ever consider multiple path types for sampled
852 : * rels, we'll need more complication.
853 : */
854 306 : rel->pages = pages;
855 306 : rel->tuples = tuples;
856 :
857 : /* Mark rel with estimated output rows, width, etc */
858 306 : set_baserel_size_estimates(root, rel);
859 306 : }
860 :
861 : /*
862 : * set_tablesample_rel_pathlist
863 : * Build access paths for a sampled relation
864 : */
865 : static void
866 306 : set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
867 : {
868 : Relids required_outer;
869 : Path *path;
870 :
871 : /*
872 : * We don't support pushing join clauses into the quals of a samplescan,
873 : * but it could still have required parameterization due to LATERAL refs
874 : * in its tlist or TABLESAMPLE arguments.
875 : */
876 306 : required_outer = rel->lateral_relids;
877 :
878 : /* Consider sampled scan */
879 306 : path = create_samplescan_path(root, rel, required_outer);
880 :
881 : /*
882 : * If the sampling method does not support repeatable scans, we must avoid
883 : * plans that would scan the rel multiple times. Ideally, we'd simply
884 : * avoid putting the rel on the inside of a nestloop join; but adding such
885 : * a consideration to the planner seems like a great deal of complication
886 : * to support an uncommon usage of second-rate sampling methods. Instead,
887 : * if there is a risk that the query might perform an unsafe join, just
888 : * wrap the SampleScan in a Materialize node. We can check for joins by
889 : * counting the membership of all_query_rels (note that this correctly
890 : * counts inheritance trees as single rels). If we're inside a subquery,
891 : * we can't easily check whether a join might occur in the outer query, so
892 : * just assume one is possible.
893 : *
894 : * GetTsmRoutine is relatively expensive compared to the other tests here,
895 : * so check repeatable_across_scans last, even though that's a bit odd.
896 : */
897 586 : if ((root->query_level > 1 ||
898 280 : bms_membership(root->all_query_rels) != BMS_SINGLETON) &&
899 98 : !(GetTsmRoutine(rte->tablesample->tsmhandler)->repeatable_across_scans))
900 : {
901 8 : path = (Path *) create_material_path(rel, path);
902 : }
903 :
904 306 : add_path(rel, path);
905 :
906 : /* For the moment, at least, there are no other paths to consider */
907 306 : }
908 :
909 : /*
910 : * set_foreign_size
911 : * Set size estimates for a foreign table RTE
912 : */
913 : static void
914 2392 : set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
915 : {
916 : /* Mark rel with estimated output rows, width, etc */
917 2392 : set_foreign_size_estimates(root, rel);
918 :
919 : /* Let FDW adjust the size estimates, if it can */
920 2392 : rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
921 :
922 : /* ... but do not let it set the rows estimate to zero */
923 2388 : rel->rows = clamp_row_est(rel->rows);
924 :
925 : /*
926 : * Also, make sure rel->tuples is not insane relative to rel->rows.
927 : * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
928 : * FDW doesn't do anything to replace that.
929 : */
930 2388 : rel->tuples = Max(rel->tuples, rel->rows);
931 2388 : }
932 :
933 : /*
934 : * set_foreign_pathlist
935 : * Build access paths for a foreign table RTE
936 : */
937 : static void
938 2388 : set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
939 : {
940 : /* Call the FDW's GetForeignPaths function to generate path(s) */
941 2388 : rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
942 2388 : }
943 :
944 : /*
945 : * set_append_rel_size
946 : * Set size estimates for a simple "append relation"
947 : *
948 : * The passed-in rel and RTE represent the entire append relation. The
949 : * relation's contents are computed by appending together the output of the
950 : * individual member relations. Note that in the non-partitioned inheritance
951 : * case, the first member relation is actually the same table as is mentioned
952 : * in the parent RTE ... but it has a different RTE and RelOptInfo. This is
953 : * a good thing because their outputs are not the same size.
954 : */
955 : static void
956 21078 : set_append_rel_size(PlannerInfo *root, RelOptInfo *rel,
957 : Index rti, RangeTblEntry *rte)
958 : {
959 21078 : int parentRTindex = rti;
960 : bool has_live_children;
961 : double parent_tuples;
962 : double parent_rows;
963 : double parent_size;
964 : double *parent_attrsizes;
965 : int nattrs;
966 : ListCell *l;
967 :
968 : /* Guard against stack overflow due to overly deep inheritance tree. */
969 21078 : check_stack_depth();
970 :
971 : Assert(IS_SIMPLE_REL(rel));
972 :
973 : /*
974 : * If this is a partitioned baserel, set the consider_partitionwise_join
975 : * flag; currently, we only consider partitionwise joins with the baserel
976 : * if its targetlist doesn't contain a whole-row Var.
977 : */
978 21078 : if (enable_partitionwise_join &&
979 4280 : rel->reloptkind == RELOPT_BASEREL &&
980 3548 : rte->relkind == RELKIND_PARTITIONED_TABLE &&
981 3548 : bms_is_empty(rel->attr_needed[InvalidAttrNumber - rel->min_attr]))
982 3472 : rel->consider_partitionwise_join = true;
983 :
984 : /*
985 : * Initialize to compute size estimates for whole append relation.
986 : *
987 : * We handle tuples estimates by setting "tuples" to the total number of
988 : * tuples accumulated from each live child, rather than using "rows".
989 : * Although an appendrel itself doesn't directly enforce any quals, its
990 : * child relations may. Therefore, setting "tuples" equal to "rows" for
991 : * an appendrel isn't always appropriate, and can lead to inaccurate cost
992 : * estimates. For example, when estimating the number of distinct values
993 : * from an appendrel, we would be unable to adjust the estimate based on
994 : * the restriction selectivity (see estimate_num_groups).
995 : *
996 : * We handle width estimates by weighting the widths of different child
997 : * rels proportionally to their number of rows. This is sensible because
998 : * the use of width estimates is mainly to compute the total relation
999 : * "footprint" if we have to sort or hash it. To do this, we sum the
1000 : * total equivalent size (in "double" arithmetic) and then divide by the
1001 : * total rowcount estimate. This is done separately for the total rel
1002 : * width and each attribute.
1003 : *
1004 : * Note: if you consider changing this logic, beware that child rels could
1005 : * have zero rows and/or width, if they were excluded by constraints.
1006 : */
1007 21078 : has_live_children = false;
1008 21078 : parent_tuples = 0;
1009 21078 : parent_rows = 0;
1010 21078 : parent_size = 0;
1011 21078 : nattrs = rel->max_attr - rel->min_attr + 1;
1012 21078 : parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
1013 :
1014 108590 : foreach(l, root->append_rel_list)
1015 : {
1016 87514 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1017 : int childRTindex;
1018 : RangeTblEntry *childRTE;
1019 : RelOptInfo *childrel;
1020 : List *childrinfos;
1021 : ListCell *parentvars;
1022 : ListCell *childvars;
1023 : ListCell *lc;
1024 :
1025 : /* append_rel_list contains all append rels; ignore others */
1026 87514 : if (appinfo->parent_relid != parentRTindex)
1027 43804 : continue;
1028 :
1029 43962 : childRTindex = appinfo->child_relid;
1030 43962 : childRTE = root->simple_rte_array[childRTindex];
1031 :
1032 : /*
1033 : * The child rel's RelOptInfo was already created during
1034 : * add_other_rels_to_query.
1035 : */
1036 43962 : childrel = find_base_rel(root, childRTindex);
1037 : Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1038 :
1039 : /* We may have already proven the child to be dummy. */
1040 43962 : if (IS_DUMMY_REL(childrel))
1041 18 : continue;
1042 :
1043 : /*
1044 : * We have to copy the parent's targetlist and quals to the child,
1045 : * with appropriate substitution of variables. However, the
1046 : * baserestrictinfo quals were already copied/substituted when the
1047 : * child RelOptInfo was built. So we don't need any additional setup
1048 : * before applying constraint exclusion.
1049 : */
1050 43944 : if (relation_excluded_by_constraints(root, childrel, childRTE))
1051 : {
1052 : /*
1053 : * This child need not be scanned, so we can omit it from the
1054 : * appendrel.
1055 : */
1056 96 : set_dummy_rel_pathlist(childrel);
1057 96 : continue;
1058 : }
1059 :
1060 : /*
1061 : * Constraint exclusion failed, so copy the parent's join quals and
1062 : * targetlist to the child, with appropriate variable substitutions.
1063 : *
1064 : * We skip join quals that came from above outer joins that can null
1065 : * this rel, since they would be of no value while generating paths
1066 : * for the child. This saves some effort while processing the child
1067 : * rel, and it also avoids an implementation restriction in
1068 : * adjust_appendrel_attrs (it can't apply nullingrels to a non-Var).
1069 : */
1070 43848 : childrinfos = NIL;
1071 56694 : foreach(lc, rel->joininfo)
1072 : {
1073 12846 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1074 :
1075 12846 : if (!bms_overlap(rinfo->clause_relids, rel->nulling_relids))
1076 10524 : childrinfos = lappend(childrinfos,
1077 10524 : adjust_appendrel_attrs(root,
1078 : (Node *) rinfo,
1079 : 1, &appinfo));
1080 : }
1081 43848 : childrel->joininfo = childrinfos;
1082 :
1083 : /*
1084 : * Now for the child's targetlist.
1085 : *
1086 : * NB: the resulting childrel->reltarget->exprs may contain arbitrary
1087 : * expressions, which otherwise would not occur in a rel's targetlist.
1088 : * Code that might be looking at an appendrel child must cope with
1089 : * such. (Normally, a rel's targetlist would only include Vars and
1090 : * PlaceHolderVars.) XXX we do not bother to update the cost or width
1091 : * fields of childrel->reltarget; not clear if that would be useful.
1092 : */
1093 87696 : childrel->reltarget->exprs = (List *)
1094 43848 : adjust_appendrel_attrs(root,
1095 43848 : (Node *) rel->reltarget->exprs,
1096 : 1, &appinfo);
1097 :
1098 : /*
1099 : * We have to make child entries in the EquivalenceClass data
1100 : * structures as well. This is needed either if the parent
1101 : * participates in some eclass joins (because we will want to consider
1102 : * inner-indexscan joins on the individual children) or if the parent
1103 : * has useful pathkeys (because we should try to build MergeAppend
1104 : * paths that produce those sort orderings).
1105 : */
1106 43848 : if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
1107 22804 : add_child_rel_equivalences(root, appinfo, rel, childrel);
1108 43848 : childrel->has_eclass_joins = rel->has_eclass_joins;
1109 :
1110 : /*
1111 : * Note: we could compute appropriate attr_needed data for the child's
1112 : * variables, by transforming the parent's attr_needed through the
1113 : * translated_vars mapping. However, currently there's no need
1114 : * because attr_needed is only examined for base relations not
1115 : * otherrels. So we just leave the child's attr_needed empty.
1116 : */
1117 :
1118 : /*
1119 : * If we consider partitionwise joins with the parent rel, do the same
1120 : * for partitioned child rels.
1121 : *
1122 : * Note: here we abuse the consider_partitionwise_join flag by setting
1123 : * it for child rels that are not themselves partitioned. We do so to
1124 : * tell try_partitionwise_join() that the child rel is sufficiently
1125 : * valid to be used as a per-partition input, even if it later gets
1126 : * proven to be dummy. (It's not usable until we've set up the
1127 : * reltarget and EC entries, which we just did.)
1128 : */
1129 43848 : if (rel->consider_partitionwise_join)
1130 11390 : childrel->consider_partitionwise_join = true;
1131 :
1132 : /*
1133 : * If parallelism is allowable for this query in general, see whether
1134 : * it's allowable for this childrel in particular. But if we've
1135 : * already decided the appendrel is not parallel-safe as a whole,
1136 : * there's no point in considering parallelism for this child. For
1137 : * consistency, do this before calling set_rel_size() for the child.
1138 : */
1139 43848 : if (root->glob->parallelModeOK && rel->consider_parallel)
1140 30558 : set_rel_consider_parallel(root, childrel, childRTE);
1141 :
1142 : /*
1143 : * Compute the child's size.
1144 : */
1145 43848 : set_rel_size(root, childrel, childRTindex, childRTE);
1146 :
1147 : /*
1148 : * It is possible that constraint exclusion detected a contradiction
1149 : * within a child subquery, even though we didn't prove one above. If
1150 : * so, we can skip this child.
1151 : */
1152 43846 : if (IS_DUMMY_REL(childrel))
1153 138 : continue;
1154 :
1155 : /* We have at least one live child. */
1156 43708 : has_live_children = true;
1157 :
1158 : /*
1159 : * If any live child is not parallel-safe, treat the whole appendrel
1160 : * as not parallel-safe. In future we might be able to generate plans
1161 : * in which some children are farmed out to workers while others are
1162 : * not; but we don't have that today, so it's a waste to consider
1163 : * partial paths anywhere in the appendrel unless it's all safe.
1164 : * (Child rels visited before this one will be unmarked in
1165 : * set_append_rel_pathlist().)
1166 : */
1167 43708 : if (!childrel->consider_parallel)
1168 13776 : rel->consider_parallel = false;
1169 :
1170 : /*
1171 : * Accumulate size information from each live child.
1172 : */
1173 : Assert(childrel->rows > 0);
1174 :
1175 43708 : parent_tuples += childrel->tuples;
1176 43708 : parent_rows += childrel->rows;
1177 43708 : parent_size += childrel->reltarget->width * childrel->rows;
1178 :
1179 : /*
1180 : * Accumulate per-column estimates too. We need not do anything for
1181 : * PlaceHolderVars in the parent list. If child expression isn't a
1182 : * Var, or we didn't record a width estimate for it, we have to fall
1183 : * back on a datatype-based estimate.
1184 : *
1185 : * By construction, child's targetlist is 1-to-1 with parent's.
1186 : */
1187 137796 : forboth(parentvars, rel->reltarget->exprs,
1188 : childvars, childrel->reltarget->exprs)
1189 : {
1190 94088 : Var *parentvar = (Var *) lfirst(parentvars);
1191 94088 : Node *childvar = (Node *) lfirst(childvars);
1192 :
1193 94088 : if (IsA(parentvar, Var) && parentvar->varno == parentRTindex)
1194 : {
1195 81540 : int pndx = parentvar->varattno - rel->min_attr;
1196 81540 : int32 child_width = 0;
1197 :
1198 81540 : if (IsA(childvar, Var) &&
1199 79310 : ((Var *) childvar)->varno == childrel->relid)
1200 : {
1201 79244 : int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
1202 :
1203 79244 : child_width = childrel->attr_widths[cndx];
1204 : }
1205 81540 : if (child_width <= 0)
1206 2296 : child_width = get_typavgwidth(exprType(childvar),
1207 : exprTypmod(childvar));
1208 : Assert(child_width > 0);
1209 81540 : parent_attrsizes[pndx] += child_width * childrel->rows;
1210 : }
1211 : }
1212 : }
1213 :
1214 21076 : if (has_live_children)
1215 : {
1216 : /*
1217 : * Save the finished size estimates.
1218 : */
1219 : int i;
1220 :
1221 : Assert(parent_rows > 0);
1222 20782 : rel->tuples = parent_tuples;
1223 20782 : rel->rows = parent_rows;
1224 20782 : rel->reltarget->width = rint(parent_size / parent_rows);
1225 211188 : for (i = 0; i < nattrs; i++)
1226 190406 : rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
1227 :
1228 : /*
1229 : * Note that we leave rel->pages as zero; this is important to avoid
1230 : * double-counting the appendrel tree in total_table_pages.
1231 : */
1232 : }
1233 : else
1234 : {
1235 : /*
1236 : * All children were excluded by constraints, so mark the whole
1237 : * appendrel dummy. We must do this in this phase so that the rel's
1238 : * dummy-ness is visible when we generate paths for other rels.
1239 : */
1240 294 : set_dummy_rel_pathlist(rel);
1241 : }
1242 :
1243 21076 : pfree(parent_attrsizes);
1244 21076 : }
1245 :
1246 : /*
1247 : * set_append_rel_pathlist
1248 : * Build access paths for an "append relation"
1249 : */
1250 : static void
1251 20782 : set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
1252 : Index rti, RangeTblEntry *rte)
1253 : {
1254 20782 : int parentRTindex = rti;
1255 20782 : List *live_childrels = NIL;
1256 : ListCell *l;
1257 :
1258 : /*
1259 : * Generate access paths for each member relation, and remember the
1260 : * non-dummy children.
1261 : */
1262 107880 : foreach(l, root->append_rel_list)
1263 : {
1264 87098 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1265 : int childRTindex;
1266 : RangeTblEntry *childRTE;
1267 : RelOptInfo *childrel;
1268 :
1269 : /* append_rel_list contains all append rels; ignore others */
1270 87098 : if (appinfo->parent_relid != parentRTindex)
1271 43204 : continue;
1272 :
1273 : /* Re-locate the child RTE and RelOptInfo */
1274 43894 : childRTindex = appinfo->child_relid;
1275 43894 : childRTE = root->simple_rte_array[childRTindex];
1276 43894 : childrel = root->simple_rel_array[childRTindex];
1277 :
1278 : /*
1279 : * If set_append_rel_size() decided the parent appendrel was
1280 : * parallel-unsafe at some point after visiting this child rel, we
1281 : * need to propagate the unsafety marking down to the child, so that
1282 : * we don't generate useless partial paths for it.
1283 : */
1284 43894 : if (!rel->consider_parallel)
1285 13882 : childrel->consider_parallel = false;
1286 :
1287 : /*
1288 : * Compute the child's access paths.
1289 : */
1290 43894 : set_rel_pathlist(root, childrel, childRTindex, childRTE);
1291 :
1292 : /*
1293 : * If child is dummy, ignore it.
1294 : */
1295 43894 : if (IS_DUMMY_REL(childrel))
1296 186 : continue;
1297 :
1298 : /*
1299 : * Child is live, so add it to the live_childrels list for use below.
1300 : */
1301 43708 : live_childrels = lappend(live_childrels, childrel);
1302 : }
1303 :
1304 : /* Add paths to the append relation. */
1305 20782 : add_paths_to_append_rel(root, rel, live_childrels);
1306 20782 : }
1307 :
1308 :
1309 : /*
1310 : * add_paths_to_append_rel
1311 : * Generate paths for the given append relation given the set of non-dummy
1312 : * child rels.
1313 : *
1314 : * The function collects all parameterizations and orderings supported by the
1315 : * non-dummy children. For every such parameterization or ordering, it creates
1316 : * an append path collecting one path from each non-dummy child with given
1317 : * parameterization or ordering. Similarly it collects partial paths from
1318 : * non-dummy children to create partial append paths.
1319 : */
1320 : void
1321 35742 : add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel,
1322 : List *live_childrels)
1323 : {
1324 35742 : List *subpaths = NIL;
1325 35742 : bool subpaths_valid = true;
1326 35742 : List *startup_subpaths = NIL;
1327 35742 : bool startup_subpaths_valid = true;
1328 35742 : List *partial_subpaths = NIL;
1329 35742 : List *pa_partial_subpaths = NIL;
1330 35742 : List *pa_nonpartial_subpaths = NIL;
1331 35742 : bool partial_subpaths_valid = true;
1332 : bool pa_subpaths_valid;
1333 35742 : List *all_child_pathkeys = NIL;
1334 35742 : List *all_child_outers = NIL;
1335 : ListCell *l;
1336 35742 : double partial_rows = -1;
1337 :
1338 : /* If appropriate, consider parallel append */
1339 35742 : pa_subpaths_valid = enable_parallel_append && rel->consider_parallel;
1340 :
1341 : /*
1342 : * For every non-dummy child, remember the cheapest path. Also, identify
1343 : * all pathkeys (orderings) and parameterizations (required_outer sets)
1344 : * available for the non-dummy member relations.
1345 : */
1346 108712 : foreach(l, live_childrels)
1347 : {
1348 72970 : RelOptInfo *childrel = lfirst(l);
1349 : ListCell *lcp;
1350 72970 : Path *cheapest_partial_path = NULL;
1351 :
1352 : /*
1353 : * If child has an unparameterized cheapest-total path, add that to
1354 : * the unparameterized Append path we are constructing for the parent.
1355 : * If not, there's no workable unparameterized path.
1356 : *
1357 : * With partitionwise aggregates, the child rel's pathlist may be
1358 : * empty, so don't assume that a path exists here.
1359 : */
1360 72970 : if (childrel->pathlist != NIL &&
1361 72970 : childrel->cheapest_total_path->param_info == NULL)
1362 72238 : accumulate_append_subpath(childrel->cheapest_total_path,
1363 : &subpaths, NULL);
1364 : else
1365 732 : subpaths_valid = false;
1366 :
1367 : /*
1368 : * When the planner is considering cheap startup plans, we'll also
1369 : * collect all the cheapest_startup_paths (if set) and build an
1370 : * AppendPath containing those as subpaths.
1371 : */
1372 72970 : if (rel->consider_startup && childrel->cheapest_startup_path != NULL)
1373 : {
1374 : /* cheapest_startup_path must not be a parameterized path. */
1375 : Assert(childrel->cheapest_startup_path->param_info == NULL);
1376 1286 : accumulate_append_subpath(childrel->cheapest_startup_path,
1377 : &startup_subpaths,
1378 : NULL);
1379 : }
1380 : else
1381 71684 : startup_subpaths_valid = false;
1382 :
1383 :
1384 : /* Same idea, but for a partial plan. */
1385 72970 : if (childrel->partial_pathlist != NIL)
1386 : {
1387 47100 : cheapest_partial_path = linitial(childrel->partial_pathlist);
1388 47100 : accumulate_append_subpath(cheapest_partial_path,
1389 : &partial_subpaths, NULL);
1390 : }
1391 : else
1392 25870 : partial_subpaths_valid = false;
1393 :
1394 : /*
1395 : * Same idea, but for a parallel append mixing partial and non-partial
1396 : * paths.
1397 : */
1398 72970 : if (pa_subpaths_valid)
1399 : {
1400 50024 : Path *nppath = NULL;
1401 :
1402 : nppath =
1403 50024 : get_cheapest_parallel_safe_total_inner(childrel->pathlist);
1404 :
1405 50024 : if (cheapest_partial_path == NULL && nppath == NULL)
1406 : {
1407 : /* Neither a partial nor a parallel-safe path? Forget it. */
1408 458 : pa_subpaths_valid = false;
1409 : }
1410 49566 : else if (nppath == NULL ||
1411 46650 : (cheapest_partial_path != NULL &&
1412 46650 : cheapest_partial_path->total_cost < nppath->total_cost))
1413 : {
1414 : /* Partial path is cheaper or the only option. */
1415 : Assert(cheapest_partial_path != NULL);
1416 46510 : accumulate_append_subpath(cheapest_partial_path,
1417 : &pa_partial_subpaths,
1418 : &pa_nonpartial_subpaths);
1419 : }
1420 : else
1421 : {
1422 : /*
1423 : * Either we've got only a non-partial path, or we think that
1424 : * a single backend can execute the best non-partial path
1425 : * faster than all the parallel backends working together can
1426 : * execute the best partial path.
1427 : *
1428 : * It might make sense to be more aggressive here. Even if
1429 : * the best non-partial path is more expensive than the best
1430 : * partial path, it could still be better to choose the
1431 : * non-partial path if there are several such paths that can
1432 : * be given to different workers. For now, we don't try to
1433 : * figure that out.
1434 : */
1435 3056 : accumulate_append_subpath(nppath,
1436 : &pa_nonpartial_subpaths,
1437 : NULL);
1438 : }
1439 : }
1440 :
1441 : /*
1442 : * Collect lists of all the available path orderings and
1443 : * parameterizations for all the children. We use these as a
1444 : * heuristic to indicate which sort orderings and parameterizations we
1445 : * should build Append and MergeAppend paths for.
1446 : */
1447 166872 : foreach(lcp, childrel->pathlist)
1448 : {
1449 93902 : Path *childpath = (Path *) lfirst(lcp);
1450 93902 : List *childkeys = childpath->pathkeys;
1451 93902 : Relids childouter = PATH_REQ_OUTER(childpath);
1452 :
1453 : /* Unsorted paths don't contribute to pathkey list */
1454 93902 : if (childkeys != NIL)
1455 : {
1456 : ListCell *lpk;
1457 21112 : bool found = false;
1458 :
1459 : /* Have we already seen this ordering? */
1460 21300 : foreach(lpk, all_child_pathkeys)
1461 : {
1462 15232 : List *existing_pathkeys = (List *) lfirst(lpk);
1463 :
1464 15232 : if (compare_pathkeys(existing_pathkeys,
1465 : childkeys) == PATHKEYS_EQUAL)
1466 : {
1467 15044 : found = true;
1468 15044 : break;
1469 : }
1470 : }
1471 21112 : if (!found)
1472 : {
1473 : /* No, so add it to all_child_pathkeys */
1474 6068 : all_child_pathkeys = lappend(all_child_pathkeys,
1475 : childkeys);
1476 : }
1477 : }
1478 :
1479 : /* Unparameterized paths don't contribute to param-set list */
1480 93902 : if (childouter)
1481 : {
1482 : ListCell *lco;
1483 6210 : bool found = false;
1484 :
1485 : /* Have we already seen this param set? */
1486 6876 : foreach(lco, all_child_outers)
1487 : {
1488 4524 : Relids existing_outers = (Relids) lfirst(lco);
1489 :
1490 4524 : if (bms_equal(existing_outers, childouter))
1491 : {
1492 3858 : found = true;
1493 3858 : break;
1494 : }
1495 : }
1496 6210 : if (!found)
1497 : {
1498 : /* No, so add it to all_child_outers */
1499 2352 : all_child_outers = lappend(all_child_outers,
1500 : childouter);
1501 : }
1502 : }
1503 : }
1504 : }
1505 :
1506 : /*
1507 : * If we found unparameterized paths for all children, build an unordered,
1508 : * unparameterized Append path for the rel. (Note: this is correct even
1509 : * if we have zero or one live subpath due to constraint exclusion.)
1510 : */
1511 35742 : if (subpaths_valid)
1512 35430 : add_path(rel, (Path *) create_append_path(root, rel, subpaths, NIL,
1513 : NIL, NULL, 0, false,
1514 : -1));
1515 :
1516 : /* build an AppendPath for the cheap startup paths, if valid */
1517 35742 : if (startup_subpaths_valid)
1518 544 : add_path(rel, (Path *) create_append_path(root, rel, startup_subpaths,
1519 : NIL, NIL, NULL, 0, false, -1));
1520 :
1521 : /*
1522 : * Consider an append of unordered, unparameterized partial paths. Make
1523 : * it parallel-aware if possible.
1524 : */
1525 35742 : if (partial_subpaths_valid && partial_subpaths != NIL)
1526 : {
1527 : AppendPath *appendpath;
1528 : ListCell *lc;
1529 21306 : int parallel_workers = 0;
1530 :
1531 : /* Find the highest number of workers requested for any subpath. */
1532 72598 : foreach(lc, partial_subpaths)
1533 : {
1534 51292 : Path *path = lfirst(lc);
1535 :
1536 51292 : parallel_workers = Max(parallel_workers, path->parallel_workers);
1537 : }
1538 : Assert(parallel_workers > 0);
1539 :
1540 : /*
1541 : * If the use of parallel append is permitted, always request at least
1542 : * log2(# of children) workers. We assume it can be useful to have
1543 : * extra workers in this case because they will be spread out across
1544 : * the children. The precise formula is just a guess, but we don't
1545 : * want to end up with a radically different answer for a table with N
1546 : * partitions vs. an unpartitioned table with the same data, so the
1547 : * use of some kind of log-scaling here seems to make some sense.
1548 : */
1549 21306 : if (enable_parallel_append)
1550 : {
1551 21258 : parallel_workers = Max(parallel_workers,
1552 : pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1553 21258 : parallel_workers = Min(parallel_workers,
1554 : max_parallel_workers_per_gather);
1555 : }
1556 : Assert(parallel_workers > 0);
1557 :
1558 : /* Generate a partial append path. */
1559 21306 : appendpath = create_append_path(root, rel, NIL, partial_subpaths,
1560 : NIL, NULL, parallel_workers,
1561 : enable_parallel_append,
1562 : -1);
1563 :
1564 : /*
1565 : * Make sure any subsequent partial paths use the same row count
1566 : * estimate.
1567 : */
1568 21306 : partial_rows = appendpath->path.rows;
1569 :
1570 : /* Add the path. */
1571 21306 : add_partial_path(rel, (Path *) appendpath);
1572 : }
1573 :
1574 : /*
1575 : * Consider a parallel-aware append using a mix of partial and non-partial
1576 : * paths. (This only makes sense if there's at least one child which has
1577 : * a non-partial path that is substantially cheaper than any partial path;
1578 : * otherwise, we should use the append path added in the previous step.)
1579 : */
1580 35742 : if (pa_subpaths_valid && pa_nonpartial_subpaths != NIL)
1581 : {
1582 : AppendPath *appendpath;
1583 : ListCell *lc;
1584 1596 : int parallel_workers = 0;
1585 :
1586 : /*
1587 : * Find the highest number of workers requested for any partial
1588 : * subpath.
1589 : */
1590 2492 : foreach(lc, pa_partial_subpaths)
1591 : {
1592 896 : Path *path = lfirst(lc);
1593 :
1594 896 : parallel_workers = Max(parallel_workers, path->parallel_workers);
1595 : }
1596 :
1597 : /*
1598 : * Same formula here as above. It's even more important in this
1599 : * instance because the non-partial paths won't contribute anything to
1600 : * the planned number of parallel workers.
1601 : */
1602 1596 : parallel_workers = Max(parallel_workers,
1603 : pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1604 1596 : parallel_workers = Min(parallel_workers,
1605 : max_parallel_workers_per_gather);
1606 : Assert(parallel_workers > 0);
1607 :
1608 1596 : appendpath = create_append_path(root, rel, pa_nonpartial_subpaths,
1609 : pa_partial_subpaths,
1610 : NIL, NULL, parallel_workers, true,
1611 : partial_rows);
1612 1596 : add_partial_path(rel, (Path *) appendpath);
1613 : }
1614 :
1615 : /*
1616 : * Also build unparameterized ordered append paths based on the collected
1617 : * list of child pathkeys.
1618 : */
1619 35742 : if (subpaths_valid)
1620 35430 : generate_orderedappend_paths(root, rel, live_childrels,
1621 : all_child_pathkeys);
1622 :
1623 : /*
1624 : * Build Append paths for each parameterization seen among the child rels.
1625 : * (This may look pretty expensive, but in most cases of practical
1626 : * interest, the child rels will expose mostly the same parameterizations,
1627 : * so that not that many cases actually get considered here.)
1628 : *
1629 : * The Append node itself cannot enforce quals, so all qual checking must
1630 : * be done in the child paths. This means that to have a parameterized
1631 : * Append path, we must have the exact same parameterization for each
1632 : * child path; otherwise some children might be failing to check the
1633 : * moved-down quals. To make them match up, we can try to increase the
1634 : * parameterization of lesser-parameterized paths.
1635 : */
1636 38094 : foreach(l, all_child_outers)
1637 : {
1638 2352 : Relids required_outer = (Relids) lfirst(l);
1639 : ListCell *lcr;
1640 :
1641 : /* Select the child paths for an Append with this parameterization */
1642 2352 : subpaths = NIL;
1643 2352 : subpaths_valid = true;
1644 8646 : foreach(lcr, live_childrels)
1645 : {
1646 6306 : RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1647 : Path *subpath;
1648 :
1649 6306 : if (childrel->pathlist == NIL)
1650 : {
1651 : /* failed to make a suitable path for this child */
1652 0 : subpaths_valid = false;
1653 0 : break;
1654 : }
1655 :
1656 6306 : subpath = get_cheapest_parameterized_child_path(root,
1657 : childrel,
1658 : required_outer);
1659 6306 : if (subpath == NULL)
1660 : {
1661 : /* failed to make a suitable path for this child */
1662 12 : subpaths_valid = false;
1663 12 : break;
1664 : }
1665 6294 : accumulate_append_subpath(subpath, &subpaths, NULL);
1666 : }
1667 :
1668 2352 : if (subpaths_valid)
1669 2340 : add_path(rel, (Path *)
1670 2340 : create_append_path(root, rel, subpaths, NIL,
1671 : NIL, required_outer, 0, false,
1672 : -1));
1673 : }
1674 :
1675 : /*
1676 : * When there is only a single child relation, the Append path can inherit
1677 : * any ordering available for the child rel's path, so that it's useful to
1678 : * consider ordered partial paths. Above we only considered the cheapest
1679 : * partial path for each child, but let's also make paths using any
1680 : * partial paths that have pathkeys.
1681 : */
1682 35742 : if (list_length(live_childrels) == 1)
1683 : {
1684 14240 : RelOptInfo *childrel = (RelOptInfo *) linitial(live_childrels);
1685 :
1686 : /* skip the cheapest partial path, since we already used that above */
1687 14444 : for_each_from(l, childrel->partial_pathlist, 1)
1688 : {
1689 204 : Path *path = (Path *) lfirst(l);
1690 : AppendPath *appendpath;
1691 :
1692 : /* skip paths with no pathkeys. */
1693 204 : if (path->pathkeys == NIL)
1694 0 : continue;
1695 :
1696 204 : appendpath = create_append_path(root, rel, NIL, list_make1(path),
1697 : NIL, NULL,
1698 : path->parallel_workers, true,
1699 : partial_rows);
1700 204 : add_partial_path(rel, (Path *) appendpath);
1701 : }
1702 : }
1703 35742 : }
1704 :
1705 : /*
1706 : * generate_orderedappend_paths
1707 : * Generate ordered append paths for an append relation
1708 : *
1709 : * Usually we generate MergeAppend paths here, but there are some special
1710 : * cases where we can generate simple Append paths, because the subpaths
1711 : * can provide tuples in the required order already.
1712 : *
1713 : * We generate a path for each ordering (pathkey list) appearing in
1714 : * all_child_pathkeys.
1715 : *
1716 : * We consider both cheapest-startup and cheapest-total cases, ie, for each
1717 : * interesting ordering, collect all the cheapest startup subpaths and all the
1718 : * cheapest total paths, and build a suitable path for each case.
1719 : *
1720 : * We don't currently generate any parameterized ordered paths here. While
1721 : * it would not take much more code here to do so, it's very unclear that it
1722 : * is worth the planning cycles to investigate such paths: there's little
1723 : * use for an ordered path on the inside of a nestloop. In fact, it's likely
1724 : * that the current coding of add_path would reject such paths out of hand,
1725 : * because add_path gives no credit for sort ordering of parameterized paths,
1726 : * and a parameterized MergeAppend is going to be more expensive than the
1727 : * corresponding parameterized Append path. If we ever try harder to support
1728 : * parameterized mergejoin plans, it might be worth adding support for
1729 : * parameterized paths here to feed such joins. (See notes in
1730 : * optimizer/README for why that might not ever happen, though.)
1731 : */
1732 : static void
1733 35430 : generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel,
1734 : List *live_childrels,
1735 : List *all_child_pathkeys)
1736 : {
1737 : ListCell *lcp;
1738 35430 : List *partition_pathkeys = NIL;
1739 35430 : List *partition_pathkeys_desc = NIL;
1740 35430 : bool partition_pathkeys_partial = true;
1741 35430 : bool partition_pathkeys_desc_partial = true;
1742 :
1743 : /*
1744 : * Some partitioned table setups may allow us to use an Append node
1745 : * instead of a MergeAppend. This is possible in cases such as RANGE
1746 : * partitioned tables where it's guaranteed that an earlier partition must
1747 : * contain rows which come earlier in the sort order. To detect whether
1748 : * this is relevant, build pathkey descriptions of the partition ordering,
1749 : * for both forward and reverse scans.
1750 : */
1751 62904 : if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1752 27474 : partitions_are_ordered(rel->boundinfo, rel->live_parts))
1753 : {
1754 22772 : partition_pathkeys = build_partition_pathkeys(root, rel,
1755 : ForwardScanDirection,
1756 : &partition_pathkeys_partial);
1757 :
1758 22772 : partition_pathkeys_desc = build_partition_pathkeys(root, rel,
1759 : BackwardScanDirection,
1760 : &partition_pathkeys_desc_partial);
1761 :
1762 : /*
1763 : * You might think we should truncate_useless_pathkeys here, but
1764 : * allowing partition keys which are a subset of the query's pathkeys
1765 : * can often be useful. For example, consider a table partitioned by
1766 : * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1767 : * paths that can produce the a, b, c ordering (perhaps via indexes on
1768 : * (a, b, c)) then it works to consider the appendrel output as
1769 : * ordered by a, b, c.
1770 : */
1771 : }
1772 :
1773 : /* Now consider each interesting sort ordering */
1774 41438 : foreach(lcp, all_child_pathkeys)
1775 : {
1776 6008 : List *pathkeys = (List *) lfirst(lcp);
1777 6008 : List *startup_subpaths = NIL;
1778 6008 : List *total_subpaths = NIL;
1779 6008 : List *fractional_subpaths = NIL;
1780 6008 : bool startup_neq_total = false;
1781 : bool match_partition_order;
1782 : bool match_partition_order_desc;
1783 : int end_index;
1784 : int first_index;
1785 : int direction;
1786 :
1787 : /*
1788 : * Determine if this sort ordering matches any partition pathkeys we
1789 : * have, for both ascending and descending partition order. If the
1790 : * partition pathkeys happen to be contained in pathkeys then it still
1791 : * works, as described above, providing that the partition pathkeys
1792 : * are complete and not just a prefix of the partition keys. (In such
1793 : * cases we'll be relying on the child paths to have sorted the
1794 : * lower-order columns of the required pathkeys.)
1795 : */
1796 6008 : match_partition_order =
1797 9838 : pathkeys_contained_in(pathkeys, partition_pathkeys) ||
1798 4002 : (!partition_pathkeys_partial &&
1799 172 : pathkeys_contained_in(partition_pathkeys, pathkeys));
1800 :
1801 13482 : match_partition_order_desc = !match_partition_order &&
1802 3752 : (pathkeys_contained_in(pathkeys, partition_pathkeys_desc) ||
1803 3786 : (!partition_pathkeys_desc_partial &&
1804 64 : pathkeys_contained_in(partition_pathkeys_desc, pathkeys)));
1805 :
1806 : /*
1807 : * When the required pathkeys match the reverse of the partition
1808 : * order, we must build the list of paths in reverse starting with the
1809 : * last matching partition first. We can get away without making any
1810 : * special cases for this in the loop below by just looping backward
1811 : * over the child relations in this case.
1812 : */
1813 6008 : if (match_partition_order_desc)
1814 : {
1815 : /* loop backward */
1816 42 : first_index = list_length(live_childrels) - 1;
1817 42 : end_index = -1;
1818 42 : direction = -1;
1819 :
1820 : /*
1821 : * Set this to true to save us having to check for
1822 : * match_partition_order_desc in the loop below.
1823 : */
1824 42 : match_partition_order = true;
1825 : }
1826 : else
1827 : {
1828 : /* for all other case, loop forward */
1829 5966 : first_index = 0;
1830 5966 : end_index = list_length(live_childrels);
1831 5966 : direction = 1;
1832 : }
1833 :
1834 : /* Select the child paths for this ordering... */
1835 22092 : for (int i = first_index; i != end_index; i += direction)
1836 : {
1837 16084 : RelOptInfo *childrel = list_nth_node(RelOptInfo, live_childrels, i);
1838 : Path *cheapest_startup,
1839 : *cheapest_total,
1840 16084 : *cheapest_fractional = NULL;
1841 :
1842 : /* Locate the right paths, if they are available. */
1843 : cheapest_startup =
1844 16084 : get_cheapest_path_for_pathkeys(childrel->pathlist,
1845 : pathkeys,
1846 : NULL,
1847 : STARTUP_COST,
1848 : false);
1849 : cheapest_total =
1850 16084 : get_cheapest_path_for_pathkeys(childrel->pathlist,
1851 : pathkeys,
1852 : NULL,
1853 : TOTAL_COST,
1854 : false);
1855 :
1856 : /*
1857 : * If we can't find any paths with the right order just use the
1858 : * cheapest-total path; we'll have to sort it later.
1859 : */
1860 16084 : if (cheapest_startup == NULL || cheapest_total == NULL)
1861 : {
1862 310 : cheapest_startup = cheapest_total =
1863 : childrel->cheapest_total_path;
1864 : /* Assert we do have an unparameterized path for this child */
1865 : Assert(cheapest_total->param_info == NULL);
1866 : }
1867 :
1868 : /*
1869 : * When building a fractional path, determine a cheapest
1870 : * fractional path for each child relation too. Looking at startup
1871 : * and total costs is not enough, because the cheapest fractional
1872 : * path may be dominated by two separate paths (one for startup,
1873 : * one for total).
1874 : *
1875 : * When needed (building fractional path), determine the cheapest
1876 : * fractional path too.
1877 : */
1878 16084 : if (root->tuple_fraction > 0)
1879 : {
1880 668 : double path_fraction = (1.0 / root->tuple_fraction);
1881 :
1882 : cheapest_fractional =
1883 668 : get_cheapest_fractional_path_for_pathkeys(childrel->pathlist,
1884 : pathkeys,
1885 : NULL,
1886 : path_fraction);
1887 :
1888 : /*
1889 : * If we found no path with matching pathkeys, use the
1890 : * cheapest total path instead.
1891 : *
1892 : * XXX We might consider partially sorted paths too (with an
1893 : * incremental sort on top). But we'd have to build all the
1894 : * incremental paths, do the costing etc.
1895 : */
1896 668 : if (!cheapest_fractional)
1897 44 : cheapest_fractional = cheapest_total;
1898 : }
1899 :
1900 : /*
1901 : * Notice whether we actually have different paths for the
1902 : * "cheapest" and "total" cases; frequently there will be no point
1903 : * in two create_merge_append_path() calls.
1904 : */
1905 16084 : if (cheapest_startup != cheapest_total)
1906 72 : startup_neq_total = true;
1907 :
1908 : /*
1909 : * Collect the appropriate child paths. The required logic varies
1910 : * for the Append and MergeAppend cases.
1911 : */
1912 16084 : if (match_partition_order)
1913 : {
1914 : /*
1915 : * We're going to make a plain Append path. We don't need
1916 : * most of what accumulate_append_subpath would do, but we do
1917 : * want to cut out child Appends or MergeAppends if they have
1918 : * just a single subpath (and hence aren't doing anything
1919 : * useful).
1920 : */
1921 6176 : cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1922 6176 : cheapest_total = get_singleton_append_subpath(cheapest_total);
1923 :
1924 6176 : startup_subpaths = lappend(startup_subpaths, cheapest_startup);
1925 6176 : total_subpaths = lappend(total_subpaths, cheapest_total);
1926 :
1927 6176 : if (cheapest_fractional)
1928 : {
1929 120 : cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
1930 120 : fractional_subpaths = lappend(fractional_subpaths, cheapest_fractional);
1931 : }
1932 : }
1933 : else
1934 : {
1935 : /*
1936 : * Otherwise, rely on accumulate_append_subpath to collect the
1937 : * child paths for the MergeAppend.
1938 : */
1939 9908 : accumulate_append_subpath(cheapest_startup,
1940 : &startup_subpaths, NULL);
1941 9908 : accumulate_append_subpath(cheapest_total,
1942 : &total_subpaths, NULL);
1943 :
1944 9908 : if (cheapest_fractional)
1945 548 : accumulate_append_subpath(cheapest_fractional,
1946 : &fractional_subpaths, NULL);
1947 : }
1948 : }
1949 :
1950 : /* ... and build the Append or MergeAppend paths */
1951 6008 : if (match_partition_order)
1952 : {
1953 : /* We only need Append */
1954 2298 : add_path(rel, (Path *) create_append_path(root,
1955 : rel,
1956 : startup_subpaths,
1957 : NIL,
1958 : pathkeys,
1959 : NULL,
1960 : 0,
1961 : false,
1962 : -1));
1963 2298 : if (startup_neq_total)
1964 0 : add_path(rel, (Path *) create_append_path(root,
1965 : rel,
1966 : total_subpaths,
1967 : NIL,
1968 : pathkeys,
1969 : NULL,
1970 : 0,
1971 : false,
1972 : -1));
1973 :
1974 2298 : if (fractional_subpaths)
1975 60 : add_path(rel, (Path *) create_append_path(root,
1976 : rel,
1977 : fractional_subpaths,
1978 : NIL,
1979 : pathkeys,
1980 : NULL,
1981 : 0,
1982 : false,
1983 : -1));
1984 : }
1985 : else
1986 : {
1987 : /* We need MergeAppend */
1988 3710 : add_path(rel, (Path *) create_merge_append_path(root,
1989 : rel,
1990 : startup_subpaths,
1991 : pathkeys,
1992 : NULL));
1993 3710 : if (startup_neq_total)
1994 48 : add_path(rel, (Path *) create_merge_append_path(root,
1995 : rel,
1996 : total_subpaths,
1997 : pathkeys,
1998 : NULL));
1999 :
2000 3710 : if (fractional_subpaths)
2001 196 : add_path(rel, (Path *) create_merge_append_path(root,
2002 : rel,
2003 : fractional_subpaths,
2004 : pathkeys,
2005 : NULL));
2006 : }
2007 : }
2008 35430 : }
2009 :
2010 : /*
2011 : * get_cheapest_parameterized_child_path
2012 : * Get cheapest path for this relation that has exactly the requested
2013 : * parameterization.
2014 : *
2015 : * Returns NULL if unable to create such a path.
2016 : */
2017 : static Path *
2018 6306 : get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel,
2019 : Relids required_outer)
2020 : {
2021 : Path *cheapest;
2022 : ListCell *lc;
2023 :
2024 : /*
2025 : * Look up the cheapest existing path with no more than the needed
2026 : * parameterization. If it has exactly the needed parameterization, we're
2027 : * done.
2028 : */
2029 6306 : cheapest = get_cheapest_path_for_pathkeys(rel->pathlist,
2030 : NIL,
2031 : required_outer,
2032 : TOTAL_COST,
2033 : false);
2034 : Assert(cheapest != NULL);
2035 6306 : if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
2036 5978 : return cheapest;
2037 :
2038 : /*
2039 : * Otherwise, we can "reparameterize" an existing path to match the given
2040 : * parameterization, which effectively means pushing down additional
2041 : * joinquals to be checked within the path's scan. However, some existing
2042 : * paths might check the available joinquals already while others don't;
2043 : * therefore, it's not clear which existing path will be cheapest after
2044 : * reparameterization. We have to go through them all and find out.
2045 : */
2046 328 : cheapest = NULL;
2047 1156 : foreach(lc, rel->pathlist)
2048 : {
2049 828 : Path *path = (Path *) lfirst(lc);
2050 :
2051 : /* Can't use it if it needs more than requested parameterization */
2052 828 : if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
2053 24 : continue;
2054 :
2055 : /*
2056 : * Reparameterization can only increase the path's cost, so if it's
2057 : * already more expensive than the current cheapest, forget it.
2058 : */
2059 1260 : if (cheapest != NULL &&
2060 456 : compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2061 384 : continue;
2062 :
2063 : /* Reparameterize if needed, then recheck cost */
2064 420 : if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
2065 : {
2066 344 : path = reparameterize_path(root, path, required_outer, 1.0);
2067 344 : if (path == NULL)
2068 32 : continue; /* failed to reparameterize this one */
2069 : Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
2070 :
2071 312 : if (cheapest != NULL &&
2072 0 : compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2073 0 : continue;
2074 : }
2075 :
2076 : /* We have a new best path */
2077 388 : cheapest = path;
2078 : }
2079 :
2080 : /* Return the best path, or NULL if we found no suitable candidate */
2081 328 : return cheapest;
2082 : }
2083 :
2084 : /*
2085 : * accumulate_append_subpath
2086 : * Add a subpath to the list being built for an Append or MergeAppend.
2087 : *
2088 : * It's possible that the child is itself an Append or MergeAppend path, in
2089 : * which case we can "cut out the middleman" and just add its child paths to
2090 : * our own list. (We don't try to do this earlier because we need to apply
2091 : * both levels of transformation to the quals.)
2092 : *
2093 : * Note that if we omit a child MergeAppend in this way, we are effectively
2094 : * omitting a sort step, which seems fine: if the parent is to be an Append,
2095 : * its result would be unsorted anyway, while if the parent is to be a
2096 : * MergeAppend, there's no point in a separate sort on a child.
2097 : *
2098 : * Normally, either path is a partial path and subpaths is a list of partial
2099 : * paths, or else path is a non-partial plan and subpaths is a list of those.
2100 : * However, if path is a parallel-aware Append, then we add its partial path
2101 : * children to subpaths and the rest to special_subpaths. If the latter is
2102 : * NULL, we don't flatten the path at all (unless it contains only partial
2103 : * paths).
2104 : */
2105 : static void
2106 196848 : accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
2107 : {
2108 196848 : if (IsA(path, AppendPath))
2109 : {
2110 14244 : AppendPath *apath = (AppendPath *) path;
2111 :
2112 14244 : if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2113 : {
2114 14052 : *subpaths = list_concat(*subpaths, apath->subpaths);
2115 14052 : return;
2116 : }
2117 192 : else if (special_subpaths != NULL)
2118 : {
2119 : List *new_special_subpaths;
2120 :
2121 : /* Split Parallel Append into partial and non-partial subpaths */
2122 96 : *subpaths = list_concat(*subpaths,
2123 96 : list_copy_tail(apath->subpaths,
2124 : apath->first_partial_path));
2125 96 : new_special_subpaths = list_copy_head(apath->subpaths,
2126 : apath->first_partial_path);
2127 96 : *special_subpaths = list_concat(*special_subpaths,
2128 : new_special_subpaths);
2129 96 : return;
2130 : }
2131 : }
2132 182604 : else if (IsA(path, MergeAppendPath))
2133 : {
2134 692 : MergeAppendPath *mpath = (MergeAppendPath *) path;
2135 :
2136 692 : *subpaths = list_concat(*subpaths, mpath->subpaths);
2137 692 : return;
2138 : }
2139 :
2140 182008 : *subpaths = lappend(*subpaths, path);
2141 : }
2142 :
2143 : /*
2144 : * get_singleton_append_subpath
2145 : * Returns the single subpath of an Append/MergeAppend, or just
2146 : * return 'path' if it's not a single sub-path Append/MergeAppend.
2147 : *
2148 : * Note: 'path' must not be a parallel-aware path.
2149 : */
2150 : static Path *
2151 12472 : get_singleton_append_subpath(Path *path)
2152 : {
2153 : Assert(!path->parallel_aware);
2154 :
2155 12472 : if (IsA(path, AppendPath))
2156 : {
2157 352 : AppendPath *apath = (AppendPath *) path;
2158 :
2159 352 : if (list_length(apath->subpaths) == 1)
2160 156 : return (Path *) linitial(apath->subpaths);
2161 : }
2162 12120 : else if (IsA(path, MergeAppendPath))
2163 : {
2164 300 : MergeAppendPath *mpath = (MergeAppendPath *) path;
2165 :
2166 300 : if (list_length(mpath->subpaths) == 1)
2167 0 : return (Path *) linitial(mpath->subpaths);
2168 : }
2169 :
2170 12316 : return path;
2171 : }
2172 :
2173 : /*
2174 : * set_dummy_rel_pathlist
2175 : * Build a dummy path for a relation that's been excluded by constraints
2176 : *
2177 : * Rather than inventing a special "dummy" path type, we represent this as an
2178 : * AppendPath with no members (see also IS_DUMMY_APPEND/IS_DUMMY_REL macros).
2179 : *
2180 : * (See also mark_dummy_rel, which does basically the same thing, but is
2181 : * typically used to change a rel into dummy state after we already made
2182 : * paths for it.)
2183 : */
2184 : static void
2185 1066 : set_dummy_rel_pathlist(RelOptInfo *rel)
2186 : {
2187 : /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2188 1066 : rel->rows = 0;
2189 1066 : rel->reltarget->width = 0;
2190 :
2191 : /* Discard any pre-existing paths; no further need for them */
2192 1066 : rel->pathlist = NIL;
2193 1066 : rel->partial_pathlist = NIL;
2194 :
2195 : /* Set up the dummy path */
2196 1066 : add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
2197 : NIL, rel->lateral_relids,
2198 : 0, false, -1));
2199 :
2200 : /*
2201 : * We set the cheapest-path fields immediately, just in case they were
2202 : * pointing at some discarded path. This is redundant in current usage
2203 : * because set_rel_pathlist will do it later, but it's cheap so we keep it
2204 : * for safety and consistency with mark_dummy_rel.
2205 : */
2206 1066 : set_cheapest(rel);
2207 1066 : }
2208 :
2209 : /*
2210 : * find_window_run_conditions
2211 : * Determine if 'wfunc' is really a WindowFunc and call its prosupport
2212 : * function to determine the function's monotonic properties. We then
2213 : * see if 'opexpr' can be used to short-circuit execution.
2214 : *
2215 : * For example row_number() over (order by ...) always produces a value one
2216 : * higher than the previous. If someone has a window function in a subquery
2217 : * and has a WHERE clause in the outer query to filter rows <= 10, then we may
2218 : * as well stop processing the windowagg once the row number reaches 11. Here
2219 : * we check if 'opexpr' might help us to stop doing needless extra processing
2220 : * in WindowAgg nodes.
2221 : *
2222 : * '*keep_original' is set to true if the caller should also use 'opexpr' for
2223 : * its original purpose. This is set to false if the caller can assume that
2224 : * the run condition will handle all of the required filtering.
2225 : *
2226 : * Returns true if 'opexpr' was found to be useful and was added to the
2227 : * WindowFunc's runCondition. We also set *keep_original accordingly and add
2228 : * 'attno' to *run_cond_attrs offset by FirstLowInvalidHeapAttributeNumber.
2229 : * If the 'opexpr' cannot be used then we set *keep_original to true and
2230 : * return false.
2231 : */
2232 : static bool
2233 240 : find_window_run_conditions(Query *subquery, RangeTblEntry *rte, Index rti,
2234 : AttrNumber attno, WindowFunc *wfunc, OpExpr *opexpr,
2235 : bool wfunc_left, bool *keep_original,
2236 : Bitmapset **run_cond_attrs)
2237 : {
2238 : Oid prosupport;
2239 : Expr *otherexpr;
2240 : SupportRequestWFuncMonotonic req;
2241 : SupportRequestWFuncMonotonic *res;
2242 : WindowClause *wclause;
2243 : List *opinfos;
2244 : OpExpr *runopexpr;
2245 : Oid runoperator;
2246 : ListCell *lc;
2247 :
2248 240 : *keep_original = true;
2249 :
2250 240 : while (IsA(wfunc, RelabelType))
2251 0 : wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2252 :
2253 : /* we can only work with window functions */
2254 240 : if (!IsA(wfunc, WindowFunc))
2255 24 : return false;
2256 :
2257 : /* can't use it if there are subplans in the WindowFunc */
2258 216 : if (contain_subplans((Node *) wfunc))
2259 6 : return false;
2260 :
2261 210 : prosupport = get_func_support(wfunc->winfnoid);
2262 :
2263 : /* Check if there's a support function for 'wfunc' */
2264 210 : if (!OidIsValid(prosupport))
2265 18 : return false;
2266 :
2267 : /* get the Expr from the other side of the OpExpr */
2268 192 : if (wfunc_left)
2269 168 : otherexpr = lsecond(opexpr->args);
2270 : else
2271 24 : otherexpr = linitial(opexpr->args);
2272 :
2273 : /*
2274 : * The value being compared must not change during the evaluation of the
2275 : * window partition.
2276 : */
2277 192 : if (!is_pseudo_constant_clause((Node *) otherexpr))
2278 0 : return false;
2279 :
2280 : /* find the window clause belonging to the window function */
2281 192 : wclause = (WindowClause *) list_nth(subquery->windowClause,
2282 192 : wfunc->winref - 1);
2283 :
2284 192 : req.type = T_SupportRequestWFuncMonotonic;
2285 192 : req.window_func = wfunc;
2286 192 : req.window_clause = wclause;
2287 :
2288 : /* call the support function */
2289 : res = (SupportRequestWFuncMonotonic *)
2290 192 : DatumGetPointer(OidFunctionCall1(prosupport,
2291 : PointerGetDatum(&req)));
2292 :
2293 : /*
2294 : * Nothing to do if the function is neither monotonically increasing nor
2295 : * monotonically decreasing.
2296 : */
2297 192 : if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2298 0 : return false;
2299 :
2300 192 : runopexpr = NULL;
2301 192 : runoperator = InvalidOid;
2302 192 : opinfos = get_op_btree_interpretation(opexpr->opno);
2303 :
2304 192 : foreach(lc, opinfos)
2305 : {
2306 192 : OpBtreeInterpretation *opinfo = (OpBtreeInterpretation *) lfirst(lc);
2307 192 : int strategy = opinfo->strategy;
2308 :
2309 : /* handle < / <= */
2310 192 : if (strategy == BTLessStrategyNumber ||
2311 : strategy == BTLessEqualStrategyNumber)
2312 : {
2313 : /*
2314 : * < / <= is supported for monotonically increasing functions in
2315 : * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2316 : * for monotonically decreasing functions.
2317 : */
2318 138 : if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2319 18 : (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2320 : {
2321 126 : *keep_original = false;
2322 126 : runopexpr = opexpr;
2323 126 : runoperator = opexpr->opno;
2324 : }
2325 138 : break;
2326 : }
2327 : /* handle > / >= */
2328 54 : else if (strategy == BTGreaterStrategyNumber ||
2329 : strategy == BTGreaterEqualStrategyNumber)
2330 : {
2331 : /*
2332 : * > / >= is supported for monotonically decreasing functions in
2333 : * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2334 : * for monotonically increasing functions.
2335 : */
2336 18 : if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2337 12 : (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2338 : {
2339 18 : *keep_original = false;
2340 18 : runopexpr = opexpr;
2341 18 : runoperator = opexpr->opno;
2342 : }
2343 18 : break;
2344 : }
2345 : /* handle = */
2346 36 : else if (strategy == BTEqualStrategyNumber)
2347 : {
2348 : int16 newstrategy;
2349 :
2350 : /*
2351 : * When both monotonically increasing and decreasing then the
2352 : * return value of the window function will be the same each time.
2353 : * We can simply use 'opexpr' as the run condition without
2354 : * modifying it.
2355 : */
2356 36 : if ((res->monotonic & MONOTONICFUNC_BOTH) == MONOTONICFUNC_BOTH)
2357 : {
2358 6 : *keep_original = false;
2359 6 : runopexpr = opexpr;
2360 6 : runoperator = opexpr->opno;
2361 6 : break;
2362 : }
2363 :
2364 : /*
2365 : * When monotonically increasing we make a qual with <wfunc> <=
2366 : * <value> or <value> >= <wfunc> in order to filter out values
2367 : * which are above the value in the equality condition. For
2368 : * monotonically decreasing functions we want to filter values
2369 : * below the value in the equality condition.
2370 : */
2371 30 : if (res->monotonic & MONOTONICFUNC_INCREASING)
2372 30 : newstrategy = wfunc_left ? BTLessEqualStrategyNumber : BTGreaterEqualStrategyNumber;
2373 : else
2374 0 : newstrategy = wfunc_left ? BTGreaterEqualStrategyNumber : BTLessEqualStrategyNumber;
2375 :
2376 : /* We must keep the original equality qual */
2377 30 : *keep_original = true;
2378 30 : runopexpr = opexpr;
2379 :
2380 : /* determine the operator to use for the WindowFuncRunCondition */
2381 30 : runoperator = get_opfamily_member(opinfo->opfamily_id,
2382 : opinfo->oplefttype,
2383 : opinfo->oprighttype,
2384 : newstrategy);
2385 30 : break;
2386 : }
2387 : }
2388 :
2389 192 : if (runopexpr != NULL)
2390 : {
2391 : WindowFuncRunCondition *wfuncrc;
2392 :
2393 180 : wfuncrc = makeNode(WindowFuncRunCondition);
2394 180 : wfuncrc->opno = runoperator;
2395 180 : wfuncrc->inputcollid = runopexpr->inputcollid;
2396 180 : wfuncrc->wfunc_left = wfunc_left;
2397 180 : wfuncrc->arg = copyObject(otherexpr);
2398 :
2399 180 : wfunc->runCondition = lappend(wfunc->runCondition, wfuncrc);
2400 :
2401 : /* record that this attno was used in a run condition */
2402 180 : *run_cond_attrs = bms_add_member(*run_cond_attrs,
2403 : attno - FirstLowInvalidHeapAttributeNumber);
2404 180 : return true;
2405 : }
2406 :
2407 : /* unsupported OpExpr */
2408 12 : return false;
2409 : }
2410 :
2411 : /*
2412 : * check_and_push_window_quals
2413 : * Check if 'clause' is a qual that can be pushed into a WindowFunc
2414 : * as a 'runCondition' qual. These, when present, allow some unnecessary
2415 : * work to be skipped during execution.
2416 : *
2417 : * 'run_cond_attrs' will be populated with all targetlist resnos of subquery
2418 : * targets (offset by FirstLowInvalidHeapAttributeNumber) that we pushed
2419 : * window quals for.
2420 : *
2421 : * Returns true if the caller still must keep the original qual or false if
2422 : * the caller can safely ignore the original qual because the WindowAgg node
2423 : * will use the runCondition to stop returning tuples.
2424 : */
2425 : static bool
2426 252 : check_and_push_window_quals(Query *subquery, RangeTblEntry *rte, Index rti,
2427 : Node *clause, Bitmapset **run_cond_attrs)
2428 : {
2429 252 : OpExpr *opexpr = (OpExpr *) clause;
2430 252 : bool keep_original = true;
2431 : Var *var1;
2432 : Var *var2;
2433 :
2434 : /* We're only able to use OpExprs with 2 operands */
2435 252 : if (!IsA(opexpr, OpExpr))
2436 18 : return true;
2437 :
2438 234 : if (list_length(opexpr->args) != 2)
2439 0 : return true;
2440 :
2441 : /*
2442 : * Currently, we restrict this optimization to strict OpExprs. The reason
2443 : * for this is that during execution, once the runcondition becomes false,
2444 : * we stop evaluating WindowFuncs. To avoid leaving around stale window
2445 : * function result values, we set them to NULL. Having only strict
2446 : * OpExprs here ensures that we properly filter out the tuples with NULLs
2447 : * in the top-level WindowAgg.
2448 : */
2449 234 : set_opfuncid(opexpr);
2450 234 : if (!func_strict(opexpr->opfuncid))
2451 0 : return true;
2452 :
2453 : /*
2454 : * Check for plain Vars that reference window functions in the subquery.
2455 : * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2456 : * be used as part of the run condition.
2457 : */
2458 :
2459 : /* Check the left side of the OpExpr */
2460 234 : var1 = linitial(opexpr->args);
2461 234 : if (IsA(var1, Var) && var1->varattno > 0)
2462 : {
2463 198 : TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2464 198 : WindowFunc *wfunc = (WindowFunc *) tle->expr;
2465 :
2466 198 : if (find_window_run_conditions(subquery, rte, rti, tle->resno, wfunc,
2467 : opexpr, true, &keep_original,
2468 : run_cond_attrs))
2469 162 : return keep_original;
2470 : }
2471 :
2472 : /* and check the right side */
2473 72 : var2 = lsecond(opexpr->args);
2474 72 : if (IsA(var2, Var) && var2->varattno > 0)
2475 : {
2476 42 : TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2477 42 : WindowFunc *wfunc = (WindowFunc *) tle->expr;
2478 :
2479 42 : if (find_window_run_conditions(subquery, rte, rti, tle->resno, wfunc,
2480 : opexpr, false, &keep_original,
2481 : run_cond_attrs))
2482 18 : return keep_original;
2483 : }
2484 :
2485 54 : return true;
2486 : }
2487 :
2488 : /*
2489 : * set_subquery_pathlist
2490 : * Generate SubqueryScan access paths for a subquery RTE
2491 : *
2492 : * We don't currently support generating parameterized paths for subqueries
2493 : * by pushing join clauses down into them; it seems too expensive to re-plan
2494 : * the subquery multiple times to consider different alternatives.
2495 : * (XXX that could stand to be reconsidered, now that we use Paths.)
2496 : * So the paths made here will be parameterized if the subquery contains
2497 : * LATERAL references, otherwise not. As long as that's true, there's no need
2498 : * for a separate set_subquery_size phase: just make the paths right away.
2499 : */
2500 : static void
2501 20250 : set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
2502 : Index rti, RangeTblEntry *rte)
2503 : {
2504 20250 : Query *parse = root->parse;
2505 20250 : Query *subquery = rte->subquery;
2506 : bool trivial_pathtarget;
2507 : Relids required_outer;
2508 : pushdown_safety_info safetyInfo;
2509 : double tuple_fraction;
2510 : RelOptInfo *sub_final_rel;
2511 20250 : Bitmapset *run_cond_attrs = NULL;
2512 : ListCell *lc;
2513 :
2514 : /*
2515 : * Must copy the Query so that planning doesn't mess up the RTE contents
2516 : * (really really need to fix the planner to not scribble on its input,
2517 : * someday ... but see remove_unused_subquery_outputs to start with).
2518 : */
2519 20250 : subquery = copyObject(subquery);
2520 :
2521 : /*
2522 : * If it's a LATERAL subquery, it might contain some Vars of the current
2523 : * query level, requiring it to be treated as parameterized, even though
2524 : * we don't support pushing down join quals into subqueries.
2525 : */
2526 20250 : required_outer = rel->lateral_relids;
2527 :
2528 : /*
2529 : * Zero out result area for subquery_is_pushdown_safe, so that it can set
2530 : * flags as needed while recursing. In particular, we need a workspace
2531 : * for keeping track of the reasons why columns are unsafe to reference.
2532 : * These reasons are stored in the bits inside unsafeFlags[i] when we
2533 : * discover reasons that column i of the subquery is unsafe to be used in
2534 : * a pushed-down qual.
2535 : */
2536 20250 : memset(&safetyInfo, 0, sizeof(safetyInfo));
2537 20250 : safetyInfo.unsafeFlags = (unsigned char *)
2538 20250 : palloc0((list_length(subquery->targetList) + 1) * sizeof(unsigned char));
2539 :
2540 : /*
2541 : * If the subquery has the "security_barrier" flag, it means the subquery
2542 : * originated from a view that must enforce row-level security. Then we
2543 : * must not push down quals that contain leaky functions. (Ideally this
2544 : * would be checked inside subquery_is_pushdown_safe, but since we don't
2545 : * currently pass the RTE to that function, we must do it here.)
2546 : */
2547 20250 : safetyInfo.unsafeLeaky = rte->security_barrier;
2548 :
2549 : /*
2550 : * If there are any restriction clauses that have been attached to the
2551 : * subquery relation, consider pushing them down to become WHERE or HAVING
2552 : * quals of the subquery itself. This transformation is useful because it
2553 : * may allow us to generate a better plan for the subquery than evaluating
2554 : * all the subquery output rows and then filtering them.
2555 : *
2556 : * There are several cases where we cannot push down clauses. Restrictions
2557 : * involving the subquery are checked by subquery_is_pushdown_safe().
2558 : * Restrictions on individual clauses are checked by
2559 : * qual_is_pushdown_safe(). Also, we don't want to push down
2560 : * pseudoconstant clauses; better to have the gating node above the
2561 : * subquery.
2562 : *
2563 : * Non-pushed-down clauses will get evaluated as qpquals of the
2564 : * SubqueryScan node.
2565 : *
2566 : * XXX Are there any cases where we want to make a policy decision not to
2567 : * push down a pushable qual, because it'd result in a worse plan?
2568 : */
2569 33738 : if (rel->baserestrictinfo != NIL &&
2570 13488 : subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2571 : {
2572 : /* OK to consider pushing down individual quals */
2573 13342 : List *upperrestrictlist = NIL;
2574 : ListCell *l;
2575 :
2576 39486 : foreach(l, rel->baserestrictinfo)
2577 : {
2578 26144 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2579 26144 : Node *clause = (Node *) rinfo->clause;
2580 :
2581 26144 : if (rinfo->pseudoconstant)
2582 : {
2583 4 : upperrestrictlist = lappend(upperrestrictlist, rinfo);
2584 4 : continue;
2585 : }
2586 :
2587 26140 : switch (qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2588 : {
2589 25458 : case PUSHDOWN_SAFE:
2590 : /* Push it down */
2591 25458 : subquery_push_qual(subquery, rte, rti, clause);
2592 25458 : break;
2593 :
2594 252 : case PUSHDOWN_WINDOWCLAUSE_RUNCOND:
2595 :
2596 : /*
2597 : * Since we can't push the qual down into the subquery,
2598 : * check if it happens to reference a window function. If
2599 : * so then it might be useful to use for the WindowAgg's
2600 : * runCondition.
2601 : */
2602 504 : if (!subquery->hasWindowFuncs ||
2603 252 : check_and_push_window_quals(subquery, rte, rti, clause,
2604 : &run_cond_attrs))
2605 : {
2606 : /*
2607 : * subquery has no window funcs or the clause is not a
2608 : * suitable window run condition qual or it is, but
2609 : * the original must also be kept in the upper query.
2610 : */
2611 102 : upperrestrictlist = lappend(upperrestrictlist, rinfo);
2612 : }
2613 252 : break;
2614 :
2615 430 : case PUSHDOWN_UNSAFE:
2616 430 : upperrestrictlist = lappend(upperrestrictlist, rinfo);
2617 430 : break;
2618 : }
2619 26144 : }
2620 13342 : rel->baserestrictinfo = upperrestrictlist;
2621 : /* We don't bother recomputing baserestrict_min_security */
2622 : }
2623 :
2624 20250 : pfree(safetyInfo.unsafeFlags);
2625 :
2626 : /*
2627 : * The upper query might not use all the subquery's output columns; if
2628 : * not, we can simplify. Pass the attributes that were pushed down into
2629 : * WindowAgg run conditions to ensure we don't accidentally think those
2630 : * are unused.
2631 : */
2632 20250 : remove_unused_subquery_outputs(subquery, rel, run_cond_attrs);
2633 :
2634 : /*
2635 : * We can safely pass the outer tuple_fraction down to the subquery if the
2636 : * outer level has no joining, aggregation, or sorting to do. Otherwise
2637 : * we'd better tell the subquery to plan for full retrieval. (XXX This
2638 : * could probably be made more intelligent ...)
2639 : */
2640 20250 : if (parse->hasAggs ||
2641 18990 : parse->groupClause ||
2642 18972 : parse->groupingSets ||
2643 18972 : root->hasHavingQual ||
2644 18972 : parse->distinctClause ||
2645 23214 : parse->sortClause ||
2646 4726 : bms_membership(root->all_baserels) == BMS_MULTIPLE)
2647 16684 : tuple_fraction = 0.0; /* default case */
2648 : else
2649 3566 : tuple_fraction = root->tuple_fraction;
2650 :
2651 : /* plan_params should not be in use in current query level */
2652 : Assert(root->plan_params == NIL);
2653 :
2654 : /* Generate a subroot and Paths for the subquery */
2655 20250 : rel->subroot = subquery_planner(root->glob, subquery, root, false,
2656 : tuple_fraction, NULL);
2657 :
2658 : /* Isolate the params needed by this specific subplan */
2659 20250 : rel->subplan_params = root->plan_params;
2660 20250 : root->plan_params = NIL;
2661 :
2662 : /*
2663 : * It's possible that constraint exclusion proved the subquery empty. If
2664 : * so, it's desirable to produce an unadorned dummy path so that we will
2665 : * recognize appropriate optimizations at this query level.
2666 : */
2667 20250 : sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
2668 :
2669 20250 : if (IS_DUMMY_REL(sub_final_rel))
2670 : {
2671 120 : set_dummy_rel_pathlist(rel);
2672 120 : return;
2673 : }
2674 :
2675 : /*
2676 : * Mark rel with estimated output rows, width, etc. Note that we have to
2677 : * do this before generating outer-query paths, else cost_subqueryscan is
2678 : * not happy.
2679 : */
2680 20130 : set_subquery_size_estimates(root, rel);
2681 :
2682 : /*
2683 : * Also detect whether the reltarget is trivial, so that we can pass that
2684 : * info to cost_subqueryscan (rather than re-deriving it multiple times).
2685 : * It's trivial if it fetches all the subplan output columns in order.
2686 : */
2687 20130 : if (list_length(rel->reltarget->exprs) != list_length(subquery->targetList))
2688 2656 : trivial_pathtarget = false;
2689 : else
2690 : {
2691 17474 : trivial_pathtarget = true;
2692 30312 : foreach(lc, rel->reltarget->exprs)
2693 : {
2694 25034 : Node *node = (Node *) lfirst(lc);
2695 : Var *var;
2696 :
2697 25034 : if (!IsA(node, Var))
2698 : {
2699 0 : trivial_pathtarget = false;
2700 0 : break;
2701 : }
2702 25034 : var = (Var *) node;
2703 25034 : if (var->varno != rti ||
2704 25034 : var->varattno != foreach_current_index(lc) + 1)
2705 : {
2706 12196 : trivial_pathtarget = false;
2707 12196 : break;
2708 : }
2709 : }
2710 : }
2711 :
2712 : /*
2713 : * For each Path that subquery_planner produced, make a SubqueryScanPath
2714 : * in the outer query.
2715 : */
2716 41026 : foreach(lc, sub_final_rel->pathlist)
2717 : {
2718 20896 : Path *subpath = (Path *) lfirst(lc);
2719 : List *pathkeys;
2720 :
2721 : /* Convert subpath's pathkeys to outer representation */
2722 20896 : pathkeys = convert_subquery_pathkeys(root,
2723 : rel,
2724 : subpath->pathkeys,
2725 : make_tlist_from_pathtarget(subpath->pathtarget));
2726 :
2727 : /* Generate outer path using this subpath */
2728 20896 : add_path(rel, (Path *)
2729 20896 : create_subqueryscan_path(root, rel, subpath,
2730 : trivial_pathtarget,
2731 : pathkeys, required_outer));
2732 : }
2733 :
2734 : /* If outer rel allows parallelism, do same for partial paths. */
2735 20130 : if (rel->consider_parallel && bms_is_empty(required_outer))
2736 : {
2737 : /* If consider_parallel is false, there should be no partial paths. */
2738 : Assert(sub_final_rel->consider_parallel ||
2739 : sub_final_rel->partial_pathlist == NIL);
2740 :
2741 : /* Same for partial paths. */
2742 16216 : foreach(lc, sub_final_rel->partial_pathlist)
2743 : {
2744 42 : Path *subpath = (Path *) lfirst(lc);
2745 : List *pathkeys;
2746 :
2747 : /* Convert subpath's pathkeys to outer representation */
2748 42 : pathkeys = convert_subquery_pathkeys(root,
2749 : rel,
2750 : subpath->pathkeys,
2751 : make_tlist_from_pathtarget(subpath->pathtarget));
2752 :
2753 : /* Generate outer path using this subpath */
2754 42 : add_partial_path(rel, (Path *)
2755 42 : create_subqueryscan_path(root, rel, subpath,
2756 : trivial_pathtarget,
2757 : pathkeys,
2758 : required_outer));
2759 : }
2760 : }
2761 : }
2762 :
2763 : /*
2764 : * set_function_pathlist
2765 : * Build the (single) access path for a function RTE
2766 : */
2767 : static void
2768 47988 : set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2769 : {
2770 : Relids required_outer;
2771 47988 : List *pathkeys = NIL;
2772 :
2773 : /*
2774 : * We don't support pushing join clauses into the quals of a function
2775 : * scan, but it could still have required parameterization due to LATERAL
2776 : * refs in the function expression.
2777 : */
2778 47988 : required_outer = rel->lateral_relids;
2779 :
2780 : /*
2781 : * The result is considered unordered unless ORDINALITY was used, in which
2782 : * case it is ordered by the ordinal column (the last one). See if we
2783 : * care, by checking for uses of that Var in equivalence classes.
2784 : */
2785 47988 : if (rte->funcordinality)
2786 : {
2787 698 : AttrNumber ordattno = rel->max_attr;
2788 698 : Var *var = NULL;
2789 : ListCell *lc;
2790 :
2791 : /*
2792 : * Is there a Var for it in rel's targetlist? If not, the query did
2793 : * not reference the ordinality column, or at least not in any way
2794 : * that would be interesting for sorting.
2795 : */
2796 1852 : foreach(lc, rel->reltarget->exprs)
2797 : {
2798 1846 : Var *node = (Var *) lfirst(lc);
2799 :
2800 : /* checking varno/varlevelsup is just paranoia */
2801 1846 : if (IsA(node, Var) &&
2802 1846 : node->varattno == ordattno &&
2803 692 : node->varno == rel->relid &&
2804 692 : node->varlevelsup == 0)
2805 : {
2806 692 : var = node;
2807 692 : break;
2808 : }
2809 : }
2810 :
2811 : /*
2812 : * Try to build pathkeys for this Var with int8 sorting. We tell
2813 : * build_expression_pathkey not to build any new equivalence class; if
2814 : * the Var isn't already mentioned in some EC, it means that nothing
2815 : * cares about the ordering.
2816 : */
2817 698 : if (var)
2818 692 : pathkeys = build_expression_pathkey(root,
2819 : (Expr *) var,
2820 : Int8LessOperator,
2821 : rel->relids,
2822 : false);
2823 : }
2824 :
2825 : /* Generate appropriate path */
2826 47988 : add_path(rel, create_functionscan_path(root, rel,
2827 : pathkeys, required_outer));
2828 47988 : }
2829 :
2830 : /*
2831 : * set_values_pathlist
2832 : * Build the (single) access path for a VALUES RTE
2833 : */
2834 : static void
2835 8152 : set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2836 : {
2837 : Relids required_outer;
2838 :
2839 : /*
2840 : * We don't support pushing join clauses into the quals of a values scan,
2841 : * but it could still have required parameterization due to LATERAL refs
2842 : * in the values expressions.
2843 : */
2844 8152 : required_outer = rel->lateral_relids;
2845 :
2846 : /* Generate appropriate path */
2847 8152 : add_path(rel, create_valuesscan_path(root, rel, required_outer));
2848 8152 : }
2849 :
2850 : /*
2851 : * set_tablefunc_pathlist
2852 : * Build the (single) access path for a table func RTE
2853 : */
2854 : static void
2855 626 : set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2856 : {
2857 : Relids required_outer;
2858 :
2859 : /*
2860 : * We don't support pushing join clauses into the quals of a tablefunc
2861 : * scan, but it could still have required parameterization due to LATERAL
2862 : * refs in the function expression.
2863 : */
2864 626 : required_outer = rel->lateral_relids;
2865 :
2866 : /* Generate appropriate path */
2867 626 : add_path(rel, create_tablefuncscan_path(root, rel,
2868 : required_outer));
2869 626 : }
2870 :
2871 : /*
2872 : * set_cte_pathlist
2873 : * Build the (single) access path for a non-self-reference CTE RTE
2874 : *
2875 : * There's no need for a separate set_cte_size phase, since we don't
2876 : * support join-qual-parameterized paths for CTEs.
2877 : */
2878 : static void
2879 3298 : set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2880 : {
2881 : Path *ctepath;
2882 : Plan *cteplan;
2883 : PlannerInfo *cteroot;
2884 : Index levelsup;
2885 : List *pathkeys;
2886 : int ndx;
2887 : ListCell *lc;
2888 : int plan_id;
2889 : Relids required_outer;
2890 :
2891 : /*
2892 : * Find the referenced CTE, and locate the path and plan previously made
2893 : * for it.
2894 : */
2895 3298 : levelsup = rte->ctelevelsup;
2896 3298 : cteroot = root;
2897 5862 : while (levelsup-- > 0)
2898 : {
2899 2564 : cteroot = cteroot->parent_root;
2900 2564 : if (!cteroot) /* shouldn't happen */
2901 0 : elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2902 : }
2903 :
2904 : /*
2905 : * Note: cte_plan_ids can be shorter than cteList, if we are still working
2906 : * on planning the CTEs (ie, this is a side-reference from another CTE).
2907 : * So we mustn't use forboth here.
2908 : */
2909 3298 : ndx = 0;
2910 4754 : foreach(lc, cteroot->parse->cteList)
2911 : {
2912 4754 : CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2913 :
2914 4754 : if (strcmp(cte->ctename, rte->ctename) == 0)
2915 3298 : break;
2916 1456 : ndx++;
2917 : }
2918 3298 : if (lc == NULL) /* shouldn't happen */
2919 0 : elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
2920 3298 : if (ndx >= list_length(cteroot->cte_plan_ids))
2921 0 : elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2922 3298 : plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
2923 3298 : if (plan_id <= 0)
2924 0 : elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
2925 :
2926 : Assert(list_length(root->glob->subpaths) == list_length(root->glob->subplans));
2927 3298 : ctepath = (Path *) list_nth(root->glob->subpaths, plan_id - 1);
2928 3298 : cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2929 :
2930 : /* Mark rel with estimated output rows, width, etc */
2931 3298 : set_cte_size_estimates(root, rel, cteplan->plan_rows);
2932 :
2933 : /* Convert the ctepath's pathkeys to outer query's representation */
2934 3298 : pathkeys = convert_subquery_pathkeys(root,
2935 : rel,
2936 : ctepath->pathkeys,
2937 : cteplan->targetlist);
2938 :
2939 : /*
2940 : * We don't support pushing join clauses into the quals of a CTE scan, but
2941 : * it could still have required parameterization due to LATERAL refs in
2942 : * its tlist.
2943 : */
2944 3298 : required_outer = rel->lateral_relids;
2945 :
2946 : /* Generate appropriate path */
2947 3298 : add_path(rel, create_ctescan_path(root, rel, pathkeys, required_outer));
2948 3298 : }
2949 :
2950 : /*
2951 : * set_namedtuplestore_pathlist
2952 : * Build the (single) access path for a named tuplestore RTE
2953 : *
2954 : * There's no need for a separate set_namedtuplestore_size phase, since we
2955 : * don't support join-qual-parameterized paths for tuplestores.
2956 : */
2957 : static void
2958 470 : set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel,
2959 : RangeTblEntry *rte)
2960 : {
2961 : Relids required_outer;
2962 :
2963 : /* Mark rel with estimated output rows, width, etc */
2964 470 : set_namedtuplestore_size_estimates(root, rel);
2965 :
2966 : /*
2967 : * We don't support pushing join clauses into the quals of a tuplestore
2968 : * scan, but it could still have required parameterization due to LATERAL
2969 : * refs in its tlist.
2970 : */
2971 470 : required_outer = rel->lateral_relids;
2972 :
2973 : /* Generate appropriate path */
2974 470 : add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
2975 470 : }
2976 :
2977 : /*
2978 : * set_result_pathlist
2979 : * Build the (single) access path for an RTE_RESULT RTE
2980 : *
2981 : * There's no need for a separate set_result_size phase, since we
2982 : * don't support join-qual-parameterized paths for these RTEs.
2983 : */
2984 : static void
2985 1616 : set_result_pathlist(PlannerInfo *root, RelOptInfo *rel,
2986 : RangeTblEntry *rte)
2987 : {
2988 : Relids required_outer;
2989 :
2990 : /* Mark rel with estimated output rows, width, etc */
2991 1616 : set_result_size_estimates(root, rel);
2992 :
2993 : /*
2994 : * We don't support pushing join clauses into the quals of a Result scan,
2995 : * but it could still have required parameterization due to LATERAL refs
2996 : * in its tlist.
2997 : */
2998 1616 : required_outer = rel->lateral_relids;
2999 :
3000 : /* Generate appropriate path */
3001 1616 : add_path(rel, create_resultscan_path(root, rel, required_outer));
3002 1616 : }
3003 :
3004 : /*
3005 : * set_worktable_pathlist
3006 : * Build the (single) access path for a self-reference CTE RTE
3007 : *
3008 : * There's no need for a separate set_worktable_size phase, since we don't
3009 : * support join-qual-parameterized paths for CTEs.
3010 : */
3011 : static void
3012 834 : set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3013 : {
3014 : Path *ctepath;
3015 : PlannerInfo *cteroot;
3016 : Index levelsup;
3017 : Relids required_outer;
3018 :
3019 : /*
3020 : * We need to find the non-recursive term's path, which is in the plan
3021 : * level that's processing the recursive UNION, which is one level *below*
3022 : * where the CTE comes from.
3023 : */
3024 834 : levelsup = rte->ctelevelsup;
3025 834 : if (levelsup == 0) /* shouldn't happen */
3026 0 : elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3027 834 : levelsup--;
3028 834 : cteroot = root;
3029 1904 : while (levelsup-- > 0)
3030 : {
3031 1070 : cteroot = cteroot->parent_root;
3032 1070 : if (!cteroot) /* shouldn't happen */
3033 0 : elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3034 : }
3035 834 : ctepath = cteroot->non_recursive_path;
3036 834 : if (!ctepath) /* shouldn't happen */
3037 0 : elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
3038 :
3039 : /* Mark rel with estimated output rows, width, etc */
3040 834 : set_cte_size_estimates(root, rel, ctepath->rows);
3041 :
3042 : /*
3043 : * We don't support pushing join clauses into the quals of a worktable
3044 : * scan, but it could still have required parameterization due to LATERAL
3045 : * refs in its tlist. (I'm not sure this is actually possible given the
3046 : * restrictions on recursive references, but it's easy enough to support.)
3047 : */
3048 834 : required_outer = rel->lateral_relids;
3049 :
3050 : /* Generate appropriate path */
3051 834 : add_path(rel, create_worktablescan_path(root, rel, required_outer));
3052 834 : }
3053 :
3054 : /*
3055 : * generate_gather_paths
3056 : * Generate parallel access paths for a relation by pushing a Gather or
3057 : * Gather Merge on top of a partial path.
3058 : *
3059 : * This must not be called until after we're done creating all partial paths
3060 : * for the specified relation. (Otherwise, add_partial_path might delete a
3061 : * path that some GatherPath or GatherMergePath has a reference to.)
3062 : *
3063 : * If we're generating paths for a scan or join relation, override_rows will
3064 : * be false, and we'll just use the relation's size estimate. When we're
3065 : * being called for a partially-grouped or partially-distinct path, though, we
3066 : * need to override the rowcount estimate. (It's not clear that the
3067 : * particular value we're using here is actually best, but the underlying rel
3068 : * has no estimate so we must do something.)
3069 : */
3070 : void
3071 16414 : generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
3072 : {
3073 : Path *cheapest_partial_path;
3074 : Path *simple_gather_path;
3075 : ListCell *lc;
3076 : double rows;
3077 16414 : double *rowsp = NULL;
3078 :
3079 : /* If there are no partial paths, there's nothing to do here. */
3080 16414 : if (rel->partial_pathlist == NIL)
3081 0 : return;
3082 :
3083 : /* Should we override the rel's rowcount estimate? */
3084 16414 : if (override_rows)
3085 1752 : rowsp = &rows;
3086 :
3087 : /*
3088 : * The output of Gather is always unsorted, so there's only one partial
3089 : * path of interest: the cheapest one. That will be the one at the front
3090 : * of partial_pathlist because of the way add_partial_path works.
3091 : */
3092 16414 : cheapest_partial_path = linitial(rel->partial_pathlist);
3093 16414 : rows = compute_gather_rows(cheapest_partial_path);
3094 : simple_gather_path = (Path *)
3095 16414 : create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
3096 : NULL, rowsp);
3097 16414 : add_path(rel, simple_gather_path);
3098 :
3099 : /*
3100 : * For each useful ordering, we can consider an order-preserving Gather
3101 : * Merge.
3102 : */
3103 34150 : foreach(lc, rel->partial_pathlist)
3104 : {
3105 17736 : Path *subpath = (Path *) lfirst(lc);
3106 : GatherMergePath *path;
3107 :
3108 17736 : if (subpath->pathkeys == NIL)
3109 16064 : continue;
3110 :
3111 1672 : rows = compute_gather_rows(subpath);
3112 1672 : path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
3113 : subpath->pathkeys, NULL, rowsp);
3114 1672 : add_path(rel, &path->path);
3115 : }
3116 : }
3117 :
3118 : /*
3119 : * get_useful_pathkeys_for_relation
3120 : * Determine which orderings of a relation might be useful.
3121 : *
3122 : * Getting data in sorted order can be useful either because the requested
3123 : * order matches the final output ordering for the overall query we're
3124 : * planning, or because it enables an efficient merge join. Here, we try
3125 : * to figure out which pathkeys to consider.
3126 : *
3127 : * This allows us to do incremental sort on top of an index scan under a gather
3128 : * merge node, i.e. parallelized.
3129 : *
3130 : * If the require_parallel_safe is true, we also require the expressions to
3131 : * be parallel safe (which allows pushing the sort below Gather Merge).
3132 : *
3133 : * XXX At the moment this can only ever return a list with a single element,
3134 : * because it looks at query_pathkeys only. So we might return the pathkeys
3135 : * directly, but it seems plausible we'll want to consider other orderings
3136 : * in the future. For example, we might want to consider pathkeys useful for
3137 : * merge joins.
3138 : */
3139 : static List *
3140 16414 : get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel,
3141 : bool require_parallel_safe)
3142 : {
3143 16414 : List *useful_pathkeys_list = NIL;
3144 :
3145 : /*
3146 : * Considering query_pathkeys is always worth it, because it might allow
3147 : * us to avoid a total sort when we have a partially presorted path
3148 : * available or to push the total sort into the parallel portion of the
3149 : * query.
3150 : */
3151 16414 : if (root->query_pathkeys)
3152 : {
3153 : ListCell *lc;
3154 7074 : int npathkeys = 0; /* useful pathkeys */
3155 :
3156 15218 : foreach(lc, root->query_pathkeys)
3157 : {
3158 10176 : PathKey *pathkey = (PathKey *) lfirst(lc);
3159 10176 : EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3160 :
3161 : /*
3162 : * We can only build a sort for pathkeys that contain a
3163 : * safe-to-compute-early EC member computable from the current
3164 : * relation's reltarget, so ignore the remainder of the list as
3165 : * soon as we find a pathkey without such a member.
3166 : *
3167 : * It's still worthwhile to return any prefix of the pathkeys list
3168 : * that meets this requirement, as we may be able to do an
3169 : * incremental sort.
3170 : *
3171 : * If requested, ensure the sort expression is parallel-safe too.
3172 : */
3173 10176 : if (!relation_can_be_sorted_early(root, rel, pathkey_ec,
3174 : require_parallel_safe))
3175 2032 : break;
3176 :
3177 8144 : npathkeys++;
3178 : }
3179 :
3180 : /*
3181 : * The whole query_pathkeys list matches, so append it directly, to
3182 : * allow comparing pathkeys easily by comparing list pointer. If we
3183 : * have to truncate the pathkeys, we gotta do a copy though.
3184 : */
3185 7074 : if (npathkeys == list_length(root->query_pathkeys))
3186 5042 : useful_pathkeys_list = lappend(useful_pathkeys_list,
3187 5042 : root->query_pathkeys);
3188 2032 : else if (npathkeys > 0)
3189 432 : useful_pathkeys_list = lappend(useful_pathkeys_list,
3190 432 : list_copy_head(root->query_pathkeys,
3191 : npathkeys));
3192 : }
3193 :
3194 16414 : return useful_pathkeys_list;
3195 : }
3196 :
3197 : /*
3198 : * generate_useful_gather_paths
3199 : * Generate parallel access paths for a relation by pushing a Gather or
3200 : * Gather Merge on top of a partial path.
3201 : *
3202 : * Unlike plain generate_gather_paths, this looks both at pathkeys of input
3203 : * paths (aiming to preserve the ordering), but also considers ordering that
3204 : * might be useful for nodes above the gather merge node, and tries to add
3205 : * a sort (regular or incremental) to provide that.
3206 : */
3207 : void
3208 808340 : generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
3209 : {
3210 : ListCell *lc;
3211 : double rows;
3212 808340 : double *rowsp = NULL;
3213 808340 : List *useful_pathkeys_list = NIL;
3214 808340 : Path *cheapest_partial_path = NULL;
3215 :
3216 : /* If there are no partial paths, there's nothing to do here. */
3217 808340 : if (rel->partial_pathlist == NIL)
3218 791926 : return;
3219 :
3220 : /* Should we override the rel's rowcount estimate? */
3221 16414 : if (override_rows)
3222 1752 : rowsp = &rows;
3223 :
3224 : /* generate the regular gather (merge) paths */
3225 16414 : generate_gather_paths(root, rel, override_rows);
3226 :
3227 : /* consider incremental sort for interesting orderings */
3228 16414 : useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
3229 :
3230 : /* used for explicit (full) sort paths */
3231 16414 : cheapest_partial_path = linitial(rel->partial_pathlist);
3232 :
3233 : /*
3234 : * Consider sorted paths for each interesting ordering. We generate both
3235 : * incremental and full sort.
3236 : */
3237 21888 : foreach(lc, useful_pathkeys_list)
3238 : {
3239 5474 : List *useful_pathkeys = lfirst(lc);
3240 : ListCell *lc2;
3241 : bool is_sorted;
3242 : int presorted_keys;
3243 :
3244 12138 : foreach(lc2, rel->partial_pathlist)
3245 : {
3246 6664 : Path *subpath = (Path *) lfirst(lc2);
3247 : GatherMergePath *path;
3248 :
3249 6664 : is_sorted = pathkeys_count_contained_in(useful_pathkeys,
3250 : subpath->pathkeys,
3251 : &presorted_keys);
3252 :
3253 : /*
3254 : * We don't need to consider the case where a subpath is already
3255 : * fully sorted because generate_gather_paths already creates a
3256 : * gather merge path for every subpath that has pathkeys present.
3257 : *
3258 : * But since the subpath is already sorted, we know we don't need
3259 : * to consider adding a sort (full or incremental) on top of it,
3260 : * so we can continue here.
3261 : */
3262 6664 : if (is_sorted)
3263 1192 : continue;
3264 :
3265 : /*
3266 : * Try at least sorting the cheapest path and also try
3267 : * incrementally sorting any path which is partially sorted
3268 : * already (no need to deal with paths which have presorted keys
3269 : * when incremental sort is disabled unless it's the cheapest
3270 : * input path).
3271 : */
3272 5472 : if (subpath != cheapest_partial_path &&
3273 222 : (presorted_keys == 0 || !enable_incremental_sort))
3274 78 : continue;
3275 :
3276 : /*
3277 : * Consider regular sort for any path that's not presorted or if
3278 : * incremental sort is disabled. We've no need to consider both
3279 : * sort and incremental sort on the same path. We assume that
3280 : * incremental sort is always faster when there are presorted
3281 : * keys.
3282 : *
3283 : * This is not redundant with the gather paths created in
3284 : * generate_gather_paths, because that doesn't generate ordered
3285 : * output. Here we add an explicit sort to match the useful
3286 : * ordering.
3287 : */
3288 5394 : if (presorted_keys == 0 || !enable_incremental_sort)
3289 : {
3290 5238 : subpath = (Path *) create_sort_path(root,
3291 : rel,
3292 : subpath,
3293 : useful_pathkeys,
3294 : -1.0);
3295 : }
3296 : else
3297 156 : subpath = (Path *) create_incremental_sort_path(root,
3298 : rel,
3299 : subpath,
3300 : useful_pathkeys,
3301 : presorted_keys,
3302 : -1);
3303 5394 : rows = compute_gather_rows(subpath);
3304 5394 : path = create_gather_merge_path(root, rel,
3305 : subpath,
3306 5394 : rel->reltarget,
3307 : subpath->pathkeys,
3308 : NULL,
3309 : rowsp);
3310 :
3311 5394 : add_path(rel, &path->path);
3312 : }
3313 : }
3314 : }
3315 :
3316 : /*
3317 : * make_rel_from_joinlist
3318 : * Build access paths using a "joinlist" to guide the join path search.
3319 : *
3320 : * See comments for deconstruct_jointree() for definition of the joinlist
3321 : * data structure.
3322 : */
3323 : static RelOptInfo *
3324 339430 : make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
3325 : {
3326 : int levels_needed;
3327 : List *initial_rels;
3328 : ListCell *jl;
3329 :
3330 : /*
3331 : * Count the number of child joinlist nodes. This is the depth of the
3332 : * dynamic-programming algorithm we must employ to consider all ways of
3333 : * joining the child nodes.
3334 : */
3335 339430 : levels_needed = list_length(joinlist);
3336 :
3337 339430 : if (levels_needed <= 0)
3338 0 : return NULL; /* nothing to do? */
3339 :
3340 : /*
3341 : * Construct a list of rels corresponding to the child joinlist nodes.
3342 : * This may contain both base rels and rels constructed according to
3343 : * sub-joinlists.
3344 : */
3345 339430 : initial_rels = NIL;
3346 871532 : foreach(jl, joinlist)
3347 : {
3348 532102 : Node *jlnode = (Node *) lfirst(jl);
3349 : RelOptInfo *thisrel;
3350 :
3351 532102 : if (IsA(jlnode, RangeTblRef))
3352 : {
3353 528772 : int varno = ((RangeTblRef *) jlnode)->rtindex;
3354 :
3355 528772 : thisrel = find_base_rel(root, varno);
3356 : }
3357 3330 : else if (IsA(jlnode, List))
3358 : {
3359 : /* Recurse to handle subproblem */
3360 3330 : thisrel = make_rel_from_joinlist(root, (List *) jlnode);
3361 : }
3362 : else
3363 : {
3364 0 : elog(ERROR, "unrecognized joinlist node type: %d",
3365 : (int) nodeTag(jlnode));
3366 : thisrel = NULL; /* keep compiler quiet */
3367 : }
3368 :
3369 532102 : initial_rels = lappend(initial_rels, thisrel);
3370 : }
3371 :
3372 339430 : if (levels_needed == 1)
3373 : {
3374 : /*
3375 : * Single joinlist node, so we're done.
3376 : */
3377 214528 : return (RelOptInfo *) linitial(initial_rels);
3378 : }
3379 : else
3380 : {
3381 : /*
3382 : * Consider the different orders in which we could join the rels,
3383 : * using a plugin, GEQO, or the regular join search code.
3384 : *
3385 : * We put the initial_rels list into a PlannerInfo field because
3386 : * has_legal_joinclause() needs to look at it (ugly :-().
3387 : */
3388 124902 : root->initial_rels = initial_rels;
3389 :
3390 124902 : if (join_search_hook)
3391 0 : return (*join_search_hook) (root, levels_needed, initial_rels);
3392 124902 : else if (enable_geqo && levels_needed >= geqo_threshold)
3393 6 : return geqo(root, levels_needed, initial_rels);
3394 : else
3395 124896 : return standard_join_search(root, levels_needed, initial_rels);
3396 : }
3397 : }
3398 :
3399 : /*
3400 : * standard_join_search
3401 : * Find possible joinpaths for a query by successively finding ways
3402 : * to join component relations into join relations.
3403 : *
3404 : * 'levels_needed' is the number of iterations needed, ie, the number of
3405 : * independent jointree items in the query. This is > 1.
3406 : *
3407 : * 'initial_rels' is a list of RelOptInfo nodes for each independent
3408 : * jointree item. These are the components to be joined together.
3409 : * Note that levels_needed == list_length(initial_rels).
3410 : *
3411 : * Returns the final level of join relations, i.e., the relation that is
3412 : * the result of joining all the original relations together.
3413 : * At least one implementation path must be provided for this relation and
3414 : * all required sub-relations.
3415 : *
3416 : * To support loadable plugins that modify planner behavior by changing the
3417 : * join searching algorithm, we provide a hook variable that lets a plugin
3418 : * replace or supplement this function. Any such hook must return the same
3419 : * final join relation as the standard code would, but it might have a
3420 : * different set of implementation paths attached, and only the sub-joinrels
3421 : * needed for these paths need have been instantiated.
3422 : *
3423 : * Note to plugin authors: the functions invoked during standard_join_search()
3424 : * modify root->join_rel_list and root->join_rel_hash. If you want to do more
3425 : * than one join-order search, you'll probably need to save and restore the
3426 : * original states of those data structures. See geqo_eval() for an example.
3427 : */
3428 : RelOptInfo *
3429 124896 : standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
3430 : {
3431 : int lev;
3432 : RelOptInfo *rel;
3433 :
3434 : /*
3435 : * This function cannot be invoked recursively within any one planning
3436 : * problem, so join_rel_level[] can't be in use already.
3437 : */
3438 : Assert(root->join_rel_level == NULL);
3439 :
3440 : /*
3441 : * We employ a simple "dynamic programming" algorithm: we first find all
3442 : * ways to build joins of two jointree items, then all ways to build joins
3443 : * of three items (from two-item joins and single items), then four-item
3444 : * joins, and so on until we have considered all ways to join all the
3445 : * items into one rel.
3446 : *
3447 : * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3448 : * set root->join_rel_level[1] to represent all the single-jointree-item
3449 : * relations.
3450 : */
3451 124896 : root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3452 :
3453 124896 : root->join_rel_level[1] = initial_rels;
3454 :
3455 317544 : for (lev = 2; lev <= levels_needed; lev++)
3456 : {
3457 : ListCell *lc;
3458 :
3459 : /*
3460 : * Determine all possible pairs of relations to be joined at this
3461 : * level, and build paths for making each one from every available
3462 : * pair of lower-level relations.
3463 : */
3464 192648 : join_search_one_level(root, lev);
3465 :
3466 : /*
3467 : * Run generate_partitionwise_join_paths() and
3468 : * generate_useful_gather_paths() for each just-processed joinrel. We
3469 : * could not do this earlier because both regular and partial paths
3470 : * can get added to a particular joinrel at multiple times within
3471 : * join_search_one_level.
3472 : *
3473 : * After that, we're done creating paths for the joinrel, so run
3474 : * set_cheapest().
3475 : */
3476 530448 : foreach(lc, root->join_rel_level[lev])
3477 : {
3478 337800 : rel = (RelOptInfo *) lfirst(lc);
3479 :
3480 : /* Create paths for partitionwise joins. */
3481 337800 : generate_partitionwise_join_paths(root, rel);
3482 :
3483 : /*
3484 : * Except for the topmost scan/join rel, consider gathering
3485 : * partial paths. We'll do the same for the topmost scan/join rel
3486 : * once we know the final targetlist (see grouping_planner's and
3487 : * its call to apply_scanjoin_target_to_paths).
3488 : */
3489 337800 : if (!bms_equal(rel->relids, root->all_query_rels))
3490 213384 : generate_useful_gather_paths(root, rel, false);
3491 :
3492 : /* Find and save the cheapest paths for this rel */
3493 337800 : set_cheapest(rel);
3494 :
3495 : #ifdef OPTIMIZER_DEBUG
3496 : pprint(rel);
3497 : #endif
3498 : }
3499 : }
3500 :
3501 : /*
3502 : * We should have a single rel at the final level.
3503 : */
3504 124896 : if (root->join_rel_level[levels_needed] == NIL)
3505 0 : elog(ERROR, "failed to build any %d-way joins", levels_needed);
3506 : Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3507 :
3508 124896 : rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3509 :
3510 124896 : root->join_rel_level = NULL;
3511 :
3512 124896 : return rel;
3513 : }
3514 :
3515 : /*****************************************************************************
3516 : * PUSHING QUALS DOWN INTO SUBQUERIES
3517 : *****************************************************************************/
3518 :
3519 : /*
3520 : * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
3521 : *
3522 : * subquery is the particular component query being checked. topquery
3523 : * is the top component of a set-operations tree (the same Query if no
3524 : * set-op is involved).
3525 : *
3526 : * Conditions checked here:
3527 : *
3528 : * 1. If the subquery has a LIMIT clause, we must not push down any quals,
3529 : * since that could change the set of rows returned.
3530 : *
3531 : * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
3532 : * quals into it, because that could change the results.
3533 : *
3534 : * 3. If the subquery uses DISTINCT, we cannot push volatile quals into it.
3535 : * This is because upper-level quals should semantically be evaluated only
3536 : * once per distinct row, not once per original row, and if the qual is
3537 : * volatile then extra evaluations could change the results. (This issue
3538 : * does not apply to other forms of aggregation such as GROUP BY, because
3539 : * when those are present we push into HAVING not WHERE, so that the quals
3540 : * are still applied after aggregation.)
3541 : *
3542 : * 4. If the subquery contains window functions, we cannot push volatile quals
3543 : * into it. The issue here is a bit different from DISTINCT: a volatile qual
3544 : * might succeed for some rows of a window partition and fail for others,
3545 : * thereby changing the partition contents and thus the window functions'
3546 : * results for rows that remain.
3547 : *
3548 : * 5. If the subquery contains any set-returning functions in its targetlist,
3549 : * we cannot push volatile quals into it. That would push them below the SRFs
3550 : * and thereby change the number of times they are evaluated. Also, a
3551 : * volatile qual could succeed for some SRF output rows and fail for others,
3552 : * a behavior that cannot occur if it's evaluated before SRF expansion.
3553 : *
3554 : * 6. If the subquery has nonempty grouping sets, we cannot push down any
3555 : * quals. The concern here is that a qual referencing a "constant" grouping
3556 : * column could get constant-folded, which would be improper because the value
3557 : * is potentially nullable by grouping-set expansion. This restriction could
3558 : * be removed if we had a parsetree representation that shows that such
3559 : * grouping columns are not really constant. (There are other ideas that
3560 : * could be used to relax this restriction, but that's the approach most
3561 : * likely to get taken in the future. Note that there's not much to be gained
3562 : * so long as subquery_planner can't move HAVING clauses to WHERE within such
3563 : * a subquery.)
3564 : *
3565 : * In addition, we make several checks on the subquery's output columns to see
3566 : * if it is safe to reference them in pushed-down quals. If output column k
3567 : * is found to be unsafe to reference, we set the reason for that inside
3568 : * safetyInfo->unsafeFlags[k], but we don't reject the subquery overall since
3569 : * column k might not be referenced by some/all quals. The unsafeFlags[]
3570 : * array will be consulted later by qual_is_pushdown_safe(). It's better to
3571 : * do it this way than to make the checks directly in qual_is_pushdown_safe(),
3572 : * because when the subquery involves set operations we have to check the
3573 : * output expressions in each arm of the set op.
3574 : *
3575 : * Note: pushing quals into a DISTINCT subquery is theoretically dubious:
3576 : * we're effectively assuming that the quals cannot distinguish values that
3577 : * the DISTINCT's equality operator sees as equal, yet there are many
3578 : * counterexamples to that assumption. However use of such a qual with a
3579 : * DISTINCT subquery would be unsafe anyway, since there's no guarantee which
3580 : * "equal" value will be chosen as the output value by the DISTINCT operation.
3581 : * So we don't worry too much about that. Another objection is that if the
3582 : * qual is expensive to evaluate, running it for each original row might cost
3583 : * more than we save by eliminating rows before the DISTINCT step. But it
3584 : * would be very hard to estimate that at this stage, and in practice pushdown
3585 : * seldom seems to make things worse, so we ignore that problem too.
3586 : *
3587 : * Note: likewise, pushing quals into a subquery with window functions is a
3588 : * bit dubious: the quals might remove some rows of a window partition while
3589 : * leaving others, causing changes in the window functions' results for the
3590 : * surviving rows. We insist that such a qual reference only partitioning
3591 : * columns, but again that only protects us if the qual does not distinguish
3592 : * values that the partitioning equality operator sees as equal. The risks
3593 : * here are perhaps larger than for DISTINCT, since no de-duplication of rows
3594 : * occurs and thus there is no theoretical problem with such a qual. But
3595 : * we'll do this anyway because the potential performance benefits are very
3596 : * large, and we've seen no field complaints about the longstanding comparable
3597 : * behavior with DISTINCT.
3598 : */
3599 : static bool
3600 13672 : subquery_is_pushdown_safe(Query *subquery, Query *topquery,
3601 : pushdown_safety_info *safetyInfo)
3602 : {
3603 : SetOperationStmt *topop;
3604 :
3605 : /* Check point 1 */
3606 13672 : if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
3607 134 : return false;
3608 :
3609 : /* Check point 6 */
3610 13538 : if (subquery->groupClause && subquery->groupingSets)
3611 12 : return false;
3612 :
3613 : /* Check points 3, 4, and 5 */
3614 13526 : if (subquery->distinctClause ||
3615 13442 : subquery->hasWindowFuncs ||
3616 13172 : subquery->hasTargetSRFs)
3617 544 : safetyInfo->unsafeVolatile = true;
3618 :
3619 : /*
3620 : * If we're at a leaf query, check for unsafe expressions in its target
3621 : * list, and mark any reasons why they're unsafe in unsafeFlags[].
3622 : * (Non-leaf nodes in setop trees have only simple Vars in their tlists,
3623 : * so no need to check them.)
3624 : */
3625 13526 : if (subquery->setOperations == NULL)
3626 13434 : check_output_expressions(subquery, safetyInfo);
3627 :
3628 : /* Are we at top level, or looking at a setop component? */
3629 13526 : if (subquery == topquery)
3630 : {
3631 : /* Top level, so check any component queries */
3632 13342 : if (subquery->setOperations != NULL)
3633 92 : if (!recurse_pushdown_safe(subquery->setOperations, topquery,
3634 : safetyInfo))
3635 0 : return false;
3636 : }
3637 : else
3638 : {
3639 : /* Setop component must not have more components (too weird) */
3640 184 : if (subquery->setOperations != NULL)
3641 0 : return false;
3642 : /* Check whether setop component output types match top level */
3643 184 : topop = castNode(SetOperationStmt, topquery->setOperations);
3644 : Assert(topop);
3645 184 : compare_tlist_datatypes(subquery->targetList,
3646 : topop->colTypes,
3647 : safetyInfo);
3648 : }
3649 13526 : return true;
3650 : }
3651 :
3652 : /*
3653 : * Helper routine to recurse through setOperations tree
3654 : */
3655 : static bool
3656 276 : recurse_pushdown_safe(Node *setOp, Query *topquery,
3657 : pushdown_safety_info *safetyInfo)
3658 : {
3659 276 : if (IsA(setOp, RangeTblRef))
3660 : {
3661 184 : RangeTblRef *rtr = (RangeTblRef *) setOp;
3662 184 : RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
3663 184 : Query *subquery = rte->subquery;
3664 :
3665 : Assert(subquery != NULL);
3666 184 : return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
3667 : }
3668 92 : else if (IsA(setOp, SetOperationStmt))
3669 : {
3670 92 : SetOperationStmt *op = (SetOperationStmt *) setOp;
3671 :
3672 : /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
3673 92 : if (op->op == SETOP_EXCEPT)
3674 0 : return false;
3675 : /* Else recurse */
3676 92 : if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
3677 0 : return false;
3678 92 : if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
3679 0 : return false;
3680 : }
3681 : else
3682 : {
3683 0 : elog(ERROR, "unrecognized node type: %d",
3684 : (int) nodeTag(setOp));
3685 : }
3686 92 : return true;
3687 : }
3688 :
3689 : /*
3690 : * check_output_expressions - check subquery's output expressions for safety
3691 : *
3692 : * There are several cases in which it's unsafe to push down an upper-level
3693 : * qual if it references a particular output column of a subquery. We check
3694 : * each output column of the subquery and set flags in unsafeFlags[k] when we
3695 : * see that column is unsafe for a pushed-down qual to reference. The
3696 : * conditions checked here are:
3697 : *
3698 : * 1. We must not push down any quals that refer to subselect outputs that
3699 : * return sets, else we'd introduce functions-returning-sets into the
3700 : * subquery's WHERE/HAVING quals.
3701 : *
3702 : * 2. We must not push down any quals that refer to subselect outputs that
3703 : * contain volatile functions, for fear of introducing strange results due
3704 : * to multiple evaluation of a volatile function.
3705 : *
3706 : * 3. If the subquery uses DISTINCT ON, we must not push down any quals that
3707 : * refer to non-DISTINCT output columns, because that could change the set
3708 : * of rows returned. (This condition is vacuous for DISTINCT, because then
3709 : * there are no non-DISTINCT output columns, so we needn't check. Note that
3710 : * subquery_is_pushdown_safe already reported that we can't use volatile
3711 : * quals if there's DISTINCT or DISTINCT ON.)
3712 : *
3713 : * 4. If the subquery has any window functions, we must not push down quals
3714 : * that reference any output columns that are not listed in all the subquery's
3715 : * window PARTITION BY clauses. We can push down quals that use only
3716 : * partitioning columns because they should succeed or fail identically for
3717 : * every row of any one window partition, and totally excluding some
3718 : * partitions will not change a window function's results for remaining
3719 : * partitions. (Again, this also requires nonvolatile quals, but
3720 : * subquery_is_pushdown_safe handles that.). Subquery columns marked as
3721 : * unsafe for this reason can still have WindowClause run conditions pushed
3722 : * down.
3723 : */
3724 : static void
3725 13434 : check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
3726 : {
3727 : ListCell *lc;
3728 :
3729 227878 : foreach(lc, subquery->targetList)
3730 : {
3731 214444 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
3732 :
3733 214444 : if (tle->resjunk)
3734 150 : continue; /* ignore resjunk columns */
3735 :
3736 : /* Functions returning sets are unsafe (point 1) */
3737 214294 : if (subquery->hasTargetSRFs &&
3738 614 : (safetyInfo->unsafeFlags[tle->resno] &
3739 614 : UNSAFE_HAS_SET_FUNC) == 0 &&
3740 614 : expression_returns_set((Node *) tle->expr))
3741 : {
3742 352 : safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_SET_FUNC;
3743 352 : continue;
3744 : }
3745 :
3746 : /* Volatile functions are unsafe (point 2) */
3747 213942 : if ((safetyInfo->unsafeFlags[tle->resno] &
3748 213930 : UNSAFE_HAS_VOLATILE_FUNC) == 0 &&
3749 213930 : contain_volatile_functions((Node *) tle->expr))
3750 : {
3751 78 : safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_VOLATILE_FUNC;
3752 78 : continue;
3753 : }
3754 :
3755 : /* If subquery uses DISTINCT ON, check point 3 */
3756 213864 : if (subquery->hasDistinctOn &&
3757 0 : (safetyInfo->unsafeFlags[tle->resno] &
3758 0 : UNSAFE_NOTIN_DISTINCTON_CLAUSE) == 0 &&
3759 0 : !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
3760 : {
3761 : /* non-DISTINCT column, so mark it unsafe */
3762 0 : safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_DISTINCTON_CLAUSE;
3763 0 : continue;
3764 : }
3765 :
3766 : /* If subquery uses window functions, check point 4 */
3767 213864 : if (subquery->hasWindowFuncs &&
3768 1158 : (safetyInfo->unsafeFlags[tle->resno] &
3769 1158 : UNSAFE_NOTIN_DISTINCTON_CLAUSE) == 0 &&
3770 1158 : !targetIsInAllPartitionLists(tle, subquery))
3771 : {
3772 : /* not present in all PARTITION BY clauses, so mark it unsafe */
3773 1062 : safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_PARTITIONBY_CLAUSE;
3774 1062 : continue;
3775 : }
3776 : }
3777 13434 : }
3778 :
3779 : /*
3780 : * For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
3781 : * push quals into each component query, but the quals can only reference
3782 : * subquery columns that suffer no type coercions in the set operation.
3783 : * Otherwise there are possible semantic gotchas. So, we check the
3784 : * component queries to see if any of them have output types different from
3785 : * the top-level setop outputs. We set the UNSAFE_TYPE_MISMATCH bit in
3786 : * unsafeFlags[k] if column k has different type in any component.
3787 : *
3788 : * We don't have to care about typmods here: the only allowed difference
3789 : * between set-op input and output typmods is input is a specific typmod
3790 : * and output is -1, and that does not require a coercion.
3791 : *
3792 : * tlist is a subquery tlist.
3793 : * colTypes is an OID list of the top-level setop's output column types.
3794 : * safetyInfo is the pushdown_safety_info to set unsafeFlags[] for.
3795 : */
3796 : static void
3797 184 : compare_tlist_datatypes(List *tlist, List *colTypes,
3798 : pushdown_safety_info *safetyInfo)
3799 : {
3800 : ListCell *l;
3801 184 : ListCell *colType = list_head(colTypes);
3802 :
3803 600 : foreach(l, tlist)
3804 : {
3805 416 : TargetEntry *tle = (TargetEntry *) lfirst(l);
3806 :
3807 416 : if (tle->resjunk)
3808 0 : continue; /* ignore resjunk columns */
3809 416 : if (colType == NULL)
3810 0 : elog(ERROR, "wrong number of tlist entries");
3811 416 : if (exprType((Node *) tle->expr) != lfirst_oid(colType))
3812 40 : safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_TYPE_MISMATCH;
3813 416 : colType = lnext(colTypes, colType);
3814 : }
3815 184 : if (colType != NULL)
3816 0 : elog(ERROR, "wrong number of tlist entries");
3817 184 : }
3818 :
3819 : /*
3820 : * targetIsInAllPartitionLists
3821 : * True if the TargetEntry is listed in the PARTITION BY clause
3822 : * of every window defined in the query.
3823 : *
3824 : * It would be safe to ignore windows not actually used by any window
3825 : * function, but it's not easy to get that info at this stage; and it's
3826 : * unlikely to be useful to spend any extra cycles getting it, since
3827 : * unreferenced window definitions are probably infrequent in practice.
3828 : */
3829 : static bool
3830 1158 : targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
3831 : {
3832 : ListCell *lc;
3833 :
3834 1278 : foreach(lc, query->windowClause)
3835 : {
3836 1182 : WindowClause *wc = (WindowClause *) lfirst(lc);
3837 :
3838 1182 : if (!targetIsInSortList(tle, InvalidOid, wc->partitionClause))
3839 1062 : return false;
3840 : }
3841 96 : return true;
3842 : }
3843 :
3844 : /*
3845 : * qual_is_pushdown_safe - is a particular rinfo safe to push down?
3846 : *
3847 : * rinfo is a restriction clause applying to the given subquery (whose RTE
3848 : * has index rti in the parent query).
3849 : *
3850 : * Conditions checked here:
3851 : *
3852 : * 1. rinfo's clause must not contain any SubPlans (mainly because it's
3853 : * unclear that it will work correctly: SubLinks will already have been
3854 : * transformed into SubPlans in the qual, but not in the subquery). Note that
3855 : * SubLinks that transform to initplans are safe, and will be accepted here
3856 : * because what we'll see in the qual is just a Param referencing the initplan
3857 : * output.
3858 : *
3859 : * 2. If unsafeVolatile is set, rinfo's clause must not contain any volatile
3860 : * functions.
3861 : *
3862 : * 3. If unsafeLeaky is set, rinfo's clause must not contain any leaky
3863 : * functions that are passed Var nodes, and therefore might reveal values from
3864 : * the subquery as side effects.
3865 : *
3866 : * 4. rinfo's clause must not refer to the whole-row output of the subquery
3867 : * (since there is no easy way to name that within the subquery itself).
3868 : *
3869 : * 5. rinfo's clause must not refer to any subquery output columns that were
3870 : * found to be unsafe to reference by subquery_is_pushdown_safe().
3871 : */
3872 : static pushdown_safe_type
3873 26140 : qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo,
3874 : pushdown_safety_info *safetyInfo)
3875 : {
3876 26140 : pushdown_safe_type safe = PUSHDOWN_SAFE;
3877 26140 : Node *qual = (Node *) rinfo->clause;
3878 : List *vars;
3879 : ListCell *vl;
3880 :
3881 : /* Refuse subselects (point 1) */
3882 26140 : if (contain_subplans(qual))
3883 66 : return PUSHDOWN_UNSAFE;
3884 :
3885 : /* Refuse volatile quals if we found they'd be unsafe (point 2) */
3886 26718 : if (safetyInfo->unsafeVolatile &&
3887 644 : contain_volatile_functions((Node *) rinfo))
3888 18 : return PUSHDOWN_UNSAFE;
3889 :
3890 : /* Refuse leaky quals if told to (point 3) */
3891 50788 : if (safetyInfo->unsafeLeaky &&
3892 24732 : contain_leaked_vars(qual))
3893 144 : return PUSHDOWN_UNSAFE;
3894 :
3895 : /*
3896 : * Examine all Vars used in clause. Since it's a restriction clause, all
3897 : * such Vars must refer to subselect output columns ... unless this is
3898 : * part of a LATERAL subquery, in which case there could be lateral
3899 : * references.
3900 : *
3901 : * By omitting the relevant flags, this also gives us a cheap sanity check
3902 : * that no aggregates or window functions appear in the qual. Those would
3903 : * be unsafe to push down, but at least for the moment we could never see
3904 : * any in a qual anyhow.
3905 : */
3906 25912 : vars = pull_var_clause(qual, PVC_INCLUDE_PLACEHOLDERS);
3907 51730 : foreach(vl, vars)
3908 : {
3909 26020 : Var *var = (Var *) lfirst(vl);
3910 :
3911 : /*
3912 : * XXX Punt if we find any PlaceHolderVars in the restriction clause.
3913 : * It's not clear whether a PHV could safely be pushed down, and even
3914 : * less clear whether such a situation could arise in any cases of
3915 : * practical interest anyway. So for the moment, just refuse to push
3916 : * down.
3917 : */
3918 26020 : if (!IsA(var, Var))
3919 : {
3920 0 : safe = PUSHDOWN_UNSAFE;
3921 0 : break;
3922 : }
3923 :
3924 : /*
3925 : * Punt if we find any lateral references. It would be safe to push
3926 : * these down, but we'd have to convert them into outer references,
3927 : * which subquery_push_qual lacks the infrastructure to do. The case
3928 : * arises so seldom that it doesn't seem worth working hard on.
3929 : */
3930 26020 : if (var->varno != rti)
3931 : {
3932 12 : safe = PUSHDOWN_UNSAFE;
3933 12 : break;
3934 : }
3935 :
3936 : /* Subqueries have no system columns */
3937 : Assert(var->varattno >= 0);
3938 :
3939 : /* Check point 4 */
3940 26008 : if (var->varattno == 0)
3941 : {
3942 0 : safe = PUSHDOWN_UNSAFE;
3943 0 : break;
3944 : }
3945 :
3946 : /* Check point 5 */
3947 26008 : if (safetyInfo->unsafeFlags[var->varattno] != 0)
3948 : {
3949 520 : if (safetyInfo->unsafeFlags[var->varattno] &
3950 : (UNSAFE_HAS_VOLATILE_FUNC | UNSAFE_HAS_SET_FUNC |
3951 : UNSAFE_NOTIN_DISTINCTON_CLAUSE | UNSAFE_TYPE_MISMATCH))
3952 : {
3953 190 : safe = PUSHDOWN_UNSAFE;
3954 190 : break;
3955 : }
3956 : else
3957 : {
3958 : /* UNSAFE_NOTIN_PARTITIONBY_CLAUSE is ok for run conditions */
3959 330 : safe = PUSHDOWN_WINDOWCLAUSE_RUNCOND;
3960 : /* don't break, we might find another Var that's unsafe */
3961 : }
3962 : }
3963 : }
3964 :
3965 25912 : list_free(vars);
3966 :
3967 25912 : return safe;
3968 : }
3969 :
3970 : /*
3971 : * subquery_push_qual - push down a qual that we have determined is safe
3972 : */
3973 : static void
3974 25594 : subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
3975 : {
3976 25594 : if (subquery->setOperations != NULL)
3977 : {
3978 : /* Recurse to push it separately to each component query */
3979 68 : recurse_push_qual(subquery->setOperations, subquery,
3980 : rte, rti, qual);
3981 : }
3982 : else
3983 : {
3984 : /*
3985 : * We need to replace Vars in the qual (which must refer to outputs of
3986 : * the subquery) with copies of the subquery's targetlist expressions.
3987 : * Note that at this point, any uplevel Vars in the qual should have
3988 : * been replaced with Params, so they need no work.
3989 : *
3990 : * This step also ensures that when we are pushing into a setop tree,
3991 : * each component query gets its own copy of the qual.
3992 : */
3993 25526 : qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
3994 : subquery->targetList,
3995 : subquery->resultRelation,
3996 : REPLACEVARS_REPORT_ERROR, 0,
3997 : &subquery->hasSubLinks);
3998 :
3999 : /*
4000 : * Now attach the qual to the proper place: normally WHERE, but if the
4001 : * subquery uses grouping or aggregation, put it in HAVING (since the
4002 : * qual really refers to the group-result rows).
4003 : */
4004 25526 : if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
4005 270 : subquery->havingQual = make_and_qual(subquery->havingQual, qual);
4006 : else
4007 25256 : subquery->jointree->quals =
4008 25256 : make_and_qual(subquery->jointree->quals, qual);
4009 :
4010 : /*
4011 : * We need not change the subquery's hasAggs or hasSubLinks flags,
4012 : * since we can't be pushing down any aggregates that weren't there
4013 : * before, and we don't push down subselects at all.
4014 : */
4015 : }
4016 25594 : }
4017 :
4018 : /*
4019 : * Helper routine to recurse through setOperations tree
4020 : */
4021 : static void
4022 204 : recurse_push_qual(Node *setOp, Query *topquery,
4023 : RangeTblEntry *rte, Index rti, Node *qual)
4024 : {
4025 204 : if (IsA(setOp, RangeTblRef))
4026 : {
4027 136 : RangeTblRef *rtr = (RangeTblRef *) setOp;
4028 136 : RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
4029 136 : Query *subquery = subrte->subquery;
4030 :
4031 : Assert(subquery != NULL);
4032 136 : subquery_push_qual(subquery, rte, rti, qual);
4033 : }
4034 68 : else if (IsA(setOp, SetOperationStmt))
4035 : {
4036 68 : SetOperationStmt *op = (SetOperationStmt *) setOp;
4037 :
4038 68 : recurse_push_qual(op->larg, topquery, rte, rti, qual);
4039 68 : recurse_push_qual(op->rarg, topquery, rte, rti, qual);
4040 : }
4041 : else
4042 : {
4043 0 : elog(ERROR, "unrecognized node type: %d",
4044 : (int) nodeTag(setOp));
4045 : }
4046 204 : }
4047 :
4048 : /*****************************************************************************
4049 : * SIMPLIFYING SUBQUERY TARGETLISTS
4050 : *****************************************************************************/
4051 :
4052 : /*
4053 : * remove_unused_subquery_outputs
4054 : * Remove subquery targetlist items we don't need
4055 : *
4056 : * It's possible, even likely, that the upper query does not read all the
4057 : * output columns of the subquery. We can remove any such outputs that are
4058 : * not needed by the subquery itself (e.g., as sort/group columns) and do not
4059 : * affect semantics otherwise (e.g., volatile functions can't be removed).
4060 : * This is useful not only because we might be able to remove expensive-to-
4061 : * compute expressions, but because deletion of output columns might allow
4062 : * optimizations such as join removal to occur within the subquery.
4063 : *
4064 : * extra_used_attrs can be passed as non-NULL to mark any columns (offset by
4065 : * FirstLowInvalidHeapAttributeNumber) that we should not remove. This
4066 : * parameter is modified by the function, so callers must make a copy if they
4067 : * need to use the passed in Bitmapset after calling this function.
4068 : *
4069 : * To avoid affecting column numbering in the targetlist, we don't physically
4070 : * remove unused tlist entries, but rather replace their expressions with NULL
4071 : * constants. This is implemented by modifying subquery->targetList.
4072 : */
4073 : static void
4074 20250 : remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel,
4075 : Bitmapset *extra_used_attrs)
4076 : {
4077 : Bitmapset *attrs_used;
4078 : ListCell *lc;
4079 :
4080 : /*
4081 : * Just point directly to extra_used_attrs. No need to bms_copy as none of
4082 : * the current callers use the Bitmapset after calling this function.
4083 : */
4084 20250 : attrs_used = extra_used_attrs;
4085 :
4086 : /*
4087 : * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4088 : * could update all the child SELECTs' tlists, but it seems not worth the
4089 : * trouble presently.
4090 : */
4091 20250 : if (subquery->setOperations)
4092 1130 : return;
4093 :
4094 : /*
4095 : * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4096 : * time: all its output columns must be used in the distinctClause.
4097 : */
4098 19646 : if (subquery->distinctClause && !subquery->hasDistinctOn)
4099 246 : return;
4100 :
4101 : /*
4102 : * Collect a bitmap of all the output column numbers used by the upper
4103 : * query.
4104 : *
4105 : * Add all the attributes needed for joins or final output. Note: we must
4106 : * look at rel's targetlist, not the attr_needed data, because attr_needed
4107 : * isn't computed for inheritance child rels, cf set_append_rel_size().
4108 : * (XXX might be worth changing that sometime.)
4109 : */
4110 19400 : pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4111 :
4112 : /* Add all the attributes used by un-pushed-down restriction clauses. */
4113 20112 : foreach(lc, rel->baserestrictinfo)
4114 : {
4115 712 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4116 :
4117 712 : pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4118 : }
4119 :
4120 : /*
4121 : * If there's a whole-row reference to the subquery, we can't remove
4122 : * anything.
4123 : */
4124 19400 : if (bms_is_member(0 - FirstLowInvalidHeapAttributeNumber, attrs_used))
4125 280 : return;
4126 :
4127 : /*
4128 : * Run through the tlist and zap entries we don't need. It's okay to
4129 : * modify the tlist items in-place because set_subquery_pathlist made a
4130 : * copy of the subquery.
4131 : */
4132 248056 : foreach(lc, subquery->targetList)
4133 : {
4134 228936 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
4135 228936 : Node *texpr = (Node *) tle->expr;
4136 :
4137 : /*
4138 : * If it has a sortgroupref number, it's used in some sort/group
4139 : * clause so we'd better not remove it. Also, don't remove any
4140 : * resjunk columns, since their reason for being has nothing to do
4141 : * with anybody reading the subquery's output. (It's likely that
4142 : * resjunk columns in a sub-SELECT would always have ressortgroupref
4143 : * set, but even if they don't, it seems imprudent to remove them.)
4144 : */
4145 228936 : if (tle->ressortgroupref || tle->resjunk)
4146 2560 : continue;
4147 :
4148 : /*
4149 : * If it's used by the upper query, we can't remove it.
4150 : */
4151 226376 : if (bms_is_member(tle->resno - FirstLowInvalidHeapAttributeNumber,
4152 : attrs_used))
4153 218848 : continue;
4154 :
4155 : /*
4156 : * If it contains a set-returning function, we can't remove it since
4157 : * that could change the number of rows returned by the subquery.
4158 : */
4159 8508 : if (subquery->hasTargetSRFs &&
4160 980 : expression_returns_set(texpr))
4161 724 : continue;
4162 :
4163 : /*
4164 : * If it contains volatile functions, we daren't remove it for fear
4165 : * that the user is expecting their side-effects to happen.
4166 : */
4167 6804 : if (contain_volatile_functions(texpr))
4168 26 : continue;
4169 :
4170 : /*
4171 : * OK, we don't need it. Replace the expression with a NULL constant.
4172 : * Preserve the exposed type of the expression, in case something
4173 : * looks at the rowtype of the subquery's result.
4174 : */
4175 6778 : tle->expr = (Expr *) makeNullConst(exprType(texpr),
4176 : exprTypmod(texpr),
4177 : exprCollation(texpr));
4178 : }
4179 : }
4180 :
4181 : /*
4182 : * create_partial_bitmap_paths
4183 : * Build partial bitmap heap path for the relation
4184 : */
4185 : void
4186 204400 : create_partial_bitmap_paths(PlannerInfo *root, RelOptInfo *rel,
4187 : Path *bitmapqual)
4188 : {
4189 : int parallel_workers;
4190 : double pages_fetched;
4191 :
4192 : /* Compute heap pages for bitmap heap scan */
4193 204400 : pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4194 : NULL, NULL);
4195 :
4196 204400 : parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4197 : max_parallel_workers_per_gather);
4198 :
4199 204400 : if (parallel_workers <= 0)
4200 200220 : return;
4201 :
4202 4180 : add_partial_path(rel, (Path *) create_bitmap_heap_path(root, rel,
4203 : bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4204 : }
4205 :
4206 : /*
4207 : * Compute the number of parallel workers that should be used to scan a
4208 : * relation. We compute the parallel workers based on the size of the heap to
4209 : * be scanned and the size of the index to be scanned, then choose a minimum
4210 : * of those.
4211 : *
4212 : * "heap_pages" is the number of pages from the table that we expect to scan, or
4213 : * -1 if we don't expect to scan any.
4214 : *
4215 : * "index_pages" is the number of pages from the index that we expect to scan, or
4216 : * -1 if we don't expect to scan any.
4217 : *
4218 : * "max_workers" is caller's limit on the number of workers. This typically
4219 : * comes from a GUC.
4220 : */
4221 : int
4222 1000266 : compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages,
4223 : int max_workers)
4224 : {
4225 1000266 : int parallel_workers = 0;
4226 :
4227 : /*
4228 : * If the user has set the parallel_workers reloption, use that; otherwise
4229 : * select a default number of workers.
4230 : */
4231 1000266 : if (rel->rel_parallel_workers != -1)
4232 1914 : parallel_workers = rel->rel_parallel_workers;
4233 : else
4234 : {
4235 : /*
4236 : * If the number of pages being scanned is insufficient to justify a
4237 : * parallel scan, just return zero ... unless it's an inheritance
4238 : * child. In that case, we want to generate a parallel path here
4239 : * anyway. It might not be worthwhile just for this relation, but
4240 : * when combined with all of its inheritance siblings it may well pay
4241 : * off.
4242 : */
4243 998352 : if (rel->reloptkind == RELOPT_BASEREL &&
4244 960282 : ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
4245 20294 : (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
4246 959570 : return 0;
4247 :
4248 38782 : if (heap_pages >= 0)
4249 : {
4250 : int heap_parallel_threshold;
4251 36696 : int heap_parallel_workers = 1;
4252 :
4253 : /*
4254 : * Select the number of workers based on the log of the size of
4255 : * the relation. This probably needs to be a good deal more
4256 : * sophisticated, but we need something here for now. Note that
4257 : * the upper limit of the min_parallel_table_scan_size GUC is
4258 : * chosen to prevent overflow here.
4259 : */
4260 36696 : heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
4261 41566 : while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
4262 : {
4263 4870 : heap_parallel_workers++;
4264 4870 : heap_parallel_threshold *= 3;
4265 4870 : if (heap_parallel_threshold > INT_MAX / 3)
4266 0 : break; /* avoid overflow */
4267 : }
4268 :
4269 36696 : parallel_workers = heap_parallel_workers;
4270 : }
4271 :
4272 38782 : if (index_pages >= 0)
4273 : {
4274 9676 : int index_parallel_workers = 1;
4275 : int index_parallel_threshold;
4276 :
4277 : /* same calculation as for heap_pages above */
4278 9676 : index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
4279 9952 : while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
4280 : {
4281 276 : index_parallel_workers++;
4282 276 : index_parallel_threshold *= 3;
4283 276 : if (index_parallel_threshold > INT_MAX / 3)
4284 0 : break; /* avoid overflow */
4285 : }
4286 :
4287 9676 : if (parallel_workers > 0)
4288 7590 : parallel_workers = Min(parallel_workers, index_parallel_workers);
4289 : else
4290 2086 : parallel_workers = index_parallel_workers;
4291 : }
4292 : }
4293 :
4294 : /* In no case use more than caller supplied maximum number of workers */
4295 40696 : parallel_workers = Min(parallel_workers, max_workers);
4296 :
4297 40696 : return parallel_workers;
4298 : }
4299 :
4300 : /*
4301 : * generate_partitionwise_join_paths
4302 : * Create paths representing partitionwise join for given partitioned
4303 : * join relation.
4304 : *
4305 : * This must not be called until after we are done adding paths for all
4306 : * child-joins. Otherwise, add_path might delete a path to which some path
4307 : * generated here has a reference.
4308 : */
4309 : void
4310 345610 : generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
4311 : {
4312 345610 : List *live_children = NIL;
4313 : int cnt_parts;
4314 : int num_parts;
4315 : RelOptInfo **part_rels;
4316 :
4317 : /* Handle only join relations here. */
4318 345610 : if (!IS_JOIN_REL(rel))
4319 0 : return;
4320 :
4321 : /* We've nothing to do if the relation is not partitioned. */
4322 345610 : if (!IS_PARTITIONED_REL(rel))
4323 343870 : return;
4324 :
4325 : /* The relation should have consider_partitionwise_join set. */
4326 : Assert(rel->consider_partitionwise_join);
4327 :
4328 : /* Guard against stack overflow due to overly deep partition hierarchy. */
4329 1740 : check_stack_depth();
4330 :
4331 1740 : num_parts = rel->nparts;
4332 1740 : part_rels = rel->part_rels;
4333 :
4334 : /* Collect non-dummy child-joins. */
4335 6506 : for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4336 : {
4337 4766 : RelOptInfo *child_rel = part_rels[cnt_parts];
4338 :
4339 : /* If it's been pruned entirely, it's certainly dummy. */
4340 4766 : if (child_rel == NULL)
4341 52 : continue;
4342 :
4343 : /* Make partitionwise join paths for this partitioned child-join. */
4344 4714 : generate_partitionwise_join_paths(root, child_rel);
4345 :
4346 : /* If we failed to make any path for this child, we must give up. */
4347 4714 : if (child_rel->pathlist == NIL)
4348 : {
4349 : /*
4350 : * Mark the parent joinrel as unpartitioned so that later
4351 : * functions treat it correctly.
4352 : */
4353 0 : rel->nparts = 0;
4354 0 : return;
4355 : }
4356 :
4357 : /* Else, identify the cheapest path for it. */
4358 4714 : set_cheapest(child_rel);
4359 :
4360 : /* Dummy children need not be scanned, so ignore those. */
4361 4714 : if (IS_DUMMY_REL(child_rel))
4362 0 : continue;
4363 :
4364 : #ifdef OPTIMIZER_DEBUG
4365 : pprint(child_rel);
4366 : #endif
4367 :
4368 4714 : live_children = lappend(live_children, child_rel);
4369 : }
4370 :
4371 : /* If all child-joins are dummy, parent join is also dummy. */
4372 1740 : if (!live_children)
4373 : {
4374 0 : mark_dummy_rel(rel);
4375 0 : return;
4376 : }
4377 :
4378 : /* Build additional paths for this rel from child-join paths. */
4379 1740 : add_paths_to_append_rel(root, rel, live_children);
4380 1740 : list_free(live_children);
4381 : }
|