PostgreSQL Source Code  git master
planner.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/parallel.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "foreign/fdwapi.h"
#include "jit/jit.h"
#include "lib/bipartite_match.h"
#include "lib/knapsack.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/appendinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/inherit.h"
#include "optimizer/optimizer.h"
#include "optimizer/paramassign.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "parser/analyze.h"
#include "parser/parse_agg.h"
#include "parser/parsetree.h"
#include "partitioning/partdesc.h"
#include "rewrite/rewriteManip.h"
#include "storage/dsm_impl.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
Include dependency graph for planner.c:

Go to the source code of this file.

Data Structures

struct  standard_qp_extra
 
struct  grouping_sets_data
 
struct  WindowClauseSortData
 

Macros

#define EXPRKIND_QUAL   0
 
#define EXPRKIND_TARGET   1
 
#define EXPRKIND_RTFUNC   2
 
#define EXPRKIND_RTFUNC_LATERAL   3
 
#define EXPRKIND_VALUES   4
 
#define EXPRKIND_VALUES_LATERAL   5
 
#define EXPRKIND_LIMIT   6
 
#define EXPRKIND_APPINFO   7
 
#define EXPRKIND_PHV   8
 
#define EXPRKIND_TABLESAMPLE   9
 
#define EXPRKIND_ARBITER_ELEM   10
 
#define EXPRKIND_TABLEFUNC   11
 
#define EXPRKIND_TABLEFUNC_LATERAL   12
 

Functions

static Nodepreprocess_expression (PlannerInfo *root, Node *expr, int kind)
 
static void preprocess_qual_conditions (PlannerInfo *root, Node *jtnode)
 
static void inheritance_planner (PlannerInfo *root)
 
static void grouping_planner (PlannerInfo *root, bool inheritance_update, double tuple_fraction)
 
static grouping_sets_datapreprocess_grouping_sets (PlannerInfo *root)
 
static Listremap_to_groupclause_idx (List *groupClause, List *gsets, int *tleref_to_colnum_map)
 
static void preprocess_rowmarks (PlannerInfo *root)
 
static double preprocess_limit (PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
 
static void remove_useless_groupby_columns (PlannerInfo *root)
 
static Listpreprocess_groupclause (PlannerInfo *root, List *force)
 
static Listextract_rollup_sets (List *groupingSets)
 
static Listreorder_grouping_sets (List *groupingSets, List *sortclause)
 
static void standard_qp_callback (PlannerInfo *root, void *extra)
 
static double get_number_of_groups (PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
 
static RelOptInfocreate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, const AggClauseCosts *agg_costs, grouping_sets_data *gd)
 
static bool is_degenerate_grouping (PlannerInfo *root)
 
static void create_degenerate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
 
static RelOptInfomake_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
 
static void create_ordinary_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
 
static void consider_groupingsets_paths (PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
 
static RelOptInfocreate_window_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, WindowFuncLists *wflists, List *activeWindows)
 
static void create_one_window_path (PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, WindowFuncLists *wflists, List *activeWindows)
 
static RelOptInfocreate_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel)
 
static RelOptInfocreate_ordered_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
 
static PathTargetmake_group_input_target (PlannerInfo *root, PathTarget *final_target)
 
