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