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