static PathTargetmake_partial_grouping_target (PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
 
static Listpostprocess_setop_tlist (List *new_tlist, List *orig_tlist)
 
static Listselect_active_windows (PlannerInfo *root, WindowFuncLists *wflists)
 
static PathTargetmake_window_input_target (PlannerInfo *root, PathTarget *final_target, List *activeWindows)
 
static Listmake_pathkeys_for_window (PlannerInfo *root, WindowClause *wc, List *tlist)
 
static PathTargetmake_sort_input_target (PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
 
static void adjust_paths_for_srfs (PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
 
static void add_paths_to_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, double dNumGroups, GroupPathExtraData *extra)
 
static RelOptInfocreate_partial_grouping_paths (PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *input_rel, grouping_sets_data *gd, GroupPathExtraData *extra, bool force_rel_creation)
 
static void gather_grouping_paths (PlannerInfo *root, RelOptInfo *rel)
 
static bool can_partial_agg (PlannerInfo *root, const AggClauseCosts *agg_costs)
 
static void apply_scanjoin_target_to_paths (PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
 
static void create_partitionwise_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, PartitionwiseAggregateType patype, GroupPathExtraData *extra)
 
static bool group_by_has_partkey (RelOptInfo *input_rel, List *targetList, List *groupClause)
 
static int common_prefix_cmp (const void *a, const void *b)
 
PlannedStmtplanner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannedStmtstandard_planner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannerInfosubquery_planner (PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
 
Exprpreprocess_phv_expression (PlannerInfo *root, Expr *expr)
 
RowMarkType select_rowmark_type (RangeTblEntry *rte, LockClauseStrength strength)
 
bool limit_needed (Query *parse)
 
void mark_partial_aggref (Aggref *agg, AggSplit aggsplit)
 
Pathget_cheapest_fractional_path (RelOptInfo *rel, double tuple_fraction)
 
Exprexpression_planner (Expr *expr)
 
Exprexpression_planner_with_deps (Expr *expr, List **relationOids, List **invalItems)
 
bool plan_cluster_use_sort (Oid tableOid, Oid indexOid)
 
int plan_create_index_workers (Oid tableOid, Oid indexOid)
 

Variables

double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION
 
int force_parallel_mode = FORCE_PARALLEL_OFF
 
bool parallel_leader_participation = true
 
planner_hook_type planner_hook = NULL
 
create_upper_paths_hook_type create_upper_paths_hook = NULL
 

Macro Definition Documentation

◆ EXPRKIND_APPINFO

#define EXPRKIND_APPINFO   7

Definition at line 88 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 91 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 87 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 89 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 81 of file planner.c.

Referenced by preprocess_expression(), preprocess_qual_conditions(), and subquery_planner().

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 83 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 92 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 93 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 90 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 82 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 85 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 86 of file planner.c.

Referenced by subquery_planner().

Function Documentation

◆ add_paths_to_grouping_rel()

static void add_paths_to_grouping_rel ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
RelOptInfo partially_grouped_rel,
const AggClauseCosts agg_costs,
grouping_sets_data gd,
double  dNumGroups,
GroupPathExtraData extra 
)
static

Definition at line 6377 of file planner.c.

References add_path(), GroupPathExtraData::agg_final_costs, AGG_HASHED, AGG_PLAIN, AGG_SORTED, AGGSPLIT_FINAL_DESERIAL, AGGSPLIT_SIMPLE, Assert, RelOptInfo::cheapest_total_path, consider_groupingsets_paths(), create_agg_path(), create_group_path(), create_sort_path(), estimate_hashagg_tablesize(), GroupPathExtraData::flags, gather_grouping_paths(), PlannerInfo::group_pathkeys, Query::groupClause, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, Query::groupingSets, Query::hasAggs, GroupPathExtraData::havingQual, lfirst, NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, RelOptInfo::reltarget, and work_mem.

Referenced by create_ordinary_grouping_paths().

6383 {
6384  Query *parse = root->parse;
6385  Path *cheapest_path = input_rel->cheapest_total_path;
6386  ListCell *lc;
6387  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6388  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6389  List *havingQual = (List *) extra->havingQual;
6390  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6391 
6392  if (can_sort)
6393  {
6394  /*
6395  * Use any available suitably-sorted path as input, and also consider
6396  * sorting the cheapest-total path.
6397  */
6398  foreach(lc, input_rel->pathlist)
6399  {
6400  Path *path = (Path *) lfirst(lc);
6401  bool is_sorted;
6402 
6403  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6404  path->pathkeys);
6405  if (path == cheapest_path || is_sorted)
6406  {
6407  /* Sort the cheapest-total path if it isn't already sorted */
6408  if (!is_sorted)
6409  path = (Path *) create_sort_path(root,
6410  grouped_rel,
6411  path,
6412  root->group_pathkeys,
6413  -1.0);
6414 
6415  /* Now decide what to stick atop it */
6416  if (parse->groupingSets)
6417  {
6418  consider_groupingsets_paths(root, grouped_rel,
6419  path, true, can_hash,
6420  gd, agg_costs, dNumGroups);
6421  }
6422  else if (parse->hasAggs)
6423  {
6424  /*
6425  * We have aggregation, possibly with plain GROUP BY. Make
6426  * an AggPath.
6427  */
6428  add_path(grouped_rel, (Path *)
6429  create_agg_path(root,
6430  grouped_rel,
6431  path,
6432  grouped_rel->reltarget,
6433  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6435  parse->groupClause,
6436  havingQual,
6437  agg_costs,
6438  dNumGroups));
6439  }
6440  else if (parse->groupClause)
6441  {
6442  /*
6443  * We have GROUP BY without aggregation or grouping sets.
6444  * Make a GroupPath.
6445  */
6446  add_path(grouped_rel, (Path *)
6447  create_group_path(root,
6448  grouped_rel,
6449  path,
6450  parse->groupClause,
6451  havingQual,
6452  dNumGroups));
6453  }
6454  else
6455  {
6456  /* Other cases should have been handled above */
6457  Assert(false);
6458  }
6459  }
6460  }
6461 
6462  /*
6463  * Instead of operating directly on the input relation, we can
6464  * consider finalizing a partially aggregated path.
6465  */
6466  if (partially_grouped_rel != NULL)
6467  {
6468  foreach(lc, partially_grouped_rel->pathlist)
6469  {
6470  Path *path = (Path *) lfirst(lc);
6471 
6472  /*
6473  * Insert a Sort node, if required. But there's no point in
6474  * sorting anything but the cheapest path.
6475  */
6476  if (!pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
6477  {
6478  if (path != partially_grouped_rel->cheapest_total_path)
6479  continue;
6480  path = (Path *) create_sort_path(root,
6481  grouped_rel,
6482  path,
6483  root->group_pathkeys,
6484  -1.0);
6485  }
6486 
6487  if (parse->hasAggs)
6488  add_path(grouped_rel, (Path *)
6489  create_agg_path(root,
6490  grouped_rel,
6491  path,
6492  grouped_rel->reltarget,
6493  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6495  parse->groupClause,
6496  havingQual,
6497  agg_final_costs,
6498  dNumGroups));
6499  else
6500  add_path(grouped_rel, (Path *)
6501  create_group_path(root,
6502  grouped_rel,
6503  path,
6504  parse->groupClause,
6505  havingQual,
6506  dNumGroups));
6507  }
6508  }
6509  }
6510 
6511  if (can_hash)
6512  {
6513  double hashaggtablesize;
6514 
6515  if (parse->groupingSets)
6516  {
6517  /*
6518  * Try for a hash-only groupingsets path over unsorted input.
6519  */
6520  consider_groupingsets_paths(root, grouped_rel,
6521  cheapest_path, false, true,
6522  gd, agg_costs, dNumGroups);
6523  }
6524  else
6525  {
6526  hashaggtablesize = estimate_hashagg_tablesize(cheapest_path,
6527  agg_costs,
6528  dNumGroups);
6529 
6530  /*
6531  * Provided that the estimated size of the hashtable does not
6532  * exceed work_mem, we'll generate a HashAgg Path, although if we
6533  * were unable to sort above, then we'd better generate a Path, so
6534  * that we at least have one.
6535  */
6536  if (hashaggtablesize < work_mem * 1024L ||
6537  grouped_rel->pathlist == NIL)
6538  {
6539  /*
6540  * We just need an Agg over the cheapest-total input path,
6541  * since input order won't matter.
6542  */
6543  add_path(grouped_rel, (Path *)
6544  create_agg_path(root, grouped_rel,
6545  cheapest_path,
6546  grouped_rel->reltarget,
6547  AGG_HASHED,
6549  parse->groupClause,
6550  havingQual,
6551  agg_costs,
6552  dNumGroups));
6553  }
6554  }
6555 
6556  /*
6557  * Generate a Finalize HashAgg Path atop of the cheapest partially
6558  * grouped path, assuming there is one. Once again, we'll only do this
6559  * if it looks as though the hash table won't exceed work_mem.
6560  */
6561  if (partially_grouped_rel && partially_grouped_rel->pathlist)
6562  {
6563  Path *path = partially_grouped_rel->cheapest_total_path;
6564 
6565  hashaggtablesize = estimate_hashagg_tablesize(path,
6566  agg_final_costs,
6567  dNumGroups);
6568 
6569  if (hashaggtablesize < work_mem * 1024L)
6570  add_path(grouped_rel, (Path *)
6571  create_agg_path(root,
6572  grouped_rel,
6573  path,
6574  grouped_rel->reltarget,
6575  AGG_HASHED,
6577  parse->groupClause,
6578  havingQual,
6579  agg_final_costs,
6580  dNumGroups));
6581  }
6582  }
6583 
6584  /*
6585  * When partitionwise aggregate is used, we might have fully aggregated
6586  * paths in the partial pathlist, because add_paths_to_append_rel() will
6587  * consider a path for grouped_rel consisting of a Parallel Append of
6588  * non-partial paths from each child.
6589  */
6590  if (grouped_rel->partial_pathlist != NIL)
6591  gather_grouping_paths(root, grouped_rel);
6592 }
List * group_pathkeys
Definition: pathnodes.h:300
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static void consider_groupingsets_paths(PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:4191
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6914
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
List * partial_pathlist
Definition: pathnodes.h:659
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2407
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition: pathnode.c:2921
struct Path * cheapest_total_path
Definition: pathnodes.h:661
double estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: selfuncs.c:3526
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
int work_mem
Definition: globals.c:121
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2408
List * pathkeys
Definition: pathnodes.h:1130
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * groupClause
Definition: parsenodes.h:148
List * pathlist
Definition: pathnodes.h:657
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2810
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2448
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:654
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ adjust_paths_for_srfs()

static void adjust_paths_for_srfs ( PlannerInfo root,
RelOptInfo rel,
List targets,
List targets_contain_srfs 
)
static

Definition at line 5935 of file planner.c.

References apply_projection_to_path(), Assert, RelOptInfo::cheapest_startup_path, RelOptInfo::cheapest_total_path, create_projection_path(), create_set_projection_path(), forboth, lfirst, lfirst_int, lfirst_node, linitial_int, list_length(), Path::param_info, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, and subpath().

Referenced by apply_scanjoin_target_to_paths(), and grouping_planner().

5937 {
5938  ListCell *lc;
5939 
5940  Assert(list_length(targets) == list_length(targets_contain_srfs));
5941  Assert(!linitial_int(targets_contain_srfs));
5942 
5943  /* If no SRFs appear at this plan level, nothing to do */
5944  if (list_length(targets) == 1)
5945  return;
5946 
5947  /*
5948  * Stack SRF-evaluation nodes atop each path for the rel.
5949  *
5950  * In principle we should re-run set_cheapest() here to identify the
5951  * cheapest path, but it seems unlikely that adding the same tlist eval
5952  * costs to all the paths would change that, so we don't bother. Instead,
5953  * just assume that the cheapest-startup and cheapest-total paths remain
5954  * so. (There should be no parameterized paths anymore, so we needn't
5955  * worry about updating cheapest_parameterized_paths.)
5956  */
5957  foreach(lc, rel->pathlist)
5958  {
5959  Path *subpath = (Path *) lfirst(lc);
5960  Path *newpath = subpath;
5961  ListCell *lc1,
5962  *lc2;
5963 
5964  Assert(subpath->param_info == NULL);
5965  forboth(lc1, targets, lc2, targets_contain_srfs)
5966  {
5967  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5968  bool contains_srfs = (bool) lfirst_int(lc2);
5969 
5970  /* If this level doesn't contain SRFs, do regular projection */
5971  if (contains_srfs)
5972  newpath = (Path *) create_set_projection_path(root,
5973  rel,
5974  newpath,
5975  thistarget);
5976  else
5977  newpath = (Path *) apply_projection_to_path(root,
5978  rel,
5979  newpath,
5980  thistarget);
5981  }
5982  lfirst(lc) = newpath;
5983  if (subpath == rel->cheapest_startup_path)
5984  rel->cheapest_startup_path = newpath;
5985  if (subpath == rel->cheapest_total_path)
5986  rel->cheapest_total_path = newpath;
5987  }
5988 
5989  /* Likewise for partial paths, if any */
5990  foreach(lc, rel->partial_pathlist)
5991  {
5992  Path *subpath = (Path *) lfirst(lc);
5993  Path *newpath = subpath;
5994  ListCell *lc1,
5995  *lc2;
5996 
5997  Assert(subpath->param_info == NULL);
5998  forboth(lc1, targets, lc2, targets_contain_srfs)
5999  {
6000  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6001  bool contains_srfs = (bool) lfirst_int(lc2);
6002 
6003  /* If this level doesn't contain SRFs, do regular projection */
6004  if (contains_srfs)
6005  newpath = (Path *) create_set_projection_path(root,
6006  rel,
6007  newpath,
6008  thistarget);
6009  else
6010  {
6011  /* avoid apply_projection_to_path, in case of multiple refs */
6012  newpath = (Path *) create_projection_path(root,
6013  rel,
6014  newpath,
6015  thistarget);
6016  }
6017  }
6018  lfirst(lc) = newpath;
6019  }
6020 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2610
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
struct Path * cheapest_startup_path
Definition: pathnodes.h:660
ParamPathInfo * param_info
Definition: pathnodes.h:1119
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2519
List * partial_pathlist
Definition: pathnodes.h:659
#define linitial_int(l)
Definition: pg_list.h:196
#define lfirst_int(lc)
Definition: pg_list.h:191
#define lfirst_node(type, lc)
Definition: pg_list.h:193
struct Path * cheapest_total_path
Definition: pathnodes.h:661
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2699
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
List * pathlist
Definition: pathnodes.h:657
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
unsigned char bool
Definition: c.h:309

◆ apply_scanjoin_target_to_paths()

static void apply_scanjoin_target_to_paths ( PlannerInfo root,
RelOptInfo rel,
List scanjoin_targets,
List scanjoin_targets_contain_srfs,
bool  scanjoin_target_parallel_safe,
bool  tlist_same_exprs 
)
static

Definition at line 6996 of file planner.c.

References add_paths_to_append_rel(), adjust_appendrel_attrs(), adjust_paths_for_srfs(), Assert, check_stack_depth(), RelOptInfo::consider_parallel, copy_pathtarget(), create_projection_path(), PathTarget::exprs, find_appinfos_by_relids(), generate_gather_paths(), Query::hasTargetSRFs, IS_DUMMY_REL, IS_OTHER_REL, IS_PARTITIONED_REL, lappend(), lfirst, lfirst_node, linitial_node, llast_node, NIL, RelOptInfo::nparts, Path::param_info, PlannerInfo::parse, RelOptInfo::part_rels, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, Path::pathtarget, pfree(), RelOptInfo::relids, RelOptInfo::reltarget, set_cheapest(), PathTarget::sortgrouprefs, and subpath().

Referenced by grouping_planner().

7002 {
7003  bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
7004  PathTarget *scanjoin_target;
7005  ListCell *lc;
7006 
7007  /* This recurses, so be paranoid. */
7009 
7010  /*
7011  * If the rel is partitioned, we want to drop its existing paths and
7012  * generate new ones. This function would still be correct if we kept the
7013  * existing paths: we'd modify them to generate the correct target above
7014  * the partitioning Append, and then they'd compete on cost with paths
7015  * generating the target below the Append. However, in our current cost
7016  * model the latter way is always the same or cheaper cost, so modifying
7017  * the existing paths would just be useless work. Moreover, when the cost
7018  * is the same, varying roundoff errors might sometimes allow an existing
7019  * path to be picked, resulting in undesirable cross-platform plan
7020  * variations. So we drop old paths and thereby force the work to be done
7021  * below the Append, except in the case of a non-parallel-safe target.
7022  *
7023  * Some care is needed, because we have to allow generate_gather_paths to
7024  * see the old partial paths in the next stanza. Hence, zap the main
7025  * pathlist here, then allow generate_gather_paths to add path(s) to the
7026  * main list, and finally zap the partial pathlist.
7027  */
7028  if (rel_is_partitioned)
7029  rel->pathlist = NIL;
7030 
7031  /*
7032  * If the scan/join target is not parallel-safe, partial paths cannot
7033  * generate it.
7034  */
7035  if (!scanjoin_target_parallel_safe)
7036  {
7037  /*
7038  * Since we can't generate the final scan/join target in parallel
7039  * workers, this is our last opportunity to use any partial paths that
7040  * exist; so build Gather path(s) that use them and emit whatever the
7041  * current reltarget is. We don't do this in the case where the
7042  * target is parallel-safe, since we will be able to generate superior
7043  * paths by doing it after the final scan/join target has been
7044  * applied.
7045  */
7046  generate_gather_paths(root, rel, false);
7047 
7048  /* Can't use parallel query above this level. */
7049  rel->partial_pathlist = NIL;
7050  rel->consider_parallel = false;
7051  }
7052 
7053  /* Finish dropping old paths for a partitioned rel, per comment above */
7054  if (rel_is_partitioned)
7055  rel->partial_pathlist = NIL;
7056 
7057  /* Extract SRF-free scan/join target. */
7058  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
7059 
7060  /*
7061  * Apply the SRF-free scan/join target to each existing path.
7062  *
7063  * If the tlist exprs are the same, we can just inject the sortgroupref
7064  * information into the existing pathtargets. Otherwise, replace each
7065  * path with a projection path that generates the SRF-free scan/join
7066  * target. This can't change the ordering of paths within rel->pathlist,
7067  * so we just modify the list in place.
7068  */
7069  foreach(lc, rel->pathlist)
7070  {
7071  Path *subpath = (Path *) lfirst(lc);
7072 
7073  /* Shouldn't have any parameterized paths anymore */
7074  Assert(subpath->param_info == NULL);
7075 
7076  if (tlist_same_exprs)
7077  subpath->pathtarget->sortgrouprefs =
7078  scanjoin_target->sortgrouprefs;
7079  else
7080  {
7081  Path *newpath;
7082 
7083  newpath = (Path *) create_projection_path(root, rel, subpath,
7084  scanjoin_target);
7085  lfirst(lc) = newpath;
7086  }
7087  }
7088 
7089  /* Likewise adjust the targets for any partial paths. */
7090  foreach(lc, rel->partial_pathlist)
7091  {
7092  Path *subpath = (Path *) lfirst(lc);
7093 
7094  /* Shouldn't have any parameterized paths anymore */
7095  Assert(subpath->param_info == NULL);
7096 
7097  if (tlist_same_exprs)
7098  subpath->pathtarget->sortgrouprefs =
7099  scanjoin_target->sortgrouprefs;
7100  else
7101  {
7102  Path *newpath;
7103 
7104  newpath = (Path *) create_projection_path(root, rel, subpath,
7105  scanjoin_target);
7106  lfirst(lc) = newpath;
7107  }
7108  }
7109 
7110  /*
7111  * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
7112  * atop each existing path. (Note that this function doesn't look at the
7113  * cheapest-path fields, which is a good thing because they're bogus right
7114  * now.)
7115  */
7116  if (root->parse->hasTargetSRFs)
7117  adjust_paths_for_srfs(root, rel,
7118  scanjoin_targets,
7119  scanjoin_targets_contain_srfs);
7120 
7121  /*
7122  * Update the rel's target to be the final (with SRFs) scan/join target.
7123  * This now matches the actual output of all the paths, and we might get
7124  * confused in createplan.c if they don't agree. We must do this now so
7125  * that any append paths made in the next part will use the correct
7126  * pathtarget (cf. create_append_path).
7127  *
7128  * Note that this is also necessary if GetForeignUpperPaths() gets called
7129  * on the final scan/join relation or on any of its children, since the
7130  * FDW might look at the rel's target to create ForeignPaths.
7131  */
7132  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
7133 
7134  /*
7135  * If the relation is partitioned, recursively apply the scan/join target
7136  * to all partitions, and generate brand-new Append paths in which the
7137  * scan/join target is computed below the Append rather than above it.
7138  * Since Append is not projection-capable, that might save a separate
7139  * Result node, and it also is important for partitionwise aggregate.
7140  */
7141  if (rel_is_partitioned)
7142  {
7143  List *live_children = NIL;
7144  int partition_idx;
7145 
7146  /* Adjust each partition. */
7147  for (partition_idx = 0; partition_idx < rel->nparts; partition_idx++)
7148  {
7149  RelOptInfo *child_rel = rel->part_rels[partition_idx];
7150  AppendRelInfo **appinfos;
7151  int nappinfos;
7152  List *child_scanjoin_targets = NIL;
7153  ListCell *lc;
7154 
7155  /* Pruned or dummy children can be ignored. */
7156  if (child_rel == NULL || IS_DUMMY_REL(child_rel))
7157  continue;
7158 
7159  /* Translate scan/join targets for this child. */
7160  appinfos = find_appinfos_by_relids(root, child_rel->relids,
7161  &nappinfos);
7162  foreach(lc, scanjoin_targets)
7163  {
7164  PathTarget *target = lfirst_node(PathTarget, lc);
7165 
7166  target = copy_pathtarget(target);
7167  target->exprs = (List *)
7169  (Node *) target->exprs,
7170  nappinfos, appinfos);
7171  child_scanjoin_targets = lappend(child_scanjoin_targets,
7172  target);
7173  }
7174  pfree(appinfos);
7175 
7176  /* Recursion does the real work. */
7177  apply_scanjoin_target_to_paths(root, child_rel,
7178  child_scanjoin_targets,
7179  scanjoin_targets_contain_srfs,
7180  scanjoin_target_parallel_safe,
7182 
7183  /* Save non-dummy children for Append paths. */
7184  if (!IS_DUMMY_REL(child_rel))
7185  live_children = lappend(live_children, child_rel);
7186  }
7187 
7188  /* Build new paths for this relation by appending child paths. */
7189  add_paths_to_append_rel(root, rel, live_children);
7190  }
7191 
7192  /*
7193  * Consider generating Gather or Gather Merge paths. We must only do this
7194  * if the relation is parallel safe, and we don't do it for child rels to
7195  * avoid creating multiple Gather nodes within the same plan. We must do
7196  * this after all paths have been generated and before set_cheapest, since
7197  * one of the generated paths may turn out to be the cheapest one.
7198  */
7199  if (rel->consider_parallel && !IS_OTHER_REL(rel))
7200  generate_gather_paths(root, rel, false);
7201 
7202  /*
7203  * Reassess which paths are the cheapest, now that we've potentially added
7204  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
7205  * this relation.
7206  */
7207  set_cheapest(rel);
7208 }
#define NIL
Definition: pg_list.h:65
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:672
static void apply_scanjoin_target_to_paths(PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
Definition: planner.c:6996
PathTarget * pathtarget
Definition: pathnodes.h:1117
Query * parse
Definition: pathnodes.h:179
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:631
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1294
ParamPathInfo * param_info
Definition: pathnodes.h:1119
Definition: nodes.h:525
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2519
List * partial_pathlist
Definition: pathnodes.h:659
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2682
#define linitial_node(type, l)
Definition: pg_list.h:198
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:5935
void pfree(void *pointer)
Definition: mcxt.c:1056
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1390
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void check_stack_depth(void)
Definition: postgres.c:3288
int nparts
Definition: pathnodes.h:721
Index * sortgrouprefs
Definition: pathnodes.h:1047
Relids relids
Definition: pathnodes.h:643
List * lappend(List *list, void *datum)
Definition: list.c:322
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:728
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1046
#define llast_node(type, l)
Definition: pg_list.h:218
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
struct RelOptInfo ** part_rels
Definition: pathnodes.h:724
bool consider_parallel
Definition: pathnodes.h:651
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:240
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:739
List * pathlist
Definition: pathnodes.h:657
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:654
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:194

◆ can_partial_agg()

static bool can_partial_agg ( PlannerInfo root,
const AggClauseCosts agg_costs 
)
static

Definition at line 6954 of file planner.c.

References Query::groupClause, Query::groupingSets, Query::hasAggs, AggClauseCosts::hasNonPartial, AggClauseCosts::hasNonSerial, NIL, parse(), and PlannerInfo::parse.

Referenced by create_grouping_paths().

6955 {
6956  Query *parse = root->parse;
6957 
6958  if (!parse->hasAggs && parse->groupClause == NIL)
6959  {
6960  /*
6961  * We don't know how to do parallel aggregation unless we have either
6962  * some aggregates or a grouping clause.
6963  */
6964  return false;
6965  }
6966  else if (parse->groupingSets)
6967  {
6968  /* We don't know how to do grouping sets in parallel. */
6969  return false;
6970  }
6971  else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
6972  {
6973  /* Insufficient support for partial mode. */
6974  return false;
6975  }
6976 
6977  /* Everything looks good. */
6978  return true;
6979 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
bool hasNonSerial
Definition: pathnodes.h:61
bool hasNonPartial
Definition: pathnodes.h:60
List * groupClause
Definition: parsenodes.h:148
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ common_prefix_cmp()

static int common_prefix_cmp ( const void *  a,
const void *  b 
)
static

Definition at line 5440 of file planner.c.

References forboth, lfirst_node, list_length(), SortGroupClause::nulls_first, SortGroupClause::sortop, SortGroupClause::tleSortGroupRef, and WindowClauseSortData::uniqueOrder.

Referenced by select_active_windows().

5441 {
5442  const WindowClauseSortData *wcsa = a;
5443  const WindowClauseSortData *wcsb = b;
5444  ListCell *item_a;
5445  ListCell *item_b;
5446 
5447  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5448  {
5451 
5452  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5453  return -1;
5454  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5455  return 1;
5456  else if (sca->sortop > scb->sortop)
5457  return -1;
5458  else if (sca->sortop < scb->sortop)
5459  return 1;
5460  else if (sca->nulls_first && !scb->nulls_first)
5461  return -1;
5462  else if (!sca->nulls_first && scb->nulls_first)
5463  return 1;
5464  /* no need to compare eqop, since it is fully determined by sortop */
5465  }
5466 
5467  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5468  return -1;
5469  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5470  return 1;
5471 
5472  return 0;
5473 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
Index tleSortGroupRef
Definition: parsenodes.h:1255
#define lfirst_node(type, lc)
Definition: pg_list.h:193
static int list_length(const List *l)
Definition: pg_list.h:169

◆ consider_groupingsets_paths()

static void consider_groupingsets_paths ( PlannerInfo root,
RelOptInfo grouped_rel,
Path path,
bool  is_sorted,
bool  can_hash,
grouping_sets_data gd,
const AggClauseCosts agg_costs,
double  dNumGroups 
)
static

Definition at line 4191 of file planner.c.

References add_path(), AGG_HASHED, AGG_MIXED, AGG_SORTED, grouping_sets_data::any_hashable, Assert, bms_is_empty(), bms_is_member(), create_groupingsets_path(), DiscreteKnapsack(), grouping_sets_data::dNumHashGroups, estimate_hashagg_tablesize(), for_each_cell, PlannerInfo::group_pathkeys, RollupData::groupClause, RollupData::gsets, RollupData::gsets_data, RollupData::hashable, Query::havingQual, i, RollupData::is_hashed, lappend(), lcons(), lfirst_node, linitial, list_concat(), list_copy(), list_head(), list_length(), list_make1, list_second_cell(), lnext(), makeNode, Max, Min, NIL, GroupingSetData::numGroups, RollupData::numGroups, palloc(), parse(), PlannerInfo::parse, Path::pathkeys, pathkeys_contained_in(), preprocess_groupclause(), remap_to_groupclause_idx(), grouping_sets_data::rollups, scale, GroupingSetData::set, grouping_sets_data::tleref_to_colnum_map, grouping_sets_data::unsortable_sets, and work_mem.

Referenced by add_paths_to_grouping_rel().

4199 {
4200  Query *parse = root->parse;
4201 
4202  /*
4203  * If we're not being offered sorted input, then only consider plans that
4204  * can be done entirely by hashing.
4205  *
4206  * We can hash everything if it looks like it'll fit in work_mem. But if
4207  * the input is actually sorted despite not being advertised as such, we
4208  * prefer to make use of that in order to use less memory.
4209  *
4210  * If none of the grouping sets are sortable, then ignore the work_mem
4211  * limit and generate a path anyway, since otherwise we'll just fail.
4212  */
4213  if (!is_sorted)
4214  {
4215  List *new_rollups = NIL;
4216  RollupData *unhashed_rollup = NULL;
4217  List *sets_data;
4218  List *empty_sets_data = NIL;
4219  List *empty_sets = NIL;
4220  ListCell *lc;
4221  ListCell *l_start = list_head(gd->rollups);
4222  AggStrategy strat = AGG_HASHED;
4223  double hashsize;
4224  double exclude_groups = 0.0;
4225 
4226  Assert(can_hash);
4227 
4228  /*
4229  * If the input is coincidentally sorted usefully (which can happen
4230  * even if is_sorted is false, since that only means that our caller
4231  * has set up the sorting for us), then save some hashtable space by
4232  * making use of that. But we need to watch out for degenerate cases:
4233  *
4234  * 1) If there are any empty grouping sets, then group_pathkeys might
4235  * be NIL if all non-empty grouping sets are unsortable. In this case,
4236  * there will be a rollup containing only empty groups, and the
4237  * pathkeys_contained_in test is vacuously true; this is ok.
4238  *
4239  * XXX: the above relies on the fact that group_pathkeys is generated
4240  * from the first rollup. If we add the ability to consider multiple
4241  * sort orders for grouping input, this assumption might fail.
4242  *
4243  * 2) If there are no empty sets and only unsortable sets, then the
4244  * rollups list will be empty (and thus l_start == NULL), and
4245  * group_pathkeys will be NIL; we must ensure that the vacuously-true
4246  * pathkeys_contained_in test doesn't cause us to crash.
4247  */
4248  if (l_start != NULL &&
4250  {
4251  unhashed_rollup = lfirst_node(RollupData, l_start);
4252  exclude_groups = unhashed_rollup->numGroups;
4253  l_start = lnext(gd->rollups, l_start);
4254  }
4255 
4256  hashsize = estimate_hashagg_tablesize(path,
4257  agg_costs,
4258  dNumGroups - exclude_groups);
4259 
4260  /*
4261  * gd->rollups is empty if we have only unsortable columns to work
4262  * with. Override work_mem in that case; otherwise, we'll rely on the
4263  * sorted-input case to generate usable mixed paths.
4264  */
4265  if (hashsize > work_mem * 1024L && gd->rollups)
4266  return; /* nope, won't fit */
4267 
4268  /*
4269  * We need to burst the existing rollups list into individual grouping
4270  * sets and recompute a groupClause for each set.
4271  */
4272  sets_data = list_copy(gd->unsortable_sets);
4273 
4274  for_each_cell(lc, gd->rollups, l_start)
4275  {
4276  RollupData *rollup = lfirst_node(RollupData, lc);
4277 
4278  /*
4279  * If we find an unhashable rollup that's not been skipped by the
4280  * "actually sorted" check above, we can't cope; we'd need sorted
4281  * input (with a different sort order) but we can't get that here.
4282  * So bail out; we'll get a valid path from the is_sorted case
4283  * instead.
4284  *
4285  * The mere presence of empty grouping sets doesn't make a rollup
4286  * unhashable (see preprocess_grouping_sets), we handle those
4287  * specially below.
4288  */
4289  if (!rollup->hashable)
4290  return;
4291 
4292  sets_data = list_concat(sets_data, rollup->gsets_data);
4293  }
4294  foreach(lc, sets_data)
4295  {
4297  List *gset = gs->set;
4298  RollupData *rollup;
4299 
4300  if (gset == NIL)
4301  {
4302  /* Empty grouping sets can't be hashed. */
4303  empty_sets_data = lappend(empty_sets_data, gs);
4304  empty_sets = lappend(empty_sets, NIL);
4305  }
4306  else
4307  {
4308  rollup = makeNode(RollupData);
4309 
4310  rollup->groupClause = preprocess_groupclause(root, gset);
4311  rollup->gsets_data = list_make1(gs);
4312  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4313  rollup->gsets_data,
4314  gd->tleref_to_colnum_map);
4315  rollup->numGroups = gs->numGroups;
4316  rollup->hashable = true;
4317  rollup->is_hashed = true;
4318  new_rollups = lappend(new_rollups, rollup);
4319  }
4320  }
4321 
4322  /*
4323  * If we didn't find anything nonempty to hash, then bail. We'll
4324  * generate a path from the is_sorted case.
4325  */
4326  if (new_rollups == NIL)
4327  return;
4328 
4329  /*
4330  * If there were empty grouping sets they should have been in the
4331  * first rollup.
4332  */
4333  Assert(!unhashed_rollup || !empty_sets);
4334 
4335  if (unhashed_rollup)
4336  {
4337  new_rollups = lappend(new_rollups, unhashed_rollup);
4338  strat = AGG_MIXED;
4339  }
4340  else if (empty_sets)
4341  {
4342  RollupData *rollup = makeNode(RollupData);
4343 
4344  rollup->groupClause = NIL;
4345  rollup->gsets_data = empty_sets_data;
4346  rollup->gsets = empty_sets;
4347  rollup->numGroups = list_length(empty_sets);
4348  rollup->hashable = false;
4349  rollup->is_hashed = false;
4350  new_rollups = lappend(new_rollups, rollup);
4351  strat = AGG_MIXED;
4352  }
4353 
4354  add_path(grouped_rel, (Path *)
4356  grouped_rel,
4357  path,
4358  (List *) parse->havingQual,
4359  strat,
4360  new_rollups,
4361  agg_costs,
4362  dNumGroups));
4363  return;
4364  }
4365 
4366  /*
4367  * If we have sorted input but nothing we can do with it, bail.
4368  */
4369  if (list_length(gd->rollups) == 0)
4370  return;
4371 
4372  /*
4373  * Given sorted input, we try and make two paths: one sorted and one mixed
4374  * sort/hash. (We need to try both because hashagg might be disabled, or
4375  * some columns might not be sortable.)
4376  *
4377  * can_hash is passed in as false if some obstacle elsewhere (such as
4378  * ordered aggs) means that we shouldn't consider hashing at all.
4379  */
4380  if (can_hash && gd->any_hashable)
4381  {
4382  List *rollups = NIL;
4383  List *hash_sets = list_copy(gd->unsortable_sets);
4384  double availspace = (work_mem * 1024.0);
4385  ListCell *lc;
4386 
4387  /*
4388  * Account first for space needed for groups we can't sort at all.
4389  */
4390  availspace -= estimate_hashagg_tablesize(path,
4391  agg_costs,
4392  gd->dNumHashGroups);
4393 
4394  if (availspace > 0 && list_length(gd->rollups) > 1)
4395  {
4396  double scale;
4397  int num_rollups = list_length(gd->rollups);
4398  int k_capacity;
4399  int *k_weights = palloc(num_rollups * sizeof(int));
4400  Bitmapset *hash_items = NULL;
4401  int i;
4402 
4403  /*
4404  * We treat this as a knapsack problem: the knapsack capacity
4405  * represents work_mem, the item weights are the estimated memory
4406  * usage of the hashtables needed to implement a single rollup,
4407  * and we really ought to use the cost saving as the item value;
4408  * however, currently the costs assigned to sort nodes don't
4409  * reflect the comparison costs well, and so we treat all items as
4410  * of equal value (each rollup we hash instead saves us one sort).
4411  *
4412  * To use the discrete knapsack, we need to scale the values to a
4413  * reasonably small bounded range. We choose to allow a 5% error
4414  * margin; we have no more than 4096 rollups in the worst possible
4415  * case, which with a 5% error margin will require a bit over 42MB
4416  * of workspace. (Anyone wanting to plan queries that complex had
4417  * better have the memory for it. In more reasonable cases, with
4418  * no more than a couple of dozen rollups, the memory usage will
4419  * be negligible.)
4420  *
4421  * k_capacity is naturally bounded, but we clamp the values for
4422  * scale and weight (below) to avoid overflows or underflows (or
4423  * uselessly trying to use a scale factor less than 1 byte).
4424  */
4425  scale = Max(availspace / (20.0 * num_rollups), 1.0);
4426  k_capacity = (int) floor(availspace / scale);
4427 
4428  /*
4429  * We leave the first rollup out of consideration since it's the
4430  * one that matches the input sort order. We assign indexes "i"
4431  * to only those entries considered for hashing; the second loop,
4432  * below, must use the same condition.
4433  */
4434  i = 0;
4436  {
4437  RollupData *rollup = lfirst_node(RollupData, lc);
4438 
4439  if (rollup->hashable)
4440  {
4441  double sz = estimate_hashagg_tablesize(path,
4442  agg_costs,
4443  rollup->numGroups);
4444 
4445  /*
4446  * If sz is enormous, but work_mem (and hence scale) is
4447  * small, avoid integer overflow here.
4448  */
4449  k_weights[i] = (int) Min(floor(sz / scale),
4450  k_capacity + 1.0);
4451  ++i;
4452  }
4453  }
4454 
4455  /*
4456  * Apply knapsack algorithm; compute the set of items which
4457  * maximizes the value stored (in this case the number of sorts
4458  * saved) while keeping the total size (approximately) within
4459  * capacity.
4460  */
4461  if (i > 0)
4462  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4463 
4464  if (!bms_is_empty(hash_items))
4465  {
4466  rollups = list_make1(linitial(gd->rollups));
4467 
4468  i = 0;
4470  {
4471  RollupData *rollup = lfirst_node(RollupData, lc);
4472 
4473  if (rollup->hashable)
4474  {
4475  if (bms_is_member(i, hash_items))
4476  hash_sets = list_concat(hash_sets,
4477  rollup->gsets_data);
4478  else
4479  rollups = lappend(rollups, rollup);
4480  ++i;
4481  }
4482  else
4483  rollups = lappend(rollups, rollup);
4484  }
4485  }
4486  }
4487 
4488  if (!rollups && hash_sets)
4489  rollups = list_copy(gd->rollups);
4490 
4491  foreach(lc, hash_sets)
4492  {
4494  RollupData *rollup = makeNode(RollupData);
4495 
4496  Assert(gs->set != NIL);
4497 
4498  rollup->groupClause = preprocess_groupclause(root, gs->set);
4499  rollup->gsets_data = list_make1(gs);
4500  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4501  rollup->gsets_data,
4502  gd->tleref_to_colnum_map);
4503  rollup->numGroups = gs->numGroups;
4504  rollup->hashable = true;
4505  rollup->is_hashed = true;
4506  rollups = lcons(rollup, rollups);
4507  }
4508 
4509  if (rollups)
4510  {
4511  add_path(grouped_rel, (Path *)
4513  grouped_rel,
4514  path,
4515  (List *) parse->havingQual,
4516  AGG_MIXED,
4517  rollups,
4518  agg_costs,
4519  dNumGroups));
4520  }
4521  }
4522 
4523  /*
4524  * Now try the simple sorted case.
4525  */
4526  if (!gd->unsortable_sets)
4527  add_path(grouped_rel, (Path *)
4529  grouped_rel,
4530  path,
4531  (List *) parse->havingQual,
4532  AGG_SORTED,
4533  gd->rollups,
4534  agg_costs,
4535  dNumGroups));
4536 }
List * group_pathkeys
Definition: pathnodes.h:300
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
List * groupClause
Definition: pathnodes.h:1684
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:3234
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
#define Min(x, y)
Definition: c.h:911
bool is_hashed
Definition: pathnodes.h:1689
List * list_copy(const List *oldlist)
Definition: list.c:1404
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int scale
Definition: pgbench.c:153
double dNumHashGroups
Definition: planner.c:110
double numGroups
Definition: pathnodes.h:1687
#define list_make1(x1)
Definition: pg_list.h:227
#define linitial(l)
Definition: pg_list.h:195
int * tleref_to_colnum_map
Definition: planner.c:115
#define lfirst_node(type, lc)
Definition: pg_list.h:193
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
double estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: selfuncs.c:3526
List * lappend(List *list, void *datum)
Definition: list.c:322
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
static List * remap_to_groupclause_idx(List *groupClause, List *gsets, int *tleref_to_colnum_map)
Definition: planner.c:2613
int work_mem
Definition: globals.c:121
List * lcons(void *datum, List *list)
Definition: list.c:454
List * pathkeys
Definition: pathnodes.h:1130
#define Max(x, y)
Definition: c.h:905
#define makeNode(_type_)
Definition: nodes.h:573
#define Assert(condition)
Definition: c.h:739
static int list_length(const List *l)
Definition: pg_list.h:169
List * unsortable_sets
Definition: planner.c:114
AggStrategy
Definition: nodes.h:754
void * palloc(Size size)
Definition: mcxt.c:949
int i
double numGroups
Definition: pathnodes.h:1678
bool hashable
Definition: pathnodes.h:1688
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
Bitmapset * DiscreteKnapsack(int max_weight, int num_items, int *item_weights, double *item_values)
Definition: knapsack.c:54
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
List * gsets_data
Definition: pathnodes.h:1686
GroupingSetsPath * create_groupingsets_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *having_qual, AggStrategy aggstrategy, List *rollups, const AggClauseCosts *agg_costs, double numGroups)
Definition: pathnode.c:2987
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648
List * gsets
Definition: pathnodes.h:1685

◆ create_degenerate_grouping_paths()

static void create_degenerate_grouping_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel 
)
static

Definition at line 3990 of file planner.c.

References add_path(), create_append_path(), create_group_result_path(), Query::groupingSets, Query::havingQual, lappend(), list_length(), NIL, parse(), PlannerInfo::parse, and RelOptInfo::reltarget.

Referenced by create_grouping_paths().

3992 {
3993  Query *parse = root->parse;
3994  int nrows;
3995  Path *path;
3996 
3997  nrows = list_length(parse->groupingSets);
3998  if (nrows > 1)
3999  {
4000  /*
4001  * Doesn't seem worthwhile writing code to cons up a generate_series
4002  * or a values scan to emit multiple rows. Instead just make N clones
4003  * and append them. (With a volatile HAVING clause, this means you
4004  * might get between 0 and N output rows. Offhand I think that's
4005  * desired.)
4006  */
4007  List *paths = NIL;
4008 
4009  while (--nrows >= 0)
4010  {
4011  path = (Path *)
4012  create_group_result_path(root, grouped_rel,
4013  grouped_rel->reltarget,
4014  (List *) parse->havingQual);
4015  paths = lappend(paths, path);
4016  }
4017  path = (Path *)
4018  create_append_path(root,
4019  grouped_rel,
4020  paths,
4021  NIL,
4022  NIL,
4023  NULL,
4024  0,
4025  false,
4026  NIL,
4027  -1);
4028  }
4029  else
4030  {
4031  /* No grouping sets, or just one, so one output row */
4032  path = (Path *)
4033  create_group_result_path(root, grouped_rel,
4034  grouped_rel->reltarget,
4035  (List *) parse->havingQual);
4036  }
4037 
4038  add_path(grouped_rel, path);
4039 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * groupingSets
Definition: parsenodes.h:150
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1183
List * lappend(List *list, void *datum)
Definition: list.c:322
static int list_length(const List *l)
Definition: pg_list.h:169
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1447
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:654
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ create_distinct_paths()

static RelOptInfo * create_distinct_paths ( PlannerInfo root,
RelOptInfo input_rel 
)
static

Definition at line 4729 of file planner.c.

References add_path(), AGG_HASHED, AGGSPLIT_SIMPLE, Assert, RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_agg_path(), create_sort_path(), create_upper_paths_hook, create_upper_unique_path(), PlannerInfo::distinct_pathkeys, Query::distinctClause, enable_hashagg, ereport, errcode(), errdetail(), errmsg(), ERROR, estimate_num_groups(), RelOptInfo::fdwroutine, fetch_upper_rel(), get_sortgrouplist_exprs(), FdwRoutine::GetForeignUpperPaths, Query::groupClause, grouping_is_hashable(), grouping_is_sortable(), Query::groupingSets, Query::hasAggs, Query::hasDistinctOn, hash_agg_entry_size(), PlannerInfo::hasHavingQual, lfirst, list_length(), MAXALIGN, NIL, parse(), PlannerInfo::parse, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, Path::pathtarget, Path::rows, RelOptInfo::serverid, set_cheapest(), SizeofMinimalTupleHeader, PlannerInfo::sort_pathkeys, Query::targetList, UPPERREL_DISTINCT, RelOptInfo::userid, RelOptInfo::useridiscurrent, PathTarget::width, and work_mem.

Referenced by grouping_planner().

4731 {
4732  Query *parse = root->parse;
4733  Path *cheapest_input_path = input_rel->cheapest_total_path;
4734  RelOptInfo *distinct_rel;
4735  double numDistinctRows;
4736  bool allow_hash;
4737  Path *path;
4738  ListCell *lc;
4739 
4740  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4741  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4742 
4743  /*
4744  * We don't compute anything at this level, so distinct_rel will be
4745  * parallel-safe if the input rel is parallel-safe. In particular, if
4746  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4747  * output those expressions, and will not be parallel-safe unless those
4748  * expressions are parallel-safe.
4749  */
4750  distinct_rel->consider_parallel = input_rel->consider_parallel;
4751 
4752  /*
4753  * If the input rel belongs to a single FDW, so does the distinct_rel.
4754  */
4755  distinct_rel->serverid = input_rel->serverid;
4756  distinct_rel->userid = input_rel->userid;
4757  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4758  distinct_rel->fdwroutine = input_rel->fdwroutine;
4759 
4760  /* Estimate number of distinct rows there will be */
4761  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4762  root->hasHavingQual)
4763  {
4764  /*
4765  * If there was grouping or aggregation, use the number of input rows
4766  * as the estimated number of DISTINCT rows (ie, assume the input is
4767  * already mostly unique).
4768  */
4769  numDistinctRows = cheapest_input_path->rows;
4770  }
4771  else
4772  {
4773  /*
4774  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4775  */
4776  List *distinctExprs;
4777 
4778  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4779  parse->targetList);
4780  numDistinctRows = estimate_num_groups(root, distinctExprs,
4781  cheapest_input_path->rows,
4782  NULL);
4783  }
4784 
4785  /*
4786  * Consider sort-based implementations of DISTINCT, if possible.
4787  */
4789  {
4790  /*
4791  * First, if we have any adequately-presorted paths, just stick a
4792  * Unique node on those. Then consider doing an explicit sort of the
4793  * cheapest input path and Unique'ing that.
4794  *
4795  * When we have DISTINCT ON, we must sort by the more rigorous of
4796  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4797  * Also, if we do have to do an explicit sort, we might as well use
4798  * the more rigorous ordering to avoid a second sort later. (Note
4799  * that the parser will have ensured that one clause is a prefix of
4800  * the other.)
4801  */
4802  List *needed_pathkeys;
4803 
4804  if (parse->hasDistinctOn &&
4806  list_length(root->sort_pathkeys))
4807  needed_pathkeys = root->sort_pathkeys;
4808  else
4809  needed_pathkeys = root->distinct_pathkeys;
4810 
4811  foreach(lc, input_rel->pathlist)
4812  {
4813  Path *path = (Path *) lfirst(lc);
4814 
4815  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4816  {
4817  add_path(distinct_rel, (Path *)
4818  create_upper_unique_path(root, distinct_rel,
4819  path,
4821  numDistinctRows));
4822  }
4823  }
4824 
4825  /* For explicit-sort case, always use the more rigorous clause */
4826  if (list_length(root->distinct_pathkeys) <
4827  list_length(root->sort_pathkeys))
4828  {
4829  needed_pathkeys = root->sort_pathkeys;
4830  /* Assert checks that parser didn't mess up... */
4832  needed_pathkeys));
4833  }
4834  else
4835  needed_pathkeys = root->distinct_pathkeys;
4836 
4837  path = cheapest_input_path;
4838  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4839  path = (Path *) create_sort_path(root, distinct_rel,
4840  path,
4841  needed_pathkeys,
4842  -1.0);
4843 
4844  add_path(distinct_rel, (Path *)
4845  create_upper_unique_path(root, distinct_rel,
4846  path,
4848  numDistinctRows));
4849  }
4850 
4851  /*
4852  * Consider hash-based implementations of DISTINCT, if possible.
4853  *
4854  * If we were not able to make any other types of path, we *must* hash or
4855  * die trying. If we do have other choices, there are several things that
4856  * should prevent selection of hashing: if the query uses DISTINCT ON
4857  * (because it won't really have the expected behavior if we hash), or if
4858  * enable_hashagg is off, or if it looks like the hashtable will exceed
4859  * work_mem.
4860  *
4861  * Note: grouping_is_hashable() is much more expensive to check than the
4862  * other gating conditions, so we want to do it last.
4863  */
4864  if (distinct_rel->pathlist == NIL)
4865  allow_hash = true; /* we have no alternatives */
4866  else if (parse->hasDistinctOn || !enable_hashagg)
4867  allow_hash = false; /* policy-based decision not to hash */
4868  else
4869  {
4870  Size hashentrysize;
4871 
4872  /* Estimate per-hash-entry space at tuple width... */
4873  hashentrysize = MAXALIGN(cheapest_input_path->pathtarget->width) +
4875  /* plus the per-hash-entry overhead */
4876  hashentrysize += hash_agg_entry_size(0);
4877 
4878  /* Allow hashing only if hashtable is predicted to fit in work_mem */
4879  allow_hash = (hashentrysize * numDistinctRows <= work_mem * 1024L);
4880  }
4881 
4882  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4883  {
4884  /* Generate hashed aggregate path --- no sort needed */
4885  add_path(distinct_rel, (Path *)
4886  create_agg_path(root,
4887  distinct_rel,
4888  cheapest_input_path,
4889  cheapest_input_path->pathtarget,
4890  AGG_HASHED,
4892  parse->distinctClause,
4893  NIL,
4894  NULL,
4895  numDistinctRows));
4896  }
4897 
4898  /* Give a helpful error if we failed to find any implementation */
4899  if (distinct_rel->pathlist == NIL)
4900  ereport(ERROR,
4901  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4902  errmsg("could not implement DISTINCT"),
4903  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4904 
4905  /*
4906  * If there is an FDW that's responsible for all baserels of the query,
4907  * let it consider adding ForeignPaths.
4908  */
4909  if (distinct_rel->fdwroutine &&
4910  distinct_rel->fdwroutine->GetForeignUpperPaths)
4911  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4912  input_rel, distinct_rel,
4913  NULL);
4914 
4915  /* Let extensions possibly add some more paths */
4917  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4918  input_rel, distinct_rel, NULL);
4919 
4920  /* Now choose the best path(s) */
4921  set_cheapest(distinct_rel);
4922 
4923  return distinct_rel;
4924 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
#define NIL
Definition: pg_list.h:65
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3044
PathTarget * pathtarget
Definition: pathnodes.h:1117
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:2869
Oid userid
Definition: pathnodes.h:693
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
int errcode(int sqlerrcode)
Definition: elog.c:608
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:582
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:694
bool hasDistinctOn
Definition: parsenodes.h:129
List * targetList
Definition: parsenodes.h:140
List * distinctClause
Definition: parsenodes.h:156
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1177
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition: pathnode.c:2921
struct Path * cheapest_total_path
Definition: pathnodes.h:661
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:696
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
List * sort_pathkeys
Definition: pathnodes.h:303
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:692
#define SizeofMinimalTupleHeader
Definition: htup_details.h:649
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
int work_mem
Definition: globals.c:121
List * distinct_pathkeys
Definition: pathnodes.h:302
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
List * pathkeys
Definition: pathnodes.h:1130
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1126
size_t Size
Definition: c.h:467
static int list_length(const List *l)
Definition: pg_list.h:169
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:1445
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
#define MAXALIGN(LEN)
Definition: c.h:692
bool consider_parallel
Definition: pathnodes.h:651
bool enable_hashagg
Definition: costsize.c:130
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:822
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:562
bool hasHavingQual
Definition: pathnodes.h:347
List * pathlist
Definition: pathnodes.h:657
Definition: pg_list.h:50
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ create_grouping_paths()

