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