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