Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * planner.c
4 : * The query optimizer external interface.
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/plan/planner.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 :
16 : #include "postgres.h"
17 :
18 : #include <limits.h>
19 : #include <math.h>
20 :
21 : #include "access/genam.h"
22 : #include "access/parallel.h"
23 : #include "access/sysattr.h"
24 : #include "access/table.h"
25 : #include "catalog/pg_aggregate.h"
26 : #include "catalog/pg_inherits.h"
27 : #include "catalog/pg_proc.h"
28 : #include "catalog/pg_type.h"
29 : #include "executor/executor.h"
30 : #include "foreign/fdwapi.h"
31 : #include "jit/jit.h"
32 : #include "lib/bipartite_match.h"
33 : #include "lib/knapsack.h"
34 : #include "miscadmin.h"
35 : #include "nodes/makefuncs.h"
36 : #include "nodes/nodeFuncs.h"
37 : #ifdef OPTIMIZER_DEBUG
38 : #include "nodes/print.h"
39 : #endif
40 : #include "nodes/supportnodes.h"
41 : #include "optimizer/appendinfo.h"
42 : #include "optimizer/clauses.h"
43 : #include "optimizer/cost.h"
44 : #include "optimizer/optimizer.h"
45 : #include "optimizer/paramassign.h"
46 : #include "optimizer/pathnode.h"
47 : #include "optimizer/paths.h"
48 : #include "optimizer/plancat.h"
49 : #include "optimizer/planmain.h"
50 : #include "optimizer/planner.h"
51 : #include "optimizer/prep.h"
52 : #include "optimizer/subselect.h"
53 : #include "optimizer/tlist.h"
54 : #include "parser/analyze.h"
55 : #include "parser/parse_agg.h"
56 : #include "parser/parse_clause.h"
57 : #include "parser/parse_relation.h"
58 : #include "parser/parsetree.h"
59 : #include "partitioning/partdesc.h"
60 : #include "rewrite/rewriteManip.h"
61 : #include "utils/acl.h"
62 : #include "utils/backend_status.h"
63 : #include "utils/lsyscache.h"
64 : #include "utils/rel.h"
65 : #include "utils/selfuncs.h"
66 :
67 : /* GUC parameters */
68 : double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
69 : int debug_parallel_query = DEBUG_PARALLEL_OFF;
70 : bool parallel_leader_participation = true;
71 : bool enable_distinct_reordering = true;
72 :
73 : /* Hook for plugins to get control in planner() */
74 : planner_hook_type planner_hook = NULL;
75 :
76 : /* Hook for plugins to get control after PlannerGlobal is initialized */
77 : planner_setup_hook_type planner_setup_hook = NULL;
78 :
79 : /* Hook for plugins to get control before PlannerGlobal is discarded */
80 : planner_shutdown_hook_type planner_shutdown_hook = NULL;
81 :
82 : /* Hook for plugins to get control when grouping_planner() plans upper rels */
83 : create_upper_paths_hook_type create_upper_paths_hook = NULL;
84 :
85 :
86 : /* Expression kind codes for preprocess_expression */
87 : #define EXPRKIND_QUAL 0
88 : #define EXPRKIND_TARGET 1
89 : #define EXPRKIND_RTFUNC 2
90 : #define EXPRKIND_RTFUNC_LATERAL 3
91 : #define EXPRKIND_VALUES 4
92 : #define EXPRKIND_VALUES_LATERAL 5
93 : #define EXPRKIND_LIMIT 6
94 : #define EXPRKIND_APPINFO 7
95 : #define EXPRKIND_PHV 8
96 : #define EXPRKIND_TABLESAMPLE 9
97 : #define EXPRKIND_ARBITER_ELEM 10
98 : #define EXPRKIND_TABLEFUNC 11
99 : #define EXPRKIND_TABLEFUNC_LATERAL 12
100 : #define EXPRKIND_GROUPEXPR 13
101 :
102 : /*
103 : * Data specific to grouping sets
104 : */
105 : typedef struct
106 : {
107 : List *rollups;
108 : List *hash_sets_idx;
109 : double dNumHashGroups;
110 : bool any_hashable;
111 : Bitmapset *unsortable_refs;
112 : Bitmapset *unhashable_refs;
113 : List *unsortable_sets;
114 : int *tleref_to_colnum_map;
115 : } grouping_sets_data;
116 :
117 : /*
118 : * Temporary structure for use during WindowClause reordering in order to be
119 : * able to sort WindowClauses on partitioning/ordering prefix.
120 : */
121 : typedef struct
122 : {
123 : WindowClause *wc;
124 : List *uniqueOrder; /* A List of unique ordering/partitioning
125 : * clauses per Window */
126 : } WindowClauseSortData;
127 :
128 : /* Passthrough data for standard_qp_callback */
129 : typedef struct
130 : {
131 : List *activeWindows; /* active windows, if any */
132 : grouping_sets_data *gset_data; /* grouping sets data, if any */
133 : SetOperationStmt *setop; /* parent set operation or NULL if not a
134 : * subquery belonging to a set operation */
135 : } standard_qp_extra;
136 :
137 : /* Local functions */
138 : static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
139 : static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
140 : static void grouping_planner(PlannerInfo *root, double tuple_fraction,
141 : SetOperationStmt *setops);
142 : static grouping_sets_data *preprocess_grouping_sets(PlannerInfo *root);
143 : static List *remap_to_groupclause_idx(List *groupClause, List *gsets,
144 : int *tleref_to_colnum_map);
145 : static void preprocess_rowmarks(PlannerInfo *root);
146 : static double preprocess_limit(PlannerInfo *root,
147 : double tuple_fraction,
148 : int64 *offset_est, int64 *count_est);
149 : static List *preprocess_groupclause(PlannerInfo *root, List *force);
150 : static List *extract_rollup_sets(List *groupingSets);
151 : static List *reorder_grouping_sets(List *groupingSets, List *sortclause);
152 : static void standard_qp_callback(PlannerInfo *root, void *extra);
153 : static double get_number_of_groups(PlannerInfo *root,
154 : double path_rows,
155 : grouping_sets_data *gd,
156 : List *target_list);
157 : static RelOptInfo *create_grouping_paths(PlannerInfo *root,
158 : RelOptInfo *input_rel,
159 : PathTarget *target,
160 : bool target_parallel_safe,
161 : grouping_sets_data *gd);
162 : static bool is_degenerate_grouping(PlannerInfo *root);
163 : static void create_degenerate_grouping_paths(PlannerInfo *root,
164 : RelOptInfo *input_rel,
165 : RelOptInfo *grouped_rel);
166 : static RelOptInfo *make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
167 : PathTarget *target, bool target_parallel_safe,
168 : Node *havingQual);
169 : static void create_ordinary_grouping_paths(PlannerInfo *root,
170 : RelOptInfo *input_rel,
171 : RelOptInfo *grouped_rel,
172 : const AggClauseCosts *agg_costs,
173 : grouping_sets_data *gd,
174 : GroupPathExtraData *extra,
175 : RelOptInfo **partially_grouped_rel_p);
176 : static void consider_groupingsets_paths(PlannerInfo *root,
177 : RelOptInfo *grouped_rel,
178 : Path *path,
179 : bool is_sorted,
180 : bool can_hash,
181 : grouping_sets_data *gd,
182 : const AggClauseCosts *agg_costs,
183 : double dNumGroups);
184 : static RelOptInfo *create_window_paths(PlannerInfo *root,
185 : RelOptInfo *input_rel,
186 : PathTarget *input_target,
187 : PathTarget *output_target,
188 : bool output_target_parallel_safe,
189 : WindowFuncLists *wflists,
190 : List *activeWindows);
191 : static void create_one_window_path(PlannerInfo *root,
192 : RelOptInfo *window_rel,
193 : Path *path,
194 : PathTarget *input_target,
195 : PathTarget *output_target,
196 : WindowFuncLists *wflists,
197 : List *activeWindows);
198 : static RelOptInfo *create_distinct_paths(PlannerInfo *root,
199 : RelOptInfo *input_rel,
200 : PathTarget *target);
201 : static void create_partial_distinct_paths(PlannerInfo *root,
202 : RelOptInfo *input_rel,
203 : RelOptInfo *final_distinct_rel,
204 : PathTarget *target);
205 : static RelOptInfo *create_final_distinct_paths(PlannerInfo *root,
206 : RelOptInfo *input_rel,
207 : RelOptInfo *distinct_rel);
208 : static List *get_useful_pathkeys_for_distinct(PlannerInfo *root,
209 : List *needed_pathkeys,
210 : List *path_pathkeys);
211 : static RelOptInfo *create_ordered_paths(PlannerInfo *root,
212 : RelOptInfo *input_rel,
213 : PathTarget *target,
214 : bool target_parallel_safe,
215 : double limit_tuples);
216 : static PathTarget *make_group_input_target(PlannerInfo *root,
217 : PathTarget *final_target);
218 : static PathTarget *make_partial_grouping_target(PlannerInfo *root,
219 : PathTarget *grouping_target,
220 : Node *havingQual);
221 : static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
222 : static void optimize_window_clauses(PlannerInfo *root,
223 : WindowFuncLists *wflists);
224 : static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
225 : static void name_active_windows(List *activeWindows);
226 : static PathTarget *make_window_input_target(PlannerInfo *root,
227 : PathTarget *final_target,
228 : List *activeWindows);
229 : static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
230 : List *tlist);
231 : static PathTarget *make_sort_input_target(PlannerInfo *root,
232 : PathTarget *final_target,
233 : bool *have_postponed_srfs);
234 : static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
235 : List *targets, List *targets_contain_srfs);
236 : static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
237 : RelOptInfo *grouped_rel,
238 : RelOptInfo *partially_grouped_rel,
239 : const AggClauseCosts *agg_costs,
240 : grouping_sets_data *gd,
241 : GroupPathExtraData *extra);
242 : static RelOptInfo *create_partial_grouping_paths(PlannerInfo *root,
243 : RelOptInfo *grouped_rel,
244 : RelOptInfo *input_rel,
245 : grouping_sets_data *gd,
246 : GroupPathExtraData *extra,
247 : bool force_rel_creation);
248 : static Path *make_ordered_path(PlannerInfo *root,
249 : RelOptInfo *rel,
250 : Path *path,
251 : Path *cheapest_path,
252 : List *pathkeys,
253 : double limit_tuples);
254 : static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel);
255 : static bool can_partial_agg(PlannerInfo *root);
256 : static void apply_scanjoin_target_to_paths(PlannerInfo *root,
257 : RelOptInfo *rel,
258 : List *scanjoin_targets,
259 : List *scanjoin_targets_contain_srfs,
260 : bool scanjoin_target_parallel_safe,
261 : bool tlist_same_exprs);
262 : static void create_partitionwise_grouping_paths(PlannerInfo *root,
263 : RelOptInfo *input_rel,
264 : RelOptInfo *grouped_rel,
265 : RelOptInfo *partially_grouped_rel,
266 : const AggClauseCosts *agg_costs,
267 : grouping_sets_data *gd,
268 : PartitionwiseAggregateType patype,
269 : GroupPathExtraData *extra);
270 : static bool group_by_has_partkey(RelOptInfo *input_rel,
271 : List *targetList,
272 : List *groupClause);
273 : static int common_prefix_cmp(const void *a, const void *b);
274 : static List *generate_setop_child_grouplist(SetOperationStmt *op,
275 : List *targetlist);
276 : static void create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
277 : List *sortPathkeys, List *groupClause,
278 : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
279 : static void create_partial_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
280 : List *sortPathkeys, List *groupClause,
281 : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
282 :
283 :
284 : /*****************************************************************************
285 : *
286 : * Query optimizer entry point
287 : *
288 : * Inputs:
289 : * parse: an analyzed-and-rewritten query tree for an optimizable statement
290 : * query_string: source text for the query tree (used for error reports)
291 : * cursorOptions: bitmask of CURSOR_OPT_XXX flags, see parsenodes.h
292 : * boundParams: passed-in parameter values, or NULL if none
293 : * es: ExplainState if being called from EXPLAIN, else NULL
294 : *
295 : * The result is a PlannedStmt tree.
296 : *
297 : * PARAM_EXTERN Param nodes within the parse tree can be replaced by Consts
298 : * using values from boundParams, if those values are marked PARAM_FLAG_CONST.
299 : * Parameter values not so marked are still relied on for estimation purposes.
300 : *
301 : * The ExplainState pointer is not currently used by the core planner, but it
302 : * is passed through to some planner hooks so that they can report information
303 : * back to EXPLAIN extension hooks.
304 : *
305 : * To support loadable plugins that monitor or modify planner behavior,
306 : * we provide a hook variable that lets a plugin get control before and
307 : * after the standard planning process. The plugin would normally call
308 : * standard_planner().
309 : *
310 : * Note to plugin authors: standard_planner() scribbles on its Query input,
311 : * so you'd better copy that data structure if you want to plan more than once.
312 : *
313 : *****************************************************************************/
314 : PlannedStmt *
315 332888 : planner(Query *parse, const char *query_string, int cursorOptions,
316 : ParamListInfo boundParams, ExplainState *es)
317 : {
318 : PlannedStmt *result;
319 :
320 332888 : if (planner_hook)
321 49847 : result = (*planner_hook) (parse, query_string, cursorOptions,
322 : boundParams, es);
323 : else
324 283041 : result = standard_planner(parse, query_string, cursorOptions,
325 : boundParams, es);
326 :
327 328897 : pgstat_report_plan_id(result->planId, false);
328 :
329 328897 : return result;
330 : }
331 :
332 : PlannedStmt *
333 332888 : standard_planner(Query *parse, const char *query_string, int cursorOptions,
334 : ParamListInfo boundParams, ExplainState *es)
335 : {
336 : PlannedStmt *result;
337 : PlannerGlobal *glob;
338 : double tuple_fraction;
339 : PlannerInfo *root;
340 : RelOptInfo *final_rel;
341 : Path *best_path;
342 : Plan *top_plan;
343 : ListCell *lp,
344 : *lr;
345 :
346 : /*
347 : * Set up global state for this planner invocation. This data is needed
348 : * across all levels of sub-Query that might exist in the given command,
349 : * so we keep it in a separate struct that's linked to by each per-Query
350 : * PlannerInfo.
351 : */
352 332888 : glob = makeNode(PlannerGlobal);
353 :
354 332888 : glob->boundParams = boundParams;
355 332888 : glob->subplans = NIL;
356 332888 : glob->subpaths = NIL;
357 332888 : glob->subroots = NIL;
358 332888 : glob->rewindPlanIDs = NULL;
359 332888 : glob->finalrtable = NIL;
360 332888 : glob->allRelids = NULL;
361 332888 : glob->prunableRelids = NULL;
362 332888 : glob->finalrteperminfos = NIL;
363 332888 : glob->finalrowmarks = NIL;
364 332888 : glob->resultRelations = NIL;
365 332888 : glob->appendRelations = NIL;
366 332888 : glob->partPruneInfos = NIL;
367 332888 : glob->relationOids = NIL;
368 332888 : glob->invalItems = NIL;
369 332888 : glob->paramExecTypes = NIL;
370 332888 : glob->lastPHId = 0;
371 332888 : glob->lastRowMarkId = 0;
372 332888 : glob->lastPlanNodeId = 0;
373 332888 : glob->transientPlan = false;
374 332888 : glob->dependsOnRole = false;
375 332888 : glob->partition_directory = NULL;
376 332888 : glob->rel_notnullatts_hash = NULL;
377 :
378 : /*
379 : * Assess whether it's feasible to use parallel mode for this query. We
380 : * can't do this in a standalone backend, or if the command will try to
381 : * modify any data, or if this is a cursor operation, or if GUCs are set
382 : * to values that don't permit parallelism, or if parallel-unsafe
383 : * functions are present in the query tree.
384 : *
385 : * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
386 : * MATERIALIZED VIEW to use parallel plans, but this is safe only because
387 : * the command is writing into a completely new table which workers won't
388 : * be able to see. If the workers could see the table, the fact that
389 : * group locking would cause them to ignore the leader's heavyweight GIN
390 : * page locks would make this unsafe. We'll have to fix that somehow if
391 : * we want to allow parallel inserts in general; updates and deletes have
392 : * additional problems especially around combo CIDs.)
393 : *
394 : * For now, we don't try to use parallel mode if we're running inside a
395 : * parallel worker. We might eventually be able to relax this
396 : * restriction, but for now it seems best not to have parallel workers
397 : * trying to create their own parallel workers.
398 : */
399 332888 : if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
400 313283 : IsUnderPostmaster &&
401 313283 : parse->commandType == CMD_SELECT &&
402 253672 : !parse->hasModifyingCTE &&
403 253554 : max_parallel_workers_per_gather > 0 &&
404 252899 : !IsParallelWorker())
405 : {
406 : /* all the cheap tests pass, so scan the query tree */
407 252859 : glob->maxParallelHazard = max_parallel_hazard(parse);
408 252859 : glob->parallelModeOK = (glob->maxParallelHazard != PROPARALLEL_UNSAFE);
409 : }
410 : else
411 : {
412 : /* skip the query tree scan, just assume it's unsafe */
413 80029 : glob->maxParallelHazard = PROPARALLEL_UNSAFE;
414 80029 : glob->parallelModeOK = false;
415 : }
416 :
417 : /*
418 : * glob->parallelModeNeeded is normally set to false here and changed to
419 : * true during plan creation if a Gather or Gather Merge plan is actually
420 : * created (cf. create_gather_plan, create_gather_merge_plan).
421 : *
422 : * However, if debug_parallel_query = on or debug_parallel_query =
423 : * regress, then we impose parallel mode whenever it's safe to do so, even
424 : * if the final plan doesn't use parallelism. It's not safe to do so if
425 : * the query contains anything parallel-unsafe; parallelModeOK will be
426 : * false in that case. Note that parallelModeOK can't change after this
427 : * point. Otherwise, everything in the query is either parallel-safe or
428 : * parallel-restricted, and in either case it should be OK to impose
429 : * parallel-mode restrictions. If that ends up breaking something, then
430 : * either some function the user included in the query is incorrectly
431 : * labeled as parallel-safe or parallel-restricted when in reality it's
432 : * parallel-unsafe, or else the query planner itself has a bug.
433 : */
434 551497 : glob->parallelModeNeeded = glob->parallelModeOK &&
435 218609 : (debug_parallel_query != DEBUG_PARALLEL_OFF);
436 :
437 : /* Determine what fraction of the plan is likely to be scanned */
438 332888 : if (cursorOptions & CURSOR_OPT_FAST_PLAN)
439 : {
440 : /*
441 : * We have no real idea how many tuples the user will ultimately FETCH
442 : * from a cursor, but it is often the case that he doesn't want 'em
443 : * all, or would prefer a fast-start plan anyway so that he can
444 : * process some of the tuples sooner. Use a GUC parameter to decide
445 : * what fraction to optimize for.
446 : */
447 3205 : tuple_fraction = cursor_tuple_fraction;
448 :
449 : /*
450 : * We document cursor_tuple_fraction as simply being a fraction, which
451 : * means the edge cases 0 and 1 have to be treated specially here. We
452 : * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
453 : */
454 3205 : if (tuple_fraction >= 1.0)
455 0 : tuple_fraction = 0.0;
456 3205 : else if (tuple_fraction <= 0.0)
457 0 : tuple_fraction = 1e-10;
458 : }
459 : else
460 : {
461 : /* Default assumption is we need all the tuples */
462 329683 : tuple_fraction = 0.0;
463 : }
464 :
465 : /*
466 : * Compute the initial path generation strategy mask.
467 : *
468 : * Some strategies, such as PGS_FOREIGNJOIN, have no corresponding enable_*
469 : * GUC, and so the corresponding bits are always set in the default
470 : * strategy mask.
471 : *
472 : * It may seem surprising that enable_indexscan sets both PGS_INDEXSCAN
473 : * and PGS_INDEXONLYSCAN. However, the historical behavior of this GUC
474 : * corresponds to this exactly: enable_indexscan=off disables both
475 : * index-scan and index-only scan paths, whereas enable_indexonlyscan=off
476 : * converts the index-only scan paths that we would have considered into
477 : * index scan paths.
478 : */
479 332888 : glob->default_pgs_mask = PGS_APPEND | PGS_MERGE_APPEND | PGS_FOREIGNJOIN |
480 : PGS_GATHER | PGS_CONSIDER_NONPARTIAL;
481 332888 : if (enable_tidscan)
482 332888 : glob->default_pgs_mask |= PGS_TIDSCAN;
483 332888 : if (enable_seqscan)
484 315843 : glob->default_pgs_mask |= PGS_SEQSCAN;
485 332888 : if (enable_indexscan)
486 330641 : glob->default_pgs_mask |= PGS_INDEXSCAN | PGS_INDEXONLYSCAN;
487 332888 : if (enable_indexonlyscan)
488 331496 : glob->default_pgs_mask |= PGS_CONSIDER_INDEXONLY;
489 332888 : if (enable_bitmapscan)
490 323573 : glob->default_pgs_mask |= PGS_BITMAPSCAN;
491 332888 : if (enable_mergejoin)
492 : {
493 331031 : glob->default_pgs_mask |= PGS_MERGEJOIN_PLAIN;
494 331031 : if (enable_material)
495 330964 : glob->default_pgs_mask |= PGS_MERGEJOIN_MATERIALIZE;
496 : }
497 332888 : if (enable_nestloop)
498 : {
499 332569 : glob->default_pgs_mask |= PGS_NESTLOOP_PLAIN;
500 332569 : if (enable_material)
501 332269 : glob->default_pgs_mask |= PGS_NESTLOOP_MATERIALIZE;
502 332569 : if (enable_memoize)
503 332450 : glob->default_pgs_mask |= PGS_NESTLOOP_MEMOIZE;
504 : }
505 332888 : if (enable_hashjoin)
506 330668 : glob->default_pgs_mask |= PGS_HASHJOIN;
507 332888 : if (enable_gathermerge)
508 332888 : glob->default_pgs_mask |= PGS_GATHER_MERGE;
509 332888 : if (enable_partitionwise_join)
510 2065 : glob->default_pgs_mask |= PGS_CONSIDER_PARTITIONWISE;
511 :
512 : /* Allow plugins to take control after we've initialized "glob" */
513 332888 : if (planner_setup_hook)
514 87098 : (*planner_setup_hook) (glob, parse, query_string, cursorOptions,
515 : &tuple_fraction, es);
516 :
517 : /* primary planning entry point (may recurse for subqueries) */
518 332120 : root = subquery_planner(glob, parse, NULL, NULL, NULL, false,
519 : tuple_fraction, NULL);
520 :
521 : /* Select best Path and turn it into a Plan */
522 329167 : final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
523 329167 : best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
524 :
525 329167 : top_plan = create_plan(root, best_path);
526 :
527 : /*
528 : * If creating a plan for a scrollable cursor, make sure it can run
529 : * backwards on demand. Add a Material node at the top at need.
530 : */
531 328897 : if (cursorOptions & CURSOR_OPT_SCROLL)
532 : {
533 221 : if (!ExecSupportsBackwardScan(top_plan))
534 26 : top_plan = materialize_finished_plan(top_plan);
535 : }
536 :
537 : /*
538 : * Optionally add a Gather node for testing purposes, provided this is
539 : * actually a safe thing to do.
540 : *
541 : * We can add Gather even when top_plan has parallel-safe initPlans, but
542 : * then we have to move the initPlans to the Gather node because of
543 : * SS_finalize_plan's limitations. That would cause cosmetic breakage of
544 : * regression tests when debug_parallel_query = regress, because initPlans
545 : * that would normally appear on the top_plan move to the Gather, causing
546 : * them to disappear from EXPLAIN output. That doesn't seem worth kluging
547 : * EXPLAIN to hide, so skip it when debug_parallel_query = regress.
548 : */
549 328897 : if (debug_parallel_query != DEBUG_PARALLEL_OFF &&
550 157 : top_plan->parallel_safe &&
551 104 : (top_plan->initPlan == NIL ||
552 0 : debug_parallel_query != DEBUG_PARALLEL_REGRESS))
553 : {
554 104 : Gather *gather = makeNode(Gather);
555 : Cost initplan_cost;
556 : bool unsafe_initplans;
557 :
558 104 : gather->plan.targetlist = top_plan->targetlist;
559 104 : gather->plan.qual = NIL;
560 104 : gather->plan.lefttree = top_plan;
561 104 : gather->plan.righttree = NULL;
562 104 : gather->num_workers = 1;
563 104 : gather->single_copy = true;
564 104 : gather->invisible = (debug_parallel_query == DEBUG_PARALLEL_REGRESS);
565 :
566 : /* Transfer any initPlans to the new top node */
567 104 : gather->plan.initPlan = top_plan->initPlan;
568 104 : top_plan->initPlan = NIL;
569 :
570 : /*
571 : * Since this Gather has no parallel-aware descendants to signal to,
572 : * we don't need a rescan Param.
573 : */
574 104 : gather->rescan_param = -1;
575 :
576 : /*
577 : * Ideally we'd use cost_gather here, but setting up dummy path data
578 : * to satisfy it doesn't seem much cleaner than knowing what it does.
579 : */
580 104 : gather->plan.startup_cost = top_plan->startup_cost +
581 : parallel_setup_cost;
582 104 : gather->plan.total_cost = top_plan->total_cost +
583 104 : parallel_setup_cost + parallel_tuple_cost * top_plan->plan_rows;
584 104 : gather->plan.plan_rows = top_plan->plan_rows;
585 104 : gather->plan.plan_width = top_plan->plan_width;
586 104 : gather->plan.parallel_aware = false;
587 104 : gather->plan.parallel_safe = false;
588 :
589 : /*
590 : * Delete the initplans' cost from top_plan. We needn't add it to the
591 : * Gather node, since the above coding already included it there.
592 : */
593 104 : SS_compute_initplan_cost(gather->plan.initPlan,
594 : &initplan_cost, &unsafe_initplans);
595 104 : top_plan->startup_cost -= initplan_cost;
596 104 : top_plan->total_cost -= initplan_cost;
597 :
598 : /* use parallel mode for parallel plans. */
599 104 : root->glob->parallelModeNeeded = true;
600 :
601 104 : top_plan = &gather->plan;
602 : }
603 :
604 : /*
605 : * If any Params were generated, run through the plan tree and compute
606 : * each plan node's extParam/allParam sets. Ideally we'd merge this into
607 : * set_plan_references' tree traversal, but for now it has to be separate
608 : * because we need to visit subplans before not after main plan.
609 : */
610 328897 : if (glob->paramExecTypes != NIL)
611 : {
612 : Assert(list_length(glob->subplans) == list_length(glob->subroots));
613 147800 : forboth(lp, glob->subplans, lr, glob->subroots)
614 : {
615 33665 : Plan *subplan = (Plan *) lfirst(lp);
616 33665 : PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
617 :
618 33665 : SS_finalize_plan(subroot, subplan);
619 : }
620 114135 : SS_finalize_plan(root, top_plan);
621 : }
622 :
623 : /* final cleanup of the plan */
624 : Assert(glob->finalrtable == NIL);
625 : Assert(glob->finalrteperminfos == NIL);
626 : Assert(glob->finalrowmarks == NIL);
627 : Assert(glob->resultRelations == NIL);
628 : Assert(glob->appendRelations == NIL);
629 328897 : top_plan = set_plan_references(root, top_plan);
630 : /* ... and the subplans (both regular subplans and initplans) */
631 : Assert(list_length(glob->subplans) == list_length(glob->subroots));
632 362562 : forboth(lp, glob->subplans, lr, glob->subroots)
633 : {
634 33665 : Plan *subplan = (Plan *) lfirst(lp);
635 33665 : PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
636 :
637 33665 : lfirst(lp) = set_plan_references(subroot, subplan);
638 : }
639 :
640 : /* build the PlannedStmt result */
641 328897 : result = makeNode(PlannedStmt);
642 :
643 328897 : result->commandType = parse->commandType;
644 328897 : result->queryId = parse->queryId;
645 328897 : result->planOrigin = PLAN_STMT_STANDARD;
646 328897 : result->hasReturning = (parse->returningList != NIL);
647 328897 : result->hasModifyingCTE = parse->hasModifyingCTE;
648 328897 : result->canSetTag = parse->canSetTag;
649 328897 : result->transientPlan = glob->transientPlan;
650 328897 : result->dependsOnRole = glob->dependsOnRole;
651 328897 : result->parallelModeNeeded = glob->parallelModeNeeded;
652 328897 : result->planTree = top_plan;
653 328897 : result->partPruneInfos = glob->partPruneInfos;
654 328897 : result->rtable = glob->finalrtable;
655 657794 : result->unprunableRelids = bms_difference(glob->allRelids,
656 328897 : glob->prunableRelids);
657 328897 : result->permInfos = glob->finalrteperminfos;
658 328897 : result->subrtinfos = glob->subrtinfos;
659 328897 : result->resultRelations = glob->resultRelations;
660 328897 : result->appendRelations = glob->appendRelations;
661 328897 : result->subplans = glob->subplans;
662 328897 : result->rewindPlanIDs = glob->rewindPlanIDs;
663 328897 : result->rowMarks = glob->finalrowmarks;
664 328897 : result->relationOids = glob->relationOids;
665 328897 : result->invalItems = glob->invalItems;
666 328897 : result->paramExecTypes = glob->paramExecTypes;
667 : /* utilityStmt should be null, but we might as well copy it */
668 328897 : result->utilityStmt = parse->utilityStmt;
669 328897 : result->elidedNodes = glob->elidedNodes;
670 328897 : result->stmt_location = parse->stmt_location;
671 328897 : result->stmt_len = parse->stmt_len;
672 :
673 328897 : result->jitFlags = PGJIT_NONE;
674 328897 : if (jit_enabled && jit_above_cost >= 0 &&
675 328255 : top_plan->total_cost > jit_above_cost)
676 : {
677 802 : result->jitFlags |= PGJIT_PERFORM;
678 :
679 : /*
680 : * Decide how much effort should be put into generating better code.
681 : */
682 802 : if (jit_optimize_above_cost >= 0 &&
683 802 : top_plan->total_cost > jit_optimize_above_cost)
684 315 : result->jitFlags |= PGJIT_OPT3;
685 802 : if (jit_inline_above_cost >= 0 &&
686 802 : top_plan->total_cost > jit_inline_above_cost)
687 315 : result->jitFlags |= PGJIT_INLINE;
688 :
689 : /*
690 : * Decide which operations should be JITed.
691 : */
692 802 : if (jit_expressions)
693 802 : result->jitFlags |= PGJIT_EXPR;
694 802 : if (jit_tuple_deforming)
695 802 : result->jitFlags |= PGJIT_DEFORM;
696 : }
697 :
698 : /* Allow plugins to take control before we discard "glob" */
699 328897 : if (planner_shutdown_hook)
700 85559 : (*planner_shutdown_hook) (glob, parse, query_string, result);
701 :
702 328897 : if (glob->partition_directory != NULL)
703 8990 : DestroyPartitionDirectory(glob->partition_directory);
704 :
705 328897 : return result;
706 : }
707 :
708 :
709 : /*--------------------
710 : * subquery_planner
711 : * Invokes the planner on a subquery. We recurse to here for each
712 : * sub-SELECT found in the query tree.
713 : *
714 : * glob is the global state for the current planner run.
715 : * parse is the querytree produced by the parser & rewriter.
716 : * plan_name is the name to assign to this subplan (NULL at the top level).
717 : * parent_root is the immediate parent Query's info (NULL at the top level).
718 : * alternative_root is a previously created PlannerInfo for which this query
719 : * level is an alternative implementation, or else NULL.
720 : * hasRecursion is true if this is a recursive WITH query.
721 : * tuple_fraction is the fraction of tuples we expect will be retrieved.
722 : * tuple_fraction is interpreted as explained for grouping_planner, below.
723 : * setops is used for set operation subqueries to provide the subquery with
724 : * the context in which it's being used so that Paths correctly sorted for the
725 : * set operation can be generated. NULL when not planning a set operation
726 : * child, or when a child of a set op that isn't interested in sorted input.
727 : *
728 : * Basically, this routine does the stuff that should only be done once
729 : * per Query object. It then calls grouping_planner. At one time,
730 : * grouping_planner could be invoked recursively on the same Query object;
731 : * that's not currently true, but we keep the separation between the two
732 : * routines anyway, in case we need it again someday.
733 : *
734 : * subquery_planner will be called recursively to handle sub-Query nodes
735 : * found within the query's expressions and rangetable.
736 : *
737 : * Returns the PlannerInfo struct ("root") that contains all data generated
738 : * while planning the subquery. In particular, the Path(s) attached to
739 : * the (UPPERREL_FINAL, NULL) upperrel represent our conclusions about the
740 : * cheapest way(s) to implement the query. The top level will select the
741 : * best Path and pass it through createplan.c to produce a finished Plan.
742 : *--------------------
743 : */
744 : PlannerInfo *
745 395958 : subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name,
746 : PlannerInfo *parent_root, PlannerInfo *alternative_root,
747 : bool hasRecursion, double tuple_fraction,
748 : SetOperationStmt *setops)
749 : {
750 : PlannerInfo *root;
751 : List *newWithCheckOptions;
752 : List *newHaving;
753 : bool hasOuterJoins;
754 : bool hasResultRTEs;
755 : RelOptInfo *final_rel;
756 : ListCell *l;
757 :
758 : /* Create a PlannerInfo data structure for this subquery */
759 395958 : root = makeNode(PlannerInfo);
760 395958 : root->parse = parse;
761 395958 : root->glob = glob;
762 395958 : root->query_level = parent_root ? parent_root->query_level + 1 : 1;
763 395958 : root->plan_name = plan_name;
764 395958 : if (alternative_root != NULL)
765 1328 : root->alternative_plan_name = alternative_root->plan_name;
766 : else
767 394630 : root->alternative_plan_name = plan_name;
768 395958 : root->parent_root = parent_root;
769 395958 : root->plan_params = NIL;
770 395958 : root->outer_params = NULL;
771 395958 : root->planner_cxt = CurrentMemoryContext;
772 395958 : root->init_plans = NIL;
773 395958 : root->cte_plan_ids = NIL;
774 395958 : root->multiexpr_params = NIL;
775 395958 : root->join_domains = NIL;
776 395958 : root->eq_classes = NIL;
777 395958 : root->ec_merging_done = false;
778 395958 : root->last_rinfo_serial = 0;
779 395958 : root->all_result_relids =
780 395958 : parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL;
781 395958 : root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */
782 395958 : root->append_rel_list = NIL;
783 395958 : root->row_identity_vars = NIL;
784 395958 : root->rowMarks = NIL;
785 395958 : memset(root->upper_rels, 0, sizeof(root->upper_rels));
786 395958 : memset(root->upper_targets, 0, sizeof(root->upper_targets));
787 395958 : root->processed_groupClause = NIL;
788 395958 : root->processed_distinctClause = NIL;
789 395958 : root->processed_tlist = NIL;
790 395958 : root->update_colnos = NIL;
791 395958 : root->grouping_map = NULL;
792 395958 : root->minmax_aggs = NIL;
793 395958 : root->qual_security_level = 0;
794 395958 : root->hasPseudoConstantQuals = false;
795 395958 : root->hasAlternativeSubPlans = false;
796 395958 : root->placeholdersFrozen = false;
797 395958 : root->hasRecursion = hasRecursion;
798 395958 : root->assumeReplanning = false;
799 395958 : if (hasRecursion)
800 692 : root->wt_param_id = assign_special_exec_param(root);
801 : else
802 395266 : root->wt_param_id = -1;
803 395958 : root->non_recursive_path = NULL;
804 :
805 : /*
806 : * Create the top-level join domain. This won't have valid contents until
807 : * deconstruct_jointree fills it in, but the node needs to exist before
808 : * that so we can build EquivalenceClasses referencing it.
809 : */
810 395958 : root->join_domains = list_make1(makeNode(JoinDomain));
811 :
812 : /*
813 : * If there is a WITH list, process each WITH query and either convert it
814 : * to RTE_SUBQUERY RTE(s) or build an initplan SubPlan structure for it.
815 : */
816 395958 : if (parse->cteList)
817 2193 : SS_process_ctes(root);
818 :
819 : /*
820 : * If it's a MERGE command, transform the joinlist as appropriate.
821 : */
822 395954 : transform_MERGE_to_join(parse);
823 :
824 : /*
825 : * Scan the rangetable for relation RTEs and retrieve the necessary
826 : * catalog information for each relation. Using this information, clear
827 : * the inh flag for any relation that has no children, collect not-null
828 : * attribute numbers for any relation that has column not-null
829 : * constraints, and expand virtual generated columns for any relation that
830 : * contains them. Note that this step does not descend into sublinks and
831 : * subqueries; if we pull up any sublinks or subqueries below, their
832 : * relation RTEs are processed just before pulling them up.
833 : */
834 395954 : parse = root->parse = preprocess_relation_rtes(root);
835 :
836 : /*
837 : * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
838 : * that we don't need so many special cases to deal with that situation.
839 : */
840 395954 : replace_empty_jointree(parse);
841 :
842 : /*
843 : * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
844 : * to transform them into joins. Note that this step does not descend
845 : * into subqueries; if we pull up any subqueries below, their SubLinks are
846 : * processed just before pulling them up.
847 : */
848 395954 : if (parse->hasSubLinks)
849 31135 : pull_up_sublinks(root);
850 :
851 : /*
852 : * Scan the rangetable for function RTEs, do const-simplification on them,
853 : * and then inline them if possible (producing subqueries that might get
854 : * pulled up next). Recursion issues here are handled in the same way as
855 : * for SubLinks.
856 : */
857 395954 : preprocess_function_rtes(root);
858 :
859 : /*
860 : * Check to see if any subqueries in the jointree can be merged into this
861 : * query.
862 : */
863 395950 : pull_up_subqueries(root);
864 :
865 : /*
866 : * If this is a simple UNION ALL query, flatten it into an appendrel. We
867 : * do this now because it requires applying pull_up_subqueries to the leaf
868 : * queries of the UNION ALL, which weren't touched above because they
869 : * weren't referenced by the jointree (they will be after we do this).
870 : */
871 395946 : if (parse->setOperations)
872 5457 : flatten_simple_union_all(root);
873 :
874 : /*
875 : * Survey the rangetable to see what kinds of entries are present. We can
876 : * skip some later processing if relevant SQL features are not used; for
877 : * example if there are no JOIN RTEs we can avoid the expense of doing
878 : * flatten_join_alias_vars(). This must be done after we have finished
879 : * adding rangetable entries, of course. (Note: actually, processing of
880 : * inherited or partitioned rels can cause RTEs for their child tables to
881 : * get added later; but those must all be RTE_RELATION entries, so they
882 : * don't invalidate the conclusions drawn here.)
883 : */
884 395946 : root->hasJoinRTEs = false;
885 395946 : root->hasLateralRTEs = false;
886 395946 : root->group_rtindex = 0;
887 395946 : hasOuterJoins = false;
888 395946 : hasResultRTEs = false;
889 1097009 : foreach(l, parse->rtable)
890 : {
891 701063 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
892 :
893 701063 : switch (rte->rtekind)
894 : {
895 74105 : case RTE_JOIN:
896 74105 : root->hasJoinRTEs = true;
897 74105 : if (IS_OUTER_JOIN(rte->jointype))
898 37011 : hasOuterJoins = true;
899 74105 : break;
900 144543 : case RTE_RESULT:
901 144543 : hasResultRTEs = true;
902 144543 : break;
903 4055 : case RTE_GROUP:
904 : Assert(parse->hasGroupRTE);
905 4055 : root->group_rtindex = list_cell_number(parse->rtable, l) + 1;
906 4055 : break;
907 478360 : default:
908 : /* No work here for other RTE types */
909 478360 : break;
910 : }
911 :
912 701063 : if (rte->lateral)
913 8540 : root->hasLateralRTEs = true;
914 :
915 : /*
916 : * We can also determine the maximum security level required for any
917 : * securityQuals now. Addition of inheritance-child RTEs won't affect
918 : * this, because child tables don't have their own securityQuals; see
919 : * expand_single_inheritance_child().
920 : */
921 701063 : if (rte->securityQuals)
922 2455 : root->qual_security_level = Max(root->qual_security_level,
923 : list_length(rte->securityQuals));
924 : }
925 :
926 : /*
927 : * If we have now verified that the query target relation is
928 : * non-inheriting, mark it as a leaf target.
929 : */
930 395946 : if (parse->resultRelation)
931 : {
932 63272 : RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable);
933 :
934 63272 : if (!rte->inh)
935 61026 : root->leaf_result_relids =
936 61026 : bms_make_singleton(parse->resultRelation);
937 : }
938 :
939 : /*
940 : * This would be a convenient time to check access permissions for all
941 : * relations mentioned in the query, since it would be better to fail now,
942 : * before doing any detailed planning. However, for historical reasons,
943 : * we leave this to be done at executor startup.
944 : *
945 : * Note, however, that we do need to check access permissions for any view
946 : * relations mentioned in the query, in order to prevent information being
947 : * leaked by selectivity estimation functions, which only check view owner
948 : * permissions on underlying tables (see all_rows_selectable() and its
949 : * callers). This is a little ugly, because it means that access
950 : * permissions for views will be checked twice, which is another reason
951 : * why it would be better to do all the ACL checks here.
952 : */
953 1096221 : foreach(l, parse->rtable)
954 : {
955 700541 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
956 :
957 700541 : if (rte->perminfoindex != 0 &&
958 380963 : rte->relkind == RELKIND_VIEW)
959 : {
960 : RTEPermissionInfo *perminfo;
961 : bool result;
962 :
963 16509 : perminfo = getRTEPermissionInfo(parse->rteperminfos, rte);
964 16509 : result = ExecCheckOneRelPerms(perminfo);
965 16509 : if (!result)
966 266 : aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_VIEW,
967 266 : get_rel_name(perminfo->relid));
968 : }
969 : }
970 :
971 : /*
972 : * Preprocess RowMark information. We need to do this after subquery
973 : * pullup, so that all base relations are present.
974 : */
975 395680 : preprocess_rowmarks(root);
976 :
977 : /*
978 : * Set hasHavingQual to remember if HAVING clause is present. Needed
979 : * because preprocess_expression will reduce a constant-true condition to
980 : * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
981 : */
982 395680 : root->hasHavingQual = (parse->havingQual != NULL);
983 :
984 : /*
985 : * Do expression preprocessing on targetlist and quals, as well as other
986 : * random expressions in the querytree. Note that we do not need to
987 : * handle sort/group expressions explicitly, because they are actually
988 : * part of the targetlist.
989 : */
990 393047 : parse->targetList = (List *)
991 395680 : preprocess_expression(root, (Node *) parse->targetList,
992 : EXPRKIND_TARGET);
993 :
994 393047 : newWithCheckOptions = NIL;
995 395615 : foreach(l, parse->withCheckOptions)
996 : {
997 2568 : WithCheckOption *wco = lfirst_node(WithCheckOption, l);
998 :
999 2568 : wco->qual = preprocess_expression(root, wco->qual,
1000 : EXPRKIND_QUAL);
1001 2568 : if (wco->qual != NULL)
1002 2236 : newWithCheckOptions = lappend(newWithCheckOptions, wco);
1003 : }
1004 393047 : parse->withCheckOptions = newWithCheckOptions;
1005 :
1006 393047 : parse->returningList = (List *)
1007 393047 : preprocess_expression(root, (Node *) parse->returningList,
1008 : EXPRKIND_TARGET);
1009 :
1010 393047 : preprocess_qual_conditions(root, (Node *) parse->jointree);
1011 :
1012 393047 : parse->havingQual = preprocess_expression(root, parse->havingQual,
1013 : EXPRKIND_QUAL);
1014 :
1015 395454 : foreach(l, parse->windowClause)
1016 : {
1017 2407 : WindowClause *wc = lfirst_node(WindowClause, l);
1018 :
1019 : /* partitionClause/orderClause are sort/group expressions */
1020 2407 : wc->startOffset = preprocess_expression(root, wc->startOffset,
1021 : EXPRKIND_LIMIT);
1022 2407 : wc->endOffset = preprocess_expression(root, wc->endOffset,
1023 : EXPRKIND_LIMIT);
1024 : }
1025 :
1026 393047 : parse->limitOffset = preprocess_expression(root, parse->limitOffset,
1027 : EXPRKIND_LIMIT);
1028 393047 : parse->limitCount = preprocess_expression(root, parse->limitCount,
1029 : EXPRKIND_LIMIT);
1030 :
1031 393047 : if (parse->onConflict)
1032 : {
1033 3528 : parse->onConflict->arbiterElems = (List *)
1034 1764 : preprocess_expression(root,
1035 1764 : (Node *) parse->onConflict->arbiterElems,
1036 : EXPRKIND_ARBITER_ELEM);
1037 3528 : parse->onConflict->arbiterWhere =
1038 1764 : preprocess_expression(root,
1039 1764 : parse->onConflict->arbiterWhere,
1040 : EXPRKIND_QUAL);
1041 3528 : parse->onConflict->onConflictSet = (List *)
1042 1764 : preprocess_expression(root,
1043 1764 : (Node *) parse->onConflict->onConflictSet,
1044 : EXPRKIND_TARGET);
1045 1764 : parse->onConflict->onConflictWhere =
1046 1764 : preprocess_expression(root,
1047 1764 : parse->onConflict->onConflictWhere,
1048 : EXPRKIND_QUAL);
1049 : /* exclRelTlist contains only Vars, so no preprocessing needed */
1050 : }
1051 :
1052 395303 : foreach(l, parse->mergeActionList)
1053 : {
1054 2256 : MergeAction *action = (MergeAction *) lfirst(l);
1055 :
1056 2256 : action->targetList = (List *)
1057 2256 : preprocess_expression(root,
1058 2256 : (Node *) action->targetList,
1059 : EXPRKIND_TARGET);
1060 2256 : action->qual =
1061 2256 : preprocess_expression(root,
1062 : (Node *) action->qual,
1063 : EXPRKIND_QUAL);
1064 : }
1065 :
1066 393047 : parse->mergeJoinCondition =
1067 393047 : preprocess_expression(root, parse->mergeJoinCondition, EXPRKIND_QUAL);
1068 :
1069 393047 : root->append_rel_list = (List *)
1070 393047 : preprocess_expression(root, (Node *) root->append_rel_list,
1071 : EXPRKIND_APPINFO);
1072 :
1073 : /* Also need to preprocess expressions within RTEs */
1074 1090288 : foreach(l, parse->rtable)
1075 : {
1076 697241 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
1077 : int kind;
1078 : ListCell *lcsq;
1079 :
1080 697241 : if (rte->rtekind == RTE_RELATION)
1081 : {
1082 367548 : if (rte->tablesample)
1083 178 : rte->tablesample = (TableSampleClause *)
1084 178 : preprocess_expression(root,
1085 178 : (Node *) rte->tablesample,
1086 : EXPRKIND_TABLESAMPLE);
1087 : }
1088 329693 : else if (rte->rtekind == RTE_SUBQUERY)
1089 : {
1090 : /*
1091 : * We don't want to do all preprocessing yet on the subquery's
1092 : * expressions, since that will happen when we plan it. But if it
1093 : * contains any join aliases of our level, those have to get
1094 : * expanded now, because planning of the subquery won't do it.
1095 : * That's only possible if the subquery is LATERAL.
1096 : */
1097 63434 : if (rte->lateral && root->hasJoinRTEs)
1098 1595 : rte->subquery = (Query *)
1099 1595 : flatten_join_alias_vars(root, root->parse,
1100 1595 : (Node *) rte->subquery);
1101 : }
1102 266259 : else if (rte->rtekind == RTE_FUNCTION)
1103 : {
1104 : /* Preprocess the function expression(s) fully */
1105 35134 : kind = rte->lateral ? EXPRKIND_RTFUNC_LATERAL : EXPRKIND_RTFUNC;
1106 35134 : rte->functions = (List *)
1107 35134 : preprocess_expression(root, (Node *) rte->functions, kind);
1108 : }
1109 231125 : else if (rte->rtekind == RTE_TABLEFUNC)
1110 : {
1111 : /* Preprocess the function expression(s) fully */
1112 519 : kind = rte->lateral ? EXPRKIND_TABLEFUNC_LATERAL : EXPRKIND_TABLEFUNC;
1113 519 : rte->tablefunc = (TableFunc *)
1114 519 : preprocess_expression(root, (Node *) rte->tablefunc, kind);
1115 : }
1116 230606 : else if (rte->rtekind == RTE_VALUES)
1117 : {
1118 : /* Preprocess the values lists fully */
1119 6728 : kind = rte->lateral ? EXPRKIND_VALUES_LATERAL : EXPRKIND_VALUES;
1120 6728 : rte->values_lists = (List *)
1121 6728 : preprocess_expression(root, (Node *) rte->values_lists, kind);
1122 : }
1123 223878 : else if (rte->rtekind == RTE_GROUP)
1124 : {
1125 : /* Preprocess the groupexprs list fully */
1126 4055 : rte->groupexprs = (List *)
1127 4055 : preprocess_expression(root, (Node *) rte->groupexprs,
1128 : EXPRKIND_GROUPEXPR);
1129 : }
1130 :
1131 : /*
1132 : * Process each element of the securityQuals list as if it were a
1133 : * separate qual expression (as indeed it is). We need to do it this
1134 : * way to get proper canonicalization of AND/OR structure. Note that
1135 : * this converts each element into an implicit-AND sublist.
1136 : */
1137 700046 : foreach(lcsq, rte->securityQuals)
1138 : {
1139 2805 : lfirst(lcsq) = preprocess_expression(root,
1140 2805 : (Node *) lfirst(lcsq),
1141 : EXPRKIND_QUAL);
1142 : }
1143 : }
1144 :
1145 : /*
1146 : * Now that we are done preprocessing expressions, and in particular done
1147 : * flattening join alias variables, get rid of the joinaliasvars lists.
1148 : * They no longer match what expressions in the rest of the tree look
1149 : * like, because we have not preprocessed expressions in those lists (and
1150 : * do not want to; for example, expanding a SubLink there would result in
1151 : * a useless unreferenced subplan). Leaving them in place simply creates
1152 : * a hazard for later scans of the tree. We could try to prevent that by
1153 : * using QTW_IGNORE_JOINALIASES in every tree scan done after this point,
1154 : * but that doesn't sound very reliable.
1155 : */
1156 393047 : if (root->hasJoinRTEs)
1157 : {
1158 257842 : foreach(l, parse->rtable)
1159 : {
1160 211380 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
1161 :
1162 211380 : rte->joinaliasvars = NIL;
1163 : }
1164 : }
1165 :
1166 : /*
1167 : * Replace any Vars in the subquery's targetlist and havingQual that
1168 : * reference GROUP outputs with the underlying grouping expressions.
1169 : *
1170 : * Note that we need to perform this replacement after we've preprocessed
1171 : * the grouping expressions. This is to ensure that there is only one
1172 : * instance of SubPlan for each SubLink contained within the grouping
1173 : * expressions.
1174 : */
1175 393047 : if (parse->hasGroupRTE)
1176 : {
1177 4055 : parse->targetList = (List *)
1178 4055 : flatten_group_exprs(root, root->parse, (Node *) parse->targetList);
1179 4055 : parse->havingQual =
1180 4055 : flatten_group_exprs(root, root->parse, parse->havingQual);
1181 : }
1182 :
1183 : /* Constant-folding might have removed all set-returning functions */
1184 393047 : if (parse->hasTargetSRFs)
1185 9905 : parse->hasTargetSRFs = expression_returns_set((Node *) parse->targetList);
1186 :
1187 : /*
1188 : * If we have grouping sets, expand the groupingSets tree of this query to
1189 : * a flat list of grouping sets. We need to do this before optimizing
1190 : * HAVING, since we can't easily tell if there's an empty grouping set
1191 : * until we have this representation.
1192 : */
1193 393047 : if (parse->groupingSets)
1194 : {
1195 855 : parse->groupingSets =
1196 855 : expand_grouping_sets(parse->groupingSets, parse->groupDistinct, -1);
1197 : }
1198 :
1199 : /*
1200 : * In some cases we may want to transfer a HAVING clause into WHERE. We
1201 : * cannot do so if the HAVING clause contains aggregates (obviously) or
1202 : * volatile functions (since a HAVING clause is supposed to be executed
1203 : * only once per group). We also can't do this if there are any grouping
1204 : * sets and the clause references any columns that are nullable by the
1205 : * grouping sets; the nulled values of those columns are not available
1206 : * before the grouping step. (The test on groupClause might seem wrong,
1207 : * but it's okay: it's just an optimization to avoid running pull_varnos
1208 : * when there cannot be any Vars in the HAVING clause.)
1209 : *
1210 : * Also, it may be that the clause is so expensive to execute that we're
1211 : * better off doing it only once per group, despite the loss of
1212 : * selectivity. This is hard to estimate short of doing the entire
1213 : * planning process twice, so we use a heuristic: clauses containing
1214 : * subplans are left in HAVING. Otherwise, we move or copy the HAVING
1215 : * clause into WHERE, in hopes of eliminating tuples before aggregation
1216 : * instead of after.
1217 : *
1218 : * If the query has no empty grouping set then we can simply move such a
1219 : * clause into WHERE; any group that fails the clause will not be in the
1220 : * output because none of its tuples will reach the grouping or
1221 : * aggregation stage. Otherwise we have to keep the clause in HAVING to
1222 : * ensure that we don't emit a bogus aggregated row. But then the HAVING
1223 : * clause must be degenerate (variable-free), so we can copy it into WHERE
1224 : * so that query_planner() can use it in a gating Result node. (This could
1225 : * be done better, but it seems not worth optimizing.)
1226 : *
1227 : * Note that a HAVING clause may contain expressions that are not fully
1228 : * preprocessed. This can happen if these expressions are part of
1229 : * grouping items. In such cases, they are replaced with GROUP Vars in
1230 : * the parser and then replaced back after we're done with expression
1231 : * preprocessing on havingQual. This is not an issue if the clause
1232 : * remains in HAVING, because these expressions will be matched to lower
1233 : * target items in setrefs.c. However, if the clause is moved or copied
1234 : * into WHERE, we need to ensure that these expressions are fully
1235 : * preprocessed.
1236 : *
1237 : * Note that both havingQual and parse->jointree->quals are in
1238 : * implicitly-ANDed-list form at this point, even though they are declared
1239 : * as Node *.
1240 : */
1241 393047 : newHaving = NIL;
1242 394150 : foreach(l, (List *) parse->havingQual)
1243 : {
1244 1103 : Node *havingclause = (Node *) lfirst(l);
1245 :
1246 1529 : if (contain_agg_clause(havingclause) ||
1247 852 : contain_volatile_functions(havingclause) ||
1248 426 : contain_subplans(havingclause) ||
1249 526 : (parse->groupClause && parse->groupingSets &&
1250 100 : bms_is_member(root->group_rtindex, pull_varnos(root, havingclause))))
1251 : {
1252 : /* keep it in HAVING */
1253 737 : newHaving = lappend(newHaving, havingclause);
1254 : }
1255 366 : else if (parse->groupClause &&
1256 336 : (parse->groupingSets == NIL ||
1257 40 : (List *) linitial(parse->groupingSets) != NIL))
1258 326 : {
1259 : /* There is GROUP BY, but no empty grouping set */
1260 : Node *whereclause;
1261 :
1262 : /* Preprocess the HAVING clause fully */
1263 326 : whereclause = preprocess_expression(root, havingclause,
1264 : EXPRKIND_QUAL);
1265 : /* ... and move it to WHERE */
1266 326 : parse->jointree->quals = (Node *)
1267 326 : list_concat((List *) parse->jointree->quals,
1268 : (List *) whereclause);
1269 : }
1270 : else
1271 : {
1272 : /* There is an empty grouping set (perhaps implicitly) */
1273 : Node *whereclause;
1274 :
1275 : /* Preprocess the HAVING clause fully */
1276 40 : whereclause = preprocess_expression(root, copyObject(havingclause),
1277 : EXPRKIND_QUAL);
1278 : /* ... and put a copy in WHERE */
1279 80 : parse->jointree->quals = (Node *)
1280 40 : list_concat((List *) parse->jointree->quals,
1281 : (List *) whereclause);
1282 : /* ... and also keep it in HAVING */
1283 40 : newHaving = lappend(newHaving, havingclause);
1284 : }
1285 : }
1286 393047 : parse->havingQual = (Node *) newHaving;
1287 :
1288 : /*
1289 : * If we have any outer joins, try to reduce them to plain inner joins.
1290 : * This step is most easily done after we've done expression
1291 : * preprocessing.
1292 : */
1293 393047 : if (hasOuterJoins)
1294 25700 : reduce_outer_joins(root);
1295 :
1296 : /*
1297 : * If we have any RTE_RESULT relations, see if they can be deleted from
1298 : * the jointree. We also rely on this processing to flatten single-child
1299 : * FromExprs underneath outer joins. This step is most effectively done
1300 : * after we've done expression preprocessing and outer join reduction.
1301 : */
1302 393047 : if (hasResultRTEs || hasOuterJoins)
1303 166437 : remove_useless_result_rtes(root);
1304 :
1305 : /*
1306 : * Do the main planning.
1307 : */
1308 393047 : grouping_planner(root, tuple_fraction, setops);
1309 :
1310 : /*
1311 : * Capture the set of outer-level param IDs we have access to, for use in
1312 : * extParam/allParam calculations later.
1313 : */
1314 393001 : SS_identify_outer_params(root);
1315 :
1316 : /*
1317 : * If any initPlans were created in this query level, adjust the surviving
1318 : * Paths' costs and parallel-safety flags to account for them. The
1319 : * initPlans won't actually get attached to the plan tree till
1320 : * create_plan() runs, but we must include their effects now.
1321 : */
1322 393001 : final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1323 393001 : SS_charge_for_initplans(root, final_rel);
1324 :
1325 : /*
1326 : * Make sure we've identified the cheapest Path for the final rel. (By
1327 : * doing this here not in grouping_planner, we include initPlan costs in
1328 : * the decision, though it's unlikely that will change anything.)
1329 : */
1330 393001 : set_cheapest(final_rel);
1331 :
1332 393001 : return root;
1333 : }
1334 :
1335 : /*
1336 : * preprocess_expression
1337 : * Do subquery_planner's preprocessing work for an expression,
1338 : * which can be a targetlist, a WHERE clause (including JOIN/ON
1339 : * conditions), a HAVING clause, or a few other things.
1340 : */
1341 : static Node *
1342 3313522 : preprocess_expression(PlannerInfo *root, Node *expr, int kind)
1343 : {
1344 : /*
1345 : * Fall out quickly if expression is empty. This occurs often enough to
1346 : * be worth checking. Note that null->null is the correct conversion for
1347 : * implicit-AND result format, too.
1348 : */
1349 3313522 : if (expr == NULL)
1350 2602493 : return NULL;
1351 :
1352 : /*
1353 : * If the query has any join RTEs, replace join alias variables with
1354 : * base-relation variables. We must do this first, since any expressions
1355 : * we may extract from the joinaliasvars lists have not been preprocessed.
1356 : * For example, if we did this after sublink processing, sublinks expanded
1357 : * out from join aliases would not get processed. But we can skip this in
1358 : * non-lateral RTE functions, VALUES lists, and TABLESAMPLE clauses, since
1359 : * they can't contain any Vars of the current query level.
1360 : */
1361 711029 : if (root->hasJoinRTEs &&
1362 331084 : !(kind == EXPRKIND_RTFUNC ||
1363 165396 : kind == EXPRKIND_VALUES ||
1364 : kind == EXPRKIND_TABLESAMPLE ||
1365 : kind == EXPRKIND_TABLEFUNC))
1366 165381 : expr = flatten_join_alias_vars(root, root->parse, expr);
1367 :
1368 : /*
1369 : * Simplify constant expressions. For function RTEs, this was already
1370 : * done by preprocess_function_rtes. (But note we must do it again for
1371 : * EXPRKIND_RTFUNC_LATERAL, because those might by now contain
1372 : * un-simplified subexpressions inserted by flattening of subqueries or
1373 : * join alias variables.)
1374 : *
1375 : * Note: an essential effect of this is to convert named-argument function
1376 : * calls to positional notation and insert the current actual values of
1377 : * any default arguments for functions. To ensure that happens, we *must*
1378 : * process all expressions here. Previous PG versions sometimes skipped
1379 : * const-simplification if it didn't seem worth the trouble, but we can't
1380 : * do that anymore.
1381 : *
1382 : * Note: this also flattens nested AND and OR expressions into N-argument
1383 : * form. All processing of a qual expression after this point must be
1384 : * careful to maintain AND/OR flatness --- that is, do not generate a tree
1385 : * with AND directly under AND, nor OR directly under OR.
1386 : */
1387 711029 : if (kind != EXPRKIND_RTFUNC)
1388 680840 : expr = eval_const_expressions(root, expr);
1389 :
1390 : /*
1391 : * If it's a qual or havingQual, canonicalize it.
1392 : */
1393 708396 : if (kind == EXPRKIND_QUAL)
1394 : {
1395 264100 : expr = (Node *) canonicalize_qual((Expr *) expr, false);
1396 :
1397 : #ifdef OPTIMIZER_DEBUG
1398 : printf("After canonicalize_qual()\n");
1399 : pprint(expr);
1400 : #endif
1401 : }
1402 :
1403 : /*
1404 : * Check for ANY ScalarArrayOpExpr with Const arrays and set the
1405 : * hashfuncid of any that might execute more quickly by using hash lookups
1406 : * instead of a linear search.
1407 : */
1408 708396 : if (kind == EXPRKIND_QUAL || kind == EXPRKIND_TARGET)
1409 : {
1410 650410 : convert_saop_to_hashed_saop(expr);
1411 : }
1412 :
1413 : /* Expand SubLinks to SubPlans */
1414 708396 : if (root->parse->hasSubLinks)
1415 91512 : expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
1416 :
1417 : /*
1418 : * XXX do not insert anything here unless you have grokked the comments in
1419 : * SS_replace_correlation_vars ...
1420 : */
1421 :
1422 : /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
1423 708396 : if (root->query_level > 1)
1424 148571 : expr = SS_replace_correlation_vars(root, expr);
1425 :
1426 : /*
1427 : * If it's a qual or havingQual, convert it to implicit-AND format. (We
1428 : * don't want to do this before eval_const_expressions, since the latter
1429 : * would be unable to simplify a top-level AND correctly. Also,
1430 : * SS_process_sublinks expects explicit-AND format.)
1431 : */
1432 708396 : if (kind == EXPRKIND_QUAL)
1433 264100 : expr = (Node *) make_ands_implicit((Expr *) expr);
1434 :
1435 708396 : return expr;
1436 : }
1437 :
1438 : /*
1439 : * preprocess_qual_conditions
1440 : * Recursively scan the query's jointree and do subquery_planner's
1441 : * preprocessing work on each qual condition found therein.
1442 : */
1443 : static void
1444 1000034 : preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
1445 : {
1446 1000034 : if (jtnode == NULL)
1447 0 : return;
1448 1000034 : if (IsA(jtnode, RangeTblRef))
1449 : {
1450 : /* nothing to do here */
1451 : }
1452 490750 : else if (IsA(jtnode, FromExpr))
1453 : {
1454 407869 : FromExpr *f = (FromExpr *) jtnode;
1455 : ListCell *l;
1456 :
1457 849094 : foreach(l, f->fromlist)
1458 441225 : preprocess_qual_conditions(root, lfirst(l));
1459 :
1460 407869 : f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
1461 : }
1462 82881 : else if (IsA(jtnode, JoinExpr))
1463 : {
1464 82881 : JoinExpr *j = (JoinExpr *) jtnode;
1465 :
1466 82881 : preprocess_qual_conditions(root, j->larg);
1467 82881 : preprocess_qual_conditions(root, j->rarg);
1468 :
1469 82881 : j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
1470 : }
1471 : else
1472 0 : elog(ERROR, "unrecognized node type: %d",
1473 : (int) nodeTag(jtnode));
1474 : }
1475 :
1476 : /*
1477 : * preprocess_phv_expression
1478 : * Do preprocessing on a PlaceHolderVar expression that's been pulled up.
1479 : *
1480 : * If a LATERAL subquery references an output of another subquery, and that
1481 : * output must be wrapped in a PlaceHolderVar because of an intermediate outer
1482 : * join, then we'll push the PlaceHolderVar expression down into the subquery
1483 : * and later pull it back up during find_lateral_references, which runs after
1484 : * subquery_planner has preprocessed all the expressions that were in the
1485 : * current query level to start with. So we need to preprocess it then.
1486 : */
1487 : Expr *
1488 75 : preprocess_phv_expression(PlannerInfo *root, Expr *expr)
1489 : {
1490 75 : return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
1491 : }
1492 :
1493 : /*--------------------
1494 : * grouping_planner
1495 : * Perform planning steps related to grouping, aggregation, etc.
1496 : *
1497 : * This function adds all required top-level processing to the scan/join
1498 : * Path(s) produced by query_planner.
1499 : *
1500 : * tuple_fraction is the fraction of tuples we expect will be retrieved.
1501 : * tuple_fraction is interpreted as follows:
1502 : * 0: expect all tuples to be retrieved (normal case)
1503 : * 0 < tuple_fraction < 1: expect the given fraction of tuples available
1504 : * from the plan to be retrieved
1505 : * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
1506 : * expected to be retrieved (ie, a LIMIT specification).
1507 : * setops is used for set operation subqueries to provide the subquery with
1508 : * the context in which it's being used so that Paths correctly sorted for the
1509 : * set operation can be generated. NULL when not planning a set operation
1510 : * child, or when a child of a set op that isn't interested in sorted input.
1511 : *
1512 : * Returns nothing; the useful output is in the Paths we attach to the
1513 : * (UPPERREL_FINAL, NULL) upperrel in *root. In addition,
1514 : * root->processed_tlist contains the final processed targetlist.
1515 : *
1516 : * Note that we have not done set_cheapest() on the final rel; it's convenient
1517 : * to leave this to the caller.
1518 : *--------------------
1519 : */
1520 : static void
1521 393047 : grouping_planner(PlannerInfo *root, double tuple_fraction,
1522 : SetOperationStmt *setops)
1523 : {
1524 393047 : Query *parse = root->parse;
1525 393047 : int64 offset_est = 0;
1526 393047 : int64 count_est = 0;
1527 393047 : double limit_tuples = -1.0;
1528 393047 : bool have_postponed_srfs = false;
1529 : PathTarget *final_target;
1530 : List *final_targets;
1531 : List *final_targets_contain_srfs;
1532 : bool final_target_parallel_safe;
1533 : RelOptInfo *current_rel;
1534 : RelOptInfo *final_rel;
1535 : FinalPathExtraData extra;
1536 : ListCell *lc;
1537 :
1538 : /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1539 393047 : if (parse->limitCount || parse->limitOffset)
1540 : {
1541 3689 : tuple_fraction = preprocess_limit(root, tuple_fraction,
1542 : &offset_est, &count_est);
1543 :
1544 : /*
1545 : * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1546 : * estimate the effects of using a bounded sort.
1547 : */
1548 3689 : if (count_est > 0 && offset_est >= 0)
1549 3227 : limit_tuples = (double) count_est + (double) offset_est;
1550 : }
1551 :
1552 : /* Make tuple_fraction accessible to lower-level routines */
1553 393047 : root->tuple_fraction = tuple_fraction;
1554 :
1555 393047 : if (parse->setOperations)
1556 : {
1557 : /*
1558 : * Construct Paths for set operations. The results will not need any
1559 : * work except perhaps a top-level sort and/or LIMIT. Note that any
1560 : * special work for recursive unions is the responsibility of
1561 : * plan_set_operations.
1562 : */
1563 4914 : current_rel = plan_set_operations(root);
1564 :
1565 : /*
1566 : * We should not need to call preprocess_targetlist, since we must be
1567 : * in a SELECT query node. Instead, use the processed_tlist returned
1568 : * by plan_set_operations (since this tells whether it returned any
1569 : * resjunk columns!), and transfer any sort key information from the
1570 : * original tlist.
1571 : */
1572 : Assert(parse->commandType == CMD_SELECT);
1573 :
1574 : /* for safety, copy processed_tlist instead of modifying in-place */
1575 4910 : root->processed_tlist =
1576 4910 : postprocess_setop_tlist(copyObject(root->processed_tlist),
1577 : parse->targetList);
1578 :
1579 : /* Also extract the PathTarget form of the setop result tlist */
1580 4910 : final_target = current_rel->cheapest_total_path->pathtarget;
1581 :
1582 : /* And check whether it's parallel safe */
1583 : final_target_parallel_safe =
1584 4910 : is_parallel_safe(root, (Node *) final_target->exprs);
1585 :
1586 : /* The setop result tlist couldn't contain any SRFs */
1587 : Assert(!parse->hasTargetSRFs);
1588 4910 : final_targets = final_targets_contain_srfs = NIL;
1589 :
1590 : /*
1591 : * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1592 : * checked already, but let's make sure).
1593 : */
1594 4910 : if (parse->rowMarks)
1595 0 : ereport(ERROR,
1596 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1597 : /*------
1598 : translator: %s is a SQL row locking clause such as FOR UPDATE */
1599 : errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1600 : LCS_asString(linitial_node(RowMarkClause,
1601 : parse->rowMarks)->strength))));
1602 :
1603 : /*
1604 : * Calculate pathkeys that represent result ordering requirements
1605 : */
1606 : Assert(parse->distinctClause == NIL);
1607 4910 : root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
1608 : parse->sortClause,
1609 : root->processed_tlist);
1610 : }
1611 : else
1612 : {
1613 : /* No set operations, do regular planning */
1614 : PathTarget *sort_input_target;
1615 : List *sort_input_targets;
1616 : List *sort_input_targets_contain_srfs;
1617 : bool sort_input_target_parallel_safe;
1618 : PathTarget *grouping_target;
1619 : List *grouping_targets;
1620 : List *grouping_targets_contain_srfs;
1621 : bool grouping_target_parallel_safe;
1622 : PathTarget *scanjoin_target;
1623 : List *scanjoin_targets;
1624 : List *scanjoin_targets_contain_srfs;
1625 : bool scanjoin_target_parallel_safe;
1626 : bool scanjoin_target_same_exprs;
1627 : bool have_grouping;
1628 388133 : WindowFuncLists *wflists = NULL;
1629 388133 : List *activeWindows = NIL;
1630 388133 : grouping_sets_data *gset_data = NULL;
1631 : standard_qp_extra qp_extra;
1632 :
1633 : /* A recursive query should always have setOperations */
1634 : Assert(!root->hasRecursion);
1635 :
1636 : /* Preprocess grouping sets and GROUP BY clause, if any */
1637 388133 : if (parse->groupingSets)
1638 : {
1639 855 : gset_data = preprocess_grouping_sets(root);
1640 : }
1641 387278 : else if (parse->groupClause)
1642 : {
1643 : /* Preprocess regular GROUP BY clause, if any */
1644 3265 : root->processed_groupClause = preprocess_groupclause(root, NIL);
1645 : }
1646 :
1647 : /*
1648 : * Preprocess targetlist. Note that much of the remaining planning
1649 : * work will be done with the PathTarget representation of tlists, but
1650 : * we must also maintain the full representation of the final tlist so
1651 : * that we can transfer its decoration (resnames etc) to the topmost
1652 : * tlist of the finished Plan. This is kept in processed_tlist.
1653 : */
1654 388129 : preprocess_targetlist(root);
1655 :
1656 : /*
1657 : * Mark all the aggregates with resolved aggtranstypes, and detect
1658 : * aggregates that are duplicates or can share transition state. We
1659 : * must do this before slicing and dicing the tlist into various
1660 : * pathtargets, else some copies of the Aggref nodes might escape
1661 : * being marked.
1662 : */
1663 388129 : if (parse->hasAggs)
1664 : {
1665 32907 : preprocess_aggrefs(root, (Node *) root->processed_tlist);
1666 32907 : preprocess_aggrefs(root, (Node *) parse->havingQual);
1667 : }
1668 :
1669 : /*
1670 : * Locate any window functions in the tlist. (We don't need to look
1671 : * anywhere else, since expressions used in ORDER BY will be in there
1672 : * too.) Note that they could all have been eliminated by constant
1673 : * folding, in which case we don't need to do any more work.
1674 : */
1675 388129 : if (parse->hasWindowFuncs)
1676 : {
1677 2197 : wflists = find_window_functions((Node *) root->processed_tlist,
1678 2197 : list_length(parse->windowClause));
1679 2197 : if (wflists->numWindowFuncs > 0)
1680 : {
1681 : /*
1682 : * See if any modifications can be made to each WindowClause
1683 : * to allow the executor to execute the WindowFuncs more
1684 : * quickly.
1685 : */
1686 2192 : optimize_window_clauses(root, wflists);
1687 :
1688 : /* Extract the list of windows actually in use. */
1689 2192 : activeWindows = select_active_windows(root, wflists);
1690 :
1691 : /* Make sure they all have names, for EXPLAIN's use. */
1692 2192 : name_active_windows(activeWindows);
1693 : }
1694 : else
1695 5 : parse->hasWindowFuncs = false;
1696 : }
1697 :
1698 : /*
1699 : * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1700 : * adding logic between here and the query_planner() call. Anything
1701 : * that is needed in MIN/MAX-optimizable cases will have to be
1702 : * duplicated in planagg.c.
1703 : */
1704 388129 : if (parse->hasAggs)
1705 32907 : preprocess_minmax_aggregates(root);
1706 :
1707 : /*
1708 : * Figure out whether there's a hard limit on the number of rows that
1709 : * query_planner's result subplan needs to return. Even if we know a
1710 : * hard limit overall, it doesn't apply if the query has any
1711 : * grouping/aggregation operations, or SRFs in the tlist.
1712 : */
1713 388129 : if (parse->groupClause ||
1714 384078 : parse->groupingSets ||
1715 384013 : parse->distinctClause ||
1716 382109 : parse->hasAggs ||
1717 352715 : parse->hasWindowFuncs ||
1718 350639 : parse->hasTargetSRFs ||
1719 341067 : root->hasHavingQual)
1720 47082 : root->limit_tuples = -1.0;
1721 : else
1722 341047 : root->limit_tuples = limit_tuples;
1723 :
1724 : /* Set up data needed by standard_qp_callback */
1725 388129 : qp_extra.activeWindows = activeWindows;
1726 388129 : qp_extra.gset_data = gset_data;
1727 :
1728 : /*
1729 : * If we're a subquery for a set operation, store the SetOperationStmt
1730 : * in qp_extra.
1731 : */
1732 388129 : qp_extra.setop = setops;
1733 :
1734 : /*
1735 : * Generate the best unsorted and presorted paths for the scan/join
1736 : * portion of this Query, ie the processing represented by the
1737 : * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1738 : * We also generate (in standard_qp_callback) pathkey representations
1739 : * of the query's sort clause, distinct clause, etc.
1740 : */
1741 388129 : current_rel = query_planner(root, standard_qp_callback, &qp_extra);
1742 :
1743 : /*
1744 : * Convert the query's result tlist into PathTarget format.
1745 : *
1746 : * Note: this cannot be done before query_planner() has performed
1747 : * appendrel expansion, because that might add resjunk entries to
1748 : * root->processed_tlist. Waiting till afterwards is also helpful
1749 : * because the target width estimates can use per-Var width numbers
1750 : * that were obtained within query_planner().
1751 : */
1752 388095 : final_target = create_pathtarget(root, root->processed_tlist);
1753 : final_target_parallel_safe =
1754 388095 : is_parallel_safe(root, (Node *) final_target->exprs);
1755 :
1756 : /*
1757 : * If ORDER BY was given, consider whether we should use a post-sort
1758 : * projection, and compute the adjusted target for preceding steps if
1759 : * so.
1760 : */
1761 388095 : if (parse->sortClause)
1762 : {
1763 57781 : sort_input_target = make_sort_input_target(root,
1764 : final_target,
1765 : &have_postponed_srfs);
1766 : sort_input_target_parallel_safe =
1767 57781 : is_parallel_safe(root, (Node *) sort_input_target->exprs);
1768 : }
1769 : else
1770 : {
1771 330314 : sort_input_target = final_target;
1772 330314 : sort_input_target_parallel_safe = final_target_parallel_safe;
1773 : }
1774 :
1775 : /*
1776 : * If we have window functions to deal with, the output from any
1777 : * grouping step needs to be what the window functions want;
1778 : * otherwise, it should be sort_input_target.
1779 : */
1780 388095 : if (activeWindows)
1781 : {
1782 2192 : grouping_target = make_window_input_target(root,
1783 : final_target,
1784 : activeWindows);
1785 : grouping_target_parallel_safe =
1786 2192 : is_parallel_safe(root, (Node *) grouping_target->exprs);
1787 : }
1788 : else
1789 : {
1790 385903 : grouping_target = sort_input_target;
1791 385903 : grouping_target_parallel_safe = sort_input_target_parallel_safe;
1792 : }
1793 :
1794 : /*
1795 : * If we have grouping or aggregation to do, the topmost scan/join
1796 : * plan node must emit what the grouping step wants; otherwise, it
1797 : * should emit grouping_target.
1798 : */
1799 384044 : have_grouping = (parse->groupClause || parse->groupingSets ||
1800 772139 : parse->hasAggs || root->hasHavingQual);
1801 388095 : if (have_grouping)
1802 : {
1803 33561 : scanjoin_target = make_group_input_target(root, final_target);
1804 : scanjoin_target_parallel_safe =
1805 33561 : is_parallel_safe(root, (Node *) scanjoin_target->exprs);
1806 : }
1807 : else
1808 : {
1809 354534 : scanjoin_target = grouping_target;
1810 354534 : scanjoin_target_parallel_safe = grouping_target_parallel_safe;
1811 : }
1812 :
1813 : /*
1814 : * If there are any SRFs in the targetlist, we must separate each of
1815 : * these PathTargets into SRF-computing and SRF-free targets. Replace
1816 : * each of the named targets with a SRF-free version, and remember the
1817 : * list of additional projection steps we need to add afterwards.
1818 : */
1819 388095 : if (parse->hasTargetSRFs)
1820 : {
1821 : /* final_target doesn't recompute any SRFs in sort_input_target */
1822 9905 : split_pathtarget_at_srfs(root, final_target, sort_input_target,
1823 : &final_targets,
1824 : &final_targets_contain_srfs);
1825 9905 : final_target = linitial_node(PathTarget, final_targets);
1826 : Assert(!linitial_int(final_targets_contain_srfs));
1827 : /* likewise for sort_input_target vs. grouping_target */
1828 9905 : split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
1829 : &sort_input_targets,
1830 : &sort_input_targets_contain_srfs);
1831 9905 : sort_input_target = linitial_node(PathTarget, sort_input_targets);
1832 : Assert(!linitial_int(sort_input_targets_contain_srfs));
1833 : /* likewise for grouping_target vs. scanjoin_target */
1834 9905 : split_pathtarget_at_srfs_grouping(root,
1835 : grouping_target, scanjoin_target,
1836 : &grouping_targets,
1837 : &grouping_targets_contain_srfs);
1838 9905 : grouping_target = linitial_node(PathTarget, grouping_targets);
1839 : Assert(!linitial_int(grouping_targets_contain_srfs));
1840 : /* scanjoin_target will not have any SRFs precomputed for it */
1841 9905 : split_pathtarget_at_srfs(root, scanjoin_target, NULL,
1842 : &scanjoin_targets,
1843 : &scanjoin_targets_contain_srfs);
1844 9905 : scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
1845 : Assert(!linitial_int(scanjoin_targets_contain_srfs));
1846 : }
1847 : else
1848 : {
1849 : /* initialize lists; for most of these, dummy values are OK */
1850 378190 : final_targets = final_targets_contain_srfs = NIL;
1851 378190 : sort_input_targets = sort_input_targets_contain_srfs = NIL;
1852 378190 : grouping_targets = grouping_targets_contain_srfs = NIL;
1853 378190 : scanjoin_targets = list_make1(scanjoin_target);
1854 378190 : scanjoin_targets_contain_srfs = NIL;
1855 : }
1856 :
1857 : /* Apply scan/join target. */
1858 388095 : scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
1859 388095 : && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
1860 388095 : apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
1861 : scanjoin_targets_contain_srfs,
1862 : scanjoin_target_parallel_safe,
1863 : scanjoin_target_same_exprs);
1864 :
1865 : /*
1866 : * Save the various upper-rel PathTargets we just computed into
1867 : * root->upper_targets[]. The core code doesn't use this, but it
1868 : * provides a convenient place for extensions to get at the info. For
1869 : * consistency, we save all the intermediate targets, even though some
1870 : * of the corresponding upperrels might not be needed for this query.
1871 : */
1872 388095 : root->upper_targets[UPPERREL_FINAL] = final_target;
1873 388095 : root->upper_targets[UPPERREL_ORDERED] = final_target;
1874 388095 : root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
1875 388095 : root->upper_targets[UPPERREL_PARTIAL_DISTINCT] = sort_input_target;
1876 388095 : root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
1877 388095 : root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
1878 :
1879 : /*
1880 : * If we have grouping and/or aggregation, consider ways to implement
1881 : * that. We build a new upperrel representing the output of this
1882 : * phase.
1883 : */
1884 388095 : if (have_grouping)
1885 : {
1886 33561 : current_rel = create_grouping_paths(root,
1887 : current_rel,
1888 : grouping_target,
1889 : grouping_target_parallel_safe,
1890 : gset_data);
1891 : /* Fix things up if grouping_target contains SRFs */
1892 33557 : if (parse->hasTargetSRFs)
1893 298 : adjust_paths_for_srfs(root, current_rel,
1894 : grouping_targets,
1895 : grouping_targets_contain_srfs);
1896 : }
1897 :
1898 : /*
1899 : * If we have window functions, consider ways to implement those. We
1900 : * build a new upperrel representing the output of this phase.
1901 : */
1902 388091 : if (activeWindows)
1903 : {
1904 2192 : current_rel = create_window_paths(root,
1905 : current_rel,
1906 : grouping_target,
1907 : sort_input_target,
1908 : sort_input_target_parallel_safe,
1909 : wflists,
1910 : activeWindows);
1911 : /* Fix things up if sort_input_target contains SRFs */
1912 2192 : if (parse->hasTargetSRFs)
1913 10 : adjust_paths_for_srfs(root, current_rel,
1914 : sort_input_targets,
1915 : sort_input_targets_contain_srfs);
1916 : }
1917 :
1918 : /*
1919 : * If there is a DISTINCT clause, consider ways to implement that. We
1920 : * build a new upperrel representing the output of this phase.
1921 : */
1922 388091 : if (parse->distinctClause)
1923 : {
1924 1931 : current_rel = create_distinct_paths(root,
1925 : current_rel,
1926 : sort_input_target);
1927 : }
1928 : } /* end of if (setOperations) */
1929 :
1930 : /*
1931 : * If ORDER BY was given, consider ways to implement that, and generate a
1932 : * new upperrel containing only paths that emit the correct ordering and
1933 : * project the correct final_target. We can apply the original
1934 : * limit_tuples limit in sort costing here, but only if there are no
1935 : * postponed SRFs.
1936 : */
1937 393001 : if (parse->sortClause)
1938 : {
1939 61038 : current_rel = create_ordered_paths(root,
1940 : current_rel,
1941 : final_target,
1942 : final_target_parallel_safe,
1943 : have_postponed_srfs ? -1.0 :
1944 : limit_tuples);
1945 : /* Fix things up if final_target contains SRFs */
1946 61038 : if (parse->hasTargetSRFs)
1947 182 : adjust_paths_for_srfs(root, current_rel,
1948 : final_targets,
1949 : final_targets_contain_srfs);
1950 : }
1951 :
1952 : /*
1953 : * Now we are prepared to build the final-output upperrel.
1954 : */
1955 393001 : final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1956 :
1957 : /*
1958 : * If the input rel is marked consider_parallel and there's nothing that's
1959 : * not parallel-safe in the LIMIT clause, then the final_rel can be marked
1960 : * consider_parallel as well. Note that if the query has rowMarks or is
1961 : * not a SELECT, consider_parallel will be false for every relation in the
1962 : * query.
1963 : */
1964 530764 : if (current_rel->consider_parallel &&
1965 275506 : is_parallel_safe(root, parse->limitOffset) &&
1966 137743 : is_parallel_safe(root, parse->limitCount))
1967 137738 : final_rel->consider_parallel = true;
1968 :
1969 : /*
1970 : * If the current_rel belongs to a single FDW, so does the final_rel.
1971 : */
1972 393001 : final_rel->serverid = current_rel->serverid;
1973 393001 : final_rel->userid = current_rel->userid;
1974 393001 : final_rel->useridiscurrent = current_rel->useridiscurrent;
1975 393001 : final_rel->fdwroutine = current_rel->fdwroutine;
1976 :
1977 : /*
1978 : * Generate paths for the final_rel. Insert all surviving paths, with
1979 : * LockRows, Limit, and/or ModifyTable steps added if needed.
1980 : */
1981 802012 : foreach(lc, current_rel->pathlist)
1982 : {
1983 409011 : Path *path = (Path *) lfirst(lc);
1984 :
1985 : /*
1986 : * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
1987 : * (Note: we intentionally test parse->rowMarks not root->rowMarks
1988 : * here. If there are only non-locking rowmarks, they should be
1989 : * handled by the ModifyTable node instead. However, root->rowMarks
1990 : * is what goes into the LockRows node.)
1991 : */
1992 409011 : if (parse->rowMarks)
1993 : {
1994 8763 : path = (Path *) create_lockrows_path(root, final_rel, path,
1995 : root->rowMarks,
1996 : assign_special_exec_param(root));
1997 : }
1998 :
1999 : /*
2000 : * If there is a LIMIT/OFFSET clause, add the LIMIT node.
2001 : */
2002 409011 : if (limit_needed(parse))
2003 : {
2004 4162 : path = (Path *) create_limit_path(root, final_rel, path,
2005 : parse->limitOffset,
2006 : parse->limitCount,
2007 : parse->limitOption,
2008 : offset_est, count_est);
2009 : }
2010 :
2011 : /*
2012 : * If this is an INSERT/UPDATE/DELETE/MERGE, add the ModifyTable node.
2013 : */
2014 409011 : if (parse->commandType != CMD_SELECT)
2015 : {
2016 : Index rootRelation;
2017 62918 : List *resultRelations = NIL;
2018 62918 : List *updateColnosLists = NIL;
2019 62918 : List *withCheckOptionLists = NIL;
2020 62918 : List *returningLists = NIL;
2021 62918 : List *mergeActionLists = NIL;
2022 62918 : List *mergeJoinConditions = NIL;
2023 : List *rowMarks;
2024 :
2025 62918 : if (bms_membership(root->all_result_relids) == BMS_MULTIPLE)
2026 : {
2027 : /* Inherited UPDATE/DELETE/MERGE */
2028 2218 : RelOptInfo *top_result_rel = find_base_rel(root,
2029 : parse->resultRelation);
2030 2218 : int resultRelation = -1;
2031 :
2032 : /* Pass the root result rel forward to the executor. */
2033 2218 : rootRelation = parse->resultRelation;
2034 :
2035 : /* Add only leaf children to ModifyTable. */
2036 6558 : while ((resultRelation = bms_next_member(root->leaf_result_relids,
2037 6558 : resultRelation)) >= 0)
2038 : {
2039 4340 : RelOptInfo *this_result_rel = find_base_rel(root,
2040 : resultRelation);
2041 :
2042 : /*
2043 : * Also exclude any leaf rels that have turned dummy since
2044 : * being added to the list, for example, by being excluded
2045 : * by constraint exclusion.
2046 : */
2047 4340 : if (IS_DUMMY_REL(this_result_rel))
2048 153 : continue;
2049 :
2050 : /* Build per-target-rel lists needed by ModifyTable */
2051 4187 : resultRelations = lappend_int(resultRelations,
2052 : resultRelation);
2053 4187 : if (parse->commandType == CMD_UPDATE)
2054 : {
2055 2853 : List *update_colnos = root->update_colnos;
2056 :
2057 2853 : if (this_result_rel != top_result_rel)
2058 : update_colnos =
2059 2853 : adjust_inherited_attnums_multilevel(root,
2060 : update_colnos,
2061 : this_result_rel->relid,
2062 : top_result_rel->relid);
2063 2853 : updateColnosLists = lappend(updateColnosLists,
2064 : update_colnos);
2065 : }
2066 4187 : if (parse->withCheckOptions)
2067 : {
2068 416 : List *withCheckOptions = parse->withCheckOptions;
2069 :
2070 416 : if (this_result_rel != top_result_rel)
2071 : withCheckOptions = (List *)
2072 416 : adjust_appendrel_attrs_multilevel(root,
2073 : (Node *) withCheckOptions,
2074 : this_result_rel,
2075 : top_result_rel);
2076 416 : withCheckOptionLists = lappend(withCheckOptionLists,
2077 : withCheckOptions);
2078 : }
2079 4187 : if (parse->returningList)
2080 : {
2081 645 : List *returningList = parse->returningList;
2082 :
2083 645 : if (this_result_rel != top_result_rel)
2084 : returningList = (List *)
2085 645 : adjust_appendrel_attrs_multilevel(root,
2086 : (Node *) returningList,
2087 : this_result_rel,
2088 : top_result_rel);
2089 645 : returningLists = lappend(returningLists,
2090 : returningList);
2091 : }
2092 4187 : if (parse->mergeActionList)
2093 : {
2094 : ListCell *l;
2095 425 : List *mergeActionList = NIL;
2096 :
2097 : /*
2098 : * Copy MergeActions and translate stuff that
2099 : * references attribute numbers.
2100 : */
2101 1322 : foreach(l, parse->mergeActionList)
2102 : {
2103 897 : MergeAction *action = lfirst(l),
2104 897 : *leaf_action = copyObject(action);
2105 :
2106 897 : leaf_action->qual =
2107 897 : adjust_appendrel_attrs_multilevel(root,
2108 : (Node *) action->qual,
2109 : this_result_rel,
2110 : top_result_rel);
2111 897 : leaf_action->targetList = (List *)
2112 897 : adjust_appendrel_attrs_multilevel(root,
2113 897 : (Node *) action->targetList,
2114 : this_result_rel,
2115 : top_result_rel);
2116 897 : if (leaf_action->commandType == CMD_UPDATE)
2117 491 : leaf_action->updateColnos =
2118 491 : adjust_inherited_attnums_multilevel(root,
2119 : action->updateColnos,
2120 : this_result_rel->relid,
2121 : top_result_rel->relid);
2122 897 : mergeActionList = lappend(mergeActionList,
2123 : leaf_action);
2124 : }
2125 :
2126 425 : mergeActionLists = lappend(mergeActionLists,
2127 : mergeActionList);
2128 : }
2129 4187 : if (parse->commandType == CMD_MERGE)
2130 : {
2131 425 : Node *mergeJoinCondition = parse->mergeJoinCondition;
2132 :
2133 425 : if (this_result_rel != top_result_rel)
2134 : mergeJoinCondition =
2135 425 : adjust_appendrel_attrs_multilevel(root,
2136 : mergeJoinCondition,
2137 : this_result_rel,
2138 : top_result_rel);
2139 425 : mergeJoinConditions = lappend(mergeJoinConditions,
2140 : mergeJoinCondition);
2141 : }
2142 : }
2143 :
2144 2218 : if (resultRelations == NIL)
2145 : {
2146 : /*
2147 : * We managed to exclude every child rel, so generate a
2148 : * dummy one-relation plan using info for the top target
2149 : * rel (even though that may not be a leaf target).
2150 : * Although it's clear that no data will be updated or
2151 : * deleted, we still need to have a ModifyTable node so
2152 : * that any statement triggers will be executed. (This
2153 : * could be cleaner if we fixed nodeModifyTable.c to allow
2154 : * zero target relations, but that probably wouldn't be a
2155 : * net win.)
2156 : */
2157 28 : resultRelations = list_make1_int(parse->resultRelation);
2158 28 : if (parse->commandType == CMD_UPDATE)
2159 26 : updateColnosLists = list_make1(root->update_colnos);
2160 28 : if (parse->withCheckOptions)
2161 0 : withCheckOptionLists = list_make1(parse->withCheckOptions);
2162 28 : if (parse->returningList)
2163 15 : returningLists = list_make1(parse->returningList);
2164 28 : if (parse->mergeActionList)
2165 1 : mergeActionLists = list_make1(parse->mergeActionList);
2166 28 : if (parse->commandType == CMD_MERGE)
2167 1 : mergeJoinConditions = list_make1(parse->mergeJoinCondition);
2168 : }
2169 : }
2170 : else
2171 : {
2172 : /* Single-relation INSERT/UPDATE/DELETE/MERGE. */
2173 60700 : rootRelation = 0; /* there's no separate root rel */
2174 60700 : resultRelations = list_make1_int(parse->resultRelation);
2175 60700 : if (parse->commandType == CMD_UPDATE)
2176 8200 : updateColnosLists = list_make1(root->update_colnos);
2177 60700 : if (parse->withCheckOptions)
2178 889 : withCheckOptionLists = list_make1(parse->withCheckOptions);
2179 60700 : if (parse->returningList)
2180 2128 : returningLists = list_make1(parse->returningList);
2181 60700 : if (parse->mergeActionList)
2182 1281 : mergeActionLists = list_make1(parse->mergeActionList);
2183 60700 : if (parse->commandType == CMD_MERGE)
2184 1281 : mergeJoinConditions = list_make1(parse->mergeJoinCondition);
2185 : }
2186 :
2187 : /*
2188 : * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
2189 : * will have dealt with fetching non-locked marked rows, else we
2190 : * need to have ModifyTable do that.
2191 : */
2192 62918 : if (parse->rowMarks)
2193 0 : rowMarks = NIL;
2194 : else
2195 62918 : rowMarks = root->rowMarks;
2196 :
2197 : path = (Path *)
2198 62918 : create_modifytable_path(root, final_rel,
2199 : path,
2200 : parse->commandType,
2201 62918 : parse->canSetTag,
2202 62918 : parse->resultRelation,
2203 : rootRelation,
2204 : resultRelations,
2205 : updateColnosLists,
2206 : withCheckOptionLists,
2207 : returningLists,
2208 : rowMarks,
2209 : parse->onConflict,
2210 : mergeActionLists,
2211 : mergeJoinConditions,
2212 : assign_special_exec_param(root));
2213 : }
2214 :
2215 : /* And shove it into final_rel */
2216 409011 : add_path(final_rel, path);
2217 : }
2218 :
2219 : /*
2220 : * Generate partial paths for final_rel, too, if outer query levels might
2221 : * be able to make use of them.
2222 : */
2223 393001 : if (final_rel->consider_parallel && root->query_level > 1 &&
2224 24646 : !limit_needed(parse))
2225 : {
2226 : Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
2227 24585 : foreach(lc, current_rel->partial_pathlist)
2228 : {
2229 112 : Path *partial_path = (Path *) lfirst(lc);
2230 :
2231 112 : add_partial_path(final_rel, partial_path);
2232 : }
2233 : }
2234 :
2235 393001 : extra.limit_needed = limit_needed(parse);
2236 393001 : extra.limit_tuples = limit_tuples;
2237 393001 : extra.count_est = count_est;
2238 393001 : extra.offset_est = offset_est;
2239 :
2240 : /*
2241 : * If there is an FDW that's responsible for all baserels of the query,
2242 : * let it consider adding ForeignPaths.
2243 : */
2244 393001 : if (final_rel->fdwroutine &&
2245 633 : final_rel->fdwroutine->GetForeignUpperPaths)
2246 596 : final_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_FINAL,
2247 : current_rel, final_rel,
2248 : &extra);
2249 :
2250 : /* Let extensions possibly add some more paths */
2251 393001 : if (create_upper_paths_hook)
2252 0 : (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2253 : current_rel, final_rel, &extra);
2254 :
2255 : /* Note: currently, we leave it to callers to do set_cheapest() */
2256 393001 : }
2257 :
2258 : /*
2259 : * Do preprocessing for groupingSets clause and related data.
2260 : *
2261 : * We expect that parse->groupingSets has already been expanded into a flat
2262 : * list of grouping sets (that is, just integer Lists of ressortgroupref
2263 : * numbers) by expand_grouping_sets(). This function handles the preliminary
2264 : * steps of organizing the grouping sets into lists of rollups, and preparing
2265 : * annotations which will later be filled in with size estimates.
2266 : */
2267 : static grouping_sets_data *
2268 855 : preprocess_grouping_sets(PlannerInfo *root)
2269 : {
2270 855 : Query *parse = root->parse;
2271 : List *sets;
2272 855 : int maxref = 0;
2273 : ListCell *lc_set;
2274 855 : grouping_sets_data *gd = palloc0_object(grouping_sets_data);
2275 :
2276 : /*
2277 : * We don't currently make any attempt to optimize the groupClause when
2278 : * there are grouping sets, so just duplicate it in processed_groupClause.
2279 : */
2280 855 : root->processed_groupClause = parse->groupClause;
2281 :
2282 : /* Detect unhashable and unsortable grouping expressions */
2283 855 : gd->any_hashable = false;
2284 855 : gd->unhashable_refs = NULL;
2285 855 : gd->unsortable_refs = NULL;
2286 855 : gd->unsortable_sets = NIL;
2287 :
2288 855 : if (parse->groupClause)
2289 : {
2290 : ListCell *lc;
2291 :
2292 2501 : foreach(lc, parse->groupClause)
2293 : {
2294 1711 : SortGroupClause *gc = lfirst_node(SortGroupClause, lc);
2295 1711 : Index ref = gc->tleSortGroupRef;
2296 :
2297 1711 : if (ref > maxref)
2298 1671 : maxref = ref;
2299 :
2300 1711 : if (!gc->hashable)
2301 24 : gd->unhashable_refs = bms_add_member(gd->unhashable_refs, ref);
2302 :
2303 1711 : if (!OidIsValid(gc->sortop))
2304 33 : gd->unsortable_refs = bms_add_member(gd->unsortable_refs, ref);
2305 : }
2306 : }
2307 :
2308 : /* Allocate workspace array for remapping */
2309 855 : gd->tleref_to_colnum_map = (int *) palloc((maxref + 1) * sizeof(int));
2310 :
2311 : /*
2312 : * If we have any unsortable sets, we must extract them before trying to
2313 : * prepare rollups. Unsortable sets don't go through
2314 : * reorder_grouping_sets, so we must apply the GroupingSetData annotation
2315 : * here.
2316 : */
2317 855 : if (!bms_is_empty(gd->unsortable_refs))
2318 : {
2319 33 : List *sortable_sets = NIL;
2320 : ListCell *lc;
2321 :
2322 99 : foreach(lc, parse->groupingSets)
2323 : {
2324 70 : List *gset = (List *) lfirst(lc);
2325 :
2326 70 : if (bms_overlap_list(gd->unsortable_refs, gset))
2327 : {
2328 38 : GroupingSetData *gs = makeNode(GroupingSetData);
2329 :
2330 38 : gs->set = gset;
2331 38 : gd->unsortable_sets = lappend(gd->unsortable_sets, gs);
2332 :
2333 : /*
2334 : * We must enforce here that an unsortable set is hashable;
2335 : * later code assumes this. Parse analysis only checks that
2336 : * every individual column is either hashable or sortable.
2337 : *
2338 : * Note that passing this test doesn't guarantee we can
2339 : * generate a plan; there might be other showstoppers.
2340 : */
2341 38 : if (bms_overlap_list(gd->unhashable_refs, gset))
2342 4 : ereport(ERROR,
2343 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2344 : errmsg("could not implement GROUP BY"),
2345 : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2346 : }
2347 : else
2348 32 : sortable_sets = lappend(sortable_sets, gset);
2349 : }
2350 :
2351 29 : if (sortable_sets)
2352 24 : sets = extract_rollup_sets(sortable_sets);
2353 : else
2354 5 : sets = NIL;
2355 : }
2356 : else
2357 822 : sets = extract_rollup_sets(parse->groupingSets);
2358 :
2359 2226 : foreach(lc_set, sets)
2360 : {
2361 1375 : List *current_sets = (List *) lfirst(lc_set);
2362 1375 : RollupData *rollup = makeNode(RollupData);
2363 : GroupingSetData *gs;
2364 :
2365 : /*
2366 : * Reorder the current list of grouping sets into correct prefix
2367 : * order. If only one aggregation pass is needed, try to make the
2368 : * list match the ORDER BY clause; if more than one pass is needed, we
2369 : * don't bother with that.
2370 : *
2371 : * Note that this reorders the sets from smallest-member-first to
2372 : * largest-member-first, and applies the GroupingSetData annotations,
2373 : * though the data will be filled in later.
2374 : */
2375 1375 : current_sets = reorder_grouping_sets(current_sets,
2376 1375 : (list_length(sets) == 1
2377 : ? parse->sortClause
2378 : : NIL));
2379 :
2380 : /*
2381 : * Get the initial (and therefore largest) grouping set.
2382 : */
2383 1375 : gs = linitial_node(GroupingSetData, current_sets);
2384 :
2385 : /*
2386 : * Order the groupClause appropriately. If the first grouping set is
2387 : * empty, then the groupClause must also be empty; otherwise we have
2388 : * to force the groupClause to match that grouping set's order.
2389 : *
2390 : * (The first grouping set can be empty even though parse->groupClause
2391 : * is not empty only if all non-empty grouping sets are unsortable.
2392 : * The groupClauses for hashed grouping sets are built later on.)
2393 : */
2394 1375 : if (gs->set)
2395 1310 : rollup->groupClause = preprocess_groupclause(root, gs->set);
2396 : else
2397 65 : rollup->groupClause = NIL;
2398 :
2399 : /*
2400 : * Is it hashable? We pretend empty sets are hashable even though we
2401 : * actually force them not to be hashed later. But don't bother if
2402 : * there's nothing but empty sets (since in that case we can't hash
2403 : * anything).
2404 : */
2405 1375 : if (gs->set &&
2406 1310 : !bms_overlap_list(gd->unhashable_refs, gs->set))
2407 : {
2408 1290 : rollup->hashable = true;
2409 1290 : gd->any_hashable = true;
2410 : }
2411 :
2412 : /*
2413 : * Now that we've pinned down an order for the groupClause for this
2414 : * list of grouping sets, we need to remap the entries in the grouping
2415 : * sets from sortgrouprefs to plain indices (0-based) into the
2416 : * groupClause for this collection of grouping sets. We keep the
2417 : * original form for later use, though.
2418 : */
2419 1375 : rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
2420 : current_sets,
2421 : gd->tleref_to_colnum_map);
2422 1375 : rollup->gsets_data = current_sets;
2423 :
2424 1375 : gd->rollups = lappend(gd->rollups, rollup);
2425 : }
2426 :
2427 851 : if (gd->unsortable_sets)
2428 : {
2429 : /*
2430 : * We have not yet pinned down a groupclause for this, but we will
2431 : * need index-based lists for estimation purposes. Construct
2432 : * hash_sets_idx based on the entire original groupclause for now.
2433 : */
2434 29 : gd->hash_sets_idx = remap_to_groupclause_idx(parse->groupClause,
2435 : gd->unsortable_sets,
2436 : gd->tleref_to_colnum_map);
2437 29 : gd->any_hashable = true;
2438 : }
2439 :
2440 851 : return gd;
2441 : }
2442 :
2443 : /*
2444 : * Given a groupclause and a list of GroupingSetData, return equivalent sets
2445 : * (without annotation) mapped to indexes into the given groupclause.
2446 : */
2447 : static List *
2448 3867 : remap_to_groupclause_idx(List *groupClause,
2449 : List *gsets,
2450 : int *tleref_to_colnum_map)
2451 : {
2452 3867 : int ref = 0;
2453 3867 : List *result = NIL;
2454 : ListCell *lc;
2455 :
2456 9301 : foreach(lc, groupClause)
2457 : {
2458 5434 : SortGroupClause *gc = lfirst_node(SortGroupClause, lc);
2459 :
2460 5434 : tleref_to_colnum_map[gc->tleSortGroupRef] = ref++;
2461 : }
2462 :
2463 8884 : foreach(lc, gsets)
2464 : {
2465 5017 : List *set = NIL;
2466 : ListCell *lc2;
2467 5017 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
2468 :
2469 11160 : foreach(lc2, gs->set)
2470 : {
2471 6143 : set = lappend_int(set, tleref_to_colnum_map[lfirst_int(lc2)]);
2472 : }
2473 :
2474 5017 : result = lappend(result, set);
2475 : }
2476 :
2477 3867 : return result;
2478 : }
2479 :
2480 :
2481 : /*
2482 : * preprocess_rowmarks - set up PlanRowMarks if needed
2483 : */
2484 : static void
2485 395680 : preprocess_rowmarks(PlannerInfo *root)
2486 : {
2487 395680 : Query *parse = root->parse;
2488 : Bitmapset *rels;
2489 : List *prowmarks;
2490 : ListCell *l;
2491 : int i;
2492 :
2493 395680 : if (parse->rowMarks)
2494 : {
2495 : /*
2496 : * We've got trouble if FOR [KEY] UPDATE/SHARE appears inside
2497 : * grouping, since grouping renders a reference to individual tuple
2498 : * CTIDs invalid. This is also checked at parse time, but that's
2499 : * insufficient because of rule substitution, query pullup, etc.
2500 : */
2501 8516 : CheckSelectLocking(parse, linitial_node(RowMarkClause,
2502 : parse->rowMarks)->strength);
2503 : }
2504 : else
2505 : {
2506 : /*
2507 : * We only need rowmarks for UPDATE, DELETE, MERGE, or FOR [KEY]
2508 : * UPDATE/SHARE.
2509 : */
2510 387164 : if (parse->commandType != CMD_UPDATE &&
2511 377429 : parse->commandType != CMD_DELETE &&
2512 374192 : parse->commandType != CMD_MERGE)
2513 372717 : return;
2514 : }
2515 :
2516 : /*
2517 : * We need to have rowmarks for all base relations except the target. We
2518 : * make a bitmapset of all base rels and then remove the items we don't
2519 : * need or have FOR [KEY] UPDATE/SHARE marks for.
2520 : */
2521 22963 : rels = get_relids_in_jointree((Node *) parse->jointree, false, false);
2522 22963 : if (parse->resultRelation)
2523 14447 : rels = bms_del_member(rels, parse->resultRelation);
2524 :
2525 : /*
2526 : * Convert RowMarkClauses to PlanRowMark representation.
2527 : */
2528 22963 : prowmarks = NIL;
2529 31614 : foreach(l, parse->rowMarks)
2530 : {
2531 8651 : RowMarkClause *rc = lfirst_node(RowMarkClause, l);
2532 8651 : RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
2533 : PlanRowMark *newrc;
2534 :
2535 : /*
2536 : * Currently, it is syntactically impossible to have FOR UPDATE et al
2537 : * applied to an update/delete target rel. If that ever becomes
2538 : * possible, we should drop the target from the PlanRowMark list.
2539 : */
2540 : Assert(rc->rti != parse->resultRelation);
2541 :
2542 : /*
2543 : * Ignore RowMarkClauses for subqueries; they aren't real tables and
2544 : * can't support true locking. Subqueries that got flattened into the
2545 : * main query should be ignored completely. Any that didn't will get
2546 : * ROW_MARK_COPY items in the next loop.
2547 : */
2548 8651 : if (rte->rtekind != RTE_RELATION)
2549 46 : continue;
2550 :
2551 8605 : rels = bms_del_member(rels, rc->rti);
2552 :
2553 8605 : newrc = makeNode(PlanRowMark);
2554 8605 : newrc->rti = newrc->prti = rc->rti;
2555 8605 : newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2556 8605 : newrc->markType = select_rowmark_type(rte, rc->strength);
2557 8605 : newrc->allMarkTypes = (1 << newrc->markType);
2558 8605 : newrc->strength = rc->strength;
2559 8605 : newrc->waitPolicy = rc->waitPolicy;
2560 8605 : newrc->isParent = false;
2561 :
2562 8605 : prowmarks = lappend(prowmarks, newrc);
2563 : }
2564 :
2565 : /*
2566 : * Now, add rowmarks for any non-target, non-locked base relations.
2567 : */
2568 22963 : i = 0;
2569 54393 : foreach(l, parse->rtable)
2570 : {
2571 31430 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
2572 : PlanRowMark *newrc;
2573 :
2574 31430 : i++;
2575 31430 : if (!bms_is_member(i, rels))
2576 28517 : continue;
2577 :
2578 2913 : newrc = makeNode(PlanRowMark);
2579 2913 : newrc->rti = newrc->prti = i;
2580 2913 : newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2581 2913 : newrc->markType = select_rowmark_type(rte, LCS_NONE);
2582 2913 : newrc->allMarkTypes = (1 << newrc->markType);
2583 2913 : newrc->strength = LCS_NONE;
2584 2913 : newrc->waitPolicy = LockWaitBlock; /* doesn't matter */
2585 2913 : newrc->isParent = false;
2586 :
2587 2913 : prowmarks = lappend(prowmarks, newrc);
2588 : }
2589 :
2590 22963 : root->rowMarks = prowmarks;
2591 : }
2592 :
2593 : /*
2594 : * Select RowMarkType to use for a given table
2595 : */
2596 : RowMarkType
2597 13412 : select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength)
2598 : {
2599 13412 : if (rte->rtekind != RTE_RELATION)
2600 : {
2601 : /* If it's not a table at all, use ROW_MARK_COPY */
2602 1089 : return ROW_MARK_COPY;
2603 : }
2604 12323 : else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2605 : {
2606 : /* Let the FDW select the rowmark type, if it wants to */
2607 114 : FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2608 :
2609 114 : if (fdwroutine->GetForeignRowMarkType != NULL)
2610 0 : return fdwroutine->GetForeignRowMarkType(rte, strength);
2611 : /* Otherwise, use ROW_MARK_COPY by default */
2612 114 : return ROW_MARK_COPY;
2613 : }
2614 : else
2615 : {
2616 : /* Regular table, apply the appropriate lock type */
2617 12209 : switch (strength)
2618 : {
2619 2033 : case LCS_NONE:
2620 :
2621 : /*
2622 : * We don't need a tuple lock, only the ability to re-fetch
2623 : * the row.
2624 : */
2625 2033 : return ROW_MARK_REFERENCE;
2626 : break;
2627 9084 : case LCS_FORKEYSHARE:
2628 9084 : return ROW_MARK_KEYSHARE;
2629 : break;
2630 201 : case LCS_FORSHARE:
2631 201 : return ROW_MARK_SHARE;
2632 : break;
2633 41 : case LCS_FORNOKEYUPDATE:
2634 41 : return ROW_MARK_NOKEYEXCLUSIVE;
2635 : break;
2636 850 : case LCS_FORUPDATE:
2637 850 : return ROW_MARK_EXCLUSIVE;
2638 : break;
2639 : }
2640 0 : elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2641 : return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2642 : }
2643 : }
2644 :
2645 : /*
2646 : * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
2647 : *
2648 : * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
2649 : * results back in *count_est and *offset_est. These variables are set to
2650 : * 0 if the corresponding clause is not present, and -1 if it's present
2651 : * but we couldn't estimate the value for it. (The "0" convention is OK
2652 : * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
2653 : * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
2654 : * usual practice of never estimating less than one row.) These values will
2655 : * be passed to create_limit_path, which see if you change this code.
2656 : *
2657 : * The return value is the suitably adjusted tuple_fraction to use for
2658 : * planning the query. This adjustment is not overridable, since it reflects
2659 : * plan actions that grouping_planner() will certainly take, not assumptions
2660 : * about context.
2661 : */
2662 : static double
2663 3689 : preprocess_limit(PlannerInfo *root, double tuple_fraction,
2664 : int64 *offset_est, int64 *count_est)
2665 : {
2666 3689 : Query *parse = root->parse;
2667 : Node *est;
2668 : double limit_fraction;
2669 :
2670 : /* Should not be called unless LIMIT or OFFSET */
2671 : Assert(parse->limitCount || parse->limitOffset);
2672 :
2673 : /*
2674 : * Try to obtain the clause values. We use estimate_expression_value
2675 : * primarily because it can sometimes do something useful with Params.
2676 : */
2677 3689 : if (parse->limitCount)
2678 : {
2679 3247 : est = estimate_expression_value(root, parse->limitCount);
2680 3247 : if (est && IsA(est, Const))
2681 : {
2682 3242 : if (((Const *) est)->constisnull)
2683 : {
2684 : /* NULL indicates LIMIT ALL, ie, no limit */
2685 0 : *count_est = 0; /* treat as not present */
2686 : }
2687 : else
2688 : {
2689 3242 : *count_est = DatumGetInt64(((Const *) est)->constvalue);
2690 3242 : if (*count_est <= 0)
2691 190 : *count_est = 1; /* force to at least 1 */
2692 : }
2693 : }
2694 : else
2695 5 : *count_est = -1; /* can't estimate */
2696 : }
2697 : else
2698 442 : *count_est = 0; /* not present */
2699 :
2700 3689 : if (parse->limitOffset)
2701 : {
2702 652 : est = estimate_expression_value(root, parse->limitOffset);
2703 652 : if (est && IsA(est, Const))
2704 : {
2705 632 : if (((Const *) est)->constisnull)
2706 : {
2707 : /* Treat NULL as no offset; the executor will too */
2708 0 : *offset_est = 0; /* treat as not present */
2709 : }
2710 : else
2711 : {
2712 632 : *offset_est = DatumGetInt64(((Const *) est)->constvalue);
2713 632 : if (*offset_est < 0)
2714 0 : *offset_est = 0; /* treat as not present */
2715 : }
2716 : }
2717 : else
2718 20 : *offset_est = -1; /* can't estimate */
2719 : }
2720 : else
2721 3037 : *offset_est = 0; /* not present */
2722 :
2723 3689 : if (*count_est != 0)
2724 : {
2725 : /*
2726 : * A LIMIT clause limits the absolute number of tuples returned.
2727 : * However, if it's not a constant LIMIT then we have to guess; for
2728 : * lack of a better idea, assume 10% of the plan's result is wanted.
2729 : */
2730 3247 : if (*count_est < 0 || *offset_est < 0)
2731 : {
2732 : /* LIMIT or OFFSET is an expression ... punt ... */
2733 20 : limit_fraction = 0.10;
2734 : }
2735 : else
2736 : {
2737 : /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
2738 3227 : limit_fraction = (double) *count_est + (double) *offset_est;
2739 : }
2740 :
2741 : /*
2742 : * If we have absolute limits from both caller and LIMIT, use the
2743 : * smaller value; likewise if they are both fractional. If one is
2744 : * fractional and the other absolute, we can't easily determine which
2745 : * is smaller, but we use the heuristic that the absolute will usually
2746 : * be smaller.
2747 : */
2748 3247 : if (tuple_fraction >= 1.0)
2749 : {
2750 5 : if (limit_fraction >= 1.0)
2751 : {
2752 : /* both absolute */
2753 5 : tuple_fraction = Min(tuple_fraction, limit_fraction);
2754 : }
2755 : else
2756 : {
2757 : /* caller absolute, limit fractional; use caller's value */
2758 : }
2759 : }
2760 3242 : else if (tuple_fraction > 0.0)
2761 : {
2762 82 : if (limit_fraction >= 1.0)
2763 : {
2764 : /* caller fractional, limit absolute; use limit */
2765 82 : tuple_fraction = limit_fraction;
2766 : }
2767 : else
2768 : {
2769 : /* both fractional */
2770 0 : tuple_fraction = Min(tuple_fraction, limit_fraction);
2771 : }
2772 : }
2773 : else
2774 : {
2775 : /* no info from caller, just use limit */
2776 3160 : tuple_fraction = limit_fraction;
2777 : }
2778 : }
2779 442 : else if (*offset_est != 0 && tuple_fraction > 0.0)
2780 : {
2781 : /*
2782 : * We have an OFFSET but no LIMIT. This acts entirely differently
2783 : * from the LIMIT case: here, we need to increase rather than decrease
2784 : * the caller's tuple_fraction, because the OFFSET acts to cause more
2785 : * tuples to be fetched instead of fewer. This only matters if we got
2786 : * a tuple_fraction > 0, however.
2787 : *
2788 : * As above, use 10% if OFFSET is present but unestimatable.
2789 : */
2790 12 : if (*offset_est < 0)
2791 0 : limit_fraction = 0.10;
2792 : else
2793 12 : limit_fraction = (double) *offset_est;
2794 :
2795 : /*
2796 : * If we have absolute counts from both caller and OFFSET, add them
2797 : * together; likewise if they are both fractional. If one is
2798 : * fractional and the other absolute, we want to take the larger, and
2799 : * we heuristically assume that's the fractional one.
2800 : */
2801 12 : if (tuple_fraction >= 1.0)
2802 : {
2803 0 : if (limit_fraction >= 1.0)
2804 : {
2805 : /* both absolute, so add them together */
2806 0 : tuple_fraction += limit_fraction;
2807 : }
2808 : else
2809 : {
2810 : /* caller absolute, limit fractional; use limit */
2811 0 : tuple_fraction = limit_fraction;
2812 : }
2813 : }
2814 : else
2815 : {
2816 12 : if (limit_fraction >= 1.0)
2817 : {
2818 : /* caller fractional, limit absolute; use caller's value */
2819 : }
2820 : else
2821 : {
2822 : /* both fractional, so add them together */
2823 0 : tuple_fraction += limit_fraction;
2824 0 : if (tuple_fraction >= 1.0)
2825 0 : tuple_fraction = 0.0; /* assume fetch all */
2826 : }
2827 : }
2828 : }
2829 :
2830 3689 : return tuple_fraction;
2831 : }
2832 :
2833 : /*
2834 : * limit_needed - do we actually need a Limit plan node?
2835 : *
2836 : * If we have constant-zero OFFSET and constant-null LIMIT, we can skip adding
2837 : * a Limit node. This is worth checking for because "OFFSET 0" is a common
2838 : * locution for an optimization fence. (Because other places in the planner
2839 : * merely check whether parse->limitOffset isn't NULL, it will still work as
2840 : * an optimization fence --- we're just suppressing unnecessary run-time
2841 : * overhead.)
2842 : *
2843 : * This might look like it could be merged into preprocess_limit, but there's
2844 : * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas
2845 : * in preprocess_limit it's good enough to consider estimated values.
2846 : */
2847 : bool
2848 842902 : limit_needed(Query *parse)
2849 : {
2850 : Node *node;
2851 :
2852 842902 : node = parse->limitCount;
2853 842902 : if (node)
2854 : {
2855 7717 : if (IsA(node, Const))
2856 : {
2857 : /* NULL indicates LIMIT ALL, ie, no limit */
2858 7501 : if (!((Const *) node)->constisnull)
2859 7501 : return true; /* LIMIT with a constant value */
2860 : }
2861 : else
2862 216 : return true; /* non-constant LIMIT */
2863 : }
2864 :
2865 835185 : node = parse->limitOffset;
2866 835185 : if (node)
2867 : {
2868 1283 : if (IsA(node, Const))
2869 : {
2870 : /* Treat NULL as no offset; the executor would too */
2871 1025 : if (!((Const *) node)->constisnull)
2872 : {
2873 1025 : int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2874 :
2875 1025 : if (offset != 0)
2876 107 : return true; /* OFFSET with a nonzero value */
2877 : }
2878 : }
2879 : else
2880 258 : return true; /* non-constant OFFSET */
2881 : }
2882 :
2883 834820 : return false; /* don't need a Limit plan node */
2884 : }
2885 :
2886 : /*
2887 : * preprocess_groupclause - do preparatory work on GROUP BY clause
2888 : *
2889 : * The idea here is to adjust the ordering of the GROUP BY elements
2890 : * (which in itself is semantically insignificant) to match ORDER BY,
2891 : * thereby allowing a single sort operation to both implement the ORDER BY
2892 : * requirement and set up for a Unique step that implements GROUP BY.
2893 : * We also consider partial match between GROUP BY and ORDER BY elements,
2894 : * which could allow to implement ORDER BY using the incremental sort.
2895 : *
2896 : * We also consider other orderings of the GROUP BY elements, which could
2897 : * match the sort ordering of other possible plans (eg an indexscan) and
2898 : * thereby reduce cost. This is implemented during the generation of grouping
2899 : * paths. See get_useful_group_keys_orderings() for details.
2900 : *
2901 : * Note: we need no comparable processing of the distinctClause because
2902 : * the parser already enforced that that matches ORDER BY.
2903 : *
2904 : * Note: we return a fresh List, but its elements are the same
2905 : * SortGroupClauses appearing in parse->groupClause. This is important
2906 : * because later processing may modify the processed_groupClause list.
2907 : *
2908 : * For grouping sets, the order of items is instead forced to agree with that
2909 : * of the grouping set (and items not in the grouping set are skipped). The
2910 : * work of sorting the order of grouping set elements to match the ORDER BY if
2911 : * possible is done elsewhere.
2912 : */
2913 : static List *
2914 7038 : preprocess_groupclause(PlannerInfo *root, List *force)
2915 : {
2916 7038 : Query *parse = root->parse;
2917 7038 : List *new_groupclause = NIL;
2918 : ListCell *sl;
2919 : ListCell *gl;
2920 :
2921 : /* For grouping sets, we need to force the ordering */
2922 7038 : if (force)
2923 : {
2924 9144 : foreach(sl, force)
2925 : {
2926 5371 : Index ref = lfirst_int(sl);
2927 5371 : SortGroupClause *cl = get_sortgroupref_clause(ref, parse->groupClause);
2928 :
2929 5371 : new_groupclause = lappend(new_groupclause, cl);
2930 : }
2931 :
2932 3773 : return new_groupclause;
2933 : }
2934 :
2935 : /* If no ORDER BY, nothing useful to do here */
2936 3265 : if (parse->sortClause == NIL)
2937 1838 : return list_copy(parse->groupClause);
2938 :
2939 : /*
2940 : * Scan the ORDER BY clause and construct a list of matching GROUP BY
2941 : * items, but only as far as we can make a matching prefix.
2942 : *
2943 : * This code assumes that the sortClause contains no duplicate items.
2944 : */
2945 2801 : foreach(sl, parse->sortClause)
2946 : {
2947 1885 : SortGroupClause *sc = lfirst_node(SortGroupClause, sl);
2948 :
2949 2767 : foreach(gl, parse->groupClause)
2950 : {
2951 2256 : SortGroupClause *gc = lfirst_node(SortGroupClause, gl);
2952 :
2953 2256 : if (equal(gc, sc))
2954 : {
2955 1374 : new_groupclause = lappend(new_groupclause, gc);
2956 1374 : break;
2957 : }
2958 : }
2959 1885 : if (gl == NULL)
2960 511 : break; /* no match, so stop scanning */
2961 : }
2962 :
2963 :
2964 : /* If no match at all, no point in reordering GROUP BY */
2965 1427 : if (new_groupclause == NIL)
2966 223 : return list_copy(parse->groupClause);
2967 :
2968 : /*
2969 : * Add any remaining GROUP BY items to the new list. We don't require a
2970 : * complete match, because even partial match allows ORDER BY to be
2971 : * implemented using incremental sort. Also, give up if there are any
2972 : * non-sortable GROUP BY items, since then there's no hope anyway.
2973 : */
2974 2705 : foreach(gl, parse->groupClause)
2975 : {
2976 1501 : SortGroupClause *gc = lfirst_node(SortGroupClause, gl);
2977 :
2978 1501 : if (list_member_ptr(new_groupclause, gc))
2979 1374 : continue; /* it matched an ORDER BY item */
2980 127 : if (!OidIsValid(gc->sortop)) /* give up, GROUP BY can't be sorted */
2981 0 : return list_copy(parse->groupClause);
2982 127 : new_groupclause = lappend(new_groupclause, gc);
2983 : }
2984 :
2985 : /* Success --- install the rearranged GROUP BY list */
2986 : Assert(list_length(parse->groupClause) == list_length(new_groupclause));
2987 1204 : return new_groupclause;
2988 : }
2989 :
2990 : /*
2991 : * Extract lists of grouping sets that can be implemented using a single
2992 : * rollup-type aggregate pass each. Returns a list of lists of grouping sets.
2993 : *
2994 : * Input must be sorted with smallest sets first. Result has each sublist
2995 : * sorted with smallest sets first.
2996 : *
2997 : * We want to produce the absolute minimum possible number of lists here to
2998 : * avoid excess sorts. Fortunately, there is an algorithm for this; the problem
2999 : * of finding the minimal partition of a partially-ordered set into chains
3000 : * (which is what we need, taking the list of grouping sets as a poset ordered
3001 : * by set inclusion) can be mapped to the problem of finding the maximum
3002 : * cardinality matching on a bipartite graph, which is solvable in polynomial
3003 : * time with a worst case of no worse than O(n^2.5) and usually much
3004 : * better. Since our N is at most 4096, we don't need to consider fallbacks to
3005 : * heuristic or approximate methods. (Planning time for a 12-d cube is under
3006 : * half a second on my modest system even with optimization off and assertions
3007 : * on.)
3008 : */
3009 : static List *
3010 846 : extract_rollup_sets(List *groupingSets)
3011 : {
3012 846 : int num_sets_raw = list_length(groupingSets);
3013 846 : int num_empty = 0;
3014 846 : int num_sets = 0; /* distinct sets */
3015 846 : int num_chains = 0;
3016 846 : List *result = NIL;
3017 : List **results;
3018 : List **orig_sets;
3019 : Bitmapset **set_masks;
3020 : int *chains;
3021 : short **adjacency;
3022 : short *adjacency_buf;
3023 : BipartiteMatchState *state;
3024 : int i;
3025 : int j;
3026 : int j_size;
3027 846 : ListCell *lc1 = list_head(groupingSets);
3028 : ListCell *lc;
3029 :
3030 : /*
3031 : * Start by stripping out empty sets. The algorithm doesn't require this,
3032 : * but the planner currently needs all empty sets to be returned in the
3033 : * first list, so we strip them here and add them back after.
3034 : */
3035 1436 : while (lc1 && lfirst(lc1) == NIL)
3036 : {
3037 590 : ++num_empty;
3038 590 : lc1 = lnext(groupingSets, lc1);
3039 : }
3040 :
3041 : /* bail out now if it turns out that all we had were empty sets. */
3042 846 : if (!lc1)
3043 65 : return list_make1(groupingSets);
3044 :
3045 : /*----------
3046 : * We don't strictly need to remove duplicate sets here, but if we don't,
3047 : * they tend to become scattered through the result, which is a bit
3048 : * confusing (and irritating if we ever decide to optimize them out).
3049 : * So we remove them here and add them back after.
3050 : *
3051 : * For each non-duplicate set, we fill in the following:
3052 : *
3053 : * orig_sets[i] = list of the original set lists
3054 : * set_masks[i] = bitmapset for testing inclusion
3055 : * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3056 : *
3057 : * chains[i] will be the result group this set is assigned to.
3058 : *
3059 : * We index all of these from 1 rather than 0 because it is convenient
3060 : * to leave 0 free for the NIL node in the graph algorithm.
3061 : *----------
3062 : */
3063 781 : orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3064 781 : set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3065 781 : adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3066 781 : adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3067 :
3068 781 : j_size = 0;
3069 781 : j = 0;
3070 781 : i = 1;
3071 :
3072 2711 : for_each_cell(lc, groupingSets, lc1)
3073 : {
3074 1930 : List *candidate = (List *) lfirst(lc);
3075 1930 : Bitmapset *candidate_set = NULL;
3076 : ListCell *lc2;
3077 1930 : int dup_of = 0;
3078 :
3079 4627 : foreach(lc2, candidate)
3080 : {
3081 2697 : candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3082 : }
3083 :
3084 : /* we can only be a dup if we're the same length as a previous set */
3085 1930 : if (j_size == list_length(candidate))
3086 : {
3087 : int k;
3088 :
3089 1728 : for (k = j; k < i; ++k)
3090 : {
3091 1119 : if (bms_equal(set_masks[k], candidate_set))
3092 : {
3093 129 : dup_of = k;
3094 129 : break;
3095 : }
3096 : }
3097 : }
3098 1192 : else if (j_size < list_length(candidate))
3099 : {
3100 1192 : j_size = list_length(candidate);
3101 1192 : j = i;
3102 : }
3103 :
3104 1930 : if (dup_of > 0)
3105 : {
3106 129 : orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3107 129 : bms_free(candidate_set);
3108 : }
3109 : else
3110 : {
3111 : int k;
3112 1801 : int n_adj = 0;
3113 :
3114 1801 : orig_sets[i] = list_make1(candidate);
3115 1801 : set_masks[i] = candidate_set;
3116 :
3117 : /* fill in adjacency list; no need to compare equal-size sets */
3118 :
3119 2873 : for (k = j - 1; k > 0; --k)
3120 : {
3121 1072 : if (bms_is_subset(set_masks[k], candidate_set))
3122 937 : adjacency_buf[++n_adj] = k;
3123 : }
3124 :
3125 1801 : if (n_adj > 0)
3126 : {
3127 513 : adjacency_buf[0] = n_adj;
3128 513 : adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3129 513 : memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3130 : }
3131 : else
3132 1288 : adjacency[i] = NULL;
3133 :
3134 1801 : ++i;
3135 : }
3136 : }
3137 :
3138 781 : num_sets = i - 1;
3139 :
3140 : /*
3141 : * Apply the graph matching algorithm to do the work.
3142 : */
3143 781 : state = BipartiteMatch(num_sets, num_sets, adjacency);
3144 :
3145 : /*
3146 : * Now, the state->pair* fields have the info we need to assign sets to
3147 : * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3148 : * pair_vu[v] = u (both will be true, but we check both so that we can do
3149 : * it in one pass)
3150 : */
3151 781 : chains = palloc0((num_sets + 1) * sizeof(int));
3152 :
3153 2582 : for (i = 1; i <= num_sets; ++i)
3154 : {
3155 1801 : int u = state->pair_vu[i];
3156 1801 : int v = state->pair_uv[i];
3157 :
3158 1801 : if (u > 0 && u < i)
3159 0 : chains[i] = chains[u];
3160 1801 : else if (v > 0 && v < i)
3161 491 : chains[i] = chains[v];
3162 : else
3163 1310 : chains[i] = ++num_chains;
3164 : }
3165 :
3166 : /* build result lists. */
3167 781 : results = palloc0((num_chains + 1) * sizeof(List *));
3168 :
3169 2582 : for (i = 1; i <= num_sets; ++i)
3170 : {
3171 1801 : int c = chains[i];
3172 :
3173 : Assert(c > 0);
3174 :
3175 1801 : results[c] = list_concat(results[c], orig_sets[i]);
3176 : }
3177 :
3178 : /* push any empty sets back on the first list. */
3179 1256 : while (num_empty-- > 0)
3180 475 : results[1] = lcons(NIL, results[1]);
3181 :
3182 : /* make result list */
3183 2091 : for (i = 1; i <= num_chains; ++i)
3184 1310 : result = lappend(result, results[i]);
3185 :
3186 : /*
3187 : * Free all the things.
3188 : *
3189 : * (This is over-fussy for small sets but for large sets we could have
3190 : * tied up a nontrivial amount of memory.)
3191 : */
3192 781 : BipartiteMatchFree(state);
3193 781 : pfree(results);
3194 781 : pfree(chains);
3195 2582 : for (i = 1; i <= num_sets; ++i)
3196 1801 : if (adjacency[i])
3197 513 : pfree(adjacency[i]);
3198 781 : pfree(adjacency);
3199 781 : pfree(adjacency_buf);
3200 781 : pfree(orig_sets);
3201 2582 : for (i = 1; i <= num_sets; ++i)
3202 1801 : bms_free(set_masks[i]);
3203 781 : pfree(set_masks);
3204 :
3205 781 : return result;
3206 : }
3207 :
3208 : /*
3209 : * Reorder the elements of a list of grouping sets such that they have correct
3210 : * prefix relationships. Also inserts the GroupingSetData annotations.
3211 : *
3212 : * The input must be ordered with smallest sets first; the result is returned
3213 : * with largest sets first. Note that the result shares no list substructure
3214 : * with the input, so it's safe for the caller to modify it later.
3215 : *
3216 : * If we're passed in a sortclause, we follow its order of columns to the
3217 : * extent possible, to minimize the chance that we add unnecessary sorts.
3218 : * (We're trying here to ensure that GROUPING SETS ((a,b,c),(c)) ORDER BY c,b,a
3219 : * gets implemented in one pass.)
3220 : */
3221 : static List *
3222 1375 : reorder_grouping_sets(List *groupingSets, List *sortclause)
3223 : {
3224 : ListCell *lc;
3225 1375 : List *previous = NIL;
3226 1375 : List *result = NIL;
3227 :
3228 3895 : foreach(lc, groupingSets)
3229 : {
3230 2520 : List *candidate = (List *) lfirst(lc);
3231 2520 : List *new_elems = list_difference_int(candidate, previous);
3232 2520 : GroupingSetData *gs = makeNode(GroupingSetData);
3233 :
3234 2664 : while (list_length(sortclause) > list_length(previous) &&
3235 : new_elems != NIL)
3236 : {
3237 244 : SortGroupClause *sc = list_nth(sortclause, list_length(previous));
3238 244 : int ref = sc->tleSortGroupRef;
3239 :
3240 244 : if (list_member_int(new_elems, ref))
3241 : {
3242 144 : previous = lappend_int(previous, ref);
3243 144 : new_elems = list_delete_int(new_elems, ref);
3244 : }
3245 : else
3246 : {
3247 : /* diverged from the sortclause; give up on it */
3248 100 : sortclause = NIL;
3249 100 : break;
3250 : }
3251 : }
3252 :
3253 2520 : previous = list_concat(previous, new_elems);
3254 :
3255 2520 : gs->set = list_copy(previous);
3256 2520 : result = lcons(gs, result);
3257 : }
3258 :
3259 1375 : list_free(previous);
3260 :
3261 1375 : return result;
3262 : }
3263 :
3264 : /*
3265 : * has_volatile_pathkey
3266 : * Returns true if any PathKey in 'keys' has an EquivalenceClass
3267 : * containing a volatile function. Otherwise returns false.
3268 : */
3269 : static bool
3270 2194 : has_volatile_pathkey(List *keys)
3271 : {
3272 : ListCell *lc;
3273 :
3274 4510 : foreach(lc, keys)
3275 : {
3276 2329 : PathKey *pathkey = lfirst_node(PathKey, lc);
3277 :
3278 2329 : if (pathkey->pk_eclass->ec_has_volatile)
3279 13 : return true;
3280 : }
3281 :
3282 2181 : return false;
3283 : }
3284 :
3285 : /*
3286 : * adjust_group_pathkeys_for_groupagg
3287 : * Add pathkeys to root->group_pathkeys to reflect the best set of
3288 : * pre-ordered input for ordered aggregates.
3289 : *
3290 : * We define "best" as the pathkeys that suit the largest number of
3291 : * aggregate functions. We find these by looking at the first ORDER BY /
3292 : * DISTINCT aggregate and take the pathkeys for that before searching for
3293 : * other aggregates that require the same or a more strict variation of the
3294 : * same pathkeys. We then repeat that process for any remaining aggregates
3295 : * with different pathkeys and if we find another set of pathkeys that suits a
3296 : * larger number of aggregates then we select those pathkeys instead.
3297 : *
3298 : * When the best pathkeys are found we also mark each Aggref that can use
3299 : * those pathkeys as aggpresorted = true.
3300 : *
3301 : * Note: When an aggregate function's ORDER BY / DISTINCT clause contains any
3302 : * volatile functions, we never make use of these pathkeys. We want to ensure
3303 : * that sorts using volatile functions are done independently in each Aggref
3304 : * rather than once at the query level. If we were to allow this then Aggrefs
3305 : * with compatible sort orders would all transition their rows in the same
3306 : * order if those pathkeys were deemed to be the best pathkeys to sort on.
3307 : * Whereas, if some other set of Aggref's pathkeys happened to be deemed
3308 : * better pathkeys to sort on, then the volatile function Aggrefs would be
3309 : * left to perform their sorts individually. To avoid this inconsistent
3310 : * behavior which could make Aggref results depend on what other Aggrefs the
3311 : * query contains, we always force Aggrefs with volatile functions to perform
3312 : * their own sorts.
3313 : */
3314 : static void
3315 1858 : adjust_group_pathkeys_for_groupagg(PlannerInfo *root)
3316 : {
3317 1858 : List *grouppathkeys = root->group_pathkeys;
3318 : List *bestpathkeys;
3319 : Bitmapset *bestaggs;
3320 : Bitmapset *unprocessed_aggs;
3321 : ListCell *lc;
3322 : int i;
3323 :
3324 : /* Shouldn't be here if there are grouping sets */
3325 : Assert(root->parse->groupingSets == NIL);
3326 : /* Shouldn't be here unless there are some ordered aggregates */
3327 : Assert(root->numOrderedAggs > 0);
3328 :
3329 : /* Do nothing if disabled */
3330 1858 : if (!enable_presorted_aggregate)
3331 5 : return;
3332 :
3333 : /*
3334 : * Make a first pass over all AggInfos to collect a Bitmapset containing
3335 : * the indexes of all AggInfos to be processed below.
3336 : */
3337 1853 : unprocessed_aggs = NULL;
3338 4272 : foreach(lc, root->agginfos)
3339 : {
3340 2419 : AggInfo *agginfo = lfirst_node(AggInfo, lc);
3341 2419 : Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3342 :
3343 2419 : if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
3344 214 : continue;
3345 :
3346 : /* Skip unless there's a DISTINCT or ORDER BY clause */
3347 2205 : if (aggref->aggdistinct == NIL && aggref->aggorder == NIL)
3348 248 : continue;
3349 :
3350 : /* Additional safety checks are needed if there's a FILTER clause */
3351 1957 : if (aggref->aggfilter != NULL)
3352 : {
3353 : ListCell *lc2;
3354 43 : bool allow_presort = true;
3355 :
3356 : /*
3357 : * When the Aggref has a FILTER clause, it's possible that the
3358 : * filter removes rows that cannot be sorted because the
3359 : * expression to sort by results in an error during its
3360 : * evaluation. This is a problem for presorting as that happens
3361 : * before the FILTER, whereas without presorting, the Aggregate
3362 : * node will apply the FILTER *before* sorting. So that we never
3363 : * try to sort anything that might error, here we aim to skip over
3364 : * any Aggrefs with arguments with expressions which, when
3365 : * evaluated, could cause an ERROR. Vars and Consts are ok. There
3366 : * may be more cases that should be allowed, but more thought
3367 : * needs to be given. Err on the side of caution.
3368 : */
3369 83 : foreach(lc2, aggref->args)
3370 : {
3371 58 : TargetEntry *tle = (TargetEntry *) lfirst(lc2);
3372 58 : Expr *expr = tle->expr;
3373 :
3374 68 : while (IsA(expr, RelabelType))
3375 10 : expr = (Expr *) (castNode(RelabelType, expr))->arg;
3376 :
3377 : /* Common case, Vars and Consts are ok */
3378 58 : if (IsA(expr, Var) || IsA(expr, Const))
3379 40 : continue;
3380 :
3381 : /* Unsupported. Don't try to presort for this Aggref */
3382 18 : allow_presort = false;
3383 18 : break;
3384 : }
3385 :
3386 : /* Skip unsupported Aggrefs */
3387 43 : if (!allow_presort)
3388 18 : continue;
3389 : }
3390 :
3391 1939 : unprocessed_aggs = bms_add_member(unprocessed_aggs,
3392 : foreach_current_index(lc));
3393 : }
3394 :
3395 : /*
3396 : * Now process all the unprocessed_aggs to find the best set of pathkeys
3397 : * for the given set of aggregates.
3398 : *
3399 : * On the first outer loop here 'bestaggs' will be empty. We'll populate
3400 : * this during the first loop using the pathkeys for the very first
3401 : * AggInfo then taking any stronger pathkeys from any other AggInfos with
3402 : * a more strict set of compatible pathkeys. Once the outer loop is
3403 : * complete, we mark off all the aggregates with compatible pathkeys then
3404 : * remove those from the unprocessed_aggs and repeat the process to try to
3405 : * find another set of pathkeys that are suitable for a larger number of
3406 : * aggregates. The outer loop will stop when there are not enough
3407 : * unprocessed aggregates for it to be possible to find a set of pathkeys
3408 : * to suit a larger number of aggregates.
3409 : */
3410 1853 : bestpathkeys = NIL;
3411 1853 : bestaggs = NULL;
3412 3657 : while (bms_num_members(unprocessed_aggs) > bms_num_members(bestaggs))
3413 : {
3414 1804 : Bitmapset *aggindexes = NULL;
3415 1804 : List *currpathkeys = NIL;
3416 :
3417 1804 : i = -1;
3418 3998 : while ((i = bms_next_member(unprocessed_aggs, i)) >= 0)
3419 : {
3420 2194 : AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3421 2194 : Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3422 : List *sortlist;
3423 : List *pathkeys;
3424 :
3425 2194 : if (aggref->aggdistinct != NIL)
3426 594 : sortlist = aggref->aggdistinct;
3427 : else
3428 1600 : sortlist = aggref->aggorder;
3429 :
3430 2194 : pathkeys = make_pathkeys_for_sortclauses(root, sortlist,
3431 : aggref->args);
3432 :
3433 : /*
3434 : * Ignore Aggrefs which have volatile functions in their ORDER BY
3435 : * or DISTINCT clause.
3436 : */
3437 2194 : if (has_volatile_pathkey(pathkeys))
3438 : {
3439 13 : unprocessed_aggs = bms_del_member(unprocessed_aggs, i);
3440 13 : continue;
3441 : }
3442 :
3443 : /*
3444 : * When not set yet, take the pathkeys from the first unprocessed
3445 : * aggregate.
3446 : */
3447 2181 : if (currpathkeys == NIL)
3448 : {
3449 1801 : currpathkeys = pathkeys;
3450 :
3451 : /* include the GROUP BY pathkeys, if they exist */
3452 1801 : if (grouppathkeys != NIL)
3453 220 : currpathkeys = append_pathkeys(list_copy(grouppathkeys),
3454 : currpathkeys);
3455 :
3456 : /* record that we found pathkeys for this aggregate */
3457 1801 : aggindexes = bms_add_member(aggindexes, i);
3458 : }
3459 : else
3460 : {
3461 : /* now look for a stronger set of matching pathkeys */
3462 :
3463 : /* include the GROUP BY pathkeys, if they exist */
3464 380 : if (grouppathkeys != NIL)
3465 240 : pathkeys = append_pathkeys(list_copy(grouppathkeys),
3466 : pathkeys);
3467 :
3468 : /* are 'pathkeys' compatible or better than 'currpathkeys'? */
3469 380 : switch (compare_pathkeys(currpathkeys, pathkeys))
3470 : {
3471 10 : case PATHKEYS_BETTER2:
3472 : /* 'pathkeys' are stronger, use these ones instead */
3473 10 : currpathkeys = pathkeys;
3474 : pg_fallthrough;
3475 :
3476 55 : case PATHKEYS_BETTER1:
3477 : /* 'pathkeys' are less strict */
3478 : pg_fallthrough;
3479 :
3480 : case PATHKEYS_EQUAL:
3481 : /* mark this aggregate as covered by 'currpathkeys' */
3482 55 : aggindexes = bms_add_member(aggindexes, i);
3483 55 : break;
3484 :
3485 325 : case PATHKEYS_DIFFERENT:
3486 325 : break;
3487 : }
3488 : }
3489 : }
3490 :
3491 : /* remove the aggregates that we've just processed */
3492 1804 : unprocessed_aggs = bms_del_members(unprocessed_aggs, aggindexes);
3493 :
3494 : /*
3495 : * If this pass included more aggregates than the previous best then
3496 : * use these ones as the best set.
3497 : */
3498 1804 : if (bms_num_members(aggindexes) > bms_num_members(bestaggs))
3499 : {
3500 1716 : bestaggs = aggindexes;
3501 1716 : bestpathkeys = currpathkeys;
3502 : }
3503 : }
3504 :
3505 : /*
3506 : * If we found any ordered aggregates, update root->group_pathkeys to add
3507 : * the best set of aggregate pathkeys. Note that bestpathkeys includes
3508 : * the original GROUP BY pathkeys already.
3509 : */
3510 1853 : if (bestpathkeys != NIL)
3511 1666 : root->group_pathkeys = bestpathkeys;
3512 :
3513 : /*
3514 : * Now that we've found the best set of aggregates we can set the
3515 : * presorted flag to indicate to the executor that it needn't bother
3516 : * performing a sort for these Aggrefs. We're able to do this now as
3517 : * there's no chance of a Hash Aggregate plan as create_grouping_paths
3518 : * will not mark the GROUP BY as GROUPING_CAN_USE_HASH due to the presence
3519 : * of ordered aggregates.
3520 : */
3521 1853 : i = -1;
3522 3599 : while ((i = bms_next_member(bestaggs, i)) >= 0)
3523 : {
3524 1746 : AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3525 :
3526 3507 : foreach(lc, agginfo->aggrefs)
3527 : {
3528 1761 : Aggref *aggref = lfirst_node(Aggref, lc);
3529 :
3530 1761 : aggref->aggpresorted = true;
3531 : }
3532 : }
3533 : }
3534 :
3535 : /*
3536 : * Compute query_pathkeys and other pathkeys during plan generation
3537 : */
3538 : static void
3539 388118 : standard_qp_callback(PlannerInfo *root, void *extra)
3540 : {
3541 388118 : Query *parse = root->parse;
3542 388118 : standard_qp_extra *qp_extra = (standard_qp_extra *) extra;
3543 388118 : List *tlist = root->processed_tlist;
3544 388118 : List *activeWindows = qp_extra->activeWindows;
3545 :
3546 : /*
3547 : * Calculate pathkeys that represent grouping/ordering and/or ordered
3548 : * aggregate requirements.
3549 : */
3550 388118 : if (qp_extra->gset_data)
3551 : {
3552 : /*
3553 : * With grouping sets, just use the first RollupData's groupClause. We
3554 : * don't make any effort to optimize grouping clauses when there are
3555 : * grouping sets, nor can we combine aggregate ordering keys with
3556 : * grouping.
3557 : */
3558 851 : List *rollups = qp_extra->gset_data->rollups;
3559 851 : List *groupClause = (rollups ? linitial_node(RollupData, rollups)->groupClause : NIL);
3560 :
3561 851 : if (grouping_is_sortable(groupClause))
3562 : {
3563 : bool sortable;
3564 :
3565 : /*
3566 : * The groupClause is logically below the grouping step. So if
3567 : * there is an RTE entry for the grouping step, we need to remove
3568 : * its RT index from the sort expressions before we make PathKeys
3569 : * for them.
3570 : */
3571 851 : root->group_pathkeys =
3572 851 : make_pathkeys_for_sortclauses_extended(root,
3573 : &groupClause,
3574 : tlist,
3575 : false,
3576 851 : parse->hasGroupRTE,
3577 : &sortable,
3578 : false);
3579 : Assert(sortable);
3580 851 : root->num_groupby_pathkeys = list_length(root->group_pathkeys);
3581 : }
3582 : else
3583 : {
3584 0 : root->group_pathkeys = NIL;
3585 0 : root->num_groupby_pathkeys = 0;
3586 : }
3587 : }
3588 387267 : else if (parse->groupClause || root->numOrderedAggs > 0)
3589 4941 : {
3590 : /*
3591 : * With a plain GROUP BY list, we can remove any grouping items that
3592 : * are proven redundant by EquivalenceClass processing. For example,
3593 : * we can remove y given "WHERE x = y GROUP BY x, y". These aren't
3594 : * especially common cases, but they're nearly free to detect. Note
3595 : * that we remove redundant items from processed_groupClause but not
3596 : * the original parse->groupClause.
3597 : */
3598 : bool sortable;
3599 :
3600 : /*
3601 : * Convert group clauses into pathkeys. Set the ec_sortref field of
3602 : * EquivalenceClass'es if it's not set yet.
3603 : */
3604 4941 : root->group_pathkeys =
3605 4941 : make_pathkeys_for_sortclauses_extended(root,
3606 : &root->processed_groupClause,
3607 : tlist,
3608 : true,
3609 : false,
3610 : &sortable,
3611 : true);
3612 4941 : if (!sortable)
3613 : {
3614 : /* Can't sort; no point in considering aggregate ordering either */
3615 0 : root->group_pathkeys = NIL;
3616 0 : root->num_groupby_pathkeys = 0;
3617 : }
3618 : else
3619 : {
3620 4941 : root->num_groupby_pathkeys = list_length(root->group_pathkeys);
3621 : /* If we have ordered aggs, consider adding onto group_pathkeys */
3622 4941 : if (root->numOrderedAggs > 0)
3623 1858 : adjust_group_pathkeys_for_groupagg(root);
3624 : }
3625 : }
3626 : else
3627 : {
3628 382326 : root->group_pathkeys = NIL;
3629 382326 : root->num_groupby_pathkeys = 0;
3630 : }
3631 :
3632 : /* We consider only the first (bottom) window in pathkeys logic */
3633 388118 : if (activeWindows != NIL)
3634 : {
3635 2192 : WindowClause *wc = linitial_node(WindowClause, activeWindows);
3636 :
3637 2192 : root->window_pathkeys = make_pathkeys_for_window(root,
3638 : wc,
3639 : tlist);
3640 : }
3641 : else
3642 385926 : root->window_pathkeys = NIL;
3643 :
3644 : /*
3645 : * As with GROUP BY, we can discard any DISTINCT items that are proven
3646 : * redundant by EquivalenceClass processing. The non-redundant list is
3647 : * kept in root->processed_distinctClause, leaving the original
3648 : * parse->distinctClause alone.
3649 : */
3650 388118 : if (parse->distinctClause)
3651 : {
3652 : bool sortable;
3653 :
3654 : /* Make a copy since pathkey processing can modify the list */
3655 1931 : root->processed_distinctClause = list_copy(parse->distinctClause);
3656 1931 : root->distinct_pathkeys =
3657 1931 : make_pathkeys_for_sortclauses_extended(root,
3658 : &root->processed_distinctClause,
3659 : tlist,
3660 : true,
3661 : false,
3662 : &sortable,
3663 : false);
3664 1931 : if (!sortable)
3665 5 : root->distinct_pathkeys = NIL;
3666 : }
3667 : else
3668 386187 : root->distinct_pathkeys = NIL;
3669 :
3670 388118 : root->sort_pathkeys =
3671 388118 : make_pathkeys_for_sortclauses(root,
3672 : parse->sortClause,
3673 : tlist);
3674 :
3675 : /* setting setop_pathkeys might be useful to the union planner */
3676 388118 : if (qp_extra->setop != NULL)
3677 : {
3678 : List *groupClauses;
3679 : bool sortable;
3680 :
3681 10416 : groupClauses = generate_setop_child_grouplist(qp_extra->setop, tlist);
3682 :
3683 10416 : root->setop_pathkeys =
3684 10416 : make_pathkeys_for_sortclauses_extended(root,
3685 : &groupClauses,
3686 : tlist,
3687 : false,
3688 : false,
3689 : &sortable,
3690 : false);
3691 10416 : if (!sortable)
3692 108 : root->setop_pathkeys = NIL;
3693 : }
3694 : else
3695 377702 : root->setop_pathkeys = NIL;
3696 :
3697 : /*
3698 : * Figure out whether we want a sorted result from query_planner.
3699 : *
3700 : * If we have a sortable GROUP BY clause, then we want a result sorted
3701 : * properly for grouping. Otherwise, if we have window functions to
3702 : * evaluate, we try to sort for the first window. Otherwise, if there's a
3703 : * sortable DISTINCT clause that's more rigorous than the ORDER BY clause,
3704 : * we try to produce output that's sufficiently well sorted for the
3705 : * DISTINCT. Otherwise, if there is an ORDER BY clause, we want to sort
3706 : * by the ORDER BY clause. Otherwise, if we're a subquery being planned
3707 : * for a set operation which can benefit from presorted results and have a
3708 : * sortable targetlist, we want to sort by the target list.
3709 : *
3710 : * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a superset
3711 : * of GROUP BY, it would be tempting to request sort by ORDER BY --- but
3712 : * that might just leave us failing to exploit an available sort order at
3713 : * all. Needs more thought. The choice for DISTINCT versus ORDER BY is
3714 : * much easier, since we know that the parser ensured that one is a
3715 : * superset of the other.
3716 : */
3717 388118 : if (root->group_pathkeys)
3718 5445 : root->query_pathkeys = root->group_pathkeys;
3719 382673 : else if (root->window_pathkeys)
3720 1757 : root->query_pathkeys = root->window_pathkeys;
3721 761832 : else if (list_length(root->distinct_pathkeys) >
3722 380916 : list_length(root->sort_pathkeys))
3723 1569 : root->query_pathkeys = root->distinct_pathkeys;
3724 379347 : else if (root->sort_pathkeys)
3725 55614 : root->query_pathkeys = root->sort_pathkeys;
3726 323733 : else if (root->setop_pathkeys != NIL)
3727 9444 : root->query_pathkeys = root->setop_pathkeys;
3728 : else
3729 314289 : root->query_pathkeys = NIL;
3730 388118 : }
3731 :
3732 : /*
3733 : * Estimate number of groups produced by grouping clauses (1 if not grouping)
3734 : *
3735 : * path_rows: number of output rows from scan/join step
3736 : * gd: grouping sets data including list of grouping sets and their clauses
3737 : * target_list: target list containing group clause references
3738 : *
3739 : * If doing grouping sets, we also annotate the gsets data with the estimates
3740 : * for each set and each individual rollup list, with a view to later
3741 : * determining whether some combination of them could be hashed instead.
3742 : */
3743 : static double
3744 40575 : get_number_of_groups(PlannerInfo *root,
3745 : double path_rows,
3746 : grouping_sets_data *gd,
3747 : List *target_list)
3748 : {
3749 40575 : Query *parse = root->parse;
3750 : double dNumGroups;
3751 :
3752 40575 : if (parse->groupClause)
3753 : {
3754 : List *groupExprs;
3755 :
3756 8482 : if (parse->groupingSets)
3757 : {
3758 : /* Add up the estimates for each grouping set */
3759 : ListCell *lc;
3760 :
3761 : Assert(gd); /* keep Coverity happy */
3762 :
3763 786 : dNumGroups = 0;
3764 :
3765 2096 : foreach(lc, gd->rollups)
3766 : {
3767 1310 : RollupData *rollup = lfirst_node(RollupData, lc);
3768 : ListCell *lc2;
3769 : ListCell *lc3;
3770 :
3771 1310 : groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3772 : target_list);
3773 :
3774 1310 : rollup->numGroups = 0.0;
3775 :
3776 3715 : forboth(lc2, rollup->gsets, lc3, rollup->gsets_data)
3777 : {
3778 2405 : List *gset = (List *) lfirst(lc2);
3779 2405 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc3);
3780 2405 : double numGroups = estimate_num_groups(root,
3781 : groupExprs,
3782 : path_rows,
3783 : &gset,
3784 : NULL);
3785 :
3786 2405 : gs->numGroups = numGroups;
3787 2405 : rollup->numGroups += numGroups;
3788 : }
3789 :
3790 1310 : dNumGroups += rollup->numGroups;
3791 : }
3792 :
3793 786 : if (gd->hash_sets_idx)
3794 : {
3795 : ListCell *lc2;
3796 :
3797 29 : gd->dNumHashGroups = 0;
3798 :
3799 29 : groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3800 : target_list);
3801 :
3802 63 : forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3803 : {
3804 34 : List *gset = (List *) lfirst(lc);
3805 34 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc2);
3806 34 : double numGroups = estimate_num_groups(root,
3807 : groupExprs,
3808 : path_rows,
3809 : &gset,
3810 : NULL);
3811 :
3812 34 : gs->numGroups = numGroups;
3813 34 : gd->dNumHashGroups += numGroups;
3814 : }
3815 :
3816 29 : dNumGroups += gd->dNumHashGroups;
3817 : }
3818 : }
3819 : else
3820 : {
3821 : /* Plain GROUP BY -- estimate based on optimized groupClause */
3822 7696 : groupExprs = get_sortgrouplist_exprs(root->processed_groupClause,
3823 : target_list);
3824 :
3825 7696 : dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3826 : NULL, NULL);
3827 : }
3828 : }
3829 32093 : else if (parse->groupingSets)
3830 : {
3831 : /* Empty grouping sets ... one result row for each one */
3832 50 : dNumGroups = list_length(parse->groupingSets);
3833 : }
3834 32043 : else if (parse->hasAggs || root->hasHavingQual)
3835 : {
3836 : /* Plain aggregation, one result row */
3837 32043 : dNumGroups = 1;
3838 : }
3839 : else
3840 : {
3841 : /* Not grouping */
3842 0 : dNumGroups = 1;
3843 : }
3844 :
3845 40575 : return dNumGroups;
3846 : }
3847 :
3848 : /*
3849 : * create_grouping_paths
3850 : *
3851 : * Build a new upperrel containing Paths for grouping and/or aggregation.
3852 : * Along the way, we also build an upperrel for Paths which are partially
3853 : * grouped and/or aggregated. A partially grouped and/or aggregated path
3854 : * needs a FinalizeAggregate node to complete the aggregation. Currently,
3855 : * the only partially grouped paths we build are also partial paths; that
3856 : * is, they need a Gather and then a FinalizeAggregate.
3857 : *
3858 : * input_rel: contains the source-data Paths
3859 : * target: the pathtarget for the result Paths to compute
3860 : * gd: grouping sets data including list of grouping sets and their clauses
3861 : *
3862 : * Note: all Paths in input_rel are expected to return the target computed
3863 : * by make_group_input_target.
3864 : */
3865 : static RelOptInfo *
3866 33561 : create_grouping_paths(PlannerInfo *root,
3867 : RelOptInfo *input_rel,
3868 : PathTarget *target,
3869 : bool target_parallel_safe,
3870 : grouping_sets_data *gd)
3871 : {
3872 33561 : Query *parse = root->parse;
3873 : RelOptInfo *grouped_rel;
3874 : RelOptInfo *partially_grouped_rel;
3875 : AggClauseCosts agg_costs;
3876 :
3877 201366 : MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3878 33561 : get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &agg_costs);
3879 :
3880 : /*
3881 : * Create grouping relation to hold fully aggregated grouping and/or
3882 : * aggregation paths.
3883 : */
3884 33561 : grouped_rel = make_grouping_rel(root, input_rel, target,
3885 : target_parallel_safe, parse->havingQual);
3886 :
3887 : /*
3888 : * Create either paths for a degenerate grouping or paths for ordinary
3889 : * grouping, as appropriate.
3890 : */
3891 33561 : if (is_degenerate_grouping(root))
3892 35 : create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3893 : else
3894 : {
3895 33526 : int flags = 0;
3896 : GroupPathExtraData extra;
3897 :
3898 : /*
3899 : * Determine whether it's possible to perform sort-based
3900 : * implementations of grouping. (Note that if processed_groupClause
3901 : * is empty, grouping_is_sortable() is trivially true, and all the
3902 : * pathkeys_contained_in() tests will succeed too, so that we'll
3903 : * consider every surviving input path.)
3904 : *
3905 : * If we have grouping sets, we might be able to sort some but not all
3906 : * of them; in this case, we need can_sort to be true as long as we
3907 : * must consider any sorted-input plan.
3908 : */
3909 33526 : if ((gd && gd->rollups != NIL)
3910 32695 : || grouping_is_sortable(root->processed_groupClause))
3911 33521 : flags |= GROUPING_CAN_USE_SORT;
3912 :
3913 : /*
3914 : * Determine whether we should consider hash-based implementations of
3915 : * grouping.
3916 : *
3917 : * Hashed aggregation only applies if we're grouping. If we have
3918 : * grouping sets, some groups might be hashable but others not; in
3919 : * this case we set can_hash true as long as there is nothing globally
3920 : * preventing us from hashing (and we should therefore consider plans
3921 : * with hashes).
3922 : *
3923 : * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3924 : * BY aggregates. (Doing so would imply storing *all* the input
3925 : * values in the hash table, and/or running many sorts in parallel,
3926 : * either of which seems like a certain loser.) We similarly don't
3927 : * support ordered-set aggregates in hashed aggregation, but that case
3928 : * is also included in the numOrderedAggs count.
3929 : *
3930 : * Note: grouping_is_hashable() is much more expensive to check than
3931 : * the other gating conditions, so we want to do it last.
3932 : */
3933 33526 : if ((parse->groupClause != NIL &&
3934 7134 : root->numOrderedAggs == 0 &&
3935 3083 : (gd ? gd->any_hashable : grouping_is_hashable(root->processed_groupClause))))
3936 3837 : flags |= GROUPING_CAN_USE_HASH;
3937 :
3938 : /*
3939 : * Determine whether partial aggregation is possible.
3940 : */
3941 33526 : if (can_partial_agg(root))
3942 29539 : flags |= GROUPING_CAN_PARTIAL_AGG;
3943 :
3944 33526 : extra.flags = flags;
3945 33526 : extra.target_parallel_safe = target_parallel_safe;
3946 33526 : extra.havingQual = parse->havingQual;
3947 33526 : extra.targetList = parse->targetList;
3948 33526 : extra.partial_costs_set = false;
3949 :
3950 : /*
3951 : * Determine whether partitionwise aggregation is in theory possible.
3952 : * It can be disabled by the user, and for now, we don't try to
3953 : * support grouping sets. create_ordinary_grouping_paths() will check
3954 : * additional conditions, such as whether input_rel is partitioned.
3955 : */
3956 33526 : if (enable_partitionwise_aggregate && !parse->groupingSets)
3957 580 : extra.patype = PARTITIONWISE_AGGREGATE_FULL;
3958 : else
3959 32946 : extra.patype = PARTITIONWISE_AGGREGATE_NONE;
3960 :
3961 33526 : create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3962 : &agg_costs, gd, &extra,
3963 : &partially_grouped_rel);
3964 : }
3965 :
3966 33557 : set_cheapest(grouped_rel);
3967 33557 : return grouped_rel;
3968 : }
3969 :
3970 : /*
3971 : * make_grouping_rel
3972 : *
3973 : * Create a new grouping rel and set basic properties.
3974 : *
3975 : * input_rel represents the underlying scan/join relation.
3976 : * target is the output expected from the grouping relation.
3977 : */
3978 : static RelOptInfo *
3979 35356 : make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
3980 : PathTarget *target, bool target_parallel_safe,
3981 : Node *havingQual)
3982 : {
3983 : RelOptInfo *grouped_rel;
3984 :
3985 35356 : if (IS_OTHER_REL(input_rel))
3986 : {
3987 1795 : grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG,
3988 : input_rel->relids);
3989 1795 : grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
3990 : }
3991 : else
3992 : {
3993 : /*
3994 : * By tradition, the relids set for the main grouping relation is
3995 : * NULL. (This could be changed, but might require adjustments
3996 : * elsewhere.)
3997 : */
3998 33561 : grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
3999 : }
4000 :
4001 : /* Set target. */
4002 35356 : grouped_rel->reltarget = target;
4003 :
4004 : /*
4005 : * If the input relation is not parallel-safe, then the grouped relation
4006 : * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4007 : * target list and HAVING quals are parallel-safe.
4008 : */
4009 57907 : if (input_rel->consider_parallel && target_parallel_safe &&
4010 22551 : is_parallel_safe(root, havingQual))
4011 22531 : grouped_rel->consider_parallel = true;
4012 :
4013 : /* Assume that the same path generation strategies are allowed */
4014 35356 : grouped_rel->pgs_mask = input_rel->pgs_mask;
4015 :
4016 : /*
4017 : * If the input rel belongs to a single FDW, so does the grouped rel.
4018 : */
4019 35356 : grouped_rel->serverid = input_rel->serverid;
4020 35356 : grouped_rel->userid = input_rel->userid;
4021 35356 : grouped_rel->useridiscurrent = input_rel->useridiscurrent;
4022 35356 : grouped_rel->fdwroutine = input_rel->fdwroutine;
4023 :
4024 35356 : return grouped_rel;
4025 : }
4026 :
4027 : /*
4028 : * is_degenerate_grouping
4029 : *
4030 : * A degenerate grouping is one in which the query has a HAVING qual and/or
4031 : * grouping sets, but no aggregates and no GROUP BY (which implies that the
4032 : * grouping sets are all empty).
4033 : */
4034 : static bool
4035 33561 : is_degenerate_grouping(PlannerInfo *root)
4036 : {
4037 33561 : Query *parse = root->parse;
4038 :
4039 32567 : return (root->hasHavingQual || parse->groupingSets) &&
4040 66128 : !parse->hasAggs && parse->groupClause == NIL;
4041 : }
4042 :
4043 : /*
4044 : * create_degenerate_grouping_paths
4045 : *
4046 : * When the grouping is degenerate (see is_degenerate_grouping), we are
4047 : * supposed to emit either zero or one row for each grouping set depending on
4048 : * whether HAVING succeeds. Furthermore, there cannot be any variables in
4049 : * either HAVING or the targetlist, so we actually do not need the FROM table
4050 : * at all! We can just throw away the plan-so-far and generate a Result node.
4051 : * This is a sufficiently unusual corner case that it's not worth contorting
4052 : * the structure of this module to avoid having to generate the earlier paths
4053 : * in the first place.
4054 : */
4055 : static void
4056 35 : create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
4057 : RelOptInfo *grouped_rel)
4058 : {
4059 35 : Query *parse = root->parse;
4060 : int nrows;
4061 : Path *path;
4062 :
4063 35 : nrows = list_length(parse->groupingSets);
4064 35 : if (nrows > 1)
4065 : {
4066 : /*
4067 : * Doesn't seem worthwhile writing code to cons up a generate_series
4068 : * or a values scan to emit multiple rows. Instead just make N clones
4069 : * and append them. (With a volatile HAVING clause, this means you
4070 : * might get between 0 and N output rows. Offhand I think that's
4071 : * desired.)
4072 : */
4073 10 : AppendPathInput append = {0};
4074 :
4075 30 : while (--nrows >= 0)
4076 : {
4077 : path = (Path *)
4078 20 : create_group_result_path(root, grouped_rel,
4079 20 : grouped_rel->reltarget,
4080 20 : (List *) parse->havingQual);
4081 20 : append.subpaths = lappend(append.subpaths, path);
4082 : }
4083 : path = (Path *)
4084 10 : create_append_path(root,
4085 : grouped_rel,
4086 : append,
4087 : NIL,
4088 : NULL,
4089 : 0,
4090 : false,
4091 : -1);
4092 : }
4093 : else
4094 : {
4095 : /* No grouping sets, or just one, so one output row */
4096 : path = (Path *)
4097 25 : create_group_result_path(root, grouped_rel,
4098 25 : grouped_rel->reltarget,
4099 25 : (List *) parse->havingQual);
4100 : }
4101 :
4102 35 : add_path(grouped_rel, path);
4103 35 : }
4104 :
4105 : /*
4106 : * create_ordinary_grouping_paths
4107 : *
4108 : * Create grouping paths for the ordinary (that is, non-degenerate) case.
4109 : *
4110 : * We need to consider sorted and hashed aggregation in the same function,
4111 : * because otherwise (1) it would be harder to throw an appropriate error
4112 : * message if neither way works, and (2) we should not allow hashtable size
4113 : * considerations to dissuade us from using hashing if sorting is not possible.
4114 : *
4115 : * *partially_grouped_rel_p will be set to the partially grouped rel which this
4116 : * function creates, or to NULL if it doesn't create one.
4117 : */
4118 : static void
4119 35321 : create_ordinary_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
4120 : RelOptInfo *grouped_rel,
4121 : const AggClauseCosts *agg_costs,
4122 : grouping_sets_data *gd,
4123 : GroupPathExtraData *extra,
4124 : RelOptInfo **partially_grouped_rel_p)
4125 : {
4126 35321 : RelOptInfo *partially_grouped_rel = NULL;
4127 35321 : PartitionwiseAggregateType patype = PARTITIONWISE_AGGREGATE_NONE;
4128 :
4129 : /*
4130 : * If this is the topmost grouping relation or if the parent relation is
4131 : * doing some form of partitionwise aggregation, then we may be able to do
4132 : * it at this level also. However, if the input relation is not
4133 : * partitioned, partitionwise aggregate is impossible.
4134 : */
4135 35321 : if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
4136 2375 : IS_PARTITIONED_REL(input_rel))
4137 : {
4138 : /*
4139 : * If this is the topmost relation or if the parent relation is doing
4140 : * full partitionwise aggregation, then we can do full partitionwise
4141 : * aggregation provided that the GROUP BY clause contains all of the
4142 : * partitioning columns at this level and the collation used by GROUP
4143 : * BY matches the partitioning collation. Otherwise, we can do at
4144 : * most partial partitionwise aggregation. But if partial aggregation
4145 : * is not supported in general then we can't use it for partitionwise
4146 : * aggregation either.
4147 : *
4148 : * Check parse->groupClause not processed_groupClause, because it's
4149 : * okay if some of the partitioning columns were proved redundant.
4150 : */
4151 1360 : if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
4152 640 : group_by_has_partkey(input_rel, extra->targetList,
4153 640 : root->parse->groupClause))
4154 404 : patype = PARTITIONWISE_AGGREGATE_FULL;
4155 316 : else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4156 281 : patype = PARTITIONWISE_AGGREGATE_PARTIAL;
4157 : else
4158 35 : patype = PARTITIONWISE_AGGREGATE_NONE;
4159 : }
4160 :
4161 : /*
4162 : * Before generating paths for grouped_rel, we first generate any possible
4163 : * partially grouped paths; that way, later code can easily consider both
4164 : * parallel and non-parallel approaches to grouping.
4165 : */
4166 35321 : if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4167 : {
4168 : bool force_rel_creation;
4169 :
4170 : /*
4171 : * If we're doing partitionwise aggregation at this level, force
4172 : * creation of a partially_grouped_rel so we can add partitionwise
4173 : * paths to it.
4174 : */
4175 31274 : force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
4176 :
4177 : partially_grouped_rel =
4178 31274 : create_partial_grouping_paths(root,
4179 : grouped_rel,
4180 : input_rel,
4181 : gd,
4182 : extra,
4183 : force_rel_creation);
4184 : }
4185 :
4186 : /* Set out parameter. */
4187 35321 : *partially_grouped_rel_p = partially_grouped_rel;
4188 :
4189 : /* Apply partitionwise aggregation technique, if possible. */
4190 35321 : if (patype != PARTITIONWISE_AGGREGATE_NONE)
4191 685 : create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
4192 : partially_grouped_rel, agg_costs,
4193 : gd, patype, extra);
4194 :
4195 : /* If we are doing partial aggregation only, return. */
4196 35321 : if (extra->patype == PARTITIONWISE_AGGREGATE_PARTIAL)
4197 : {
4198 : Assert(partially_grouped_rel);
4199 :
4200 713 : if (partially_grouped_rel->pathlist)
4201 713 : set_cheapest(partially_grouped_rel);
4202 :
4203 713 : return;
4204 : }
4205 :
4206 : /* Gather any partially grouped partial paths. */
4207 34608 : if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
4208 2323 : gather_grouping_paths(root, partially_grouped_rel);
4209 :
4210 : /* Now choose the best path(s) for partially_grouped_rel. */
4211 34608 : if (partially_grouped_rel && partially_grouped_rel->pathlist)
4212 2511 : set_cheapest(partially_grouped_rel);
4213 :
4214 : /* Build final grouping paths */
4215 34608 : add_paths_to_grouping_rel(root, input_rel, grouped_rel,
4216 : partially_grouped_rel, agg_costs, gd,
4217 : extra);
4218 :
4219 : /* Give a helpful error if we failed to find any implementation */
4220 34608 : if (grouped_rel->pathlist == NIL)
4221 4 : ereport(ERROR,
4222 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4223 : errmsg("could not implement GROUP BY"),
4224 : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4225 :
4226 : /*
4227 : * If there is an FDW that's responsible for all baserels of the query,
4228 : * let it consider adding ForeignPaths.
4229 : */
4230 34604 : if (grouped_rel->fdwroutine &&
4231 169 : grouped_rel->fdwroutine->GetForeignUpperPaths)
4232 168 : grouped_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG,
4233 : input_rel, grouped_rel,
4234 : extra);
4235 :
4236 : /* Let extensions possibly add some more paths */
4237 34604 : if (create_upper_paths_hook)
4238 0 : (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4239 : input_rel, grouped_rel,
4240 : extra);
4241 : }
4242 :
4243 : /*
4244 : * For a given input path, consider the possible ways of doing grouping sets on
4245 : * it, by combinations of hashing and sorting. This can be called multiple
4246 : * times, so it's important that it not scribble on input. No result is
4247 : * returned, but any generated paths are added to grouped_rel.
4248 : */
4249 : static void
4250 1642 : consider_groupingsets_paths(PlannerInfo *root,
4251 : RelOptInfo *grouped_rel,
4252 : Path *path,
4253 : bool is_sorted,
4254 : bool can_hash,
4255 : grouping_sets_data *gd,
4256 : const AggClauseCosts *agg_costs,
4257 : double dNumGroups)
4258 : {
4259 1642 : Query *parse = root->parse;
4260 1642 : Size hash_mem_limit = get_hash_memory_limit();
4261 :
4262 : /*
4263 : * If we're not being offered sorted input, then only consider plans that
4264 : * can be done entirely by hashing.
4265 : *
4266 : * We can hash everything if it looks like it'll fit in hash_mem. But if
4267 : * the input is actually sorted despite not being advertised as such, we
4268 : * prefer to make use of that in order to use less memory.
4269 : *
4270 : * If none of the grouping sets are sortable, then ignore the hash_mem
4271 : * limit and generate a path anyway, since otherwise we'll just fail.
4272 : */
4273 1642 : if (!is_sorted)
4274 : {
4275 757 : List *new_rollups = NIL;
4276 757 : RollupData *unhashed_rollup = NULL;
4277 : List *sets_data;
4278 757 : List *empty_sets_data = NIL;
4279 757 : List *empty_sets = NIL;
4280 : ListCell *lc;
4281 757 : ListCell *l_start = list_head(gd->rollups);
4282 757 : AggStrategy strat = AGG_HASHED;
4283 : double hashsize;
4284 757 : double exclude_groups = 0.0;
4285 :
4286 : Assert(can_hash);
4287 :
4288 : /*
4289 : * If the input is coincidentally sorted usefully (which can happen
4290 : * even if is_sorted is false, since that only means that our caller
4291 : * has set up the sorting for us), then save some hashtable space by
4292 : * making use of that. But we need to watch out for degenerate cases:
4293 : *
4294 : * 1) If there are any empty grouping sets, then group_pathkeys might
4295 : * be NIL if all non-empty grouping sets are unsortable. In this case,
4296 : * there will be a rollup containing only empty groups, and the
4297 : * pathkeys_contained_in test is vacuously true; this is ok.
4298 : *
4299 : * XXX: the above relies on the fact that group_pathkeys is generated
4300 : * from the first rollup. If we add the ability to consider multiple
4301 : * sort orders for grouping input, this assumption might fail.
4302 : *
4303 : * 2) If there are no empty sets and only unsortable sets, then the
4304 : * rollups list will be empty (and thus l_start == NULL), and
4305 : * group_pathkeys will be NIL; we must ensure that the vacuously-true
4306 : * pathkeys_contained_in test doesn't cause us to crash.
4307 : */
4308 1509 : if (l_start != NULL &&
4309 752 : pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
4310 : {
4311 30 : unhashed_rollup = lfirst_node(RollupData, l_start);
4312 30 : exclude_groups = unhashed_rollup->numGroups;
4313 30 : l_start = lnext(gd->rollups, l_start);
4314 : }
4315 :
4316 757 : hashsize = estimate_hashagg_tablesize(root,
4317 : path,
4318 : agg_costs,
4319 : dNumGroups - exclude_groups);
4320 :
4321 : /*
4322 : * gd->rollups is empty if we have only unsortable columns to work
4323 : * with. Override hash_mem in that case; otherwise, we'll rely on the
4324 : * sorted-input case to generate usable mixed paths.
4325 : */
4326 757 : if (hashsize > hash_mem_limit && gd->rollups)
4327 15 : return; /* nope, won't fit */
4328 :
4329 : /*
4330 : * We need to burst the existing rollups list into individual grouping
4331 : * sets and recompute a groupClause for each set.
4332 : */
4333 742 : sets_data = list_copy(gd->unsortable_sets);
4334 :
4335 1873 : for_each_cell(lc, gd->rollups, l_start)
4336 : {
4337 1151 : RollupData *rollup = lfirst_node(RollupData, lc);
4338 :
4339 : /*
4340 : * If we find an unhashable rollup that's not been skipped by the
4341 : * "actually sorted" check above, we can't cope; we'd need sorted
4342 : * input (with a different sort order) but we can't get that here.
4343 : * So bail out; we'll get a valid path from the is_sorted case
4344 : * instead.
4345 : *
4346 : * The mere presence of empty grouping sets doesn't make a rollup
4347 : * unhashable (see preprocess_grouping_sets), we handle those
4348 : * specially below.
4349 : */
4350 1151 : if (!rollup->hashable)
4351 20 : return;
4352 :
4353 1131 : sets_data = list_concat(sets_data, rollup->gsets_data);
4354 : }
4355 2913 : foreach(lc, sets_data)
4356 : {
4357 2191 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
4358 2191 : List *gset = gs->set;
4359 : RollupData *rollup;
4360 :
4361 2191 : if (gset == NIL)
4362 : {
4363 : /* Empty grouping sets can't be hashed. */
4364 445 : empty_sets_data = lappend(empty_sets_data, gs);
4365 445 : empty_sets = lappend(empty_sets, NIL);
4366 : }
4367 : else
4368 : {
4369 1746 : rollup = makeNode(RollupData);
4370 :
4371 1746 : rollup->groupClause = preprocess_groupclause(root, gset);
4372 1746 : rollup->gsets_data = list_make1(gs);
4373 1746 : rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4374 : rollup->gsets_data,
4375 : gd->tleref_to_colnum_map);
4376 1746 : rollup->numGroups = gs->numGroups;
4377 1746 : rollup->hashable = true;
4378 1746 : rollup->is_hashed = true;
4379 1746 : new_rollups = lappend(new_rollups, rollup);
4380 : }
4381 : }
4382 :
4383 : /*
4384 : * If we didn't find anything nonempty to hash, then bail. We'll
4385 : * generate a path from the is_sorted case.
4386 : */
4387 722 : if (new_rollups == NIL)
4388 0 : return;
4389 :
4390 : /*
4391 : * If there were empty grouping sets they should have been in the
4392 : * first rollup.
4393 : */
4394 : Assert(!unhashed_rollup || !empty_sets);
4395 :
4396 722 : if (unhashed_rollup)
4397 : {
4398 30 : new_rollups = lappend(new_rollups, unhashed_rollup);
4399 30 : strat = AGG_MIXED;
4400 : }
4401 692 : else if (empty_sets)
4402 : {
4403 405 : RollupData *rollup = makeNode(RollupData);
4404 :
4405 405 : rollup->groupClause = NIL;
4406 405 : rollup->gsets_data = empty_sets_data;
4407 405 : rollup->gsets = empty_sets;
4408 405 : rollup->numGroups = list_length(empty_sets);
4409 405 : rollup->hashable = false;
4410 405 : rollup->is_hashed = false;
4411 405 : new_rollups = lappend(new_rollups, rollup);
4412 405 : strat = AGG_MIXED;
4413 : }
4414 :
4415 722 : add_path(grouped_rel, (Path *)
4416 722 : create_groupingsets_path(root,
4417 : grouped_rel,
4418 : path,
4419 722 : (List *) parse->havingQual,
4420 : strat,
4421 : new_rollups,
4422 : agg_costs));
4423 722 : return;
4424 : }
4425 :
4426 : /*
4427 : * If we have sorted input but nothing we can do with it, bail.
4428 : */
4429 885 : if (gd->rollups == NIL)
4430 0 : return;
4431 :
4432 : /*
4433 : * Given sorted input, we try and make two paths: one sorted and one mixed
4434 : * sort/hash. (We need to try both because hashagg might be disabled, or
4435 : * some columns might not be sortable.)
4436 : *
4437 : * can_hash is passed in as false if some obstacle elsewhere (such as
4438 : * ordered aggs) means that we shouldn't consider hashing at all.
4439 : */
4440 885 : if (can_hash && gd->any_hashable)
4441 : {
4442 806 : List *rollups = NIL;
4443 806 : List *hash_sets = list_copy(gd->unsortable_sets);
4444 806 : double availspace = hash_mem_limit;
4445 : ListCell *lc;
4446 :
4447 : /*
4448 : * Account first for space needed for groups we can't sort at all.
4449 : */
4450 806 : availspace -= estimate_hashagg_tablesize(root,
4451 : path,
4452 : agg_costs,
4453 : gd->dNumHashGroups);
4454 :
4455 806 : if (availspace > 0 && list_length(gd->rollups) > 1)
4456 : {
4457 : double scale;
4458 411 : int num_rollups = list_length(gd->rollups);
4459 : int k_capacity;
4460 411 : int *k_weights = palloc(num_rollups * sizeof(int));
4461 411 : Bitmapset *hash_items = NULL;
4462 : int i;
4463 :
4464 : /*
4465 : * We treat this as a knapsack problem: the knapsack capacity
4466 : * represents hash_mem, the item weights are the estimated memory
4467 : * usage of the hashtables needed to implement a single rollup,
4468 : * and we really ought to use the cost saving as the item value;
4469 : * however, currently the costs assigned to sort nodes don't
4470 : * reflect the comparison costs well, and so we treat all items as
4471 : * of equal value (each rollup we hash instead saves us one sort).
4472 : *
4473 : * To use the discrete knapsack, we need to scale the values to a
4474 : * reasonably small bounded range. We choose to allow a 5% error
4475 : * margin; we have no more than 4096 rollups in the worst possible
4476 : * case, which with a 5% error margin will require a bit over 42MB
4477 : * of workspace. (Anyone wanting to plan queries that complex had
4478 : * better have the memory for it. In more reasonable cases, with
4479 : * no more than a couple of dozen rollups, the memory usage will
4480 : * be negligible.)
4481 : *
4482 : * k_capacity is naturally bounded, but we clamp the values for
4483 : * scale and weight (below) to avoid overflows or underflows (or
4484 : * uselessly trying to use a scale factor less than 1 byte).
4485 : */
4486 411 : scale = Max(availspace / (20.0 * num_rollups), 1.0);
4487 411 : k_capacity = (int) floor(availspace / scale);
4488 :
4489 : /*
4490 : * We leave the first rollup out of consideration since it's the
4491 : * one that matches the input sort order. We assign indexes "i"
4492 : * to only those entries considered for hashing; the second loop,
4493 : * below, must use the same condition.
4494 : */
4495 411 : i = 0;
4496 1042 : for_each_from(lc, gd->rollups, 1)
4497 : {
4498 631 : RollupData *rollup = lfirst_node(RollupData, lc);
4499 :
4500 631 : if (rollup->hashable)
4501 : {
4502 631 : double sz = estimate_hashagg_tablesize(root,
4503 : path,
4504 : agg_costs,
4505 : rollup->numGroups);
4506 :
4507 : /*
4508 : * If sz is enormous, but hash_mem (and hence scale) is
4509 : * small, avoid integer overflow here.
4510 : */
4511 631 : k_weights[i] = (int) Min(floor(sz / scale),
4512 : k_capacity + 1.0);
4513 631 : ++i;
4514 : }
4515 : }
4516 :
4517 : /*
4518 : * Apply knapsack algorithm; compute the set of items which
4519 : * maximizes the value stored (in this case the number of sorts
4520 : * saved) while keeping the total size (approximately) within
4521 : * capacity.
4522 : */
4523 411 : if (i > 0)
4524 411 : hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4525 :
4526 411 : if (!bms_is_empty(hash_items))
4527 : {
4528 411 : rollups = list_make1(linitial(gd->rollups));
4529 :
4530 411 : i = 0;
4531 1042 : for_each_from(lc, gd->rollups, 1)
4532 : {
4533 631 : RollupData *rollup = lfirst_node(RollupData, lc);
4534 :
4535 631 : if (rollup->hashable)
4536 : {
4537 631 : if (bms_is_member(i, hash_items))
4538 601 : hash_sets = list_concat(hash_sets,
4539 601 : rollup->gsets_data);
4540 : else
4541 30 : rollups = lappend(rollups, rollup);
4542 631 : ++i;
4543 : }
4544 : else
4545 0 : rollups = lappend(rollups, rollup);
4546 : }
4547 : }
4548 : }
4549 :
4550 806 : if (!rollups && hash_sets)
4551 20 : rollups = list_copy(gd->rollups);
4552 :
4553 1523 : foreach(lc, hash_sets)
4554 : {
4555 717 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
4556 717 : RollupData *rollup = makeNode(RollupData);
4557 :
4558 : Assert(gs->set != NIL);
4559 :
4560 717 : rollup->groupClause = preprocess_groupclause(root, gs->set);
4561 717 : rollup->gsets_data = list_make1(gs);
4562 717 : rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4563 : rollup->gsets_data,
4564 : gd->tleref_to_colnum_map);
4565 717 : rollup->numGroups = gs->numGroups;
4566 717 : rollup->hashable = true;
4567 717 : rollup->is_hashed = true;
4568 717 : rollups = lcons(rollup, rollups);
4569 : }
4570 :
4571 806 : if (rollups)
4572 : {
4573 431 : add_path(grouped_rel, (Path *)
4574 431 : create_groupingsets_path(root,
4575 : grouped_rel,
4576 : path,
4577 431 : (List *) parse->havingQual,
4578 : AGG_MIXED,
4579 : rollups,
4580 : agg_costs));
4581 : }
4582 : }
4583 :
4584 : /*
4585 : * Now try the simple sorted case.
4586 : */
4587 885 : if (!gd->unsortable_sets)
4588 861 : add_path(grouped_rel, (Path *)
4589 861 : create_groupingsets_path(root,
4590 : grouped_rel,
4591 : path,
4592 861 : (List *) parse->havingQual,
4593 : AGG_SORTED,
4594 : gd->rollups,
4595 : agg_costs));
4596 : }
4597 :
4598 : /*
4599 : * create_window_paths
4600 : *
4601 : * Build a new upperrel containing Paths for window-function evaluation.
4602 : *
4603 : * input_rel: contains the source-data Paths
4604 : * input_target: result of make_window_input_target
4605 : * output_target: what the topmost WindowAggPath should return
4606 : * wflists: result of find_window_functions
4607 : * activeWindows: result of select_active_windows
4608 : *
4609 : * Note: all Paths in input_rel are expected to return input_target.
4610 : */
4611 : static RelOptInfo *
4612 2192 : create_window_paths(PlannerInfo *root,
4613 : RelOptInfo *input_rel,
4614 : PathTarget *input_target,
4615 : PathTarget *output_target,
4616 : bool output_target_parallel_safe,
4617 : WindowFuncLists *wflists,
4618 : List *activeWindows)
4619 : {
4620 : RelOptInfo *window_rel;
4621 : ListCell *lc;
4622 :
4623 : /* For now, do all work in the (WINDOW, NULL) upperrel */
4624 2192 : window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4625 :
4626 : /*
4627 : * If the input relation is not parallel-safe, then the window relation
4628 : * can't be parallel-safe, either. Otherwise, we need to examine the
4629 : * target list and active windows for non-parallel-safe constructs.
4630 : */
4631 2192 : if (input_rel->consider_parallel && output_target_parallel_safe &&
4632 0 : is_parallel_safe(root, (Node *) activeWindows))
4633 0 : window_rel->consider_parallel = true;
4634 :
4635 : /*
4636 : * If the input rel belongs to a single FDW, so does the window rel.
4637 : */
4638 2192 : window_rel->serverid = input_rel->serverid;
4639 2192 : window_rel->userid = input_rel->userid;
4640 2192 : window_rel->useridiscurrent = input_rel->useridiscurrent;
4641 2192 : window_rel->fdwroutine = input_rel->fdwroutine;
4642 :
4643 : /*
4644 : * Consider computing window functions starting from the existing
4645 : * cheapest-total path (which will likely require a sort) as well as any
4646 : * existing paths that satisfy or partially satisfy root->window_pathkeys.
4647 : */
4648 4646 : foreach(lc, input_rel->pathlist)
4649 : {
4650 2454 : Path *path = (Path *) lfirst(lc);
4651 : int presorted_keys;
4652 :
4653 2716 : if (path == input_rel->cheapest_total_path ||
4654 262 : pathkeys_count_contained_in(root->window_pathkeys, path->pathkeys,
4655 116 : &presorted_keys) ||
4656 116 : presorted_keys > 0)
4657 2359 : create_one_window_path(root,
4658 : window_rel,
4659 : path,
4660 : input_target,
4661 : output_target,
4662 : wflists,
4663 : activeWindows);
4664 : }
4665 :
4666 : /*
4667 : * If there is an FDW that's responsible for all baserels of the query,
4668 : * let it consider adding ForeignPaths.
4669 : */
4670 2192 : if (window_rel->fdwroutine &&
4671 6 : window_rel->fdwroutine->GetForeignUpperPaths)
4672 6 : window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4673 : input_rel, window_rel,
4674 : NULL);
4675 :
4676 : /* Let extensions possibly add some more paths */
4677 2192 : if (create_upper_paths_hook)
4678 0 : (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4679 : input_rel, window_rel, NULL);
4680 :
4681 : /* Now choose the best path(s) */
4682 2192 : set_cheapest(window_rel);
4683 :
4684 2192 : return window_rel;
4685 : }
4686 :
4687 : /*
4688 : * Stack window-function implementation steps atop the given Path, and
4689 : * add the result to window_rel.
4690 : *
4691 : * window_rel: upperrel to contain result
4692 : * path: input Path to use (must return input_target)
4693 : * input_target: result of make_window_input_target
4694 : * output_target: what the topmost WindowAggPath should return
4695 : * wflists: result of find_window_functions
4696 : * activeWindows: result of select_active_windows
4697 : */
4698 : static void
4699 2359 : create_one_window_path(PlannerInfo *root,
4700 : RelOptInfo *window_rel,
4701 : Path *path,
4702 : PathTarget *input_target,
4703 : PathTarget *output_target,
4704 : WindowFuncLists *wflists,
4705 : List *activeWindows)
4706 : {
4707 : PathTarget *window_target;
4708 : ListCell *l;
4709 2359 : List *topqual = NIL;
4710 :
4711 : /*
4712 : * Since each window clause could require a different sort order, we stack
4713 : * up a WindowAgg node for each clause, with sort steps between them as
4714 : * needed. (We assume that select_active_windows chose a good order for
4715 : * executing the clauses in.)
4716 : *
4717 : * input_target should contain all Vars and Aggs needed for the result.
4718 : * (In some cases we wouldn't need to propagate all of these all the way
4719 : * to the top, since they might only be needed as inputs to WindowFuncs.
4720 : * It's probably not worth trying to optimize that though.) It must also
4721 : * contain all window partitioning and sorting expressions, to ensure
4722 : * they're computed only once at the bottom of the stack (that's critical
4723 : * for volatile functions). As we climb up the stack, we'll add outputs
4724 : * for the WindowFuncs computed at each level.
4725 : */
4726 2359 : window_target = input_target;
4727 :
4728 4873 : foreach(l, activeWindows)
4729 : {
4730 2514 : WindowClause *wc = lfirst_node(WindowClause, l);
4731 : List *window_pathkeys;
4732 2514 : List *runcondition = NIL;
4733 : int presorted_keys;
4734 : bool is_sorted;
4735 : bool topwindow;
4736 : ListCell *lc2;
4737 :
4738 2514 : window_pathkeys = make_pathkeys_for_window(root,
4739 : wc,
4740 : root->processed_tlist);
4741 :
4742 2514 : is_sorted = pathkeys_count_contained_in(window_pathkeys,
4743 : path->pathkeys,
4744 : &presorted_keys);
4745 :
4746 : /* Sort if necessary */
4747 2514 : if (!is_sorted)
4748 : {
4749 : /*
4750 : * No presorted keys or incremental sort disabled, just perform a
4751 : * complete sort.
4752 : */
4753 1811 : if (presorted_keys == 0 || !enable_incremental_sort)
4754 1760 : path = (Path *) create_sort_path(root, window_rel,
4755 : path,
4756 : window_pathkeys,
4757 : -1.0);
4758 : else
4759 : {
4760 : /*
4761 : * Since we have presorted keys and incremental sort is
4762 : * enabled, just use incremental sort.
4763 : */
4764 51 : path = (Path *) create_incremental_sort_path(root,
4765 : window_rel,
4766 : path,
4767 : window_pathkeys,
4768 : presorted_keys,
4769 : -1.0);
4770 : }
4771 : }
4772 :
4773 2514 : if (lnext(activeWindows, l))
4774 : {
4775 : /*
4776 : * Add the current WindowFuncs to the output target for this
4777 : * intermediate WindowAggPath. We must copy window_target to
4778 : * avoid changing the previous path's target.
4779 : *
4780 : * Note: a WindowFunc adds nothing to the target's eval costs; but
4781 : * we do need to account for the increase in tlist width.
4782 : */
4783 155 : int64 tuple_width = window_target->width;
4784 :
4785 155 : window_target = copy_pathtarget(window_target);
4786 370 : foreach(lc2, wflists->windowFuncs[wc->winref])
4787 : {
4788 215 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4789 :
4790 215 : add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4791 215 : tuple_width += get_typavgwidth(wfunc->wintype, -1);
4792 : }
4793 155 : window_target->width = clamp_width_est(tuple_width);
4794 : }
4795 : else
4796 : {
4797 : /* Install the goal target in the topmost WindowAgg */
4798 2359 : window_target = output_target;
4799 : }
4800 :
4801 : /* mark the final item in the list as the top-level window */
4802 2514 : topwindow = foreach_current_index(l) == list_length(activeWindows) - 1;
4803 :
4804 : /*
4805 : * Collect the WindowFuncRunConditions from each WindowFunc and
4806 : * convert them into OpExprs
4807 : */
4808 5761 : foreach(lc2, wflists->windowFuncs[wc->winref])
4809 : {
4810 : ListCell *lc3;
4811 3247 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4812 :
4813 3397 : foreach(lc3, wfunc->runCondition)
4814 : {
4815 150 : WindowFuncRunCondition *wfuncrc =
4816 : lfirst_node(WindowFuncRunCondition, lc3);
4817 : Expr *opexpr;
4818 : Expr *leftop;
4819 : Expr *rightop;
4820 :
4821 150 : if (wfuncrc->wfunc_left)
4822 : {
4823 135 : leftop = (Expr *) copyObject(wfunc);
4824 135 : rightop = copyObject(wfuncrc->arg);
4825 : }
4826 : else
4827 : {
4828 15 : leftop = copyObject(wfuncrc->arg);
4829 15 : rightop = (Expr *) copyObject(wfunc);
4830 : }
4831 :
4832 150 : opexpr = make_opclause(wfuncrc->opno,
4833 : BOOLOID,
4834 : false,
4835 : leftop,
4836 : rightop,
4837 : InvalidOid,
4838 : wfuncrc->inputcollid);
4839 :
4840 150 : runcondition = lappend(runcondition, opexpr);
4841 :
4842 150 : if (!topwindow)
4843 20 : topqual = lappend(topqual, opexpr);
4844 : }
4845 : }
4846 :
4847 : path = (Path *)
4848 2514 : create_windowagg_path(root, window_rel, path, window_target,
4849 2514 : wflists->windowFuncs[wc->winref],
4850 : runcondition, wc,
4851 : topwindow ? topqual : NIL, topwindow);
4852 : }
4853 :
4854 2359 : add_path(window_rel, path);
4855 2359 : }
4856 :
4857 : /*
4858 : * create_distinct_paths
4859 : *
4860 : * Build a new upperrel containing Paths for SELECT DISTINCT evaluation.
4861 : *
4862 : * input_rel: contains the source-data Paths
4863 : * target: the pathtarget for the result Paths to compute
4864 : *
4865 : * Note: input paths should already compute the desired pathtarget, since
4866 : * Sort/Unique won't project anything.
4867 : */
4868 : static RelOptInfo *
4869 1931 : create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
4870 : PathTarget *target)
4871 : {
4872 : RelOptInfo *distinct_rel;
4873 :
4874 : /* For now, do all work in the (DISTINCT, NULL) upperrel */
4875 1931 : distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4876 :
4877 : /*
4878 : * We don't compute anything at this level, so distinct_rel will be
4879 : * parallel-safe if the input rel is parallel-safe. In particular, if
4880 : * there is a DISTINCT ON (...) clause, any path for the input_rel will
4881 : * output those expressions, and will not be parallel-safe unless those
4882 : * expressions are parallel-safe.
4883 : */
4884 1931 : distinct_rel->consider_parallel = input_rel->consider_parallel;
4885 :
4886 : /*
4887 : * If the input rel belongs to a single FDW, so does the distinct_rel.
4888 : */
4889 1931 : distinct_rel->serverid = input_rel->serverid;
4890 1931 : distinct_rel->userid = input_rel->userid;
4891 1931 : distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4892 1931 : distinct_rel->fdwroutine = input_rel->fdwroutine;
4893 :
4894 : /* build distinct paths based on input_rel's pathlist */
4895 1931 : create_final_distinct_paths(root, input_rel, distinct_rel);
4896 :
4897 : /* now build distinct paths based on input_rel's partial_pathlist */
4898 1931 : create_partial_distinct_paths(root, input_rel, distinct_rel, target);
4899 :
4900 : /* Give a helpful error if we failed to create any paths */
4901 1931 : if (distinct_rel->pathlist == NIL)
4902 0 : ereport(ERROR,
4903 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4904 : errmsg("could not implement DISTINCT"),
4905 : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4906 :
4907 : /*
4908 : * If there is an FDW that's responsible for all baserels of the query,
4909 : * let it consider adding ForeignPaths.
4910 : */
4911 1931 : if (distinct_rel->fdwroutine &&
4912 8 : distinct_rel->fdwroutine->GetForeignUpperPaths)
4913 8 : distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4914 : UPPERREL_DISTINCT,
4915 : input_rel,
4916 : distinct_rel,
4917 : NULL);
4918 :
4919 : /* Let extensions possibly add some more paths */
4920 1931 : if (create_upper_paths_hook)
4921 0 : (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
4922 : distinct_rel, NULL);
4923 :
4924 : /* Now choose the best path(s) */
4925 1931 : set_cheapest(distinct_rel);
4926 :
4927 1931 : return distinct_rel;
4928 : }
4929 :
4930 : /*
4931 : * create_partial_distinct_paths
4932 : *
4933 : * Process 'input_rel' partial paths and add unique/aggregate paths to the
4934 : * UPPERREL_PARTIAL_DISTINCT rel. For paths created, add Gather/GatherMerge
4935 : * paths on top and add a final unique/aggregate path to remove any duplicate
4936 : * produced from combining rows from parallel workers.
4937 : */
4938 : static void
4939 1931 : create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
4940 : RelOptInfo *final_distinct_rel,
4941 : PathTarget *target)
4942 : {
4943 : RelOptInfo *partial_distinct_rel;
4944 : Query *parse;
4945 : List *distinctExprs;
4946 : double numDistinctRows;
4947 : Path *cheapest_partial_path;
4948 : ListCell *lc;
4949 :
4950 : /* nothing to do when there are no partial paths in the input rel */
4951 1931 : if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
4952 1841 : return;
4953 :
4954 90 : parse = root->parse;
4955 :
4956 : /* can't do parallel DISTINCT ON */
4957 90 : if (parse->hasDistinctOn)
4958 0 : return;
4959 :
4960 90 : partial_distinct_rel = fetch_upper_rel(root, UPPERREL_PARTIAL_DISTINCT,
4961 : NULL);
4962 90 : partial_distinct_rel->reltarget = target;
4963 90 : partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
4964 :
4965 : /*
4966 : * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
4967 : */
4968 90 : partial_distinct_rel->serverid = input_rel->serverid;
4969 90 : partial_distinct_rel->userid = input_rel->userid;
4970 90 : partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4971 90 : partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
4972 :
4973 90 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
4974 :
4975 90 : distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
4976 : parse->targetList);
4977 :
4978 : /* estimate how many distinct rows we'll get from each worker */
4979 90 : numDistinctRows = estimate_num_groups(root, distinctExprs,
4980 : cheapest_partial_path->rows,
4981 : NULL, NULL);
4982 :
4983 : /*
4984 : * Try sorting the cheapest path and incrementally sorting any paths with
4985 : * presorted keys and put a unique paths atop of those. We'll also
4986 : * attempt to reorder the required pathkeys to match the input path's
4987 : * pathkeys as much as possible, in hopes of avoiding a possible need to
4988 : * re-sort.
4989 : */
4990 90 : if (grouping_is_sortable(root->processed_distinctClause))
4991 : {
4992 193 : foreach(lc, input_rel->partial_pathlist)
4993 : {
4994 103 : Path *input_path = (Path *) lfirst(lc);
4995 : Path *sorted_path;
4996 103 : List *useful_pathkeys_list = NIL;
4997 :
4998 : useful_pathkeys_list =
4999 103 : get_useful_pathkeys_for_distinct(root,
5000 : root->distinct_pathkeys,
5001 : input_path->pathkeys);
5002 : Assert(list_length(useful_pathkeys_list) > 0);
5003 :
5004 319 : foreach_node(List, useful_pathkeys, useful_pathkeys_list)
5005 : {
5006 113 : sorted_path = make_ordered_path(root,
5007 : partial_distinct_rel,
5008 : input_path,
5009 : cheapest_partial_path,
5010 : useful_pathkeys,
5011 : -1.0);
5012 :
5013 113 : if (sorted_path == NULL)
5014 8 : continue;
5015 :
5016 : /*
5017 : * An empty distinct_pathkeys means all tuples have the same
5018 : * value for the DISTINCT clause. See
5019 : * create_final_distinct_paths()
5020 : */
5021 105 : if (root->distinct_pathkeys == NIL)
5022 : {
5023 : Node *limitCount;
5024 :
5025 5 : limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5026 : sizeof(int64),
5027 : Int64GetDatum(1), false,
5028 : true);
5029 :
5030 : /*
5031 : * Apply a LimitPath onto the partial path to restrict the
5032 : * tuples from each worker to 1.
5033 : * create_final_distinct_paths will need to apply an
5034 : * additional LimitPath to restrict this to a single row
5035 : * after the Gather node. If the query already has a
5036 : * LIMIT clause, then we could end up with three Limit
5037 : * nodes in the final plan. Consolidating the top two of
5038 : * these could be done, but does not seem worth troubling
5039 : * over.
5040 : */
5041 5 : add_partial_path(partial_distinct_rel, (Path *)
5042 5 : create_limit_path(root, partial_distinct_rel,
5043 : sorted_path,
5044 : NULL,
5045 : limitCount,
5046 : LIMIT_OPTION_COUNT,
5047 : 0, 1));
5048 : }
5049 : else
5050 : {
5051 100 : add_partial_path(partial_distinct_rel, (Path *)
5052 100 : create_unique_path(root, partial_distinct_rel,
5053 : sorted_path,
5054 100 : list_length(root->distinct_pathkeys),
5055 : numDistinctRows));
5056 : }
5057 : }
5058 : }
5059 : }
5060 :
5061 : /*
5062 : * Now try hash aggregate paths, if enabled and hashing is possible. Since
5063 : * we're not on the hook to ensure we do our best to create at least one
5064 : * path here, we treat enable_hashagg as a hard off-switch rather than the
5065 : * slightly softer variant in create_final_distinct_paths.
5066 : */
5067 90 : if (enable_hashagg && grouping_is_hashable(root->processed_distinctClause))
5068 : {
5069 65 : add_partial_path(partial_distinct_rel, (Path *)
5070 65 : create_agg_path(root,
5071 : partial_distinct_rel,
5072 : cheapest_partial_path,
5073 : cheapest_partial_path->pathtarget,
5074 : AGG_HASHED,
5075 : AGGSPLIT_SIMPLE,
5076 : root->processed_distinctClause,
5077 : NIL,
5078 : NULL,
5079 : numDistinctRows));
5080 : }
5081 :
5082 : /*
5083 : * If there is an FDW that's responsible for all baserels of the query,
5084 : * let it consider adding ForeignPaths.
5085 : */
5086 90 : if (partial_distinct_rel->fdwroutine &&
5087 0 : partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
5088 0 : partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
5089 : UPPERREL_PARTIAL_DISTINCT,
5090 : input_rel,
5091 : partial_distinct_rel,
5092 : NULL);
5093 :
5094 : /* Let extensions possibly add some more partial paths */
5095 90 : if (create_upper_paths_hook)
5096 0 : (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
5097 : input_rel, partial_distinct_rel, NULL);
5098 :
5099 90 : if (partial_distinct_rel->partial_pathlist != NIL)
5100 : {
5101 90 : generate_useful_gather_paths(root, partial_distinct_rel, true);
5102 90 : set_cheapest(partial_distinct_rel);
5103 :
5104 : /*
5105 : * Finally, create paths to distinctify the final result. This step
5106 : * is needed to remove any duplicates due to combining rows from
5107 : * parallel workers.
5108 : */
5109 90 : create_final_distinct_paths(root, partial_distinct_rel,
5110 : final_distinct_rel);
5111 : }
5112 : }
5113 :
5114 : /*
5115 : * create_final_distinct_paths
5116 : * Create distinct paths in 'distinct_rel' based on 'input_rel' pathlist
5117 : *
5118 : * input_rel: contains the source-data paths
5119 : * distinct_rel: destination relation for storing created paths
5120 : */
5121 : static RelOptInfo *
5122 2021 : create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
5123 : RelOptInfo *distinct_rel)
5124 : {
5125 2021 : Query *parse = root->parse;
5126 2021 : Path *cheapest_input_path = input_rel->cheapest_total_path;
5127 : double numDistinctRows;
5128 : bool allow_hash;
5129 :
5130 : /* Estimate number of distinct rows there will be */
5131 2021 : if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
5132 1962 : root->hasHavingQual)
5133 : {
5134 : /*
5135 : * If there was grouping or aggregation, use the number of input rows
5136 : * as the estimated number of DISTINCT rows (ie, assume the input is
5137 : * already mostly unique).
5138 : */
5139 59 : numDistinctRows = cheapest_input_path->rows;
5140 : }
5141 : else
5142 : {
5143 : /*
5144 : * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
5145 : */
5146 : List *distinctExprs;
5147 :
5148 1962 : distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
5149 : parse->targetList);
5150 1962 : numDistinctRows = estimate_num_groups(root, distinctExprs,
5151 : cheapest_input_path->rows,
5152 : NULL, NULL);
5153 : }
5154 :
5155 : /*
5156 : * Consider sort-based implementations of DISTINCT, if possible.
5157 : */
5158 2021 : if (grouping_is_sortable(root->processed_distinctClause))
5159 : {
5160 : /*
5161 : * Firstly, if we have any adequately-presorted paths, just stick a
5162 : * Unique node on those. We also, consider doing an explicit sort of
5163 : * the cheapest input path and Unique'ing that. If any paths have
5164 : * presorted keys then we'll create an incremental sort atop of those
5165 : * before adding a unique node on the top. We'll also attempt to
5166 : * reorder the required pathkeys to match the input path's pathkeys as
5167 : * much as possible, in hopes of avoiding a possible need to re-sort.
5168 : *
5169 : * When we have DISTINCT ON, we must sort by the more rigorous of
5170 : * DISTINCT and ORDER BY, else it won't have the desired behavior.
5171 : * Also, if we do have to do an explicit sort, we might as well use
5172 : * the more rigorous ordering to avoid a second sort later. (Note
5173 : * that the parser will have ensured that one clause is a prefix of
5174 : * the other.)
5175 : */
5176 : List *needed_pathkeys;
5177 : ListCell *lc;
5178 2016 : double limittuples = root->distinct_pathkeys == NIL ? 1.0 : -1.0;
5179 :
5180 2195 : if (parse->hasDistinctOn &&
5181 179 : list_length(root->distinct_pathkeys) <
5182 179 : list_length(root->sort_pathkeys))
5183 45 : needed_pathkeys = root->sort_pathkeys;
5184 : else
5185 1971 : needed_pathkeys = root->distinct_pathkeys;
5186 :
5187 5376 : foreach(lc, input_rel->pathlist)
5188 : {
5189 3360 : Path *input_path = (Path *) lfirst(lc);
5190 : Path *sorted_path;
5191 3360 : List *useful_pathkeys_list = NIL;
5192 :
5193 : useful_pathkeys_list =
5194 3360 : get_useful_pathkeys_for_distinct(root,
5195 : needed_pathkeys,
5196 : input_path->pathkeys);
5197 : Assert(list_length(useful_pathkeys_list) > 0);
5198 :
5199 10578 : foreach_node(List, useful_pathkeys, useful_pathkeys_list)
5200 : {
5201 3858 : sorted_path = make_ordered_path(root,
5202 : distinct_rel,
5203 : input_path,
5204 : cheapest_input_path,
5205 : useful_pathkeys,
5206 : limittuples);
5207 :
5208 3858 : if (sorted_path == NULL)
5209 529 : continue;
5210 :
5211 : /*
5212 : * distinct_pathkeys may have become empty if all of the
5213 : * pathkeys were determined to be redundant. If all of the
5214 : * pathkeys are redundant then each DISTINCT target must only
5215 : * allow a single value, therefore all resulting tuples must
5216 : * be identical (or at least indistinguishable by an equality
5217 : * check). We can uniquify these tuples simply by just taking
5218 : * the first tuple. All we do here is add a path to do "LIMIT
5219 : * 1" atop of 'sorted_path'. When doing a DISTINCT ON we may
5220 : * still have a non-NIL sort_pathkeys list, so we must still
5221 : * only do this with paths which are correctly sorted by
5222 : * sort_pathkeys.
5223 : */
5224 3329 : if (root->distinct_pathkeys == NIL)
5225 : {
5226 : Node *limitCount;
5227 :
5228 96 : limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5229 : sizeof(int64),
5230 : Int64GetDatum(1), false,
5231 : true);
5232 :
5233 : /*
5234 : * If the query already has a LIMIT clause, then we could
5235 : * end up with a duplicate LimitPath in the final plan.
5236 : * That does not seem worth troubling over too much.
5237 : */
5238 96 : add_path(distinct_rel, (Path *)
5239 96 : create_limit_path(root, distinct_rel, sorted_path,
5240 : NULL, limitCount,
5241 : LIMIT_OPTION_COUNT, 0, 1));
5242 : }
5243 : else
5244 : {
5245 3233 : add_path(distinct_rel, (Path *)
5246 3233 : create_unique_path(root, distinct_rel,
5247 : sorted_path,
5248 3233 : list_length(root->distinct_pathkeys),
5249 : numDistinctRows));
5250 : }
5251 : }
5252 : }
5253 : }
5254 :
5255 : /*
5256 : * Consider hash-based implementations of DISTINCT, if possible.
5257 : *
5258 : * If we were not able to make any other types of path, we *must* hash or
5259 : * die trying. If we do have other choices, there are two things that
5260 : * should prevent selection of hashing: if the query uses DISTINCT ON
5261 : * (because it won't really have the expected behavior if we hash), or if
5262 : * enable_hashagg is off.
5263 : *
5264 : * Note: grouping_is_hashable() is much more expensive to check than the
5265 : * other gating conditions, so we want to do it last.
5266 : */
5267 2021 : if (distinct_rel->pathlist == NIL)
5268 5 : allow_hash = true; /* we have no alternatives */
5269 2016 : else if (parse->hasDistinctOn || !enable_hashagg)
5270 304 : allow_hash = false; /* policy-based decision not to hash */
5271 : else
5272 1712 : allow_hash = true; /* default */
5273 :
5274 2021 : if (allow_hash && grouping_is_hashable(root->processed_distinctClause))
5275 : {
5276 : /* Generate hashed aggregate path --- no sort needed */
5277 1717 : add_path(distinct_rel, (Path *)
5278 1717 : create_agg_path(root,
5279 : distinct_rel,
5280 : cheapest_input_path,
5281 : cheapest_input_path->pathtarget,
5282 : AGG_HASHED,
5283 : AGGSPLIT_SIMPLE,
5284 : root->processed_distinctClause,
5285 : NIL,
5286 : NULL,
5287 : numDistinctRows));
5288 : }
5289 :
5290 2021 : return distinct_rel;
5291 : }
5292 :
5293 : /*
5294 : * get_useful_pathkeys_for_distinct
5295 : * Get useful orderings of pathkeys for distinctClause by reordering
5296 : * 'needed_pathkeys' to match the given 'path_pathkeys' as much as possible.
5297 : *
5298 : * This returns a list of pathkeys that can be useful for DISTINCT or DISTINCT
5299 : * ON clause. For convenience, it always includes the given 'needed_pathkeys'.
5300 : */
5301 : static List *
5302 3463 : get_useful_pathkeys_for_distinct(PlannerInfo *root, List *needed_pathkeys,
5303 : List *path_pathkeys)
5304 : {
5305 3463 : List *useful_pathkeys_list = NIL;
5306 3463 : List *useful_pathkeys = NIL;
5307 :
5308 : /* always include the given 'needed_pathkeys' */
5309 3463 : useful_pathkeys_list = lappend(useful_pathkeys_list,
5310 : needed_pathkeys);
5311 :
5312 3463 : if (!enable_distinct_reordering)
5313 0 : return useful_pathkeys_list;
5314 :
5315 : /*
5316 : * Scan the given 'path_pathkeys' and construct a list of PathKey nodes
5317 : * that match 'needed_pathkeys', but only up to the longest matching
5318 : * prefix.
5319 : *
5320 : * When we have DISTINCT ON, we must ensure that the resulting pathkey
5321 : * list matches initial distinctClause pathkeys; otherwise, it won't have
5322 : * the desired behavior.
5323 : */
5324 8634 : foreach_node(PathKey, pathkey, path_pathkeys)
5325 : {
5326 : /*
5327 : * The PathKey nodes are canonical, so they can be checked for
5328 : * equality by simple pointer comparison.
5329 : */
5330 1730 : if (!list_member_ptr(needed_pathkeys, pathkey))
5331 7 : break;
5332 1723 : if (root->parse->hasDistinctOn &&
5333 139 : !list_member_ptr(root->distinct_pathkeys, pathkey))
5334 15 : break;
5335 :
5336 1708 : useful_pathkeys = lappend(useful_pathkeys, pathkey);
5337 : }
5338 :
5339 : /* If no match at all, no point in reordering needed_pathkeys */
5340 3463 : if (useful_pathkeys == NIL)
5341 1983 : return useful_pathkeys_list;
5342 :
5343 : /*
5344 : * If not full match, the resulting pathkey list is not useful without
5345 : * incremental sort.
5346 : */
5347 1480 : if (list_length(useful_pathkeys) < list_length(needed_pathkeys) &&
5348 920 : !enable_incremental_sort)
5349 48 : return useful_pathkeys_list;
5350 :
5351 : /* Append the remaining PathKey nodes in needed_pathkeys */
5352 1432 : useful_pathkeys = list_concat_unique_ptr(useful_pathkeys,
5353 : needed_pathkeys);
5354 :
5355 : /*
5356 : * If the resulting pathkey list is the same as the 'needed_pathkeys',
5357 : * just drop it.
5358 : */
5359 1432 : if (compare_pathkeys(needed_pathkeys,
5360 : useful_pathkeys) == PATHKEYS_EQUAL)
5361 924 : return useful_pathkeys_list;
5362 :
5363 508 : useful_pathkeys_list = lappend(useful_pathkeys_list,
5364 : useful_pathkeys);
5365 :
5366 508 : return useful_pathkeys_list;
5367 : }
5368 :
5369 : /*
5370 : * create_ordered_paths
5371 : *
5372 : * Build a new upperrel containing Paths for ORDER BY evaluation.
5373 : *
5374 : * All paths in the result must satisfy the ORDER BY ordering.
5375 : * The only new paths we need consider are an explicit full sort
5376 : * and incremental sort on the cheapest-total existing path.
5377 : *
5378 : * input_rel: contains the source-data Paths
5379 : * target: the output tlist the result Paths must emit
5380 : * limit_tuples: estimated bound on the number of output tuples,
5381 : * or -1 if no LIMIT or couldn't estimate
5382 : *
5383 : * XXX This only looks at sort_pathkeys. I wonder if it needs to look at the
5384 : * other pathkeys (grouping, ...) like generate_useful_gather_paths.
5385 : */
5386 : static RelOptInfo *
5387 61038 : create_ordered_paths(PlannerInfo *root,
5388 : RelOptInfo *input_rel,
5389 : PathTarget *target,
5390 : bool target_parallel_safe,
5391 : double limit_tuples)
5392 : {
5393 61038 : Path *cheapest_input_path = input_rel->cheapest_total_path;
5394 : RelOptInfo *ordered_rel;
5395 : ListCell *lc;
5396 :
5397 : /* For now, do all work in the (ORDERED, NULL) upperrel */
5398 61038 : ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
5399 :
5400 : /*
5401 : * If the input relation is not parallel-safe, then the ordered relation
5402 : * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
5403 : * target list is parallel-safe.
5404 : */
5405 61038 : if (input_rel->consider_parallel && target_parallel_safe)
5406 42574 : ordered_rel->consider_parallel = true;
5407 :
5408 : /* Assume that the same path generation strategies are allowed. */
5409 61038 : ordered_rel->pgs_mask = input_rel->pgs_mask;
5410 :
5411 : /*
5412 : * If the input rel belongs to a single FDW, so does the ordered_rel.
5413 : */
5414 61038 : ordered_rel->serverid = input_rel->serverid;
5415 61038 : ordered_rel->userid = input_rel->userid;
5416 61038 : ordered_rel->useridiscurrent = input_rel->useridiscurrent;
5417 61038 : ordered_rel->fdwroutine = input_rel->fdwroutine;
5418 :
5419 155849 : foreach(lc, input_rel->pathlist)
5420 : {
5421 94811 : Path *input_path = (Path *) lfirst(lc);
5422 : Path *sorted_path;
5423 : bool is_sorted;
5424 : int presorted_keys;
5425 :
5426 94811 : is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5427 : input_path->pathkeys, &presorted_keys);
5428 :
5429 94811 : if (is_sorted)
5430 36899 : sorted_path = input_path;
5431 : else
5432 : {
5433 : /*
5434 : * Try at least sorting the cheapest path and also try
5435 : * incrementally sorting any path which is partially sorted
5436 : * already (no need to deal with paths which have presorted keys
5437 : * when incremental sort is disabled unless it's the cheapest
5438 : * input path).
5439 : */
5440 57912 : if (input_path != cheapest_input_path &&
5441 4721 : (presorted_keys == 0 || !enable_incremental_sort))
5442 1636 : continue;
5443 :
5444 : /*
5445 : * We've no need to consider both a sort and incremental sort.
5446 : * We'll just do a sort if there are no presorted keys and an
5447 : * incremental sort when there are presorted keys.
5448 : */
5449 56276 : if (presorted_keys == 0 || !enable_incremental_sort)
5450 52750 : sorted_path = (Path *) create_sort_path(root,
5451 : ordered_rel,
5452 : input_path,
5453 : root->sort_pathkeys,
5454 : limit_tuples);
5455 : else
5456 3526 : sorted_path = (Path *) create_incremental_sort_path(root,
5457 : ordered_rel,
5458 : input_path,
5459 : root->sort_pathkeys,
5460 : presorted_keys,
5461 : limit_tuples);
5462 : }
5463 :
5464 : /*
5465 : * If the pathtarget of the result path has different expressions from
5466 : * the target to be applied, a projection step is needed.
5467 : */
5468 93175 : if (!equal(sorted_path->pathtarget->exprs, target->exprs))
5469 288 : sorted_path = apply_projection_to_path(root, ordered_rel,
5470 : sorted_path, target);
5471 :
5472 93175 : add_path(ordered_rel, sorted_path);
5473 : }
5474 :
5475 : /*
5476 : * generate_gather_paths() will have already generated a simple Gather
5477 : * path for the best parallel path, if any, and the loop above will have
5478 : * considered sorting it. Similarly, generate_gather_paths() will also
5479 : * have generated order-preserving Gather Merge plans which can be used
5480 : * without sorting if they happen to match the sort_pathkeys, and the loop
5481 : * above will have handled those as well. However, there's one more
5482 : * possibility: it may make sense to sort the cheapest partial path or
5483 : * incrementally sort any partial path that is partially sorted according
5484 : * to the required output order and then use Gather Merge.
5485 : */
5486 61038 : if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5487 42454 : input_rel->partial_pathlist != NIL)
5488 : {
5489 : Path *cheapest_partial_path;
5490 :
5491 2396 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
5492 :
5493 5347 : foreach(lc, input_rel->partial_pathlist)
5494 : {
5495 2951 : Path *input_path = (Path *) lfirst(lc);
5496 : Path *sorted_path;
5497 : bool is_sorted;
5498 : int presorted_keys;
5499 : double total_groups;
5500 :
5501 2951 : is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5502 : input_path->pathkeys,
5503 : &presorted_keys);
5504 :
5505 2951 : if (is_sorted)
5506 476 : continue;
5507 :
5508 : /*
5509 : * Try at least sorting the cheapest path and also try
5510 : * incrementally sorting any path which is partially sorted
5511 : * already (no need to deal with paths which have presorted keys
5512 : * when incremental sort is disabled unless it's the cheapest
5513 : * partial path).
5514 : */
5515 2475 : if (input_path != cheapest_partial_path &&
5516 101 : (presorted_keys == 0 || !enable_incremental_sort))
5517 0 : continue;
5518 :
5519 : /*
5520 : * We've no need to consider both a sort and incremental sort.
5521 : * We'll just do a sort if there are no presorted keys and an
5522 : * incremental sort when there are presorted keys.
5523 : */
5524 2475 : if (presorted_keys == 0 || !enable_incremental_sort)
5525 2359 : sorted_path = (Path *) create_sort_path(root,
5526 : ordered_rel,
5527 : input_path,
5528 : root->sort_pathkeys,
5529 : limit_tuples);
5530 : else
5531 116 : sorted_path = (Path *) create_incremental_sort_path(root,
5532 : ordered_rel,
5533 : input_path,
5534 : root->sort_pathkeys,
5535 : presorted_keys,
5536 : limit_tuples);
5537 2475 : total_groups = compute_gather_rows(sorted_path);
5538 : sorted_path = (Path *)
5539 2475 : create_gather_merge_path(root, ordered_rel,
5540 : sorted_path,
5541 : sorted_path->pathtarget,
5542 : root->sort_pathkeys, NULL,
5543 : &total_groups);
5544 :
5545 : /*
5546 : * If the pathtarget of the result path has different expressions
5547 : * from the target to be applied, a projection step is needed.
5548 : */
5549 2475 : if (!equal(sorted_path->pathtarget->exprs, target->exprs))
5550 5 : sorted_path = apply_projection_to_path(root, ordered_rel,
5551 : sorted_path, target);
5552 :
5553 2475 : add_path(ordered_rel, sorted_path);
5554 : }
5555 : }
5556 :
5557 : /*
5558 : * If there is an FDW that's responsible for all baserels of the query,
5559 : * let it consider adding ForeignPaths.
5560 : */
5561 61038 : if (ordered_rel->fdwroutine &&
5562 193 : ordered_rel->fdwroutine->GetForeignUpperPaths)
5563 185 : ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5564 : input_rel, ordered_rel,
5565 : NULL);
5566 :
5567 : /* Let extensions possibly add some more paths */
5568 61038 : if (create_upper_paths_hook)
5569 0 : (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5570 : input_rel, ordered_rel, NULL);
5571 :
5572 : /*
5573 : * No need to bother with set_cheapest here; grouping_planner does not
5574 : * need us to do it.
5575 : */
5576 : Assert(ordered_rel->pathlist != NIL);
5577 :
5578 61038 : return ordered_rel;
5579 : }
5580 :
5581 :
5582 : /*
5583 : * make_group_input_target
5584 : * Generate appropriate PathTarget for initial input to grouping nodes.
5585 : *
5586 : * If there is grouping or aggregation, the scan/join subplan cannot emit
5587 : * the query's final targetlist; for example, it certainly can't emit any
5588 : * aggregate function calls. This routine generates the correct target
5589 : * for the scan/join subplan.
5590 : *
5591 : * The query target list passed from the parser already contains entries
5592 : * for all ORDER BY and GROUP BY expressions, but it will not have entries
5593 : * for variables used only in HAVING clauses; so we need to add those
5594 : * variables to the subplan target list. Also, we flatten all expressions
5595 : * except GROUP BY items into their component variables; other expressions
5596 : * will be computed by the upper plan nodes rather than by the subplan.
5597 : * For example, given a query like
5598 : * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
5599 : * we want to pass this targetlist to the subplan:
5600 : * a+b,c,d
5601 : * where the a+b target will be used by the Sort/Group steps, and the
5602 : * other targets will be used for computing the final results.
5603 : *
5604 : * 'final_target' is the query's final target list (in PathTarget form)
5605 : *
5606 : * The result is the PathTarget to be computed by the Paths returned from
5607 : * query_planner().
5608 : */
5609 : static PathTarget *
5610 33561 : make_group_input_target(PlannerInfo *root, PathTarget *final_target)
5611 : {
5612 33561 : Query *parse = root->parse;
5613 : PathTarget *input_target;
5614 : List *non_group_cols;
5615 : List *non_group_vars;
5616 : int i;
5617 : ListCell *lc;
5618 :
5619 : /*
5620 : * We must build a target containing all grouping columns, plus any other
5621 : * Vars mentioned in the query's targetlist and HAVING qual.
5622 : */
5623 33561 : input_target = create_empty_pathtarget();
5624 33561 : non_group_cols = NIL;
5625 :
5626 33561 : i = 0;
5627 84423 : foreach(lc, final_target->exprs)
5628 : {
5629 50862 : Expr *expr = (Expr *) lfirst(lc);
5630 50862 : Index sgref = get_pathtarget_sortgroupref(final_target, i);
5631 :
5632 58716 : if (sgref && root->processed_groupClause &&
5633 7854 : get_sortgroupref_clause_noerr(sgref,
5634 : root->processed_groupClause) != NULL)
5635 : {
5636 : /*
5637 : * It's a grouping column, so add it to the input target as-is.
5638 : *
5639 : * Note that the target is logically below the grouping step. So
5640 : * with grouping sets we need to remove the RT index of the
5641 : * grouping step if there is any from the target expression.
5642 : */
5643 6343 : if (parse->hasGroupRTE && parse->groupingSets != NIL)
5644 : {
5645 : Assert(root->group_rtindex > 0);
5646 : expr = (Expr *)
5647 1703 : remove_nulling_relids((Node *) expr,
5648 1703 : bms_make_singleton(root->group_rtindex),
5649 : NULL);
5650 : }
5651 6343 : add_column_to_pathtarget(input_target, expr, sgref);
5652 : }
5653 : else
5654 : {
5655 : /*
5656 : * Non-grouping column, so just remember the expression for later
5657 : * call to pull_var_clause.
5658 : */
5659 44519 : non_group_cols = lappend(non_group_cols, expr);
5660 : }
5661 :
5662 50862 : i++;
5663 : }
5664 :
5665 : /*
5666 : * If there's a HAVING clause, we'll need the Vars it uses, too.
5667 : */
5668 33561 : if (parse->havingQual)
5669 758 : non_group_cols = lappend(non_group_cols, parse->havingQual);
5670 :
5671 : /*
5672 : * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5673 : * add them to the input target if not already present. (A Var used
5674 : * directly as a GROUP BY item will be present already.) Note this
5675 : * includes Vars used in resjunk items, so we are covering the needs of
5676 : * ORDER BY and window specifications. Vars used within Aggrefs and
5677 : * WindowFuncs will be pulled out here, too.
5678 : *
5679 : * Note that the target is logically below the grouping step. So with
5680 : * grouping sets we need to remove the RT index of the grouping step if
5681 : * there is any from the non-group Vars.
5682 : */
5683 33561 : non_group_vars = pull_var_clause((Node *) non_group_cols,
5684 : PVC_RECURSE_AGGREGATES |
5685 : PVC_RECURSE_WINDOWFUNCS |
5686 : PVC_INCLUDE_PLACEHOLDERS);
5687 33561 : if (parse->hasGroupRTE && parse->groupingSets != NIL)
5688 : {
5689 : Assert(root->group_rtindex > 0);
5690 : non_group_vars = (List *)
5691 786 : remove_nulling_relids((Node *) non_group_vars,
5692 786 : bms_make_singleton(root->group_rtindex),
5693 : NULL);
5694 : }
5695 33561 : add_new_columns_to_pathtarget(input_target, non_group_vars);
5696 :
5697 : /* clean up cruft */
5698 33561 : list_free(non_group_vars);
5699 33561 : list_free(non_group_cols);
5700 :
5701 : /* XXX this causes some redundant cost calculation ... */
5702 33561 : return set_pathtarget_cost_width(root, input_target);
5703 : }
5704 :
5705 : /*
5706 : * make_partial_grouping_target
5707 : * Generate appropriate PathTarget for output of partial aggregate
5708 : * (or partial grouping, if there are no aggregates) nodes.
5709 : *
5710 : * A partial aggregation node needs to emit all the same aggregates that
5711 : * a regular aggregation node would, plus any aggregates used in HAVING;
5712 : * except that the Aggref nodes should be marked as partial aggregates.
5713 : *
5714 : * In addition, we'd better emit any Vars and PlaceHolderVars that are
5715 : * used outside of Aggrefs in the aggregation tlist and HAVING. (Presumably,
5716 : * these would be Vars that are grouped by or used in grouping expressions.)
5717 : *
5718 : * grouping_target is the tlist to be emitted by the topmost aggregation step.
5719 : * havingQual represents the HAVING clause.
5720 : */
5721 : static PathTarget *
5722 3224 : make_partial_grouping_target(PlannerInfo *root,
5723 : PathTarget *grouping_target,
5724 : Node *havingQual)
5725 : {
5726 : PathTarget *partial_target;
5727 : List *non_group_cols;
5728 : List *non_group_exprs;
5729 : int i;
5730 : ListCell *lc;
5731 :
5732 3224 : partial_target = create_empty_pathtarget();
5733 3224 : non_group_cols = NIL;
5734 :
5735 3224 : i = 0;
5736 10639 : foreach(lc, grouping_target->exprs)
5737 : {
5738 7415 : Expr *expr = (Expr *) lfirst(lc);
5739 7415 : Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
5740 :
5741 11387 : if (sgref && root->processed_groupClause &&
5742 3972 : get_sortgroupref_clause_noerr(sgref,
5743 : root->processed_groupClause) != NULL)
5744 : {
5745 : /*
5746 : * It's a grouping column, so add it to the partial_target as-is.
5747 : * (This allows the upper agg step to repeat the grouping calcs.)
5748 : */
5749 2350 : add_column_to_pathtarget(partial_target, expr, sgref);
5750 : }
5751 : else
5752 : {
5753 : /*
5754 : * Non-grouping column, so just remember the expression for later
5755 : * call to pull_var_clause.
5756 : */
5757 5065 : non_group_cols = lappend(non_group_cols, expr);
5758 : }
5759 :
5760 7415 : i++;
5761 : }
5762 :
5763 : /*
5764 : * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
5765 : */
5766 3224 : if (havingQual)
5767 729 : non_group_cols = lappend(non_group_cols, havingQual);
5768 :
5769 : /*
5770 : * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
5771 : * non-group cols (plus HAVING), and add them to the partial_target if not
5772 : * already present. (An expression used directly as a GROUP BY item will
5773 : * be present already.) Note this includes Vars used in resjunk items, so
5774 : * we are covering the needs of ORDER BY and window specifications.
5775 : */
5776 3224 : non_group_exprs = pull_var_clause((Node *) non_group_cols,
5777 : PVC_INCLUDE_AGGREGATES |
5778 : PVC_RECURSE_WINDOWFUNCS |
5779 : PVC_INCLUDE_PLACEHOLDERS);
5780 :
5781 3224 : add_new_columns_to_pathtarget(partial_target, non_group_exprs);
5782 :
5783 : /*
5784 : * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5785 : * are at the top level of the target list, so we can just scan the list
5786 : * rather than recursing through the expression trees.
5787 : */
5788 11133 : foreach(lc, partial_target->exprs)
5789 : {
5790 7909 : Aggref *aggref = (Aggref *) lfirst(lc);
5791 :
5792 7909 : if (IsA(aggref, Aggref))
5793 : {
5794 : Aggref *newaggref;
5795 :
5796 : /*
5797 : * We shouldn't need to copy the substructure of the Aggref node,
5798 : * but flat-copy the node itself to avoid damaging other trees.
5799 : */
5800 5534 : newaggref = makeNode(Aggref);
5801 5534 : memcpy(newaggref, aggref, sizeof(Aggref));
5802 :
5803 : /* For now, assume serialization is required */
5804 5534 : mark_partial_aggref(newaggref, AGGSPLIT_INITIAL_SERIAL);
5805 :
5806 5534 : lfirst(lc) = newaggref;
5807 : }
5808 : }
5809 :
5810 : /* clean up cruft */
5811 3224 : list_free(non_group_exprs);
5812 3224 : list_free(non_group_cols);
5813 :
5814 : /* XXX this causes some redundant cost calculation ... */
5815 3224 : return set_pathtarget_cost_width(root, partial_target);
5816 : }
5817 :
5818 : /*
5819 : * mark_partial_aggref
5820 : * Adjust an Aggref to make it represent a partial-aggregation step.
5821 : *
5822 : * The Aggref node is modified in-place; caller must do any copying required.
5823 : */
5824 : void
5825 15474 : mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
5826 : {
5827 : /* aggtranstype should be computed by this point */
5828 : Assert(OidIsValid(agg->aggtranstype));
5829 : /* ... but aggsplit should still be as the parser left it */
5830 : Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5831 :
5832 : /* Mark the Aggref with the intended partial-aggregation mode */
5833 15474 : agg->aggsplit = aggsplit;
5834 :
5835 : /*
5836 : * Adjust result type if needed. Normally, a partial aggregate returns
5837 : * the aggregate's transition type; but if that's INTERNAL and we're
5838 : * serializing, it returns BYTEA instead.
5839 : */
5840 15474 : if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5841 : {
5842 13551 : if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5843 261 : agg->aggtype = BYTEAOID;
5844 : else
5845 13290 : agg->aggtype = agg->aggtranstype;
5846 : }
5847 15474 : }
5848 :
5849 : /*
5850 : * postprocess_setop_tlist
5851 : * Fix up targetlist returned by plan_set_operations().
5852 : *
5853 : * We need to transpose sort key info from the orig_tlist into new_tlist.
5854 : * NOTE: this would not be good enough if we supported resjunk sort keys
5855 : * for results of set operations --- then, we'd need to project a whole
5856 : * new tlist to evaluate the resjunk columns. For now, just ereport if we
5857 : * find any resjunk columns in orig_tlist.
5858 : */
5859 : static List *
5860 4910 : postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
5861 : {
5862 : ListCell *l;
5863 4910 : ListCell *orig_tlist_item = list_head(orig_tlist);
5864 :
5865 19099 : foreach(l, new_tlist)
5866 : {
5867 14189 : TargetEntry *new_tle = lfirst_node(TargetEntry, l);
5868 : TargetEntry *orig_tle;
5869 :
5870 : /* ignore resjunk columns in setop result */
5871 14189 : if (new_tle->resjunk)
5872 0 : continue;
5873 :
5874 : Assert(orig_tlist_item != NULL);
5875 14189 : orig_tle = lfirst_node(TargetEntry, orig_tlist_item);
5876 14189 : orig_tlist_item = lnext(orig_tlist, orig_tlist_item);
5877 14189 : if (orig_tle->resjunk) /* should not happen */
5878 0 : elog(ERROR, "resjunk output columns are not implemented");
5879 : Assert(new_tle->resno == orig_tle->resno);
5880 14189 : new_tle->ressortgroupref = orig_tle->ressortgroupref;
5881 : }
5882 4910 : if (orig_tlist_item != NULL)
5883 0 : elog(ERROR, "resjunk output columns are not implemented");
5884 4910 : return new_tlist;
5885 : }
5886 :
5887 : /*
5888 : * optimize_window_clauses
5889 : * Call each WindowFunc's prosupport function to see if we're able to
5890 : * make any adjustments to any of the WindowClause's so that the executor
5891 : * can execute the window functions in a more optimal way.
5892 : *
5893 : * Currently we only allow adjustments to the WindowClause's frameOptions. We
5894 : * may allow more things to be done here in the future.
5895 : */
5896 : static void
5897 2192 : optimize_window_clauses(PlannerInfo *root, WindowFuncLists *wflists)
5898 : {
5899 2192 : List *windowClause = root->parse->windowClause;
5900 : ListCell *lc;
5901 :
5902 4589 : foreach(lc, windowClause)
5903 : {
5904 2397 : WindowClause *wc = lfirst_node(WindowClause, lc);
5905 : ListCell *lc2;
5906 2397 : int optimizedFrameOptions = 0;
5907 :
5908 : Assert(wc->winref <= wflists->maxWinRef);
5909 :
5910 : /* skip any WindowClauses that have no WindowFuncs */
5911 2397 : if (wflists->windowFuncs[wc->winref] == NIL)
5912 20 : continue;
5913 :
5914 2920 : foreach(lc2, wflists->windowFuncs[wc->winref])
5915 : {
5916 : SupportRequestOptimizeWindowClause req;
5917 : SupportRequestOptimizeWindowClause *res;
5918 2412 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
5919 : Oid prosupport;
5920 :
5921 2412 : prosupport = get_func_support(wfunc->winfnoid);
5922 :
5923 : /* Check if there's a support function for 'wfunc' */
5924 2412 : if (!OidIsValid(prosupport))
5925 1869 : break; /* can't optimize this WindowClause */
5926 :
5927 730 : req.type = T_SupportRequestOptimizeWindowClause;
5928 730 : req.window_clause = wc;
5929 730 : req.window_func = wfunc;
5930 730 : req.frameOptions = wc->frameOptions;
5931 :
5932 : /* call the support function */
5933 : res = (SupportRequestOptimizeWindowClause *)
5934 730 : DatumGetPointer(OidFunctionCall1(prosupport,
5935 : PointerGetDatum(&req)));
5936 :
5937 : /*
5938 : * Skip to next WindowClause if the support function does not
5939 : * support this request type.
5940 : */
5941 730 : if (res == NULL)
5942 187 : break;
5943 :
5944 : /*
5945 : * Save these frameOptions for the first WindowFunc for this
5946 : * WindowClause.
5947 : */
5948 543 : if (foreach_current_index(lc2) == 0)
5949 523 : optimizedFrameOptions = res->frameOptions;
5950 :
5951 : /*
5952 : * On subsequent WindowFuncs, if the frameOptions are not the same
5953 : * then we're unable to optimize the frameOptions for this
5954 : * WindowClause.
5955 : */
5956 20 : else if (optimizedFrameOptions != res->frameOptions)
5957 0 : break; /* skip to the next WindowClause, if any */
5958 : }
5959 :
5960 : /* adjust the frameOptions if all WindowFunc's agree that it's ok */
5961 2377 : if (lc2 == NULL && wc->frameOptions != optimizedFrameOptions)
5962 : {
5963 : ListCell *lc3;
5964 :
5965 : /* apply the new frame options */
5966 508 : wc->frameOptions = optimizedFrameOptions;
5967 :
5968 : /*
5969 : * We now check to see if changing the frameOptions has caused
5970 : * this WindowClause to be a duplicate of some other WindowClause.
5971 : * This can only happen if we have multiple WindowClauses, so
5972 : * don't bother if there's only 1.
5973 : */
5974 508 : if (list_length(windowClause) == 1)
5975 433 : continue;
5976 :
5977 : /*
5978 : * Do the duplicate check and reuse the existing WindowClause if
5979 : * we find a duplicate.
5980 : */
5981 190 : foreach(lc3, windowClause)
5982 : {
5983 145 : WindowClause *existing_wc = lfirst_node(WindowClause, lc3);
5984 :
5985 : /* skip over the WindowClause we're currently editing */
5986 145 : if (existing_wc == wc)
5987 45 : continue;
5988 :
5989 : /*
5990 : * Perform the same duplicate check that is done in
5991 : * transformWindowFuncCall.
5992 : */
5993 200 : if (equal(wc->partitionClause, existing_wc->partitionClause) &&
5994 100 : equal(wc->orderClause, existing_wc->orderClause) &&
5995 100 : wc->frameOptions == existing_wc->frameOptions &&
5996 60 : equal(wc->startOffset, existing_wc->startOffset) &&
5997 30 : equal(wc->endOffset, existing_wc->endOffset))
5998 : {
5999 : ListCell *lc4;
6000 :
6001 : /*
6002 : * Now move each WindowFunc in 'wc' into 'existing_wc'.
6003 : * This required adjusting each WindowFunc's winref and
6004 : * moving the WindowFuncs in 'wc' to the list of
6005 : * WindowFuncs in 'existing_wc'.
6006 : */
6007 65 : foreach(lc4, wflists->windowFuncs[wc->winref])
6008 : {
6009 35 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc4);
6010 :
6011 35 : wfunc->winref = existing_wc->winref;
6012 : }
6013 :
6014 : /* move list items */
6015 60 : wflists->windowFuncs[existing_wc->winref] = list_concat(wflists->windowFuncs[existing_wc->winref],
6016 30 : wflists->windowFuncs[wc->winref]);
6017 30 : wflists->windowFuncs[wc->winref] = NIL;
6018 :
6019 : /*
6020 : * transformWindowFuncCall() should have made sure there
6021 : * are no other duplicates, so we needn't bother looking
6022 : * any further.
6023 : */
6024 30 : break;
6025 : }
6026 : }
6027 : }
6028 : }
6029 2192 : }
6030 :
6031 : /*
6032 : * select_active_windows
6033 : * Create a list of the "active" window clauses (ie, those referenced
6034 : * by non-deleted WindowFuncs) in the order they are to be executed.
6035 : */
6036 : static List *
6037 2192 : select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
6038 : {
6039 2192 : List *windowClause = root->parse->windowClause;
6040 2192 : List *result = NIL;
6041 : ListCell *lc;
6042 2192 : int nActive = 0;
6043 2192 : WindowClauseSortData *actives = palloc_array(WindowClauseSortData,
6044 : list_length(windowClause));
6045 :
6046 : /* First, construct an array of the active windows */
6047 4589 : foreach(lc, windowClause)
6048 : {
6049 2397 : WindowClause *wc = lfirst_node(WindowClause, lc);
6050 :
6051 : /* It's only active if wflists shows some related WindowFuncs */
6052 : Assert(wc->winref <= wflists->maxWinRef);
6053 2397 : if (wflists->windowFuncs[wc->winref] == NIL)
6054 50 : continue;
6055 :
6056 2347 : actives[nActive].wc = wc; /* original clause */
6057 :
6058 : /*
6059 : * For sorting, we want the list of partition keys followed by the
6060 : * list of sort keys. But pathkeys construction will remove duplicates
6061 : * between the two, so we can as well (even though we can't detect all
6062 : * of the duplicates, since some may come from ECs - that might mean
6063 : * we miss optimization chances here). We must, however, ensure that
6064 : * the order of entries is preserved with respect to the ones we do
6065 : * keep.
6066 : *
6067 : * partitionClause and orderClause had their own duplicates removed in
6068 : * parse analysis, so we're only concerned here with removing
6069 : * orderClause entries that also appear in partitionClause.
6070 : */
6071 4694 : actives[nActive].uniqueOrder =
6072 2347 : list_concat_unique(list_copy(wc->partitionClause),
6073 2347 : wc->orderClause);
6074 2347 : nActive++;
6075 : }
6076 :
6077 : /*
6078 : * Sort active windows by their partitioning/ordering clauses, ignoring
6079 : * any framing clauses, so that the windows that need the same sorting are
6080 : * adjacent in the list. When we come to generate paths, this will avoid
6081 : * inserting additional Sort nodes.
6082 : *
6083 : * This is how we implement a specific requirement from the SQL standard,
6084 : * which says that when two or more windows are order-equivalent (i.e.
6085 : * have matching partition and order clauses, even if their names or
6086 : * framing clauses differ), then all peer rows must be presented in the
6087 : * same order in all of them. If we allowed multiple sort nodes for such
6088 : * cases, we'd risk having the peer rows end up in different orders in
6089 : * equivalent windows due to sort instability. (See General Rule 4 of
6090 : * <window clause> in SQL2008 - SQL2016.)
6091 : *
6092 : * Additionally, if the entire list of clauses of one window is a prefix
6093 : * of another, put first the window with stronger sorting requirements.
6094 : * This way we will first sort for stronger window, and won't have to sort
6095 : * again for the weaker one.
6096 : */
6097 2192 : qsort(actives, nActive, sizeof(WindowClauseSortData), common_prefix_cmp);
6098 :
6099 : /* build ordered list of the original WindowClause nodes */
6100 4539 : for (int i = 0; i < nActive; i++)
6101 2347 : result = lappend(result, actives[i].wc);
6102 :
6103 2192 : pfree(actives);
6104 :
6105 2192 : return result;
6106 : }
6107 :
6108 : /*
6109 : * name_active_windows
6110 : * Ensure all active windows have unique names.
6111 : *
6112 : * The parser will have checked that user-assigned window names are unique
6113 : * within the Query. Here we assign made-up names to any unnamed
6114 : * WindowClauses for the benefit of EXPLAIN. (We don't want to do this
6115 : * at parse time, because it'd mess up decompilation of views.)
6116 : *
6117 : * activeWindows: result of select_active_windows
6118 : */
6119 : static void
6120 2192 : name_active_windows(List *activeWindows)
6121 : {
6122 2192 : int next_n = 1;
6123 : char newname[16];
6124 : ListCell *lc;
6125 :
6126 4539 : foreach(lc, activeWindows)
6127 : {
6128 2347 : WindowClause *wc = lfirst_node(WindowClause, lc);
6129 :
6130 : /* Nothing to do if it has a name already. */
6131 2347 : if (wc->name)
6132 480 : continue;
6133 :
6134 : /* Select a name not currently present in the list. */
6135 : for (;;)
6136 5 : {
6137 : ListCell *lc2;
6138 :
6139 1872 : snprintf(newname, sizeof(newname), "w%d", next_n++);
6140 4034 : foreach(lc2, activeWindows)
6141 : {
6142 2167 : WindowClause *wc2 = lfirst_node(WindowClause, lc2);
6143 :
6144 2167 : if (wc2->name && strcmp(wc2->name, newname) == 0)
6145 5 : break; /* matched */
6146 : }
6147 1872 : if (lc2 == NULL)
6148 1867 : break; /* reached the end with no match */
6149 : }
6150 1867 : wc->name = pstrdup(newname);
6151 : }
6152 2192 : }
6153 :
6154 : /*
6155 : * common_prefix_cmp
6156 : * QSort comparison function for WindowClauseSortData
6157 : *
6158 : * Sort the windows by the required sorting clauses. First, compare the sort
6159 : * clauses themselves. Second, if one window's clauses are a prefix of another
6160 : * one's clauses, put the window with more sort clauses first.
6161 : *
6162 : * We purposefully sort by the highest tleSortGroupRef first. Since
6163 : * tleSortGroupRefs are assigned for the query's DISTINCT and ORDER BY first
6164 : * and because here we sort the lowest tleSortGroupRefs last, if a
6165 : * WindowClause is sharing a tleSortGroupRef with the query's DISTINCT or
6166 : * ORDER BY clause, this makes it more likely that the final WindowAgg will
6167 : * provide presorted input for the query's DISTINCT or ORDER BY clause, thus
6168 : * reducing the total number of sorts required for the query.
6169 : */
6170 : static int
6171 170 : common_prefix_cmp(const void *a, const void *b)
6172 : {
6173 170 : const WindowClauseSortData *wcsa = a;
6174 170 : const WindowClauseSortData *wcsb = b;
6175 : ListCell *item_a;
6176 : ListCell *item_b;
6177 :
6178 305 : forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
6179 : {
6180 220 : SortGroupClause *sca = lfirst_node(SortGroupClause, item_a);
6181 220 : SortGroupClause *scb = lfirst_node(SortGroupClause, item_b);
6182 :
6183 220 : if (sca->tleSortGroupRef > scb->tleSortGroupRef)
6184 85 : return -1;
6185 210 : else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
6186 55 : return 1;
6187 155 : else if (sca->sortop > scb->sortop)
6188 0 : return -1;
6189 155 : else if (sca->sortop < scb->sortop)
6190 20 : return 1;
6191 135 : else if (sca->nulls_first && !scb->nulls_first)
6192 0 : return -1;
6193 135 : else if (!sca->nulls_first && scb->nulls_first)
6194 0 : return 1;
6195 : /* no need to compare eqop, since it is fully determined by sortop */
6196 : }
6197 :
6198 85 : if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
6199 5 : return -1;
6200 80 : else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
6201 25 : return 1;
6202 :
6203 55 : return 0;
6204 : }
6205 :
6206 : /*
6207 : * make_window_input_target
6208 : * Generate appropriate PathTarget for initial input to WindowAgg nodes.
6209 : *
6210 : * When the query has window functions, this function computes the desired
6211 : * target to be computed by the node just below the first WindowAgg.
6212 : * This tlist must contain all values needed to evaluate the window functions,
6213 : * compute the final target list, and perform any required final sort step.
6214 : * If multiple WindowAggs are needed, each intermediate one adds its window
6215 : * function results onto this base tlist; only the topmost WindowAgg computes
6216 : * the actual desired target list.
6217 : *
6218 : * This function is much like make_group_input_target, though not quite enough
6219 : * like it to share code. As in that function, we flatten most expressions
6220 : * into their component variables. But we do not want to flatten window
6221 : * PARTITION BY/ORDER BY clauses, since that might result in multiple
6222 : * evaluations of them, which would be bad (possibly even resulting in
6223 : * inconsistent answers, if they contain volatile functions).
6224 : * Also, we must not flatten GROUP BY clauses that were left unflattened by
6225 : * make_group_input_target, because we may no longer have access to the
6226 : * individual Vars in them.
6227 : *
6228 : * Another key difference from make_group_input_target is that we don't
6229 : * flatten Aggref expressions, since those are to be computed below the
6230 : * window functions and just referenced like Vars above that.
6231 : *
6232 : * 'final_target' is the query's final target list (in PathTarget form)
6233 : * 'activeWindows' is the list of active windows previously identified by
6234 : * select_active_windows.
6235 : *
6236 : * The result is the PathTarget to be computed by the plan node immediately
6237 : * below the first WindowAgg node.
6238 : */
6239 : static PathTarget *
6240 2192 : make_window_input_target(PlannerInfo *root,
6241 : PathTarget *final_target,
6242 : List *activeWindows)
6243 : {
6244 : PathTarget *input_target;
6245 : Bitmapset *sgrefs;
6246 : List *flattenable_cols;
6247 : List *flattenable_vars;
6248 : int i;
6249 : ListCell *lc;
6250 :
6251 : Assert(root->parse->hasWindowFuncs);
6252 :
6253 : /*
6254 : * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
6255 : * into a bitmapset for convenient reference below.
6256 : */
6257 2192 : sgrefs = NULL;
6258 4539 : foreach(lc, activeWindows)
6259 : {
6260 2347 : WindowClause *wc = lfirst_node(WindowClause, lc);
6261 : ListCell *lc2;
6262 :
6263 2969 : foreach(lc2, wc->partitionClause)
6264 : {
6265 622 : SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc2);
6266 :
6267 622 : sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
6268 : }
6269 4237 : foreach(lc2, wc->orderClause)
6270 : {
6271 1890 : SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc2);
6272 :
6273 1890 : sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
6274 : }
6275 : }
6276 :
6277 : /* Add in sortgroupref numbers of GROUP BY clauses, too */
6278 2348 : foreach(lc, root->processed_groupClause)
6279 : {
6280 156 : SortGroupClause *grpcl = lfirst_node(SortGroupClause, lc);
6281 :
6282 156 : sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
6283 : }
6284 :
6285 : /*
6286 : * Construct a target containing all the non-flattenable targetlist items,
6287 : * and save aside the others for a moment.
6288 : */
6289 2192 : input_target = create_empty_pathtarget();
6290 2192 : flattenable_cols = NIL;
6291 :
6292 2192 : i = 0;
6293 9224 : foreach(lc, final_target->exprs)
6294 : {
6295 7032 : Expr *expr = (Expr *) lfirst(lc);
6296 7032 : Index sgref = get_pathtarget_sortgroupref(final_target, i);
6297 :
6298 : /*
6299 : * Don't want to deconstruct window clauses or GROUP BY items. (Note
6300 : * that such items can't contain window functions, so it's okay to
6301 : * compute them below the WindowAgg nodes.)
6302 : */
6303 7032 : if (sgref != 0 && bms_is_member(sgref, sgrefs))
6304 : {
6305 : /*
6306 : * Don't want to deconstruct this value, so add it to the input
6307 : * target as-is.
6308 : */
6309 2374 : add_column_to_pathtarget(input_target, expr, sgref);
6310 : }
6311 : else
6312 : {
6313 : /*
6314 : * Column is to be flattened, so just remember the expression for
6315 : * later call to pull_var_clause.
6316 : */
6317 4658 : flattenable_cols = lappend(flattenable_cols, expr);
6318 : }
6319 :
6320 7032 : i++;
6321 : }
6322 :
6323 : /*
6324 : * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
6325 : * add them to the input target if not already present. (Some might be
6326 : * there already because they're used directly as window/group clauses.)
6327 : *
6328 : * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
6329 : * Aggrefs are placed in the Agg node's tlist and not left to be computed
6330 : * at higher levels. On the other hand, we should recurse into
6331 : * WindowFuncs to make sure their input expressions are available.
6332 : */
6333 2192 : flattenable_vars = pull_var_clause((Node *) flattenable_cols,
6334 : PVC_INCLUDE_AGGREGATES |
6335 : PVC_RECURSE_WINDOWFUNCS |
6336 : PVC_INCLUDE_PLACEHOLDERS);
6337 2192 : add_new_columns_to_pathtarget(input_target, flattenable_vars);
6338 :
6339 : /* clean up cruft */
6340 2192 : list_free(flattenable_vars);
6341 2192 : list_free(flattenable_cols);
6342 :
6343 : /* XXX this causes some redundant cost calculation ... */
6344 2192 : return set_pathtarget_cost_width(root, input_target);
6345 : }
6346 :
6347 : /*
6348 : * make_pathkeys_for_window
6349 : * Create a pathkeys list describing the required input ordering
6350 : * for the given WindowClause.
6351 : *
6352 : * Modifies wc's partitionClause to remove any clauses which are deemed
6353 : * redundant by the pathkey logic.
6354 : *
6355 : * The required ordering is first the PARTITION keys, then the ORDER keys.
6356 : * In the future we might try to implement windowing using hashing, in which
6357 : * case the ordering could be relaxed, but for now we always sort.
6358 : */
6359 : static List *
6360 4706 : make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
6361 : List *tlist)
6362 : {
6363 4706 : List *window_pathkeys = NIL;
6364 :
6365 : /* Throw error if can't sort */
6366 4706 : if (!grouping_is_sortable(wc->partitionClause))
6367 0 : ereport(ERROR,
6368 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6369 : errmsg("could not implement window PARTITION BY"),
6370 : errdetail("Window partitioning columns must be of sortable datatypes.")));
6371 4706 : if (!grouping_is_sortable(wc->orderClause))
6372 0 : ereport(ERROR,
6373 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6374 : errmsg("could not implement window ORDER BY"),
6375 : errdetail("Window ordering columns must be of sortable datatypes.")));
6376 :
6377 : /*
6378 : * First fetch the pathkeys for the PARTITION BY clause. We can safely
6379 : * remove any clauses from the wc->partitionClause for redundant pathkeys.
6380 : */
6381 4706 : if (wc->partitionClause != NIL)
6382 : {
6383 : bool sortable;
6384 :
6385 1088 : window_pathkeys = make_pathkeys_for_sortclauses_extended(root,
6386 : &wc->partitionClause,
6387 : tlist,
6388 : true,
6389 : false,
6390 : &sortable,
6391 : false);
6392 :
6393 : Assert(sortable);
6394 : }
6395 :
6396 : /*
6397 : * In principle, we could also consider removing redundant ORDER BY items
6398 : * too as doing so does not alter the result of peer row checks done by
6399 : * the executor. However, we must *not* remove the ordering column for
6400 : * RANGE OFFSET cases, as the executor needs that for in_range tests even
6401 : * if it's known to be equal to some partitioning column.
6402 : */
6403 4706 : if (wc->orderClause != NIL)
6404 : {
6405 : List *orderby_pathkeys;
6406 :
6407 3694 : orderby_pathkeys = make_pathkeys_for_sortclauses(root,
6408 : wc->orderClause,
6409 : tlist);
6410 :
6411 : /* Okay, make the combined pathkeys */
6412 3694 : if (window_pathkeys != NIL)
6413 781 : window_pathkeys = append_pathkeys(window_pathkeys, orderby_pathkeys);
6414 : else
6415 2913 : window_pathkeys = orderby_pathkeys;
6416 : }
6417 :
6418 4706 : return window_pathkeys;
6419 : }
6420 :
6421 : /*
6422 : * make_sort_input_target
6423 : * Generate appropriate PathTarget for initial input to Sort step.
6424 : *
6425 : * If the query has ORDER BY, this function chooses the target to be computed
6426 : * by the node just below the Sort (and DISTINCT, if any, since Unique can't
6427 : * project) steps. This might or might not be identical to the query's final
6428 : * output target.
6429 : *
6430 : * The main argument for keeping the sort-input tlist the same as the final
6431 : * is that we avoid a separate projection node (which will be needed if
6432 : * they're different, because Sort can't project). However, there are also
6433 : * advantages to postponing tlist evaluation till after the Sort: it ensures
6434 : * a consistent order of evaluation for any volatile functions in the tlist,
6435 : * and if there's also a LIMIT, we can stop the query without ever computing
6436 : * tlist functions for later rows, which is beneficial for both volatile and
6437 : * expensive functions.
6438 : *
6439 : * Our current policy is to postpone volatile expressions till after the sort
6440 : * unconditionally (assuming that that's possible, ie they are in plain tlist
6441 : * columns and not ORDER BY/GROUP BY/DISTINCT columns). We also prefer to
6442 : * postpone set-returning expressions, because running them beforehand would
6443 : * bloat the sort dataset, and because it might cause unexpected output order
6444 : * if the sort isn't stable. However there's a constraint on that: all SRFs
6445 : * in the tlist should be evaluated at the same plan step, so that they can
6446 : * run in sync in nodeProjectSet. So if any SRFs are in sort columns, we
6447 : * mustn't postpone any SRFs. (Note that in principle that policy should
6448 : * probably get applied to the group/window input targetlists too, but we
6449 : * have not done that historically.) Lastly, expensive expressions are
6450 : * postponed if there is a LIMIT, or if root->tuple_fraction shows that
6451 : * partial evaluation of the query is possible (if neither is true, we expect
6452 : * to have to evaluate the expressions for every row anyway), or if there are
6453 : * any volatile or set-returning expressions (since once we've put in a
6454 : * projection at all, it won't cost any more to postpone more stuff).
6455 : *
6456 : * Another issue that could potentially be considered here is that
6457 : * evaluating tlist expressions could result in data that's either wider
6458 : * or narrower than the input Vars, thus changing the volume of data that
6459 : * has to go through the Sort. However, we usually have only a very bad
6460 : * idea of the output width of any expression more complex than a Var,
6461 : * so for now it seems too risky to try to optimize on that basis.
6462 : *
6463 : * Note that if we do produce a modified sort-input target, and then the
6464 : * query ends up not using an explicit Sort, no particular harm is done:
6465 : * we'll initially use the modified target for the preceding path nodes,
6466 : * but then change them to the final target with apply_projection_to_path.
6467 : * Moreover, in such a case the guarantees about evaluation order of
6468 : * volatile functions still hold, since the rows are sorted already.
6469 : *
6470 : * This function has some things in common with make_group_input_target and
6471 : * make_window_input_target, though the detailed rules for what to do are
6472 : * different. We never flatten/postpone any grouping or ordering columns;
6473 : * those are needed before the sort. If we do flatten a particular
6474 : * expression, we leave Aggref and WindowFunc nodes alone, since those were
6475 : * computed earlier.
6476 : *
6477 : * 'final_target' is the query's final target list (in PathTarget form)
6478 : * 'have_postponed_srfs' is an output argument, see below
6479 : *
6480 : * The result is the PathTarget to be computed by the plan node immediately
6481 : * below the Sort step (and the Distinct step, if any). This will be
6482 : * exactly final_target if we decide a projection step wouldn't be helpful.
6483 : *
6484 : * In addition, *have_postponed_srfs is set to true if we choose to postpone
6485 : * any set-returning functions to after the Sort.
6486 : */
6487 : static PathTarget *
6488 57781 : make_sort_input_target(PlannerInfo *root,
6489 : PathTarget *final_target,
6490 : bool *have_postponed_srfs)
6491 : {
6492 57781 : Query *parse = root->parse;
6493 : PathTarget *input_target;
6494 : int ncols;
6495 : bool *col_is_srf;
6496 : bool *postpone_col;
6497 : bool have_srf;
6498 : bool have_volatile;
6499 : bool have_expensive;
6500 : bool have_srf_sortcols;
6501 : bool postpone_srfs;
6502 : List *postponable_cols;
6503 : List *postponable_vars;
6504 : int i;
6505 : ListCell *lc;
6506 :
6507 : /* Shouldn't get here unless query has ORDER BY */
6508 : Assert(parse->sortClause);
6509 :
6510 57781 : *have_postponed_srfs = false; /* default result */
6511 :
6512 : /* Inspect tlist and collect per-column information */
6513 57781 : ncols = list_length(final_target->exprs);
6514 57781 : col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
6515 57781 : postpone_col = (bool *) palloc0(ncols * sizeof(bool));
6516 57781 : have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
6517 :
6518 57781 : i = 0;
6519 337829 : foreach(lc, final_target->exprs)
6520 : {
6521 280048 : Expr *expr = (Expr *) lfirst(lc);
6522 :
6523 : /*
6524 : * If the column has a sortgroupref, assume it has to be evaluated
6525 : * before sorting. Generally such columns would be ORDER BY, GROUP
6526 : * BY, etc targets. One exception is columns that were removed from
6527 : * GROUP BY by remove_useless_groupby_columns() ... but those would
6528 : * only be Vars anyway. There don't seem to be any cases where it
6529 : * would be worth the trouble to double-check.
6530 : */
6531 280048 : if (get_pathtarget_sortgroupref(final_target, i) == 0)
6532 : {
6533 : /*
6534 : * Check for SRF or volatile functions. Check the SRF case first
6535 : * because we must know whether we have any postponed SRFs.
6536 : */
6537 198655 : if (parse->hasTargetSRFs &&
6538 180 : expression_returns_set((Node *) expr))
6539 : {
6540 : /* We'll decide below whether these are postponable */
6541 80 : col_is_srf[i] = true;
6542 80 : have_srf = true;
6543 : }
6544 198395 : else if (contain_volatile_functions((Node *) expr))
6545 : {
6546 : /* Unconditionally postpone */
6547 175 : postpone_col[i] = true;
6548 175 : have_volatile = true;
6549 : }
6550 : else
6551 : {
6552 : /*
6553 : * Else check the cost. XXX it's annoying to have to do this
6554 : * when set_pathtarget_cost_width() just did it. Refactor to
6555 : * allow sharing the work?
6556 : */
6557 : QualCost cost;
6558 :
6559 198220 : cost_qual_eval_node(&cost, (Node *) expr, root);
6560 :
6561 : /*
6562 : * We arbitrarily define "expensive" as "more than 10X
6563 : * cpu_operator_cost". Note this will take in any PL function
6564 : * with default cost.
6565 : */
6566 198220 : if (cost.per_tuple > 10 * cpu_operator_cost)
6567 : {
6568 14259 : postpone_col[i] = true;
6569 14259 : have_expensive = true;
6570 : }
6571 : }
6572 : }
6573 : else
6574 : {
6575 : /* For sortgroupref cols, just check if any contain SRFs */
6576 81573 : if (!have_srf_sortcols &&
6577 81830 : parse->hasTargetSRFs &&
6578 277 : expression_returns_set((Node *) expr))
6579 122 : have_srf_sortcols = true;
6580 : }
6581 :
6582 280048 : i++;
6583 : }
6584 :
6585 : /*
6586 : * We can postpone SRFs if we have some but none are in sortgroupref cols.
6587 : */
6588 57781 : postpone_srfs = (have_srf && !have_srf_sortcols);
6589 :
6590 : /*
6591 : * If we don't need a post-sort projection, just return final_target.
6592 : */
6593 57781 : if (!(postpone_srfs || have_volatile ||
6594 57558 : (have_expensive &&
6595 8521 : (parse->limitCount || root->tuple_fraction > 0))))
6596 57528 : return final_target;
6597 :
6598 : /*
6599 : * Report whether the post-sort projection will contain set-returning
6600 : * functions. This is important because it affects whether the Sort can
6601 : * rely on the query's LIMIT (if any) to bound the number of rows it needs
6602 : * to return.
6603 : */
6604 253 : *have_postponed_srfs = postpone_srfs;
6605 :
6606 : /*
6607 : * Construct the sort-input target, taking all non-postponable columns and
6608 : * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
6609 : * the postponable ones.
6610 : */
6611 253 : input_target = create_empty_pathtarget();
6612 253 : postponable_cols = NIL;
6613 :
6614 253 : i = 0;
6615 1825 : foreach(lc, final_target->exprs)
6616 : {
6617 1572 : Expr *expr = (Expr *) lfirst(lc);
6618 :
6619 1572 : if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
6620 305 : postponable_cols = lappend(postponable_cols, expr);
6621 : else
6622 1267 : add_column_to_pathtarget(input_target, expr,
6623 1267 : get_pathtarget_sortgroupref(final_target, i));
6624 :
6625 1572 : i++;
6626 : }
6627 :
6628 : /*
6629 : * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
6630 : * postponable columns, and add them to the sort-input target if not
6631 : * already present. (Some might be there already.) We mustn't
6632 : * deconstruct Aggrefs or WindowFuncs here, since the projection node
6633 : * would be unable to recompute them.
6634 : */
6635 253 : postponable_vars = pull_var_clause((Node *) postponable_cols,
6636 : PVC_INCLUDE_AGGREGATES |
6637 : PVC_INCLUDE_WINDOWFUNCS |
6638 : PVC_INCLUDE_PLACEHOLDERS);
6639 253 : add_new_columns_to_pathtarget(input_target, postponable_vars);
6640 :
6641 : /* clean up cruft */
6642 253 : list_free(postponable_vars);
6643 253 : list_free(postponable_cols);
6644 :
6645 : /* XXX this represents even more redundant cost calculation ... */
6646 253 : return set_pathtarget_cost_width(root, input_target);
6647 : }
6648 :
6649 : /*
6650 : * get_cheapest_fractional_path
6651 : * Find the cheapest path for retrieving a specified fraction of all
6652 : * the tuples expected to be returned by the given relation.
6653 : *
6654 : * Do not consider parameterized paths. If the caller needs a path for upper
6655 : * rel, it can't have parameterized paths. If the caller needs an append
6656 : * subpath, it could become limited by the treatment of similar
6657 : * parameterization of all the subpaths.
6658 : *
6659 : * We interpret tuple_fraction the same way as grouping_planner.
6660 : *
6661 : * We assume set_cheapest() has been run on the given rel.
6662 : */
6663 : Path *
6664 360742 : get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
6665 : {
6666 360742 : Path *best_path = rel->cheapest_total_path;
6667 : ListCell *l;
6668 :
6669 : /* If all tuples will be retrieved, just return the cheapest-total path */
6670 360742 : if (tuple_fraction <= 0.0)
6671 353726 : return best_path;
6672 :
6673 : /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
6674 7016 : if (tuple_fraction >= 1.0 && best_path->rows > 0)
6675 3065 : tuple_fraction /= best_path->rows;
6676 :
6677 17848 : foreach(l, rel->pathlist)
6678 : {
6679 10832 : Path *path = (Path *) lfirst(l);
6680 :
6681 10832 : if (path->param_info)
6682 166 : continue;
6683 :
6684 14316 : if (path == rel->cheapest_total_path ||
6685 3650 : compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
6686 10344 : continue;
6687 :
6688 322 : best_path = path;
6689 : }
6690 :
6691 7016 : return best_path;
6692 : }
6693 :
6694 : /*
6695 : * adjust_paths_for_srfs
6696 : * Fix up the Paths of the given upperrel to handle tSRFs properly.
6697 : *
6698 : * The executor can only handle set-returning functions that appear at the
6699 : * top level of the targetlist of a ProjectSet plan node. If we have any SRFs
6700 : * that are not at top level, we need to split up the evaluation into multiple
6701 : * plan levels in which each level satisfies this constraint. This function
6702 : * modifies each Path of an upperrel that (might) compute any SRFs in its
6703 : * output tlist to insert appropriate projection steps.
6704 : *
6705 : * The given targets and targets_contain_srfs lists are from
6706 : * split_pathtarget_at_srfs(). We assume the existing Paths emit the first
6707 : * target in targets.
6708 : */
6709 : static void
6710 10395 : adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
6711 : List *targets, List *targets_contain_srfs)
6712 : {
6713 : ListCell *lc;
6714 :
6715 : Assert(list_length(targets) == list_length(targets_contain_srfs));
6716 : Assert(!linitial_int(targets_contain_srfs));
6717 :
6718 : /* If no SRFs appear at this plan level, nothing to do */
6719 10395 : if (list_length(targets) == 1)
6720 490 : return;
6721 :
6722 : /*
6723 : * Stack SRF-evaluation nodes atop each path for the rel.
6724 : *
6725 : * In principle we should re-run set_cheapest() here to identify the
6726 : * cheapest path, but it seems unlikely that adding the same tlist eval
6727 : * costs to all the paths would change that, so we don't bother. Instead,
6728 : * just assume that the cheapest-startup and cheapest-total paths remain
6729 : * so. (There should be no parameterized paths anymore, so we needn't
6730 : * worry about updating cheapest_parameterized_paths.)
6731 : */
6732 19841 : foreach(lc, rel->pathlist)
6733 : {
6734 9936 : Path *subpath = (Path *) lfirst(lc);
6735 9936 : Path *newpath = subpath;
6736 : ListCell *lc1,
6737 : *lc2;
6738 :
6739 : Assert(subpath->param_info == NULL);
6740 30593 : forboth(lc1, targets, lc2, targets_contain_srfs)
6741 : {
6742 20657 : PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6743 20657 : bool contains_srfs = (bool) lfirst_int(lc2);
6744 :
6745 : /* If this level doesn't contain SRFs, do regular projection */
6746 20657 : if (contains_srfs)
6747 9986 : newpath = (Path *) create_set_projection_path(root,
6748 : rel,
6749 : newpath,
6750 : thistarget);
6751 : else
6752 10671 : newpath = (Path *) apply_projection_to_path(root,
6753 : rel,
6754 : newpath,
6755 : thistarget);
6756 : }
6757 9936 : lfirst(lc) = newpath;
6758 9936 : if (subpath == rel->cheapest_startup_path)
6759 238 : rel->cheapest_startup_path = newpath;
6760 9936 : if (subpath == rel->cheapest_total_path)
6761 238 : rel->cheapest_total_path = newpath;
6762 : }
6763 :
6764 : /* Likewise for partial paths, if any */
6765 9920 : foreach(lc, rel->partial_pathlist)
6766 : {
6767 15 : Path *subpath = (Path *) lfirst(lc);
6768 15 : Path *newpath = subpath;
6769 : ListCell *lc1,
6770 : *lc2;
6771 :
6772 : Assert(subpath->param_info == NULL);
6773 60 : forboth(lc1, targets, lc2, targets_contain_srfs)
6774 : {
6775 45 : PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6776 45 : bool contains_srfs = (bool) lfirst_int(lc2);
6777 :
6778 : /* If this level doesn't contain SRFs, do regular projection */
6779 45 : if (contains_srfs)
6780 15 : newpath = (Path *) create_set_projection_path(root,
6781 : rel,
6782 : newpath,
6783 : thistarget);
6784 : else
6785 : {
6786 : /* avoid apply_projection_to_path, in case of multiple refs */
6787 30 : newpath = (Path *) create_projection_path(root,
6788 : rel,
6789 : newpath,
6790 : thistarget);
6791 : }
6792 : }
6793 15 : lfirst(lc) = newpath;
6794 : }
6795 : }
6796 :
6797 : /*
6798 : * expression_planner
6799 : * Perform planner's transformations on a standalone expression.
6800 : *
6801 : * Various utility commands need to evaluate expressions that are not part
6802 : * of a plannable query. They can do so using the executor's regular
6803 : * expression-execution machinery, but first the expression has to be fed
6804 : * through here to transform it from parser output to something executable.
6805 : *
6806 : * Currently, we disallow sublinks in standalone expressions, so there's no
6807 : * real "planning" involved here. (That might not always be true though.)
6808 : * What we must do is run eval_const_expressions to ensure that any function
6809 : * calls are converted to positional notation and function default arguments
6810 : * get inserted. The fact that constant subexpressions get simplified is a
6811 : * side-effect that is useful when the expression will get evaluated more than
6812 : * once. Also, we must fix operator function IDs.
6813 : *
6814 : * This does not return any information about dependencies of the expression.
6815 : * Hence callers should use the results only for the duration of the current
6816 : * query. Callers that would like to cache the results for longer should use
6817 : * expression_planner_with_deps, probably via the plancache.
6818 : *
6819 : * Note: this must not make any damaging changes to the passed-in expression
6820 : * tree. (It would actually be okay to apply fix_opfuncids to it, but since
6821 : * we first do an expression_tree_mutator-based walk, what is returned will
6822 : * be a new node tree.) The result is constructed in the current memory
6823 : * context; beware that this can leak a lot of additional stuff there, too.
6824 : */
6825 : Expr *
6826 134334 : expression_planner(Expr *expr)
6827 : {
6828 : Node *result;
6829 :
6830 : /*
6831 : * Convert named-argument function calls, insert default arguments and
6832 : * simplify constant subexprs
6833 : */
6834 134334 : result = eval_const_expressions(NULL, (Node *) expr);
6835 :
6836 : /* Fill in opfuncid values if missing */
6837 134322 : fix_opfuncids(result);
6838 :
6839 134322 : return (Expr *) result;
6840 : }
6841 :
6842 : /*
6843 : * expression_planner_with_deps
6844 : * Perform planner's transformations on a standalone expression,
6845 : * returning expression dependency information along with the result.
6846 : *
6847 : * This is identical to expression_planner() except that it also returns
6848 : * information about possible dependencies of the expression, ie identities of
6849 : * objects whose definitions affect the result. As in a PlannedStmt, these
6850 : * are expressed as a list of relation Oids and a list of PlanInvalItems.
6851 : */
6852 : Expr *
6853 252 : expression_planner_with_deps(Expr *expr,
6854 : List **relationOids,
6855 : List **invalItems)
6856 : {
6857 : Node *result;
6858 : PlannerGlobal glob;
6859 : PlannerInfo root;
6860 :
6861 : /* Make up dummy planner state so we can use setrefs machinery */
6862 7308 : MemSet(&glob, 0, sizeof(glob));
6863 252 : glob.type = T_PlannerGlobal;
6864 252 : glob.relationOids = NIL;
6865 252 : glob.invalItems = NIL;
6866 :
6867 23688 : MemSet(&root, 0, sizeof(root));
6868 252 : root.type = T_PlannerInfo;
6869 252 : root.glob = &glob;
6870 :
6871 : /*
6872 : * Convert named-argument function calls, insert default arguments and
6873 : * simplify constant subexprs. Collect identities of inlined functions
6874 : * and elided domains, too.
6875 : */
6876 252 : result = eval_const_expressions(&root, (Node *) expr);
6877 :
6878 : /* Fill in opfuncid values if missing */
6879 252 : fix_opfuncids(result);
6880 :
6881 : /*
6882 : * Now walk the finished expression to find anything else we ought to
6883 : * record as an expression dependency.
6884 : */
6885 252 : (void) extract_query_dependencies_walker(result, &root);
6886 :
6887 252 : *relationOids = glob.relationOids;
6888 252 : *invalItems = glob.invalItems;
6889 :
6890 252 : return (Expr *) result;
6891 : }
6892 :
6893 :
6894 : /*
6895 : * plan_cluster_use_sort
6896 : * Use the planner to decide how CLUSTER should implement sorting
6897 : *
6898 : * tableOid is the OID of a table to be clustered on its index indexOid
6899 : * (which is already known to be a btree index). Decide whether it's
6900 : * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
6901 : * Return true to use sorting, false to use an indexscan.
6902 : *
6903 : * Note: caller had better already hold some type of lock on the table.
6904 : */
6905 : bool
6906 140 : plan_cluster_use_sort(Oid tableOid, Oid indexOid)
6907 : {
6908 : PlannerInfo *root;
6909 : Query *query;
6910 : PlannerGlobal *glob;
6911 : RangeTblEntry *rte;
6912 : RelOptInfo *rel;
6913 : IndexOptInfo *indexInfo;
6914 : QualCost indexExprCost;
6915 : Cost comparisonCost;
6916 : Path *seqScanPath;
6917 : Path seqScanAndSortPath;
6918 : IndexPath *indexScanPath;
6919 : ListCell *lc;
6920 :
6921 : /* We can short-circuit the cost comparison if indexscans are disabled */
6922 140 : if (!enable_indexscan)
6923 20 : return true; /* use sort */
6924 :
6925 : /* Set up mostly-dummy planner state */
6926 120 : query = makeNode(Query);
6927 120 : query->commandType = CMD_SELECT;
6928 :
6929 120 : glob = makeNode(PlannerGlobal);
6930 :
6931 120 : root = makeNode(PlannerInfo);
6932 120 : root->parse = query;
6933 120 : root->glob = glob;
6934 120 : root->query_level = 1;
6935 120 : root->planner_cxt = CurrentMemoryContext;
6936 120 : root->wt_param_id = -1;
6937 120 : root->join_domains = list_make1(makeNode(JoinDomain));
6938 :
6939 : /* Build a minimal RTE for the rel */
6940 120 : rte = makeNode(RangeTblEntry);
6941 120 : rte->rtekind = RTE_RELATION;
6942 120 : rte->relid = tableOid;
6943 120 : rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6944 120 : rte->rellockmode = AccessShareLock;
6945 120 : rte->lateral = false;
6946 120 : rte->inh = false;
6947 120 : rte->inFromCl = true;
6948 120 : query->rtable = list_make1(rte);
6949 120 : addRTEPermissionInfo(&query->rteperminfos, rte);
6950 :
6951 : /* Set up RTE/RelOptInfo arrays */
6952 120 : setup_simple_rel_arrays(root);
6953 :
6954 : /* Build RelOptInfo */
6955 120 : rel = build_simple_rel(root, 1, NULL);
6956 :
6957 : /* Locate IndexOptInfo for the target index */
6958 120 : indexInfo = NULL;
6959 150 : foreach(lc, rel->indexlist)
6960 : {
6961 150 : indexInfo = lfirst_node(IndexOptInfo, lc);
6962 150 : if (indexInfo->indexoid == indexOid)
6963 120 : break;
6964 : }
6965 :
6966 : /*
6967 : * It's possible that get_relation_info did not generate an IndexOptInfo
6968 : * for the desired index; this could happen if it's not yet reached its
6969 : * indcheckxmin usability horizon, or if it's a system index and we're
6970 : * ignoring system indexes. In such cases we should tell CLUSTER to not
6971 : * trust the index contents but use seqscan-and-sort.
6972 : */
6973 120 : if (lc == NULL) /* not in the list? */
6974 0 : return true; /* use sort */
6975 :
6976 : /*
6977 : * Rather than doing all the pushups that would be needed to use
6978 : * set_baserel_size_estimates, just do a quick hack for rows and width.
6979 : */
6980 120 : rel->rows = rel->tuples;
6981 120 : rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6982 :
6983 120 : root->total_table_pages = rel->pages;
6984 :
6985 : /*
6986 : * Determine eval cost of the index expressions, if any. We need to
6987 : * charge twice that amount for each tuple comparison that happens during
6988 : * the sort, since tuplesort.c will have to re-evaluate the index
6989 : * expressions each time. (XXX that's pretty inefficient...)
6990 : */
6991 120 : cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6992 120 : comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6993 :
6994 : /* Estimate the cost of seq scan + sort */
6995 120 : seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6996 120 : cost_sort(&seqScanAndSortPath, root, NIL,
6997 : seqScanPath->disabled_nodes,
6998 120 : seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6999 : comparisonCost, maintenance_work_mem, -1.0);
7000 :
7001 : /* Estimate the cost of index scan */
7002 120 : indexScanPath = create_index_path(root, indexInfo,
7003 : NIL, NIL, NIL, NIL,
7004 : ForwardScanDirection, false,
7005 : NULL, 1.0, false);
7006 :
7007 120 : return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
7008 : }
7009 :
7010 : /*
7011 : * plan_create_index_workers
7012 : * Use the planner to decide how many parallel worker processes
7013 : * CREATE INDEX should request for use
7014 : *
7015 : * tableOid is the table on which the index is to be built. indexOid is the
7016 : * OID of an index to be created or reindexed (which must be an index with
7017 : * support for parallel builds - currently btree, GIN, or BRIN).
7018 : *
7019 : * Return value is the number of parallel worker processes to request. It
7020 : * may be unsafe to proceed if this is 0. Note that this does not include the
7021 : * leader participating as a worker (value is always a number of parallel
7022 : * worker processes).
7023 : *
7024 : * Note: caller had better already hold some type of lock on the table and
7025 : * index.
7026 : */
7027 : int
7028 22472 : plan_create_index_workers(Oid tableOid, Oid indexOid)
7029 : {
7030 : PlannerInfo *root;
7031 : Query *query;
7032 : PlannerGlobal *glob;
7033 : RangeTblEntry *rte;
7034 : Relation heap;
7035 : Relation index;
7036 : RelOptInfo *rel;
7037 : int parallel_workers;
7038 : BlockNumber heap_blocks;
7039 : double reltuples;
7040 : double allvisfrac;
7041 :
7042 : /*
7043 : * We don't allow performing parallel operation in standalone backend or
7044 : * when parallelism is disabled.
7045 : */
7046 22472 : if (!IsUnderPostmaster || max_parallel_maintenance_workers == 0)
7047 277 : return 0;
7048 :
7049 : /* Set up largely-dummy planner state */
7050 22195 : query = makeNode(Query);
7051 22195 : query->commandType = CMD_SELECT;
7052 :
7053 22195 : glob = makeNode(PlannerGlobal);
7054 :
7055 22195 : root = makeNode(PlannerInfo);
7056 22195 : root->parse = query;
7057 22195 : root->glob = glob;
7058 22195 : root->query_level = 1;
7059 22195 : root->planner_cxt = CurrentMemoryContext;
7060 22195 : root->wt_param_id = -1;
7061 22195 : root->join_domains = list_make1(makeNode(JoinDomain));
7062 :
7063 : /*
7064 : * Build a minimal RTE.
7065 : *
7066 : * Mark the RTE with inh = true. This is a kludge to prevent
7067 : * get_relation_info() from fetching index info, which is necessary
7068 : * because it does not expect that any IndexOptInfo is currently
7069 : * undergoing REINDEX.
7070 : */
7071 22195 : rte = makeNode(RangeTblEntry);
7072 22195 : rte->rtekind = RTE_RELATION;
7073 22195 : rte->relid = tableOid;
7074 22195 : rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
7075 22195 : rte->rellockmode = AccessShareLock;
7076 22195 : rte->lateral = false;
7077 22195 : rte->inh = true;
7078 22195 : rte->inFromCl = true;
7079 22195 : query->rtable = list_make1(rte);
7080 22195 : addRTEPermissionInfo(&query->rteperminfos, rte);
7081 :
7082 : /* Set up RTE/RelOptInfo arrays */
7083 22195 : setup_simple_rel_arrays(root);
7084 :
7085 : /* Build RelOptInfo */
7086 22195 : rel = build_simple_rel(root, 1, NULL);
7087 :
7088 : /* Rels are assumed already locked by the caller */
7089 22195 : heap = table_open(tableOid, NoLock);
7090 22195 : index = index_open(indexOid, NoLock);
7091 :
7092 : /*
7093 : * Determine if it's safe to proceed.
7094 : *
7095 : * Currently, parallel workers can't access the leader's temporary tables.
7096 : * Furthermore, any index predicate or index expressions must be parallel
7097 : * safe.
7098 : */
7099 22195 : if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
7100 20815 : !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index)) ||
7101 20725 : !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index)))
7102 : {
7103 1470 : parallel_workers = 0;
7104 1470 : goto done;
7105 : }
7106 :
7107 : /*
7108 : * If parallel_workers storage parameter is set for the table, accept that
7109 : * as the number of parallel worker processes to launch (though still cap
7110 : * at max_parallel_maintenance_workers). Note that we deliberately do not
7111 : * consider any other factor when parallel_workers is set. (e.g., memory
7112 : * use by workers.)
7113 : */
7114 20725 : if (rel->rel_parallel_workers != -1)
7115 : {
7116 57 : parallel_workers = Min(rel->rel_parallel_workers,
7117 : max_parallel_maintenance_workers);
7118 57 : goto done;
7119 : }
7120 :
7121 : /*
7122 : * Estimate heap relation size ourselves, since rel->pages cannot be
7123 : * trusted (heap RTE was marked as inheritance parent)
7124 : */
7125 20668 : estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
7126 :
7127 : /*
7128 : * Determine number of workers to scan the heap relation using generic
7129 : * model
7130 : */
7131 20668 : parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
7132 : max_parallel_maintenance_workers);
7133 :
7134 : /*
7135 : * Cap workers based on available maintenance_work_mem as needed.
7136 : *
7137 : * Note that each tuplesort participant receives an even share of the
7138 : * total maintenance_work_mem budget. Aim to leave participants
7139 : * (including the leader as a participant) with no less than 32MB of
7140 : * memory. This leaves cases where maintenance_work_mem is set to 64MB
7141 : * immediately past the threshold of being capable of launching a single
7142 : * parallel worker to sort.
7143 : */
7144 20777 : while (parallel_workers > 0 &&
7145 219 : maintenance_work_mem / (parallel_workers + 1) < 32 * 1024)
7146 109 : parallel_workers--;
7147 :
7148 20668 : done:
7149 22195 : index_close(index, NoLock);
7150 22195 : table_close(heap, NoLock);
7151 :
7152 22195 : return parallel_workers;
7153 : }
7154 :
7155 : /*
7156 : * add_paths_to_grouping_rel
7157 : *
7158 : * Add non-partial paths to grouping relation.
7159 : */
7160 : static void
7161 34608 : add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
7162 : RelOptInfo *grouped_rel,
7163 : RelOptInfo *partially_grouped_rel,
7164 : const AggClauseCosts *agg_costs,
7165 : grouping_sets_data *gd,
7166 : GroupPathExtraData *extra)
7167 : {
7168 34608 : Query *parse = root->parse;
7169 34608 : Path *cheapest_path = input_rel->cheapest_total_path;
7170 34608 : Path *cheapest_partially_grouped_path = NULL;
7171 : ListCell *lc;
7172 34608 : bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7173 34608 : bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7174 34608 : List *havingQual = (List *) extra->havingQual;
7175 34608 : AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7176 34608 : double dNumGroups = 0;
7177 34608 : double dNumFinalGroups = 0;
7178 :
7179 : /*
7180 : * Estimate number of groups for non-split aggregation.
7181 : */
7182 34608 : dNumGroups = get_number_of_groups(root,
7183 : cheapest_path->rows,
7184 : gd,
7185 : extra->targetList);
7186 :
7187 34608 : if (partially_grouped_rel && partially_grouped_rel->pathlist)
7188 : {
7189 2511 : cheapest_partially_grouped_path =
7190 : partially_grouped_rel->cheapest_total_path;
7191 :
7192 : /*
7193 : * Estimate number of groups for final phase of partial aggregation.
7194 : */
7195 : dNumFinalGroups =
7196 2511 : get_number_of_groups(root,
7197 : cheapest_partially_grouped_path->rows,
7198 : gd,
7199 : extra->targetList);
7200 : }
7201 :
7202 34608 : if (can_sort)
7203 : {
7204 : /*
7205 : * Use any available suitably-sorted path as input, and also consider
7206 : * sorting the cheapest-total path and incremental sort on any paths
7207 : * with presorted keys.
7208 : */
7209 71722 : foreach(lc, input_rel->pathlist)
7210 : {
7211 : ListCell *lc2;
7212 37119 : Path *path = (Path *) lfirst(lc);
7213 37119 : Path *path_save = path;
7214 37119 : List *pathkey_orderings = NIL;
7215 :
7216 : /* generate alternative group orderings that might be useful */
7217 37119 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7218 :
7219 : Assert(list_length(pathkey_orderings) > 0);
7220 :
7221 74355 : foreach(lc2, pathkey_orderings)
7222 : {
7223 37236 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7224 :
7225 : /* restore the path (we replace it in the loop) */
7226 37236 : path = path_save;
7227 :
7228 37236 : path = make_ordered_path(root,
7229 : grouped_rel,
7230 : path,
7231 : cheapest_path,
7232 : info->pathkeys,
7233 : -1.0);
7234 37236 : if (path == NULL)
7235 306 : continue;
7236 :
7237 : /* Now decide what to stick atop it */
7238 36930 : if (parse->groupingSets)
7239 : {
7240 885 : consider_groupingsets_paths(root, grouped_rel,
7241 : path, true, can_hash,
7242 : gd, agg_costs, dNumGroups);
7243 : }
7244 36045 : else if (parse->hasAggs)
7245 : {
7246 : /*
7247 : * We have aggregation, possibly with plain GROUP BY. Make
7248 : * an AggPath.
7249 : */
7250 35393 : add_path(grouped_rel, (Path *)
7251 35393 : create_agg_path(root,
7252 : grouped_rel,
7253 : path,
7254 35393 : grouped_rel->reltarget,
7255 35393 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7256 : AGGSPLIT_SIMPLE,
7257 : info->clauses,
7258 : havingQual,
7259 : agg_costs,
7260 : dNumGroups));
7261 : }
7262 652 : else if (parse->groupClause)
7263 : {
7264 : /*
7265 : * We have GROUP BY without aggregation or grouping sets.
7266 : * Make a GroupPath.
7267 : */
7268 652 : add_path(grouped_rel, (Path *)
7269 652 : create_group_path(root,
7270 : grouped_rel,
7271 : path,
7272 : info->clauses,
7273 : havingQual,
7274 : dNumGroups));
7275 : }
7276 : else
7277 : {
7278 : /* Other cases should have been handled above */
7279 : Assert(false);
7280 : }
7281 : }
7282 : }
7283 :
7284 : /*
7285 : * Instead of operating directly on the input relation, we can
7286 : * consider finalizing a partially aggregated path.
7287 : */
7288 34603 : if (partially_grouped_rel != NULL)
7289 : {
7290 6478 : foreach(lc, partially_grouped_rel->pathlist)
7291 : {
7292 : ListCell *lc2;
7293 3967 : Path *path = (Path *) lfirst(lc);
7294 3967 : Path *path_save = path;
7295 3967 : List *pathkey_orderings = NIL;
7296 :
7297 : /* generate alternative group orderings that might be useful */
7298 3967 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7299 :
7300 : Assert(list_length(pathkey_orderings) > 0);
7301 :
7302 : /* process all potentially interesting grouping reorderings */
7303 7934 : foreach(lc2, pathkey_orderings)
7304 : {
7305 3967 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7306 :
7307 : /* restore the path (we replace it in the loop) */
7308 3967 : path = path_save;
7309 :
7310 3967 : path = make_ordered_path(root,
7311 : grouped_rel,
7312 : path,
7313 : cheapest_partially_grouped_path,
7314 : info->pathkeys,
7315 : -1.0);
7316 :
7317 3967 : if (path == NULL)
7318 172 : continue;
7319 :
7320 3795 : if (parse->hasAggs)
7321 3593 : add_path(grouped_rel, (Path *)
7322 3593 : create_agg_path(root,
7323 : grouped_rel,
7324 : path,
7325 3593 : grouped_rel->reltarget,
7326 3593 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7327 : AGGSPLIT_FINAL_DESERIAL,
7328 : info->clauses,
7329 : havingQual,
7330 : agg_final_costs,
7331 : dNumFinalGroups));
7332 : else
7333 202 : add_path(grouped_rel, (Path *)
7334 202 : create_group_path(root,
7335 : grouped_rel,
7336 : path,
7337 : info->clauses,
7338 : havingQual,
7339 : dNumFinalGroups));
7340 :
7341 : }
7342 : }
7343 : }
7344 : }
7345 :
7346 34608 : if (can_hash)
7347 : {
7348 4859 : if (parse->groupingSets)
7349 : {
7350 : /*
7351 : * Try for a hash-only groupingsets path over unsorted input.
7352 : */
7353 757 : consider_groupingsets_paths(root, grouped_rel,
7354 : cheapest_path, false, true,
7355 : gd, agg_costs, dNumGroups);
7356 : }
7357 : else
7358 : {
7359 : /*
7360 : * Generate a HashAgg Path. We just need an Agg over the
7361 : * cheapest-total input path, since input order won't matter.
7362 : */
7363 4102 : add_path(grouped_rel, (Path *)
7364 4102 : create_agg_path(root, grouped_rel,
7365 : cheapest_path,
7366 4102 : grouped_rel->reltarget,
7367 : AGG_HASHED,
7368 : AGGSPLIT_SIMPLE,
7369 : root->processed_groupClause,
7370 : havingQual,
7371 : agg_costs,
7372 : dNumGroups));
7373 : }
7374 :
7375 : /*
7376 : * Generate a Finalize HashAgg Path atop of the cheapest partially
7377 : * grouped path, assuming there is one
7378 : */
7379 4859 : if (partially_grouped_rel && partially_grouped_rel->pathlist)
7380 : {
7381 1202 : add_path(grouped_rel, (Path *)
7382 1202 : create_agg_path(root,
7383 : grouped_rel,
7384 : cheapest_partially_grouped_path,
7385 1202 : grouped_rel->reltarget,
7386 : AGG_HASHED,
7387 : AGGSPLIT_FINAL_DESERIAL,
7388 : root->processed_groupClause,
7389 : havingQual,
7390 : agg_final_costs,
7391 : dNumFinalGroups));
7392 : }
7393 : }
7394 :
7395 : /*
7396 : * When partitionwise aggregate is used, we might have fully aggregated
7397 : * paths in the partial pathlist, because add_paths_to_append_rel() will
7398 : * consider a path for grouped_rel consisting of a Parallel Append of
7399 : * non-partial paths from each child.
7400 : */
7401 34608 : if (grouped_rel->partial_pathlist != NIL)
7402 265 : gather_grouping_paths(root, grouped_rel);
7403 34608 : }
7404 :
7405 : /*
7406 : * create_partial_grouping_paths
7407 : *
7408 : * Create a new upper relation representing the result of partial aggregation
7409 : * and populate it with appropriate paths. Note that we don't finalize the
7410 : * lists of paths here, so the caller can add additional partial or non-partial
7411 : * paths and must afterward call gather_grouping_paths and set_cheapest on
7412 : * the returned upper relation.
7413 : *
7414 : * All paths for this new upper relation -- both partial and non-partial --
7415 : * have been partially aggregated but require a subsequent FinalizeAggregate
7416 : * step.
7417 : *
7418 : * NB: This function is allowed to return NULL if it determines that there is
7419 : * no real need to create a new RelOptInfo.
7420 : */
7421 : static RelOptInfo *
7422 31274 : create_partial_grouping_paths(PlannerInfo *root,
7423 : RelOptInfo *grouped_rel,
7424 : RelOptInfo *input_rel,
7425 : grouping_sets_data *gd,
7426 : GroupPathExtraData *extra,
7427 : bool force_rel_creation)
7428 : {
7429 31274 : Query *parse = root->parse;
7430 : RelOptInfo *partially_grouped_rel;
7431 31274 : RelOptInfo *eager_agg_rel = NULL;
7432 31274 : AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
7433 31274 : AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7434 31274 : Path *cheapest_partial_path = NULL;
7435 31274 : Path *cheapest_total_path = NULL;
7436 31274 : double dNumPartialGroups = 0;
7437 31274 : double dNumPartialPartialGroups = 0;
7438 : ListCell *lc;
7439 31274 : bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7440 31274 : bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7441 :
7442 : /*
7443 : * Check whether any partially aggregated paths have been generated
7444 : * through eager aggregation.
7445 : */
7446 31274 : if (input_rel->grouped_rel &&
7447 797 : !IS_DUMMY_REL(input_rel->grouped_rel) &&
7448 797 : input_rel->grouped_rel->pathlist != NIL)
7449 747 : eager_agg_rel = input_rel->grouped_rel;
7450 :
7451 : /*
7452 : * Consider whether we should generate partially aggregated non-partial
7453 : * paths. We can only do this if we have a non-partial path, and only if
7454 : * the parent of the input rel is performing partial partitionwise
7455 : * aggregation. (Note that extra->patype is the type of partitionwise
7456 : * aggregation being used at the parent level, not this level.)
7457 : */
7458 31274 : if (input_rel->pathlist != NIL &&
7459 31274 : extra->patype == PARTITIONWISE_AGGREGATE_PARTIAL)
7460 713 : cheapest_total_path = input_rel->cheapest_total_path;
7461 :
7462 : /*
7463 : * If parallelism is possible for grouped_rel, then we should consider
7464 : * generating partially-grouped partial paths. However, if the input rel
7465 : * has no partial paths, then we can't.
7466 : */
7467 31274 : if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
7468 2743 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
7469 :
7470 : /*
7471 : * If we can't partially aggregate partial paths, and we can't partially
7472 : * aggregate non-partial paths, and no partially aggregated paths were
7473 : * generated by eager aggregation, then don't bother creating the new
7474 : * RelOptInfo at all, unless the caller specified force_rel_creation.
7475 : */
7476 31274 : if (cheapest_total_path == NULL &&
7477 28238 : cheapest_partial_path == NULL &&
7478 28131 : eager_agg_rel == NULL &&
7479 28131 : !force_rel_creation)
7480 28050 : return NULL;
7481 :
7482 : /*
7483 : * Build a new upper relation to represent the result of partially
7484 : * aggregating the rows from the input relation.
7485 : */
7486 3224 : partially_grouped_rel = fetch_upper_rel(root,
7487 : UPPERREL_PARTIAL_GROUP_AGG,
7488 : grouped_rel->relids);
7489 3224 : partially_grouped_rel->consider_parallel =
7490 3224 : grouped_rel->consider_parallel;
7491 3224 : partially_grouped_rel->pgs_mask = grouped_rel->pgs_mask;
7492 3224 : partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
7493 3224 : partially_grouped_rel->serverid = grouped_rel->serverid;
7494 3224 : partially_grouped_rel->userid = grouped_rel->userid;
7495 3224 : partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
7496 3224 : partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
7497 :
7498 : /*
7499 : * Build target list for partial aggregate paths. These paths cannot just
7500 : * emit the same tlist as regular aggregate paths, because (1) we must
7501 : * include Vars and Aggrefs needed in HAVING, which might not appear in
7502 : * the result tlist, and (2) the Aggrefs must be set in partial mode.
7503 : */
7504 3224 : partially_grouped_rel->reltarget =
7505 3224 : make_partial_grouping_target(root, grouped_rel->reltarget,
7506 : extra->havingQual);
7507 :
7508 3224 : if (!extra->partial_costs_set)
7509 : {
7510 : /*
7511 : * Collect statistics about aggregates for estimating costs of
7512 : * performing aggregation in parallel.
7513 : */
7514 11646 : MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
7515 11646 : MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
7516 1941 : if (parse->hasAggs)
7517 : {
7518 : /* partial phase */
7519 1832 : get_agg_clause_costs(root, AGGSPLIT_INITIAL_SERIAL,
7520 : agg_partial_costs);
7521 :
7522 : /* final phase */
7523 1832 : get_agg_clause_costs(root, AGGSPLIT_FINAL_DESERIAL,
7524 : agg_final_costs);
7525 : }
7526 :
7527 1941 : extra->partial_costs_set = true;
7528 : }
7529 :
7530 : /* Estimate number of partial groups. */
7531 3224 : if (cheapest_total_path != NULL)
7532 : dNumPartialGroups =
7533 713 : get_number_of_groups(root,
7534 : cheapest_total_path->rows,
7535 : gd,
7536 : extra->targetList);
7537 3224 : if (cheapest_partial_path != NULL)
7538 : dNumPartialPartialGroups =
7539 2743 : get_number_of_groups(root,
7540 : cheapest_partial_path->rows,
7541 : gd,
7542 : extra->targetList);
7543 :
7544 3224 : if (can_sort && cheapest_total_path != NULL)
7545 : {
7546 : /* This should have been checked previously */
7547 : Assert(parse->hasAggs || parse->groupClause);
7548 :
7549 : /*
7550 : * Use any available suitably-sorted path as input, and also consider
7551 : * sorting the cheapest partial path.
7552 : */
7553 1426 : foreach(lc, input_rel->pathlist)
7554 : {
7555 : ListCell *lc2;
7556 713 : Path *path = (Path *) lfirst(lc);
7557 713 : Path *path_save = path;
7558 713 : List *pathkey_orderings = NIL;
7559 :
7560 : /* generate alternative group orderings that might be useful */
7561 713 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7562 :
7563 : Assert(list_length(pathkey_orderings) > 0);
7564 :
7565 : /* process all potentially interesting grouping reorderings */
7566 1426 : foreach(lc2, pathkey_orderings)
7567 : {
7568 713 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7569 :
7570 : /* restore the path (we replace it in the loop) */
7571 713 : path = path_save;
7572 :
7573 713 : path = make_ordered_path(root,
7574 : partially_grouped_rel,
7575 : path,
7576 : cheapest_total_path,
7577 : info->pathkeys,
7578 : -1.0);
7579 :
7580 713 : if (path == NULL)
7581 0 : continue;
7582 :
7583 713 : if (parse->hasAggs)
7584 653 : add_path(partially_grouped_rel, (Path *)
7585 653 : create_agg_path(root,
7586 : partially_grouped_rel,
7587 : path,
7588 653 : partially_grouped_rel->reltarget,
7589 653 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7590 : AGGSPLIT_INITIAL_SERIAL,
7591 : info->clauses,
7592 : NIL,
7593 : agg_partial_costs,
7594 : dNumPartialGroups));
7595 : else
7596 60 : add_path(partially_grouped_rel, (Path *)
7597 60 : create_group_path(root,
7598 : partially_grouped_rel,
7599 : path,
7600 : info->clauses,
7601 : NIL,
7602 : dNumPartialGroups));
7603 : }
7604 : }
7605 : }
7606 :
7607 3224 : if (can_sort && cheapest_partial_path != NULL)
7608 : {
7609 : /* Similar to above logic, but for partial paths. */
7610 5861 : foreach(lc, input_rel->partial_pathlist)
7611 : {
7612 : ListCell *lc2;
7613 3118 : Path *path = (Path *) lfirst(lc);
7614 3118 : Path *path_save = path;
7615 3118 : List *pathkey_orderings = NIL;
7616 :
7617 : /* generate alternative group orderings that might be useful */
7618 3118 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7619 :
7620 : Assert(list_length(pathkey_orderings) > 0);
7621 :
7622 : /* process all potentially interesting grouping reorderings */
7623 6236 : foreach(lc2, pathkey_orderings)
7624 : {
7625 3118 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7626 :
7627 :
7628 : /* restore the path (we replace it in the loop) */
7629 3118 : path = path_save;
7630 :
7631 3118 : path = make_ordered_path(root,
7632 : partially_grouped_rel,
7633 : path,
7634 : cheapest_partial_path,
7635 : info->pathkeys,
7636 : -1.0);
7637 :
7638 3118 : if (path == NULL)
7639 5 : continue;
7640 :
7641 3113 : if (parse->hasAggs)
7642 3014 : add_partial_path(partially_grouped_rel, (Path *)
7643 3014 : create_agg_path(root,
7644 : partially_grouped_rel,
7645 : path,
7646 3014 : partially_grouped_rel->reltarget,
7647 3014 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7648 : AGGSPLIT_INITIAL_SERIAL,
7649 : info->clauses,
7650 : NIL,
7651 : agg_partial_costs,
7652 : dNumPartialPartialGroups));
7653 : else
7654 99 : add_partial_path(partially_grouped_rel, (Path *)
7655 99 : create_group_path(root,
7656 : partially_grouped_rel,
7657 : path,
7658 : info->clauses,
7659 : NIL,
7660 : dNumPartialPartialGroups));
7661 : }
7662 : }
7663 : }
7664 :
7665 : /*
7666 : * Add a partially-grouped HashAgg Path where possible
7667 : */
7668 3224 : if (can_hash && cheapest_total_path != NULL)
7669 : {
7670 : /* Checked above */
7671 : Assert(parse->hasAggs || parse->groupClause);
7672 :
7673 713 : add_path(partially_grouped_rel, (Path *)
7674 713 : create_agg_path(root,
7675 : partially_grouped_rel,
7676 : cheapest_total_path,
7677 713 : partially_grouped_rel->reltarget,
7678 : AGG_HASHED,
7679 : AGGSPLIT_INITIAL_SERIAL,
7680 : root->processed_groupClause,
7681 : NIL,
7682 : agg_partial_costs,
7683 : dNumPartialGroups));
7684 : }
7685 :
7686 : /*
7687 : * Now add a partially-grouped HashAgg partial Path where possible
7688 : */
7689 3224 : if (can_hash && cheapest_partial_path != NULL)
7690 : {
7691 1434 : add_partial_path(partially_grouped_rel, (Path *)
7692 1434 : create_agg_path(root,
7693 : partially_grouped_rel,
7694 : cheapest_partial_path,
7695 1434 : partially_grouped_rel->reltarget,
7696 : AGG_HASHED,
7697 : AGGSPLIT_INITIAL_SERIAL,
7698 : root->processed_groupClause,
7699 : NIL,
7700 : agg_partial_costs,
7701 : dNumPartialPartialGroups));
7702 : }
7703 :
7704 : /*
7705 : * Add any partially aggregated paths generated by eager aggregation to
7706 : * the new upper relation after applying projection steps as needed.
7707 : */
7708 3224 : if (eager_agg_rel)
7709 : {
7710 : /* Add the paths */
7711 1954 : foreach(lc, eager_agg_rel->pathlist)
7712 : {
7713 1207 : Path *path = (Path *) lfirst(lc);
7714 :
7715 : /* Shouldn't have any parameterized paths anymore */
7716 : Assert(path->param_info == NULL);
7717 :
7718 1207 : path = (Path *) create_projection_path(root,
7719 : partially_grouped_rel,
7720 : path,
7721 1207 : partially_grouped_rel->reltarget);
7722 :
7723 1207 : add_path(partially_grouped_rel, path);
7724 : }
7725 :
7726 : /*
7727 : * Likewise add the partial paths, but only if parallelism is possible
7728 : * for partially_grouped_rel.
7729 : */
7730 747 : if (partially_grouped_rel->consider_parallel)
7731 : {
7732 1690 : foreach(lc, eager_agg_rel->partial_pathlist)
7733 : {
7734 1010 : Path *path = (Path *) lfirst(lc);
7735 :
7736 : /* Shouldn't have any parameterized paths anymore */
7737 : Assert(path->param_info == NULL);
7738 :
7739 1010 : path = (Path *) create_projection_path(root,
7740 : partially_grouped_rel,
7741 : path,
7742 1010 : partially_grouped_rel->reltarget);
7743 :
7744 1010 : add_partial_path(partially_grouped_rel, path);
7745 : }
7746 : }
7747 : }
7748 :
7749 : /*
7750 : * If there is an FDW that's responsible for all baserels of the query,
7751 : * let it consider adding partially grouped ForeignPaths.
7752 : */
7753 3224 : if (partially_grouped_rel->fdwroutine &&
7754 3 : partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
7755 : {
7756 3 : FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
7757 :
7758 3 : fdwroutine->GetForeignUpperPaths(root,
7759 : UPPERREL_PARTIAL_GROUP_AGG,
7760 : input_rel, partially_grouped_rel,
7761 : extra);
7762 : }
7763 :
7764 3224 : return partially_grouped_rel;
7765 : }
7766 :
7767 : /*
7768 : * make_ordered_path
7769 : * Return a path ordered by 'pathkeys' based on the given 'path'. May
7770 : * return NULL if it doesn't make sense to generate an ordered path in
7771 : * this case.
7772 : */
7773 : static Path *
7774 49005 : make_ordered_path(PlannerInfo *root, RelOptInfo *rel, Path *path,
7775 : Path *cheapest_path, List *pathkeys, double limit_tuples)
7776 : {
7777 : bool is_sorted;
7778 : int presorted_keys;
7779 :
7780 49005 : is_sorted = pathkeys_count_contained_in(pathkeys,
7781 : path->pathkeys,
7782 : &presorted_keys);
7783 :
7784 49005 : if (!is_sorted)
7785 : {
7786 : /*
7787 : * Try at least sorting the cheapest path and also try incrementally
7788 : * sorting any path which is partially sorted already (no need to deal
7789 : * with paths which have presorted keys when incremental sort is
7790 : * disabled unless it's the cheapest input path).
7791 : */
7792 12907 : if (path != cheapest_path &&
7793 2146 : (presorted_keys == 0 || !enable_incremental_sort))
7794 1020 : return NULL;
7795 :
7796 : /*
7797 : * We've no need to consider both a sort and incremental sort. We'll
7798 : * just do a sort if there are no presorted keys and an incremental
7799 : * sort when there are presorted keys.
7800 : */
7801 11887 : if (presorted_keys == 0 || !enable_incremental_sort)
7802 10615 : path = (Path *) create_sort_path(root,
7803 : rel,
7804 : path,
7805 : pathkeys,
7806 : limit_tuples);
7807 : else
7808 1272 : path = (Path *) create_incremental_sort_path(root,
7809 : rel,
7810 : path,
7811 : pathkeys,
7812 : presorted_keys,
7813 : limit_tuples);
7814 : }
7815 :
7816 47985 : return path;
7817 : }
7818 :
7819 : /*
7820 : * Generate Gather and Gather Merge paths for a grouping relation or partial
7821 : * grouping relation.
7822 : *
7823 : * generate_useful_gather_paths does most of the work, but we also consider a
7824 : * special case: we could try sorting the data by the group_pathkeys and then
7825 : * applying Gather Merge.
7826 : *
7827 : * NB: This function shouldn't be used for anything other than a grouped or
7828 : * partially grouped relation not only because of the fact that it explicitly
7829 : * references group_pathkeys but we pass "true" as the third argument to
7830 : * generate_useful_gather_paths().
7831 : */
7832 : static void
7833 2588 : gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
7834 : {
7835 : ListCell *lc;
7836 : Path *cheapest_partial_path;
7837 : List *groupby_pathkeys;
7838 :
7839 : /*
7840 : * This occurs after any partial aggregation has taken place, so trim off
7841 : * any pathkeys added for ORDER BY / DISTINCT aggregates.
7842 : */
7843 2588 : if (list_length(root->group_pathkeys) > root->num_groupby_pathkeys)
7844 15 : groupby_pathkeys = list_copy_head(root->group_pathkeys,
7845 : root->num_groupby_pathkeys);
7846 : else
7847 2573 : groupby_pathkeys = root->group_pathkeys;
7848 :
7849 : /* Try Gather for unordered paths and Gather Merge for ordered ones. */
7850 2588 : generate_useful_gather_paths(root, rel, true);
7851 :
7852 2588 : cheapest_partial_path = linitial(rel->partial_pathlist);
7853 :
7854 : /* XXX Shouldn't this also consider the group-key-reordering? */
7855 6148 : foreach(lc, rel->partial_pathlist)
7856 : {
7857 3560 : Path *path = (Path *) lfirst(lc);
7858 : bool is_sorted;
7859 : int presorted_keys;
7860 : double total_groups;
7861 :
7862 3560 : is_sorted = pathkeys_count_contained_in(groupby_pathkeys,
7863 : path->pathkeys,
7864 : &presorted_keys);
7865 :
7866 3560 : if (is_sorted)
7867 2327 : continue;
7868 :
7869 : /*
7870 : * Try at least sorting the cheapest path and also try incrementally
7871 : * sorting any path which is partially sorted already (no need to deal
7872 : * with paths which have presorted keys when incremental sort is
7873 : * disabled unless it's the cheapest input path).
7874 : */
7875 1233 : if (path != cheapest_partial_path &&
7876 0 : (presorted_keys == 0 || !enable_incremental_sort))
7877 0 : continue;
7878 :
7879 : /*
7880 : * We've no need to consider both a sort and incremental sort. We'll
7881 : * just do a sort if there are no presorted keys and an incremental
7882 : * sort when there are presorted keys.
7883 : */
7884 1233 : if (presorted_keys == 0 || !enable_incremental_sort)
7885 1233 : path = (Path *) create_sort_path(root, rel, path,
7886 : groupby_pathkeys,
7887 : -1.0);
7888 : else
7889 0 : path = (Path *) create_incremental_sort_path(root,
7890 : rel,
7891 : path,
7892 : groupby_pathkeys,
7893 : presorted_keys,
7894 : -1.0);
7895 1233 : total_groups = compute_gather_rows(path);
7896 : path = (Path *)
7897 1233 : create_gather_merge_path(root,
7898 : rel,
7899 : path,
7900 1233 : rel->reltarget,
7901 : groupby_pathkeys,
7902 : NULL,
7903 : &total_groups);
7904 :
7905 1233 : add_path(rel, path);
7906 : }
7907 2588 : }
7908 :
7909 : /*
7910 : * can_partial_agg
7911 : *
7912 : * Determines whether or not partial grouping and/or aggregation is possible.
7913 : * Returns true when possible, false otherwise.
7914 : */
7915 : static bool
7916 33526 : can_partial_agg(PlannerInfo *root)
7917 : {
7918 33526 : Query *parse = root->parse;
7919 :
7920 33526 : if (!parse->hasAggs && parse->groupClause == NIL)
7921 : {
7922 : /*
7923 : * We don't know how to do parallel aggregation unless we have either
7924 : * some aggregates or a grouping clause.
7925 : */
7926 0 : return false;
7927 : }
7928 33526 : else if (parse->groupingSets)
7929 : {
7930 : /* We don't know how to do grouping sets in parallel. */
7931 836 : return false;
7932 : }
7933 32690 : else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
7934 : {
7935 : /* Insufficient support for partial mode. */
7936 3151 : return false;
7937 : }
7938 :
7939 : /* Everything looks good. */
7940 29539 : return true;
7941 : }
7942 :
7943 : /*
7944 : * apply_scanjoin_target_to_paths
7945 : *
7946 : * Adjust the final scan/join relation, and recursively all of its children,
7947 : * to generate the final scan/join target. It would be more correct to model
7948 : * this as a separate planning step with a new RelOptInfo at the toplevel and
7949 : * for each child relation, but doing it this way is noticeably cheaper.
7950 : * Maybe that problem can be solved at some point, but for now we do this.
7951 : *
7952 : * If tlist_same_exprs is true, then the scan/join target to be applied has
7953 : * the same expressions as the existing reltarget, so we need only insert the
7954 : * appropriate sortgroupref information. By avoiding the creation of
7955 : * projection paths we save effort both immediately and at plan creation time.
7956 : */
7957 : static void
7958 407619 : apply_scanjoin_target_to_paths(PlannerInfo *root,
7959 : RelOptInfo *rel,
7960 : List *scanjoin_targets,
7961 : List *scanjoin_targets_contain_srfs,
7962 : bool scanjoin_target_parallel_safe,
7963 : bool tlist_same_exprs)
7964 : {
7965 407619 : bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
7966 : PathTarget *scanjoin_target;
7967 : ListCell *lc;
7968 :
7969 : /* This recurses, so be paranoid. */
7970 407619 : check_stack_depth();
7971 :
7972 : /*
7973 : * If the rel only has Append and MergeAppend paths, we want to drop its
7974 : * existing paths and generate new ones. This function would still be
7975 : * correct if we kept the existing paths: we'd modify them to generate the
7976 : * correct target above the partitioning Append, and then they'd compete
7977 : * on cost with paths generating the target below the Append. However, in
7978 : * our current cost model the latter way is always the same or cheaper
7979 : * cost, so modifying the existing paths would just be useless work.
7980 : * Moreover, when the cost is the same, varying roundoff errors might
7981 : * sometimes allow an existing path to be picked, resulting in undesirable
7982 : * cross-platform plan variations. So we drop old paths and thereby force
7983 : * the work to be done below the Append.
7984 : *
7985 : * However, there are several cases when this optimization is not safe. If
7986 : * the rel isn't partitioned, then none of the paths will be Append or
7987 : * MergeAppend paths, so we should definitely not do this. If it is
7988 : * partitioned but is a joinrel, it may have Append and MergeAppend paths,
7989 : * but it can also have join paths that we can't afford to discard.
7990 : *
7991 : * Some care is needed, because we have to allow
7992 : * generate_useful_gather_paths to see the old partial paths in the next
7993 : * stanza. Hence, zap the main pathlist here, then allow
7994 : * generate_useful_gather_paths to add path(s) to the main list, and
7995 : * finally zap the partial pathlist.
7996 : */
7997 407619 : if (rel_is_partitioned && IS_SIMPLE_REL(rel))
7998 8578 : rel->pathlist = NIL;
7999 :
8000 : /*
8001 : * If the scan/join target is not parallel-safe, partial paths cannot
8002 : * generate it.
8003 : */
8004 407619 : if (!scanjoin_target_parallel_safe)
8005 : {
8006 : /*
8007 : * Since we can't generate the final scan/join target in parallel
8008 : * workers, this is our last opportunity to use any partial paths that
8009 : * exist; so build Gather path(s) that use them and emit whatever the
8010 : * current reltarget is. We don't do this in the case where the
8011 : * target is parallel-safe, since we will be able to generate superior
8012 : * paths by doing it after the final scan/join target has been
8013 : * applied.
8014 : */
8015 52635 : generate_useful_gather_paths(root, rel, false);
8016 :
8017 : /* Can't use parallel query above this level. */
8018 52635 : rel->partial_pathlist = NIL;
8019 52635 : rel->consider_parallel = false;
8020 : }
8021 :
8022 : /* Finish dropping old paths for a partitioned rel, per comment above */
8023 407619 : if (rel_is_partitioned && IS_SIMPLE_REL(rel))
8024 8578 : rel->partial_pathlist = NIL;
8025 :
8026 : /* Extract SRF-free scan/join target. */
8027 407619 : scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
8028 :
8029 : /*
8030 : * Apply the SRF-free scan/join target to each existing path.
8031 : *
8032 : * If the tlist exprs are the same, we can just inject the sortgroupref
8033 : * information into the existing pathtargets. Otherwise, replace each
8034 : * path with a projection path that generates the SRF-free scan/join
8035 : * target. This can't change the ordering of paths within rel->pathlist,
8036 : * so we just modify the list in place.
8037 : */
8038 851286 : foreach(lc, rel->pathlist)
8039 : {
8040 443667 : Path *subpath = (Path *) lfirst(lc);
8041 :
8042 : /* Shouldn't have any parameterized paths anymore */
8043 : Assert(subpath->param_info == NULL);
8044 :
8045 443667 : if (tlist_same_exprs)
8046 159461 : subpath->pathtarget->sortgrouprefs =
8047 159461 : scanjoin_target->sortgrouprefs;
8048 : else
8049 : {
8050 : Path *newpath;
8051 :
8052 284206 : newpath = (Path *) create_projection_path(root, rel, subpath,
8053 : scanjoin_target);
8054 284206 : lfirst(lc) = newpath;
8055 : }
8056 : }
8057 :
8058 : /* Likewise adjust the targets for any partial paths. */
8059 427448 : foreach(lc, rel->partial_pathlist)
8060 : {
8061 19829 : Path *subpath = (Path *) lfirst(lc);
8062 :
8063 : /* Shouldn't have any parameterized paths anymore */
8064 : Assert(subpath->param_info == NULL);
8065 :
8066 19829 : if (tlist_same_exprs)
8067 15796 : subpath->pathtarget->sortgrouprefs =
8068 15796 : scanjoin_target->sortgrouprefs;
8069 : else
8070 : {
8071 : Path *newpath;
8072 :
8073 4033 : newpath = (Path *) create_projection_path(root, rel, subpath,
8074 : scanjoin_target);
8075 4033 : lfirst(lc) = newpath;
8076 : }
8077 : }
8078 :
8079 : /*
8080 : * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
8081 : * atop each existing path. (Note that this function doesn't look at the
8082 : * cheapest-path fields, which is a good thing because they're bogus right
8083 : * now.)
8084 : */
8085 407619 : if (root->parse->hasTargetSRFs)
8086 9905 : adjust_paths_for_srfs(root, rel,
8087 : scanjoin_targets,
8088 : scanjoin_targets_contain_srfs);
8089 :
8090 : /*
8091 : * Update the rel's target to be the final (with SRFs) scan/join target.
8092 : * This now matches the actual output of all the paths, and we might get
8093 : * confused in createplan.c if they don't agree. We must do this now so
8094 : * that any append paths made in the next part will use the correct
8095 : * pathtarget (cf. create_append_path).
8096 : *
8097 : * Note that this is also necessary if GetForeignUpperPaths() gets called
8098 : * on the final scan/join relation or on any of its children, since the
8099 : * FDW might look at the rel's target to create ForeignPaths.
8100 : */
8101 407619 : rel->reltarget = llast_node(PathTarget, scanjoin_targets);
8102 :
8103 : /*
8104 : * If the relation is partitioned, recursively apply the scan/join target
8105 : * to all partitions, and generate brand-new Append paths in which the
8106 : * scan/join target is computed below the Append rather than above it.
8107 : * Since Append is not projection-capable, that might save a separate
8108 : * Result node, and it also is important for partitionwise aggregate.
8109 : */
8110 407619 : if (rel_is_partitioned)
8111 : {
8112 9881 : List *live_children = NIL;
8113 : int i;
8114 :
8115 : /* Adjust each partition. */
8116 9881 : i = -1;
8117 29445 : while ((i = bms_next_member(rel->live_parts, i)) >= 0)
8118 : {
8119 19564 : RelOptInfo *child_rel = rel->part_rels[i];
8120 : AppendRelInfo **appinfos;
8121 : int nappinfos;
8122 19564 : List *child_scanjoin_targets = NIL;
8123 :
8124 : Assert(child_rel != NULL);
8125 :
8126 : /* Dummy children can be ignored. */
8127 19564 : if (IS_DUMMY_REL(child_rel))
8128 40 : continue;
8129 :
8130 : /* Translate scan/join targets for this child. */
8131 19524 : appinfos = find_appinfos_by_relids(root, child_rel->relids,
8132 : &nappinfos);
8133 39048 : foreach(lc, scanjoin_targets)
8134 : {
8135 19524 : PathTarget *target = lfirst_node(PathTarget, lc);
8136 :
8137 19524 : target = copy_pathtarget(target);
8138 19524 : target->exprs = (List *)
8139 19524 : adjust_appendrel_attrs(root,
8140 19524 : (Node *) target->exprs,
8141 : nappinfos, appinfos);
8142 19524 : child_scanjoin_targets = lappend(child_scanjoin_targets,
8143 : target);
8144 : }
8145 19524 : pfree(appinfos);
8146 :
8147 : /* Recursion does the real work. */
8148 19524 : apply_scanjoin_target_to_paths(root, child_rel,
8149 : child_scanjoin_targets,
8150 : scanjoin_targets_contain_srfs,
8151 : scanjoin_target_parallel_safe,
8152 : tlist_same_exprs);
8153 :
8154 : /* Save non-dummy children for Append paths. */
8155 19524 : if (!IS_DUMMY_REL(child_rel))
8156 19524 : live_children = lappend(live_children, child_rel);
8157 : }
8158 :
8159 : /* Build new paths for this relation by appending child paths. */
8160 9881 : add_paths_to_append_rel(root, rel, live_children);
8161 : }
8162 :
8163 : /*
8164 : * Consider generating Gather or Gather Merge paths. We must only do this
8165 : * if the relation is parallel safe, and we don't do it for child rels to
8166 : * avoid creating multiple Gather nodes within the same plan. We must do
8167 : * this after all paths have been generated and before set_cheapest, since
8168 : * one of the generated paths may turn out to be the cheapest one.
8169 : */
8170 407619 : if (rel->consider_parallel && !IS_OTHER_REL(rel))
8171 138425 : generate_useful_gather_paths(root, rel, false);
8172 :
8173 : /*
8174 : * Reassess which paths are the cheapest, now that we've potentially added
8175 : * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
8176 : * this relation.
8177 : */
8178 407619 : set_cheapest(rel);
8179 407619 : }
8180 :
8181 : /*
8182 : * create_partitionwise_grouping_paths
8183 : *
8184 : * If the partition keys of input relation are part of the GROUP BY clause, all
8185 : * the rows belonging to a given group come from a single partition. This
8186 : * allows aggregation/grouping over a partitioned relation to be broken down
8187 : * into aggregation/grouping on each partition. This should be no worse, and
8188 : * often better, than the normal approach.
8189 : *
8190 : * However, if the GROUP BY clause does not contain all the partition keys,
8191 : * rows from a given group may be spread across multiple partitions. In that
8192 : * case, we perform partial aggregation for each group, append the results,
8193 : * and then finalize aggregation. This is less certain to win than the
8194 : * previous case. It may win if the PartialAggregate stage greatly reduces
8195 : * the number of groups, because fewer rows will pass through the Append node.
8196 : * It may lose if we have lots of small groups.
8197 : */
8198 : static void
8199 685 : create_partitionwise_grouping_paths(PlannerInfo *root,
8200 : RelOptInfo *input_rel,
8201 : RelOptInfo *grouped_rel,
8202 : RelOptInfo *partially_grouped_rel,
8203 : const AggClauseCosts *agg_costs,
8204 : grouping_sets_data *gd,
8205 : PartitionwiseAggregateType patype,
8206 : GroupPathExtraData *extra)
8207 : {
8208 685 : List *grouped_live_children = NIL;
8209 685 : List *partially_grouped_live_children = NIL;
8210 685 : PathTarget *target = grouped_rel->reltarget;
8211 685 : bool partial_grouping_valid = true;
8212 : int i;
8213 :
8214 : Assert(patype != PARTITIONWISE_AGGREGATE_NONE);
8215 : Assert(patype != PARTITIONWISE_AGGREGATE_PARTIAL ||
8216 : partially_grouped_rel != NULL);
8217 :
8218 : /* Add paths for partitionwise aggregation/grouping. */
8219 685 : i = -1;
8220 2480 : while ((i = bms_next_member(input_rel->live_parts, i)) >= 0)
8221 : {
8222 1795 : RelOptInfo *child_input_rel = input_rel->part_rels[i];
8223 : PathTarget *child_target;
8224 : AppendRelInfo **appinfos;
8225 : int nappinfos;
8226 : GroupPathExtraData child_extra;
8227 : RelOptInfo *child_grouped_rel;
8228 : RelOptInfo *child_partially_grouped_rel;
8229 :
8230 : Assert(child_input_rel != NULL);
8231 :
8232 : /* Dummy children can be ignored. */
8233 1795 : if (IS_DUMMY_REL(child_input_rel))
8234 0 : continue;
8235 :
8236 1795 : child_target = copy_pathtarget(target);
8237 :
8238 : /*
8239 : * Copy the given "extra" structure as is and then override the
8240 : * members specific to this child.
8241 : */
8242 1795 : memcpy(&child_extra, extra, sizeof(child_extra));
8243 :
8244 1795 : appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
8245 : &nappinfos);
8246 :
8247 1795 : child_target->exprs = (List *)
8248 1795 : adjust_appendrel_attrs(root,
8249 1795 : (Node *) target->exprs,
8250 : nappinfos, appinfos);
8251 :
8252 : /* Translate havingQual and targetList. */
8253 1795 : child_extra.havingQual = (Node *)
8254 : adjust_appendrel_attrs(root,
8255 : extra->havingQual,
8256 : nappinfos, appinfos);
8257 1795 : child_extra.targetList = (List *)
8258 1795 : adjust_appendrel_attrs(root,
8259 1795 : (Node *) extra->targetList,
8260 : nappinfos, appinfos);
8261 :
8262 : /*
8263 : * extra->patype was the value computed for our parent rel; patype is
8264 : * the value for this relation. For the child, our value is its
8265 : * parent rel's value.
8266 : */
8267 1795 : child_extra.patype = patype;
8268 :
8269 : /*
8270 : * Create grouping relation to hold fully aggregated grouping and/or
8271 : * aggregation paths for the child.
8272 : */
8273 1795 : child_grouped_rel = make_grouping_rel(root, child_input_rel,
8274 : child_target,
8275 1795 : extra->target_parallel_safe,
8276 : child_extra.havingQual);
8277 :
8278 : /* Create grouping paths for this child relation. */
8279 1795 : create_ordinary_grouping_paths(root, child_input_rel,
8280 : child_grouped_rel,
8281 : agg_costs, gd, &child_extra,
8282 : &child_partially_grouped_rel);
8283 :
8284 1795 : if (child_partially_grouped_rel)
8285 : {
8286 : partially_grouped_live_children =
8287 1283 : lappend(partially_grouped_live_children,
8288 : child_partially_grouped_rel);
8289 : }
8290 : else
8291 512 : partial_grouping_valid = false;
8292 :
8293 1795 : if (patype == PARTITIONWISE_AGGREGATE_FULL)
8294 : {
8295 1082 : set_cheapest(child_grouped_rel);
8296 1082 : grouped_live_children = lappend(grouped_live_children,
8297 : child_grouped_rel);
8298 : }
8299 :
8300 1795 : pfree(appinfos);
8301 : }
8302 :
8303 : /*
8304 : * Try to create append paths for partially grouped children. For full
8305 : * partitionwise aggregation, we might have paths in the partial_pathlist
8306 : * if parallel aggregation is possible. For partial partitionwise
8307 : * aggregation, we may have paths in both pathlist and partial_pathlist.
8308 : *
8309 : * NB: We must have a partially grouped path for every child in order to
8310 : * generate a partially grouped path for this relation.
8311 : */
8312 685 : if (partially_grouped_rel && partial_grouping_valid)
8313 : {
8314 : Assert(partially_grouped_live_children != NIL);
8315 :
8316 501 : add_paths_to_append_rel(root, partially_grouped_rel,
8317 : partially_grouped_live_children);
8318 : }
8319 :
8320 : /* If possible, create append paths for fully grouped children. */
8321 685 : if (patype == PARTITIONWISE_AGGREGATE_FULL)
8322 : {
8323 : Assert(grouped_live_children != NIL);
8324 :
8325 404 : add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
8326 : }
8327 685 : }
8328 :
8329 : /*
8330 : * group_by_has_partkey
8331 : *
8332 : * Returns true if all the partition keys of the given relation are part of
8333 : * the GROUP BY clauses, including having matching collation, false otherwise.
8334 : */
8335 : static bool
8336 640 : group_by_has_partkey(RelOptInfo *input_rel,
8337 : List *targetList,
8338 : List *groupClause)
8339 : {
8340 640 : List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
8341 640 : int cnt = 0;
8342 : int partnatts;
8343 :
8344 : /* Input relation should be partitioned. */
8345 : Assert(input_rel->part_scheme);
8346 :
8347 : /* Rule out early, if there are no partition keys present. */
8348 640 : if (!input_rel->partexprs)
8349 0 : return false;
8350 :
8351 640 : partnatts = input_rel->part_scheme->partnatts;
8352 :
8353 1074 : for (cnt = 0; cnt < partnatts; cnt++)
8354 : {
8355 670 : List *partexprs = input_rel->partexprs[cnt];
8356 : ListCell *lc;
8357 670 : bool found = false;
8358 :
8359 1001 : foreach(lc, partexprs)
8360 : {
8361 : ListCell *lg;
8362 775 : Expr *partexpr = lfirst(lc);
8363 775 : Oid partcoll = input_rel->part_scheme->partcollation[cnt];
8364 :
8365 1206 : foreach(lg, groupexprs)
8366 : {
8367 875 : Expr *groupexpr = lfirst(lg);
8368 875 : Oid groupcoll = exprCollation((Node *) groupexpr);
8369 :
8370 : /*
8371 : * Note: we can assume there is at most one RelabelType node;
8372 : * eval_const_expressions() will have simplified if more than
8373 : * one.
8374 : */
8375 875 : if (IsA(groupexpr, RelabelType))
8376 20 : groupexpr = ((RelabelType *) groupexpr)->arg;
8377 :
8378 875 : if (equal(groupexpr, partexpr))
8379 : {
8380 : /*
8381 : * Reject a match if the grouping collation does not match
8382 : * the partitioning collation.
8383 : */
8384 444 : if (OidIsValid(partcoll) && OidIsValid(groupcoll) &&
8385 : partcoll != groupcoll)
8386 10 : return false;
8387 :
8388 434 : found = true;
8389 434 : break;
8390 : }
8391 : }
8392 :
8393 765 : if (found)
8394 434 : break;
8395 : }
8396 :
8397 : /*
8398 : * If none of the partition key expressions match with any of the
8399 : * GROUP BY expression, return false.
8400 : */
8401 660 : if (!found)
8402 226 : return false;
8403 : }
8404 :
8405 404 : return true;
8406 : }
8407 :
8408 : /*
8409 : * generate_setop_child_grouplist
8410 : * Build a SortGroupClause list defining the sort/grouping properties
8411 : * of the child of a set operation.
8412 : *
8413 : * This is similar to generate_setop_grouplist() but differs as the setop
8414 : * child query's targetlist entries may already have a tleSortGroupRef
8415 : * assigned for other purposes, such as GROUP BYs. Here we keep the
8416 : * SortGroupClause list in the same order as 'op' groupClauses and just adjust
8417 : * the tleSortGroupRef to reference the TargetEntry's 'ressortgroupref'. If
8418 : * any of the columns in the targetlist don't match to the setop's colTypes
8419 : * then we return an empty list. This may leave some TLEs with unreferenced
8420 : * ressortgroupref markings, but that's harmless.
8421 : */
8422 : static List *
8423 10416 : generate_setop_child_grouplist(SetOperationStmt *op, List *targetlist)
8424 : {
8425 10416 : List *grouplist = copyObject(op->groupClauses);
8426 : ListCell *lg;
8427 : ListCell *lt;
8428 : ListCell *ct;
8429 :
8430 10416 : lg = list_head(grouplist);
8431 10416 : ct = list_head(op->colTypes);
8432 40549 : foreach(lt, targetlist)
8433 : {
8434 30374 : TargetEntry *tle = (TargetEntry *) lfirst(lt);
8435 : SortGroupClause *sgc;
8436 : Oid coltype;
8437 :
8438 : /* resjunk columns could have sortgrouprefs. Leave these alone */
8439 30374 : if (tle->resjunk)
8440 0 : continue;
8441 :
8442 : /*
8443 : * We expect every non-resjunk target to have a SortGroupClause and
8444 : * colTypes.
8445 : */
8446 : Assert(lg != NULL);
8447 : Assert(ct != NULL);
8448 30374 : sgc = (SortGroupClause *) lfirst(lg);
8449 30374 : coltype = lfirst_oid(ct);
8450 :
8451 : /* reject if target type isn't the same as the setop target type */
8452 30374 : if (coltype != exprType((Node *) tle->expr))
8453 241 : return NIL;
8454 :
8455 30133 : lg = lnext(grouplist, lg);
8456 30133 : ct = lnext(op->colTypes, ct);
8457 :
8458 : /* assign a tleSortGroupRef, or reuse the existing one */
8459 30133 : sgc->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
8460 : }
8461 :
8462 : Assert(lg == NULL);
8463 : Assert(ct == NULL);
8464 :
8465 10175 : return grouplist;
8466 : }
8467 :
8468 : /*
8469 : * create_unique_paths
8470 : * Build a new RelOptInfo containing Paths that represent elimination of
8471 : * distinct rows from the input data. Distinct-ness is defined according to
8472 : * the needs of the semijoin represented by sjinfo. If it is not possible
8473 : * to identify how to make the data unique, NULL is returned.
8474 : *
8475 : * If used at all, this is likely to be called repeatedly on the same rel,
8476 : * so we cache the result.
8477 : */
8478 : RelOptInfo *
8479 6893 : create_unique_paths(PlannerInfo *root, RelOptInfo *rel, SpecialJoinInfo *sjinfo)
8480 : {
8481 : RelOptInfo *unique_rel;
8482 6893 : List *sortPathkeys = NIL;
8483 6893 : List *groupClause = NIL;
8484 : MemoryContext oldcontext;
8485 :
8486 : /* Caller made a mistake if SpecialJoinInfo is the wrong one */
8487 : Assert(sjinfo->jointype == JOIN_SEMI);
8488 : Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
8489 :
8490 : /* If result already cached, return it */
8491 6893 : if (rel->unique_rel)
8492 1196 : return rel->unique_rel;
8493 :
8494 : /* If it's not possible to unique-ify, return NULL */
8495 5697 : if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
8496 104 : return NULL;
8497 :
8498 : /*
8499 : * Punt if this is a child relation and we failed to build a unique-ified
8500 : * relation for its parent. This can happen if all the RHS columns were
8501 : * found to be equated to constants when unique-ifying the parent table,
8502 : * leaving no columns to unique-ify.
8503 : */
8504 5593 : if (IS_OTHER_REL(rel) && rel->top_parent->unique_rel == NULL)
8505 10 : return NULL;
8506 :
8507 : /*
8508 : * When called during GEQO join planning, we are in a short-lived memory
8509 : * context. We must make sure that the unique rel and any subsidiary data
8510 : * structures created for a baserel survive the GEQO cycle, else the
8511 : * baserel is trashed for future GEQO cycles. On the other hand, when we
8512 : * are creating those for a joinrel during GEQO, we don't want them to
8513 : * clutter the main planning context. Upshot is that the best solution is
8514 : * to explicitly allocate memory in the same context the given RelOptInfo
8515 : * is in.
8516 : */
8517 5583 : oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
8518 :
8519 5583 : unique_rel = makeNode(RelOptInfo);
8520 5583 : memcpy(unique_rel, rel, sizeof(RelOptInfo));
8521 :
8522 : /*
8523 : * clear path info
8524 : */
8525 5583 : unique_rel->pathlist = NIL;
8526 5583 : unique_rel->ppilist = NIL;
8527 5583 : unique_rel->partial_pathlist = NIL;
8528 5583 : unique_rel->cheapest_startup_path = NULL;
8529 5583 : unique_rel->cheapest_total_path = NULL;
8530 5583 : unique_rel->cheapest_parameterized_paths = NIL;
8531 :
8532 : /*
8533 : * Build the target list for the unique rel. We also build the pathkeys
8534 : * that represent the ordering requirements for the sort-based
8535 : * implementation, and the list of SortGroupClause nodes that represent
8536 : * the columns to be grouped on for the hash-based implementation.
8537 : *
8538 : * For a child rel, we can construct these fields from those of its
8539 : * parent.
8540 : */
8541 5583 : if (IS_OTHER_REL(rel))
8542 360 : {
8543 : PathTarget *child_unique_target;
8544 : PathTarget *parent_unique_target;
8545 :
8546 360 : parent_unique_target = rel->top_parent->unique_rel->reltarget;
8547 :
8548 360 : child_unique_target = copy_pathtarget(parent_unique_target);
8549 :
8550 : /* Translate the target expressions */
8551 360 : child_unique_target->exprs = (List *)
8552 360 : adjust_appendrel_attrs_multilevel(root,
8553 360 : (Node *) parent_unique_target->exprs,
8554 : rel,
8555 360 : rel->top_parent);
8556 :
8557 360 : unique_rel->reltarget = child_unique_target;
8558 :
8559 360 : sortPathkeys = rel->top_parent->unique_pathkeys;
8560 360 : groupClause = rel->top_parent->unique_groupclause;
8561 : }
8562 : else
8563 : {
8564 : List *newtlist;
8565 : int nextresno;
8566 5223 : List *sortList = NIL;
8567 : ListCell *lc1;
8568 : ListCell *lc2;
8569 :
8570 : /*
8571 : * The values we are supposed to unique-ify may be expressions in the
8572 : * variables of the input rel's targetlist. We have to add any such
8573 : * expressions to the unique rel's targetlist.
8574 : *
8575 : * To complicate matters, some of the values to be unique-ified may be
8576 : * known redundant by the EquivalenceClass machinery (e.g., because
8577 : * they have been equated to constants). There is no need to compare
8578 : * such values during unique-ification, and indeed we had better not
8579 : * try because the Vars involved may not have propagated as high as
8580 : * the semijoin's level. We use make_pathkeys_for_sortclauses to
8581 : * detect such cases, which is a tad inefficient but it doesn't seem
8582 : * worth building specialized infrastructure for this.
8583 : */
8584 5223 : newtlist = make_tlist_from_pathtarget(rel->reltarget);
8585 5223 : nextresno = list_length(newtlist) + 1;
8586 :
8587 10647 : forboth(lc1, sjinfo->semi_rhs_exprs, lc2, sjinfo->semi_operators)
8588 : {
8589 5424 : Expr *uniqexpr = lfirst(lc1);
8590 5424 : Oid in_oper = lfirst_oid(lc2);
8591 : Oid sortop;
8592 : TargetEntry *tle;
8593 5424 : bool made_tle = false;
8594 :
8595 5424 : tle = tlist_member(uniqexpr, newtlist);
8596 5424 : if (!tle)
8597 : {
8598 2722 : tle = makeTargetEntry(uniqexpr,
8599 : nextresno,
8600 : NULL,
8601 : false);
8602 2722 : newtlist = lappend(newtlist, tle);
8603 2722 : nextresno++;
8604 2722 : made_tle = true;
8605 : }
8606 :
8607 : /*
8608 : * Try to build an ORDER BY list to sort the input compatibly. We
8609 : * do this for each sortable clause even when the clauses are not
8610 : * all sortable, so that we can detect clauses that are redundant
8611 : * according to the pathkey machinery.
8612 : */
8613 5424 : sortop = get_ordering_op_for_equality_op(in_oper, false);
8614 5424 : if (OidIsValid(sortop))
8615 : {
8616 : Oid eqop;
8617 : SortGroupClause *sortcl;
8618 :
8619 : /*
8620 : * The Unique node will need equality operators. Normally
8621 : * these are the same as the IN clause operators, but if those
8622 : * are cross-type operators then the equality operators are
8623 : * the ones for the IN clause operators' RHS datatype.
8624 : */
8625 5424 : eqop = get_equality_op_for_ordering_op(sortop, NULL);
8626 5424 : if (!OidIsValid(eqop)) /* shouldn't happen */
8627 0 : elog(ERROR, "could not find equality operator for ordering operator %u",
8628 : sortop);
8629 :
8630 5424 : sortcl = makeNode(SortGroupClause);
8631 5424 : sortcl->tleSortGroupRef = assignSortGroupRef(tle, newtlist);
8632 5424 : sortcl->eqop = eqop;
8633 5424 : sortcl->sortop = sortop;
8634 5424 : sortcl->reverse_sort = false;
8635 5424 : sortcl->nulls_first = false;
8636 5424 : sortcl->hashable = false; /* no need to make this accurate */
8637 5424 : sortList = lappend(sortList, sortcl);
8638 :
8639 : /*
8640 : * At each step, convert the SortGroupClause list to pathkey
8641 : * form. If the just-added SortGroupClause is redundant, the
8642 : * result will be shorter than the SortGroupClause list.
8643 : */
8644 5424 : sortPathkeys = make_pathkeys_for_sortclauses(root, sortList,
8645 : newtlist);
8646 5424 : if (list_length(sortPathkeys) != list_length(sortList))
8647 : {
8648 : /* Drop the redundant SortGroupClause */
8649 1710 : sortList = list_delete_last(sortList);
8650 : Assert(list_length(sortPathkeys) == list_length(sortList));
8651 : /* Undo tlist addition, if we made one */
8652 1710 : if (made_tle)
8653 : {
8654 10 : newtlist = list_delete_last(newtlist);
8655 10 : nextresno--;
8656 : }
8657 : /* We need not consider this clause for hashing, either */
8658 1710 : continue;
8659 : }
8660 : }
8661 0 : else if (sjinfo->semi_can_btree) /* shouldn't happen */
8662 0 : elog(ERROR, "could not find ordering operator for equality operator %u",
8663 : in_oper);
8664 :
8665 3714 : if (sjinfo->semi_can_hash)
8666 : {
8667 : /* Create a GROUP BY list for the Agg node to use */
8668 : Oid eq_oper;
8669 : SortGroupClause *groupcl;
8670 :
8671 : /*
8672 : * Get the hashable equality operators for the Agg node to
8673 : * use. Normally these are the same as the IN clause
8674 : * operators, but if those are cross-type operators then the
8675 : * equality operators are the ones for the IN clause
8676 : * operators' RHS datatype.
8677 : */
8678 3714 : if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
8679 0 : elog(ERROR, "could not find compatible hash operator for operator %u",
8680 : in_oper);
8681 :
8682 3714 : groupcl = makeNode(SortGroupClause);
8683 3714 : groupcl->tleSortGroupRef = assignSortGroupRef(tle, newtlist);
8684 3714 : groupcl->eqop = eq_oper;
8685 3714 : groupcl->sortop = sortop;
8686 3714 : groupcl->reverse_sort = false;
8687 3714 : groupcl->nulls_first = false;
8688 3714 : groupcl->hashable = true;
8689 3714 : groupClause = lappend(groupClause, groupcl);
8690 : }
8691 : }
8692 :
8693 : /*
8694 : * Done building the sortPathkeys and groupClause. But the
8695 : * sortPathkeys are bogus if not all the clauses were sortable.
8696 : */
8697 5223 : if (!sjinfo->semi_can_btree)
8698 0 : sortPathkeys = NIL;
8699 :
8700 : /*
8701 : * It can happen that all the RHS columns are equated to constants.
8702 : * We'd have to do something special to unique-ify in that case, and
8703 : * it's such an unlikely-in-the-real-world case that it's not worth
8704 : * the effort. So just punt if we found no columns to unique-ify.
8705 : */
8706 5223 : if (sortPathkeys == NIL && groupClause == NIL)
8707 : {
8708 1625 : MemoryContextSwitchTo(oldcontext);
8709 1625 : return NULL;
8710 : }
8711 :
8712 : /* Convert the required targetlist back to PathTarget form */
8713 3598 : unique_rel->reltarget = create_pathtarget(root, newtlist);
8714 : }
8715 :
8716 : /* build unique paths based on input rel's pathlist */
8717 3958 : create_final_unique_paths(root, rel, sortPathkeys, groupClause,
8718 : sjinfo, unique_rel);
8719 :
8720 : /* build unique paths based on input rel's partial_pathlist */
8721 3958 : create_partial_unique_paths(root, rel, sortPathkeys, groupClause,
8722 : sjinfo, unique_rel);
8723 :
8724 : /* Now choose the best path(s) */
8725 3958 : set_cheapest(unique_rel);
8726 :
8727 : /*
8728 : * There shouldn't be any partial paths for the unique relation;
8729 : * otherwise, we won't be able to properly guarantee uniqueness.
8730 : */
8731 : Assert(unique_rel->partial_pathlist == NIL);
8732 :
8733 : /* Cache the result */
8734 3958 : rel->unique_rel = unique_rel;
8735 3958 : rel->unique_pathkeys = sortPathkeys;
8736 3958 : rel->unique_groupclause = groupClause;
8737 :
8738 3958 : MemoryContextSwitchTo(oldcontext);
8739 :
8740 3958 : return unique_rel;
8741 : }
8742 :
8743 : /*
8744 : * create_final_unique_paths
8745 : * Create unique paths in 'unique_rel' based on 'input_rel' pathlist
8746 : */
8747 : static void
8748 7080 : create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
8749 : List *sortPathkeys, List *groupClause,
8750 : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
8751 : {
8752 7080 : Path *cheapest_input_path = input_rel->cheapest_total_path;
8753 :
8754 : /* Estimate number of output rows */
8755 7080 : unique_rel->rows = estimate_num_groups(root,
8756 : sjinfo->semi_rhs_exprs,
8757 : cheapest_input_path->rows,
8758 : NULL,
8759 : NULL);
8760 :
8761 : /* Consider sort-based implementations, if possible. */
8762 7080 : if (sjinfo->semi_can_btree)
8763 : {
8764 : ListCell *lc;
8765 :
8766 : /*
8767 : * Use any available suitably-sorted path as input, and also consider
8768 : * sorting the cheapest-total path and incremental sort on any paths
8769 : * with presorted keys.
8770 : *
8771 : * To save planning time, we ignore parameterized input paths unless
8772 : * they are the cheapest-total path.
8773 : */
8774 15436 : foreach(lc, input_rel->pathlist)
8775 : {
8776 8356 : Path *input_path = (Path *) lfirst(lc);
8777 : Path *path;
8778 : bool is_sorted;
8779 : int presorted_keys;
8780 :
8781 : /*
8782 : * Ignore parameterized paths that are not the cheapest-total
8783 : * path.
8784 : */
8785 8356 : if (input_path->param_info &&
8786 : input_path != cheapest_input_path)
8787 739 : continue;
8788 :
8789 7653 : is_sorted = pathkeys_count_contained_in(sortPathkeys,
8790 : input_path->pathkeys,
8791 : &presorted_keys);
8792 :
8793 : /*
8794 : * Ignore paths that are not suitably or partially sorted, unless
8795 : * they are the cheapest total path (no need to deal with paths
8796 : * which have presorted keys when incremental sort is disabled).
8797 : */
8798 7653 : if (!is_sorted && input_path != cheapest_input_path &&
8799 76 : (presorted_keys == 0 || !enable_incremental_sort))
8800 36 : continue;
8801 :
8802 : /*
8803 : * Make a separate ProjectionPath in case we need a Result node.
8804 : */
8805 7617 : path = (Path *) create_projection_path(root,
8806 : unique_rel,
8807 : input_path,
8808 7617 : unique_rel->reltarget);
8809 :
8810 7617 : if (!is_sorted)
8811 : {
8812 : /*
8813 : * We've no need to consider both a sort and incremental sort.
8814 : * We'll just do a sort if there are no presorted keys and an
8815 : * incremental sort when there are presorted keys.
8816 : */
8817 3941 : if (presorted_keys == 0 || !enable_incremental_sort)
8818 3901 : path = (Path *) create_sort_path(root,
8819 : unique_rel,
8820 : path,
8821 : sortPathkeys,
8822 : -1.0);
8823 : else
8824 40 : path = (Path *) create_incremental_sort_path(root,
8825 : unique_rel,
8826 : path,
8827 : sortPathkeys,
8828 : presorted_keys,
8829 : -1.0);
8830 : }
8831 :
8832 7617 : path = (Path *) create_unique_path(root, unique_rel, path,
8833 : list_length(sortPathkeys),
8834 : unique_rel->rows);
8835 :
8836 7617 : add_path(unique_rel, path);
8837 : }
8838 : }
8839 :
8840 : /* Consider hash-based implementation, if possible. */
8841 7080 : if (sjinfo->semi_can_hash)
8842 : {
8843 : Path *path;
8844 :
8845 : /*
8846 : * Make a separate ProjectionPath in case we need a Result node.
8847 : */
8848 7080 : path = (Path *) create_projection_path(root,
8849 : unique_rel,
8850 : cheapest_input_path,
8851 7080 : unique_rel->reltarget);
8852 :
8853 7080 : path = (Path *) create_agg_path(root,
8854 : unique_rel,
8855 : path,
8856 : cheapest_input_path->pathtarget,
8857 : AGG_HASHED,
8858 : AGGSPLIT_SIMPLE,
8859 : groupClause,
8860 : NIL,
8861 : NULL,
8862 : unique_rel->rows);
8863 :
8864 7080 : add_path(unique_rel, path);
8865 : }
8866 7080 : }
8867 :
8868 : /*
8869 : * create_partial_unique_paths
8870 : * Create unique paths in 'unique_rel' based on 'input_rel' partial_pathlist
8871 : */
8872 : static void
8873 3958 : create_partial_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
8874 : List *sortPathkeys, List *groupClause,
8875 : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
8876 : {
8877 : RelOptInfo *partial_unique_rel;
8878 : Path *cheapest_partial_path;
8879 :
8880 : /* nothing to do when there are no partial paths in the input rel */
8881 3958 : if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
8882 836 : return;
8883 :
8884 : /*
8885 : * nothing to do if there's anything in the targetlist that's
8886 : * parallel-restricted.
8887 : */
8888 3122 : if (!is_parallel_safe(root, (Node *) unique_rel->reltarget->exprs))
8889 0 : return;
8890 :
8891 3122 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
8892 :
8893 3122 : partial_unique_rel = makeNode(RelOptInfo);
8894 3122 : memcpy(partial_unique_rel, input_rel, sizeof(RelOptInfo));
8895 :
8896 : /*
8897 : * clear path info
8898 : */
8899 3122 : partial_unique_rel->pathlist = NIL;
8900 3122 : partial_unique_rel->ppilist = NIL;
8901 3122 : partial_unique_rel->partial_pathlist = NIL;
8902 3122 : partial_unique_rel->cheapest_startup_path = NULL;
8903 3122 : partial_unique_rel->cheapest_total_path = NULL;
8904 3122 : partial_unique_rel->cheapest_parameterized_paths = NIL;
8905 :
8906 : /* Estimate number of output rows */
8907 3122 : partial_unique_rel->rows = estimate_num_groups(root,
8908 : sjinfo->semi_rhs_exprs,
8909 : cheapest_partial_path->rows,
8910 : NULL,
8911 : NULL);
8912 3122 : partial_unique_rel->reltarget = unique_rel->reltarget;
8913 :
8914 : /* Consider sort-based implementations, if possible. */
8915 3122 : if (sjinfo->semi_can_btree)
8916 : {
8917 : ListCell *lc;
8918 :
8919 : /*
8920 : * Use any available suitably-sorted path as input, and also consider
8921 : * sorting the cheapest partial path and incremental sort on any paths
8922 : * with presorted keys.
8923 : */
8924 6498 : foreach(lc, input_rel->partial_pathlist)
8925 : {
8926 3376 : Path *input_path = (Path *) lfirst(lc);
8927 : Path *path;
8928 : bool is_sorted;
8929 : int presorted_keys;
8930 :
8931 3376 : is_sorted = pathkeys_count_contained_in(sortPathkeys,
8932 : input_path->pathkeys,
8933 : &presorted_keys);
8934 :
8935 : /*
8936 : * Ignore paths that are not suitably or partially sorted, unless
8937 : * they are the cheapest partial path (no need to deal with paths
8938 : * which have presorted keys when incremental sort is disabled).
8939 : */
8940 3376 : if (!is_sorted && input_path != cheapest_partial_path &&
8941 0 : (presorted_keys == 0 || !enable_incremental_sort))
8942 0 : continue;
8943 :
8944 : /*
8945 : * Make a separate ProjectionPath in case we need a Result node.
8946 : */
8947 3376 : path = (Path *) create_projection_path(root,
8948 : partial_unique_rel,
8949 : input_path,
8950 3376 : partial_unique_rel->reltarget);
8951 :
8952 3376 : if (!is_sorted)
8953 : {
8954 : /*
8955 : * We've no need to consider both a sort and incremental sort.
8956 : * We'll just do a sort if there are no presorted keys and an
8957 : * incremental sort when there are presorted keys.
8958 : */
8959 3082 : if (presorted_keys == 0 || !enable_incremental_sort)
8960 3082 : path = (Path *) create_sort_path(root,
8961 : partial_unique_rel,
8962 : path,
8963 : sortPathkeys,
8964 : -1.0);
8965 : else
8966 0 : path = (Path *) create_incremental_sort_path(root,
8967 : partial_unique_rel,
8968 : path,
8969 : sortPathkeys,
8970 : presorted_keys,
8971 : -1.0);
8972 : }
8973 :
8974 3376 : path = (Path *) create_unique_path(root, partial_unique_rel, path,
8975 : list_length(sortPathkeys),
8976 : partial_unique_rel->rows);
8977 :
8978 3376 : add_partial_path(partial_unique_rel, path);
8979 : }
8980 : }
8981 :
8982 : /* Consider hash-based implementation, if possible. */
8983 3122 : if (sjinfo->semi_can_hash)
8984 : {
8985 : Path *path;
8986 :
8987 : /*
8988 : * Make a separate ProjectionPath in case we need a Result node.
8989 : */
8990 3122 : path = (Path *) create_projection_path(root,
8991 : partial_unique_rel,
8992 : cheapest_partial_path,
8993 3122 : partial_unique_rel->reltarget);
8994 :
8995 3122 : path = (Path *) create_agg_path(root,
8996 : partial_unique_rel,
8997 : path,
8998 : cheapest_partial_path->pathtarget,
8999 : AGG_HASHED,
9000 : AGGSPLIT_SIMPLE,
9001 : groupClause,
9002 : NIL,
9003 : NULL,
9004 : partial_unique_rel->rows);
9005 :
9006 3122 : add_partial_path(partial_unique_rel, path);
9007 : }
9008 :
9009 3122 : if (partial_unique_rel->partial_pathlist != NIL)
9010 : {
9011 3122 : generate_useful_gather_paths(root, partial_unique_rel, true);
9012 3122 : set_cheapest(partial_unique_rel);
9013 :
9014 : /*
9015 : * Finally, create paths to unique-ify the final result. This step is
9016 : * needed to remove any duplicates due to combining rows from parallel
9017 : * workers.
9018 : */
9019 3122 : create_final_unique_paths(root, partial_unique_rel,
9020 : sortPathkeys, groupClause,
9021 : sjinfo, unique_rel);
9022 : }
9023 : }
9024 :
9025 : /*
9026 : * Choose a unique name for some subroot.
9027 : *
9028 : * Modifies glob->subplanNames to track names already used.
9029 : */
9030 : char *
9031 64725 : choose_plan_name(PlannerGlobal *glob, const char *name, bool always_number)
9032 : {
9033 : unsigned n;
9034 :
9035 : /*
9036 : * If a numeric suffix is not required, then search the list of
9037 : * previously-assigned names for a match. If none is found, then we can
9038 : * use the provided name without modification.
9039 : */
9040 64725 : if (!always_number)
9041 : {
9042 19119 : bool found = false;
9043 :
9044 46124 : foreach_ptr(char, subplan_name, glob->subplanNames)
9045 : {
9046 12236 : if (strcmp(subplan_name, name) == 0)
9047 : {
9048 4350 : found = true;
9049 4350 : break;
9050 : }
9051 : }
9052 :
9053 19119 : if (!found)
9054 : {
9055 : /* pstrdup here is just to avoid cast-away-const */
9056 14769 : char *chosen_name = pstrdup(name);
9057 :
9058 14769 : glob->subplanNames = lappend(glob->subplanNames, chosen_name);
9059 14769 : return chosen_name;
9060 : }
9061 : }
9062 :
9063 : /*
9064 : * If a numeric suffix is required or if the un-suffixed name is already
9065 : * in use, then loop until we find a positive integer that produces a
9066 : * novel name.
9067 : */
9068 49956 : for (n = 1; true; ++n)
9069 43224 : {
9070 93180 : char *proposed_name = psprintf("%s_%u", name, n);
9071 93180 : bool found = false;
9072 :
9073 347903 : foreach_ptr(char, subplan_name, glob->subplanNames)
9074 : {
9075 204767 : if (strcmp(subplan_name, proposed_name) == 0)
9076 : {
9077 43224 : found = true;
9078 43224 : break;
9079 : }
9080 : }
9081 :
9082 93180 : if (!found)
9083 : {
9084 49956 : glob->subplanNames = lappend(glob->subplanNames, proposed_name);
9085 49956 : return proposed_name;
9086 : }
9087 :
9088 43224 : pfree(proposed_name);
9089 : }
9090 : }
|