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