static RelOptInfo * create_grouping_paths ( PlannerInfo root,
RelOptInfo input_rel,
PathTarget target,
bool  target_parallel_safe,
const AggClauseCosts agg_costs,
grouping_sets_data gd 
)
static

Definition at line 3806 of file planner.c.

References grouping_sets_data::any_hashable, can_partial_agg(), create_degenerate_grouping_paths(), create_ordinary_grouping_paths(), enable_partitionwise_aggregate, GroupPathExtraData::flags, Query::groupClause, GROUPING_CAN_PARTIAL_AGG, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, grouping_is_hashable(), grouping_is_sortable(), Query::groupingSets, Query::havingQual, GroupPathExtraData::havingQual, is_degenerate_grouping(), make_grouping_rel(), NIL, AggClauseCosts::numOrderedAggs, parse(), PlannerInfo::parse, GroupPathExtraData::partial_costs_set, PARTITIONWISE_AGGREGATE_FULL, PARTITIONWISE_AGGREGATE_NONE, GroupPathExtraData::patype, grouping_sets_data::rollups, set_cheapest(), GroupPathExtraData::target_parallel_safe, Query::targetList, and GroupPathExtraData::targetList.

Referenced by grouping_planner().

3812 {
3813  Query *parse = root->parse;
3814  RelOptInfo *grouped_rel;
3815  RelOptInfo *partially_grouped_rel;
3816 
3817  /*
3818  * Create grouping relation to hold fully aggregated grouping and/or
3819  * aggregation paths.
3820  */
3821  grouped_rel = make_grouping_rel(root, input_rel, target,
3822  target_parallel_safe, parse->havingQual);
3823 
3824  /*
3825  * Create either paths for a degenerate grouping or paths for ordinary
3826  * grouping, as appropriate.
3827  */
3828  if (is_degenerate_grouping(root))
3829  create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3830  else
3831  {
3832  int flags = 0;
3833  GroupPathExtraData extra;
3834 
3835  /*
3836  * Determine whether it's possible to perform sort-based
3837  * implementations of grouping. (Note that if groupClause is empty,
3838  * grouping_is_sortable() is trivially true, and all the
3839  * pathkeys_contained_in() tests will succeed too, so that we'll
3840  * consider every surviving input path.)
3841  *
3842  * If we have grouping sets, we might be able to sort some but not all
3843  * of them; in this case, we need can_sort to be true as long as we
3844  * must consider any sorted-input plan.
3845  */
3846  if ((gd && gd->rollups != NIL)
3847  || grouping_is_sortable(parse->groupClause))
3848  flags |= GROUPING_CAN_USE_SORT;
3849 
3850  /*
3851  * Determine whether we should consider hash-based implementations of
3852  * grouping.
3853  *
3854  * Hashed aggregation only applies if we're grouping. If we have
3855  * grouping sets, some groups might be hashable but others not; in
3856  * this case we set can_hash true as long as there is nothing globally
3857  * preventing us from hashing (and we should therefore consider plans
3858  * with hashes).
3859  *
3860  * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3861  * BY aggregates. (Doing so would imply storing *all* the input
3862  * values in the hash table, and/or running many sorts in parallel,
3863  * either of which seems like a certain loser.) We similarly don't
3864  * support ordered-set aggregates in hashed aggregation, but that case
3865  * is also included in the numOrderedAggs count.
3866  *
3867  * Note: grouping_is_hashable() is much more expensive to check than
3868  * the other gating conditions, so we want to do it last.
3869  */
3870  if ((parse->groupClause != NIL &&
3871  agg_costs->numOrderedAggs == 0 &&
3872  (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause))))
3873  flags |= GROUPING_CAN_USE_HASH;
3874 
3875  /*
3876  * Determine whether partial aggregation is possible.
3877  */
3878  if (can_partial_agg(root, agg_costs))
3879  flags |= GROUPING_CAN_PARTIAL_AGG;
3880 
3881  extra.flags = flags;
3882  extra.target_parallel_safe = target_parallel_safe;
3883  extra.havingQual = parse->havingQual;
3884  extra.targetList = parse->targetList;
3885  extra.partial_costs_set = false;
3886 
3887  /*
3888  * Determine whether partitionwise aggregation is in theory possible.
3889  * It can be disabled by the user, and for now, we don't try to
3890  * support grouping sets. create_ordinary_grouping_paths() will check
3891  * additional conditions, such as whether input_rel is partitioned.
3892  */
3895  else
3897 
3898  create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3899  agg_costs, gd, &extra,
3900  &partially_grouped_rel);
3901  }
3902 
3903  set_cheapest(grouped_rel);
3904  return grouped_rel;
3905 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3916
static void create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
Definition: planner.c:3990
List * groupingSets
Definition: parsenodes.h:150
PartitionwiseAggregateType patype
Definition: pathnodes.h:2454
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:582
bool enable_partitionwise_aggregate
Definition: costsize.c:137
List * targetList
Definition: parsenodes.h:140
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2407
static bool is_degenerate_grouping(PlannerInfo *root)
Definition: planner.c:3969
int numOrderedAggs
Definition: pathnodes.h:59
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define GROUPING_CAN_PARTIAL_AGG
Definition: pathnodes.h:2409
static bool can_partial_agg(PlannerInfo *root, const AggClauseCosts *agg_costs)
Definition: planner.c:6954
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2408
static void create_ordinary_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
Definition: planner.c:4055
List * groupClause
Definition: parsenodes.h:148
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:562
Node * havingQual
Definition: parsenodes.h:152
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ create_one_window_path()

static void create_one_window_path ( PlannerInfo root,
RelOptInfo window_rel,
Path path,
PathTarget input_target,
PathTarget output_target,
WindowFuncLists wflists,
List activeWindows 
)
static

Definition at line 4636 of file planner.c.

References add_column_to_pathtarget(), add_path(), copy_pathtarget(), create_sort_path(), create_windowagg_path(), get_typavgwidth(), lfirst_node, lnext(), make_pathkeys_for_window(), Path::pathkeys, pathkeys_contained_in(), PlannerInfo::processed_tlist, PathTarget::width, WindowFuncLists::windowFuncs, and WindowClause::winref.

Referenced by create_window_paths().

