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