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