4643 {
4644  PathTarget *window_target;
4645  ListCell *l;
4646 
4647  /*
4648  * Since each window clause could require a different sort order, we stack
4649  * up a WindowAgg node for each clause, with sort steps between them as
4650  * needed. (We assume that select_active_windows chose a good order for
4651  * executing the clauses in.)
4652  *
4653  * input_target should contain all Vars and Aggs needed for the result.
4654  * (In some cases we wouldn't need to propagate all of these all the way
4655  * to the top, since they might only be needed as inputs to WindowFuncs.
4656  * It's probably not worth trying to optimize that though.) It must also
4657  * contain all window partitioning and sorting expressions, to ensure
4658  * they're computed only once at the bottom of the stack (that's critical
4659  * for volatile functions). As we climb up the stack, we'll add outputs
4660  * for the WindowFuncs computed at each level.
4661  */
4662  window_target = input_target;
4663 
4664  foreach(l, activeWindows)
4665  {
4667  List *window_pathkeys;
4668 
4669  window_pathkeys = make_pathkeys_for_window(root,
4670  wc,
4671  root->processed_tlist);
4672 
4673  /* Sort if necessary */
4674  if (!pathkeys_contained_in(window_pathkeys, path->pathkeys))
4675  {
4676  path = (Path *) create_sort_path(root, window_rel,
4677  path,
4678  window_pathkeys,
4679  -1.0);
4680  }
4681 
4682  if (lnext(activeWindows, l))
4683  {
4684  /*
4685  * Add the current WindowFuncs to the output target for this
4686  * intermediate WindowAggPath. We must copy window_target to
4687  * avoid changing the previous path's target.
4688  *
4689  * Note: a WindowFunc adds nothing to the target's eval costs; but
4690  * we do need to account for the increase in tlist width.
4691  */
4692  ListCell *lc2;
4693 
4694  window_target = copy_pathtarget(window_target);
4695  foreach(lc2, wflists->windowFuncs[wc->winref])
4696  {
4697  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4698 
4699  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4700  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4701  }
4702  }
4703  else
4704  {
4705  /* Install the goal target in the topmost WindowAgg */
4706  window_target = output_target;
4707  }
4708 
4709  path = (Path *)
4710  create_windowagg_path(root, window_rel, path, window_target,
4711  wflists->windowFuncs[wc->winref],
4712  wc);
4713  }
4714 
4715  add_path(window_rel, path);
4716 }
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:672
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:710
#define lfirst_node(type, lc)
Definition: pg_list.h:193
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5627
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2356
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
List * pathkeys
Definition: pathnodes.h:1130
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause)
Definition: pathnode.c:3215
Oid wintype
Definition: primnodes.h:374
List * processed_tlist
Definition: pathnodes.h:325
Definition: pg_list.h:50
List ** windowFuncs
Definition: clauses.h:24

◆ create_ordered_paths()

static RelOptInfo * create_ordered_paths ( PlannerInfo root,
RelOptInfo input_rel,
PathTarget target,
bool  target_parallel_safe,
double  limit_tuples 
)
static

Definition at line 4941 of file planner.c.

References add_path(), apply_projection_to_path(), Assert, RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_gather_merge_path(), create_sort_path(), create_upper_paths_hook, RelOptInfo::fdwroutine, fetch_upper_rel(), FdwRoutine::GetForeignUpperPaths, lfirst, linitial, NIL, Path::parallel_workers, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, Path::pathtarget, Path::rows, RelOptInfo::serverid, PlannerInfo::sort_pathkeys, UPPERREL_ORDERED, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by grouping_planner().

4946 {
4947  Path *cheapest_input_path = input_rel->cheapest_total_path;
4948  RelOptInfo *ordered_rel;
4949  ListCell *lc;
4950 
4951  /* For now, do all work in the (ORDERED, NULL) upperrel */
4952  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4953 
4954  /*
4955  * If the input relation is not parallel-safe, then the ordered relation
4956  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4957  * target list is parallel-safe.
4958  */
4959  if (input_rel->consider_parallel && target_parallel_safe)
4960  ordered_rel->consider_parallel = true;
4961 
4962  /*
4963  * If the input rel belongs to a single FDW, so does the ordered_rel.
4964  */
4965  ordered_rel->serverid = input_rel->serverid;
4966  ordered_rel->userid = input_rel->userid;
4967  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4968  ordered_rel->fdwroutine = input_rel->fdwroutine;
4969 
4970  foreach(lc, input_rel->pathlist)
4971  {
4972  Path *path = (Path *) lfirst(lc);
4973  bool is_sorted;
4974 
4975  is_sorted = pathkeys_contained_in(root->sort_pathkeys,
4976  path->pathkeys);
4977  if (path == cheapest_input_path || is_sorted)
4978  {
4979  if (!is_sorted)
4980  {
4981  /* An explicit sort here can take advantage of LIMIT */
4982  path = (Path *) create_sort_path(root,
4983  ordered_rel,
4984  path,
4985  root->sort_pathkeys,
4986  limit_tuples);
4987  }
4988 
4989  /* Add projection step if needed */
4990  if (path->pathtarget != target)
4991  path = apply_projection_to_path(root, ordered_rel,
4992  path, target);
4993 
4994  add_path(ordered_rel, path);
4995  }
4996  }
4997 
4998  /*
4999  * generate_gather_paths() will have already generated a simple Gather
5000  * path for the best parallel path, if any, and the loop above will have
5001  * considered sorting it. Similarly, generate_gather_paths() will also
5002  * have generated order-preserving Gather Merge plans which can be used
5003  * without sorting if they happen to match the sort_pathkeys, and the loop
5004  * above will have handled those as well. However, there's one more
5005  * possibility: it may make sense to sort the cheapest partial path
5006  * according to the required output order and then use Gather Merge.
5007  */
5008  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5009  input_rel->partial_pathlist != NIL)
5010  {
5011  Path *cheapest_partial_path;
5012 
5013  cheapest_partial_path = linitial(input_rel->partial_pathlist);
5014 
5015  /*
5016  * If cheapest partial path doesn't need a sort, this is redundant
5017  * with what's already been tried.
5018  */
5020  cheapest_partial_path->pathkeys))
5021  {
5022  Path *path;
5023  double total_groups;
5024 
5025  path = (Path *) create_sort_path(root,
5026  ordered_rel,
5027  cheapest_partial_path,
5028  root->sort_pathkeys,
5029  limit_tuples);
5030 
5031  total_groups = cheapest_partial_path->rows *
5032  cheapest_partial_path->parallel_workers;
5033  path = (Path *)
5034  create_gather_merge_path(root, ordered_rel,
5035  path,
5036  path->pathtarget,
5037  root->sort_pathkeys, NULL,
5038  &total_groups);
5039 
5040  /* Add projection step if needed */
5041  if (path->pathtarget != target)
5042  path = apply_projection_to_path(root, ordered_rel,
5043  path, target);
5044 
5045  add_path(ordered_rel, path);
5046  }
5047  }
5048 
5049  /*
5050  * If there is an FDW that's responsible for all baserels of the query,
5051  * let it consider adding ForeignPaths.
5052  */
5053  if (ordered_rel->fdwroutine &&
5054  ordered_rel->fdwroutine->GetForeignUpperPaths)
5055  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5056  input_rel, ordered_rel,
5057  NULL);
5058 
5059  /* Let extensions possibly add some more paths */
5061  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5062  input_rel, ordered_rel, NULL);
5063 
5064  /*
5065  * No need to bother with set_cheapest here; grouping_planner does not
5066  * need us to do it.
5067  */
5068  Assert(ordered_rel->pathlist != NIL);
5069 
5070  return ordered_rel;
5071 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2610
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1117
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Oid userid
Definition: pathnodes.h:693
int parallel_workers
Definition: pathnodes.h:1123
List * partial_pathlist
Definition: pathnodes.h:659
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:694
#define linitial(l)
Definition: pg_list.h:195
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1177
struct Path * cheapest_total_path
Definition: pathnodes.h:661
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:696
List * sort_pathkeys
Definition: pathnodes.h:303
Oid serverid
Definition: pathnodes.h:692
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1753
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
List * pathkeys
Definition: pathnodes.h:1130
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1126
bool consider_parallel
Definition: pathnodes.h:651
List * pathlist
Definition: pathnodes.h:657

◆ create_ordinary_grouping_paths()

static void create_ordinary_grouping_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
const AggClauseCosts agg_costs,
grouping_sets_data gd,
GroupPathExtraData extra,
RelOptInfo **  partially_grouped_rel_p 
)
static

Definition at line 4055 of file planner.c.

References add_paths_to_grouping_rel(), Assert, RelOptInfo::cheapest_total_path, create_partial_grouping_paths(), create_partitionwise_grouping_paths(), create_upper_paths_hook, ereport, errcode(), errdetail(), errmsg(), ERROR, RelOptInfo::fdwroutine, GroupPathExtraData::flags, gather_grouping_paths(), get_number_of_groups(), FdwRoutine::GetForeignUpperPaths, group_by_has_partkey(), Query::groupClause, GROUPING_CAN_PARTIAL_AGG, IS_PARTITIONED_REL, NIL, PlannerInfo::parse, RelOptInfo::partial_pathlist, PARTITIONWISE_AGGREGATE_FULL, PARTITIONWISE_AGGREGATE_NONE, PARTITIONWISE_AGGREGATE_PARTIAL, RelOptInfo::pathlist, GroupPathExtraData::patype, Path::rows, set_cheapest(), GroupPathExtraData::targetList, and UPPERREL_GROUP_AGG.

Referenced by create_grouping_paths(), and create_partitionwise_grouping_paths().

4061 {
4062  Path *cheapest_path = input_rel->cheapest_total_path;
4063  RelOptInfo *partially_grouped_rel = NULL;
4064  double dNumGroups;
4066 
4067  /*
4068  * If this is the topmost grouping relation or if the parent relation is
4069  * doing some form of partitionwise aggregation, then we may be able to do
4070  * it at this level also. However, if the input relation is not
4071  * partitioned, partitionwise aggregate is impossible.
4072  */
4073  if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
4074  IS_PARTITIONED_REL(input_rel))
4075  {
4076  /*
4077  * If this is the topmost relation or if the parent relation is doing
4078  * full partitionwise aggregation, then we can do full partitionwise
4079  * aggregation provided that the GROUP BY clause contains all of the
4080  * partitioning columns at this level. Otherwise, we can do at most
4081  * partial partitionwise aggregation. But if partial aggregation is
4082  * not supported in general then we can't use it for partitionwise
4083  * aggregation either.
4084  */
4085  if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
4086  group_by_has_partkey(input_rel, extra->targetList,
4087  root->parse->groupClause))
4089  else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4091  else
4093  }
4094 
4095  /*
4096  * Before generating paths for grouped_rel, we first generate any possible
4097  * partially grouped paths; that way, later code can easily consider both
4098  * parallel and non-parallel approaches to grouping.
4099  */
4100  if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4101  {
4102  bool force_rel_creation;
4103 
4104  /*
4105  * If we're doing partitionwise aggregation at this level, force
4106  * creation of a partially_grouped_rel so we can add partitionwise
4107  * paths to it.
4108  */
4109  force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
4110 
4111  partially_grouped_rel =
4113  grouped_rel,
4114  input_rel,
4115  gd,
4116  extra,
4117  force_rel_creation);
4118  }
4119 
4120  /* Set out parameter. */
4121  *partially_grouped_rel_p = partially_grouped_rel;
4122 
4123  /* Apply partitionwise aggregation technique, if possible. */
4124  if (patype != PARTITIONWISE_AGGREGATE_NONE)
4125  create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
4126  partially_grouped_rel, agg_costs,
4127  gd, patype, extra);
4128 
4129  /* If we are doing partial aggregation only, return. */
4131  {
4132  Assert(partially_grouped_rel);
4133 
4134  if (partially_grouped_rel->pathlist)
4135  set_cheapest(partially_grouped_rel);
4136 
4137  return;
4138  }
4139 
4140  /* Gather any partially grouped partial paths. */
4141  if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
4142  {
4143  gather_grouping_paths(root, partially_grouped_rel);
4144  set_cheapest(partially_grouped_rel);
4145  }
4146 
4147  /*
4148  * Estimate number of groups.
4149  */
4150  dNumGroups = get_number_of_groups(root,
4151  cheapest_path->rows,
4152  gd,
4153  extra->targetList);
4154 
4155  /* Build final grouping paths */
4156  add_paths_to_grouping_rel(root, input_rel, grouped_rel,
4157  partially_grouped_rel, agg_costs, gd,
4158  dNumGroups, extra);
4159 
4160  /* Give a helpful error if we failed to find any implementation */
4161  if (grouped_rel->pathlist == NIL)
4162  ereport(ERROR,
4163  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4164  errmsg("could not implement GROUP BY"),
4165  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4166 
4167  /*
4168  * If there is an FDW that's responsible for all baserels of the query,
4169  * let it consider adding ForeignPaths.
4170  */
4171  if (grouped_rel->fdwroutine &&
4172  grouped_rel->fdwroutine->GetForeignUpperPaths)
4174  input_rel, grouped_rel,
4175  extra);
4176 
4177  /* Let extensions possibly add some more paths */
4179  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4180  input_rel, grouped_rel,
4181  extra);
4182 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
PartitionwiseAggregateType
Definition: pathnodes.h:2422
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3685
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6914
PartitionwiseAggregateType patype
Definition: pathnodes.h:2454
int errcode(int sqlerrcode)
Definition: elog.c:608
List * partial_pathlist
Definition: pathnodes.h:659
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
static RelOptInfo * create_partial_grouping_paths(PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *input_rel, grouping_sets_data *gd, GroupPathExtraData *extra, bool force_rel_creation)
Definition: planner.c:6611
#define ERROR
Definition: elog.h:43
struct Path * cheapest_total_path
Definition: pathnodes.h:661
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:696
int errdetail(const char *fmt,...)
Definition: elog.c:955
static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, double dNumGroups, GroupPathExtraData *extra)
Definition: planner.c:6377
#define ereport(elevel, rest)
Definition: elog.h:141
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define GROUPING_CAN_PARTIAL_AGG
Definition: pathnodes.h:2409
static void create_partitionwise_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, PartitionwiseAggregateType patype, GroupPathExtraData *extra)
Definition: planner.c:7228
#define Assert(condition)
Definition: c.h:739
double rows
Definition: pathnodes.h:1126
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:739
List * pathlist
Definition: pathnodes.h:657
static bool group_by_has_partkey(RelOptInfo *input_rel, List *targetList, List *groupClause)
Definition: planner.c:7368

◆ create_partial_grouping_paths()

static RelOptInfo * create_partial_grouping_paths ( PlannerInfo root,
RelOptInfo grouped_rel,
RelOptInfo input_rel,
grouping_sets_data gd,
GroupPathExtraData extra,
bool  force_rel_creation 
)
static

Definition at line 6611 of file planner.c.

References add_partial_path(), add_path(), GroupPathExtraData::agg_final_costs, AGG_HASHED, GroupPathExtraData::agg_partial_costs, AGG_PLAIN, AGG_SORTED, AGGSPLIT_FINAL_DESERIAL, AGGSPLIT_INITIAL_SERIAL, Assert, RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_agg_path(), create_group_path(), create_sort_path(), estimate_hashagg_tablesize(), PathTarget::exprs, RelOptInfo::fdwroutine, fetch_upper_rel(), GroupPathExtraData::flags, get_agg_clause_costs(), get_number_of_groups(), FdwRoutine::GetForeignUpperPaths, PlannerInfo::group_pathkeys, Query::groupClause, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, Query::hasAggs, GroupPathExtraData::havingQual, lfirst, linitial, make_partial_grouping_target(), MemSet, NIL, parse(), PlannerInfo::parse, GroupPathExtraData::partial_costs_set, RelOptInfo::partial_pathlist, PARTITIONWISE_AGGREGATE_PARTIAL, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, GroupPathExtraData::patype, RelOptInfo::relids, RelOptInfo::reloptkind, RelOptInfo::reltarget, Path::rows, RelOptInfo::serverid, GroupPathExtraData::targetList, UPPERREL_PARTIAL_GROUP_AGG, RelOptInfo::userid, RelOptInfo::useridiscurrent, and work_mem.

Referenced by create_ordinary_grouping_paths().

6617 {
6618  Query *parse = root->parse;
6619  RelOptInfo *partially_grouped_rel;
6620  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
6621  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6622  Path *cheapest_partial_path = NULL;
6623  Path *cheapest_total_path = NULL;
6624  double dNumPartialGroups = 0;
6625  double dNumPartialPartialGroups = 0;
6626  ListCell *lc;
6627  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6628  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6629 
6630  /*
6631  * Consider whether we should generate partially aggregated non-partial
6632  * paths. We can only do this if we have a non-partial path, and only if
6633  * the parent of the input rel is performing partial partitionwise
6634  * aggregation. (Note that extra->patype is the type of partitionwise
6635  * aggregation being used at the parent level, not this level.)
6636  */
6637  if (input_rel->pathlist != NIL &&
6639  cheapest_total_path = input_rel->cheapest_total_path;
6640 
6641  /*
6642  * If parallelism is possible for grouped_rel, then we should consider
6643  * generating partially-grouped partial paths. However, if the input rel
6644  * has no partial paths, then we can't.
6645  */
6646  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
6647  cheapest_partial_path = linitial(input_rel->partial_pathlist);
6648 
6649  /*
6650  * If we can't partially aggregate partial paths, and we can't partially
6651  * aggregate non-partial paths, then don't bother creating the new
6652  * RelOptInfo at all, unless the caller specified force_rel_creation.
6653  */
6654  if (cheapest_total_path == NULL &&
6655  cheapest_partial_path == NULL &&
6656  !force_rel_creation)
6657  return NULL;
6658 
6659  /*
6660  * Build a new upper relation to represent the result of partially
6661  * aggregating the rows from the input relation.
6662  */
6663  partially_grouped_rel = fetch_upper_rel(root,
6665  grouped_rel->relids);
6666  partially_grouped_rel->consider_parallel =
6667  grouped_rel->consider_parallel;
6668  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
6669  partially_grouped_rel->serverid = grouped_rel->serverid;
6670  partially_grouped_rel->userid = grouped_rel->userid;
6671  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
6672  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
6673 
6674  /*
6675  * Build target list for partial aggregate paths. These paths cannot just
6676  * emit the same tlist as regular aggregate paths, because (1) we must
6677  * include Vars and Aggrefs needed in HAVING, which might not appear in
6678  * the result tlist, and (2) the Aggrefs must be set in partial mode.
6679  */
6680  partially_grouped_rel->reltarget =
6681  make_partial_grouping_target(root, grouped_rel->reltarget,
6682  extra->havingQual);
6683 
6684  if (!extra->partial_costs_set)
6685  {
6686  /*
6687  * Collect statistics about aggregates for estimating costs of
6688  * performing aggregation in parallel.
6689  */
6690  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
6691  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
6692  if (parse->hasAggs)
6693  {
6694  List *partial_target_exprs;
6695 
6696  /* partial phase */
6697  partial_target_exprs = partially_grouped_rel->reltarget->exprs;
6698  get_agg_clause_costs(root, (Node *) partial_target_exprs,
6700  agg_partial_costs);
6701 
6702  /* final phase */
6703  get_agg_clause_costs(root, (Node *) grouped_rel->reltarget->exprs,
6705  agg_final_costs);
6706  get_agg_clause_costs(root, extra->havingQual,
6708  agg_final_costs);
6709  }
6710 
6711  extra->partial_costs_set = true;
6712  }
6713 
6714  /* Estimate number of partial groups. */
6715  if (cheapest_total_path != NULL)
6716  dNumPartialGroups =
6717  get_number_of_groups(root,
6718  cheapest_total_path->rows,
6719  gd,
6720  extra->targetList);
6721  if (cheapest_partial_path != NULL)
6722  dNumPartialPartialGroups =
6723  get_number_of_groups(root,
6724  cheapest_partial_path->rows,
6725  gd,
6726  extra->targetList);
6727 
6728  if (can_sort && cheapest_total_path != NULL)
6729  {
6730  /* This should have been checked previously */
6731  Assert(parse->hasAggs || parse->groupClause);
6732 
6733  /*
6734  * Use any available suitably-sorted path as input, and also consider
6735  * sorting the cheapest partial path.
6736  */
6737  foreach(lc, input_rel->pathlist)
6738  {
6739  Path *path = (Path *) lfirst(lc);
6740  bool is_sorted;
6741 
6742  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6743  path->pathkeys);
6744  if (path == cheapest_total_path || is_sorted)
6745  {
6746  /* Sort the cheapest partial path, if it isn't already */
6747  if (!is_sorted)
6748  path = (Path *) create_sort_path(root,
6749  partially_grouped_rel,
6750  path,
6751  root->group_pathkeys,
6752  -1.0);
6753 
6754  if (parse->hasAggs)
6755  add_path(partially_grouped_rel, (Path *)
6756  create_agg_path(root,
6757  partially_grouped_rel,
6758  path,
6759  partially_grouped_rel->reltarget,
6760  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6762  parse->groupClause,
6763  NIL,
6764  agg_partial_costs,
6765  dNumPartialGroups));
6766  else
6767  add_path(partially_grouped_rel, (Path *)
6768  create_group_path(root,
6769  partially_grouped_rel,
6770  path,
6771  parse->groupClause,
6772  NIL,
6773  dNumPartialGroups));
6774  }
6775  }
6776  }
6777 
6778  if (can_sort && cheapest_partial_path != NULL)
6779  {
6780  /* Similar to above logic, but for partial paths. */
6781  foreach(lc, input_rel->partial_pathlist)
6782  {
6783  Path *path = (Path *) lfirst(lc);
6784  bool is_sorted;
6785 
6786  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6787  path->pathkeys);
6788  if (path == cheapest_partial_path || is_sorted)
6789  {
6790  /* Sort the cheapest partial path, if it isn't already */
6791  if (!is_sorted)
6792  path = (Path *) create_sort_path(root,
6793  partially_grouped_rel,
6794  path,
6795  root->group_pathkeys,
6796  -1.0);
6797 
6798  if (parse->hasAggs)
6799  add_partial_path(partially_grouped_rel, (Path *)
6800  create_agg_path(root,
6801  partially_grouped_rel,
6802  path,
6803  partially_grouped_rel->reltarget,
6804  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6806  parse->groupClause,
6807  NIL,
6808  agg_partial_costs,
6809  dNumPartialPartialGroups));
6810  else
6811  add_partial_path(partially_grouped_rel, (Path *)
6812  create_group_path(root,
6813  partially_grouped_rel,
6814  path,
6815  parse->groupClause,
6816  NIL,
6817  dNumPartialPartialGroups));
6818  }
6819  }
6820  }
6821 
6822  if (can_hash && cheapest_total_path != NULL)
6823  {
6824  double hashaggtablesize;
6825 
6826  /* Checked above */
6827  Assert(parse->hasAggs || parse->groupClause);
6828 
6829  hashaggtablesize =
6830  estimate_hashagg_tablesize(cheapest_total_path,
6831  agg_partial_costs,
6832  dNumPartialGroups);
6833 
6834  /*
6835  * Tentatively produce a partial HashAgg Path, depending on if it
6836  * looks as if the hash table will fit in work_mem.
6837  */
6838  if (hashaggtablesize < work_mem * 1024L &&
6839  cheapest_total_path != NULL)
6840  {
6841  add_path(partially_grouped_rel, (Path *)
6842  create_agg_path(root,
6843  partially_grouped_rel,
6844  cheapest_total_path,
6845  partially_grouped_rel->reltarget,
6846  AGG_HASHED,
6848  parse->groupClause,
6849  NIL,
6850  agg_partial_costs,
6851  dNumPartialGroups));
6852  }
6853  }
6854 
6855  if (can_hash && cheapest_partial_path != NULL)
6856  {
6857  double hashaggtablesize;
6858 
6859  hashaggtablesize =
6860  estimate_hashagg_tablesize(cheapest_partial_path,
6861  agg_partial_costs,
6862  dNumPartialPartialGroups);
6863 
6864  /* Do the same for partial paths. */
6865  if (hashaggtablesize < work_mem * 1024L &&
6866  cheapest_partial_path != NULL)
6867  {
6868  add_partial_path(partially_grouped_rel, (Path *)
6869  create_agg_path(root,
6870  partially_grouped_rel,
6871  cheapest_partial_path,
6872  partially_grouped_rel->reltarget,
6873  AGG_HASHED,
6875  parse->groupClause,
6876  NIL,
6877  agg_partial_costs,
6878  dNumPartialPartialGroups));
6879  }
6880  }
6881 
6882  /*
6883  * If there is an FDW that's responsible for all baserels of the query,
6884  * let it consider adding partially grouped ForeignPaths.
6885  */
6886  if (partially_grouped_rel->fdwroutine &&
6887  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
6888  {
6889  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
6890 
6891  fdwroutine->GetForeignUpperPaths(root,
6893  input_rel, partially_grouped_rel,
6894  extra);
6895  }
6896 
6897  return partially_grouped_rel;
6898 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
List * group_pathkeys
Definition: pathnodes.h:300
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
RelOptKind reloptkind
Definition: pathnodes.h:640
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3685
Oid userid
Definition: pathnodes.h:693
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:2447
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:228
bool hasAggs
Definition: parsenodes.h:125
Definition: nodes.h:525
PartitionwiseAggregateType patype
Definition: pathnodes.h:2454
List * partial_pathlist
Definition: pathnodes.h:659
#define MemSet(start, val, len)
Definition: c.h:962
bool useridiscurrent
Definition: pathnodes.h:694
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2407
#define linitial(l)
Definition: pg_list.h:195
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1177
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition: pathnode.c:2921
struct Path * cheapest_total_path
Definition: pathnodes.h:661
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:696
Relids relids
Definition: pathnodes.h:643
double estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: selfuncs.c:3526
Oid serverid
Definition: pathnodes.h:692
List * exprs
Definition: pathnodes.h:1046
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
int work_mem
Definition: globals.c:121
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2408
List * pathkeys
Definition: pathnodes.h:1130
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1126
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:5189
bool consider_parallel
Definition: pathnodes.h:651
List * groupClause
Definition: parsenodes.h:148
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
List * pathlist
Definition: pathnodes.h:657
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2810
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2448
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:654
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ create_partitionwise_grouping_paths()

static void create_partitionwise_grouping_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
RelOptInfo partially_grouped_rel,
const AggClauseCosts agg_costs,
grouping_sets_data gd,
PartitionwiseAggregateType  patype,
GroupPathExtraData extra 
)
static

