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