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