Definition at line 7228 of file planner.c.

References add_paths_to_append_rel(), adjust_appendrel_attrs(), Assert, copy_pathtarget(), create_ordinary_grouping_paths(), PathTarget::exprs, find_appinfos_by_relids(), GroupPathExtraData::havingQual, IS_DUMMY_REL, lappend(), make_grouping_rel(), NIL, RelOptInfo::nparts, RelOptInfo::part_rels, PARTITIONWISE_AGGREGATE_FULL, PARTITIONWISE_AGGREGATE_NONE, PARTITIONWISE_AGGREGATE_PARTIAL, RelOptInfo::pathlist, GroupPathExtraData::patype, pfree(), RelOptInfo::relids, RelOptInfo::reltarget, set_cheapest(), GroupPathExtraData::target_parallel_safe, and GroupPathExtraData::targetList.

Referenced by create_ordinary_grouping_paths().

7236 {
7237  int nparts = input_rel->nparts;
7238  int cnt_parts;
7239  List *grouped_live_children = NIL;
7240  List *partially_grouped_live_children = NIL;
7241  PathTarget *target = grouped_rel->reltarget;
7242  bool partial_grouping_valid = true;
7243 
7246  partially_grouped_rel != NULL);
7247 
7248  /* Add paths for partitionwise aggregation/grouping. */
7249  for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
7250  {
7251  RelOptInfo *child_input_rel = input_rel->part_rels[cnt_parts];
7252  PathTarget *child_target = copy_pathtarget(target);
7253  AppendRelInfo **appinfos;
7254  int nappinfos;
7255  GroupPathExtraData child_extra;
7256  RelOptInfo *child_grouped_rel;
7257  RelOptInfo *child_partially_grouped_rel;
7258 
7259  /* Pruned or dummy children can be ignored. */
7260  if (child_input_rel == NULL || IS_DUMMY_REL(child_input_rel))
7261  continue;
7262 
7263  /*
7264  * Copy the given "extra" structure as is and then override the
7265  * members specific to this child.
7266  */
7267  memcpy(&child_extra, extra, sizeof(child_extra));
7268 
7269  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7270  &nappinfos);
7271 
7272  child_target->exprs = (List *)
7274  (Node *) target->exprs,
7275  nappinfos, appinfos);
7276 
7277  /* Translate havingQual and targetList. */
7278  child_extra.havingQual = (Node *)
7280  extra->havingQual,
7281  nappinfos, appinfos);
7282  child_extra.targetList = (List *)
7284  (Node *) extra->targetList,
7285  nappinfos, appinfos);
7286 
7287  /*
7288  * extra->patype was the value computed for our parent rel; patype is
7289  * the value for this relation. For the child, our value is its
7290  * parent rel's value.
7291  */
7292  child_extra.patype = patype;
7293 
7294  /*
7295  * Create grouping relation to hold fully aggregated grouping and/or
7296  * aggregation paths for the child.
7297  */
7298  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7299  child_target,
7300  extra->target_parallel_safe,
7301  child_extra.havingQual);
7302 
7303  /* Create grouping paths for this child relation. */
7304  create_ordinary_grouping_paths(root, child_input_rel,
7305  child_grouped_rel,
7306  agg_costs, gd, &child_extra,
7307  &child_partially_grouped_rel);
7308 
7309  if (child_partially_grouped_rel)
7310  {
7311  partially_grouped_live_children =
7312  lappend(partially_grouped_live_children,
7313  child_partially_grouped_rel);
7314  }
7315  else
7316  partial_grouping_valid = false;
7317 
7318  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7319  {
7320  set_cheapest(child_grouped_rel);
7321  grouped_live_children = lappend(grouped_live_children,
7322  child_grouped_rel);
7323  }
7324 
7325  pfree(appinfos);
7326  }
7327 
7328  /*
7329  * Try to create append paths for partially grouped children. For full
7330  * partitionwise aggregation, we might have paths in the partial_pathlist
7331  * if parallel aggregation is possible. For partial partitionwise
7332  * aggregation, we may have paths in both pathlist and partial_pathlist.
7333  *
7334  * NB: We must have a partially grouped path for every child in order to
7335  * generate a partially grouped path for this relation.
7336  */
7337  if (partially_grouped_rel && partial_grouping_valid)
7338  {
7339  Assert(partially_grouped_live_children != NIL);
7340 
7341  add_paths_to_append_rel(root, partially_grouped_rel,
7342  partially_grouped_live_children);
7343 
7344  /*
7345  * We need call set_cheapest, since the finalization step will use the
7346  * cheapest path from the rel.
7347  */
7348  if (partially_grouped_rel->pathlist)
7349  set_cheapest(partially_grouped_rel);
7350  }
7351 
7352  /* If possible, create append paths for fully grouped children. */
7353  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7354  {
7355  Assert(grouped_live_children != NIL);
7356 
7357  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7358  }
7359 }
#define NIL
Definition: pg_list.h:65
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:672
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3916
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1294
Definition: nodes.h:525
PartitionwiseAggregateType patype
Definition: pathnodes.h:2454
void pfree(void *pointer)
Definition: mcxt.c:1056
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1390
int nparts
Definition: pathnodes.h:721
Relids relids
Definition: pathnodes.h:643
List * lappend(List *list, void *datum)
Definition: list.c:322
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:728
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1046
#define Assert(condition)
Definition: c.h:739
struct RelOptInfo ** part_rels
Definition: pathnodes.h:724
static void create_ordinary_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
Definition: planner.c:4055
List * pathlist
Definition: pathnodes.h:657
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:654
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:194

◆ create_window_paths()

static RelOptInfo * create_window_paths ( PlannerInfo root,
RelOptInfo input_rel,
PathTarget input_target,
PathTarget output_target,
bool  output_target_parallel_safe,
WindowFuncLists wflists,
List activeWindows 
)
static

Definition at line 4552 of file planner.c.

References RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_one_window_path(), create_upper_paths_hook, RelOptInfo::fdwroutine, fetch_upper_rel(), FdwRoutine::GetForeignUpperPaths, is_parallel_safe(), lfirst, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, RelOptInfo::serverid, set_cheapest(), UPPERREL_WINDOW, RelOptInfo::userid, RelOptInfo::useridiscurrent, and PlannerInfo::window_pathkeys.

Referenced by grouping_planner().

4559 {
4560  RelOptInfo *window_rel;
4561  ListCell *lc;
4562 
4563  /* For now, do all work in the (WINDOW, NULL) upperrel */
4564  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4565 
4566  /*
4567  * If the input relation is not parallel-safe, then the window relation
4568  * can't be parallel-safe, either. Otherwise, we need to examine the
4569  * target list and active windows for non-parallel-safe constructs.
4570  */
4571  if (input_rel->consider_parallel && output_target_parallel_safe &&
4572  is_parallel_safe(root, (Node *) activeWindows))
4573  window_rel->consider_parallel = true;
4574 
4575  /*
4576  * If the input rel belongs to a single FDW, so does the window rel.
4577  */
4578  window_rel->serverid = input_rel->serverid;
4579  window_rel->userid = input_rel->userid;
4580  window_rel->useridiscurrent = input_rel->useridiscurrent;
4581  window_rel->fdwroutine = input_rel->fdwroutine;
4582 
4583  /*
4584  * Consider computing window functions starting from the existing
4585  * cheapest-total path (which will likely require a sort) as well as any
4586  * existing paths that satisfy root->window_pathkeys (which won't).
4587  */
4588  foreach(lc, input_rel->pathlist)
4589  {
4590  Path *path = (Path *) lfirst(lc);
4591 
4592  if (path == input_rel->cheapest_total_path ||
4595  window_rel,
4596  path,
4597  input_target,
4598  output_target,
4599  wflists,
4600  activeWindows);
4601  }
4602 
4603  /*
4604  * If there is an FDW that's responsible for all baserels of the query,
4605  * let it consider adding ForeignPaths.
4606  */
4607  if (window_rel->fdwroutine &&
4608  window_rel->fdwroutine->GetForeignUpperPaths)
4609  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4610  input_rel, window_rel,
4611  NULL);
4612 
4613  /* Let extensions possibly add some more paths */
4615  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4616  input_rel, window_rel, NULL);
4617 
4618  /* Now choose the best path(s) */
4619  set_cheapest(window_rel);
4620 
4621  return window_rel;
4622 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
static void create_one_window_path(PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, WindowFuncLists *wflists, List *activeWindows)
Definition: planner.c:4636
Oid userid
Definition: pathnodes.h:693
Definition: nodes.h:525
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:694
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:853
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1177
struct Path * cheapest_total_path
Definition: pathnodes.h:661
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:696
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:692
List * window_pathkeys
Definition: pathnodes.h:301
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
List * pathkeys
Definition: pathnodes.h:1130
#define lfirst(lc)
Definition: pg_list.h:190
bool consider_parallel
Definition: pathnodes.h:651
List * pathlist
Definition: pathnodes.h:657

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 6051 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

Referenced by ATExecAddColumn(), ATPrepAlterColumnType(), BeginCopyFrom(), CheckMutability(), ComputePartitionAttrs(), ExecPrepareCheck(), ExecPrepareExpr(), ExecPrepareQual(), load_domaintype_info(), set_baserel_partition_constraint(), slot_fill_defaults(), StoreAttrDefault(), and transformPartitionBoundValue().

6052 {
6053  Node *result;
6054 
6055  /*
6056  * Convert named-argument function calls, insert default arguments and
6057  * simplify constant subexprs
6058  */
6059  result = eval_const_expressions(NULL, (Node *) expr);
6060 
6061  /* Fill in opfuncid values if missing */
6062  fix_opfuncids(result);
6063 
6064  return (Expr *) result;
6065 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1587
Definition: nodes.h:525
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2252

◆ expression_planner_with_deps()

Expr* expression_planner_with_deps ( Expr expr,
List **  relationOids,
List **  invalItems 
)

Definition at line 6078 of file planner.c.

References eval_const_expressions(), extract_query_dependencies_walker(), fix_opfuncids(), PlannerInfo::glob, PlannerGlobal::invalItems, MemSet, NIL, PlannerGlobal::relationOids, T_PlannerGlobal, T_PlannerInfo, PlannerGlobal::type, and PlannerInfo::type.

Referenced by GetCachedExpression().

6081 {
6082  Node *result;
6083  PlannerGlobal glob;
6084  PlannerInfo root;
6085 
6086  /* Make up dummy planner state so we can use setrefs machinery */
6087  MemSet(&glob, 0, sizeof(glob));
6088  glob.type = T_PlannerGlobal;
6089  glob.relationOids = NIL;
6090  glob.invalItems = NIL;
6091 
6092  MemSet(&root, 0, sizeof(root));
6093  root.type = T_PlannerInfo;
6094  root.glob = &glob;
6095 
6096  /*
6097  * Convert named-argument function calls, insert default arguments and
6098  * simplify constant subexprs. Collect identities of inlined functions
6099  * and elided domains, too.
6100  */
6101  result = eval_const_expressions(&root, (Node *) expr);
6102 
6103  /* Fill in opfuncid values if missing */
6104  fix_opfuncids(result);
6105 
6106  /*
6107  * Now walk the finished expression to find anything else we ought to
6108  * record as an expression dependency.
6109  */
6110  (void) extract_query_dependencies_walker(result, &root);
6111 
6112  *relationOids = glob.relationOids;
6113  *invalItems = glob.invalItems;
6114 
6115  return (Expr *) result;
6116 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1587
Definition: nodes.h:525
#define MemSet(start, val, len)
Definition: c.h:962
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2252
PlannerGlobal * glob
Definition: pathnodes.h:181
List * invalItems
Definition: pathnodes.h:129
NodeTag type
Definition: pathnodes.h:177
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:2826
NodeTag type
Definition: pathnodes.h:107
List * relationOids
Definition: pathnodes.h:127

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

Definition at line 3337 of file planner.c.

References Assert, BipartiteMatch(), BipartiteMatchFree(), bms_add_member(), bms_equal(), bms_free(), bms_is_subset(), for_each_cell, i, lappend(), lcons(), lfirst, lfirst_int, list_concat(), list_head(), list_length(), list_make1, lnext(), NIL, BipartiteMatchState::pair_uv, BipartiteMatchState::pair_vu, palloc(), palloc0(), and pfree().

Referenced by preprocess_grouping_sets().

3338 {
3339  int num_sets_raw = list_length(groupingSets);
3340  int num_empty = 0;
3341  int num_sets = 0; /* distinct sets */
3342  int num_chains = 0;
3343  List *result = NIL;
3344  List **results;
3345  List **orig_sets;
3346  Bitmapset **set_masks;
3347  int *chains;
3348  short **adjacency;
3349  short *adjacency_buf;
3351  int i;
3352  int j;
3353  int j_size;
3354  ListCell *lc1 = list_head(groupingSets);
3355  ListCell *lc;
3356 
3357  /*
3358  * Start by stripping out empty sets. The algorithm doesn't require this,
3359  * but the planner currently needs all empty sets to be returned in the
3360  * first list, so we strip them here and add them back after.
3361  */
3362  while (lc1 && lfirst(lc1) == NIL)
3363  {
3364  ++num_empty;
3365  lc1 = lnext(groupingSets, lc1);
3366  }
3367 
3368  /* bail out now if it turns out that all we had were empty sets. */
3369  if (!lc1)
3370  return list_make1(groupingSets);
3371 
3372  /*----------
3373  * We don't strictly need to remove duplicate sets here, but if we don't,
3374  * they tend to become scattered through the result, which is a bit
3375  * confusing (and irritating if we ever decide to optimize them out).
3376  * So we remove them here and add them back after.
3377  *
3378  * For each non-duplicate set, we fill in the following:
3379  *
3380  * orig_sets[i] = list of the original set lists
3381  * set_masks[i] = bitmapset for testing inclusion
3382  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3383  *
3384  * chains[i] will be the result group this set is assigned to.
3385  *
3386  * We index all of these from 1 rather than 0 because it is convenient
3387  * to leave 0 free for the NIL node in the graph algorithm.
3388  *----------
3389  */
3390  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3391  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3392  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3393  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3394 
3395  j_size = 0;
3396  j = 0;
3397  i = 1;
3398 
3399  for_each_cell(lc, groupingSets, lc1)
3400  {
3401  List *candidate = (List *) lfirst(lc);
3402  Bitmapset *candidate_set = NULL;
3403  ListCell *lc2;
3404  int dup_of = 0;
3405 
3406  foreach(lc2, candidate)
3407  {
3408  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3409  }
3410 
3411  /* we can only be a dup if we're the same length as a previous set */
3412  if (j_size == list_length(candidate))
3413  {
3414  int k;
3415 
3416  for (k = j; k < i; ++k)
3417  {
3418  if (bms_equal(set_masks[k], candidate_set))
3419  {
3420  dup_of = k;
3421  break;
3422  }
3423  }
3424  }
3425  else if (j_size < list_length(candidate))
3426  {
3427  j_size = list_length(candidate);
3428  j = i;
3429  }
3430 
3431  if (dup_of > 0)
3432  {
3433  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3434  bms_free(candidate_set);
3435  }
3436  else
3437  {
3438  int k;
3439  int n_adj = 0;
3440 
3441  orig_sets[i] = list_make1(candidate);
3442  set_masks[i] = candidate_set;
3443 
3444  /* fill in adjacency list; no need to compare equal-size sets */
3445 
3446  for (k = j - 1; k > 0; --k)
3447  {
3448  if (bms_is_subset(set_masks[k], candidate_set))
3449  adjacency_buf[++n_adj] = k;
3450  }
3451 
3452  if (n_adj > 0)
3453  {
3454  adjacency_buf[0] = n_adj;
3455  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3456  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3457  }
3458  else
3459  adjacency[i] = NULL;
3460 
3461  ++i;
3462  }
3463  }
3464 
3465  num_sets = i - 1;
3466 
3467  /*
3468  * Apply the graph matching algorithm to do the work.
3469  */
3470  state = BipartiteMatch(num_sets, num_sets, adjacency);
3471 
3472  /*
3473  * Now, the state->pair* fields have the info we need to assign sets to
3474  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3475  * pair_vu[v] = u (both will be true, but we check both so that we can do
3476  * it in one pass)
3477  */
3478  chains = palloc0((num_sets + 1) * sizeof(int));
3479 
3480  for (i = 1; i <= num_sets; ++i)
3481  {
3482  int u = state->pair_vu[i];
3483  int v = state->pair_uv[i];
3484 
3485  if (u > 0 && u < i)
3486  chains[i] = chains[u];
3487  else if (v > 0 && v < i)
3488  chains[i] = chains[v];
3489  else
3490  chains[i] = ++num_chains;
3491  }
3492 
3493  /* build result lists. */
3494  results = palloc0((num_chains + 1) * sizeof(List *));
3495 
3496  for (i = 1; i <= num_sets; ++i)
3497  {
3498  int c = chains[i];
3499 
3500  Assert(c > 0);
3501 
3502  results[c] = list_concat(results[c], orig_sets[i]);
3503  }
3504 
3505  /* push any empty sets back on the first list. */
3506  while (num_empty-- > 0)
3507  results[1] = lcons(NIL, results[1]);
3508 
3509  /* make result list */
3510  for (i = 1; i <= num_chains; ++i)
3511  result = lappend(result, results[i]);
3512 
3513  /*
3514  * Free all the things.
3515  *
3516  * (This is over-fussy for small sets but for large sets we could have
3517  * tied up a nontrivial amount of memory.)
3518  */
3519  BipartiteMatchFree(state);
3520  pfree(results);
3521  pfree(chains);
3522  for (i = 1; i <= num_sets; ++i)
3523  if (adjacency[i])
3524  pfree(adjacency[i]);
3525  pfree(adjacency);
3526  pfree(adjacency_buf);
3527  pfree(orig_sets);
3528  for (i = 1; i <= num_sets; ++i)
3529  bms_free(set_masks[i]);
3530  pfree(set_masks);
3531 
3532  return result;
3533 }
#define NIL
Definition: pg_list.h:65
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
void BipartiteMatchFree(BipartiteMatchState *state)
#define list_make1(x1)
Definition: pg_list.h:227
void pfree(void *pointer)
Definition: mcxt.c:1056
#define lfirst_int(lc)
Definition: pg_list.h:191
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
char * c
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * lappend(List *list, void *datum)
Definition: list.c:322
void * palloc0(Size size)
Definition: mcxt.c:980
BipartiteMatchState * BipartiteMatch(int u_size, int v_size, short **adjacency)
List * lcons(void *datum, List *list)
Definition: list.c:454
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Definition: regguts.h:298
static int list_length(const List *l)
Definition: pg_list.h:169
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
void * palloc(Size size)
Definition: mcxt.c:949
int i
Definition: pg_list.h:50
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94

◆ gather_grouping_paths()

static void gather_grouping_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 6914 of file planner.c.

References add_path(), create_gather_merge_path(), create_sort_path(), generate_gather_paths(), PlannerInfo::group_pathkeys, linitial, Path::parallel_workers, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::reltarget, and Path::rows.

Referenced by add_paths_to_grouping_rel(), and create_ordinary_grouping_paths().

6915 {
6916  Path *cheapest_partial_path;
6917 
6918  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
6919  generate_gather_paths(root, rel, true);
6920 
6921  /* Try cheapest partial path + explicit Sort + Gather Merge. */
6922  cheapest_partial_path = linitial(rel->partial_pathlist);
6924  cheapest_partial_path->pathkeys))
6925  {
6926  Path *path;
6927  double total_groups;
6928 
6929  total_groups =
6930  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
6931  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
6932  root->group_pathkeys,
6933  -1.0);
6934  path = (Path *)
6936  rel,
6937  path,
6938  rel->reltarget,
6939  root->group_pathkeys,
6940  NULL,
6941  &total_groups);
6942 
6943  add_path(rel, path);
6944  }
6945 }
List * group_pathkeys
Definition: pathnodes.h:300
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
int parallel_workers
Definition: pathnodes.h:1123
List * partial_pathlist
Definition: pathnodes.h:659
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2682
#define linitial(l)
Definition: pg_list.h:195
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1753
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
List * pathkeys
Definition: pathnodes.h:1130
double rows
Definition: pathnodes.h:1126
struct PathTarget * reltarget
Definition: pathnodes.h:654

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

