PostgreSQL Source Code  git master
planner.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  * The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2022, 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/htup_details.h"
23 #include "access/parallel.h"
24 #include "access/sysattr.h"
25 #include "access/table.h"
26 #include "access/xact.h"
27 #include "catalog/pg_constraint.h"
28 #include "catalog/pg_inherits.h"
29 #include "catalog/pg_proc.h"
30 #include "catalog/pg_type.h"
31 #include "executor/executor.h"
32 #include "executor/nodeAgg.h"
33 #include "foreign/fdwapi.h"
34 #include "jit/jit.h"
35 #include "lib/bipartite_match.h"
36 #include "lib/knapsack.h"
37 #include "miscadmin.h"
38 #include "nodes/makefuncs.h"
39 #include "nodes/nodeFuncs.h"
40 #ifdef OPTIMIZER_DEBUG
41 #include "nodes/print.h"
42 #endif
43 #include "optimizer/appendinfo.h"
44 #include "optimizer/clauses.h"
45 #include "optimizer/cost.h"
46 #include "optimizer/inherit.h"
47 #include "optimizer/optimizer.h"
48 #include "optimizer/paramassign.h"
49 #include "optimizer/pathnode.h"
50 #include "optimizer/paths.h"
51 #include "optimizer/plancat.h"
52 #include "optimizer/planmain.h"
53 #include "optimizer/planner.h"
54 #include "optimizer/prep.h"
55 #include "optimizer/subselect.h"
56 #include "optimizer/tlist.h"
57 #include "parser/analyze.h"
58 #include "parser/parse_agg.h"
59 #include "parser/parsetree.h"
60 #include "partitioning/partdesc.h"
61 #include "rewrite/rewriteManip.h"
62 #include "storage/dsm_impl.h"
63 #include "utils/lsyscache.h"
64 #include "utils/rel.h"
65 #include "utils/selfuncs.h"
66 #include "utils/syscache.h"
67 
68 /* GUC parameters */
72 
73 /* Hook for plugins to get control in planner() */
75 
76 /* Hook for plugins to get control when grouping_planner() plans upper rels */
78 
79 
80 /* Expression kind codes for preprocess_expression */
81 #define EXPRKIND_QUAL 0
82 #define EXPRKIND_TARGET 1
83 #define EXPRKIND_RTFUNC 2
84 #define EXPRKIND_RTFUNC_LATERAL 3
85 #define EXPRKIND_VALUES 4
86 #define EXPRKIND_VALUES_LATERAL 5
87 #define EXPRKIND_LIMIT 6
88 #define EXPRKIND_APPINFO 7
89 #define EXPRKIND_PHV 8
90 #define EXPRKIND_TABLESAMPLE 9
91 #define EXPRKIND_ARBITER_ELEM 10
92 #define EXPRKIND_TABLEFUNC 11
93 #define EXPRKIND_TABLEFUNC_LATERAL 12
94 
95 /* Passthrough data for standard_qp_callback */
96 typedef struct
97 {
98  List *activeWindows; /* active windows, if any */
99  List *groupClause; /* overrides parse->groupClause */
101 
102 /*
103  * Data specific to grouping sets
104  */
105 
106 typedef struct
107 {
117 
118 /*
119  * Temporary structure for use during WindowClause reordering in order to be
120  * able to sort WindowClauses on partitioning/ordering prefix.
121  */
122 typedef struct
123 {
125  List *uniqueOrder; /* A List of unique ordering/partitioning
126  * clauses per Window */
128 
129 /* Local functions */
130 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
131 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
132 static void grouping_planner(PlannerInfo *root, double tuple_fraction);
134 static List *remap_to_groupclause_idx(List *groupClause, List *gsets,
135  int *tleref_to_colnum_map);
136 static void preprocess_rowmarks(PlannerInfo *root);
137 static double preprocess_limit(PlannerInfo *root,
138  double tuple_fraction,
139  int64 *offset_est, int64 *count_est);
141 static List *preprocess_groupclause(PlannerInfo *root, List *force);
142 static List *extract_rollup_sets(List *groupingSets);
143 static List *reorder_grouping_sets(List *groupingSets, List *sortclause);
144 static void standard_qp_callback(PlannerInfo *root, void *extra);
145 static double get_number_of_groups(PlannerInfo *root,
146  double path_rows,
147  grouping_sets_data *gd,
148  List *target_list);
150  RelOptInfo *input_rel,
151  PathTarget *target,
152  bool target_parallel_safe,
153  grouping_sets_data *gd);
154 static bool is_degenerate_grouping(PlannerInfo *root);
156  RelOptInfo *input_rel,
157  RelOptInfo *grouped_rel);
158 static RelOptInfo *make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
159  PathTarget *target, bool target_parallel_safe,
160  Node *havingQual);
162  RelOptInfo *input_rel,
163  RelOptInfo *grouped_rel,
164  const AggClauseCosts *agg_costs,
165  grouping_sets_data *gd,
166  GroupPathExtraData *extra,
167  RelOptInfo **partially_grouped_rel_p);
168 static void consider_groupingsets_paths(PlannerInfo *root,
169  RelOptInfo *grouped_rel,
170  Path *path,
171  bool is_sorted,
172  bool can_hash,
173  grouping_sets_data *gd,
174  const AggClauseCosts *agg_costs,
175  double dNumGroups);
177  RelOptInfo *input_rel,
178  PathTarget *input_target,
179  PathTarget *output_target,
180  bool output_target_parallel_safe,
181  WindowFuncLists *wflists,
182  List *activeWindows);
183 static void create_one_window_path(PlannerInfo *root,
184  RelOptInfo *window_rel,
185  Path *path,
186  PathTarget *input_target,
187  PathTarget *output_target,
188  WindowFuncLists *wflists,
189  List *activeWindows);
191  RelOptInfo *input_rel);
193  RelOptInfo *input_rel,
194  RelOptInfo *final_distinct_rel);
196  RelOptInfo *input_rel,
197  RelOptInfo *distinct_rel);
199  RelOptInfo *input_rel,
200  PathTarget *target,
201  bool target_parallel_safe,
202  double limit_tuples);
204  PathTarget *final_target);
206  PathTarget *grouping_target,
207  Node *havingQual);
208 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
209 static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
211  PathTarget *final_target,
212  List *activeWindows);
214  List *tlist);
216  PathTarget *final_target,
217  bool *have_postponed_srfs);
218 static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
219  List *targets, List *targets_contain_srfs);
220 static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
221  RelOptInfo *grouped_rel,
222  RelOptInfo *partially_grouped_rel,
223  const AggClauseCosts *agg_costs,
224  grouping_sets_data *gd,
225  double dNumGroups,
226  GroupPathExtraData *extra);
228  RelOptInfo *grouped_rel,
229  RelOptInfo *input_rel,
230  grouping_sets_data *gd,
231  GroupPathExtraData *extra,
232  bool force_rel_creation);
233 static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel);
234 static bool can_partial_agg(PlannerInfo *root);
236  RelOptInfo *rel,
237  List *scanjoin_targets,
238  List *scanjoin_targets_contain_srfs,
239  bool scanjoin_target_parallel_safe,
240  bool tlist_same_exprs);
242  RelOptInfo *input_rel,
243  RelOptInfo *grouped_rel,
244  RelOptInfo *partially_grouped_rel,
245  const AggClauseCosts *agg_costs,
246  grouping_sets_data *gd,
248  GroupPathExtraData *extra);
249 static bool group_by_has_partkey(RelOptInfo *input_rel,
250  List *targetList,
251  List *groupClause);
252 static int common_prefix_cmp(const void *a, const void *b);
253 
254 
255 /*****************************************************************************
256  *
257  * Query optimizer entry point
258  *
259  * To support loadable plugins that monitor or modify planner behavior,
260  * we provide a hook variable that lets a plugin get control before and
261  * after the standard planning process. The plugin would normally call
262  * standard_planner().
263  *
264  * Note to plugin authors: standard_planner() scribbles on its Query input,
265  * so you'd better copy that data structure if you want to plan more than once.
266  *
267  *****************************************************************************/
268 PlannedStmt *
269 planner(Query *parse, const char *query_string, int cursorOptions,
270  ParamListInfo boundParams)
271 {
272  PlannedStmt *result;
273 
274  if (planner_hook)
275  result = (*planner_hook) (parse, query_string, cursorOptions, boundParams);
276  else
277  result = standard_planner(parse, query_string, cursorOptions, boundParams);
278  return result;
279 }
280 
281 PlannedStmt *
282 standard_planner(Query *parse, const char *query_string, int cursorOptions,
283  ParamListInfo boundParams)
284 {
285  PlannedStmt *result;
286  PlannerGlobal *glob;
287  double tuple_fraction;
288  PlannerInfo *root;
289  RelOptInfo *final_rel;
290  Path *best_path;
291  Plan *top_plan;
292  ListCell *lp,
293  *lr;
294 
295  /*
296  * Set up global state for this planner invocation. This data is needed
297  * across all levels of sub-Query that might exist in the given command,
298  * so we keep it in a separate struct that's linked to by each per-Query
299  * PlannerInfo.
300  */
301  glob = makeNode(PlannerGlobal);
302 
303  glob->boundParams = boundParams;
304  glob->subplans = NIL;
305  glob->subroots = NIL;
306  glob->rewindPlanIDs = NULL;
307  glob->finalrtable = NIL;
308  glob->finalrowmarks = NIL;
309  glob->resultRelations = NIL;
310  glob->appendRelations = NIL;
311  glob->relationOids = NIL;
312  glob->invalItems = NIL;
313  glob->paramExecTypes = NIL;
314  glob->lastPHId = 0;
315  glob->lastRowMarkId = 0;
316  glob->lastPlanNodeId = 0;
317  glob->transientPlan = false;
318  glob->dependsOnRole = false;
319 
320  /*
321  * Assess whether it's feasible to use parallel mode for this query. We
322  * can't do this in a standalone backend, or if the command will try to
323  * modify any data, or if this is a cursor operation, or if GUCs are set
324  * to values that don't permit parallelism, or if parallel-unsafe
325  * functions are present in the query tree.
326  *
327  * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
328  * MATERIALIZED VIEW to use parallel plans, but as of now, only the leader
329  * backend writes into a completely new table. In the future, we can
330  * extend it to allow workers to write into the table. However, to allow
331  * parallel updates and deletes, we have to solve other problems,
332  * especially around combo CIDs.)
333  *
334  * For now, we don't try to use parallel mode if we're running inside a
335  * parallel worker. We might eventually be able to relax this
336  * restriction, but for now it seems best not to have parallel workers
337  * trying to create their own parallel workers.
338  */
339  if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
341  parse->commandType == CMD_SELECT &&
342  !parse->hasModifyingCTE &&
344  !IsParallelWorker())
345  {
346  /* all the cheap tests pass, so scan the query tree */
348  glob->parallelModeOK = (glob->maxParallelHazard != PROPARALLEL_UNSAFE);
349  }
350  else
351  {
352  /* skip the query tree scan, just assume it's unsafe */
353  glob->maxParallelHazard = PROPARALLEL_UNSAFE;
354  glob->parallelModeOK = false;
355  }
356 
357  /*
358  * glob->parallelModeNeeded is normally set to false here and changed to
359  * true during plan creation if a Gather or Gather Merge plan is actually
360  * created (cf. create_gather_plan, create_gather_merge_plan).
361  *
362  * However, if force_parallel_mode = on or force_parallel_mode = regress,
363  * then we impose parallel mode whenever it's safe to do so, even if the
364  * final plan doesn't use parallelism. It's not safe to do so if the
365  * query contains anything parallel-unsafe; parallelModeOK will be false
366  * in that case. Note that parallelModeOK can't change after this point.
367  * Otherwise, everything in the query is either parallel-safe or
368  * parallel-restricted, and in either case it should be OK to impose
369  * parallel-mode restrictions. If that ends up breaking something, then
370  * either some function the user included in the query is incorrectly
371  * labeled as parallel-safe or parallel-restricted when in reality it's
372  * parallel-unsafe, or else the query planner itself has a bug.
373  */
374  glob->parallelModeNeeded = glob->parallelModeOK &&
376 
377  /* Determine what fraction of the plan is likely to be scanned */
378  if (cursorOptions & CURSOR_OPT_FAST_PLAN)
379  {
380  /*
381  * We have no real idea how many tuples the user will ultimately FETCH
382  * from a cursor, but it is often the case that he doesn't want 'em
383  * all, or would prefer a fast-start plan anyway so that he can
384  * process some of the tuples sooner. Use a GUC parameter to decide
385  * what fraction to optimize for.
386  */
387  tuple_fraction = cursor_tuple_fraction;
388 
389  /*
390  * We document cursor_tuple_fraction as simply being a fraction, which
391  * means the edge cases 0 and 1 have to be treated specially here. We
392  * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
393  */
394  if (tuple_fraction >= 1.0)
395  tuple_fraction = 0.0;
396  else if (tuple_fraction <= 0.0)
397  tuple_fraction = 1e-10;
398  }
399  else
400  {
401  /* Default assumption is we need all the tuples */
402  tuple_fraction = 0.0;
403  }
404 
405  /* primary planning entry point (may recurse for subqueries) */
406  root = subquery_planner(glob, parse, NULL,
407  false, tuple_fraction);
408 
409  /* Select best Path and turn it into a Plan */
410  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
411  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
412 
413  top_plan = create_plan(root, best_path);
414 
415  /*
416  * If creating a plan for a scrollable cursor, make sure it can run
417  * backwards on demand. Add a Material node at the top at need.
418  */
419  if (cursorOptions & CURSOR_OPT_SCROLL)
420  {
421  if (!ExecSupportsBackwardScan(top_plan))
422  top_plan = materialize_finished_plan(top_plan);
423  }
424 
425  /*
426  * Optionally add a Gather node for testing purposes, provided this is
427  * actually a safe thing to do.
428  */
430  {
431  Gather *gather = makeNode(Gather);
432 
433  /*
434  * If there are any initPlans attached to the formerly-top plan node,
435  * move them up to the Gather node; same as we do for Material node in
436  * materialize_finished_plan.
437  */
438  gather->plan.initPlan = top_plan->initPlan;
439  top_plan->initPlan = NIL;
440 
441  gather->plan.targetlist = top_plan->targetlist;
442  gather->plan.qual = NIL;
443  gather->plan.lefttree = top_plan;
444  gather->plan.righttree = NULL;
445  gather->num_workers = 1;
446  gather->single_copy = true;
448 
449  /*
450  * Since this Gather has no parallel-aware descendants to signal to,
451  * we don't need a rescan Param.
452  */
453  gather->rescan_param = -1;
454 
455  /*
456  * Ideally we'd use cost_gather here, but setting up dummy path data
457  * to satisfy it doesn't seem much cleaner than knowing what it does.
458  */
459  gather->plan.startup_cost = top_plan->startup_cost +
461  gather->plan.total_cost = top_plan->total_cost +
463  gather->plan.plan_rows = top_plan->plan_rows;
464  gather->plan.plan_width = top_plan->plan_width;
465  gather->plan.parallel_aware = false;
466  gather->plan.parallel_safe = false;
467 
468  /* use parallel mode for parallel plans. */
469  root->glob->parallelModeNeeded = true;
470 
471  top_plan = &gather->plan;
472  }
473 
474  /*
475  * If any Params were generated, run through the plan tree and compute
476  * each plan node's extParam/allParam sets. Ideally we'd merge this into
477  * set_plan_references' tree traversal, but for now it has to be separate
478  * because we need to visit subplans before not after main plan.
479  */
480  if (glob->paramExecTypes != NIL)
481  {
482  Assert(list_length(glob->subplans) == list_length(glob->subroots));
483  forboth(lp, glob->subplans, lr, glob->subroots)
484  {
485  Plan *subplan = (Plan *) lfirst(lp);
486  PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
487 
488  SS_finalize_plan(subroot, subplan);
489  }
490  SS_finalize_plan(root, top_plan);
491  }
492 
493  /* final cleanup of the plan */
494  Assert(glob->finalrtable == NIL);
495  Assert(glob->finalrowmarks == NIL);
496  Assert(glob->resultRelations == NIL);
497  Assert(glob->appendRelations == NIL);
498  top_plan = set_plan_references(root, top_plan);
499  /* ... and the subplans (both regular subplans and initplans) */
500  Assert(list_length(glob->subplans) == list_length(glob->subroots));
501  forboth(lp, glob->subplans, lr, glob->subroots)
502  {
503  Plan *subplan = (Plan *) lfirst(lp);
504  PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
505 
506  lfirst(lp) = set_plan_references(subroot, subplan);
507  }
508 
509  /* build the PlannedStmt result */
510  result = makeNode(PlannedStmt);
511 
512  result->commandType = parse->commandType;
513  result->queryId = parse->queryId;
514  result->hasReturning = (parse->returningList != NIL);
515  result->hasModifyingCTE = parse->hasModifyingCTE;
516  result->canSetTag = parse->canSetTag;
517  result->transientPlan = glob->transientPlan;
518  result->dependsOnRole = glob->dependsOnRole;
519  result->parallelModeNeeded = glob->parallelModeNeeded;
520  result->planTree = top_plan;
521  result->rtable = glob->finalrtable;
522  result->resultRelations = glob->resultRelations;
523  result->appendRelations = glob->appendRelations;
524  result->subplans = glob->subplans;
525  result->rewindPlanIDs = glob->rewindPlanIDs;
526  result->rowMarks = glob->finalrowmarks;
527  result->relationOids = glob->relationOids;
528  result->invalItems = glob->invalItems;
529  result->paramExecTypes = glob->paramExecTypes;
530  /* utilityStmt should be null, but we might as well copy it */
531  result->utilityStmt = parse->utilityStmt;
532  result->stmt_location = parse->stmt_location;
533  result->stmt_len = parse->stmt_len;
534 
535  result->jitFlags = PGJIT_NONE;
536  if (jit_enabled && jit_above_cost >= 0 &&
537  top_plan->total_cost > jit_above_cost)
538  {
539  result->jitFlags |= PGJIT_PERFORM;
540 
541  /*
542  * Decide how much effort should be put into generating better code.
543  */
544  if (jit_optimize_above_cost >= 0 &&
546  result->jitFlags |= PGJIT_OPT3;
547  if (jit_inline_above_cost >= 0 &&
548  top_plan->total_cost > jit_inline_above_cost)
549  result->jitFlags |= PGJIT_INLINE;
550 
551  /*
552  * Decide which operations should be JITed.
553  */
554  if (jit_expressions)
555  result->jitFlags |= PGJIT_EXPR;
557  result->jitFlags |= PGJIT_DEFORM;
558  }
559 
560  if (glob->partition_directory != NULL)
562 
563  return result;
564 }
565 
566 
567 /*--------------------
568  * subquery_planner
569  * Invokes the planner on a subquery. We recurse to here for each
570  * sub-SELECT found in the query tree.
571  *
572  * glob is the global state for the current planner run.
573  * parse is the querytree produced by the parser & rewriter.
574  * parent_root is the immediate parent Query's info (NULL at the top level).
575  * hasRecursion is true if this is a recursive WITH query.
576  * tuple_fraction is the fraction of tuples we expect will be retrieved.
577  * tuple_fraction is interpreted as explained for grouping_planner, below.
578  *
579  * Basically, this routine does the stuff that should only be done once
580  * per Query object. It then calls grouping_planner. At one time,
581  * grouping_planner could be invoked recursively on the same Query object;
582  * that's not currently true, but we keep the separation between the two
583  * routines anyway, in case we need it again someday.
584  *
585  * subquery_planner will be called recursively to handle sub-Query nodes
586  * found within the query's expressions and rangetable.
587  *
588  * Returns the PlannerInfo struct ("root") that contains all data generated
589  * while planning the subquery. In particular, the Path(s) attached to
590  * the (UPPERREL_FINAL, NULL) upperrel represent our conclusions about the
591  * cheapest way(s) to implement the query. The top level will select the
592  * best Path and pass it through createplan.c to produce a finished Plan.
593  *--------------------
594  */
595 PlannerInfo *
597  PlannerInfo *parent_root,
598  bool hasRecursion, double tuple_fraction)
599 {
600  PlannerInfo *root;
601  List *newWithCheckOptions;
602  List *newHaving;
603  bool hasOuterJoins;
604  bool hasResultRTEs;
605  RelOptInfo *final_rel;
606  ListCell *l;
607 
608  /* Create a PlannerInfo data structure for this subquery */
609  root = makeNode(PlannerInfo);
610  root->parse = parse;
611  root->glob = glob;
612  root->query_level = parent_root ? parent_root->query_level + 1 : 1;
613  root->parent_root = parent_root;
614  root->plan_params = NIL;
615  root->outer_params = NULL;
617  root->init_plans = NIL;
618  root->cte_plan_ids = NIL;
619  root->multiexpr_params = NIL;
620  root->eq_classes = NIL;
621  root->ec_merging_done = false;
622  root->all_result_relids =
623  parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL;
624  root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */
625  root->append_rel_list = NIL;
626  root->row_identity_vars = NIL;
627  root->rowMarks = NIL;
628  memset(root->upper_rels, 0, sizeof(root->upper_rels));
629  memset(root->upper_targets, 0, sizeof(root->upper_targets));
630  root->processed_tlist = NIL;
631  root->update_colnos = NIL;
632  root->grouping_map = NULL;
633  root->minmax_aggs = NIL;
634  root->qual_security_level = 0;
635  root->hasPseudoConstantQuals = false;
636  root->hasAlternativeSubPlans = false;
637  root->hasRecursion = hasRecursion;
638  if (hasRecursion)
640  else
641  root->wt_param_id = -1;
642  root->non_recursive_path = NULL;
643  root->partColsUpdated = false;
644 
645  /*
646  * If there is a WITH list, process each WITH query and either convert it
647  * to RTE_SUBQUERY RTE(s) or build an initplan SubPlan structure for it.
648  */
649  if (parse->cteList)
650  SS_process_ctes(root);
651 
652  /*
653  * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
654  * that we don't need so many special cases to deal with that situation.
655  */
657 
658  /*
659  * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
660  * to transform them into joins. Note that this step does not descend
661  * into subqueries; if we pull up any subqueries below, their SubLinks are
662  * processed just before pulling them up.
663  */
664  if (parse->hasSubLinks)
665  pull_up_sublinks(root);
666 
667  /*
668  * Scan the rangetable for function RTEs, do const-simplification on them,
669  * and then inline them if possible (producing subqueries that might get
670  * pulled up next). Recursion issues here are handled in the same way as
671  * for SubLinks.
672  */
674 
675  /*
676  * Check to see if any subqueries in the jointree can be merged into this
677  * query.
678  */
679  pull_up_subqueries(root);
680 
681  /*
682  * If this is a simple UNION ALL query, flatten it into an appendrel. We
683  * do this now because it requires applying pull_up_subqueries to the leaf
684  * queries of the UNION ALL, which weren't touched above because they
685  * weren't referenced by the jointree (they will be after we do this).
686  */
687  if (parse->setOperations)
689 
690  /*
691  * Survey the rangetable to see what kinds of entries are present. We can
692  * skip some later processing if relevant SQL features are not used; for
693  * example if there are no JOIN RTEs we can avoid the expense of doing
694  * flatten_join_alias_vars(). This must be done after we have finished
695  * adding rangetable entries, of course. (Note: actually, processing of
696  * inherited or partitioned rels can cause RTEs for their child tables to
697  * get added later; but those must all be RTE_RELATION entries, so they
698  * don't invalidate the conclusions drawn here.)
699  */
700  root->hasJoinRTEs = false;
701  root->hasLateralRTEs = false;
702  hasOuterJoins = false;
703  hasResultRTEs = false;
704  foreach(l, parse->rtable)
705  {
707 
708  switch (rte->rtekind)
709  {
710  case RTE_RELATION:
711  if (rte->inh)
712  {
713  /*
714  * Check to see if the relation actually has any children;
715  * if not, clear the inh flag so we can treat it as a
716  * plain base relation.
717  *
718  * Note: this could give a false-positive result, if the
719  * rel once had children but no longer does. We used to
720  * be able to clear rte->inh later on when we discovered
721  * that, but no more; we have to handle such cases as
722  * full-fledged inheritance.
723  */
724  rte->inh = has_subclass(rte->relid);
725  }
726  break;
727  case RTE_JOIN:
728  root->hasJoinRTEs = true;
729  if (IS_OUTER_JOIN(rte->jointype))
730  hasOuterJoins = true;
731  break;
732  case RTE_RESULT:
733  hasResultRTEs = true;
734  break;
735  default:
736  /* No work here for other RTE types */
737  break;
738  }
739 
740  if (rte->lateral)
741  root->hasLateralRTEs = true;
742 
743  /*
744  * We can also determine the maximum security level required for any
745  * securityQuals now. Addition of inheritance-child RTEs won't affect
746  * this, because child tables don't have their own securityQuals; see
747  * expand_single_inheritance_child().
748  */
749  if (rte->securityQuals)
751  list_length(rte->securityQuals));
752  }
753 
754  /*
755  * If we have now verified that the query target relation is
756  * non-inheriting, mark it as a leaf target.
757  */
758  if (parse->resultRelation)
759  {
760  RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable);
761 
762  if (!rte->inh)
763  root->leaf_result_relids =
764  bms_make_singleton(parse->resultRelation);
765  }
766 
767  /*
768  * Preprocess RowMark information. We need to do this after subquery
769  * pullup, so that all base relations are present.
770  */
771  preprocess_rowmarks(root);
772 
773  /*
774  * Set hasHavingQual to remember if HAVING clause is present. Needed
775  * because preprocess_expression will reduce a constant-true condition to
776  * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
777  */
778  root->hasHavingQual = (parse->havingQual != NULL);
779 
780  /*
781  * Do expression preprocessing on targetlist and quals, as well as other
782  * random expressions in the querytree. Note that we do not need to
783  * handle sort/group expressions explicitly, because they are actually
784  * part of the targetlist.
785  */
786  parse->targetList = (List *)
787  preprocess_expression(root, (Node *) parse->targetList,
789 
790  /* Constant-folding might have removed all set-returning functions */
791  if (parse->hasTargetSRFs)
792  parse->hasTargetSRFs = expression_returns_set((Node *) parse->targetList);
793 
794  newWithCheckOptions = NIL;
795  foreach(l, parse->withCheckOptions)
796  {
798 
799  wco->qual = preprocess_expression(root, wco->qual,
800  EXPRKIND_QUAL);
801  if (wco->qual != NULL)
802  newWithCheckOptions = lappend(newWithCheckOptions, wco);
803  }
804  parse->withCheckOptions = newWithCheckOptions;
805 
806  parse->returningList = (List *)
807  preprocess_expression(root, (Node *) parse->returningList,
809 
810  preprocess_qual_conditions(root, (Node *) parse->jointree);
811 
812  parse->havingQual = preprocess_expression(root, parse->havingQual,
813  EXPRKIND_QUAL);
814 
815  foreach(l, parse->windowClause)
816  {
818 
819  /* partitionClause/orderClause are sort/group expressions */
822  wc->endOffset = preprocess_expression(root, wc->endOffset,
824  }
825 
826  parse->limitOffset = preprocess_expression(root, parse->limitOffset,
828  parse->limitCount = preprocess_expression(root, parse->limitCount,
830 
831  if (parse->onConflict)
832  {
833  parse->onConflict->arbiterElems = (List *)
835  (Node *) parse->onConflict->arbiterElems,
837  parse->onConflict->arbiterWhere =
839  parse->onConflict->arbiterWhere,
840  EXPRKIND_QUAL);
841  parse->onConflict->onConflictSet = (List *)
843  (Node *) parse->onConflict->onConflictSet,
845  parse->onConflict->onConflictWhere =
847  parse->onConflict->onConflictWhere,
848  EXPRKIND_QUAL);
849  /* exclRelTlist contains only Vars, so no preprocessing needed */
850  }
851 
852  root->append_rel_list = (List *)
855 
856  /* Also need to preprocess expressions within RTEs */
857  foreach(l, parse->rtable)
858  {
860  int kind;
861  ListCell *lcsq;
862 
863  if (rte->rtekind == RTE_RELATION)
864  {
865  if (rte->tablesample)
866  rte->tablesample = (TableSampleClause *)
868  (Node *) rte->tablesample,
870  }
871  else if (rte->rtekind == RTE_SUBQUERY)
872  {
873  /*
874  * We don't want to do all preprocessing yet on the subquery's
875  * expressions, since that will happen when we plan it. But if it
876  * contains any join aliases of our level, those have to get
877  * expanded now, because planning of the subquery won't do it.
878  * That's only possible if the subquery is LATERAL.
879  */
880  if (rte->lateral && root->hasJoinRTEs)
881  rte->subquery = (Query *)
883  (Node *) rte->subquery);
884  }
885  else if (rte->rtekind == RTE_FUNCTION)
886  {
887  /* Preprocess the function expression(s) fully */
889  rte->functions = (List *)
890  preprocess_expression(root, (Node *) rte->functions, kind);
891  }
892  else if (rte->rtekind == RTE_TABLEFUNC)
893  {
894  /* Preprocess the function expression(s) fully */
896  rte->tablefunc = (TableFunc *)
897  preprocess_expression(root, (Node *) rte->tablefunc, kind);
898  }
899  else if (rte->rtekind == RTE_VALUES)
900  {
901  /* Preprocess the values lists fully */
903  rte->values_lists = (List *)
904  preprocess_expression(root, (Node *) rte->values_lists, kind);
905  }
906 
907  /*
908  * Process each element of the securityQuals list as if it were a
909  * separate qual expression (as indeed it is). We need to do it this
910  * way to get proper canonicalization of AND/OR structure. Note that
911  * this converts each element into an implicit-AND sublist.
912  */
913  foreach(lcsq, rte->securityQuals)
914  {
915  lfirst(lcsq) = preprocess_expression(root,
916  (Node *) lfirst(lcsq),
917  EXPRKIND_QUAL);
918  }
919  }
920 
921  /*
922  * Now that we are done preprocessing expressions, and in particular done
923  * flattening join alias variables, get rid of the joinaliasvars lists.
924  * They no longer match what expressions in the rest of the tree look
925  * like, because we have not preprocessed expressions in those lists (and
926  * do not want to; for example, expanding a SubLink there would result in
927  * a useless unreferenced subplan). Leaving them in place simply creates
928  * a hazard for later scans of the tree. We could try to prevent that by
929  * using QTW_IGNORE_JOINALIASES in every tree scan done after this point,
930  * but that doesn't sound very reliable.
931  */
932  if (root->hasJoinRTEs)
933  {
934  foreach(l, parse->rtable)
935  {
937 
938  rte->joinaliasvars = NIL;
939  }
940  }
941 
942  /*
943  * In some cases we may want to transfer a HAVING clause into WHERE. We
944  * cannot do so if the HAVING clause contains aggregates (obviously) or
945  * volatile functions (since a HAVING clause is supposed to be executed
946  * only once per group). We also can't do this if there are any nonempty
947  * grouping sets; moving such a clause into WHERE would potentially change
948  * the results, if any referenced column isn't present in all the grouping
949  * sets. (If there are only empty grouping sets, then the HAVING clause
950  * must be degenerate as discussed below.)
951  *
952  * Also, it may be that the clause is so expensive to execute that we're
953  * better off doing it only once per group, despite the loss of
954  * selectivity. This is hard to estimate short of doing the entire
955  * planning process twice, so we use a heuristic: clauses containing
956  * subplans are left in HAVING. Otherwise, we move or copy the HAVING
957  * clause into WHERE, in hopes of eliminating tuples before aggregation
958  * instead of after.
959  *
960  * If the query has explicit grouping then we can simply move such a
961  * clause into WHERE; any group that fails the clause will not be in the
962  * output because none of its tuples will reach the grouping or
963  * aggregation stage. Otherwise we must have a degenerate (variable-free)
964  * HAVING clause, which we put in WHERE so that query_planner() can use it
965  * in a gating Result node, but also keep in HAVING to ensure that we
966  * don't emit a bogus aggregated row. (This could be done better, but it
967  * seems not worth optimizing.)
968  *
969  * Note that both havingQual and parse->jointree->quals are in
970  * implicitly-ANDed-list form at this point, even though they are declared
971  * as Node *.
972  */
973  newHaving = NIL;
974  foreach(l, (List *) parse->havingQual)
975  {
976  Node *havingclause = (Node *) lfirst(l);
977 
978  if ((parse->groupClause && parse->groupingSets) ||
979  contain_agg_clause(havingclause) ||
980  contain_volatile_functions(havingclause) ||
981  contain_subplans(havingclause))
982  {
983  /* keep it in HAVING */
984  newHaving = lappend(newHaving, havingclause);
985  }
986  else if (parse->groupClause && !parse->groupingSets)
987  {
988  /* move it to WHERE */
989  parse->jointree->quals = (Node *)
990  lappend((List *) parse->jointree->quals, havingclause);
991  }
992  else
993  {
994  /* put a copy in WHERE, keep it in HAVING */
995  parse->jointree->quals = (Node *)
996  lappend((List *) parse->jointree->quals,
997  copyObject(havingclause));
998  newHaving = lappend(newHaving, havingclause);
999  }
1000  }
1001  parse->havingQual = (Node *) newHaving;
1002 
1003  /* Remove any redundant GROUP BY columns */
1005 
1006  /*
1007  * If we have any outer joins, try to reduce them to plain inner joins.
1008  * This step is most easily done after we've done expression
1009  * preprocessing.
1010  */
1011  if (hasOuterJoins)
1012  reduce_outer_joins(root);
1013 
1014  /*
1015  * If we have any RTE_RESULT relations, see if they can be deleted from
1016  * the jointree. This step is most effectively done after we've done
1017  * expression preprocessing and outer join reduction.
1018  */
1019  if (hasResultRTEs)
1021 
1022  /*
1023  * Do the main planning.
1024  */
1025  grouping_planner(root, tuple_fraction);
1026 
1027  /*
1028  * Capture the set of outer-level param IDs we have access to, for use in
1029  * extParam/allParam calculations later.
1030  */
1032 
1033  /*
1034  * If any initPlans were created in this query level, adjust the surviving
1035  * Paths' costs and parallel-safety flags to account for them. The
1036  * initPlans won't actually get attached to the plan tree till
1037  * create_plan() runs, but we must include their effects now.
1038  */
1039  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1040  SS_charge_for_initplans(root, final_rel);
1041 
1042  /*
1043  * Make sure we've identified the cheapest Path for the final rel. (By
1044  * doing this here not in grouping_planner, we include initPlan costs in
1045  * the decision, though it's unlikely that will change anything.)
1046  */
1047  set_cheapest(final_rel);
1048 
1049  return root;
1050 }
1051 
1052 /*
1053  * preprocess_expression
1054  * Do subquery_planner's preprocessing work for an expression,
1055  * which can be a targetlist, a WHERE clause (including JOIN/ON
1056  * conditions), a HAVING clause, or a few other things.
1057  */
1058 static Node *
1059 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
1060 {
1061  /*
1062  * Fall out quickly if expression is empty. This occurs often enough to
1063  * be worth checking. Note that null->null is the correct conversion for
1064  * implicit-AND result format, too.
1065  */
1066  if (expr == NULL)
1067  return NULL;
1068 
1069  /*
1070  * If the query has any join RTEs, replace join alias variables with
1071  * base-relation variables. We must do this first, since any expressions
1072  * we may extract from the joinaliasvars lists have not been preprocessed.
1073  * For example, if we did this after sublink processing, sublinks expanded
1074  * out from join aliases would not get processed. But we can skip this in
1075  * non-lateral RTE functions, VALUES lists, and TABLESAMPLE clauses, since
1076  * they can't contain any Vars of the current query level.
1077  */
1078  if (root->hasJoinRTEs &&
1079  !(kind == EXPRKIND_RTFUNC ||
1080  kind == EXPRKIND_VALUES ||
1081  kind == EXPRKIND_TABLESAMPLE ||
1082  kind == EXPRKIND_TABLEFUNC))
1083  expr = flatten_join_alias_vars(root->parse, expr);
1084 
1085  /*
1086  * Simplify constant expressions. For function RTEs, this was already
1087  * done by preprocess_function_rtes. (But note we must do it again for
1088  * EXPRKIND_RTFUNC_LATERAL, because those might by now contain
1089  * un-simplified subexpressions inserted by flattening of subqueries or
1090  * join alias variables.)
1091  *
1092  * Note: an essential effect of this is to convert named-argument function
1093  * calls to positional notation and insert the current actual values of
1094  * any default arguments for functions. To ensure that happens, we *must*
1095  * process all expressions here. Previous PG versions sometimes skipped
1096  * const-simplification if it didn't seem worth the trouble, but we can't
1097  * do that anymore.
1098  *
1099  * Note: this also flattens nested AND and OR expressions into N-argument
1100  * form. All processing of a qual expression after this point must be
1101  * careful to maintain AND/OR flatness --- that is, do not generate a tree
1102  * with AND directly under AND, nor OR directly under OR.
1103  */
1104  if (kind != EXPRKIND_RTFUNC)
1105  expr = eval_const_expressions(root, expr);
1106 
1107  /*
1108  * If it's a qual or havingQual, canonicalize it.
1109  */
1110  if (kind == EXPRKIND_QUAL)
1111  {
1112  expr = (Node *) canonicalize_qual((Expr *) expr, false);
1113 
1114 #ifdef OPTIMIZER_DEBUG
1115  printf("After canonicalize_qual()\n");
1116  pprint(expr);
1117 #endif
1118  }
1119 
1120  /*
1121  * Check for ANY ScalarArrayOpExpr with Const arrays and set the
1122  * hashfuncid of any that might execute more quickly by using hash lookups
1123  * instead of a linear search.
1124  */
1125  if (kind == EXPRKIND_QUAL || kind == EXPRKIND_TARGET)
1126  {
1128  }
1129 
1130  /* Expand SubLinks to SubPlans */
1131  if (root->parse->hasSubLinks)
1132  expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
1133 
1134  /*
1135  * XXX do not insert anything here unless you have grokked the comments in
1136  * SS_replace_correlation_vars ...
1137  */
1138 
1139  /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
1140  if (root->query_level > 1)
1141  expr = SS_replace_correlation_vars(root, expr);
1142 
1143  /*
1144  * If it's a qual or havingQual, convert it to implicit-AND format. (We
1145  * don't want to do this before eval_const_expressions, since the latter
1146  * would be unable to simplify a top-level AND correctly. Also,
1147  * SS_process_sublinks expects explicit-AND format.)
1148  */
1149  if (kind == EXPRKIND_QUAL)
1150  expr = (Node *) make_ands_implicit((Expr *) expr);
1151 
1152  return expr;
1153 }
1154 
1155 /*
1156  * preprocess_qual_conditions
1157  * Recursively scan the query's jointree and do subquery_planner's
1158  * preprocessing work on each qual condition found therein.
1159  */
1160 static void
1162 {
1163  if (jtnode == NULL)
1164  return;
1165  if (IsA(jtnode, RangeTblRef))
1166  {
1167  /* nothing to do here */
1168  }
1169  else if (IsA(jtnode, FromExpr))
1170  {
1171  FromExpr *f = (FromExpr *) jtnode;
1172  ListCell *l;
1173 
1174  foreach(l, f->fromlist)
1176 
1178  }
1179  else if (IsA(jtnode, JoinExpr))
1180  {
1181  JoinExpr *j = (JoinExpr *) jtnode;
1182 
1183  preprocess_qual_conditions(root, j->larg);
1184  preprocess_qual_conditions(root, j->rarg);
1185 
1186  j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
1187  }
1188  else
1189  elog(ERROR, "unrecognized node type: %d",
1190  (int) nodeTag(jtnode));
1191 }
1192 
1193 /*
1194  * preprocess_phv_expression
1195  * Do preprocessing on a PlaceHolderVar expression that's been pulled up.
1196  *
1197  * If a LATERAL subquery references an output of another subquery, and that
1198  * output must be wrapped in a PlaceHolderVar because of an intermediate outer
1199  * join, then we'll push the PlaceHolderVar expression down into the subquery
1200  * and later pull it back up during find_lateral_references, which runs after
1201  * subquery_planner has preprocessed all the expressions that were in the
1202  * current query level to start with. So we need to preprocess it then.
1203  */
1204 Expr *
1206 {
1207  return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
1208 }
1209 
1210 /*--------------------
1211  * grouping_planner
1212  * Perform planning steps related to grouping, aggregation, etc.
1213  *
1214  * This function adds all required top-level processing to the scan/join
1215  * Path(s) produced by query_planner.
1216  *
1217  * tuple_fraction is the fraction of tuples we expect will be retrieved.
1218  * tuple_fraction is interpreted as follows:
1219  * 0: expect all tuples to be retrieved (normal case)
1220  * 0 < tuple_fraction < 1: expect the given fraction of tuples available
1221  * from the plan to be retrieved
1222  * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
1223  * expected to be retrieved (ie, a LIMIT specification)
1224  *
1225  * Returns nothing; the useful output is in the Paths we attach to the
1226  * (UPPERREL_FINAL, NULL) upperrel in *root. In addition,
1227  * root->processed_tlist contains the final processed targetlist.
1228  *
1229  * Note that we have not done set_cheapest() on the final rel; it's convenient
1230  * to leave this to the caller.
1231  *--------------------
1232  */
1233 static void
1234 grouping_planner(PlannerInfo *root, double tuple_fraction)
1235 {
1236  Query *parse = root->parse;
1237  int64 offset_est = 0;
1238  int64 count_est = 0;
1239  double limit_tuples = -1.0;
1240  bool have_postponed_srfs = false;
1241  PathTarget *final_target;
1242  List *final_targets;
1243  List *final_targets_contain_srfs;
1244  bool final_target_parallel_safe;
1245  RelOptInfo *current_rel;
1246  RelOptInfo *final_rel;
1247  FinalPathExtraData extra;
1248  ListCell *lc;
1249 
1250  /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1251  if (parse->limitCount || parse->limitOffset)
1252  {
1253  tuple_fraction = preprocess_limit(root, tuple_fraction,
1254  &offset_est, &count_est);
1255 
1256  /*
1257  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1258  * estimate the effects of using a bounded sort.
1259  */
1260  if (count_est > 0 && offset_est >= 0)
1261  limit_tuples = (double) count_est + (double) offset_est;
1262  }
1263 
1264  /* Make tuple_fraction accessible to lower-level routines */
1265  root->tuple_fraction = tuple_fraction;
1266 
1267  if (parse->setOperations)
1268  {
1269  /*
1270  * If there's a top-level ORDER BY, assume we have to fetch all the
1271  * tuples. This might be too simplistic given all the hackery below
1272  * to possibly avoid the sort; but the odds of accurate estimates here
1273  * are pretty low anyway. XXX try to get rid of this in favor of
1274  * letting plan_set_operations generate both fast-start and
1275  * cheapest-total paths.
1276  */
1277  if (parse->sortClause)
1278  root->tuple_fraction = 0.0;
1279 
1280  /*
1281  * Construct Paths for set operations. The results will not need any
1282  * work except perhaps a top-level sort and/or LIMIT. Note that any
1283  * special work for recursive unions is the responsibility of
1284  * plan_set_operations.
1285  */
1286  current_rel = plan_set_operations(root);
1287 
1288  /*
1289  * We should not need to call preprocess_targetlist, since we must be
1290  * in a SELECT query node. Instead, use the processed_tlist returned
1291  * by plan_set_operations (since this tells whether it returned any
1292  * resjunk columns!), and transfer any sort key information from the
1293  * original tlist.
1294  */
1295  Assert(parse->commandType == CMD_SELECT);
1296 
1297  /* for safety, copy processed_tlist instead of modifying in-place */
1298  root->processed_tlist =
1300  parse->targetList);
1301 
1302  /* Also extract the PathTarget form of the setop result tlist */
1303  final_target = current_rel->cheapest_total_path->pathtarget;
1304 
1305  /* And check whether it's parallel safe */
1306  final_target_parallel_safe =
1307  is_parallel_safe(root, (Node *) final_target->exprs);
1308 
1309  /* The setop result tlist couldn't contain any SRFs */
1310  Assert(!parse->hasTargetSRFs);
1311  final_targets = final_targets_contain_srfs = NIL;
1312 
1313  /*
1314  * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1315  * checked already, but let's make sure).
1316  */
1317  if (parse->rowMarks)
1318  ereport(ERROR,
1319  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1320  /*------
1321  translator: %s is a SQL row locking clause such as FOR UPDATE */
1322  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1324  parse->rowMarks)->strength))));
1325 
1326  /*
1327  * Calculate pathkeys that represent result ordering requirements
1328  */
1329  Assert(parse->distinctClause == NIL);
1331  parse->sortClause,
1332  root->processed_tlist);
1333  }
1334  else
1335  {
1336  /* No set operations, do regular planning */
1337  PathTarget *sort_input_target;
1338  List *sort_input_targets;
1339  List *sort_input_targets_contain_srfs;
1340  bool sort_input_target_parallel_safe;
1341  PathTarget *grouping_target;
1342  List *grouping_targets;
1343  List *grouping_targets_contain_srfs;
1344  bool grouping_target_parallel_safe;
1345  PathTarget *scanjoin_target;
1346  List *scanjoin_targets;
1347  List *scanjoin_targets_contain_srfs;
1348  bool scanjoin_target_parallel_safe;
1349  bool scanjoin_target_same_exprs;
1350  bool have_grouping;
1351  WindowFuncLists *wflists = NULL;
1352  List *activeWindows = NIL;
1353  grouping_sets_data *gset_data = NULL;
1354  standard_qp_extra qp_extra;
1355 
1356  /* A recursive query should always have setOperations */
1357  Assert(!root->hasRecursion);
1358 
1359  /* Preprocess grouping sets and GROUP BY clause, if any */
1360  if (parse->groupingSets)
1361  {
1362  gset_data = preprocess_grouping_sets(root);
1363  }
1364  else
1365  {
1366  /* Preprocess regular GROUP BY clause, if any */
1367  if (parse->groupClause)
1368  parse->groupClause = preprocess_groupclause(root, NIL);
1369  }
1370 
1371  /*
1372  * Preprocess targetlist. Note that much of the remaining planning
1373  * work will be done with the PathTarget representation of tlists, but
1374  * we must also maintain the full representation of the final tlist so
1375  * that we can transfer its decoration (resnames etc) to the topmost
1376  * tlist of the finished Plan. This is kept in processed_tlist.
1377  */
1378  preprocess_targetlist(root);
1379 
1380  /*
1381  * Mark all the aggregates with resolved aggtranstypes, and detect
1382  * aggregates that are duplicates or can share transition state. We
1383  * must do this before slicing and dicing the tlist into various
1384  * pathtargets, else some copies of the Aggref nodes might escape
1385  * being marked.
1386  */
1387  if (parse->hasAggs)
1388  {
1389  preprocess_aggrefs(root, (Node *) root->processed_tlist);
1390  preprocess_aggrefs(root, (Node *) parse->havingQual);
1391  }
1392 
1393  /*
1394  * Locate any window functions in the tlist. (We don't need to look
1395  * anywhere else, since expressions used in ORDER BY will be in there
1396  * too.) Note that they could all have been eliminated by constant
1397  * folding, in which case we don't need to do any more work.
1398  */
1399  if (parse->hasWindowFuncs)
1400  {
1401  wflists = find_window_functions((Node *) root->processed_tlist,
1402  list_length(parse->windowClause));
1403  if (wflists->numWindowFuncs > 0)
1404  activeWindows = select_active_windows(root, wflists);
1405  else
1406  parse->hasWindowFuncs = false;
1407  }
1408 
1409  /*
1410  * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1411  * adding logic between here and the query_planner() call. Anything
1412  * that is needed in MIN/MAX-optimizable cases will have to be
1413  * duplicated in planagg.c.
1414  */
1415  if (parse->hasAggs)
1417 
1418  /*
1419  * Figure out whether there's a hard limit on the number of rows that
1420  * query_planner's result subplan needs to return. Even if we know a
1421  * hard limit overall, it doesn't apply if the query has any
1422  * grouping/aggregation operations, or SRFs in the tlist.
1423  */
1424  if (parse->groupClause ||
1425  parse->groupingSets ||
1426  parse->distinctClause ||
1427  parse->hasAggs ||
1428  parse->hasWindowFuncs ||
1429  parse->hasTargetSRFs ||
1430  root->hasHavingQual)
1431  root->limit_tuples = -1.0;
1432  else
1433  root->limit_tuples = limit_tuples;
1434 
1435  /* Set up data needed by standard_qp_callback */
1436  qp_extra.activeWindows = activeWindows;
1437  qp_extra.groupClause = (gset_data
1438  ? (gset_data->rollups ? linitial_node(RollupData, gset_data->rollups)->groupClause : NIL)
1439  : parse->groupClause);
1440 
1441  /*
1442  * Generate the best unsorted and presorted paths for the scan/join
1443  * portion of this Query, ie the processing represented by the
1444  * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1445  * We also generate (in standard_qp_callback) pathkey representations
1446  * of the query's sort clause, distinct clause, etc.
1447  */
1448  current_rel = query_planner(root, standard_qp_callback, &qp_extra);
1449 
1450  /*
1451  * Convert the query's result tlist into PathTarget format.
1452  *
1453  * Note: this cannot be done before query_planner() has performed
1454  * appendrel expansion, because that might add resjunk entries to
1455  * root->processed_tlist. Waiting till afterwards is also helpful
1456  * because the target width estimates can use per-Var width numbers
1457  * that were obtained within query_planner().
1458  */
1459  final_target = create_pathtarget(root, root->processed_tlist);
1460  final_target_parallel_safe =
1461  is_parallel_safe(root, (Node *) final_target->exprs);
1462 
1463  /*
1464  * If ORDER BY was given, consider whether we should use a post-sort
1465  * projection, and compute the adjusted target for preceding steps if
1466  * so.
1467  */
1468  if (parse->sortClause)
1469  {
1470  sort_input_target = make_sort_input_target(root,
1471  final_target,
1472  &have_postponed_srfs);
1473  sort_input_target_parallel_safe =
1474  is_parallel_safe(root, (Node *) sort_input_target->exprs);
1475  }
1476  else
1477  {
1478  sort_input_target = final_target;
1479  sort_input_target_parallel_safe = final_target_parallel_safe;
1480  }
1481 
1482  /*
1483  * If we have window functions to deal with, the output from any
1484  * grouping step needs to be what the window functions want;
1485  * otherwise, it should be sort_input_target.
1486  */
1487  if (activeWindows)
1488  {
1489  grouping_target = make_window_input_target(root,
1490  final_target,
1491  activeWindows);
1492  grouping_target_parallel_safe =
1493  is_parallel_safe(root, (Node *) grouping_target->exprs);
1494  }
1495  else
1496  {
1497  grouping_target = sort_input_target;
1498  grouping_target_parallel_safe = sort_input_target_parallel_safe;
1499  }
1500 
1501  /*
1502  * If we have grouping or aggregation to do, the topmost scan/join
1503  * plan node must emit what the grouping step wants; otherwise, it
1504  * should emit grouping_target.
1505  */
1506  have_grouping = (parse->groupClause || parse->groupingSets ||
1507  parse->hasAggs || root->hasHavingQual);
1508  if (have_grouping)
1509  {
1510  scanjoin_target = make_group_input_target(root, final_target);
1511  scanjoin_target_parallel_safe =
1512  is_parallel_safe(root, (Node *) scanjoin_target->exprs);
1513  }
1514  else
1515  {
1516  scanjoin_target = grouping_target;
1517  scanjoin_target_parallel_safe = grouping_target_parallel_safe;
1518  }
1519 
1520  /*
1521  * If there are any SRFs in the targetlist, we must separate each of
1522  * these PathTargets into SRF-computing and SRF-free targets. Replace
1523  * each of the named targets with a SRF-free version, and remember the
1524  * list of additional projection steps we need to add afterwards.
1525  */
1526  if (parse->hasTargetSRFs)
1527  {
1528  /* final_target doesn't recompute any SRFs in sort_input_target */
1529  split_pathtarget_at_srfs(root, final_target, sort_input_target,
1530  &final_targets,
1531  &final_targets_contain_srfs);
1532  final_target = linitial_node(PathTarget, final_targets);
1533  Assert(!linitial_int(final_targets_contain_srfs));
1534  /* likewise for sort_input_target vs. grouping_target */
1535  split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
1536  &sort_input_targets,
1537  &sort_input_targets_contain_srfs);
1538  sort_input_target = linitial_node(PathTarget, sort_input_targets);
1539  Assert(!linitial_int(sort_input_targets_contain_srfs));
1540  /* likewise for grouping_target vs. scanjoin_target */
1541  split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
1542  &grouping_targets,
1543  &grouping_targets_contain_srfs);
1544  grouping_target = linitial_node(PathTarget, grouping_targets);
1545  Assert(!linitial_int(grouping_targets_contain_srfs));
1546  /* scanjoin_target will not have any SRFs precomputed for it */
1547  split_pathtarget_at_srfs(root, scanjoin_target, NULL,
1548  &scanjoin_targets,
1549  &scanjoin_targets_contain_srfs);
1550  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
1551  Assert(!linitial_int(scanjoin_targets_contain_srfs));
1552  }
1553  else
1554  {
1555  /* initialize lists; for most of these, dummy values are OK */
1556  final_targets = final_targets_contain_srfs = NIL;
1557  sort_input_targets = sort_input_targets_contain_srfs = NIL;
1558  grouping_targets = grouping_targets_contain_srfs = NIL;
1559  scanjoin_targets = list_make1(scanjoin_target);
1560  scanjoin_targets_contain_srfs = NIL;
1561  }
1562 
1563  /* Apply scan/join target. */
1564  scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
1565  && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
1566  apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
1567  scanjoin_targets_contain_srfs,
1568  scanjoin_target_parallel_safe,
1569  scanjoin_target_same_exprs);
1570 
1571  /*
1572  * Save the various upper-rel PathTargets we just computed into
1573  * root->upper_targets[]. The core code doesn't use this, but it
1574  * provides a convenient place for extensions to get at the info. For
1575  * consistency, we save all the intermediate targets, even though some
1576  * of the corresponding upperrels might not be needed for this query.
1577  */
1578  root->upper_targets[UPPERREL_FINAL] = final_target;
1579  root->upper_targets[UPPERREL_ORDERED] = final_target;
1580  root->upper_targets[UPPERREL_PARTIAL_DISTINCT] = sort_input_target;
1581  root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
1582  root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
1583  root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
1584 
1585  /*
1586  * If we have grouping and/or aggregation, consider ways to implement
1587  * that. We build a new upperrel representing the output of this
1588  * phase.
1589  */
1590  if (have_grouping)
1591  {
1592  current_rel = create_grouping_paths(root,
1593  current_rel,
1594  grouping_target,
1595  grouping_target_parallel_safe,
1596  gset_data);
1597  /* Fix things up if grouping_target contains SRFs */
1598  if (parse->hasTargetSRFs)
1599  adjust_paths_for_srfs(root, current_rel,
1600  grouping_targets,
1601  grouping_targets_contain_srfs);
1602  }
1603 
1604  /*
1605  * If we have window functions, consider ways to implement those. We
1606  * build a new upperrel representing the output of this phase.
1607  */
1608  if (activeWindows)
1609  {
1610  current_rel = create_window_paths(root,
1611  current_rel,
1612  grouping_target,
1613  sort_input_target,
1614  sort_input_target_parallel_safe,
1615  wflists,
1616  activeWindows);
1617  /* Fix things up if sort_input_target contains SRFs */
1618  if (parse->hasTargetSRFs)
1619  adjust_paths_for_srfs(root, current_rel,
1620  sort_input_targets,
1621  sort_input_targets_contain_srfs);
1622  }
1623 
1624  /*
1625  * If there is a DISTINCT clause, consider ways to implement that. We
1626  * build a new upperrel representing the output of this phase.
1627  */
1628  if (parse->distinctClause)
1629  {
1630  current_rel = create_distinct_paths(root,
1631  current_rel);
1632  }
1633  } /* end of if (setOperations) */
1634 
1635  /*
1636  * If ORDER BY was given, consider ways to implement that, and generate a
1637  * new upperrel containing only paths that emit the correct ordering and
1638  * project the correct final_target. We can apply the original
1639  * limit_tuples limit in sort costing here, but only if there are no
1640  * postponed SRFs.
1641  */
1642  if (parse->sortClause)
1643  {
1644  current_rel = create_ordered_paths(root,
1645  current_rel,
1646  final_target,
1647  final_target_parallel_safe,
1648  have_postponed_srfs ? -1.0 :
1649  limit_tuples);
1650  /* Fix things up if final_target contains SRFs */
1651  if (parse->hasTargetSRFs)
1652  adjust_paths_for_srfs(root, current_rel,
1653  final_targets,
1654  final_targets_contain_srfs);
1655  }
1656 
1657  /*
1658  * Now we are prepared to build the final-output upperrel.
1659  */
1660  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1661 
1662  /*
1663  * If the input rel is marked consider_parallel and there's nothing that's
1664  * not parallel-safe in the LIMIT clause, then the final_rel can be marked
1665  * consider_parallel as well. Note that if the query has rowMarks or is
1666  * not a SELECT, consider_parallel will be false for every relation in the
1667  * query.
1668  */
1669  if (current_rel->consider_parallel &&
1670  is_parallel_safe(root, parse->limitOffset) &&
1671  is_parallel_safe(root, parse->limitCount))
1672  final_rel->consider_parallel = true;
1673 
1674  /*
1675  * If the current_rel belongs to a single FDW, so does the final_rel.
1676  */
1677  final_rel->serverid = current_rel->serverid;
1678  final_rel->userid = current_rel->userid;
1679  final_rel->useridiscurrent = current_rel->useridiscurrent;
1680  final_rel->fdwroutine = current_rel->fdwroutine;
1681 
1682  /*
1683  * Generate paths for the final_rel. Insert all surviving paths, with
1684  * LockRows, Limit, and/or ModifyTable steps added if needed.
1685  */
1686  foreach(lc, current_rel->pathlist)
1687  {
1688  Path *path = (Path *) lfirst(lc);
1689 
1690  /*
1691  * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
1692  * (Note: we intentionally test parse->rowMarks not root->rowMarks
1693  * here. If there are only non-locking rowmarks, they should be
1694  * handled by the ModifyTable node instead. However, root->rowMarks
1695  * is what goes into the LockRows node.)
1696  */
1697  if (parse->rowMarks)
1698  {
1699  path = (Path *) create_lockrows_path(root, final_rel, path,
1700  root->rowMarks,
1702  }
1703 
1704  /*
1705  * If there is a LIMIT/OFFSET clause, add the LIMIT node.
1706  */
1707  if (limit_needed(parse))
1708  {
1709  path = (Path *) create_limit_path(root, final_rel, path,
1710  parse->limitOffset,
1711  parse->limitCount,
1712  parse->limitOption,
1713  offset_est, count_est);
1714  }
1715 
1716  /*
1717  * If this is an INSERT/UPDATE/DELETE, add the ModifyTable node.
1718  */
1719  if (parse->commandType != CMD_SELECT)
1720  {
1721  Index rootRelation;
1722  List *resultRelations = NIL;
1723  List *updateColnosLists = NIL;
1724  List *withCheckOptionLists = NIL;
1725  List *returningLists = NIL;
1726  List *rowMarks;
1727 
1729  {
1730  /* Inherited UPDATE/DELETE */
1731  RelOptInfo *top_result_rel = find_base_rel(root,
1732  parse->resultRelation);
1733  int resultRelation = -1;
1734 
1735  /* Add only leaf children to ModifyTable. */
1736  while ((resultRelation = bms_next_member(root->leaf_result_relids,
1737  resultRelation)) >= 0)
1738  {
1739  RelOptInfo *this_result_rel = find_base_rel(root,
1740  resultRelation);
1741 
1742  /*
1743  * Also exclude any leaf rels that have turned dummy since
1744  * being added to the list, for example, by being excluded
1745  * by constraint exclusion.
1746  */
1747  if (IS_DUMMY_REL(this_result_rel))
1748  continue;
1749 
1750  /* Build per-target-rel lists needed by ModifyTable */
1751  resultRelations = lappend_int(resultRelations,
1752  resultRelation);
1753  if (parse->commandType == CMD_UPDATE)
1754  {
1755  List *update_colnos = root->update_colnos;
1756 
1757  if (this_result_rel != top_result_rel)
1758  update_colnos =
1760  update_colnos,
1761  this_result_rel->relid,
1762  top_result_rel->relid);
1763  updateColnosLists = lappend(updateColnosLists,
1764  update_colnos);
1765  }
1766  if (parse->withCheckOptions)
1767  {
1768  List *withCheckOptions = parse->withCheckOptions;
1769 
1770  if (this_result_rel != top_result_rel)
1771  withCheckOptions = (List *)
1773  (Node *) withCheckOptions,
1774  this_result_rel->relids,
1775  top_result_rel->relids);
1776  withCheckOptionLists = lappend(withCheckOptionLists,
1777  withCheckOptions);
1778  }
1779  if (parse->returningList)
1780  {
1781  List *returningList = parse->returningList;
1782 
1783  if (this_result_rel != top_result_rel)
1784  returningList = (List *)
1786  (Node *) returningList,
1787  this_result_rel->relids,
1788  top_result_rel->relids);
1789  returningLists = lappend(returningLists,
1790  returningList);
1791  }
1792  }
1793 
1794  if (resultRelations == NIL)
1795  {
1796  /*
1797  * We managed to exclude every child rel, so generate a
1798  * dummy one-relation plan using info for the top target
1799  * rel (even though that may not be a leaf target).
1800  * Although it's clear that no data will be updated or
1801  * deleted, we still need to have a ModifyTable node so
1802  * that any statement triggers will be executed. (This
1803  * could be cleaner if we fixed nodeModifyTable.c to allow
1804  * zero target relations, but that probably wouldn't be a
1805  * net win.)
1806  */
1807  resultRelations = list_make1_int(parse->resultRelation);
1808  if (parse->commandType == CMD_UPDATE)
1809  updateColnosLists = list_make1(root->update_colnos);
1810  if (parse->withCheckOptions)
1811  withCheckOptionLists = list_make1(parse->withCheckOptions);
1812  if (parse->returningList)
1813  returningLists = list_make1(parse->returningList);
1814  }
1815  }
1816  else
1817  {
1818  /* Single-relation INSERT/UPDATE/DELETE. */
1819  resultRelations = list_make1_int(parse->resultRelation);
1820  if (parse->commandType == CMD_UPDATE)
1821  updateColnosLists = list_make1(root->update_colnos);
1822  if (parse->withCheckOptions)
1823  withCheckOptionLists = list_make1(parse->withCheckOptions);
1824  if (parse->returningList)
1825  returningLists = list_make1(parse->returningList);
1826  }
1827 
1828  /*
1829  * If target is a partition root table, we need to mark the
1830  * ModifyTable node appropriately for that.
1831  */
1832  if (rt_fetch(parse->resultRelation, parse->rtable)->relkind ==
1833  RELKIND_PARTITIONED_TABLE)
1834  rootRelation = parse->resultRelation;
1835  else
1836  rootRelation = 0;
1837 
1838  /*
1839  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
1840  * will have dealt with fetching non-locked marked rows, else we
1841  * need to have ModifyTable do that.
1842  */
1843  if (parse->rowMarks)
1844  rowMarks = NIL;
1845  else
1846  rowMarks = root->rowMarks;
1847 
1848  path = (Path *)
1849  create_modifytable_path(root, final_rel,
1850  path,
1851  parse->commandType,
1852  parse->canSetTag,
1853  parse->resultRelation,
1854  rootRelation,
1855  root->partColsUpdated,
1856  resultRelations,
1857  updateColnosLists,
1858  withCheckOptionLists,
1859  returningLists,
1860  rowMarks,
1861  parse->onConflict,
1863  }
1864 
1865  /* And shove it into final_rel */
1866  add_path(final_rel, path);
1867  }
1868 
1869  /*
1870  * Generate partial paths for final_rel, too, if outer query levels might
1871  * be able to make use of them.
1872  */
1873  if (final_rel->consider_parallel && root->query_level > 1 &&
1874  !limit_needed(parse))
1875  {
1876  Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
1877  foreach(lc, current_rel->partial_pathlist)
1878  {
1879  Path *partial_path = (Path *) lfirst(lc);
1880 
1881  add_partial_path(final_rel, partial_path);
1882  }
1883  }
1884 
1885  extra.limit_needed = limit_needed(parse);
1886  extra.limit_tuples = limit_tuples;
1887  extra.count_est = count_est;
1888  extra.offset_est = offset_est;
1889 
1890  /*
1891  * If there is an FDW that's responsible for all baserels of the query,
1892  * let it consider adding ForeignPaths.
1893  */
1894  if (final_rel->fdwroutine &&
1895  final_rel->fdwroutine->GetForeignUpperPaths)
1897  current_rel, final_rel,
1898  &extra);
1899 
1900  /* Let extensions possibly add some more paths */
1902  (*create_upper_paths_hook) (root, UPPERREL_FINAL,
1903  current_rel, final_rel, &extra);
1904 
1905  /* Note: currently, we leave it to callers to do set_cheapest() */
1906 }
1907 
1908 /*
1909  * Do preprocessing for groupingSets clause and related data. This handles the
1910  * preliminary steps of expanding the grouping sets, organizing them into lists
1911  * of rollups, and preparing annotations which will later be filled in with
1912  * size estimates.
1913  */
1914 static grouping_sets_data *
1916 {
1917  Query *parse = root->parse;
1918  List *sets;
1919  int maxref = 0;
1920  ListCell *lc;
1921  ListCell *lc_set;
1923 
1924  parse->groupingSets = expand_grouping_sets(parse->groupingSets, parse->groupDistinct, -1);
1925 
1926  gd->any_hashable = false;
1927  gd->unhashable_refs = NULL;
1928  gd->unsortable_refs = NULL;
1929  gd->unsortable_sets = NIL;
1930 
1931  if (parse->groupClause)
1932  {
1933  ListCell *lc;
1934 
1935  foreach(lc, parse->groupClause)
1936  {
1938  Index ref = gc->tleSortGroupRef;
1939 
1940  if (ref > maxref)
1941  maxref = ref;
1942 
1943  if (!gc->hashable)
1945 
1946  if (!OidIsValid(gc->sortop))
1948  }
1949  }
1950 
1951  /* Allocate workspace array for remapping */
1952  gd->tleref_to_colnum_map = (int *) palloc((maxref + 1) * sizeof(int));
1953 
1954  /*
1955  * If we have any unsortable sets, we must extract them before trying to
1956  * prepare rollups. Unsortable sets don't go through
1957  * reorder_grouping_sets, so we must apply the GroupingSetData annotation
1958  * here.
1959  */
1960  if (!bms_is_empty(gd->unsortable_refs))
1961  {
1962  List *sortable_sets = NIL;
1963 
1964  foreach(lc, parse->groupingSets)
1965  {
1966  List *gset = (List *) lfirst(lc);
1967 
1968  if (bms_overlap_list(gd->unsortable_refs, gset))
1969  {
1971 
1972  gs->set = gset;
1973  gd->unsortable_sets = lappend(gd->unsortable_sets, gs);
1974 
1975  /*
1976  * We must enforce here that an unsortable set is hashable;
1977  * later code assumes this. Parse analysis only checks that
1978  * every individual column is either hashable or sortable.
1979  *
1980  * Note that passing this test doesn't guarantee we can
1981  * generate a plan; there might be other showstoppers.
1982  */
1983  if (bms_overlap_list(gd->unhashable_refs, gset))
1984  ereport(ERROR,
1985  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1986  errmsg("could not implement GROUP BY"),
1987  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
1988  }
1989  else
1990  sortable_sets = lappend(sortable_sets, gset);
1991  }
1992 
1993  if (sortable_sets)
1994  sets = extract_rollup_sets(sortable_sets);
1995  else
1996  sets = NIL;
1997  }
1998  else
1999  sets = extract_rollup_sets(parse->groupingSets);
2000 
2001  foreach(lc_set, sets)
2002  {
2003  List *current_sets = (List *) lfirst(lc_set);
2004  RollupData *rollup = makeNode(RollupData);
2005  GroupingSetData *gs;
2006 
2007  /*
2008  * Reorder the current list of grouping sets into correct prefix
2009  * order. If only one aggregation pass is needed, try to make the
2010  * list match the ORDER BY clause; if more than one pass is needed, we
2011  * don't bother with that.
2012  *
2013  * Note that this reorders the sets from smallest-member-first to
2014  * largest-member-first, and applies the GroupingSetData annotations,
2015  * though the data will be filled in later.
2016  */
2017  current_sets = reorder_grouping_sets(current_sets,
2018  (list_length(sets) == 1
2019  ? parse->sortClause
2020  : NIL));
2021 
2022  /*
2023  * Get the initial (and therefore largest) grouping set.
2024  */
2025  gs = linitial_node(GroupingSetData, current_sets);
2026 
2027  /*
2028  * Order the groupClause appropriately. If the first grouping set is
2029  * empty, then the groupClause must also be empty; otherwise we have
2030  * to force the groupClause to match that grouping set's order.
2031  *
2032  * (The first grouping set can be empty even though parse->groupClause
2033  * is not empty only if all non-empty grouping sets are unsortable.
2034  * The groupClauses for hashed grouping sets are built later on.)
2035  */
2036  if (gs->set)
2037  rollup->groupClause = preprocess_groupclause(root, gs->set);
2038  else
2039  rollup->groupClause = NIL;
2040 
2041  /*
2042  * Is it hashable? We pretend empty sets are hashable even though we
2043  * actually force them not to be hashed later. But don't bother if
2044  * there's nothing but empty sets (since in that case we can't hash
2045  * anything).
2046  */
2047  if (gs->set &&
2049  {
2050  rollup->hashable = true;
2051  gd->any_hashable = true;
2052  }
2053 
2054  /*
2055  * Now that we've pinned down an order for the groupClause for this
2056  * list of grouping sets, we need to remap the entries in the grouping
2057  * sets from sortgrouprefs to plain indices (0-based) into the
2058  * groupClause for this collection of grouping sets. We keep the
2059  * original form for later use, though.
2060  */
2061  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
2062  current_sets,
2063  gd->tleref_to_colnum_map);
2064  rollup->gsets_data = current_sets;
2065 
2066  gd->rollups = lappend(gd->rollups, rollup);
2067  }
2068 
2069  if (gd->unsortable_sets)
2070  {
2071  /*
2072  * We have not yet pinned down a groupclause for this, but we will
2073  * need index-based lists for estimation purposes. Construct
2074  * hash_sets_idx based on the entire original groupclause for now.
2075  */
2076  gd->hash_sets_idx = remap_to_groupclause_idx(parse->groupClause,
2077  gd->unsortable_sets,
2078  gd->tleref_to_colnum_map);
2079  gd->any_hashable = true;
2080  }
2081 
2082  return gd;
2083 }
2084 
2085 /*
2086  * Given a groupclause and a list of GroupingSetData, return equivalent sets
2087  * (without annotation) mapped to indexes into the given groupclause.
2088  */
2089 static List *
2091  List *gsets,
2092  int *tleref_to_colnum_map)
2093 {
2094  int ref = 0;
2095  List *result = NIL;
2096  ListCell *lc;
2097 
2098  foreach(lc, groupClause)
2099  {
2101 
2102  tleref_to_colnum_map[gc->tleSortGroupRef] = ref++;
2103  }
2104 
2105  foreach(lc, gsets)
2106  {
2107  List *set = NIL;
2108  ListCell *lc2;
2110 
2111  foreach(lc2, gs->set)
2112  {
2113  set = lappend_int(set, tleref_to_colnum_map[lfirst_int(lc2)]);
2114  }
2115 
2116  result = lappend(result, set);
2117  }
2118 
2119  return result;
2120 }
2121 
2122 
2123 /*
2124  * preprocess_rowmarks - set up PlanRowMarks if needed
2125  */
2126 static void
2128 {
2129  Query *parse = root->parse;
2130  Bitmapset *rels;
2131  List *prowmarks;
2132  ListCell *l;
2133  int i;
2134 
2135  if (parse->rowMarks)
2136  {
2137  /*
2138  * We've got trouble if FOR [KEY] UPDATE/SHARE appears inside
2139  * grouping, since grouping renders a reference to individual tuple
2140  * CTIDs invalid. This is also checked at parse time, but that's
2141  * insufficient because of rule substitution, query pullup, etc.
2142  */
2144  parse->rowMarks)->strength);
2145  }
2146  else
2147  {
2148  /*
2149  * We only need rowmarks for UPDATE, DELETE, or FOR [KEY]
2150  * UPDATE/SHARE.
2151  */
2152  if (parse->commandType != CMD_UPDATE &&
2153  parse->commandType != CMD_DELETE)
2154  return;
2155  }
2156 
2157  /*
2158  * We need to have rowmarks for all base relations except the target. We
2159  * make a bitmapset of all base rels and then remove the items we don't
2160  * need or have FOR [KEY] UPDATE/SHARE marks for.
2161  */
2162  rels = get_relids_in_jointree((Node *) parse->jointree, false);
2163  if (parse->resultRelation)
2164  rels = bms_del_member(rels, parse->resultRelation);
2165 
2166  /*
2167  * Convert RowMarkClauses to PlanRowMark representation.
2168  */
2169  prowmarks = NIL;
2170  foreach(l, parse->rowMarks)
2171  {
2173  RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
2174  PlanRowMark *newrc;
2175 
2176  /*
2177  * Currently, it is syntactically impossible to have FOR UPDATE et al
2178  * applied to an update/delete target rel. If that ever becomes
2179  * possible, we should drop the target from the PlanRowMark list.
2180  */
2181  Assert(rc->rti != parse->resultRelation);
2182 
2183  /*
2184  * Ignore RowMarkClauses for subqueries; they aren't real tables and
2185  * can't support true locking. Subqueries that got flattened into the
2186  * main query should be ignored completely. Any that didn't will get
2187  * ROW_MARK_COPY items in the next loop.
2188  */
2189  if (rte->rtekind != RTE_RELATION)
2190  continue;
2191 
2192  rels = bms_del_member(rels, rc->rti);
2193 
2194  newrc = makeNode(PlanRowMark);
2195  newrc->rti = newrc->prti = rc->rti;
2196  newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2197  newrc->markType = select_rowmark_type(rte, rc->strength);
2198  newrc->allMarkTypes = (1 << newrc->markType);
2199  newrc->strength = rc->strength;
2200  newrc->waitPolicy = rc->waitPolicy;
2201  newrc->isParent = false;
2202 
2203  prowmarks = lappend(prowmarks, newrc);
2204  }
2205 
2206  /*
2207  * Now, add rowmarks for any non-target, non-locked base relations.
2208  */
2209  i = 0;
2210  foreach(l, parse->rtable)
2211  {
2213  PlanRowMark *newrc;
2214 
2215  i++;
2216  if (!bms_is_member(i, rels))
2217  continue;
2218 
2219  newrc = makeNode(PlanRowMark);
2220  newrc->rti = newrc->prti = i;
2221  newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2222  newrc->markType = select_rowmark_type(rte, LCS_NONE);
2223  newrc->allMarkTypes = (1 << newrc->markType);
2224  newrc->strength = LCS_NONE;
2225  newrc->waitPolicy = LockWaitBlock; /* doesn't matter */
2226  newrc->isParent = false;
2227 
2228  prowmarks = lappend(prowmarks, newrc);
2229  }
2230 
2231  root->rowMarks = prowmarks;
2232 }
2233 
2234 /*
2235  * Select RowMarkType to use for a given table
2236  */
2239 {
2240  if (rte->rtekind != RTE_RELATION)
2241  {
2242  /* If it's not a table at all, use ROW_MARK_COPY */
2243  return ROW_MARK_COPY;
2244  }
2245  else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2246  {
2247  /* Let the FDW select the rowmark type, if it wants to */
2248  FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2249 
2250  if (fdwroutine->GetForeignRowMarkType != NULL)
2251  return fdwroutine->GetForeignRowMarkType(rte, strength);
2252  /* Otherwise, use ROW_MARK_COPY by default */
2253  return ROW_MARK_COPY;
2254  }
2255  else
2256  {
2257  /* Regular table, apply the appropriate lock type */
2258  switch (strength)
2259  {
2260  case LCS_NONE:
2261 
2262  /*
2263  * We don't need a tuple lock, only the ability to re-fetch
2264  * the row.
2265  */
2266  return ROW_MARK_REFERENCE;
2267  break;
2268  case LCS_FORKEYSHARE:
2269  return ROW_MARK_KEYSHARE;
2270  break;
2271  case LCS_FORSHARE:
2272  return ROW_MARK_SHARE;
2273  break;
2274  case LCS_FORNOKEYUPDATE:
2275  return ROW_MARK_NOKEYEXCLUSIVE;
2276  break;
2277  case LCS_FORUPDATE:
2278  return ROW_MARK_EXCLUSIVE;
2279  break;
2280  }
2281  elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2282  return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2283  }
2284 }
2285 
2286 /*
2287  * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
2288  *
2289  * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
2290  * results back in *count_est and *offset_est. These variables are set to
2291  * 0 if the corresponding clause is not present, and -1 if it's present
2292  * but we couldn't estimate the value for it. (The "0" convention is OK
2293  * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
2294  * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
2295  * usual practice of never estimating less than one row.) These values will
2296  * be passed to create_limit_path, which see if you change this code.
2297  *
2298  * The return value is the suitably adjusted tuple_fraction to use for
2299  * planning the query. This adjustment is not overridable, since it reflects
2300  * plan actions that grouping_planner() will certainly take, not assumptions
2301  * about context.
2302  */
2303 static double
2304 preprocess_limit(PlannerInfo *root, double tuple_fraction,
2305  int64 *offset_est, int64 *count_est)
2306 {
2307  Query *parse = root->parse;
2308  Node *est;
2309  double limit_fraction;
2310 
2311  /* Should not be called unless LIMIT or OFFSET */
2312  Assert(parse->limitCount || parse->limitOffset);
2313 
2314  /*
2315  * Try to obtain the clause values. We use estimate_expression_value
2316  * primarily because it can sometimes do something useful with Params.
2317  */
2318  if (parse->limitCount)
2319  {
2320  est = estimate_expression_value(root, parse->limitCount);
2321  if (est && IsA(est, Const))
2322  {
2323  if (((Const *) est)->constisnull)
2324  {
2325  /* NULL indicates LIMIT ALL, ie, no limit */
2326  *count_est = 0; /* treat as not present */
2327  }
2328  else
2329  {
2330  *count_est = DatumGetInt64(((Const *) est)->constvalue);
2331  if (*count_est <= 0)
2332  *count_est = 1; /* force to at least 1 */
2333  }
2334  }
2335  else
2336  *count_est = -1; /* can't estimate */
2337  }
2338  else
2339  *count_est = 0; /* not present */
2340 
2341  if (parse->limitOffset)
2342  {
2343  est = estimate_expression_value(root, parse->limitOffset);
2344  if (est && IsA(est, Const))
2345  {
2346  if (((Const *) est)->constisnull)
2347  {
2348  /* Treat NULL as no offset; the executor will too */
2349  *offset_est = 0; /* treat as not present */
2350  }
2351  else
2352  {
2353  *offset_est = DatumGetInt64(((Const *) est)->constvalue);
2354  if (*offset_est < 0)
2355  *offset_est = 0; /* treat as not present */
2356  }
2357  }
2358  else
2359  *offset_est = -1; /* can't estimate */
2360  }
2361  else
2362  *offset_est = 0; /* not present */
2363 
2364  if (*count_est != 0)
2365  {
2366  /*
2367  * A LIMIT clause limits the absolute number of tuples returned.
2368  * However, if it's not a constant LIMIT then we have to guess; for
2369  * lack of a better idea, assume 10% of the plan's result is wanted.
2370  */
2371  if (*count_est < 0 || *offset_est < 0)
2372  {
2373  /* LIMIT or OFFSET is an expression ... punt ... */
2374  limit_fraction = 0.10;
2375  }
2376  else
2377  {
2378  /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
2379  limit_fraction = (double) *count_est + (double) *offset_est;
2380  }
2381 
2382  /*
2383  * If we have absolute limits from both caller and LIMIT, use the
2384  * smaller value; likewise if they are both fractional. If one is
2385  * fractional and the other absolute, we can't easily determine which
2386  * is smaller, but we use the heuristic that the absolute will usually
2387  * be smaller.
2388  */
2389  if (tuple_fraction >= 1.0)
2390  {
2391  if (limit_fraction >= 1.0)
2392  {
2393  /* both absolute */
2394  tuple_fraction = Min(tuple_fraction, limit_fraction);
2395  }
2396  else
2397  {
2398  /* caller absolute, limit fractional; use caller's value */
2399  }
2400  }
2401  else if (tuple_fraction > 0.0)
2402  {
2403  if (limit_fraction >= 1.0)
2404  {
2405  /* caller fractional, limit absolute; use limit */
2406  tuple_fraction = limit_fraction;
2407  }
2408  else
2409  {
2410  /* both fractional */
2411  tuple_fraction = Min(tuple_fraction, limit_fraction);
2412  }
2413  }
2414  else
2415  {
2416  /* no info from caller, just use limit */
2417  tuple_fraction = limit_fraction;
2418  }
2419  }
2420  else if (*offset_est != 0 && tuple_fraction > 0.0)
2421  {
2422  /*
2423  * We have an OFFSET but no LIMIT. This acts entirely differently
2424  * from the LIMIT case: here, we need to increase rather than decrease
2425  * the caller's tuple_fraction, because the OFFSET acts to cause more
2426  * tuples to be fetched instead of fewer. This only matters if we got
2427  * a tuple_fraction > 0, however.
2428  *
2429  * As above, use 10% if OFFSET is present but unestimatable.
2430  */
2431  if (*offset_est < 0)
2432  limit_fraction = 0.10;
2433  else
2434  limit_fraction = (double) *offset_est;
2435 
2436  /*
2437  * If we have absolute counts from both caller and OFFSET, add them
2438  * together; likewise if they are both fractional. If one is
2439  * fractional and the other absolute, we want to take the larger, and
2440  * we heuristically assume that's the fractional one.
2441  */
2442  if (tuple_fraction >= 1.0)
2443  {
2444  if (limit_fraction >= 1.0)
2445  {
2446  /* both absolute, so add them together */
2447  tuple_fraction += limit_fraction;
2448  }
2449  else
2450  {
2451  /* caller absolute, limit fractional; use limit */
2452  tuple_fraction = limit_fraction;
2453  }
2454  }
2455  else
2456  {
2457  if (limit_fraction >= 1.0)
2458  {
2459  /* caller fractional, limit absolute; use caller's value */
2460  }
2461  else
2462  {
2463  /* both fractional, so add them together */
2464  tuple_fraction += limit_fraction;
2465  if (tuple_fraction >= 1.0)
2466  tuple_fraction = 0.0; /* assume fetch all */
2467  }
2468  }
2469  }
2470 
2471  return tuple_fraction;
2472 }
2473 
2474 /*
2475  * limit_needed - do we actually need a Limit plan node?
2476  *
2477  * If we have constant-zero OFFSET and constant-null LIMIT, we can skip adding
2478  * a Limit node. This is worth checking for because "OFFSET 0" is a common
2479  * locution for an optimization fence. (Because other places in the planner
2480  * merely check whether parse->limitOffset isn't NULL, it will still work as
2481  * an optimization fence --- we're just suppressing unnecessary run-time
2482  * overhead.)
2483  *
2484  * This might look like it could be merged into preprocess_limit, but there's
2485  * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas
2486  * in preprocess_limit it's good enough to consider estimated values.
2487  */
2488 bool
2490 {
2491  Node *node;
2492 
2493  node = parse->limitCount;
2494  if (node)
2495  {
2496  if (IsA(node, Const))
2497  {
2498  /* NULL indicates LIMIT ALL, ie, no limit */
2499  if (!((Const *) node)->constisnull)
2500  return true; /* LIMIT with a constant value */
2501  }
2502  else
2503  return true; /* non-constant LIMIT */
2504  }
2505 
2506  node = parse->limitOffset;
2507  if (node)
2508  {
2509  if (IsA(node, Const))
2510  {
2511  /* Treat NULL as no offset; the executor would too */
2512  if (!((Const *) node)->constisnull)
2513  {
2514  int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2515 
2516  if (offset != 0)
2517  return true; /* OFFSET with a nonzero value */
2518  }
2519  }
2520  else
2521  return true; /* non-constant OFFSET */
2522  }
2523 
2524  return false; /* don't need a Limit plan node */
2525 }
2526 
2527 
2528 /*
2529  * remove_useless_groupby_columns
2530  * Remove any columns in the GROUP BY clause that are redundant due to
2531  * being functionally dependent on other GROUP BY columns.
2532  *
2533  * Since some other DBMSes do not allow references to ungrouped columns, it's
2534  * not unusual to find all columns listed in GROUP BY even though listing the
2535  * primary-key columns would be sufficient. Deleting such excess columns
2536  * avoids redundant sorting work, so it's worth doing.
2537  *
2538  * Relcache invalidations will ensure that cached plans become invalidated
2539  * when the underlying index of the pkey constraint is dropped.
2540  *
2541  * Currently, we only make use of pkey constraints for this, however, we may
2542  * wish to take this further in the future and also use unique constraints
2543  * which have NOT NULL columns. In that case, plan invalidation will still
2544  * work since relations will receive a relcache invalidation when a NOT NULL
2545  * constraint is dropped.
2546  */
2547 static void
2549 {
2550  Query *parse = root->parse;
2551  Bitmapset **groupbyattnos;
2552  Bitmapset **surplusvars;
2553  ListCell *lc;
2554  int relid;
2555 
2556  /* No chance to do anything if there are less than two GROUP BY items */
2557  if (list_length(parse->groupClause) < 2)
2558  return;
2559 
2560  /* Don't fiddle with the GROUP BY clause if the query has grouping sets */
2561  if (parse->groupingSets)
2562  return;
2563 
2564  /*
2565  * Scan the GROUP BY clause to find GROUP BY items that are simple Vars.
2566  * Fill groupbyattnos[k] with a bitmapset of the column attnos of RTE k
2567  * that are GROUP BY items.
2568  */
2569  groupbyattnos = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
2570  (list_length(parse->rtable) + 1));
2571  foreach(lc, parse->groupClause)
2572  {
2574  TargetEntry *tle = get_sortgroupclause_tle(sgc, parse->targetList);
2575  Var *var = (Var *) tle->expr;
2576 
2577  /*
2578  * Ignore non-Vars and Vars from other query levels.
2579  *
2580  * XXX in principle, stable expressions containing Vars could also be
2581  * removed, if all the Vars are functionally dependent on other GROUP
2582  * BY items. But it's not clear that such cases occur often enough to
2583  * be worth troubling over.
2584  */
2585  if (!IsA(var, Var) ||
2586  var->varlevelsup > 0)
2587  continue;
2588 
2589  /* OK, remember we have this Var */
2590  relid = var->varno;
2591  Assert(relid <= list_length(parse->rtable));
2592  groupbyattnos[relid] = bms_add_member(groupbyattnos[relid],
2594  }
2595 
2596  /*
2597  * Consider each relation and see if it is possible to remove some of its
2598  * Vars from GROUP BY. For simplicity and speed, we do the actual removal
2599  * in a separate pass. Here, we just fill surplusvars[k] with a bitmapset
2600  * of the column attnos of RTE k that are removable GROUP BY items.
2601  */
2602  surplusvars = NULL; /* don't allocate array unless required */
2603  relid = 0;
2604  foreach(lc, parse->rtable)
2605  {
2607  Bitmapset *relattnos;
2608  Bitmapset *pkattnos;
2609  Oid constraintOid;
2610 
2611  relid++;
2612 
2613  /* Only plain relations could have primary-key constraints */
2614  if (rte->rtekind != RTE_RELATION)
2615  continue;
2616 
2617  /*
2618  * We must skip inheritance parent tables as some of the child rels
2619  * may cause duplicate rows. This cannot happen with partitioned
2620  * tables, however.
2621  */
2622  if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
2623  continue;
2624 
2625  /* Nothing to do unless this rel has multiple Vars in GROUP BY */
2626  relattnos = groupbyattnos[relid];
2627  if (bms_membership(relattnos) != BMS_MULTIPLE)
2628  continue;
2629 
2630  /*
2631  * Can't remove any columns for this rel if there is no suitable
2632  * (i.e., nondeferrable) primary key constraint.
2633  */
2634  pkattnos = get_primary_key_attnos(rte->relid, false, &constraintOid);
2635  if (pkattnos == NULL)
2636  continue;
2637 
2638  /*
2639  * If the primary key is a proper subset of relattnos then we have
2640  * some items in the GROUP BY that can be removed.
2641  */
2642  if (bms_subset_compare(pkattnos, relattnos) == BMS_SUBSET1)
2643  {
2644  /*
2645  * To easily remember whether we've found anything to do, we don't
2646  * allocate the surplusvars[] array until we find something.
2647  */
2648  if (surplusvars == NULL)
2649  surplusvars = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
2650  (list_length(parse->rtable) + 1));
2651 
2652  /* Remember the attnos of the removable columns */
2653  surplusvars[relid] = bms_difference(relattnos, pkattnos);
2654  }
2655  }
2656 
2657  /*
2658  * If we found any surplus Vars, build a new GROUP BY clause without them.
2659  * (Note: this may leave some TLEs with unreferenced ressortgroupref
2660  * markings, but that's harmless.)
2661  */
2662  if (surplusvars != NULL)
2663  {
2664  List *new_groupby = NIL;
2665 
2666  foreach(lc, parse->groupClause)
2667  {
2669  TargetEntry *tle = get_sortgroupclause_tle(sgc, parse->targetList);
2670  Var *var = (Var *) tle->expr;
2671 
2672  /*
2673  * New list must include non-Vars, outer Vars, and anything not
2674  * marked as surplus.
2675  */
2676  if (!IsA(var, Var) ||
2677  var->varlevelsup > 0 ||
2679  surplusvars[var->varno]))
2680  new_groupby = lappend(new_groupby, sgc);
2681  }
2682 
2683  parse->groupClause = new_groupby;
2684  }
2685 }
2686 
2687 /*
2688  * preprocess_groupclause - do preparatory work on GROUP BY clause
2689  *
2690  * The idea here is to adjust the ordering of the GROUP BY elements
2691  * (which in itself is semantically insignificant) to match ORDER BY,
2692  * thereby allowing a single sort operation to both implement the ORDER BY
2693  * requirement and set up for a Unique step that implements GROUP BY.
2694  *
2695  * In principle it might be interesting to consider other orderings of the
2696  * GROUP BY elements, which could match the sort ordering of other
2697  * possible plans (eg an indexscan) and thereby reduce cost. We don't
2698  * bother with that, though. Hashed grouping will frequently win anyway.
2699  *
2700  * Note: we need no comparable processing of the distinctClause because
2701  * the parser already enforced that that matches ORDER BY.
2702  *
2703  * For grouping sets, the order of items is instead forced to agree with that
2704  * of the grouping set (and items not in the grouping set are skipped). The
2705  * work of sorting the order of grouping set elements to match the ORDER BY if
2706  * possible is done elsewhere.
2707  */
2708 static List *
2710 {
2711  Query *parse = root->parse;
2712  List *new_groupclause = NIL;
2713  bool partial_match;
2714  ListCell *sl;
2715  ListCell *gl;
2716 
2717  /* For grouping sets, we need to force the ordering */
2718  if (force)
2719  {
2720  foreach(sl, force)
2721  {
2722  Index ref = lfirst_int(sl);
2723  SortGroupClause *cl = get_sortgroupref_clause(ref, parse->groupClause);
2724 
2725  new_groupclause = lappend(new_groupclause, cl);
2726  }
2727 
2728  return new_groupclause;
2729  }
2730 
2731  /* If no ORDER BY, nothing useful to do here */
2732  if (parse->sortClause == NIL)
2733  return parse->groupClause;
2734 
2735  /*
2736  * Scan the ORDER BY clause and construct a list of matching GROUP BY
2737  * items, but only as far as we can make a matching prefix.
2738  *
2739  * This code assumes that the sortClause contains no duplicate items.
2740  */
2741  foreach(sl, parse->sortClause)
2742  {
2744 
2745  foreach(gl, parse->groupClause)
2746  {
2748 
2749  if (equal(gc, sc))
2750  {
2751  new_groupclause = lappend(new_groupclause, gc);
2752  break;
2753  }
2754  }
2755  if (gl == NULL)
2756  break; /* no match, so stop scanning */
2757  }
2758 
2759  /* Did we match all of the ORDER BY list, or just some of it? */
2760  partial_match = (sl != NULL);
2761 
2762  /* If no match at all, no point in reordering GROUP BY */
2763  if (new_groupclause == NIL)
2764  return parse->groupClause;
2765 
2766  /*
2767  * Add any remaining GROUP BY items to the new list, but only if we were
2768  * able to make a complete match. In other words, we only rearrange the
2769  * GROUP BY list if the result is that one list is a prefix of the other
2770  * --- otherwise there's no possibility of a common sort. Also, give up
2771  * if there are any non-sortable GROUP BY items, since then there's no
2772  * hope anyway.
2773  */
2774  foreach(gl, parse->groupClause)
2775  {
2777 
2778  if (list_member_ptr(new_groupclause, gc))
2779  continue; /* it matched an ORDER BY item */
2780  if (partial_match)
2781  return parse->groupClause; /* give up, no common sort possible */
2782  if (!OidIsValid(gc->sortop))
2783  return parse->groupClause; /* give up, GROUP BY can't be sorted */
2784  new_groupclause = lappend(new_groupclause, gc);
2785  }
2786 
2787  /* Success --- install the rearranged GROUP BY list */
2788  Assert(list_length(parse->groupClause) == list_length(new_groupclause));
2789  return new_groupclause;
2790 }
2791 
2792 /*
2793  * Extract lists of grouping sets that can be implemented using a single
2794  * rollup-type aggregate pass each. Returns a list of lists of grouping sets.
2795  *
2796  * Input must be sorted with smallest sets first. Result has each sublist
2797  * sorted with smallest sets first.
2798  *
2799  * We want to produce the absolute minimum possible number of lists here to
2800  * avoid excess sorts. Fortunately, there is an algorithm for this; the problem
2801  * of finding the minimal partition of a partially-ordered set into chains
2802  * (which is what we need, taking the list of grouping sets as a poset ordered
2803  * by set inclusion) can be mapped to the problem of finding the maximum
2804  * cardinality matching on a bipartite graph, which is solvable in polynomial
2805  * time with a worst case of no worse than O(n^2.5) and usually much
2806  * better. Since our N is at most 4096, we don't need to consider fallbacks to
2807  * heuristic or approximate methods. (Planning time for a 12-d cube is under
2808  * half a second on my modest system even with optimization off and assertions
2809  * on.)
2810  */
2811 static List *
2813 {
2814  int num_sets_raw = list_length(groupingSets);
2815  int num_empty = 0;
2816  int num_sets = 0; /* distinct sets */
2817  int num_chains = 0;
2818  List *result = NIL;
2819  List **results;
2820  List **orig_sets;
2821  Bitmapset **set_masks;
2822  int *chains;
2823  short **adjacency;
2824  short *adjacency_buf;
2826  int i;
2827  int j;
2828  int j_size;
2829  ListCell *lc1 = list_head(groupingSets);
2830  ListCell *lc;
2831 
2832  /*
2833  * Start by stripping out empty sets. The algorithm doesn't require this,
2834  * but the planner currently needs all empty sets to be returned in the
2835  * first list, so we strip them here and add them back after.
2836  */
2837  while (lc1 && lfirst(lc1) == NIL)
2838  {
2839  ++num_empty;
2840  lc1 = lnext(groupingSets, lc1);
2841  }
2842 
2843  /* bail out now if it turns out that all we had were empty sets. */
2844  if (!lc1)
2845  return list_make1(groupingSets);
2846 
2847  /*----------
2848  * We don't strictly need to remove duplicate sets here, but if we don't,
2849  * they tend to become scattered through the result, which is a bit
2850  * confusing (and irritating if we ever decide to optimize them out).
2851  * So we remove them here and add them back after.
2852  *
2853  * For each non-duplicate set, we fill in the following:
2854  *
2855  * orig_sets[i] = list of the original set lists
2856  * set_masks[i] = bitmapset for testing inclusion
2857  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
2858  *
2859  * chains[i] will be the result group this set is assigned to.
2860  *
2861  * We index all of these from 1 rather than 0 because it is convenient
2862  * to leave 0 free for the NIL node in the graph algorithm.
2863  *----------
2864  */
2865  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
2866  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
2867  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
2868  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
2869 
2870  j_size = 0;
2871  j = 0;
2872  i = 1;
2873 
2874  for_each_cell(lc, groupingSets, lc1)
2875  {
2876  List *candidate = (List *) lfirst(lc);
2877  Bitmapset *candidate_set = NULL;
2878  ListCell *lc2;
2879  int dup_of = 0;
2880 
2881  foreach(lc2, candidate)
2882  {
2883  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
2884  }
2885 
2886  /* we can only be a dup if we're the same length as a previous set */
2887  if (j_size == list_length(candidate))
2888  {
2889  int k;
2890 
2891  for (k = j; k < i; ++k)
2892  {
2893  if (bms_equal(set_masks[k], candidate_set))
2894  {
2895  dup_of = k;
2896  break;
2897  }
2898  }
2899  }
2900  else if (j_size < list_length(candidate))
2901  {
2902  j_size = list_length(candidate);
2903  j = i;
2904  }
2905 
2906  if (dup_of > 0)
2907  {
2908  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
2909  bms_free(candidate_set);
2910  }
2911  else
2912  {
2913  int k;
2914  int n_adj = 0;
2915 
2916  orig_sets[i] = list_make1(candidate);
2917  set_masks[i] = candidate_set;
2918 
2919  /* fill in adjacency list; no need to compare equal-size sets */
2920 
2921  for (k = j - 1; k > 0; --k)
2922  {
2923  if (bms_is_subset(set_masks[k], candidate_set))
2924  adjacency_buf[++n_adj] = k;
2925  }
2926 
2927  if (n_adj > 0)
2928  {
2929  adjacency_buf[0] = n_adj;
2930  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
2931  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
2932  }
2933  else
2934  adjacency[i] = NULL;
2935 
2936  ++i;
2937  }
2938  }
2939 
2940  num_sets = i - 1;
2941 
2942  /*
2943  * Apply the graph matching algorithm to do the work.
2944  */
2945  state = BipartiteMatch(num_sets, num_sets, adjacency);
2946 
2947  /*
2948  * Now, the state->pair* fields have the info we need to assign sets to
2949  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
2950  * pair_vu[v] = u (both will be true, but we check both so that we can do
2951  * it in one pass)
2952  */
2953  chains = palloc0((num_sets + 1) * sizeof(int));
2954 
2955  for (i = 1; i <= num_sets; ++i)
2956  {
2957  int u = state->pair_vu[i];
2958  int v = state->pair_uv[i];
2959 
2960  if (u > 0 && u < i)
2961  chains[i] = chains[u];
2962  else if (v > 0 && v < i)
2963  chains[i] = chains[v];
2964  else
2965  chains[i] = ++num_chains;
2966  }
2967 
2968  /* build result lists. */
2969  results = palloc0((num_chains + 1) * sizeof(List *));
2970 
2971  for (i = 1; i <= num_sets; ++i)
2972  {
2973  int c = chains[i];
2974 
2975  Assert(c > 0);
2976 
2977  results[c] = list_concat(results[c], orig_sets[i]);
2978  }
2979 
2980  /* push any empty sets back on the first list. */
2981  while (num_empty-- > 0)
2982  results[1] = lcons(NIL, results[1]);
2983 
2984  /* make result list */
2985  for (i = 1; i <= num_chains; ++i)
2986  result = lappend(result, results[i]);
2987 
2988  /*
2989  * Free all the things.
2990  *
2991  * (This is over-fussy for small sets but for large sets we could have
2992  * tied up a nontrivial amount of memory.)
2993  */
2995  pfree(results);
2996  pfree(chains);
2997  for (i = 1; i <= num_sets; ++i)
2998  if (adjacency[i])
2999  pfree(adjacency[i]);
3000  pfree(adjacency);
3001  pfree(adjacency_buf);
3002  pfree(orig_sets);
3003  for (i = 1; i <= num_sets; ++i)
3004  bms_free(set_masks[i]);
3005  pfree(set_masks);
3006 
3007  return result;
3008 }
3009 
3010 /*
3011  * Reorder the elements of a list of grouping sets such that they have correct
3012  * prefix relationships. Also inserts the GroupingSetData annotations.
3013  *
3014  * The input must be ordered with smallest sets first; the result is returned
3015  * with largest sets first. Note that the result shares no list substructure
3016  * with the input, so it's safe for the caller to modify it later.
3017  *
3018  * If we're passed in a sortclause, we follow its order of columns to the
3019  * extent possible, to minimize the chance that we add unnecessary sorts.
3020  * (We're trying here to ensure that GROUPING SETS ((a,b,c),(c)) ORDER BY c,b,a
3021  * gets implemented in one pass.)
3022  */
3023 static List *
3024 reorder_grouping_sets(List *groupingsets, List *sortclause)
3025 {
3026  ListCell *lc;
3027  List *previous = NIL;
3028  List *result = NIL;
3029 
3030  foreach(lc, groupingsets)
3031  {
3032  List *candidate = (List *) lfirst(lc);
3033  List *new_elems = list_difference_int(candidate, previous);
3035 
3036  while (list_length(sortclause) > list_length(previous) &&
3037  list_length(new_elems) > 0)
3038  {
3039  SortGroupClause *sc = list_nth(sortclause, list_length(previous));
3040  int ref = sc->tleSortGroupRef;
3041 
3042  if (list_member_int(new_elems, ref))
3043  {
3044  previous = lappend_int(previous, ref);
3045  new_elems = list_delete_int(new_elems, ref);
3046  }
3047  else
3048  {
3049  /* diverged from the sortclause; give up on it */
3050  sortclause = NIL;
3051  break;
3052  }
3053  }
3054 
3055  previous = list_concat(previous, new_elems);
3056 
3057  gs->set = list_copy(previous);
3058  result = lcons(gs, result);
3059  }
3060 
3061  list_free(previous);
3062 
3063  return result;
3064 }
3065 
3066 /*
3067  * Compute query_pathkeys and other pathkeys during plan generation
3068  */
3069 static void
3071 {
3072  Query *parse = root->parse;
3073  standard_qp_extra *qp_extra = (standard_qp_extra *) extra;
3074  List *tlist = root->processed_tlist;
3075  List *activeWindows = qp_extra->activeWindows;
3076 
3077  /*
3078  * Calculate pathkeys that represent grouping/ordering requirements. The
3079  * sortClause is certainly sort-able, but GROUP BY and DISTINCT might not
3080  * be, in which case we just leave their pathkeys empty.
3081  */
3082  if (qp_extra->groupClause &&
3083  grouping_is_sortable(qp_extra->groupClause))
3084  root->group_pathkeys =
3086  qp_extra->groupClause,
3087  tlist);
3088  else
3089  root->group_pathkeys = NIL;
3090 
3091  /* We consider only the first (bottom) window in pathkeys logic */
3092  if (activeWindows != NIL)
3093  {
3094  WindowClause *wc = linitial_node(WindowClause, activeWindows);
3095 
3097  wc,
3098  tlist);
3099  }
3100  else
3101  root->window_pathkeys = NIL;
3102 
3103  if (parse->distinctClause &&
3104  grouping_is_sortable(parse->distinctClause))
3105  root->distinct_pathkeys =
3107  parse->distinctClause,
3108  tlist);
3109  else
3110  root->distinct_pathkeys = NIL;
3111 
3112  root->sort_pathkeys =
3114  parse->sortClause,
3115  tlist);
3116 
3117  /*
3118  * Figure out whether we want a sorted result from query_planner.
3119  *
3120  * If we have a sortable GROUP BY clause, then we want a result sorted
3121  * properly for grouping. Otherwise, if we have window functions to
3122  * evaluate, we try to sort for the first window. Otherwise, if there's a
3123  * sortable DISTINCT clause that's more rigorous than the ORDER BY clause,
3124  * we try to produce output that's sufficiently well sorted for the
3125  * DISTINCT. Otherwise, if there is an ORDER BY clause, we want to sort
3126  * by the ORDER BY clause.
3127  *
3128  * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a superset
3129  * of GROUP BY, it would be tempting to request sort by ORDER BY --- but
3130  * that might just leave us failing to exploit an available sort order at
3131  * all. Needs more thought. The choice for DISTINCT versus ORDER BY is
3132  * much easier, since we know that the parser ensured that one is a
3133  * superset of the other.
3134  */
3135  if (root->group_pathkeys)
3136  root->query_pathkeys = root->group_pathkeys;
3137  else if (root->window_pathkeys)
3138  root->query_pathkeys = root->window_pathkeys;
3139  else if (list_length(root->distinct_pathkeys) >
3140  list_length(root->sort_pathkeys))
3141  root->query_pathkeys = root->distinct_pathkeys;
3142  else if (root->sort_pathkeys)
3143  root->query_pathkeys = root->sort_pathkeys;
3144  else
3145  root->query_pathkeys = NIL;
3146 }
3147 
3148 /*
3149  * Estimate number of groups produced by grouping clauses (1 if not grouping)
3150  *
3151  * path_rows: number of output rows from scan/join step
3152  * gd: grouping sets data including list of grouping sets and their clauses
3153  * target_list: target list containing group clause references
3154  *
3155  * If doing grouping sets, we also annotate the gsets data with the estimates
3156  * for each set and each individual rollup list, with a view to later
3157  * determining whether some combination of them could be hashed instead.
3158  */
3159 static double
3161  double path_rows,
3162  grouping_sets_data *gd,
3163  List *target_list)
3164 {
3165  Query *parse = root->parse;
3166  double dNumGroups;
3167 
3168  if (parse->groupClause)
3169  {
3170  List *groupExprs;
3171 
3172  if (parse->groupingSets)
3173  {
3174  /* Add up the estimates for each grouping set */
3175  ListCell *lc;
3176  ListCell *lc2;
3177 
3178  Assert(gd); /* keep Coverity happy */
3179 
3180  dNumGroups = 0;
3181 
3182  foreach(lc, gd->rollups)
3183  {
3184  RollupData *rollup = lfirst_node(RollupData, lc);
3185  ListCell *lc;
3186 
3187  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3188  target_list);
3189 
3190  rollup->numGroups = 0.0;
3191 
3192  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3193  {
3194  List *gset = (List *) lfirst(lc);
3196  double numGroups = estimate_num_groups(root,
3197  groupExprs,
3198  path_rows,
3199  &gset,
3200  NULL);
3201 
3202  gs->numGroups = numGroups;
3203  rollup->numGroups += numGroups;
3204  }
3205 
3206  dNumGroups += rollup->numGroups;
3207  }
3208 
3209  if (gd->hash_sets_idx)
3210  {
3211  ListCell *lc;
3212 
3213  gd->dNumHashGroups = 0;
3214 
3215  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3216  target_list);
3217 
3218  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3219  {
3220  List *gset = (List *) lfirst(lc);
3222  double numGroups = estimate_num_groups(root,
3223  groupExprs,
3224  path_rows,
3225  &gset,
3226  NULL);
3227 
3228  gs->numGroups = numGroups;
3229  gd->dNumHashGroups += numGroups;
3230  }
3231 
3232  dNumGroups += gd->dNumHashGroups;
3233  }
3234  }
3235  else
3236  {
3237  /* Plain GROUP BY */
3238  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3239  target_list);
3240 
3241  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3242  NULL, NULL);
3243  }
3244  }
3245  else if (parse->groupingSets)
3246  {
3247  /* Empty grouping sets ... one result row for each one */
3248  dNumGroups = list_length(parse->groupingSets);
3249  }
3250  else if (parse->hasAggs || root->hasHavingQual)
3251  {
3252  /* Plain aggregation, one result row */
3253  dNumGroups = 1;
3254  }
3255  else
3256  {
3257  /* Not grouping */
3258  dNumGroups = 1;
3259  }
3260 
3261  return dNumGroups;
3262 }
3263 
3264 /*
3265  * create_grouping_paths
3266  *
3267  * Build a new upperrel containing Paths for grouping and/or aggregation.
3268  * Along the way, we also build an upperrel for Paths which are partially
3269  * grouped and/or aggregated. A partially grouped and/or aggregated path
3270  * needs a FinalizeAggregate node to complete the aggregation. Currently,
3271  * the only partially grouped paths we build are also partial paths; that
3272  * is, they need a Gather and then a FinalizeAggregate.
3273  *
3274  * input_rel: contains the source-data Paths
3275  * target: the pathtarget for the result Paths to compute
3276  * gd: grouping sets data including list of grouping sets and their clauses
3277  *
3278  * Note: all Paths in input_rel are expected to return the target computed
3279  * by make_group_input_target.
3280  */
3281 static RelOptInfo *
3283  RelOptInfo *input_rel,
3284  PathTarget *target,
3285  bool target_parallel_safe,
3286  grouping_sets_data *gd)
3287 {
3288  Query *parse = root->parse;
3289  RelOptInfo *grouped_rel;
3290  RelOptInfo *partially_grouped_rel;
3291  AggClauseCosts agg_costs;
3292 
3293  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3294  get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &agg_costs);
3295 
3296  /*
3297  * Create grouping relation to hold fully aggregated grouping and/or
3298  * aggregation paths.
3299  */
3300  grouped_rel = make_grouping_rel(root, input_rel, target,
3301  target_parallel_safe, parse->havingQual);
3302 
3303  /*
3304  * Create either paths for a degenerate grouping or paths for ordinary
3305  * grouping, as appropriate.
3306  */
3307  if (is_degenerate_grouping(root))
3308  create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3309  else
3310  {
3311  int flags = 0;
3312  GroupPathExtraData extra;
3313 
3314  /*
3315  * Determine whether it's possible to perform sort-based
3316  * implementations of grouping. (Note that if groupClause is empty,
3317  * grouping_is_sortable() is trivially true, and all the
3318  * pathkeys_contained_in() tests will succeed too, so that we'll
3319  * consider every surviving input path.)
3320  *
3321  * If we have grouping sets, we might be able to sort some but not all
3322  * of them; in this case, we need can_sort to be true as long as we
3323  * must consider any sorted-input plan.
3324  */
3325  if ((gd && gd->rollups != NIL)
3326  || grouping_is_sortable(parse->groupClause))
3327  flags |= GROUPING_CAN_USE_SORT;
3328 
3329  /*
3330  * Determine whether we should consider hash-based implementations of
3331  * grouping.
3332  *
3333  * Hashed aggregation only applies if we're grouping. If we have
3334  * grouping sets, some groups might be hashable but others not; in
3335  * this case we set can_hash true as long as there is nothing globally
3336  * preventing us from hashing (and we should therefore consider plans
3337  * with hashes).
3338  *
3339  * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3340  * BY aggregates. (Doing so would imply storing *all* the input
3341  * values in the hash table, and/or running many sorts in parallel,
3342  * either of which seems like a certain loser.) We similarly don't
3343  * support ordered-set aggregates in hashed aggregation, but that case
3344  * is also included in the numOrderedAggs count.
3345  *
3346  * Note: grouping_is_hashable() is much more expensive to check than
3347  * the other gating conditions, so we want to do it last.
3348  */
3349  if ((parse->groupClause != NIL &&
3350  root->numOrderedAggs == 0 &&
3351  (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause))))
3352  flags |= GROUPING_CAN_USE_HASH;
3353 
3354  /*
3355  * Determine whether partial aggregation is possible.
3356  */
3357  if (can_partial_agg(root))
3358  flags |= GROUPING_CAN_PARTIAL_AGG;
3359 
3360  extra.flags = flags;
3361  extra.target_parallel_safe = target_parallel_safe;
3362  extra.havingQual = parse->havingQual;
3363  extra.targetList = parse->targetList;
3364  extra.partial_costs_set = false;
3365 
3366  /*
3367  * Determine whether partitionwise aggregation is in theory possible.
3368  * It can be disabled by the user, and for now, we don't try to
3369  * support grouping sets. create_ordinary_grouping_paths() will check
3370  * additional conditions, such as whether input_rel is partitioned.
3371  */
3372  if (enable_partitionwise_aggregate && !parse->groupingSets)
3374  else
3376 
3377  create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3378  &agg_costs, gd, &extra,
3379  &partially_grouped_rel);
3380  }
3381 
3382  set_cheapest(grouped_rel);
3383  return grouped_rel;
3384 }
3385 
3386 /*
3387  * make_grouping_rel
3388  *
3389  * Create a new grouping rel and set basic properties.
3390  *
3391  * input_rel represents the underlying scan/join relation.
3392  * target is the output expected from the grouping relation.
3393  */
3394 static RelOptInfo *
3396  PathTarget *target, bool target_parallel_safe,
3397  Node *havingQual)
3398 {
3399  RelOptInfo *grouped_rel;
3400 
3401  if (IS_OTHER_REL(input_rel))
3402  {
3403  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG,
3404  input_rel->relids);
3405  grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
3406  }
3407  else
3408  {
3409  /*
3410  * By tradition, the relids set for the main grouping relation is
3411  * NULL. (This could be changed, but might require adjustments
3412  * elsewhere.)
3413  */
3414  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
3415  }
3416 
3417  /* Set target. */
3418  grouped_rel->reltarget = target;
3419 
3420  /*
3421  * If the input relation is not parallel-safe, then the grouped relation
3422  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
3423  * target list and HAVING quals are parallel-safe.
3424  */
3425  if (input_rel->consider_parallel && target_parallel_safe &&
3426  is_parallel_safe(root, (Node *) havingQual))
3427  grouped_rel->consider_parallel = true;
3428 
3429  /*
3430  * If the input rel belongs to a single FDW, so does the grouped rel.
3431  */
3432  grouped_rel->serverid = input_rel->serverid;
3433  grouped_rel->userid = input_rel->userid;
3434  grouped_rel->useridiscurrent = input_rel->useridiscurrent;
3435  grouped_rel->fdwroutine = input_rel->fdwroutine;
3436 
3437  return grouped_rel;
3438 }
3439 
3440 /*
3441  * is_degenerate_grouping
3442  *
3443  * A degenerate grouping is one in which the query has a HAVING qual and/or
3444  * grouping sets, but no aggregates and no GROUP BY (which implies that the
3445  * grouping sets are all empty).
3446  */
3447 static bool
3449 {
3450  Query *parse = root->parse;
3451 
3452  return (root->hasHavingQual || parse->groupingSets) &&
3453  !parse->hasAggs && parse->groupClause == NIL;
3454 }
3455 
3456 /*
3457  * create_degenerate_grouping_paths
3458  *
3459  * When the grouping is degenerate (see is_degenerate_grouping), we are
3460  * supposed to emit either zero or one row for each grouping set depending on
3461  * whether HAVING succeeds. Furthermore, there cannot be any variables in
3462  * either HAVING or the targetlist, so we actually do not need the FROM table
3463  * at all! We can just throw away the plan-so-far and generate a Result node.
3464  * This is a sufficiently unusual corner case that it's not worth contorting
3465  * the structure of this module to avoid having to generate the earlier paths
3466  * in the first place.
3467  */
3468 static void
3470  RelOptInfo *grouped_rel)
3471 {
3472  Query *parse = root->parse;
3473  int nrows;
3474  Path *path;
3475 
3476  nrows = list_length(parse->groupingSets);
3477  if (nrows > 1)
3478  {
3479  /*
3480  * Doesn't seem worthwhile writing code to cons up a generate_series
3481  * or a values scan to emit multiple rows. Instead just make N clones
3482  * and append them. (With a volatile HAVING clause, this means you
3483  * might get between 0 and N output rows. Offhand I think that's
3484  * desired.)
3485  */
3486  List *paths = NIL;
3487 
3488  while (--nrows >= 0)
3489  {
3490  path = (Path *)
3491  create_group_result_path(root, grouped_rel,
3492  grouped_rel->reltarget,
3493  (List *) parse->havingQual);
3494  paths = lappend(paths, path);
3495  }
3496  path = (Path *)
3497  create_append_path(root,
3498  grouped_rel,
3499  paths,
3500  NIL,
3501  NIL,
3502  NULL,
3503  0,
3504  false,
3505  -1);
3506  }
3507  else
3508  {
3509  /* No grouping sets, or just one, so one output row */
3510  path = (Path *)
3511  create_group_result_path(root, grouped_rel,
3512  grouped_rel->reltarget,
3513  (List *) parse->havingQual);
3514  }
3515 
3516  add_path(grouped_rel, path);
3517 }
3518 
3519 /*
3520  * create_ordinary_grouping_paths
3521  *
3522  * Create grouping paths for the ordinary (that is, non-degenerate) case.
3523  *
3524  * We need to consider sorted and hashed aggregation in the same function,
3525  * because otherwise (1) it would be harder to throw an appropriate error
3526  * message if neither way works, and (2) we should not allow hashtable size
3527  * considerations to dissuade us from using hashing if sorting is not possible.
3528  *
3529  * *partially_grouped_rel_p will be set to the partially grouped rel which this
3530  * function creates, or to NULL if it doesn't create one.
3531  */
3532 static void
3534  RelOptInfo *grouped_rel,
3535  const AggClauseCosts *agg_costs,
3536  grouping_sets_data *gd,
3537  GroupPathExtraData *extra,
3538  RelOptInfo **partially_grouped_rel_p)
3539 {
3540  Path *cheapest_path = input_rel->cheapest_total_path;
3541  RelOptInfo *partially_grouped_rel = NULL;
3542  double dNumGroups;
3544 
3545  /*
3546  * If this is the topmost grouping relation or if the parent relation is
3547  * doing some form of partitionwise aggregation, then we may be able to do
3548  * it at this level also. However, if the input relation is not
3549  * partitioned, partitionwise aggregate is impossible.
3550  */
3551  if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
3552  IS_PARTITIONED_REL(input_rel))
3553  {
3554  /*
3555  * If this is the topmost relation or if the parent relation is doing
3556  * full partitionwise aggregation, then we can do full partitionwise
3557  * aggregation provided that the GROUP BY clause contains all of the
3558  * partitioning columns at this level. Otherwise, we can do at most
3559  * partial partitionwise aggregation. But if partial aggregation is
3560  * not supported in general then we can't use it for partitionwise
3561  * aggregation either.
3562  */
3563  if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
3564  group_by_has_partkey(input_rel, extra->targetList,
3565  root->parse->groupClause))
3567  else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3569  else
3571  }
3572 
3573  /*
3574  * Before generating paths for grouped_rel, we first generate any possible
3575  * partially grouped paths; that way, later code can easily consider both
3576  * parallel and non-parallel approaches to grouping.
3577  */
3578  if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3579  {
3580  bool force_rel_creation;
3581 
3582  /*
3583  * If we're doing partitionwise aggregation at this level, force
3584  * creation of a partially_grouped_rel so we can add partitionwise
3585  * paths to it.
3586  */
3587  force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
3588 
3589  partially_grouped_rel =
3591  grouped_rel,
3592  input_rel,
3593  gd,
3594  extra,
3595  force_rel_creation);
3596  }
3597 
3598  /* Set out parameter. */
3599  *partially_grouped_rel_p = partially_grouped_rel;
3600 
3601  /* Apply partitionwise aggregation technique, if possible. */
3602  if (patype != PARTITIONWISE_AGGREGATE_NONE)
3603  create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
3604  partially_grouped_rel, agg_costs,
3605  gd, patype, extra);
3606 
3607  /* If we are doing partial aggregation only, return. */
3609  {
3610  Assert(partially_grouped_rel);
3611 
3612  if (partially_grouped_rel->pathlist)
3613  set_cheapest(partially_grouped_rel);
3614 
3615  return;
3616  }
3617 
3618  /* Gather any partially grouped partial paths. */
3619  if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
3620  {
3621  gather_grouping_paths(root, partially_grouped_rel);
3622  set_cheapest(partially_grouped_rel);
3623  }
3624 
3625  /*
3626  * Estimate number of groups.
3627  */
3628  dNumGroups = get_number_of_groups(root,
3629  cheapest_path->rows,
3630  gd,
3631  extra->targetList);
3632 
3633  /* Build final grouping paths */
3634  add_paths_to_grouping_rel(root, input_rel, grouped_rel,
3635  partially_grouped_rel, agg_costs, gd,
3636  dNumGroups, extra);
3637 
3638  /* Give a helpful error if we failed to find any implementation */
3639  if (grouped_rel->pathlist == NIL)
3640  ereport(ERROR,
3641  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3642  errmsg("could not implement GROUP BY"),
3643  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
3644 
3645  /*
3646  * If there is an FDW that's responsible for all baserels of the query,
3647  * let it consider adding ForeignPaths.
3648  */
3649  if (grouped_rel->fdwroutine &&
3650  grouped_rel->fdwroutine->GetForeignUpperPaths)
3652  input_rel, grouped_rel,
3653  extra);
3654 
3655  /* Let extensions possibly add some more paths */
3657  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
3658  input_rel, grouped_rel,
3659  extra);
3660 }
3661 
3662 /*
3663  * For a given input path, consider the possible ways of doing grouping sets on
3664  * it, by combinations of hashing and sorting. This can be called multiple
3665  * times, so it's important that it not scribble on input. No result is
3666  * returned, but any generated paths are added to grouped_rel.
3667  */
3668 static void
3670  RelOptInfo *grouped_rel,
3671  Path *path,
3672  bool is_sorted,
3673  bool can_hash,
3674  grouping_sets_data *gd,
3675  const AggClauseCosts *agg_costs,
3676  double dNumGroups)
3677 {
3678  Query *parse = root->parse;
3679  Size hash_mem_limit = get_hash_memory_limit();
3680 
3681  /*
3682  * If we're not being offered sorted input, then only consider plans that
3683  * can be done entirely by hashing.
3684  *
3685  * We can hash everything if it looks like it'll fit in hash_mem. But if
3686  * the input is actually sorted despite not being advertised as such, we
3687  * prefer to make use of that in order to use less memory.
3688  *
3689  * If none of the grouping sets are sortable, then ignore the hash_mem
3690  * limit and generate a path anyway, since otherwise we'll just fail.
3691  */
3692  if (!is_sorted)
3693  {
3694  List *new_rollups = NIL;
3695  RollupData *unhashed_rollup = NULL;
3696  List *sets_data;
3697  List *empty_sets_data = NIL;
3698  List *empty_sets = NIL;
3699  ListCell *lc;
3700  ListCell *l_start = list_head(gd->rollups);
3701  AggStrategy strat = AGG_HASHED;
3702  double hashsize;
3703  double exclude_groups = 0.0;
3704 
3705  Assert(can_hash);
3706 
3707  /*
3708  * If the input is coincidentally sorted usefully (which can happen
3709  * even if is_sorted is false, since that only means that our caller
3710  * has set up the sorting for us), then save some hashtable space by
3711  * making use of that. But we need to watch out for degenerate cases:
3712  *
3713  * 1) If there are any empty grouping sets, then group_pathkeys might
3714  * be NIL if all non-empty grouping sets are unsortable. In this case,
3715  * there will be a rollup containing only empty groups, and the
3716  * pathkeys_contained_in test is vacuously true; this is ok.
3717  *
3718  * XXX: the above relies on the fact that group_pathkeys is generated
3719  * from the first rollup. If we add the ability to consider multiple
3720  * sort orders for grouping input, this assumption might fail.
3721  *
3722  * 2) If there are no empty sets and only unsortable sets, then the
3723  * rollups list will be empty (and thus l_start == NULL), and
3724  * group_pathkeys will be NIL; we must ensure that the vacuously-true
3725  * pathkeys_contained_in test doesn't cause us to crash.
3726  */
3727  if (l_start != NULL &&
3729  {
3730  unhashed_rollup = lfirst_node(RollupData, l_start);
3731  exclude_groups = unhashed_rollup->numGroups;
3732  l_start = lnext(gd->rollups, l_start);
3733  }
3734 
3735  hashsize = estimate_hashagg_tablesize(root,
3736  path,
3737  agg_costs,
3738  dNumGroups - exclude_groups);
3739 
3740  /*
3741  * gd->rollups is empty if we have only unsortable columns to work
3742  * with. Override hash_mem in that case; otherwise, we'll rely on the
3743  * sorted-input case to generate usable mixed paths.
3744  */
3745  if (hashsize > hash_mem_limit && gd->rollups)
3746  return; /* nope, won't fit */
3747 
3748  /*
3749  * We need to burst the existing rollups list into individual grouping
3750  * sets and recompute a groupClause for each set.
3751  */
3752  sets_data = list_copy(gd->unsortable_sets);
3753 
3754  for_each_cell(lc, gd->rollups, l_start)
3755  {
3756  RollupData *rollup = lfirst_node(RollupData, lc);
3757 
3758  /*
3759  * If we find an unhashable rollup that's not been skipped by the
3760  * "actually sorted" check above, we can't cope; we'd need sorted
3761  * input (with a different sort order) but we can't get that here.
3762  * So bail out; we'll get a valid path from the is_sorted case
3763  * instead.
3764  *
3765  * The mere presence of empty grouping sets doesn't make a rollup
3766  * unhashable (see preprocess_grouping_sets), we handle those
3767  * specially below.
3768  */
3769  if (!rollup->hashable)
3770  return;
3771 
3772  sets_data = list_concat(sets_data, rollup->gsets_data);
3773  }
3774  foreach(lc, sets_data)
3775  {
3777  List *gset = gs->set;
3778  RollupData *rollup;
3779 
3780  if (gset == NIL)
3781  {
3782  /* Empty grouping sets can't be hashed. */
3783  empty_sets_data = lappend(empty_sets_data, gs);
3784  empty_sets = lappend(empty_sets, NIL);
3785  }
3786  else
3787  {
3788  rollup = makeNode(RollupData);
3789 
3790  rollup->groupClause = preprocess_groupclause(root, gset);
3791  rollup->gsets_data = list_make1(gs);
3792  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
3793  rollup->gsets_data,
3794  gd->tleref_to_colnum_map);
3795  rollup->numGroups = gs->numGroups;
3796  rollup->hashable = true;
3797  rollup->is_hashed = true;
3798  new_rollups = lappend(new_rollups, rollup);
3799  }
3800  }
3801 
3802  /*
3803  * If we didn't find anything nonempty to hash, then bail. We'll
3804  * generate a path from the is_sorted case.
3805  */
3806  if (new_rollups == NIL)
3807  return;
3808 
3809  /*
3810  * If there were empty grouping sets they should have been in the
3811  * first rollup.
3812  */
3813  Assert(!unhashed_rollup || !empty_sets);
3814 
3815  if (unhashed_rollup)
3816  {
3817  new_rollups = lappend(new_rollups, unhashed_rollup);
3818  strat = AGG_MIXED;
3819  }
3820  else if (empty_sets)
3821  {
3822  RollupData *rollup = makeNode(RollupData);
3823 
3824  rollup->groupClause = NIL;
3825  rollup->gsets_data = empty_sets_data;
3826  rollup->gsets = empty_sets;
3827  rollup->numGroups = list_length(empty_sets);
3828  rollup->hashable = false;
3829  rollup->is_hashed = false;
3830  new_rollups = lappend(new_rollups, rollup);
3831  strat = AGG_MIXED;
3832  }
3833 
3834  add_path(grouped_rel, (Path *)
3836  grouped_rel,
3837  path,
3838  (List *) parse->havingQual,
3839  strat,
3840  new_rollups,
3841  agg_costs,
3842  dNumGroups));
3843  return;
3844  }
3845 
3846  /*
3847  * If we have sorted input but nothing we can do with it, bail.
3848  */
3849  if (list_length(gd->rollups) == 0)
3850  return;
3851 
3852  /*
3853  * Given sorted input, we try and make two paths: one sorted and one mixed
3854  * sort/hash. (We need to try both because hashagg might be disabled, or
3855  * some columns might not be sortable.)
3856  *
3857  * can_hash is passed in as false if some obstacle elsewhere (such as
3858  * ordered aggs) means that we shouldn't consider hashing at all.
3859  */
3860  if (can_hash && gd->any_hashable)
3861  {
3862  List *rollups = NIL;
3863  List *hash_sets = list_copy(gd->unsortable_sets);
3864  double availspace = hash_mem_limit;
3865  ListCell *lc;
3866 
3867  /*
3868  * Account first for space needed for groups we can't sort at all.
3869  */
3870  availspace -= estimate_hashagg_tablesize(root,
3871  path,
3872  agg_costs,
3873  gd->dNumHashGroups);
3874 
3875  if (availspace > 0 && list_length(gd->rollups) > 1)
3876  {
3877  double scale;
3878  int num_rollups = list_length(gd->rollups);
3879  int k_capacity;
3880  int *k_weights = palloc(num_rollups * sizeof(int));
3881  Bitmapset *hash_items = NULL;
3882  int i;
3883 
3884  /*
3885  * We treat this as a knapsack problem: the knapsack capacity
3886  * represents hash_mem, the item weights are the estimated memory
3887  * usage of the hashtables needed to implement a single rollup,
3888  * and we really ought to use the cost saving as the item value;
3889  * however, currently the costs assigned to sort nodes don't
3890  * reflect the comparison costs well, and so we treat all items as
3891  * of equal value (each rollup we hash instead saves us one sort).
3892  *
3893  * To use the discrete knapsack, we need to scale the values to a
3894  * reasonably small bounded range. We choose to allow a 5% error
3895  * margin; we have no more than 4096 rollups in the worst possible
3896  * case, which with a 5% error margin will require a bit over 42MB
3897  * of workspace. (Anyone wanting to plan queries that complex had
3898  * better have the memory for it. In more reasonable cases, with
3899  * no more than a couple of dozen rollups, the memory usage will
3900  * be negligible.)
3901  *
3902  * k_capacity is naturally bounded, but we clamp the values for
3903  * scale and weight (below) to avoid overflows or underflows (or
3904  * uselessly trying to use a scale factor less than 1 byte).
3905  */
3906  scale = Max(availspace / (20.0 * num_rollups), 1.0);
3907  k_capacity = (int) floor(availspace / scale);
3908 
3909  /*
3910  * We leave the first rollup out of consideration since it's the
3911  * one that matches the input sort order. We assign indexes "i"
3912  * to only those entries considered for hashing; the second loop,
3913  * below, must use the same condition.
3914  */
3915  i = 0;
3916  for_each_from(lc, gd->rollups, 1)
3917  {
3918  RollupData *rollup = lfirst_node(RollupData, lc);
3919 
3920  if (rollup->hashable)
3921  {
3922  double sz = estimate_hashagg_tablesize(root,
3923  path,
3924  agg_costs,
3925  rollup->numGroups);
3926 
3927  /*
3928  * If sz is enormous, but hash_mem (and hence scale) is
3929  * small, avoid integer overflow here.
3930  */
3931  k_weights[i] = (int) Min(floor(sz / scale),
3932  k_capacity + 1.0);
3933  ++i;
3934  }
3935  }
3936 
3937  /*
3938  * Apply knapsack algorithm; compute the set of items which
3939  * maximizes the value stored (in this case the number of sorts
3940  * saved) while keeping the total size (approximately) within
3941  * capacity.
3942  */
3943  if (i > 0)
3944  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
3945 
3946  if (!bms_is_empty(hash_items))
3947  {
3948  rollups = list_make1(linitial(gd->rollups));
3949 
3950  i = 0;
3951  for_each_from(lc, gd->rollups, 1)
3952  {
3953  RollupData *rollup = lfirst_node(RollupData, lc);
3954 
3955  if (rollup->hashable)
3956  {
3957  if (bms_is_member(i, hash_items))
3958  hash_sets = list_concat(hash_sets,
3959  rollup->gsets_data);
3960  else
3961  rollups = lappend(rollups, rollup);
3962  ++i;
3963  }
3964  else
3965  rollups = lappend(rollups, rollup);
3966  }
3967  }
3968  }
3969 
3970  if (!rollups && hash_sets)
3971  rollups = list_copy(gd->rollups);
3972 
3973  foreach(lc, hash_sets)
3974  {
3976  RollupData *rollup = makeNode(RollupData);
3977 
3978  Assert(gs->set != NIL);
3979 
3980  rollup->groupClause = preprocess_groupclause(root, gs->set);
3981  rollup->gsets_data = list_make1(gs);
3982  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
3983  rollup->gsets_data,
3984  gd->tleref_to_colnum_map);
3985  rollup->numGroups = gs->numGroups;
3986  rollup->hashable = true;
3987  rollup->is_hashed = true;
3988  rollups = lcons(rollup, rollups);
3989  }
3990 
3991  if (rollups)
3992  {
3993  add_path(grouped_rel, (Path *)
3995  grouped_rel,
3996  path,
3997  (List *) parse->havingQual,
3998  AGG_MIXED,
3999  rollups,
4000  agg_costs,
4001  dNumGroups));
4002  }
4003  }
4004 
4005  /*
4006  * Now try the simple sorted case.
4007  */
4008  if (!gd->unsortable_sets)
4009  add_path(grouped_rel, (Path *)
4011  grouped_rel,
4012  path,
4013  (List *) parse->havingQual,
4014  AGG_SORTED,
4015  gd->rollups,
4016  agg_costs,
4017  dNumGroups));
4018 }
4019 
4020 /*
4021  * create_window_paths
4022  *
4023  * Build a new upperrel containing Paths for window-function evaluation.
4024  *
4025  * input_rel: contains the source-data Paths
4026  * input_target: result of make_window_input_target
4027  * output_target: what the topmost WindowAggPath should return
4028  * wflists: result of find_window_functions
4029  * activeWindows: result of select_active_windows
4030  *
4031  * Note: all Paths in input_rel are expected to return input_target.
4032  */
4033 static RelOptInfo *
4035  RelOptInfo *input_rel,
4036  PathTarget *input_target,
4037  PathTarget *output_target,
4038  bool output_target_parallel_safe,
4039  WindowFuncLists *wflists,
4040  List *activeWindows)
4041 {
4042  RelOptInfo *window_rel;
4043  ListCell *lc;
4044 
4045  /* For now, do all work in the (WINDOW, NULL) upperrel */
4046  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4047 
4048  /*
4049  * If the input relation is not parallel-safe, then the window relation
4050  * can't be parallel-safe, either. Otherwise, we need to examine the
4051  * target list and active windows for non-parallel-safe constructs.
4052  */
4053  if (input_rel->consider_parallel && output_target_parallel_safe &&
4054  is_parallel_safe(root, (Node *) activeWindows))
4055  window_rel->consider_parallel = true;
4056 
4057  /*
4058  * If the input rel belongs to a single FDW, so does the window rel.
4059  */
4060  window_rel->serverid = input_rel->serverid;
4061  window_rel->userid = input_rel->userid;
4062  window_rel->useridiscurrent = input_rel->useridiscurrent;
4063  window_rel->fdwroutine = input_rel->fdwroutine;
4064 
4065  /*
4066  * Consider computing window functions starting from the existing
4067  * cheapest-total path (which will likely require a sort) as well as any
4068  * existing paths that satisfy or partially satisfy root->window_pathkeys.
4069  */
4070  foreach(lc, input_rel->pathlist)
4071  {
4072  Path *path = (Path *) lfirst(lc);
4073  int presorted_keys;
4074 
4075  if (path == input_rel->cheapest_total_path ||
4077  &presorted_keys) ||
4078  presorted_keys > 0)
4080  window_rel,
4081  path,
4082  input_target,
4083  output_target,
4084  wflists,
4085  activeWindows);
4086  }
4087 
4088  /*
4089  * If there is an FDW that's responsible for all baserels of the query,
4090  * let it consider adding ForeignPaths.
4091  */
4092  if (window_rel->fdwroutine &&
4093  window_rel->fdwroutine->GetForeignUpperPaths)
4094  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4095  input_rel, window_rel,
4096  NULL);
4097 
4098  /* Let extensions possibly add some more paths */
4100  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4101  input_rel, window_rel, NULL);
4102 
4103  /* Now choose the best path(s) */
4104  set_cheapest(window_rel);
4105 
4106  return window_rel;
4107 }
4108 
4109 /*
4110  * Stack window-function implementation steps atop the given Path, and
4111  * add the result to window_rel.
4112  *
4113  * window_rel: upperrel to contain result
4114  * path: input Path to use (must return input_target)
4115  * input_target: result of make_window_input_target
4116  * output_target: what the topmost WindowAggPath should return
4117  * wflists: result of find_window_functions
4118  * activeWindows: result of select_active_windows
4119  */
4120 static void
4122  RelOptInfo *window_rel,
4123  Path *path,
4124  PathTarget *input_target,
4125  PathTarget *output_target,
4126  WindowFuncLists *wflists,
4127  List *activeWindows)
4128 {
4129  PathTarget *window_target;
4130  ListCell *l;
4131 
4132  /*
4133  * Since each window clause could require a different sort order, we stack
4134  * up a WindowAgg node for each clause, with sort steps between them as
4135  * needed. (We assume that select_active_windows chose a good order for
4136  * executing the clauses in.)
4137  *
4138  * input_target should contain all Vars and Aggs needed for the result.
4139  * (In some cases we wouldn't need to propagate all of these all the way
4140  * to the top, since they might only be needed as inputs to WindowFuncs.
4141  * It's probably not worth trying to optimize that though.) It must also
4142  * contain all window partitioning and sorting expressions, to ensure
4143  * they're computed only once at the bottom of the stack (that's critical
4144  * for volatile functions). As we climb up the stack, we'll add outputs
4145  * for the WindowFuncs computed at each level.
4146  */
4147  window_target = input_target;
4148 
4149  foreach(l, activeWindows)
4150  {
4152  List *window_pathkeys;
4153  int presorted_keys;
4154  bool is_sorted;
4155 
4156  window_pathkeys = make_pathkeys_for_window(root,
4157  wc,
4158  root->processed_tlist);
4159 
4160  is_sorted = pathkeys_count_contained_in(window_pathkeys,
4161  path->pathkeys,
4162  &presorted_keys);
4163 
4164  /* Sort if necessary */
4165  if (!is_sorted)
4166  {
4167  /*
4168  * No presorted keys or incremental sort disabled, just perform a
4169  * complete sort.
4170  */
4171  if (presorted_keys == 0 || !enable_incremental_sort)
4172  path = (Path *) create_sort_path(root, window_rel,
4173  path,
4174  window_pathkeys,
4175  -1.0);
4176  else
4177  {
4178  /*
4179  * Since we have presorted keys and incremental sort is
4180  * enabled, just use incremental sort.
4181  */
4182  path = (Path *) create_incremental_sort_path(root,
4183  window_rel,
4184  path,
4185  window_pathkeys,
4186  presorted_keys,
4187  -1.0);
4188  }
4189  }
4190 
4191  if (lnext(activeWindows, l))
4192  {
4193  /*
4194  * Add the current WindowFuncs to the output target for this
4195  * intermediate WindowAggPath. We must copy window_target to
4196  * avoid changing the previous path's target.
4197  *
4198  * Note: a WindowFunc adds nothing to the target's eval costs; but
4199  * we do need to account for the increase in tlist width.
4200  */
4201  ListCell *lc2;
4202 
4203  window_target = copy_pathtarget(window_target);
4204  foreach(lc2, wflists->windowFuncs[wc->winref])
4205  {
4206  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4207 
4208  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4209  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4210  }
4211  }
4212  else
4213  {
4214  /* Install the goal target in the topmost WindowAgg */
4215  window_target = output_target;
4216  }
4217 
4218  path = (Path *)
4219  create_windowagg_path(root, window_rel, path, window_target,
4220  wflists->windowFuncs[wc->winref],
4221  wc);
4222  }
4223 
4224  add_path(window_rel, path);
4225 }
4226 
4227 /*
4228  * create_distinct_paths
4229  *
4230  * Build a new upperrel containing Paths for SELECT DISTINCT evaluation.
4231  *
4232  * input_rel: contains the source-data Paths
4233  *
4234  * Note: input paths should already compute the desired pathtarget, since
4235  * Sort/Unique won't project anything.
4236  */
4237 static RelOptInfo *
4239 {
4240  RelOptInfo *distinct_rel;
4241 
4242  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4243  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4244 
4245  /*
4246  * We don't compute anything at this level, so distinct_rel will be
4247  * parallel-safe if the input rel is parallel-safe. In particular, if
4248  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4249  * output those expressions, and will not be parallel-safe unless those
4250  * expressions are parallel-safe.
4251  */
4252  distinct_rel->consider_parallel = input_rel->consider_parallel;
4253 
4254  /*
4255  * If the input rel belongs to a single FDW, so does the distinct_rel.
4256  */
4257  distinct_rel->serverid = input_rel->serverid;
4258  distinct_rel->userid = input_rel->userid;
4259  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4260  distinct_rel->fdwroutine = input_rel->fdwroutine;
4261 
4262  /* build distinct paths based on input_rel's pathlist */
4263  create_final_distinct_paths(root, input_rel, distinct_rel);
4264 
4265  /* now build distinct paths based on input_rel's partial_pathlist */
4266  create_partial_distinct_paths(root, input_rel, distinct_rel);
4267 
4268  /* Give a helpful error if we failed to create any paths */
4269  if (distinct_rel->pathlist == NIL)
4270  ereport(ERROR,
4271  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4272  errmsg("could not implement DISTINCT"),
4273  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4274 
4275  /*
4276  * If there is an FDW that's responsible for all baserels of the query,
4277  * let it consider adding ForeignPaths.
4278  */
4279  if (distinct_rel->fdwroutine &&
4280  distinct_rel->fdwroutine->GetForeignUpperPaths)
4281  distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4283  input_rel,
4284  distinct_rel,
4285  NULL);
4286 
4287  /* Let extensions possibly add some more paths */
4289  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
4290  distinct_rel, NULL);
4291 
4292  /* Now choose the best path(s) */
4293  set_cheapest(distinct_rel);
4294 
4295  return distinct_rel;
4296 }
4297 
4298 /*
4299  * create_partial_distinct_paths
4300  *
4301  * Process 'input_rel' partial paths and add unique/aggregate paths to the
4302  * UPPERREL_PARTIAL_DISTINCT rel. For paths created, add Gather/GatherMerge
4303  * paths on top and add a final unique/aggregate path to remove any duplicate
4304  * produced from combining rows from parallel workers.
4305  */
4306 static void
4308  RelOptInfo *final_distinct_rel)
4309 {
4310  RelOptInfo *partial_distinct_rel;
4311  Query *parse;
4312  List *distinctExprs;
4313  double numDistinctRows;
4314  Path *cheapest_partial_path;
4315  ListCell *lc;
4316 
4317  /* nothing to do when there are no partial paths in the input rel */
4318  if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
4319  return;
4320 
4321  parse = root->parse;
4322 
4323  /* can't do parallel DISTINCT ON */
4324  if (parse->hasDistinctOn)
4325  return;
4326 
4327  partial_distinct_rel = fetch_upper_rel(root, UPPERREL_PARTIAL_DISTINCT,
4328  NULL);
4329  partial_distinct_rel->reltarget = root->upper_targets[UPPERREL_PARTIAL_DISTINCT];
4330  partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
4331 
4332  /*
4333  * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
4334  */
4335  partial_distinct_rel->serverid = input_rel->serverid;
4336  partial_distinct_rel->userid = input_rel->userid;
4337  partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4338  partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
4339 
4340  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4341 
4342  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4343  parse->targetList);
4344 
4345  /* estimate how many distinct rows we'll get from each worker */
4346  numDistinctRows = estimate_num_groups(root, distinctExprs,
4347  cheapest_partial_path->rows,
4348  NULL, NULL);
4349 
4350  /* first try adding unique paths atop of sorted paths */
4351  if (grouping_is_sortable(parse->distinctClause))
4352  {
4353  foreach(lc, input_rel->partial_pathlist)
4354  {
4355  Path *path = (Path *) lfirst(lc);
4356 
4358  {
4359  add_partial_path(partial_distinct_rel, (Path *)
4361  partial_distinct_rel,
4362  path,
4364  numDistinctRows));
4365  }
4366  }
4367  }
4368 
4369  /*
4370  * Now try hash aggregate paths, if enabled and hashing is possible. Since
4371  * we're not on the hook to ensure we do our best to create at least one
4372  * path here, we treat enable_hashagg as a hard off-switch rather than the
4373  * slightly softer variant in create_final_distinct_paths.
4374  */
4375  if (enable_hashagg && grouping_is_hashable(parse->distinctClause))
4376  {
4377  add_partial_path(partial_distinct_rel, (Path *)
4378  create_agg_path(root,
4379  partial_distinct_rel,
4380  cheapest_partial_path,
4381  cheapest_partial_path->pathtarget,
4382  AGG_HASHED,
4384  parse->distinctClause,
4385  NIL,
4386  NULL,
4387  numDistinctRows));
4388  }
4389 
4390  /*
4391  * If there is an FDW that's responsible for all baserels of the query,
4392  * let it consider adding ForeignPaths.
4393  */
4394  if (partial_distinct_rel->fdwroutine &&
4395  partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
4396  partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4398  input_rel,
4399  partial_distinct_rel,
4400  NULL);
4401 
4402  /* Let extensions possibly add some more partial paths */
4404  (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
4405  input_rel, partial_distinct_rel, NULL);
4406 
4407  if (partial_distinct_rel->partial_pathlist != NIL)
4408  {
4409  generate_gather_paths(root, partial_distinct_rel, true);
4410  set_cheapest(partial_distinct_rel);
4411 
4412  /*
4413  * Finally, create paths to distinctify the final result. This step
4414  * is needed to remove any duplicates due to combining rows from
4415  * parallel workers.
4416  */
4417  create_final_distinct_paths(root, partial_distinct_rel,
4418  final_distinct_rel);
4419  }
4420 }
4421 
4422 /*
4423  * create_final_distinct_paths
4424  * Create distinct paths in 'distinct_rel' based on 'input_rel' pathlist
4425  *
4426  * input_rel: contains the source-data paths
4427  * distinct_rel: destination relation for storing created paths
4428  */
4429 static RelOptInfo *
4431  RelOptInfo *distinct_rel)
4432 {
4433  Query *parse = root->parse;
4434  Path *cheapest_input_path = input_rel->cheapest_total_path;
4435  double numDistinctRows;
4436  bool allow_hash;
4437  Path *path;
4438  ListCell *lc;
4439 
4440  /* Estimate number of distinct rows there will be */
4441  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4442  root->hasHavingQual)
4443  {
4444  /*
4445  * If there was grouping or aggregation, use the number of input rows
4446  * as the estimated number of DISTINCT rows (ie, assume the input is
4447  * already mostly unique).
4448  */
4449  numDistinctRows = cheapest_input_path->rows;
4450  }
4451  else
4452  {
4453  /*
4454  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4455  */
4456  List *distinctExprs;
4457 
4458  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4459  parse->targetList);
4460  numDistinctRows = estimate_num_groups(root, distinctExprs,
4461  cheapest_input_path->rows,
4462  NULL, NULL);
4463  }
4464 
4465  /*
4466  * Consider sort-based implementations of DISTINCT, if possible.
4467  */
4468  if (grouping_is_sortable(parse->distinctClause))
4469  {
4470  /*
4471  * First, if we have any adequately-presorted paths, just stick a
4472  * Unique node on those. Then consider doing an explicit sort of the
4473  * cheapest input path and Unique'ing that.
4474  *
4475  * When we have DISTINCT ON, we must sort by the more rigorous of
4476  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4477  * Also, if we do have to do an explicit sort, we might as well use
4478  * the more rigorous ordering to avoid a second sort later. (Note
4479  * that the parser will have ensured that one clause is a prefix of
4480  * the other.)
4481  */
4482  List *needed_pathkeys;
4483 
4484  if (parse->hasDistinctOn &&
4486  list_length(root->sort_pathkeys))
4487  needed_pathkeys = root->sort_pathkeys;
4488  else
4489  needed_pathkeys = root->distinct_pathkeys;
4490 
4491  foreach(lc, input_rel->pathlist)
4492  {
4493  Path *path = (Path *) lfirst(lc);
4494 
4495  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4496  {
4497  add_path(distinct_rel, (Path *)
4498  create_upper_unique_path(root, distinct_rel,
4499  path,
4501  numDistinctRows));
4502  }
4503  }
4504 
4505  /* For explicit-sort case, always use the more rigorous clause */
4506  if (list_length(root->distinct_pathkeys) <
4507  list_length(root->sort_pathkeys))
4508  {
4509  needed_pathkeys = root->sort_pathkeys;
4510  /* Assert checks that parser didn't mess up... */
4512  needed_pathkeys));
4513  }
4514  else
4515  needed_pathkeys = root->distinct_pathkeys;
4516 
4517  path = cheapest_input_path;
4518  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4519  path = (Path *) create_sort_path(root, distinct_rel,
4520  path,
4521  needed_pathkeys,
4522  -1.0);
4523 
4524  add_path(distinct_rel, (Path *)
4525  create_upper_unique_path(root, distinct_rel,
4526  path,
4528  numDistinctRows));
4529  }
4530 
4531  /*
4532  * Consider hash-based implementations of DISTINCT, if possible.
4533  *
4534  * If we were not able to make any other types of path, we *must* hash or
4535  * die trying. If we do have other choices, there are two things that
4536  * should prevent selection of hashing: if the query uses DISTINCT ON
4537  * (because it won't really have the expected behavior if we hash), or if
4538  * enable_hashagg is off.
4539  *
4540  * Note: grouping_is_hashable() is much more expensive to check than the
4541  * other gating conditions, so we want to do it last.
4542  */
4543  if (distinct_rel->pathlist == NIL)
4544  allow_hash = true; /* we have no alternatives */
4545  else if (parse->hasDistinctOn || !enable_hashagg)
4546  allow_hash = false; /* policy-based decision not to hash */
4547  else
4548  allow_hash = true; /* default */
4549 
4550  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4551  {
4552  /* Generate hashed aggregate path --- no sort needed */
4553  add_path(distinct_rel, (Path *)
4554  create_agg_path(root,
4555  distinct_rel,
4556  cheapest_input_path,
4557  cheapest_input_path->pathtarget,
4558  AGG_HASHED,
4560  parse->distinctClause,
4561  NIL,
4562  NULL,
4563  numDistinctRows));
4564  }
4565 
4566  return distinct_rel;
4567 }
4568 
4569 /*
4570  * create_ordered_paths
4571  *
4572  * Build a new upperrel containing Paths for ORDER BY evaluation.
4573  *
4574  * All paths in the result must satisfy the ORDER BY ordering.
4575  * The only new paths we need consider are an explicit full sort
4576  * and incremental sort on the cheapest-total existing path.
4577  *
4578  * input_rel: contains the source-data Paths
4579  * target: the output tlist the result Paths must emit
4580  * limit_tuples: estimated bound on the number of output tuples,
4581  * or -1 if no LIMIT or couldn't estimate
4582  *
4583  * XXX This only looks at sort_pathkeys. I wonder if it needs to look at the
4584  * other pathkeys (grouping, ...) like generate_useful_gather_paths.
4585  */
4586 static RelOptInfo *
4588  RelOptInfo *input_rel,
4589  PathTarget *target,
4590  bool target_parallel_safe,
4591  double limit_tuples)
4592 {
4593  Path *cheapest_input_path = input_rel->cheapest_total_path;
4594  RelOptInfo *ordered_rel;
4595  ListCell *lc;
4596 
4597  /* For now, do all work in the (ORDERED, NULL) upperrel */
4598  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4599 
4600  /*
4601  * If the input relation is not parallel-safe, then the ordered relation
4602  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4603  * target list is parallel-safe.
4604  */
4605  if (input_rel->consider_parallel && target_parallel_safe)
4606  ordered_rel->consider_parallel = true;
4607 
4608  /*
4609  * If the input rel belongs to a single FDW, so does the ordered_rel.
4610  */
4611  ordered_rel->serverid = input_rel->serverid;
4612  ordered_rel->userid = input_rel->userid;
4613  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4614  ordered_rel->fdwroutine = input_rel->fdwroutine;
4615 
4616  foreach(lc, input_rel->pathlist)
4617  {
4618  Path *input_path = (Path *) lfirst(lc);
4619  Path *sorted_path = input_path;
4620  bool is_sorted;
4621  int presorted_keys;
4622 
4623  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4624  input_path->pathkeys, &presorted_keys);
4625 
4626  if (is_sorted)
4627  {
4628  /* Use the input path as is, but add a projection step if needed */
4629  if (sorted_path->pathtarget != target)
4630  sorted_path = apply_projection_to_path(root, ordered_rel,
4631  sorted_path, target);
4632 
4633  add_path(ordered_rel, sorted_path);
4634  }
4635  else
4636  {
4637  /*
4638  * Try adding an explicit sort, but only to the cheapest total
4639  * path since a full sort should generally add the same cost to
4640  * all paths.
4641  */
4642  if (input_path == cheapest_input_path)
4643  {
4644  /*
4645  * Sort the cheapest input path. An explicit sort here can
4646  * take advantage of LIMIT.
4647  */
4648  sorted_path = (Path *) create_sort_path(root,
4649  ordered_rel,
4650  input_path,
4651  root->sort_pathkeys,
4652  limit_tuples);
4653  /* Add projection step if needed */
4654  if (sorted_path->pathtarget != target)
4655  sorted_path = apply_projection_to_path(root, ordered_rel,
4656  sorted_path, target);
4657 
4658  add_path(ordered_rel, sorted_path);
4659  }
4660 
4661  /*
4662  * If incremental sort is enabled, then try it as well. Unlike
4663  * with regular sorts, we can't just look at the cheapest path,
4664  * because the cost of incremental sort depends on how well
4665  * presorted the path is. Additionally incremental sort may enable
4666  * a cheaper startup path to win out despite higher total cost.
4667  */
4669  continue;
4670 
4671  /* Likewise, if the path can't be used for incremental sort. */
4672  if (!presorted_keys)
4673  continue;
4674 
4675  /* Also consider incremental sort. */
4676  sorted_path = (Path *) create_incremental_sort_path(root,
4677  ordered_rel,
4678  input_path,
4679  root->sort_pathkeys,
4680  presorted_keys,
4681  limit_tuples);
4682 
4683  /* Add projection step if needed */
4684  if (sorted_path->pathtarget != target)
4685  sorted_path = apply_projection_to_path(root, ordered_rel,
4686  sorted_path, target);
4687 
4688  add_path(ordered_rel, sorted_path);
4689  }
4690  }
4691 
4692  /*
4693  * generate_gather_paths() will have already generated a simple Gather
4694  * path for the best parallel path, if any, and the loop above will have
4695  * considered sorting it. Similarly, generate_gather_paths() will also
4696  * have generated order-preserving Gather Merge plans which can be used
4697  * without sorting if they happen to match the sort_pathkeys, and the loop
4698  * above will have handled those as well. However, there's one more
4699  * possibility: it may make sense to sort the cheapest partial path
4700  * according to the required output order and then use Gather Merge.
4701  */
4702  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
4703  input_rel->partial_pathlist != NIL)
4704  {
4705  Path *cheapest_partial_path;
4706 
4707  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4708 
4709  /*
4710  * If cheapest partial path doesn't need a sort, this is redundant
4711  * with what's already been tried.
4712  */
4714  cheapest_partial_path->pathkeys))
4715  {
4716  Path *path;
4717  double total_groups;
4718 
4719  path = (Path *) create_sort_path(root,
4720  ordered_rel,
4721  cheapest_partial_path,
4722  root->sort_pathkeys,
4723  limit_tuples);
4724 
4725  total_groups = cheapest_partial_path->rows *
4726  cheapest_partial_path->parallel_workers;
4727  path = (Path *)
4728  create_gather_merge_path(root, ordered_rel,
4729  path,
4730  path->pathtarget,
4731  root->sort_pathkeys, NULL,
4732  &total_groups);
4733 
4734  /* Add projection step if needed */
4735  if (path->pathtarget != target)
4736  path = apply_projection_to_path(root, ordered_rel,
4737  path, target);
4738 
4739  add_path(ordered_rel, path);
4740  }
4741 
4742  /*
4743  * Consider incremental sort with a gather merge on partial paths.
4744  *
4745  * We can also skip the entire loop when we only have a single-item
4746  * sort_pathkeys because then we can't possibly have a presorted
4747  * prefix of the list without having the list be fully sorted.
4748  */
4750  {
4751  ListCell *lc;
4752 
4753  foreach(lc, input_rel->partial_pathlist)
4754  {
4755  Path *input_path = (Path *) lfirst(lc);
4756  Path *sorted_path;
4757  bool is_sorted;
4758  int presorted_keys;
4759  double total_groups;
4760 
4761  /*
4762  * We don't care if this is the cheapest partial path - we
4763  * can't simply skip it, because it may be partially sorted in
4764  * which case we want to consider adding incremental sort
4765  * (instead of full sort, which is what happens above).
4766  */
4767 
4768  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4769  input_path->pathkeys,
4770  &presorted_keys);
4771 
4772  /* No point in adding incremental sort on fully sorted paths. */
4773  if (is_sorted)
4774  continue;
4775 
4776  if (presorted_keys == 0)
4777  continue;
4778 
4779  /* Since we have presorted keys, consider incremental sort. */
4780  sorted_path = (Path *) create_incremental_sort_path(root,
4781  ordered_rel,
4782  input_path,
4783  root->sort_pathkeys,
4784  presorted_keys,
4785  limit_tuples);
4786  total_groups = input_path->rows *
4787  input_path->parallel_workers;
4788  sorted_path = (Path *)
4789  create_gather_merge_path(root, ordered_rel,
4790  sorted_path,
4791  sorted_path->pathtarget,
4792  root->sort_pathkeys, NULL,
4793  &total_groups);
4794 
4795  /* Add projection step if needed */
4796  if (sorted_path->pathtarget != target)
4797  sorted_path = apply_projection_to_path(root, ordered_rel,
4798  sorted_path, target);
4799 
4800  add_path(ordered_rel, sorted_path);
4801  }
4802  }
4803  }
4804 
4805  /*
4806  * If there is an FDW that's responsible for all baserels of the query,
4807  * let it consider adding ForeignPaths.
4808  */
4809  if (ordered_rel->fdwroutine &&
4810  ordered_rel->fdwroutine->GetForeignUpperPaths)
4811  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
4812  input_rel, ordered_rel,
4813  NULL);
4814 
4815  /* Let extensions possibly add some more paths */
4817  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
4818  input_rel, ordered_rel, NULL);
4819 
4820  /*
4821  * No need to bother with set_cheapest here; grouping_planner does not
4822  * need us to do it.
4823  */
4824  Assert(ordered_rel->pathlist != NIL);
4825 
4826  return ordered_rel;
4827 }
4828 
4829 
4830 /*
4831  * make_group_input_target
4832  * Generate appropriate PathTarget for initial input to grouping nodes.
4833  *
4834  * If there is grouping or aggregation, the scan/join subplan cannot emit
4835  * the query's final targetlist; for example, it certainly can't emit any
4836  * aggregate function calls. This routine generates the correct target
4837  * for the scan/join subplan.
4838  *
4839  * The query target list passed from the parser already contains entries
4840  * for all ORDER BY and GROUP BY expressions, but it will not have entries
4841  * for variables used only in HAVING clauses; so we need to add those
4842  * variables to the subplan target list. Also, we flatten all expressions
4843  * except GROUP BY items into their component variables; other expressions
4844  * will be computed by the upper plan nodes rather than by the subplan.
4845  * For example, given a query like
4846  * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
4847  * we want to pass this targetlist to the subplan:
4848  * a+b,c,d
4849  * where the a+b target will be used by the Sort/Group steps, and the
4850  * other targets will be used for computing the final results.
4851  *
4852  * 'final_target' is the query's final target list (in PathTarget form)
4853  *
4854  * The result is the PathTarget to be computed by the Paths returned from
4855  * query_planner().
4856  */
4857 static PathTarget *
4859 {
4860  Query *parse = root->parse;
4861  PathTarget *input_target;
4862  List *non_group_cols;
4863  List *non_group_vars;
4864  int i;
4865  ListCell *lc;
4866 
4867  /*
4868  * We must build a target containing all grouping columns, plus any other
4869  * Vars mentioned in the query's targetlist and HAVING qual.
4870  */
4871  input_target = create_empty_pathtarget();
4872  non_group_cols = NIL;
4873 
4874  i = 0;
4875  foreach(lc, final_target->exprs)
4876  {
4877  Expr *expr = (Expr *) lfirst(lc);
4878  Index sgref = get_pathtarget_sortgroupref(final_target, i);
4879 
4880  if (sgref && parse->groupClause &&
4881  get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
4882  {
4883  /*
4884  * It's a grouping column, so add it to the input target as-is.
4885  */
4886  add_column_to_pathtarget(input_target, expr, sgref);
4887  }
4888  else
4889  {
4890  /*
4891  * Non-grouping column, so just remember the expression for later
4892  * call to pull_var_clause.
4893  */
4894  non_group_cols = lappend(non_group_cols, expr);
4895  }
4896 
4897  i++;
4898  }
4899 
4900  /*
4901  * If there's a HAVING clause, we'll need the Vars it uses, too.
4902  */
4903  if (parse->havingQual)
4904  non_group_cols = lappend(non_group_cols, parse->havingQual);
4905 
4906  /*
4907  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
4908  * add them to the input target if not already present. (A Var used
4909  * directly as a GROUP BY item will be present already.) Note this
4910  * includes Vars used in resjunk items, so we are covering the needs of
4911  * ORDER BY and window specifications. Vars used within Aggrefs and
4912  * WindowFuncs will be pulled out here, too.
4913  */
4914  non_group_vars = pull_var_clause((Node *) non_group_cols,
4918  add_new_columns_to_pathtarget(input_target, non_group_vars);
4919 
4920  /* clean up cruft */
4921  list_free(non_group_vars);
4922  list_free(non_group_cols);
4923 
4924  /* XXX this causes some redundant cost calculation ... */
4925  return set_pathtarget_cost_width(root, input_target);
4926 }
4927 
4928 /*
4929  * make_partial_grouping_target
4930  * Generate appropriate PathTarget for output of partial aggregate
4931  * (or partial grouping, if there are no aggregates) nodes.
4932  *
4933  * A partial aggregation node needs to emit all the same aggregates that
4934  * a regular aggregation node would, plus any aggregates used in HAVING;
4935  * except that the Aggref nodes should be marked as partial aggregates.
4936  *
4937  * In addition, we'd better emit any Vars and PlaceHolderVars that are
4938  * used outside of Aggrefs in the aggregation tlist and HAVING. (Presumably,
4939  * these would be Vars that are grouped by or used in grouping expressions.)
4940  *
4941  * grouping_target is the tlist to be emitted by the topmost aggregation step.
4942  * havingQual represents the HAVING clause.
4943  */
4944 static PathTarget *
4946  PathTarget *grouping_target,
4947  Node *havingQual)
4948 {
4949  Query *parse = root->parse;
4950  PathTarget *partial_target;
4951  List *non_group_cols;
4952  List *non_group_exprs;
4953  int i;
4954  ListCell *lc;
4955 
4956  partial_target = create_empty_pathtarget();
4957  non_group_cols = NIL;
4958 
4959  i = 0;
4960  foreach(lc, grouping_target->exprs)
4961  {
4962  Expr *expr = (Expr *) lfirst(lc);
4963  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
4964 
4965  if (sgref && parse->groupClause &&
4966  get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
4967  {
4968  /*
4969  * It's a grouping column, so add it to the partial_target as-is.
4970  * (This allows the upper agg step to repeat the grouping calcs.)
4971  */
4972  add_column_to_pathtarget(partial_target, expr, sgref);
4973  }
4974  else
4975  {
4976  /*
4977  * Non-grouping column, so just remember the expression for later
4978  * call to pull_var_clause.
4979  */
4980  non_group_cols = lappend(non_group_cols, expr);
4981  }
4982 
4983  i++;
4984  }
4985 
4986  /*
4987  * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
4988  */
4989  if (havingQual)
4990  non_group_cols = lappend(non_group_cols, havingQual);
4991 
4992  /*
4993  * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
4994  * non-group cols (plus HAVING), and add them to the partial_target if not
4995  * already present. (An expression used directly as a GROUP BY item will
4996  * be present already.) Note this includes Vars used in resjunk items, so
4997  * we are covering the needs of ORDER BY and window specifications.
4998  */
4999  non_group_exprs = pull_var_clause((Node *) non_group_cols,
5003 
5004  add_new_columns_to_pathtarget(partial_target, non_group_exprs);
5005 
5006  /*
5007  * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5008  * are at the top level of the target list, so we can just scan the list
5009  * rather than recursing through the expression trees.
5010  */
5011  foreach(lc, partial_target->exprs)
5012  {
5013  Aggref *aggref = (Aggref *) lfirst(lc);
5014 
5015  if (IsA(aggref, Aggref))
5016  {
5017  Aggref *newaggref;
5018 
5019  /*
5020  * We shouldn't need to copy the substructure of the Aggref node,
5021  * but flat-copy the node itself to avoid damaging other trees.
5022  */
5023  newaggref = makeNode(Aggref);
5024  memcpy(newaggref, aggref, sizeof(Aggref));
5025 
5026  /* For now, assume serialization is required */
5028 
5029  lfirst(lc) = newaggref;
5030  }
5031  }
5032 
5033  /* clean up cruft */
5034  list_free(non_group_exprs);
5035  list_free(non_group_cols);
5036 
5037  /* XXX this causes some redundant cost calculation ... */
5038  return set_pathtarget_cost_width(root, partial_target);
5039 }
5040 
5041 /*
5042  * mark_partial_aggref
5043  * Adjust an Aggref to make it represent a partial-aggregation step.
5044  *
5045  * The Aggref node is modified in-place; caller must do any copying required.
5046  */
5047 void
5049 {
5050  /* aggtranstype should be computed by this point */
5052  /* ... but aggsplit should still be as the parser left it */
5053  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5054 
5055  /* Mark the Aggref with the intended partial-aggregation mode */
5056  agg->aggsplit = aggsplit;
5057 
5058  /*
5059  * Adjust result type if needed. Normally, a partial aggregate returns
5060  * the aggregate's transition type; but if that's INTERNAL and we're
5061  * serializing, it returns BYTEA instead.
5062  */
5063  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5064  {
5065  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5066  agg->aggtype = BYTEAOID;
5067  else
5068  agg->aggtype = agg->aggtranstype;
5069  }
5070 }
5071 
5072 /*
5073  * postprocess_setop_tlist
5074  * Fix up targetlist returned by plan_set_operations().
5075  *
5076  * We need to transpose sort key info from the orig_tlist into new_tlist.
5077  * NOTE: this would not be good enough if we supported resjunk sort keys
5078  * for results of set operations --- then, we'd need to project a whole
5079  * new tlist to evaluate the resjunk columns. For now, just ereport if we
5080  * find any resjunk columns in orig_tlist.
5081  */
5082 static List *
5083 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
5084 {
5085  ListCell *l;
5086  ListCell *orig_tlist_item = list_head(orig_tlist);
5087 
5088  foreach(l, new_tlist)
5089  {
5090  TargetEntry *new_tle = lfirst_node(TargetEntry, l);
5091  TargetEntry *orig_tle;
5092 
5093  /* ignore resjunk columns in setop result */
5094  if (new_tle->resjunk)
5095  continue;
5096 
5097  Assert(orig_tlist_item != NULL);
5098  orig_tle = lfirst_node(TargetEntry, orig_tlist_item);
5099  orig_tlist_item = lnext(orig_tlist, orig_tlist_item);
5100  if (orig_tle->resjunk) /* should not happen */
5101  elog(ERROR, "resjunk output columns are not implemented");
5102  Assert(new_tle->resno == orig_tle->resno);
5103  new_tle->ressortgroupref = orig_tle->ressortgroupref;
5104  }
5105  if (orig_tlist_item != NULL)
5106  elog(ERROR, "resjunk output columns are not implemented");
5107  return new_tlist;
5108 }
5109 
5110 /*
5111  * select_active_windows
5112  * Create a list of the "active" window clauses (ie, those referenced
5113  * by non-deleted WindowFuncs) in the order they are to be executed.
5114  */
5115 static List *
5117 {
5118  List *windowClause = root->parse->windowClause;
5119  List *result = NIL;
5120  ListCell *lc;
5121  int nActive = 0;
5123  * list_length(windowClause));
5124 
5125  /* First, construct an array of the active windows */
5126  foreach(lc, windowClause)
5127  {
5129 
5130  /* It's only active if wflists shows some related WindowFuncs */
5131  Assert(wc->winref <= wflists->maxWinRef);
5132  if (wflists->windowFuncs[wc->winref] == NIL)
5133  continue;
5134 
5135  actives[nActive].wc = wc; /* original clause */
5136 
5137  /*
5138  * For sorting, we want the list of partition keys followed by the
5139  * list of sort keys. But pathkeys construction will remove duplicates
5140  * between the two, so we can as well (even though we can't detect all
5141  * of the duplicates, since some may come from ECs - that might mean
5142  * we miss optimization chances here). We must, however, ensure that
5143  * the order of entries is preserved with respect to the ones we do
5144  * keep.
5145  *
5146  * partitionClause and orderClause had their own duplicates removed in
5147  * parse analysis, so we're only concerned here with removing
5148  * orderClause entries that also appear in partitionClause.
5149  */
5150  actives[nActive].uniqueOrder =
5152  wc->orderClause);
5153  nActive++;
5154  }
5155 
5156  /*
5157  * Sort active windows by their partitioning/ordering clauses, ignoring
5158  * any framing clauses, so that the windows that need the same sorting are
5159  * adjacent in the list. When we come to generate paths, this will avoid
5160  * inserting additional Sort nodes.
5161  *
5162  * This is how we implement a specific requirement from the SQL standard,
5163  * which says that when two or more windows are order-equivalent (i.e.
5164  * have matching partition and order clauses, even if their names or
5165  * framing clauses differ), then all peer rows must be presented in the
5166  * same order in all of them. If we allowed multiple sort nodes for such
5167  * cases, we'd risk having the peer rows end up in different orders in
5168  * equivalent windows due to sort instability. (See General Rule 4 of
5169  * <window clause> in SQL2008 - SQL2016.)
5170  *
5171  * Additionally, if the entire list of clauses of one window is a prefix
5172  * of another, put first the window with stronger sorting requirements.
5173  * This way we will first sort for stronger window, and won't have to sort
5174  * again for the weaker one.
5175  */
5176  qsort(actives, nActive, sizeof(WindowClauseSortData), common_prefix_cmp);
5177 
5178  /* build ordered list of the original WindowClause nodes */
5179  for (int i = 0; i < nActive; i++)
5180  result = lappend(result, actives[i].wc);
5181 
5182  pfree(actives);
5183 
5184  return result;
5185 }
5186 
5187 /*
5188  * common_prefix_cmp
5189  * QSort comparison function for WindowClauseSortData
5190  *
5191  * Sort the windows by the required sorting clauses. First, compare the sort
5192  * clauses themselves. Second, if one window's clauses are a prefix of another
5193  * one's clauses, put the window with more sort clauses first.
5194  */
5195 static int
5196 common_prefix_cmp(const void *a, const void *b)
5197 {
5198  const WindowClauseSortData *wcsa = a;
5199  const WindowClauseSortData *wcsb = b;
5200  ListCell *item_a;
5201  ListCell *item_b;
5202 
5203  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5204  {
5207 
5208  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5209  return -1;
5210  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5211  return 1;
5212  else if (sca->sortop > scb->sortop)
5213  return -1;
5214  else if (sca->sortop < scb->sortop)
5215  return 1;
5216  else if (sca->nulls_first && !scb->nulls_first)
5217  return -1;
5218  else if (!sca->nulls_first && scb->nulls_first)
5219  return 1;
5220  /* no need to compare eqop, since it is fully determined by sortop */
5221  }
5222 
5223  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5224  return -1;
5225  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5226  return 1;
5227 
5228  return 0;
5229 }
5230 
5231 /*
5232  * make_window_input_target
5233  * Generate appropriate PathTarget for initial input to WindowAgg nodes.
5234  *
5235  * When the query has window functions, this function computes the desired
5236  * target to be computed by the node just below the first WindowAgg.
5237  * This tlist must contain all values needed to evaluate the window functions,
5238  * compute the final target list, and perform any required final sort step.
5239  * If multiple WindowAggs are needed, each intermediate one adds its window
5240  * function results onto this base tlist; only the topmost WindowAgg computes
5241  * the actual desired target list.
5242  *
5243  * This function is much like make_group_input_target, though not quite enough
5244  * like it to share code. As in that function, we flatten most expressions
5245  * into their component variables. But we do not want to flatten window
5246  * PARTITION BY/ORDER BY clauses, since that might result in multiple
5247  * evaluations of them, which would be bad (possibly even resulting in
5248  * inconsistent answers, if they contain volatile functions).
5249  * Also, we must not flatten GROUP BY clauses that were left unflattened by
5250  * make_group_input_target, because we may no longer have access to the
5251  * individual Vars in them.
5252  *
5253  * Another key difference from make_group_input_target is that we don't
5254  * flatten Aggref expressions, since those are to be computed below the
5255  * window functions and just referenced like Vars above that.
5256  *
5257  * 'final_target' is the query's final target list (in PathTarget form)
5258  * 'activeWindows' is the list of active windows previously identified by
5259  * select_active_windows.
5260  *
5261  * The result is the PathTarget to be computed by the plan node immediately
5262  * below the first WindowAgg node.
5263  */
5264 static PathTarget *
5266  PathTarget *final_target,
5267  List *activeWindows)
5268 {
5269  Query *parse = root->parse;
5270  PathTarget *input_target;
5271  Bitmapset *sgrefs;
5272  List *flattenable_cols;
5273  List *flattenable_vars;
5274  int i;
5275  ListCell *lc;
5276 
5277  Assert(parse->hasWindowFuncs);
5278 
5279  /*
5280  * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
5281  * into a bitmapset for convenient reference below.
5282  */
5283  sgrefs = NULL;
5284  foreach(lc, activeWindows)
5285  {
5287  ListCell *lc2;
5288 
5289  foreach(lc2, wc->partitionClause)
5290  {
5292 
5293  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5294  }
5295  foreach(lc2, wc->orderClause)
5296  {
5298 
5299  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5300  }
5301  }
5302 
5303  /* Add in sortgroupref numbers of GROUP BY clauses, too */
5304  foreach(lc, parse->groupClause)
5305  {
5307 
5308  sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
5309  }
5310 
5311  /*
5312  * Construct a target containing all the non-flattenable targetlist items,
5313  * and save aside the others for a moment.
5314  */
5315  input_target = create_empty_pathtarget();
5316  flattenable_cols = NIL;
5317 
5318  i = 0;
5319  foreach(lc, final_target->exprs)
5320  {
5321  Expr *expr = (Expr *) lfirst(lc);
5322  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5323 
5324  /*
5325  * Don't want to deconstruct window clauses or GROUP BY items. (Note
5326  * that such items can't contain window functions, so it's okay to
5327  * compute them below the WindowAgg nodes.)
5328  */
5329  if (sgref != 0 && bms_is_member(sgref, sgrefs))
5330  {
5331  /*
5332  * Don't want to deconstruct this value, so add it to the input
5333  * target as-is.
5334  */
5335  add_column_to_pathtarget(input_target, expr, sgref);
5336  }
5337  else
5338  {
5339  /*
5340  * Column is to be flattened, so just remember the expression for
5341  * later call to pull_var_clause.
5342  */
5343  flattenable_cols = lappend(flattenable_cols, expr);
5344  }
5345 
5346  i++;
5347  }
5348 
5349  /*
5350  * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
5351  * add them to the input target if not already present. (Some might be
5352  * there already because they're used directly as window/group clauses.)
5353  *
5354  * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
5355  * Aggrefs are placed in the Agg node's tlist and not left to be computed
5356  * at higher levels. On the other hand, we should recurse into
5357  * WindowFuncs to make sure their input expressions are available.
5358  */
5359  flattenable_vars = pull_var_clause((Node *) flattenable_cols,
5363  add_new_columns_to_pathtarget(input_target, flattenable_vars);
5364 
5365  /* clean up cruft */
5366  list_free(flattenable_vars);
5367  list_free(flattenable_cols);
5368 
5369  /* XXX this causes some redundant cost calculation ... */
5370  return set_pathtarget_cost_width(root, input_target);
5371 }
5372 
5373 /*
5374  * make_pathkeys_for_window
5375  * Create a pathkeys list describing the required input ordering
5376  * for the given WindowClause.
5377  *
5378  * The required ordering is first the PARTITION keys, then the ORDER keys.
5379  * In the future we might try to implement windowing using hashing, in which
5380  * case the ordering could be relaxed, but for now we always sort.
5381  */
5382 static List *
5384  List *tlist)
5385 {
5386  List *window_pathkeys;
5387  List *window_sortclauses;
5388 
5389  /* Throw error if can't sort */
5391  ereport(ERROR,
5392  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5393  errmsg("could not implement window PARTITION BY"),
5394  errdetail("Window partitioning columns must be of sortable datatypes.")));
5396  ereport(ERROR,
5397  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5398  errmsg("could not implement window ORDER BY"),
5399  errdetail("Window ordering columns must be of sortable datatypes.")));
5400 
5401  /* Okay, make the combined pathkeys */
5402  window_sortclauses = list_concat_copy(wc->partitionClause, wc->orderClause);
5403  window_pathkeys = make_pathkeys_for_sortclauses(root,
5404  window_sortclauses,
5405  tlist);
5406  list_free(window_sortclauses);
5407  return window_pathkeys;
5408 }
5409 
5410 /*
5411  * make_sort_input_target
5412  * Generate appropriate PathTarget for initial input to Sort step.
5413  *
5414  * If the query has ORDER BY, this function chooses the target to be computed
5415  * by the node just below the Sort (and DISTINCT, if any, since Unique can't
5416  * project) steps. This might or might not be identical to the query's final
5417  * output target.
5418  *
5419  * The main argument for keeping the sort-input tlist the same as the final
5420  * is that we avoid a separate projection node (which will be needed if
5421  * they're different, because Sort can't project). However, there are also
5422  * advantages to postponing tlist evaluation till after the Sort: it ensures
5423  * a consistent order of evaluation for any volatile functions in the tlist,
5424  * and if there's also a LIMIT, we can stop the query without ever computing
5425  * tlist functions for later rows, which is beneficial for both volatile and
5426  * expensive functions.
5427  *
5428  * Our current policy is to postpone volatile expressions till after the sort
5429  * unconditionally (assuming that that's possible, ie they are in plain tlist
5430  * columns and not ORDER BY/GROUP BY/DISTINCT columns). We also prefer to
5431  * postpone set-returning expressions, because running them beforehand would
5432  * bloat the sort dataset, and because it might cause unexpected output order
5433  * if the sort isn't stable. However there's a constraint on that: all SRFs
5434  * in the tlist should be evaluated at the same plan step, so that they can
5435  * run in sync in nodeProjectSet. So if any SRFs are in sort columns, we
5436  * mustn't postpone any SRFs. (Note that in principle that policy should
5437  * probably get applied to the group/window input targetlists too, but we
5438  * have not done that historically.) Lastly, expensive expressions are
5439  * postponed if there is a LIMIT, or if root->tuple_fraction shows that
5440  * partial evaluation of the query is possible (if neither is true, we expect
5441  * to have to evaluate the expressions for every row anyway), or if there are
5442  * any volatile or set-returning expressions (since once we've put in a
5443  * projection at all, it won't cost any more to postpone more stuff).
5444  *
5445  * Another issue that could potentially be considered here is that
5446  * evaluating tlist expressions could result in data that's either wider
5447  * or narrower than the input Vars, thus changing the volume of data that
5448  * has to go through the Sort. However, we usually have only a very bad
5449  * idea of the output width of any expression more complex than a Var,
5450  * so for now it seems too risky to try to optimize on that basis.
5451  *
5452  * Note that if we do produce a modified sort-input target, and then the
5453  * query ends up not using an explicit Sort, no particular harm is done:
5454  * we'll initially use the modified target for the preceding path nodes,
5455  * but then change them to the final target with apply_projection_to_path.
5456  * Moreover, in such a case the guarantees about evaluation order of
5457  * volatile functions still hold, since the rows are sorted already.
5458  *
5459  * This function has some things in common with make_group_input_target and
5460  * make_window_input_target, though the detailed rules for what to do are
5461  * different. We never flatten/postpone any grouping or ordering columns;
5462  * those are needed before the sort. If we do flatten a particular
5463  * expression, we leave Aggref and WindowFunc nodes alone, since those were
5464  * computed earlier.
5465  *
5466  * 'final_target' is the query's final target list (in PathTarget form)
5467  * 'have_postponed_srfs' is an output argument, see below
5468  *
5469  * The result is the PathTarget to be computed by the plan node immediately
5470  * below the Sort step (and the Distinct step, if any). This will be
5471  * exactly final_target if we decide a projection step wouldn't be helpful.
5472  *
5473  * In addition, *have_postponed_srfs is set to true if we choose to postpone
5474  * any set-returning functions to after the Sort.
5475  */
5476 static PathTarget *
5478  PathTarget *final_target,
5479  bool *have_postponed_srfs)
5480 {
5481  Query *parse = root->parse;
5482  PathTarget *input_target;
5483  int ncols;
5484  bool *col_is_srf;
5485  bool *postpone_col;
5486  bool have_srf;
5487  bool have_volatile;
5488  bool have_expensive;
5489  bool have_srf_sortcols;
5490  bool postpone_srfs;
5491  List *postponable_cols;
5492  List *postponable_vars;
5493  int i;
5494  ListCell *lc;
5495 
5496  /* Shouldn't get here unless query has ORDER BY */
5497  Assert(parse->sortClause);
5498 
5499  *have_postponed_srfs = false; /* default result */
5500 
5501  /* Inspect tlist and collect per-column information */
5502  ncols = list_length(final_target->exprs);
5503  col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
5504  postpone_col = (bool *) palloc0(ncols * sizeof(bool));
5505  have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
5506 
5507  i = 0;
5508  foreach(lc, final_target->exprs)
5509  {
5510  Expr *expr = (Expr *) lfirst(lc);
5511 
5512  /*
5513  * If the column has a sortgroupref, assume it has to be evaluated
5514  * before sorting. Generally such columns would be ORDER BY, GROUP
5515  * BY, etc targets. One exception is columns that were removed from
5516  * GROUP BY by remove_useless_groupby_columns() ... but those would
5517  * only be Vars anyway. There don't seem to be any cases where it
5518  * would be worth the trouble to double-check.
5519  */
5520  if (get_pathtarget_sortgroupref(final_target, i) == 0)
5521  {
5522  /*
5523  * Check for SRF or volatile functions. Check the SRF case first
5524  * because we must know whether we have any postponed SRFs.
5525  */
5526  if (parse->hasTargetSRFs &&
5527  expression_returns_set((Node *) expr))
5528  {
5529  /* We'll decide below whether these are postponable */
5530  col_is_srf[i] = true;
5531  have_srf = true;
5532  }
5533  else if (contain_volatile_functions((Node *) expr))
5534  {
5535  /* Unconditionally postpone */
5536  postpone_col[i] = true;
5537  have_volatile = true;
5538  }
5539  else
5540  {
5541  /*
5542  * Else check the cost. XXX it's annoying to have to do this
5543  * when set_pathtarget_cost_width() just did it. Refactor to
5544  * allow sharing the work?
5545  */
5546  QualCost cost;
5547 
5548  cost_qual_eval_node(&cost, (Node *) expr, root);
5549 
5550  /*
5551  * We arbitrarily define "expensive" as "more than 10X
5552  * cpu_operator_cost". Note this will take in any PL function
5553  * with default cost.
5554  */
5555  if (cost.per_tuple > 10 * cpu_operator_cost)
5556  {
5557  postpone_col[i] = true;
5558  have_expensive = true;
5559  }
5560  }
5561  }
5562  else
5563  {
5564  /* For sortgroupref cols, just check if any contain SRFs */
5565  if (!have_srf_sortcols &&
5566  parse->hasTargetSRFs &&
5567  expression_returns_set((Node *) expr))
5568  have_srf_sortcols = true;
5569  }
5570 
5571  i++;
5572  }
5573 
5574  /*
5575  * We can postpone SRFs if we have some but none are in sortgroupref cols.
5576  */
5577  postpone_srfs = (have_srf && !have_srf_sortcols);
5578 
5579  /*
5580  * If we don't need a post-sort projection, just return final_target.
5581  */
5582  if (!(postpone_srfs || have_volatile ||
5583  (have_expensive &&
5584  (parse->limitCount || root->tuple_fraction > 0))))
5585  return final_target;
5586 
5587  /*
5588  * Report whether the post-sort projection will contain set-returning
5589  * functions. This is important because it affects whether the Sort can
5590  * rely on the query's LIMIT (if any) to bound the number of rows it needs
5591  * to return.
5592  */
5593  *have_postponed_srfs = postpone_srfs;
5594 
5595  /*
5596  * Construct the sort-input target, taking all non-postponable columns and
5597  * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
5598  * the postponable ones.
5599  */
5600  input_target = create_empty_pathtarget();
5601  postponable_cols = NIL;
5602 
5603  i = 0;
5604  foreach(lc, final_target->exprs)
5605  {
5606  Expr *expr = (Expr *) lfirst(lc);
5607 
5608  if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
5609  postponable_cols = lappend(postponable_cols, expr);
5610  else
5611  add_column_to_pathtarget(input_target, expr,
5612  get_pathtarget_sortgroupref(final_target, i));
5613 
5614  i++;
5615  }
5616 
5617  /*
5618  * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
5619  * postponable columns, and add them to the sort-input target if not
5620  * already present. (Some might be there already.) We mustn't
5621  * deconstruct Aggrefs or WindowFuncs here, since the projection node
5622  * would be unable to recompute them.
5623  */
5624  postponable_vars = pull_var_clause((Node *) postponable_cols,
5628  add_new_columns_to_pathtarget(input_target, postponable_vars);
5629 
5630  /* clean up cruft */
5631  list_free(postponable_vars);
5632  list_free(postponable_cols);
5633 
5634  /* XXX this represents even more redundant cost calculation ... */
5635  return set_pathtarget_cost_width(root, input_target);
5636 }
5637 
5638 /*
5639  * get_cheapest_fractional_path
5640  * Find the cheapest path for retrieving a specified fraction of all
5641  * the tuples expected to be returned by the given relation.
5642  *
5643  * We interpret tuple_fraction the same way as grouping_planner.
5644  *
5645  * We assume set_cheapest() has been run on the given rel.
5646  */
5647 Path *
5648 get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
5649 {
5650  Path *best_path = rel->cheapest_total_path;
5651  ListCell *l;
5652 
5653  /* If all tuples will be retrieved, just return the cheapest-total path */
5654  if (tuple_fraction <= 0.0)
5655  return best_path;
5656 
5657  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5658  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5659  tuple_fraction /= best_path->rows;
5660 
5661  foreach(l, rel->pathlist)
5662  {
5663  Path *path = (Path *) lfirst(l);
5664 
5665  if (path == rel->cheapest_total_path ||
5666  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5667  continue;
5668 
5669  best_path = path;
5670  }
5671 
5672  return best_path;
5673 }
5674 
5675 /*
5676  * adjust_paths_for_srfs
5677  * Fix up the Paths of the given upperrel to handle tSRFs properly.
5678  *
5679  * The executor can only handle set-returning functions that appear at the
5680  * top level of the targetlist of a ProjectSet plan node. If we have any SRFs
5681  * that are not at top level, we need to split up the evaluation into multiple
5682  * plan levels in which each level satisfies this constraint. This function
5683  * modifies each Path of an upperrel that (might) compute any SRFs in its
5684  * output tlist to insert appropriate projection steps.
5685  *
5686  * The given targets and targets_contain_srfs lists are from
5687  * split_pathtarget_at_srfs(). We assume the existing Paths emit the first
5688  * target in targets.
5689  */
5690 static void
5692  List *targets, List *targets_contain_srfs)
5693 {
5694  ListCell *lc;
5695 
5696  Assert(list_length(targets) == list_length(targets_contain_srfs));
5697  Assert(!linitial_int(targets_contain_srfs));
5698 
5699  /* If no SRFs appear at this plan level, nothing to do */
5700  if (list_length(targets) == 1)
5701  return;
5702 
5703  /*
5704  * Stack SRF-evaluation nodes atop each path for the rel.
5705  *
5706  * In principle we should re-run set_cheapest() here to identify the
5707  * cheapest path, but it seems unlikely that adding the same tlist eval
5708  * costs to all the paths would change that, so we don't bother. Instead,
5709  * just assume that the cheapest-startup and cheapest-total paths remain
5710  * so. (There should be no parameterized paths anymore, so we needn't
5711  * worry about updating cheapest_parameterized_paths.)
5712  */
5713  foreach(lc, rel->pathlist)
5714  {
5715  Path *subpath = (Path *) lfirst(lc);
5716  Path *newpath = subpath;
5717  ListCell *lc1,
5718  *lc2;
5719 
5720  Assert(subpath->param_info == NULL);
5721  forboth(lc1, targets, lc2, targets_contain_srfs)
5722  {
5723  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5724  bool contains_srfs = (bool) lfirst_int(lc2);
5725 
5726  /* If this level doesn't contain SRFs, do regular projection */
5727  if (contains_srfs)
5728  newpath = (Path *) create_set_projection_path(root,
5729  rel,
5730  newpath,
5731  thistarget);
5732  else
5733  newpath = (Path *) apply_projection_to_path(root,
5734  rel,
5735  newpath,
5736  thistarget);
5737  }
5738  lfirst(lc) = newpath;
5739  if (subpath == rel->cheapest_startup_path)
5740  rel->cheapest_startup_path = newpath;
5741  if (subpath == rel->cheapest_total_path)
5742  rel->cheapest_total_path = newpath;
5743  }
5744 
5745  /* Likewise for partial paths, if any */
5746  foreach(lc, rel->partial_pathlist)
5747  {
5748  Path *subpath = (Path *) lfirst(lc);
5749  Path *newpath = subpath;
5750  ListCell *lc1,
5751  *lc2;
5752 
5753  Assert(subpath->param_info == NULL);
5754  forboth(lc1, targets, lc2, targets_contain_srfs)
5755  {
5756  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5757  bool contains_srfs = (bool) lfirst_int(lc2);
5758 
5759  /* If this level doesn't contain SRFs, do regular projection */
5760  if (contains_srfs)
5761  newpath = (Path *) create_set_projection_path(root,
5762  rel,
5763  newpath,
5764  thistarget);
5765  else
5766  {
5767  /* avoid apply_projection_to_path, in case of multiple refs */
5768  newpath = (Path *) create_projection_path(root,
5769  rel,
5770  newpath,
5771  thistarget);
5772  }
5773  }
5774  lfirst(lc) = newpath;
5775  }
5776 }
5777 
5778 /*
5779  * expression_planner
5780  * Perform planner's transformations on a standalone expression.
5781  *
5782  * Various utility commands need to evaluate expressions that are not part
5783  * of a plannable query. They can do so using the executor's regular
5784  * expression-execution machinery, but first the expression has to be fed
5785  * through here to transform it from parser output to something executable.
5786  *
5787  * Currently, we disallow sublinks in standalone expressions, so there's no
5788  * real "planning" involved here. (That might not always be true though.)
5789  * What we must do is run eval_const_expressions to ensure that any function
5790  * calls are converted to positional notation and function default arguments
5791  * get inserted. The fact that constant subexpressions get simplified is a
5792  * side-effect that is useful when the expression will get evaluated more than
5793  * once. Also, we must fix operator function IDs.
5794  *
5795  * This does not return any information about dependencies of the expression.
5796  * Hence callers should use the results only for the duration of the current
5797  * query. Callers that would like to cache the results for longer should use
5798  * expression_planner_with_deps, probably via the plancache.
5799  *
5800  * Note: this must not make any damaging changes to the passed-in expression
5801  * tree. (It would actually be okay to apply fix_opfuncids to it, but since
5802  * we first do an expression_tree_mutator-based walk, what is returned will
5803  * be a new node tree.) The result is constructed in the current memory
5804  * context; beware that this can leak a lot of additional stuff there, too.
5805  */
5806 Expr *
5808 {
5809  Node *result;
5810 
5811  /*
5812  * Convert named-argument function calls, insert default arguments and
5813  * simplify constant subexprs
5814  */
5815  result = eval_const_expressions(NULL, (Node *) expr);
5816 
5817  /* Fill in opfuncid values if missing */
5818  fix_opfuncids(result);
5819