Definition at line 5892 of file planner.c.

References RelOptInfo::cheapest_total_path, compare_fractional_path_costs(), lfirst, RelOptInfo::pathlist, and Path::rows.

Referenced by make_subplan(), recurse_set_operations(), and standard_planner().

5893 {
5894  Path *best_path = rel->cheapest_total_path;
5895  ListCell *l;
5896 
5897  /* If all tuples will be retrieved, just return the cheapest-total path */
5898  if (tuple_fraction <= 0.0)
5899  return best_path;
5900 
5901  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5902  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5903  tuple_fraction /= best_path->rows;
5904 
5905  foreach(l, rel->pathlist)
5906  {
5907  Path *path = (Path *) lfirst(l);
5908 
5909  if (path == rel->cheapest_total_path ||
5910  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5911  continue;
5912 
5913  best_path = path;
5914  }
5915 
5916  return best_path;
5917 }
struct Path * cheapest_total_path
Definition: pathnodes.h:661
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1126
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: pathnodes.h:657

◆ get_number_of_groups()

static double get_number_of_groups ( PlannerInfo root,
double  path_rows,
grouping_sets_data gd,
List target_list 
)
static

Definition at line 3685 of file planner.c.

References Assert, grouping_sets_data::dNumHashGroups, estimate_num_groups(), forboth, get_sortgrouplist_exprs(), Query::groupClause, RollupData::groupClause, Query::groupingSets, RollupData::gsets, RollupData::gsets_data, Query::hasAggs, grouping_sets_data::hash_sets_idx, PlannerInfo::hasHavingQual, lfirst, lfirst_node, list_length(), GroupingSetData::numGroups, RollupData::numGroups, parse(), PlannerInfo::parse, grouping_sets_data::rollups, and grouping_sets_data::unsortable_sets.

Referenced by create_ordinary_grouping_paths(), and create_partial_grouping_paths().

3689 {
3690  Query *parse = root->parse;
3691  double dNumGroups;
3692 
3693  if (parse->groupClause)
3694  {
3695  List *groupExprs;
3696 
3697  if (parse->groupingSets)
3698  {
3699  /* Add up the estimates for each grouping set */
3700  ListCell *lc;
3701  ListCell *lc2;
3702 
3703  Assert(gd); /* keep Coverity happy */
3704 
3705  dNumGroups = 0;
3706 
3707  foreach(lc, gd->rollups)
3708  {
3709  RollupData *rollup = lfirst_node(RollupData, lc);
3710  ListCell *lc;
3711 
3712  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3713  target_list);
3714 
3715  rollup->numGroups = 0.0;
3716 
3717  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3718  {
3719  List *gset = (List *) lfirst(lc);
3721  double numGroups = estimate_num_groups(root,
3722  groupExprs,
3723  path_rows,
3724  &gset);
3725 
3726  gs->numGroups = numGroups;
3727  rollup->numGroups += numGroups;
3728  }
3729 
3730  dNumGroups += rollup->numGroups;
3731  }
3732 
3733  if (gd->hash_sets_idx)
3734  {
3735  ListCell *lc;
3736 
3737  gd->dNumHashGroups = 0;
3738 
3739  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3740  target_list);
3741 
3742  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3743  {
3744  List *gset = (List *) lfirst(lc);
3746  double numGroups = estimate_num_groups(root,
3747  groupExprs,
3748  path_rows,
3749  &gset);
3750 
3751  gs->numGroups = numGroups;
3752  gd->dNumHashGroups += numGroups;
3753  }
3754 
3755  dNumGroups += gd->dNumHashGroups;
3756  }
3757  }
3758  else
3759  {
3760  /* Plain GROUP BY */
3761  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3762  target_list);
3763 
3764  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3765  NULL);
3766  }
3767  }
3768  else if (parse->groupingSets)
3769  {
3770  /* Empty grouping sets ... one result row for each one */
3771  dNumGroups = list_length(parse->groupingSets);
3772  }
3773  else if (parse->hasAggs || root->hasHavingQual)
3774  {
3775  /* Plain aggregation, one result row */
3776  dNumGroups = 1;
3777  }
3778  else
3779  {
3780  /* Not grouping */
3781  dNumGroups = 1;
3782  }
3783 
3784  return dNumGroups;
3785 }
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3044
Query * parse
Definition: pathnodes.h:179
List * groupClause
Definition: pathnodes.h:1684
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
bool hasAggs
Definition: parsenodes.h:125
List * hash_sets_idx
Definition: planner.c:109
List * groupingSets
Definition: parsenodes.h:150
double dNumHashGroups
Definition: planner.c:110
double numGroups
Definition: pathnodes.h:1687
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
List * unsortable_sets
Definition: planner.c:114
List * groupClause
Definition: parsenodes.h:148
double numGroups
Definition: pathnodes.h:1678
bool hasHavingQual
Definition: pathnodes.h:347
Definition: pg_list.h:50
List * gsets_data
Definition: pathnodes.h:1686
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648
List * gsets
Definition: pathnodes.h:1685

◆ group_by_has_partkey()

static bool group_by_has_partkey ( RelOptInfo input_rel,
List targetList,
List groupClause 
)
static

Definition at line 7368 of file planner.c.

References Assert, get_sortgrouplist_exprs(), lfirst, list_member(), RelOptInfo::part_scheme, RelOptInfo::partexprs, and PartitionSchemeData::partnatts.

Referenced by create_ordinary_grouping_paths().

7371 {
7372  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7373  int cnt = 0;
7374  int partnatts;
7375 
7376  /* Input relation should be partitioned. */
7377  Assert(input_rel->part_scheme);
7378 
7379  /* Rule out early, if there are no partition keys present. */
7380  if (!input_rel->partexprs)
7381  return false;
7382 
7383  partnatts = input_rel->part_scheme->partnatts;
7384 
7385  for (cnt = 0; cnt < partnatts; cnt++)
7386  {
7387  List *partexprs = input_rel->partexprs[cnt];
7388  ListCell *lc;
7389  bool found = false;
7390 
7391  foreach(lc, partexprs)
7392  {
7393  Expr *partexpr = lfirst(lc);
7394 
7395  if (list_member(groupexprs, partexpr))
7396  {
7397  found = true;
7398  break;
7399  }
7400  }
7401 
7402  /*
7403  * If none of the partition key expressions match with any of the
7404  * GROUP BY expression, return false.
7405  */
7406  if (!found)
7407  return false;
7408  }
7409 
7410  return true;
7411 }
List ** partexprs
Definition: pathnodes.h:726
bool list_member(const List *list, const void *datum)
Definition: list.c:614
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
PartitionScheme part_scheme
Definition: pathnodes.h:720
Definition: pg_list.h:50

◆ grouping_planner()

static void grouping_planner ( PlannerInfo root,
bool  inheritance_update,
double  tuple_fraction 
)
static

Definition at line 1834 of file planner.c.

References standard_qp_extra::activeWindows, add_partial_path(), add_path(), adjust_paths_for_srfs(), AGGSPLIT_SIMPLE, apply_scanjoin_target_to_paths(), Assert, assign_special_exec_param(), Query::canSetTag, RelOptInfo::cheapest_total_path, CMD_SELECT, Query::commandType, RelOptInfo::consider_parallel, copyObject, FinalPathExtraData::count_est, create_distinct_paths(), create_grouping_paths(), create_limit_path(), create_lockrows_path(), create_modifytable_path(), create_ordered_paths(), create_pathtarget, create_upper_paths_hook, create_window_paths(), Query::distinctClause, equal(), ereport, errcode(), errmsg(), ERROR, PathTarget::exprs, RelOptInfo::fdwroutine, fetch_upper_rel(), find_window_functions(), get_agg_clause_costs(), FdwRoutine::GetForeignUpperPaths, standard_qp_extra::groupClause, Query::groupClause, Query::groupingSets, Query::hasAggs, PlannerInfo::hasHavingQual, PlannerInfo::hasRecursion, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, is_parallel_safe(), LCS_asString(), lfirst, FinalPathExtraData::limit_needed, limit_needed(), PlannerInfo::limit_tuples, FinalPathExtraData::limit_tuples, Query::limitCount, Query::limitOffset, linitial_int, linitial_node, list_length(), list_make1, list_make1_int, make_group_input_target(), make_pathkeys_for_sortclauses(), make_sort_input_target(), make_window_input_target(), MemSet, NIL, WindowFuncLists::numWindowFuncs, FinalPathExtraData::offset_est, Query::onConflict, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, Path::pathtarget, plan_set_operations(), postprocess_setop_tlist(), preprocess_groupclause(), preprocess_grouping_sets(), preprocess_limit(), preprocess_minmax_aggregates(), preprocess_targetlist(), PlannerInfo::processed_tlist, PlannerInfo::query_level, query_planner(), RelOptInfo::reltarget, Query::resultRelation, Query::returningList, grouping_sets_data::rollups, Query::rowMarks, PlannerInfo::rowMarks, rt_fetch, Query::rtable, select_active_windows(), RelOptInfo::serverid, Query::setOperations, PlannerInfo::sort_pathkeys, Query::sortClause, split_pathtarget_at_srfs(), standard_qp_callback(), Query::targetList, PlannerInfo::tuple_fraction, PlannerInfo::upper_targets, UPPERREL_DISTINCT, UPPERREL_FINAL, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, UPPERREL_WINDOW, RelOptInfo::userid, RelOptInfo::useridiscurrent, Query::windowClause, and Query::withCheckOptions.

Referenced by inheritance_planner(), and subquery_planner().

1836 {
1837  Query *parse = root->parse;
1838  int64 offset_est = 0;
1839  int64 count_est = 0;
1840  double limit_tuples = -1.0;
1841  bool have_postponed_srfs = false;
1842  PathTarget *final_target;
1843  List *final_targets;
1844  List *final_targets_contain_srfs;
1845  bool final_target_parallel_safe;
1846  RelOptInfo *current_rel;
1847  RelOptInfo *final_rel;
1848  FinalPathExtraData extra;
1849  ListCell *lc;
1850 
1851  /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1852  if (parse->limitCount || parse->limitOffset)
1853  {
1854  tuple_fraction = preprocess_limit(root, tuple_fraction,
1855  &offset_est, &count_est);
1856 
1857  /*
1858  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1859  * estimate the effects of using a bounded sort.
1860  */
1861  if (count_est > 0 && offset_est >= 0)
1862  limit_tuples = (double) count_est + (double) offset_est;
1863  }
1864 
1865  /* Make tuple_fraction accessible to lower-level routines */
1866  root->tuple_fraction = tuple_fraction;
1867 
1868  if (parse->setOperations)
1869  {
1870  /*
1871  * If there's a top-level ORDER BY, assume we have to fetch all the
1872  * tuples. This might be too simplistic given all the hackery below
1873  * to possibly avoid the sort; but the odds of accurate estimates here
1874  * are pretty low anyway. XXX try to get rid of this in favor of
1875  * letting plan_set_operations generate both fast-start and
1876  * cheapest-total paths.
1877  */
1878  if (parse->sortClause)
1879  root->tuple_fraction = 0.0;
1880 
1881  /*
1882  * Construct Paths for set operations. The results will not need any
1883  * work except perhaps a top-level sort and/or LIMIT. Note that any
1884  * special work for recursive unions is the responsibility of
1885  * plan_set_operations.
1886  */
1887  current_rel = plan_set_operations(root);
1888 
1889  /*
1890  * We should not need to call preprocess_targetlist, since we must be
1891  * in a SELECT query node. Instead, use the processed_tlist returned
1892  * by plan_set_operations (since this tells whether it returned any
1893  * resjunk columns!), and transfer any sort key information from the
1894  * original tlist.
1895  */
1896  Assert(parse->commandType == CMD_SELECT);
1897 
1898  /* for safety, copy processed_tlist instead of modifying in-place */
1899  root->processed_tlist =
1901  parse->targetList);
1902 
1903  /* Also extract the PathTarget form of the setop result tlist */
1904  final_target = current_rel->cheapest_total_path->pathtarget;
1905 
1906  /* And check whether it's parallel safe */
1907  final_target_parallel_safe =
1908  is_parallel_safe(root, (Node *) final_target->exprs);
1909 
1910  /* The setop result tlist couldn't contain any SRFs */
1911  Assert(!parse->hasTargetSRFs);
1912  final_targets = final_targets_contain_srfs = NIL;
1913 
1914  /*
1915  * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1916  * checked already, but let's make sure).
1917  */
1918  if (parse->rowMarks)
1919  ereport(ERROR,
1920  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1921  /*------
1922  translator: %s is a SQL row locking clause such as FOR UPDATE */
1923  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1925  parse->rowMarks)->strength))));
1926 
1927  /*
1928  * Calculate pathkeys that represent result ordering requirements
1929  */
1930  Assert(parse->distinctClause == NIL);
1932  parse->sortClause,
1933  root->processed_tlist);
1934  }
1935  else
1936  {
1937  /* No set operations, do regular planning */
1938  PathTarget *sort_input_target;
1939  List *sort_input_targets;
1940  List *sort_input_targets_contain_srfs;
1941  bool sort_input_target_parallel_safe;
1942  PathTarget *grouping_target;
1943  List *grouping_targets;
1944  List *grouping_targets_contain_srfs;
1945  bool grouping_target_parallel_safe;
1946  PathTarget *scanjoin_target;
1947  List *scanjoin_targets;
1948  List *scanjoin_targets_contain_srfs;
1949  bool scanjoin_target_parallel_safe;
1950  bool scanjoin_target_same_exprs;
1951  bool have_grouping;
1952  AggClauseCosts agg_costs;
1953  WindowFuncLists *wflists = NULL;
1954  List *activeWindows = NIL;
1955  grouping_sets_data *gset_data = NULL;
1956  standard_qp_extra qp_extra;
1957 
1958  /* A recursive query should always have setOperations */
1959  Assert(!root->hasRecursion);
1960 
1961  /* Preprocess grouping sets and GROUP BY clause, if any */
1962  if (parse->groupingSets)
1963  {
1964  gset_data = preprocess_grouping_sets(root);
1965  }
1966  else
1967  {
1968  /* Preprocess regular GROUP BY clause, if any */
1969  if (parse->groupClause)
1970  parse->groupClause = preprocess_groupclause(root, NIL);
1971  }
1972 
1973  /*
1974  * Preprocess targetlist. Note that much of the remaining planning
1975  * work will be done with the PathTarget representation of tlists, but
1976  * we must also maintain the full representation of the final tlist so
1977  * that we can transfer its decoration (resnames etc) to the topmost
1978  * tlist of the finished Plan. This is kept in processed_tlist.
1979  */
1980  root->processed_tlist = preprocess_targetlist(root);
1981 
1982  /*
1983  * Collect statistics about aggregates for estimating costs, and mark
1984  * all the aggregates with resolved aggtranstypes. We must do this
1985  * before slicing and dicing the tlist into various pathtargets, else
1986  * some copies of the Aggref nodes might escape being marked with the
1987  * correct transtypes.
1988  *
1989  * Note: currently, we do not detect duplicate aggregates here. This
1990  * may result in somewhat-overestimated cost, which is fine for our
1991  * purposes since all Paths will get charged the same. But at some
1992  * point we might wish to do that detection in the planner, rather
1993  * than during executor startup.
1994  */
1995  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
1996  if (parse->hasAggs)
1997  {
1998  get_agg_clause_costs(root, (Node *) root->processed_tlist,
1999  AGGSPLIT_SIMPLE, &agg_costs);
2001  &agg_costs);
2002  }
2003 
2004  /*
2005  * Locate any window functions in the tlist. (We don't need to look
2006  * anywhere else, since expressions used in ORDER BY will be in there
2007  * too.) Note that they could all have been eliminated by constant
2008  * folding, in which case we don't need to do any more work.
2009  */
2010  if (parse->hasWindowFuncs)
2011  {
2012  wflists = find_window_functions((Node *) root->processed_tlist,
2013  list_length(parse->windowClause));
2014  if (wflists->numWindowFuncs > 0)
2015  activeWindows = select_active_windows(root, wflists);
2016  else
2017  parse->hasWindowFuncs = false;
2018  }
2019 
2020  /*
2021  * Preprocess MIN/MAX aggregates, if any. Note: be careful about
2022  * adding logic between here and the query_planner() call. Anything
2023  * that is needed in MIN/MAX-optimizable cases will have to be
2024  * duplicated in planagg.c.
2025  */
2026  if (parse->hasAggs)
2028 
2029  /*
2030  * Figure out whether there's a hard limit on the number of rows that
2031  * query_planner's result subplan needs to return. Even if we know a
2032  * hard limit overall, it doesn't apply if the query has any
2033  * grouping/aggregation operations, or SRFs in the tlist.
2034  */
2035  if (parse->groupClause ||
2036  parse->groupingSets ||
2037  parse->distinctClause ||
2038  parse->hasAggs ||
2039  parse->hasWindowFuncs ||
2040  parse->hasTargetSRFs ||
2041  root->hasHavingQual)
2042  root->limit_tuples = -1.0;
2043  else
2044  root->limit_tuples = limit_tuples;
2045 
2046  /* Set up data needed by standard_qp_callback */
2047  qp_extra.activeWindows = activeWindows;
2048  qp_extra.groupClause = (gset_data
2049  ? (gset_data->rollups ? linitial_node(RollupData, gset_data->rollups)->groupClause : NIL)
2050  : parse->groupClause);
2051 
2052  /*
2053  * Generate the best unsorted and presorted paths for the scan/join
2054  * portion of this Query, ie the processing represented by the
2055  * FROM/WHERE clauses. (Note there may not be any presorted paths.)
2056  * We also generate (in standard_qp_callback) pathkey representations
2057  * of the query's sort clause, distinct clause, etc.
2058  */
2059  current_rel = query_planner(root, standard_qp_callback, &qp_extra);
2060 
2061  /*
2062  * Convert the query's result tlist into PathTarget format.
2063  *
2064  * Note: this cannot be done before query_planner() has performed
2065  * appendrel expansion, because that might add resjunk entries to
2066  * root->processed_tlist. Waiting till afterwards is also helpful
2067  * because the target width estimates can use per-Var width numbers
2068  * that were obtained within query_planner().
2069  */
2070  final_target = create_pathtarget(root, root->processed_tlist);
2071  final_target_parallel_safe =
2072  is_parallel_safe(root, (Node *) final_target->exprs);
2073 
2074  /*
2075  * If ORDER BY was given, consider whether we should use a post-sort
2076  * projection, and compute the adjusted target for preceding steps if
2077  * so.
2078  */
2079  if (parse->sortClause)
2080  {
2081  sort_input_target = make_sort_input_target(root,
2082  final_target,
2083  &have_postponed_srfs);
2084  sort_input_target_parallel_safe =
2085  is_parallel_safe(root, (Node *) sort_input_target->exprs);
2086  }
2087  else
2088  {
2089  sort_input_target = final_target;
2090  sort_input_target_parallel_safe = final_target_parallel_safe;
2091  }
2092 
2093  /*
2094  * If we have window functions to deal with, the output from any
2095  * grouping step needs to be what the window functions want;
2096  * otherwise, it should be sort_input_target.
2097  */
2098  if (activeWindows)
2099  {
2100  grouping_target = make_window_input_target(root,
2101  final_target,
2102  activeWindows);
2103  grouping_target_parallel_safe =
2104  is_parallel_safe(root, (Node *) grouping_target->exprs);
2105  }
2106  else
2107  {
2108  grouping_target = sort_input_target;
2109  grouping_target_parallel_safe = sort_input_target_parallel_safe;
2110  }
2111 
2112  /*
2113  * If we have grouping or aggregation to do, the topmost scan/join
2114  * plan node must emit what the grouping step wants; otherwise, it
2115  * should emit grouping_target.
2116  */
2117  have_grouping = (parse->groupClause || parse->groupingSets ||
2118  parse->hasAggs || root->hasHavingQual);
2119  if (have_grouping)
2120  {
2121  scanjoin_target = make_group_input_target(root, final_target);
2122  scanjoin_target_parallel_safe =
2123  is_parallel_safe(root, (Node *) scanjoin_target->exprs);
2124  }
2125  else
2126  {
2127  scanjoin_target = grouping_target;
2128  scanjoin_target_parallel_safe = grouping_target_parallel_safe;
2129  }
2130 
2131  /*
2132  * If there are any SRFs in the targetlist, we must separate each of
2133  * these PathTargets into SRF-computing and SRF-free targets. Replace
2134  * each of the named targets with a SRF-free version, and remember the
2135  * list of additional projection steps we need to add afterwards.
2136  */
2137  if (parse->hasTargetSRFs)
2138  {
2139  /* final_target doesn't recompute any SRFs in sort_input_target */
2140  split_pathtarget_at_srfs(root, final_target, sort_input_target,
2141  &final_targets,
2142  &final_targets_contain_srfs);
2143  final_target = linitial_node(PathTarget, final_targets);
2144  Assert(!linitial_int(final_targets_contain_srfs));
2145  /* likewise for sort_input_target vs. grouping_target */
2146  split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
2147  &sort_input_targets,
2148  &sort_input_targets_contain_srfs);
2149  sort_input_target = linitial_node(PathTarget, sort_input_targets);
2150  Assert(!linitial_int(sort_input_targets_contain_srfs));
2151  /* likewise for grouping_target vs. scanjoin_target */
2152  split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
2153  &grouping_targets,
2154  &grouping_targets_contain_srfs);
2155  grouping_target = linitial_node(PathTarget, grouping_targets);
2156  Assert(!linitial_int(grouping_targets_contain_srfs));
2157  /* scanjoin_target will not have any SRFs precomputed for it */
2158  split_pathtarget_at_srfs(root, scanjoin_target, NULL,
2159  &scanjoin_targets,
2160  &scanjoin_targets_contain_srfs);
2161  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
2162  Assert(!linitial_int(scanjoin_targets_contain_srfs));
2163  }
2164  else
2165  {
2166  /* initialize lists; for most of these, dummy values are OK */
2167  final_targets = final_targets_contain_srfs = NIL;
2168  sort_input_targets = sort_input_targets_contain_srfs = NIL;
2169  grouping_targets = grouping_targets_contain_srfs = NIL;
2170  scanjoin_targets = list_make1(scanjoin_target);
2171  scanjoin_targets_contain_srfs = NIL;
2172  }
2173 
2174  /* Apply scan/join target. */
2175  scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
2176  && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
2177  apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
2178  scanjoin_targets_contain_srfs,
2179  scanjoin_target_parallel_safe,
2180  scanjoin_target_same_exprs);
2181 
2182  /*
2183  * Save the various upper-rel PathTargets we just computed into
2184  * root->upper_targets[]. The core code doesn't use this, but it
2185  * provides a convenient place for extensions to get at the info. For
2186  * consistency, we save all the intermediate targets, even though some
2187  * of the corresponding upperrels might not be needed for this query.
2188  */
2189  root->upper_targets[UPPERREL_FINAL] = final_target;
2190  root->upper_targets[UPPERREL_ORDERED] = final_target;
2191  root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
2192  root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
2193  root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
2194 
2195  /*
2196  * If we have grouping and/or aggregation, consider ways to implement
2197  * that. We build a new upperrel representing the output of this
2198  * phase.
2199  */
2200  if (have_grouping)
2201  {
2202  current_rel = create_grouping_paths(root,
2203  current_rel,
2204  grouping_target,
2205  grouping_target_parallel_safe,
2206  &agg_costs,
2207  gset_data);
2208  /* Fix things up if grouping_target contains SRFs */
2209  if (parse->hasTargetSRFs)
2210  adjust_paths_for_srfs(root, current_rel,
2211  grouping_targets,
2212  grouping_targets_contain_srfs);
2213  }
2214 
2215  /*
2216  * If we have window functions, consider ways to implement those. We
2217  * build a new upperrel representing the output of this phase.
2218  */
2219  if (activeWindows)
2220  {
2221  current_rel = create_window_paths(root,
2222  current_rel,
2223  grouping_target,
2224  sort_input_target,
2225  sort_input_target_parallel_safe,
2226  wflists,
2227  activeWindows);
2228  /* Fix things up if sort_input_target contains SRFs */
2229  if (parse->hasTargetSRFs)
2230  adjust_paths_for_srfs(root, current_rel,
2231  sort_input_targets,
2232  sort_input_targets_contain_srfs);
2233  }
2234 
2235  /*
2236  * If there is a DISTINCT clause, consider ways to implement that. We
2237  * build a new upperrel representing the output of this phase.
2238  */
2239  if (parse->distinctClause)
2240  {
2241  current_rel = create_distinct_paths(root,
2242  current_rel);
2243  }
2244  } /* end of if (setOperations) */
2245 
2246  /*
2247  * If ORDER BY was given, consider ways to implement that, and generate a
2248  * new upperrel containing only paths that emit the correct ordering and
2249  * project the correct final_target. We can apply the original
2250  * limit_tuples limit in sort costing here, but only if there are no
2251  * postponed SRFs.
2252  */
2253  if (parse->sortClause)
2254  {
2255  current_rel = create_ordered_paths(root,
2256  current_rel,
2257  final_target,
2258  final_target_parallel_safe,
2259  have_postponed_srfs ? -1.0 :
2260  limit_tuples);
2261  /* Fix things up if final_target contains SRFs */
2262  if (parse->hasTargetSRFs)
2263  adjust_paths_for_srfs(root, current_rel,
2264  final_targets,
2265  final_targets_contain_srfs);
2266  }
2267 
2268  /*
2269  * Now we are prepared to build the final-output upperrel.
2270  */
2271  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
2272 
2273  /*
2274  * If the input rel is marked consider_parallel and there's nothing that's
2275  * not parallel-safe in the LIMIT clause, then the final_rel can be marked
2276  * consider_parallel as well. Note that if the query has rowMarks or is
2277  * not a SELECT, consider_parallel will be false for every relation in the
2278  * query.
2279  */
2280  if (current_rel->consider_parallel &&
2281  is_parallel_safe(root, parse->limitOffset) &&
2282  is_parallel_safe(root, parse->limitCount))
2283  final_rel->consider_parallel = true;
2284 
2285  /*
2286  * If the current_rel belongs to a single FDW, so does the final_rel.
2287  */
2288  final_rel->serverid = current_rel->serverid;
2289  final_rel->userid = current_rel->userid;
2290  final_rel->useridiscurrent = current_rel->useridiscurrent;
2291  final_rel->fdwroutine = current_rel->fdwroutine;
2292 
2293  /*
2294  * Generate paths for the final_rel. Insert all surviving paths, with
2295  * LockRows, Limit, and/or ModifyTable steps added if needed.
2296  */
2297  foreach(lc, current_rel->pathlist)
2298  {
2299  Path *path = (Path *) lfirst(lc);
2300 
2301  /*
2302  * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
2303  * (Note: we intentionally test parse->rowMarks not root->rowMarks
2304  * here. If there are only non-locking rowmarks, they should be
2305  * handled by the ModifyTable node instead. However, root->rowMarks
2306  * is what goes into the LockRows node.)
2307  */
2308  if (parse->rowMarks)
2309  {
2310  path = (Path *) create_lockrows_path(root, final_rel, path,
2311  root->rowMarks,
2313  }
2314 
2315  /*
2316  * If there is a LIMIT/OFFSET clause, add the LIMIT node.
2317  */
2318  if (limit_needed(parse))
2319  {
2320  path = (Path *) create_limit_path(root, final_rel, path,
2321  parse->limitOffset,
2322  parse->limitCount,
2323  offset_est, count_est);
2324  }
2325 
2326  /*
2327  * If this is an INSERT/UPDATE/DELETE, and we're not being called from
2328  * inheritance_planner, add the ModifyTable node.
2329  */
2330  if (parse->commandType != CMD_SELECT && !inheritance_update)
2331  {
2332  Index rootRelation;
2333  List *withCheckOptionLists;
2334  List *returningLists;
2335  List *rowMarks;
2336 
2337  /*
2338  * If target is a partition root table, we need to mark the
2339  * ModifyTable node appropriately for that.
2340  */
2341  if (rt_fetch(parse->resultRelation, parse->rtable)->relkind ==
2342  RELKIND_PARTITIONED_TABLE)
2343  rootRelation = parse->resultRelation;
2344  else
2345  rootRelation = 0;
2346 
2347  /*
2348  * Set up the WITH CHECK OPTION and RETURNING lists-of-lists, if
2349  * needed.
2350  */
2351  if (parse->withCheckOptions)
2352  withCheckOptionLists = list_make1(parse->withCheckOptions);
2353  else
2354  withCheckOptionLists = NIL;
2355 
2356  if (parse->returningList)
2357  returningLists = list_make1(parse->returningList);
2358  else
2359  returningLists = NIL;
2360 
2361  /*
2362  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
2363  * will have dealt with fetching non-locked marked rows, else we
2364  * need to have ModifyTable do that.
2365  */
2366  if (parse->rowMarks)
2367  rowMarks = NIL;
2368  else
2369  rowMarks = root->rowMarks;
2370 
2371  path = (Path *)
2372  create_modifytable_path(root, final_rel,
2373  parse->commandType,
2374  parse->canSetTag,
2375  parse->resultRelation,
2376  rootRelation,
2377  false,
2379  list_make1(path),
2380  list_make1(root),
2381  withCheckOptionLists,
2382  returningLists,
2383  rowMarks,
2384  parse->onConflict,
2386  }
2387 
2388  /* And shove it into final_rel */
2389  add_path(final_rel, path);
2390  }
2391 
2392  /*
2393  * Generate partial paths for final_rel, too, if outer query levels might
2394  * be able to make use of them.
2395  */
2396  if (final_rel->consider_parallel && root->query_level > 1 &&
2397  !limit_needed(parse))
2398  {
2399  Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
2400  foreach(lc, current_rel->partial_pathlist)
2401  {
2402  Path *partial_path = (Path *) lfirst(lc);
2403 
2404  add_partial_path(final_rel, partial_path);
2405  }
2406  }
2407 
2408  extra.limit_needed = limit_needed(parse);
2409  extra.limit_tuples = limit_tuples;
2410  extra.count_est = count_est;
2411  extra.offset_est = offset_est;
2412 
2413  /*
2414  * If there is an FDW that's responsible for all baserels of the query,
2415  * let it consider adding ForeignPaths.
2416  */
2417  if (final_rel->fdwroutine &&
2418  final_rel->fdwroutine->GetForeignUpperPaths)
2420  current_rel, final_rel,
2421  &extra);
2422 
2423  /* Let extensions possibly add some more paths */
2425  (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2426  current_rel, final_rel, &extra);
2427 
2428  /* Note: currently, we leave it to callers to do set_cheapest() */
2429 }
RelOptInfo * plan_set_operations(PlannerInfo *root)
Definition: prepunion.c:103
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
Node * limitOffset
Definition: parsenodes.h:160
#define NIL
Definition: pg_list.h:65
List * rowMarks
Definition: pathnodes.h:292
static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
Definition: planner.c:2827
static void apply_scanjoin_target_to_paths(PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
Definition: planner.c:6996
PathTarget * pathtarget
Definition: pathnodes.h:1117
Query * parse
Definition: pathnodes.h:179
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:2666
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * sortClause
Definition: parsenodes.h:158
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3384
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3018
OnConflictExpr * onConflict
Definition: parsenodes.h:144
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:1071
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:3234
Oid userid
Definition: pathnodes.h:693
List * withCheckOptions
Definition: parsenodes.h:171
void split_pathtarget_at_srfs(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition: tlist.c:886
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:228
bool hasAggs
Definition: parsenodes.h:125
int resultRelation
Definition: parsenodes.h:122
int numWindowFuncs
Definition: clauses.h:22
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition: clauses.c:506
List * groupingSets
Definition: parsenodes.h:150
bool limit_needed(Query *parse)
Definition: planner.c:3012
Definition: nodes.h:525
RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra)
Definition: planmain.c:55
int errcode(int sqlerrcode)
Definition: elog.c:608
List * partial_pathlist
Definition: pathnodes.h:659
static RelOptInfo * create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel)
Definition: planner.c:4729
#define MemSet(start, val, len)
Definition: c.h:962
static PathTarget * make_group_input_target(PlannerInfo *root, PathTarget *final_target)
Definition: planner.c:5102
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
int assign_special_exec_param(PlannerInfo *root)
Definition: paramassign.c:584
bool useridiscurrent
Definition: pathnodes.h:694
List * rowMarks
Definition: parsenodes.h:163
#define linitial_node(type, l)
Definition: pg_list.h:198
LimitPath * create_limit_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, Node *limitOffset, Node *limitCount, int64 offset_est, int64 count_est)
Definition: pathnode.c:3545
bool hasRecursion
Definition: pathnodes.h:350
static RelOptInfo * create_window_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, WindowFuncLists *wflists, List *activeWindows)
Definition: planner.c:4552
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
static List * postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
Definition: planner.c:5327
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:5935
void preprocess_minmax_aggregates(PlannerInfo *root)
Definition: planagg.c:72
#define list_make1(x1)
Definition: pg_list.h:227
#define linitial_int(l)
Definition: pg_list.h:196
static RelOptInfo * create_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, const AggClauseCosts *agg_costs, grouping_sets_data *gd)
Definition: planner.c:3806
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:853
double tuple_fraction
Definition: pathnodes.h:336
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
#define ERROR
Definition: elog.h:43
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, CmdType operation, bool canSetTag, Index nominalRelation, Index rootRelation, bool partColsUpdated, List *resultRelations, List *subpaths, List *subroots, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: pathnode.c:3443
List * preprocess_targetlist(PlannerInfo *root)
Definition: preptlist.c:69
double limit_tuples
Definition: pathnodes.h:337
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1177
struct Path * cheapest_total_path
Definition: pathnodes.h:661
Node * limitCount
Definition: parsenodes.h:161
static PathTarget * make_window_input_target(PlannerInfo *root, PathTarget *final_target, List *activeWindows)
Definition: planner.c:5509
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:696
static void standard_qp_callback(PlannerInfo *root, void *extra)
Definition: planner.c:3595
#define create_pathtarget(root, tlist)
Definition: tlist.h:54
static grouping_sets_data * preprocess_grouping_sets(PlannerInfo *root)
Definition: planner.c:2438
List * returningList
Definition: parsenodes.h:146
#define list_make1_int(x1)
Definition: pg_list.h:238
#define ereport(elevel, rest)
Definition: elog.h:141
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * sort_pathkeys
Definition: pathnodes.h:303
Oid serverid
Definition: pathnodes.h:692
List * exprs
Definition: pathnodes.h:1046
unsigned int Index
Definition: c.h:476
static RelOptInfo * create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
Definition: planner.c:4941
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
List * groupClause
Definition: planner.c:99
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
bool hasWindowFuncs
Definition: parsenodes.h:126
bool canSetTag
Definition: parsenodes.h:118
static int list_length(const List *l)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:651
Index query_level
Definition: pathnodes.h:183
List * activeWindows
Definition: planner.c:98
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:822
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
static List * select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
Definition: planner.c:5360
bool hasHavingQual
Definition: pathnodes.h:347
List * pathlist
Definition: pathnodes.h:657
#define copyObject(obj)
Definition: nodes.h:641
Node * havingQual
Definition: parsenodes.h:152
List * processed_tlist
Definition: pathnodes.h:325
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:654
static PathTarget * make_sort_input_target(PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
Definition: planner.c:5721
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: pathnodes.h:314

◆ inheritance_planner()

static void inheritance_planner ( PlannerInfo root)
static

Definition at line 1210 of file planner.c.

References add_path(), adjust_appendrel_attrs(), PlannerInfo::append_rel_array, PlannerInfo::append_rel_list, Assert, assign_special_exec_param(), bms_add_member(), bms_is_member(), bms_make_singleton(), bms_next_member(), Query::canSetTag, ChangeVarNodes(), RelOptInfo::cheapest_total_path, AppendRelInfo::child_relid, CMD_DELETE, CMD_SELECT, CMD_UPDATE, Query::commandType, copyObject, create_append_path(), create_modifytable_path(), create_pathtarget, fetch_upper_rel(), forboth, grouping_planner(), RangeTblEntry::inh, INHKIND_INHERITED, INHKIND_PARTITIONED, PlannerInfo::inhTargetKind, PlannerInfo::init_plans, IS_DUMMY_REL, PlannerInfo::join_info_list, lappend(), lappend_int(), lfirst, lfirst_int, lfirst_node, list_length(), list_make1, list_make1_int, list_nth_cell(), makeNode, NIL, Query::onConflict, palloc0(), AppendRelInfo::parent_relid, parse(), PlannerInfo::parse, PlannerInfo::partColsUpdated, PlannerInfo::placeholder_list, preprocess_targetlist(), PlannerInfo::processed_tlist, RangeTblEntry::relkind, RelOptInfo::reltarget, Query::resultRelation, Query::returningList, Query::rowMarks, PlannerInfo::rowMarks, rt_fetch, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblEntry::securityQuals, set_cheapest(), PlannerInfo::simple_rel_array, PlannerInfo::simple_rel_array_size, PlannerInfo::simple_rte_array, subpath(), UPPERREL_FINAL, and Query::withCheckOptions.

Referenced by subquery_planner().

1211 {
1212  Query *parse = root->parse;
1213  int top_parentRTindex = parse->resultRelation;
1214  List *select_rtable;
1215  List *select_appinfos;
1216  List *child_appinfos;
1217  List *old_child_rtis;
1218  List *new_child_rtis;
1219  Bitmapset *subqueryRTindexes;
1220  Index next_subquery_rti;
1221  int nominalRelation = -1;
1222  Index rootRelation = 0;
1223  List *final_rtable = NIL;
1224  List *final_rowmarks = NIL;
1225  List *final_appendrels = NIL;
1226  int save_rel_array_size = 0;
1227  RelOptInfo **save_rel_array = NULL;
1228  AppendRelInfo **save_append_rel_array = NULL;
1229  List *subpaths = NIL;
1230  List *subroots = NIL;
1231  List *resultRelations = NIL;
1232  List *withCheckOptionLists = NIL;
1233  List *returningLists = NIL;
1234  List *rowMarks;
1235  RelOptInfo *final_rel;
1236  ListCell *lc;
1237  ListCell *lc2;
1238  Index rti;
1239  RangeTblEntry *parent_rte;
1240  Bitmapset *parent_relids;
1241  Query **parent_parses;
1242 
1243  /* Should only get here for UPDATE or DELETE */
1244  Assert(parse->commandType == CMD_UPDATE ||
1245  parse->commandType == CMD_DELETE);
1246 
1247  /*
1248  * We generate a modified instance of the original Query for each target
1249  * relation, plan that, and put all the plans into a list that will be
1250  * controlled by a single ModifyTable node. All the instances share the
1251  * same rangetable, but each instance must have its own set of subquery
1252  * RTEs within the finished rangetable because (1) they are likely to get
1253  * scribbled on during planning, and (2) it's not inconceivable that
1254  * subqueries could get planned differently in different cases. We need
1255  * not create duplicate copies of other RTE kinds, in particular not the
1256  * target relations, because they don't have either of those issues. Not
1257  * having to duplicate the target relations is important because doing so
1258  * (1) would result in a rangetable of length O(N^2) for N targets, with
1259  * at least O(N^3) work expended here; and (2) would greatly complicate
1260  * management of the rowMarks list.
1261  *
1262  * To begin with, generate a bitmapset of the relids of the subquery RTEs.
1263  */
1264  subqueryRTindexes = NULL;
1265  rti = 1;
1266  foreach(lc, parse->rtable)
1267  {
1269 
1270  if (rte->rtekind == RTE_SUBQUERY)
1271  subqueryRTindexes = bms_add_member(subqueryRTindexes, rti);
1272  rti++;
1273  }
1274 
1275  /*
1276  * If the parent RTE is a partitioned table, we should use that as the
1277  * nominal target relation, because the RTEs added for partitioned tables
1278  * (including the root parent) as child members of the inheritance set do
1279  * not appear anywhere else in the plan, so the confusion explained below
1280  * for non-partitioning inheritance cases is not possible.
1281  */
1282  parent_rte = rt_fetch(top_parentRTindex, parse->rtable);
1283  Assert(parent_rte->inh);
1284  if (parent_rte->relkind == RELKIND_PARTITIONED_TABLE)
1285  {
1286  nominalRelation = top_parentRTindex;
1287  rootRelation = top_parentRTindex;
1288  }
1289 
1290  /*
1291  * Before generating the real per-child-relation plans, do a cycle of
1292  * planning as though the query were a SELECT. The objective here is to
1293  * find out which child relations need to be processed, using the same
1294  * expansion and pruning logic as for a SELECT. We'll then pull out the
1295  * RangeTblEntry-s generated for the child rels, and make use of the
1296  * AppendRelInfo entries for them to guide the real planning. (This is
1297  * rather inefficient; we could perhaps stop short of making a full Path
1298  * tree. But this whole function is inefficient and slated for
1299  * destruction, so let's not contort query_planner for that.)
1300  */
1301  {
1302  PlannerInfo *subroot;
1303 
1304  /*
1305  * Flat-copy the PlannerInfo to prevent modification of the original.
1306  */
1307  subroot = makeNode(PlannerInfo);
1308  memcpy(subroot, root, sizeof(PlannerInfo));
1309 
1310  /*
1311  * Make a deep copy of the parsetree for this planning cycle to mess
1312  * around with, and change it to look like a SELECT. (Hack alert: the
1313  * target RTE still has updatedCols set if this is an UPDATE, so that
1314  * expand_partitioned_rtentry will correctly update
1315  * subroot->partColsUpdated.)
1316  */
1317  subroot->parse = copyObject(root->parse);
1318 
1319  subroot->parse->commandType = CMD_SELECT;
1320  subroot->parse->resultRelation = 0;
1321 
1322  /*
1323  * Ensure the subroot has its own copy of the original
1324  * append_rel_list, since it'll be scribbled on. (Note that at this
1325  * point, the list only contains AppendRelInfos for flattened UNION
1326  * ALL subqueries.)
1327  */
1328  subroot->append_rel_list = copyObject(root->append_rel_list);
1329 
1330  /*
1331  * Better make a private copy of the rowMarks, too.
1332  */
1333  subroot->rowMarks = copyObject(root->rowMarks);
1334 
1335  /* There shouldn't be any OJ info to translate, as yet */
1336  Assert(subroot->join_info_list == NIL);
1337  /* and we haven't created PlaceHolderInfos, either */
1338  Assert(subroot->placeholder_list == NIL);
1339 
1340  /* Generate Path(s) for accessing this result relation */
1341  grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
1342 
1343  /* Extract the info we need. */
1344  select_rtable = subroot->parse->rtable;
1345  select_appinfos = subroot->append_rel_list;
1346 
1347  /*
1348  * We need to propagate partColsUpdated back, too. (The later
1349  * planning cycles will not set this because they won't run
1350  * expand_partitioned_rtentry for the UPDATE target.)
1351  */
1352  root->partColsUpdated = subroot->partColsUpdated;
1353  }
1354 
1355  /*----------
1356  * Since only one rangetable can exist in the final plan, we need to make
1357  * sure that it contains all the RTEs needed for any child plan. This is
1358  * complicated by the need to use separate subquery RTEs for each child.
1359  * We arrange the final rtable as follows:
1360  * 1. All original rtable entries (with their original RT indexes).
1361  * 2. All the relation RTEs generated for children of the target table.
1362  * 3. Subquery RTEs for children after the first. We need N * (K - 1)
1363  * RT slots for this, if there are N subqueries and K child tables.
1364  * 4. Additional RTEs generated during the child planning runs, such as
1365  * children of inheritable RTEs other than the target table.
1366  * We assume that each child planning run will create an identical set
1367  * of type-4 RTEs.
1368  *
1369  * So the next thing to do is append the type-2 RTEs (the target table's
1370  * children) to the original rtable. We look through select_appinfos
1371  * to find them.
1372  *
1373  * To identify which AppendRelInfos are relevant as we thumb through
1374  * select_appinfos, we need to look for both direct and indirect children
1375  * of top_parentRTindex, so we use a bitmap of known parent relids.
1376  * expand_inherited_rtentry() always processes a parent before any of that
1377  * parent's children, so we should see an intermediate parent before its
1378  * children.
1379  *----------
1380  */
1381  child_appinfos = NIL;
1382  old_child_rtis = NIL;
1383  new_child_rtis = NIL;
1384  parent_relids = bms_make_singleton(top_parentRTindex);
1385  foreach(lc, select_appinfos)
1386  {
1387  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
1388  RangeTblEntry *child_rte;
1389 
1390  /* append_rel_list contains all append rels; ignore others */
1391  if (!bms_is_member(appinfo->parent_relid, parent_relids))
1392  continue;
1393 
1394  /* remember relevant AppendRelInfos for use below */
1395  child_appinfos = lappend(child_appinfos, appinfo);
1396 
1397  /* extract RTE for this child rel */
1398  child_rte = rt_fetch(appinfo->child_relid, select_rtable);
1399 
1400  /* and append it to the original rtable */
1401  parse->rtable = lappend(parse->rtable, child_rte);
1402 
1403  /* remember child's index in the SELECT rtable */
1404  old_child_rtis = lappend_int(old_child_rtis, appinfo->child_relid);
1405 
1406  /* and its new index in the final rtable */
1407  new_child_rtis = lappend_int(new_child_rtis, list_length(parse->rtable));
1408 
1409  /* if child is itself partitioned, update parent_relids */
1410  if (child_rte->inh)
1411  {
1412  Assert(child_rte->relkind == RELKIND_PARTITIONED_TABLE);
1413  parent_relids = bms_add_member(parent_relids, appinfo->child_relid);
1414  }
1415  }
1416 
1417  /*
1418  * It's possible that the RTIs we just assigned for the child rels in the
1419  * final rtable are different from what they were in the SELECT query.
1420  * Adjust the AppendRelInfos so that they will correctly map RT indexes to
1421  * the final indexes. We can do this left-to-right since no child rel's
1422  * final RT index could be greater than what it had in the SELECT query.
1423  */
1424  forboth(lc, old_child_rtis, lc2, new_child_rtis)
1425  {
1426  int old_child_rti = lfirst_int(lc);
1427  int new_child_rti = lfirst_int(lc2);
1428 
1429  if (old_child_rti == new_child_rti)
1430  continue; /* nothing to do */
1431 
1432  Assert(old_child_rti > new_child_rti);
1433 
1434  ChangeVarNodes((Node *) child_appinfos,
1435  old_child_rti, new_child_rti, 0);
1436  }
1437 
1438  /*
1439  * Now set up rangetable entries for subqueries for additional children
1440  * (the first child will just use the original ones). These all have to
1441  * look more or less real, or EXPLAIN will get unhappy; so we just make
1442  * them all clones of the original subqueries.
1443  */
1444  next_subquery_rti = list_length(parse->rtable) + 1;
1445  if (subqueryRTindexes != NULL)
1446  {
1447  int n_children = list_length(child_appinfos);
1448 
1449  while (n_children-- > 1)
1450  {
1451  int oldrti = -1;
1452 
1453  while ((oldrti = bms_next_member(subqueryRTindexes, oldrti)) >= 0)
1454  {
1455  RangeTblEntry *subqrte;
1456 
1457  subqrte = rt_fetch(oldrti, parse->rtable);
1458  parse->rtable = lappend(parse->rtable, copyObject(subqrte));
1459  }
1460  }
1461  }
1462 
1463  /*
1464  * The query for each child is obtained by translating the query for its
1465  * immediate parent, since the AppendRelInfo data we have shows deltas
1466  * between parents and children. We use the parent_parses array to
1467  * remember the appropriate query trees. This is indexed by parent relid.
1468  * Since the maximum number of parents is limited by the number of RTEs in
1469  * the SELECT query, we use that number to allocate the array. An extra
1470  * entry is needed since relids start from 1.
1471  */
1472  parent_parses = (Query **) palloc0((list_length(select_rtable) + 1) *
1473  sizeof(Query *));
1474  parent_parses[top_parentRTindex] = parse;
1475 
1476  /*
1477  * And now we can get on with generating a plan for each child table.
1478  */
1479  foreach(lc, child_appinfos)
1480  {
1481  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
1482  Index this_subquery_rti = next_subquery_rti;
1483  Query *parent_parse;
1484  PlannerInfo *subroot;
1485  RangeTblEntry *child_rte;
1486  RelOptInfo *sub_final_rel;
1487  Path *subpath;
1488 
1489  /*
1490  * expand_inherited_rtentry() always processes a parent before any of
1491  * that parent's children, so the parent query for this relation
1492  * should already be available.
1493  */
1494  parent_parse = parent_parses[appinfo->parent_relid];
1495  Assert(parent_parse != NULL);
1496 
1497  /*
1498  * We need a working copy of the PlannerInfo so that we can control
1499  * propagation of information back to the main copy.
1500  */
1501  subroot = makeNode(PlannerInfo);
1502  memcpy(subroot, root, sizeof(PlannerInfo));
1503 
1504  /*
1505  * Generate modified query with this rel as target. We first apply
1506  * adjust_appendrel_attrs, which copies the Query and changes
1507  * references to the parent RTE to refer to the current child RTE,
1508  * then fool around with subquery RTEs.
1509  */
1510  subroot->parse = (Query *)
1511  adjust_appendrel_attrs(subroot,
1512  (Node *) parent_parse,
1513  1, &appinfo);
1514 
1515  /*
1516  * If there are securityQuals attached to the parent, move them to the
1517  * child rel (they've already been transformed properly for that).
1518  */
1519  parent_rte = rt_fetch(appinfo->parent_relid, subroot->parse->rtable);
1520  child_rte = rt_fetch(appinfo->child_relid, subroot->parse->rtable);
1521  child_rte->securityQuals = parent_rte->securityQuals;
1522  parent_rte->securityQuals = NIL;
1523 
1524  /*
1525  * HACK: setting this to a value other than INHKIND_NONE signals to
1526  * relation_excluded_by_constraints() to treat the result relation as
1527  * being an appendrel member.
1528  */
1529  subroot->inhTargetKind =
1530  (rootRelation != 0) ? INHKIND_PARTITIONED : INHKIND_INHERITED;
1531 
1532  /*
1533  * If this child is further partitioned, remember it as a parent.
1534  * Since a partitioned table does not have any data, we don't need to
1535  * create a plan for it, and we can stop processing it here. We do,
1536  * however, need to remember its modified PlannerInfo for use when
1537  * processing its children, since we'll update their varnos based on
1538  * the delta from immediate parent to child, not from top to child.
1539  *
1540  * Note: a very non-obvious point is that we have not yet added
1541  * duplicate subquery RTEs to the subroot's rtable. We mustn't,
1542  * because then its children would have two sets of duplicates,
1543  * confusing matters.
1544  */
1545  if (child_rte->inh)
1546  {
1547  Assert(child_rte->relkind == RELKIND_PARTITIONED_TABLE);
1548  parent_parses[appinfo->child_relid] = subroot->parse;
1549  continue;
1550  }
1551 
1552  /*
1553  * Set the nominal target relation of the ModifyTable node if not
1554  * already done. If the target is a partitioned table, we already set
1555  * nominalRelation to refer to the partition root, above. For
1556  * non-partitioned inheritance cases, we'll use the first child
1557  * relation (even if it's excluded) as the nominal target relation.
1558  * Because of the way expand_inherited_rtentry works, that should be
1559  * the RTE representing the parent table in its role as a simple
1560  * member of the inheritance set.
1561  *
1562  * It would be logically cleaner to *always* use the inheritance
1563  * parent RTE as the nominal relation; but that RTE is not otherwise
1564  * referenced in the plan in the non-partitioned inheritance case.
1565  * Instead the duplicate child RTE created by expand_inherited_rtentry
1566  * is used elsewhere in the plan, so using the original parent RTE
1567  * would give rise to confusing use of multiple aliases in EXPLAIN
1568  * output for what the user will think is the "same" table. OTOH,
1569  * it's not a problem in the partitioned inheritance case, because
1570  * there is no duplicate RTE for the parent.
1571  */
1572  if (nominalRelation < 0)
1573  nominalRelation = appinfo->child_relid;
1574 
1575  /*
1576  * As above, each child plan run needs its own append_rel_list and
1577  * rowmarks, which should start out as pristine copies of the
1578  * originals. There can't be any references to UPDATE/DELETE target
1579  * rels in them; but there could be subquery references, which we'll
1580  * fix up in a moment.
1581  */
1582  subroot->append_rel_list = copyObject(root->append_rel_list);
1583  subroot->rowMarks = copyObject(root->rowMarks);
1584 
1585  /*
1586  * If this isn't the first child Query, adjust Vars and jointree
1587  * entries to reference the appropriate set of subquery RTEs.
1588  */
1589  if (final_rtable != NIL && subqueryRTindexes != NULL)
1590  {
1591  int oldrti = -1;
1592 
1593  while ((oldrti = bms_next_member(subqueryRTindexes, oldrti)) >= 0)
1594  {
1595  Index newrti = next_subquery_rti++;
1596 
1597  ChangeVarNodes((Node *) subroot->parse, oldrti, newrti, 0);
1598  ChangeVarNodes((Node *) subroot->append_rel_list,
1599  oldrti, newrti, 0);
1600  ChangeVarNodes((Node *) subroot->rowMarks, oldrti, newrti, 0);
1601  }
1602  }
1603 
1604  /* There shouldn't be any OJ info to translate, as yet */
1605  Assert(subroot->join_info_list == NIL);
1606  /* and we haven't created PlaceHolderInfos, either */
1607  Assert(subroot->placeholder_list == NIL);
1608 
1609  /* Generate Path(s) for accessing this result relation */
1610  grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
1611 
1612  /*
1613  * Select cheapest path in case there's more than one. We always run
1614  * modification queries to conclusion, so we care only for the
1615  * cheapest-total path.
1616  */
1617  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
1618  set_cheapest(sub_final_rel);
1619  subpath = sub_final_rel->cheapest_total_path;
1620 
1621  /*
1622  * If this child rel was excluded by constraint exclusion, exclude it
1623  * from the result plan.
1624  */
1625  if (IS_DUMMY_REL(sub_final_rel))
1626  continue;
1627 
1628  /*
1629  * If this is the first non-excluded child, its post-planning rtable
1630  * becomes the initial contents of final_rtable; otherwise, copy its
1631  * modified subquery RTEs into final_rtable, to ensure we have sane
1632  * copies of those. Also save the first non-excluded child's version
1633  * of the rowmarks list; we assume all children will end up with
1634  * equivalent versions of that. Likewise for append_rel_list.
1635  */
1636  if (final_rtable == NIL)
1637  {
1638  final_rtable = subroot->parse->rtable;
1639  final_rowmarks = subroot->rowMarks;
1640  final_appendrels = subroot->append_rel_list;
1641  }
1642  else
1643  {
1644  Assert(list_length(final_rtable) ==
1645  list_length(subroot->parse->rtable));
1646  if (subqueryRTindexes != NULL)
1647  {
1648  int oldrti = -1;
1649 
1650  while ((oldrti = bms_next_member(subqueryRTindexes, oldrti)) >= 0)
1651  {
1652  Index newrti = this_subquery_rti++;
1653  RangeTblEntry *subqrte;
1654  ListCell *newrticell;
1655 
1656  subqrte = rt_fetch(newrti, subroot->parse->rtable);
1657  newrticell = list_nth_cell(final_rtable, newrti - 1);
1658  lfirst(newrticell) = subqrte;
1659  }
1660  }
1661  }
1662 
1663  /*
1664  * We need to collect all the RelOptInfos from all child plans into
1665  * the main PlannerInfo, since setrefs.c will need them. We use the
1666  * last child's simple_rel_array, so we have to propagate forward the
1667  * RelOptInfos that were already built in previous children.
1668  */
1669  Assert(subroot->simple_rel_array_size >= save_rel_array_size);
1670  for (rti = 1; rti < save_rel_array_size; rti++)
1671  {
1672  RelOptInfo *brel = save_rel_array[rti];
1673 
1674  if (brel)
1675  subroot->simple_rel_array[rti] = brel;
1676  }
1677  save_rel_array_size = subroot->simple_rel_array_size;
1678  save_rel_array = subroot->simple_rel_array;
1679  save_append_rel_array = subroot->append_rel_array;
1680 
1681  /*
1682  * Make sure any initplans from this rel get into the outer list. Note
1683  * we're effectively assuming all children generate the same
1684  * init_plans.
1685  */
1686  root->init_plans = subroot->init_plans;
1687 
1688  /* Build list of sub-paths */
1689  subpaths = lappend(subpaths, subpath);
1690 
1691  /* Build list of modified subroots, too */
1692  subroots = lappend(subroots, subroot);
1693 
1694  /* Build list of target-relation RT indexes */
1695  resultRelations = lappend_int(resultRelations, appinfo->child_relid);
1696 
1697  /* Build lists of per-relation WCO and RETURNING targetlists */
1698  if (parse->withCheckOptions)
1699  withCheckOptionLists = lappend(withCheckOptionLists,
1700  subroot->parse->withCheckOptions);
1701  if (parse->returningList)
1702  returningLists = lappend(returningLists,
1703  subroot->parse->returningList);
1704 
1705  Assert(!parse->onConflict);
1706  }
1707 
1708  /* Result path must go into outer query's FINAL upperrel */
1709  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1710 
1711  /*
1712  * We don't currently worry about setting final_rel's consider_parallel
1713  * flag in this case, nor about allowing FDWs or create_upper_paths_hook
1714  * to get control here.
1715  */
1716 
1717  if (subpaths == NIL)
1718  {
1719  /*
1720  * We managed to exclude every child rel, so generate a dummy path
1721  * representing the empty set. Although it's clear that no data will
1722  * be updated or deleted, we will still need to have a ModifyTable
1723  * node so that any statement triggers are executed. (This could be
1724  * cleaner if we fixed nodeModifyTable.c to support zero child nodes,
1725  * but that probably wouldn't be a net win.)
1726  */
1727  Path *dummy_path;
1728 
1729  /* tlist processing never got done, either */
1730  root->processed_tlist = preprocess_targetlist(root);
1731  final_rel->reltarget = create_pathtarget(root, root->processed_tlist);
1732 
1733  /* Make a dummy path, cf set_dummy_rel_pathlist() */
1734  dummy_path = (Path *) create_append_path(NULL, final_rel, NIL, NIL,
1735  NIL, NULL, 0, false,
1736  NIL, -1);
1737 
1738  /* These lists must be nonempty to make a valid ModifyTable node */
1739  subpaths = list_make1(dummy_path);
1740  subroots = list_make1(root);
1741  resultRelations = list_make1_int(parse->resultRelation);
1742  if (parse->withCheckOptions)
1743  withCheckOptionLists = list_make1(parse->withCheckOptions);
1744  if (parse-