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 grouping_planner (PlannerInfo *root, 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, 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 void create_partial_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel)
 
static RelOptInfocreate_final_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_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)
 
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, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
PlannedStmtstandard_planner (Query *parse, const char *query_string, 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 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 preprocess_expression(), and 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 6136 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_incremental_sort_path(), create_sort_path(), enable_incremental_sort, 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, list_length(), NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_count_contained_in(), RelOptInfo::pathlist, and RelOptInfo::reltarget.

Referenced by create_ordinary_grouping_paths().

6142 {
6143  Query *parse = root->parse;
6144  Path *cheapest_path = input_rel->cheapest_total_path;
6145  ListCell *lc;
6146  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6147  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6148  List *havingQual = (List *) extra->havingQual;
6149  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6150 
6151  if (can_sort)
6152  {
6153  /*
6154  * Use any available suitably-sorted path as input, and also consider
6155  * sorting the cheapest-total path.
6156  */
6157  foreach(lc, input_rel->pathlist)
6158  {
6159  Path *path = (Path *) lfirst(lc);
6160  Path *path_original = path;
6161  bool is_sorted;
6162  int presorted_keys;
6163 
6164  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6165  path->pathkeys,
6166  &presorted_keys);
6167 
6168  if (path == cheapest_path || is_sorted)
6169  {
6170  /* Sort the cheapest-total path if it isn't already sorted */
6171  if (!is_sorted)
6172  path = (Path *) create_sort_path(root,
6173  grouped_rel,
6174  path,
6175  root->group_pathkeys,
6176  -1.0);
6177 
6178  /* Now decide what to stick atop it */
6179  if (parse->groupingSets)
6180  {
6181  consider_groupingsets_paths(root, grouped_rel,
6182  path, true, can_hash,
6183  gd, agg_costs, dNumGroups);
6184  }
6185  else if (parse->hasAggs)
6186  {
6187  /*
6188  * We have aggregation, possibly with plain GROUP BY. Make
6189  * an AggPath.
6190  */
6191  add_path(grouped_rel, (Path *)
6192  create_agg_path(root,
6193  grouped_rel,
6194  path,
6195  grouped_rel->reltarget,
6196  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6198  parse->groupClause,
6199  havingQual,
6200  agg_costs,
6201  dNumGroups));
6202  }
6203  else if (parse->groupClause)
6204  {
6205  /*
6206  * We have GROUP BY without aggregation or grouping sets.
6207  * Make a GroupPath.
6208  */
6209  add_path(grouped_rel, (Path *)
6210  create_group_path(root,
6211  grouped_rel,
6212  path,
6213  parse->groupClause,
6214  havingQual,
6215  dNumGroups));
6216  }
6217  else
6218  {
6219  /* Other cases should have been handled above */
6220  Assert(false);
6221  }
6222  }
6223 
6224  /*
6225  * Now we may consider incremental sort on this path, but only
6226  * when the path is not already sorted and when incremental sort
6227  * is enabled.
6228  */
6229  if (is_sorted || !enable_incremental_sort)
6230  continue;
6231 
6232  /* Restore the input path (we might have added Sort on top). */
6233  path = path_original;
6234 
6235  /* no shared prefix, no point in building incremental sort */
6236  if (presorted_keys == 0)
6237  continue;
6238 
6239  /*
6240  * We should have already excluded pathkeys of length 1 because
6241  * then presorted_keys > 0 would imply is_sorted was true.
6242  */
6243  Assert(list_length(root->group_pathkeys) != 1);
6244 
6245  path = (Path *) create_incremental_sort_path(root,
6246  grouped_rel,
6247  path,
6248  root->group_pathkeys,
6249  presorted_keys,
6250  -1.0);
6251 
6252  /* Now decide what to stick atop it */
6253  if (parse->groupingSets)
6254  {
6255  consider_groupingsets_paths(root, grouped_rel,
6256  path, true, can_hash,
6257  gd, agg_costs, dNumGroups);
6258  }
6259  else if (parse->hasAggs)
6260  {
6261  /*
6262  * We have aggregation, possibly with plain GROUP BY. Make an
6263  * AggPath.
6264  */
6265  add_path(grouped_rel, (Path *)
6266  create_agg_path(root,
6267  grouped_rel,
6268  path,
6269  grouped_rel->reltarget,
6270  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6272  parse->groupClause,
6273  havingQual,
6274  agg_costs,
6275  dNumGroups));
6276  }
6277  else if (parse->groupClause)
6278  {
6279  /*
6280  * We have GROUP BY without aggregation or grouping sets. Make
6281  * a GroupPath.
6282  */
6283  add_path(grouped_rel, (Path *)
6284  create_group_path(root,
6285  grouped_rel,
6286  path,
6287  parse->groupClause,
6288  havingQual,
6289  dNumGroups));
6290  }
6291  else
6292  {
6293  /* Other cases should have been handled above */
6294  Assert(false);
6295  }
6296  }
6297 
6298  /*
6299  * Instead of operating directly on the input relation, we can
6300  * consider finalizing a partially aggregated path.
6301  */
6302  if (partially_grouped_rel != NULL)
6303  {
6304  foreach(lc, partially_grouped_rel->pathlist)
6305  {
6306  Path *path = (Path *) lfirst(lc);
6307  Path *path_original = path;
6308  bool is_sorted;
6309  int presorted_keys;
6310 
6311  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6312  path->pathkeys,
6313  &presorted_keys);
6314 
6315  /*
6316  * Insert a Sort node, if required. But there's no point in
6317  * sorting anything but the cheapest path.
6318  */
6319  if (!is_sorted)
6320  {
6321  if (path != partially_grouped_rel->cheapest_total_path)
6322  continue;
6323  path = (Path *) create_sort_path(root,
6324  grouped_rel,
6325  path,
6326  root->group_pathkeys,
6327  -1.0);
6328  }
6329 
6330  if (parse->hasAggs)
6331  add_path(grouped_rel, (Path *)
6332  create_agg_path(root,
6333  grouped_rel,
6334  path,
6335  grouped_rel->reltarget,
6336  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6338  parse->groupClause,
6339  havingQual,
6340  agg_final_costs,
6341  dNumGroups));
6342  else
6343  add_path(grouped_rel, (Path *)
6344  create_group_path(root,
6345  grouped_rel,
6346  path,
6347  parse->groupClause,
6348  havingQual,
6349  dNumGroups));
6350 
6351  /*
6352  * Now we may consider incremental sort on this path, but only
6353  * when the path is not already sorted and when incremental
6354  * sort is enabled.
6355  */
6356  if (is_sorted || !enable_incremental_sort)
6357  continue;
6358 
6359  /* Restore the input path (we might have added Sort on top). */
6360  path = path_original;
6361 
6362  /* no shared prefix, not point in building incremental sort */
6363  if (presorted_keys == 0)
6364  continue;
6365 
6366  /*
6367  * We should have already excluded pathkeys of length 1
6368  * because then presorted_keys > 0 would imply is_sorted was
6369  * true.
6370  */
6371  Assert(list_length(root->group_pathkeys) != 1);
6372 
6373  path = (Path *) create_incremental_sort_path(root,
6374  grouped_rel,
6375  path,
6376  root->group_pathkeys,
6377  presorted_keys,
6378  -1.0);
6379 
6380  if (parse->hasAggs)
6381  add_path(grouped_rel, (Path *)
6382  create_agg_path(root,
6383  grouped_rel,
6384  path,
6385  grouped_rel->reltarget,
6386  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6388  parse->groupClause,
6389  havingQual,
6390  agg_final_costs,
6391  dNumGroups));
6392  else
6393  add_path(grouped_rel, (Path *)
6394  create_group_path(root,
6395  grouped_rel,
6396  path,
6397  parse->groupClause,
6398  havingQual,
6399  dNumGroups));
6400  }
6401  }
6402  }
6403 
6404  if (can_hash)
6405  {
6406  if (parse->groupingSets)
6407  {
6408  /*
6409  * Try for a hash-only groupingsets path over unsorted input.
6410  */
6411  consider_groupingsets_paths(root, grouped_rel,
6412  cheapest_path, false, true,
6413  gd, agg_costs, dNumGroups);
6414  }
6415  else
6416  {
6417  /*
6418  * Generate a HashAgg Path. We just need an Agg over the
6419  * cheapest-total input path, since input order won't matter.
6420  */
6421  add_path(grouped_rel, (Path *)
6422  create_agg_path(root, grouped_rel,
6423  cheapest_path,
6424  grouped_rel->reltarget,
6425  AGG_HASHED,
6427  parse->groupClause,
6428  havingQual,
6429  agg_costs,
6430  dNumGroups));
6431  }
6432 
6433  /*
6434  * Generate a Finalize HashAgg Path atop of the cheapest partially
6435  * grouped path, assuming there is one
6436  */
6437  if (partially_grouped_rel && partially_grouped_rel->pathlist)
6438  {
6439  Path *path = partially_grouped_rel->cheapest_total_path;
6440 
6441  add_path(grouped_rel, (Path *)
6442  create_agg_path(root,
6443  grouped_rel,
6444  path,
6445  grouped_rel->reltarget,
6446  AGG_HASHED,
6448  parse->groupClause,
6449  havingQual,
6450  agg_final_costs,
6451  dNumGroups));
6452  }
6453  }
6454 
6455  /*
6456  * When partitionwise aggregate is used, we might have fully aggregated
6457  * paths in the partial pathlist, because add_paths_to_append_rel() will
6458  * consider a path for grouped_rel consisting of a Parallel Append of
6459  * non-partial paths from each child.
6460  */
6461  if (grouped_rel->partial_pathlist != NIL)
6462  gather_grouping_paths(root, grouped_rel);
6463 }
List * group_pathkeys
Definition: pathnodes.h:296
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:162
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:139
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:3669
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6867
bool hasAggs
Definition: parsenodes.h:133
List * groupingSets
Definition: parsenodes.h:161
List * partial_pathlist
Definition: pathnodes.h:697
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2892
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2552
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:3096
struct Path * cheapest_total_path
Definition: pathnodes.h:699
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2553
List * pathkeys
Definition: pathnodes.h:1196
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * groupClause
Definition: parsenodes.h:158
List * pathlist
Definition: pathnodes.h:695
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2985
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2593
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:692
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ adjust_paths_for_srfs()

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

Definition at line 5691 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().

5693 {
5694  ListCell *lc;
5695 
5696  Assert(list_length(targets) == list_length(targets_contain_srfs));
5697  Assert(!linitial_int(targets_contain_srfs));
5698 
5699  /* If no SRFs appear at this plan level, nothing to do */
5700  if (list_length(targets) == 1)
5701  return;
5702 
5703  /*
5704  * Stack SRF-evaluation nodes atop each path for the rel.
5705  *
5706  * In principle we should re-run set_cheapest() here to identify the
5707  * cheapest path, but it seems unlikely that adding the same tlist eval
5708  * costs to all the paths would change that, so we don't bother. Instead,
5709  * just assume that the cheapest-startup and cheapest-total paths remain
5710  * so. (There should be no parameterized paths anymore, so we needn't
5711  * worry about updating cheapest_parameterized_paths.)
5712  */
5713  foreach(lc, rel->pathlist)
5714  {
5715  Path *subpath = (Path *) lfirst(lc);
5716  Path *newpath = subpath;
5717  ListCell *lc1,
5718  *lc2;
5719 
5720  Assert(subpath->param_info == NULL);
5721  forboth(lc1, targets, lc2, targets_contain_srfs)
5722  {
5723  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5724  bool contains_srfs = (bool) lfirst_int(lc2);
5725 
5726  /* If this level doesn't contain SRFs, do regular projection */
5727  if (contains_srfs)
5728  newpath = (Path *) create_set_projection_path(root,
5729  rel,
5730  newpath,
5731  thistarget);
5732  else
5733  newpath = (Path *) apply_projection_to_path(root,
5734  rel,
5735  newpath,
5736  thistarget);
5737  }
5738  lfirst(lc) = newpath;
5739  if (subpath == rel->cheapest_startup_path)
5740  rel->cheapest_startup_path = newpath;
5741  if (subpath == rel->cheapest_total_path)
5742  rel->cheapest_total_path = newpath;
5743  }
5744 
5745  /* Likewise for partial paths, if any */
5746  foreach(lc, rel->partial_pathlist)
5747  {
5748  Path *subpath = (Path *) lfirst(lc);
5749  Path *newpath = subpath;
5750  ListCell *lc1,
5751  *lc2;
5752 
5753  Assert(subpath->param_info == NULL);
5754  forboth(lc1, targets, lc2, targets_contain_srfs)
5755  {
5756  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5757  bool contains_srfs = (bool) lfirst_int(lc2);
5758 
5759  /* If this level doesn't contain SRFs, do regular projection */
5760  if (contains_srfs)
5761  newpath = (Path *) create_set_projection_path(root,
5762  rel,
5763  newpath,
5764  thistarget);
5765  else
5766  {
5767  /* avoid apply_projection_to_path, in case of multiple refs */
5768  newpath = (Path *) create_projection_path(root,
5769  rel,
5770  newpath,
5771  thistarget);
5772  }
5773  }
5774  lfirst(lc) = newpath;
5775  }
5776 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2734
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
struct Path * cheapest_startup_path
Definition: pathnodes.h:698
ParamPathInfo * param_info
Definition: pathnodes.h:1185
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2626
List * partial_pathlist
Definition: pathnodes.h:697
#define linitial_int(l)
Definition: pg_list.h:175
#define lfirst_int(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:172
struct Path * cheapest_total_path
Definition: pathnodes.h:699
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2823
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * pathlist
Definition: pathnodes.h:695
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
unsigned char bool
Definition: c.h:391

◆ 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 6997 of file planner.c.

References add_paths_to_append_rel(), adjust_appendrel_attrs(), adjust_paths_for_srfs(), Assert, bms_next_member(), check_stack_depth(), RelOptInfo::consider_parallel, copy_pathtarget(), create_projection_path(), PathTarget::exprs, find_appinfos_by_relids(), generate_useful_gather_paths(), Query::hasTargetSRFs, i, IS_DUMMY_REL, IS_OTHER_REL, IS_PARTITIONED_REL, lappend(), lfirst, lfirst_node, linitial_node, RelOptInfo::live_parts, llast_node, NIL, 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().

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

◆ can_partial_agg()

static bool can_partial_agg ( PlannerInfo root)
static

Definition at line 6955 of file planner.c.

References Query::groupClause, Query::groupingSets, Query::hasAggs, PlannerInfo::hasNonPartialAggs, PlannerInfo::hasNonSerialAggs, NIL, parse(), and PlannerInfo::parse.

Referenced by create_grouping_paths().

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

◆ common_prefix_cmp()

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

Definition at line 5196 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().

5197 {
5198  const WindowClauseSortData *wcsa = a;
5199  const WindowClauseSortData *wcsb = b;
5200  ListCell *item_a;
5201  ListCell *item_b;
5202 
5203  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5204  {
5207 
5208  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5209  return -1;
5210  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5211  return 1;
5212  else if (sca->sortop > scb->sortop)
5213  return -1;
5214  else if (sca->sortop < scb->sortop)
5215  return 1;
5216  else if (sca->nulls_first && !scb->nulls_first)
5217  return -1;
5218  else if (!sca->nulls_first && scb->nulls_first)
5219  return 1;
5220  /* no need to compare eqop, since it is fully determined by sortop */
5221  }
5222 
5223  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5224  return -1;
5225  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5226  return 1;
5227 
5228  return 0;
5229 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
Index tleSortGroupRef
Definition: parsenodes.h:1295
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:149

◆ 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 3669 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, for_each_from, get_hash_memory_limit(), 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, 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, and grouping_sets_data::unsortable_sets.

Referenced by add_paths_to_grouping_rel().

3677 {
3678  Query *parse = root->parse;
3679  Size hash_mem_limit = get_hash_memory_limit();
3680 
3681  /*
3682  * If we're not being offered sorted input, then only consider plans that
3683  * can be done entirely by hashing.
3684  *
3685  * We can hash everything if it looks like it'll fit in hash_mem. But if
3686  * the input is actually sorted despite not being advertised as such, we
3687  * prefer to make use of that in order to use less memory.
3688  *
3689  * If none of the grouping sets are sortable, then ignore the hash_mem
3690  * limit and generate a path anyway, since otherwise we'll just fail.
3691  */
3692  if (!is_sorted)
3693  {
3694  List *new_rollups = NIL;
3695  RollupData *unhashed_rollup = NULL;
3696  List *sets_data;
3697  List *empty_sets_data = NIL;
3698  List *empty_sets = NIL;
3699  ListCell *lc;
3700  ListCell *l_start = list_head(gd->rollups);
3701  AggStrategy strat = AGG_HASHED;
3702  double hashsize;
3703  double exclude_groups = 0.0;
3704 
3705  Assert(can_hash);
3706 
3707  /*
3708  * If the input is coincidentally sorted usefully (which can happen
3709  * even if is_sorted is false, since that only means that our caller
3710  * has set up the sorting for us), then save some hashtable space by
3711  * making use of that. But we need to watch out for degenerate cases:
3712  *
3713  * 1) If there are any empty grouping sets, then group_pathkeys might
3714  * be NIL if all non-empty grouping sets are unsortable. In this case,
3715  * there will be a rollup containing only empty groups, and the
3716  * pathkeys_contained_in test is vacuously true; this is ok.
3717  *
3718  * XXX: the above relies on the fact that group_pathkeys is generated
3719  * from the first rollup. If we add the ability to consider multiple
3720  * sort orders for grouping input, this assumption might fail.
3721  *
3722  * 2) If there are no empty sets and only unsortable sets, then the
3723  * rollups list will be empty (and thus l_start == NULL), and
3724  * group_pathkeys will be NIL; we must ensure that the vacuously-true
3725  * pathkeys_contained_in test doesn't cause us to crash.
3726  */
3727  if (l_start != NULL &&
3729  {
3730  unhashed_rollup = lfirst_node(RollupData, l_start);
3731  exclude_groups = unhashed_rollup->numGroups;
3732  l_start = lnext(gd->rollups, l_start);
3733  }
3734 
3735  hashsize = estimate_hashagg_tablesize(root,
3736  path,
3737  agg_costs,
3738  dNumGroups - exclude_groups);
3739 
3740  /*
3741  * gd->rollups is empty if we have only unsortable columns to work
3742  * with. Override hash_mem in that case; otherwise, we'll rely on the
3743  * sorted-input case to generate usable mixed paths.
3744  */
3745  if (hashsize > hash_mem_limit && gd->rollups)
3746  return; /* nope, won't fit */
3747 
3748  /*
3749  * We need to burst the existing rollups list into individual grouping
3750  * sets and recompute a groupClause for each set.
3751  */
3752  sets_data = list_copy(gd->unsortable_sets);
3753 
3754  for_each_cell(lc, gd->rollups, l_start)
3755  {
3756  RollupData *rollup = lfirst_node(RollupData, lc);
3757 
3758  /*
3759  * If we find an unhashable rollup that's not been skipped by the
3760  * "actually sorted" check above, we can't cope; we'd need sorted
3761  * input (with a different sort order) but we can't get that here.
3762  * So bail out; we'll get a valid path from the is_sorted case
3763  * instead.
3764  *
3765  * The mere presence of empty grouping sets doesn't make a rollup
3766  * unhashable (see preprocess_grouping_sets), we handle those
3767  * specially below.
3768  */
3769  if (!rollup->hashable)
3770  return;
3771 
3772  sets_data = list_concat(sets_data, rollup->gsets_data);
3773  }
3774  foreach(lc, sets_data)
3775  {
3777  List *gset = gs->set;
3778  RollupData *rollup;
3779 
3780  if (gset == NIL)
3781  {
3782  /* Empty grouping sets can't be hashed. */
3783  empty_sets_data = lappend(empty_sets_data, gs);
3784  empty_sets = lappend(empty_sets, NIL);
3785  }
3786  else
3787  {
3788  rollup = makeNode(RollupData);
3789 
3790  rollup->groupClause = preprocess_groupclause(root, gset);
3791  rollup->gsets_data = list_make1(gs);
3792  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
3793  rollup->gsets_data,
3794  gd->tleref_to_colnum_map);
3795  rollup->numGroups = gs->numGroups;
3796  rollup->hashable = true;
3797  rollup->is_hashed = true;
3798  new_rollups = lappend(new_rollups, rollup);
3799  }
3800  }
3801 
3802  /*
3803  * If we didn't find anything nonempty to hash, then bail. We'll
3804  * generate a path from the is_sorted case.
3805  */
3806  if (new_rollups == NIL)
3807  return;
3808 
3809  /*
3810  * If there were empty grouping sets they should have been in the
3811  * first rollup.
3812  */
3813  Assert(!unhashed_rollup || !empty_sets);
3814 
3815  if (unhashed_rollup)
3816  {
3817  new_rollups = lappend(new_rollups, unhashed_rollup);
3818  strat = AGG_MIXED;
3819  }
3820  else if (empty_sets)
3821  {
3822  RollupData *rollup = makeNode(RollupData);
3823 
3824  rollup->groupClause = NIL;
3825  rollup->gsets_data = empty_sets_data;
3826  rollup->gsets = empty_sets;
3827  rollup->numGroups = list_length(empty_sets);
3828  rollup->hashable = false;
3829  rollup->is_hashed = false;
3830  new_rollups = lappend(new_rollups, rollup);
3831  strat = AGG_MIXED;
3832  }
3833 
3834  add_path(grouped_rel, (Path *)
3836  grouped_rel,
3837  path,
3838  (List *) parse->havingQual,
3839  strat,
3840  new_rollups,
3841  agg_costs,
3842  dNumGroups));
3843  return;
3844  }
3845 
3846  /*
3847  * If we have sorted input but nothing we can do with it, bail.
3848  */
3849  if (list_length(gd->rollups) == 0)
3850  return;
3851 
3852  /*
3853  * Given sorted input, we try and make two paths: one sorted and one mixed
3854  * sort/hash. (We need to try both because hashagg might be disabled, or
3855  * some columns might not be sortable.)
3856  *
3857  * can_hash is passed in as false if some obstacle elsewhere (such as
3858  * ordered aggs) means that we shouldn't consider hashing at all.
3859  */
3860  if (can_hash && gd->any_hashable)
3861  {
3862  List *rollups = NIL;
3863  List *hash_sets = list_copy(gd->unsortable_sets);
3864  double availspace = hash_mem_limit;
3865  ListCell *lc;
3866 
3867  /*
3868  * Account first for space needed for groups we can't sort at all.
3869  */
3870  availspace -= estimate_hashagg_tablesize(root,
3871  path,
3872  agg_costs,
3873  gd->dNumHashGroups);
3874 
3875  if (availspace > 0 && list_length(gd->rollups) > 1)
3876  {
3877  double scale;
3878  int num_rollups = list_length(gd->rollups);
3879  int k_capacity;
3880  int *k_weights = palloc(num_rollups * sizeof(int));
3881  Bitmapset *hash_items = NULL;
3882  int i;
3883 
3884  /*
3885  * We treat this as a knapsack problem: the knapsack capacity
3886  * represents hash_mem, the item weights are the estimated memory
3887  * usage of the hashtables needed to implement a single rollup,
3888  * and we really ought to use the cost saving as the item value;
3889  * however, currently the costs assigned to sort nodes don't
3890  * reflect the comparison costs well, and so we treat all items as
3891  * of equal value (each rollup we hash instead saves us one sort).
3892  *
3893  * To use the discrete knapsack, we need to scale the values to a
3894  * reasonably small bounded range. We choose to allow a 5% error
3895  * margin; we have no more than 4096 rollups in the worst possible
3896  * case, which with a 5% error margin will require a bit over 42MB
3897  * of workspace. (Anyone wanting to plan queries that complex had
3898  * better have the memory for it. In more reasonable cases, with
3899  * no more than a couple of dozen rollups, the memory usage will
3900  * be negligible.)
3901  *
3902  * k_capacity is naturally bounded, but we clamp the values for
3903  * scale and weight (below) to avoid overflows or underflows (or
3904  * uselessly trying to use a scale factor less than 1 byte).
3905  */
3906  scale = Max(availspace / (20.0 * num_rollups), 1.0);
3907  k_capacity = (int) floor(availspace / scale);
3908 
3909  /*
3910  * We leave the first rollup out of consideration since it's the
3911  * one that matches the input sort order. We assign indexes "i"
3912  * to only those entries considered for hashing; the second loop,
3913  * below, must use the same condition.
3914  */
3915  i = 0;
3916  for_each_from(lc, gd->rollups, 1)
3917  {
3918  RollupData *rollup = lfirst_node(RollupData, lc);
3919 
3920  if (rollup->hashable)
3921  {
3922  double sz = estimate_hashagg_tablesize(root,
3923  path,
3924  agg_costs,
3925  rollup->numGroups);
3926 
3927  /*
3928  * If sz is enormous, but hash_mem (and hence scale) is
3929  * small, avoid integer overflow here.
3930  */
3931  k_weights[i] = (int) Min(floor(sz / scale),
3932  k_capacity + 1.0);
3933  ++i;
3934  }
3935  }
3936 
3937  /*
3938  * Apply knapsack algorithm; compute the set of items which
3939  * maximizes the value stored (in this case the number of sorts
3940  * saved) while keeping the total size (approximately) within
3941  * capacity.
3942  */
3943  if (i > 0)
3944  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
3945 
3946  if (!bms_is_empty(hash_items))
3947  {
3948  rollups = list_make1(linitial(gd->rollups));
3949 
3950  i = 0;
3951  for_each_from(lc, gd->rollups, 1)
3952  {
3953  RollupData *rollup = lfirst_node(RollupData, lc);
3954 
3955  if (rollup->hashable)
3956  {
3957  if (bms_is_member(i, hash_items))
3958  hash_sets = list_concat(hash_sets,
3959  rollup->gsets_data);
3960  else
3961  rollups = lappend(rollups, rollup);
3962  ++i;
3963  }
3964  else
3965  rollups = lappend(rollups, rollup);
3966  }
3967  }
3968  }
3969 
3970  if (!rollups && hash_sets)
3971  rollups = list_copy(gd->rollups);
3972 
3973  foreach(lc, hash_sets)
3974  {
3976  RollupData *rollup = makeNode(RollupData);
3977 
3978  Assert(gs->set != NIL);
3979 
3980  rollup->groupClause = preprocess_groupclause(root, gs->set);
3981  rollup->gsets_data = list_make1(gs);
3982  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
3983  rollup->gsets_data,
3984  gd->tleref_to_colnum_map);
3985  rollup->numGroups = gs->numGroups;
3986  rollup->hashable = true;
3987  rollup->is_hashed = true;
3988  rollups = lcons(rollup, rollups);
3989  }
3990 
3991  if (rollups)
3992  {
3993  add_path(grouped_rel, (Path *)
3995  grouped_rel,
3996  path,
3997  (List *) parse->havingQual,
3998  AGG_MIXED,
3999  rollups,
4000  agg_costs,
4001  dNumGroups));
4002  }
4003  }
4004 
4005  /*
4006  * Now try the simple sorted case.
4007  */
4008  if (!gd->unsortable_sets)
4009  add_path(grouped_rel, (Path *)
4011  grouped_rel,
4012  path,
4013  (List *) parse->havingQual,
4014  AGG_SORTED,
4015  gd->rollups,
4016  agg_costs,
4017  dNumGroups));
4018 }
List * group_pathkeys
Definition: pathnodes.h:296
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:162
List * groupClause
Definition: pathnodes.h:1793
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
double estimate_hashagg_tablesize(PlannerInfo *root, Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: selfuncs.c:3870
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:2709
Cardinality numGroups
Definition: pathnodes.h:1796
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417
#define Min(x, y)
Definition: c.h:986
bool is_hashed
Definition: pathnodes.h:1798
List * list_copy(const List *oldlist)
Definition: list.c:1418
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int scale
Definition: pgbench.c:191
double dNumHashGroups
Definition: planner.c:110
#define list_make1(x1)
Definition: pg_list.h:206
#define linitial(l)
Definition: pg_list.h:174
int * tleref_to_colnum_map
Definition: planner.c:115
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
List * lappend(List *list, void *datum)
Definition: list.c:336
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:2090
List * lcons(void *datum, List *list)
Definition: list.c:468
List * pathkeys
Definition: pathnodes.h:1196
#define Max(x, y)
Definition: c.h:980
#define makeNode(_type_)
Definition: nodes.h:584
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
static int list_length(const List *l)
Definition: pg_list.h:149
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
List * unsortable_sets
Definition: planner.c:114
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3401
Cardinality numGroups
Definition: pathnodes.h:1787
AggStrategy
Definition: nodes.h:766
void * palloc(Size size)
Definition: mcxt.c:1062
int i
bool hashable
Definition: pathnodes.h:1797
Node * havingQual
Definition: parsenodes.h:163
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:1795
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:3163
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673
List * gsets
Definition: pathnodes.h:1794

◆ create_degenerate_grouping_paths()

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

Definition at line 3469 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().

3471 {
3472  Query *parse = root->parse;
3473  int nrows;
3474  Path *path;
3475 
3476  nrows = list_length(parse->groupingSets);
3477  if (nrows > 1)
3478  {
3479  /*
3480  * Doesn't seem worthwhile writing code to cons up a generate_series
3481  * or a values scan to emit multiple rows. Instead just make N clones
3482  * and append them. (With a volatile HAVING clause, this means you
3483  * might get between 0 and N output rows. Offhand I think that's
3484  * desired.)
3485  */
3486  List *paths = NIL;
3487 
3488  while (--nrows >= 0)
3489  {
3490  path = (Path *)
3491  create_group_result_path(root, grouped_rel,
3492  grouped_rel->reltarget,
3493  (List *) parse->havingQual);
3494  paths = lappend(paths, path);
3495  }
3496  path = (Path *)
3497  create_append_path(root,
3498  grouped_rel,
3499  paths,
3500  NIL,
3501  NIL,
3502  NULL,
3503  0,
3504  false,
3505  -1);
3506  }
3507  else
3508  {
3509  /* No grouping sets, or just one, so one output row */
3510  path = (Path *)
3511  create_group_result_path(root, grouped_rel,
3512  grouped_rel->reltarget,
3513  (List *) parse->havingQual);
3514  }
3515 
3516  add_path(grouped_rel, path);
3517 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:162
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * groupingSets
Definition: parsenodes.h:161
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition: pathnode.c:1244
List * lappend(List *list, void *datum)
Definition: list.c:336
static int list_length(const List *l)
Definition: pg_list.h:149
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1504
Node * havingQual
Definition: parsenodes.h:163
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:692
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ create_distinct_paths()

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

Definition at line 4238 of file planner.c.

References RelOptInfo::consider_parallel, create_final_distinct_paths(), create_partial_distinct_paths(), create_upper_paths_hook, ereport, errcode(), errdetail(), errmsg(), ERROR, RelOptInfo::fdwroutine, fetch_upper_rel(), FdwRoutine::GetForeignUpperPaths, NIL, RelOptInfo::pathlist, RelOptInfo::serverid, set_cheapest(), UPPERREL_DISTINCT, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by grouping_planner().

4239 {
4240  RelOptInfo *distinct_rel;
4241 
4242  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4243  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4244 
4245  /*
4246  * We don't compute anything at this level, so distinct_rel will be
4247  * parallel-safe if the input rel is parallel-safe. In particular, if
4248  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4249  * output those expressions, and will not be parallel-safe unless those
4250  * expressions are parallel-safe.
4251  */
4252  distinct_rel->consider_parallel = input_rel->consider_parallel;
4253 
4254  /*
4255  * If the input rel belongs to a single FDW, so does the distinct_rel.
4256  */
4257  distinct_rel->serverid = input_rel->serverid;
4258  distinct_rel->userid = input_rel->userid;
4259  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4260  distinct_rel->fdwroutine = input_rel->fdwroutine;
4261 
4262  /* build distinct paths based on input_rel's pathlist */
4263  create_final_distinct_paths(root, input_rel, distinct_rel);
4264 
4265  /* now build distinct paths based on input_rel's partial_pathlist */
4266  create_partial_distinct_paths(root, input_rel, distinct_rel);
4267 
4268  /* Give a helpful error if we failed to create any paths */
4269  if (distinct_rel->pathlist == NIL)
4270  ereport(ERROR,
4271  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4272  errmsg("could not implement DISTINCT"),
4273  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4274 
4275  /*
4276  * If there is an FDW that's responsible for all baserels of the query,
4277  * let it consider adding ForeignPaths.
4278  */
4279  if (distinct_rel->fdwroutine &&
4280  distinct_rel->fdwroutine->GetForeignUpperPaths)
4281  distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4283  input_rel,
4284  distinct_rel,
4285  NULL);
4286 
4287  /* Let extensions possibly add some more paths */
4289  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
4290  distinct_rel, NULL);
4291 
4292  /* Now choose the best path(s) */
4293  set_cheapest(distinct_rel);
4294 
4295  return distinct_rel;
4296 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
#define NIL
Definition: pg_list.h:65
Oid userid
Definition: pathnodes.h:733
int errcode(int sqlerrcode)
Definition: elog.c:698
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:734
#define ERROR
Definition: elog.h:46
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
int errdetail(const char *fmt,...)
Definition: elog.c:1042
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:732
#define ereport(elevel,...)
Definition: elog.h:157
static RelOptInfo * create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_rel)
Definition: planner.c:4430
bool consider_parallel
Definition: pathnodes.h:689
int errmsg(const char *fmt,...)
Definition: elog.c:909
List * pathlist
Definition: pathnodes.h:695
static void create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel)
Definition: planner.c:4307

◆ create_final_distinct_paths()

static RelOptInfo * create_final_distinct_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo distinct_rel 
)
static

Definition at line 4430 of file planner.c.

References add_path(), AGG_HASHED, AGGSPLIT_SIMPLE, Assert, RelOptInfo::cheapest_total_path, create_agg_path(), create_sort_path(), create_upper_unique_path(), PlannerInfo::distinct_pathkeys, Query::distinctClause, enable_hashagg, estimate_num_groups(), get_sortgrouplist_exprs(), Query::groupClause, grouping_is_hashable(), grouping_is_sortable(), Query::groupingSets, Query::hasAggs, Query::hasDistinctOn, PlannerInfo::hasHavingQual, lfirst, list_length(), NIL, parse(), PlannerInfo::parse, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, Path::pathtarget, Path::rows, PlannerInfo::sort_pathkeys, and Query::targetList.

Referenced by create_distinct_paths(), and create_partial_distinct_paths().

4432 {
4433  Query *parse = root->parse;
4434  Path *cheapest_input_path = input_rel->cheapest_total_path;
4435  double numDistinctRows;
4436  bool allow_hash;
4437  Path *path;
4438  ListCell *lc;
4439 
4440  /* Estimate number of distinct rows there will be */
4441  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4442  root->hasHavingQual)
4443  {
4444  /*
4445  * If there was grouping or aggregation, use the number of input rows
4446  * as the estimated number of DISTINCT rows (ie, assume the input is
4447  * already mostly unique).
4448  */
4449  numDistinctRows = cheapest_input_path->rows;
4450  }
4451  else
4452  {
4453  /*
4454  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4455  */
4456  List *distinctExprs;
4457 
4458  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4459  parse->targetList);
4460  numDistinctRows = estimate_num_groups(root, distinctExprs,
4461  cheapest_input_path->rows,
4462  NULL, NULL);
4463  }
4464 
4465  /*
4466  * Consider sort-based implementations of DISTINCT, if possible.
4467  */
4469  {
4470  /*
4471  * First, if we have any adequately-presorted paths, just stick a
4472  * Unique node on those. Then consider doing an explicit sort of the
4473  * cheapest input path and Unique'ing that.
4474  *
4475  * When we have DISTINCT ON, we must sort by the more rigorous of
4476  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4477  * Also, if we do have to do an explicit sort, we might as well use
4478  * the more rigorous ordering to avoid a second sort later. (Note
4479  * that the parser will have ensured that one clause is a prefix of
4480  * the other.)
4481  */
4482  List *needed_pathkeys;
4483 
4484  if (parse->hasDistinctOn &&
4486  list_length(root->sort_pathkeys))
4487  needed_pathkeys = root->sort_pathkeys;
4488  else
4489  needed_pathkeys = root->distinct_pathkeys;
4490 
4491  foreach(lc, input_rel->pathlist)
4492  {
4493  Path *path = (Path *) lfirst(lc);
4494 
4495  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4496  {
4497  add_path(distinct_rel, (Path *)
4498  create_upper_unique_path(root, distinct_rel,
4499  path,
4501  numDistinctRows));
4502  }
4503  }
4504 
4505  /* For explicit-sort case, always use the more rigorous clause */
4506  if (list_length(root->distinct_pathkeys) <
4507  list_length(root->sort_pathkeys))
4508  {
4509  needed_pathkeys = root->sort_pathkeys;
4510  /* Assert checks that parser didn't mess up... */
4512  needed_pathkeys));
4513  }
4514  else
4515  needed_pathkeys = root->distinct_pathkeys;
4516 
4517  path = cheapest_input_path;
4518  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4519  path = (Path *) create_sort_path(root, distinct_rel,
4520  path,
4521  needed_pathkeys,
4522  -1.0);
4523 
4524  add_path(distinct_rel, (Path *)
4525  create_upper_unique_path(root, distinct_rel,
4526  path,
4528  numDistinctRows));
4529  }
4530 
4531  /*
4532  * Consider hash-based implementations of DISTINCT, if possible.
4533  *
4534  * If we were not able to make any other types of path, we *must* hash or
4535  * die trying. If we do have other choices, there are two things that
4536  * should prevent selection of hashing: if the query uses DISTINCT ON
4537  * (because it won't really have the expected behavior if we hash), or if
4538  * enable_hashagg is off.
4539  *
4540  * Note: grouping_is_hashable() is much more expensive to check than the
4541  * other gating conditions, so we want to do it last.
4542  */
4543  if (distinct_rel->pathlist == NIL)
4544  allow_hash = true; /* we have no alternatives */
4545  else if (parse->hasDistinctOn || !enable_hashagg)
4546  allow_hash = false; /* policy-based decision not to hash */
4547  else
4548  allow_hash = true; /* default */
4549 
4550  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4551  {
4552  /* Generate hashed aggregate path --- no sort needed */
4553  add_path(distinct_rel, (Path *)
4554  create_agg_path(root,
4555  distinct_rel,
4556  cheapest_input_path,
4557  cheapest_input_path->pathtarget,
4558  AGG_HASHED,
4560  parse->distinctClause,
4561  NIL,
4562  NULL,
4563  numDistinctRows));
4564  }
4565 
4566  return distinct_rel;
4567 }
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1183
Query * parse
Definition: pathnodes.h:162
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:3044
bool hasAggs
Definition: parsenodes.h:133
List * groupingSets
Definition: parsenodes.h:161
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:549
bool hasDistinctOn
Definition: parsenodes.h:137
List * targetList
Definition: parsenodes.h:150
List * distinctClause
Definition: parsenodes.h:167
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:3096
struct Path * cheapest_total_path
Definition: pathnodes.h:699
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
List * sort_pathkeys
Definition: pathnodes.h:299
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
List * distinct_pathkeys
Definition: pathnodes.h:298
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
List * pathkeys
Definition: pathnodes.h:1196
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:381
bool enable_hashagg
Definition: costsize.c:140
List * groupClause
Definition: parsenodes.h:158
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:529
bool hasHavingQual
Definition: pathnodes.h:348
List * pathlist
Definition: pathnodes.h:695
Cardinality rows
Definition: pathnodes.h:1192
Definition: pg_list.h:50
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ create_grouping_paths()

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

Definition at line 3282 of file planner.c.

References AGGSPLIT_SIMPLE, grouping_sets_data::any_hashable, can_partial_agg(), create_degenerate_grouping_paths(), create_ordinary_grouping_paths(), enable_partitionwise_aggregate, GroupPathExtraData::flags, get_agg_clause_costs(), 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(), MemSet, NIL, PlannerInfo::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().

3287 {
3288  Query *parse = root->parse;
3289  RelOptInfo *grouped_rel;
3290  RelOptInfo *partially_grouped_rel;
3291  AggClauseCosts agg_costs;
3292 
3293  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3294  get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &agg_costs);
3295 
3296  /*
3297  * Create grouping relation to hold fully aggregated grouping and/or
3298  * aggregation paths.
3299  */
3300  grouped_rel = make_grouping_rel(root, input_rel, target,
3301  target_parallel_safe, parse->havingQual);
3302 
3303  /*
3304  * Create either paths for a degenerate grouping or paths for ordinary
3305  * grouping, as appropriate.
3306  */
3307  if (is_degenerate_grouping(root))
3308  create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3309  else
3310  {
3311  int flags = 0;
3312  GroupPathExtraData extra;
3313 
3314  /*
3315  * Determine whether it's possible to perform sort-based
3316  * implementations of grouping. (Note that if groupClause is empty,
3317  * grouping_is_sortable() is trivially true, and all the
3318  * pathkeys_contained_in() tests will succeed too, so that we'll
3319  * consider every surviving input path.)
3320  *
3321  * If we have grouping sets, we might be able to sort some but not all
3322  * of them; in this case, we need can_sort to be true as long as we
3323  * must consider any sorted-input plan.
3324  */
3325  if ((gd && gd->rollups != NIL)
3326  || grouping_is_sortable(parse->groupClause))
3327  flags |= GROUPING_CAN_USE_SORT;
3328 
3329  /*
3330  * Determine whether we should consider hash-based implementations of
3331  * grouping.
3332  *
3333  * Hashed aggregation only applies if we're grouping. If we have
3334  * grouping sets, some groups might be hashable but others not; in
3335  * this case we set can_hash true as long as there is nothing globally
3336  * preventing us from hashing (and we should therefore consider plans
3337  * with hashes).
3338  *
3339  * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3340  * BY aggregates. (Doing so would imply storing *all* the input
3341  * values in the hash table, and/or running many sorts in parallel,
3342  * either of which seems like a certain loser.) We similarly don't
3343  * support ordered-set aggregates in hashed aggregation, but that case
3344  * is also included in the numOrderedAggs count.
3345  *
3346  * Note: grouping_is_hashable() is much more expensive to check than
3347  * the other gating conditions, so we want to do it last.
3348  */
3349  if ((parse->groupClause != NIL &&
3350  root->numOrderedAggs == 0 &&
3351  (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause))))
3352  flags |= GROUPING_CAN_USE_HASH;
3353 
3354  /*
3355  * Determine whether partial aggregation is possible.
3356  */
3357  if (can_partial_agg(root))
3358  flags |= GROUPING_CAN_PARTIAL_AGG;
3359 
3360  extra.flags = flags;
3361  extra.target_parallel_safe = target_parallel_safe;
3362  extra.havingQual = parse->havingQual;
3363  extra.targetList = parse->targetList;
3364  extra.partial_costs_set = false;
3365 
3366  /*
3367  * Determine whether partitionwise aggregation is in theory possible.
3368  * It can be disabled by the user, and for now, we don't try to
3369  * support grouping sets. create_ordinary_grouping_paths() will check
3370  * additional conditions, such as whether input_rel is partitioned.
3371  */
3374  else
3376 
3377  create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3378  &agg_costs, gd, &extra,
3379  &partially_grouped_rel);
3380  }
3381 
3382  set_cheapest(grouped_rel);
3383  return grouped_rel;
3384 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:162
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3395
static void create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
Definition: planner.c:3469
List * groupingSets
Definition: parsenodes.h:161
PartitionwiseAggregateType patype
Definition: pathnodes.h:2599
#define MemSet(start, val, len)
Definition: c.h:1008
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:549
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:538
static bool can_partial_agg(PlannerInfo *root)
Definition: planner.c:6955
bool enable_partitionwise_aggregate
Definition: costsize.c:148
List * targetList
Definition: parsenodes.h:150
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2552
int numOrderedAggs
Definition: pathnodes.h:359
static bool is_degenerate_grouping(PlannerInfo *root)
Definition: planner.c:3448
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define GROUPING_CAN_PARTIAL_AGG
Definition: pathnodes.h:2554
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2553
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:3533
List * groupClause
Definition: parsenodes.h:158
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:529
Node * havingQual
Definition: parsenodes.h:163
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ 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 4121 of file planner.c.

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

Referenced by create_window_paths().

4128 {
4129  PathTarget *window_target;
4130  ListCell *l;
4131 
4132  /*
4133  * Since each window clause could require a different sort order, we stack
4134  * up a WindowAgg node for each clause, with sort steps between them as
4135  * needed. (We assume that select_active_windows chose a good order for
4136  * executing the clauses in.)
4137  *
4138  * input_target should contain all Vars and Aggs needed for the result.
4139  * (In some cases we wouldn't need to propagate all of these all the way
4140  * to the top, since they might only be needed as inputs to WindowFuncs.
4141  * It's probably not worth trying to optimize that though.) It must also
4142  * contain all window partitioning and sorting expressions, to ensure
4143  * they're computed only once at the bottom of the stack (that's critical
4144  * for volatile functions). As we climb up the stack, we'll add outputs
4145  * for the WindowFuncs computed at each level.
4146  */
4147  window_target = input_target;
4148 
4149  foreach(l, activeWindows)
4150  {
4152  List *window_pathkeys;
4153  int presorted_keys;
4154  bool is_sorted;
4155 
4156  window_pathkeys = make_pathkeys_for_window(root,
4157  wc,
4158  root->processed_tlist);
4159 
4160  is_sorted = pathkeys_count_contained_in(window_pathkeys,
4161  path->pathkeys,
4162  &presorted_keys);
4163 
4164  /* Sort if necessary */
4165  if (!is_sorted)
4166  {
4167  /*
4168  * No presorted keys or incremental sort disabled, just perform a
4169  * complete sort.
4170  */
4171  if (presorted_keys == 0 || !enable_incremental_sort)
4172  path = (Path *) create_sort_path(root, window_rel,
4173  path,
4174  window_pathkeys,
4175  -1.0);
4176  else
4177  {
4178  /*
4179  * Since we have presorted keys and incremental sort is
4180  * enabled, just use incremental sort.
4181  */
4182  path = (Path *) create_incremental_sort_path(root,
4183  window_rel,
4184  path,
4185  window_pathkeys,
4186  presorted_keys,
4187  -1.0);
4188  }
4189  }
4190 
4191  if (lnext(activeWindows, l))
4192  {
4193  /*
4194  * Add the current WindowFuncs to the output target for this
4195  * intermediate WindowAggPath. We must copy window_target to
4196  * avoid changing the previous path's target.
4197  *
4198  * Note: a WindowFunc adds nothing to the target's eval costs; but
4199  * we do need to account for the increase in tlist width.
4200  */
4201  ListCell *lc2;
4202 
4203  window_target = copy_pathtarget(window_target);
4204  foreach(lc2, wflists->windowFuncs[wc->winref])
4205  {
4206  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4207 
4208  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4209  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4210  }
4211  }
4212  else
4213  {
4214  /* Install the goal target in the topmost WindowAgg */
4215  window_target = output_target;
4216  }
4217 
4218  path = (Path *)
4219  create_windowagg_path(root, window_rel, path, window_target,
4220  wflists->windowFuncs[wc->winref],
4221  wc);
4222  }
4223 
4224  add_path(window_rel, path);
4225 }
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:646
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:139
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:684
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2892
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5383
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2525
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
List * pathkeys
Definition: pathnodes.h:1196
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause)
Definition: pathnode.c:3395
Oid wintype
Definition: primnodes.h:387
List * processed_tlist
Definition: pathnodes.h:321
Definition: pg_list.h:50
List ** windowFuncs
Definition: clauses.h:23

◆ 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 4587 of file planner.c.

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

Referenced by grouping_planner().

4592 {
4593  Path *cheapest_input_path = input_rel->cheapest_total_path;
4594  RelOptInfo *ordered_rel;
4595  ListCell *lc;
4596 
4597  /* For now, do all work in the (ORDERED, NULL) upperrel */
4598  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4599 
4600  /*
4601  * If the input relation is not parallel-safe, then the ordered relation
4602  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4603  * target list is parallel-safe.
4604  */
4605  if (input_rel->consider_parallel && target_parallel_safe)
4606  ordered_rel->consider_parallel = true;
4607 
4608  /*
4609  * If the input rel belongs to a single FDW, so does the ordered_rel.
4610  */
4611  ordered_rel->serverid = input_rel->serverid;
4612  ordered_rel->userid = input_rel->userid;
4613  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4614  ordered_rel->fdwroutine = input_rel->fdwroutine;
4615 
4616  foreach(lc, input_rel->pathlist)
4617  {
4618  Path *input_path = (Path *) lfirst(lc);
4619  Path *sorted_path = input_path;
4620  bool is_sorted;
4621  int presorted_keys;
4622 
4623  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4624  input_path->pathkeys, &presorted_keys);
4625 
4626  if (is_sorted)
4627  {
4628  /* Use the input path as is, but add a projection step if needed */
4629  if (sorted_path->pathtarget != target)
4630  sorted_path = apply_projection_to_path(root, ordered_rel,
4631  sorted_path, target);
4632 
4633  add_path(ordered_rel, sorted_path);
4634  }
4635  else
4636  {
4637  /*
4638  * Try adding an explicit sort, but only to the cheapest total
4639  * path since a full sort should generally add the same cost to
4640  * all paths.
4641  */
4642  if (input_path == cheapest_input_path)
4643  {
4644  /*
4645  * Sort the cheapest input path. An explicit sort here can
4646  * take advantage of LIMIT.
4647  */
4648  sorted_path = (Path *) create_sort_path(root,
4649  ordered_rel,
4650  input_path,
4651  root->sort_pathkeys,
4652  limit_tuples);
4653  /* Add projection step if needed */
4654  if (sorted_path->pathtarget != target)
4655  sorted_path = apply_projection_to_path(root, ordered_rel,
4656  sorted_path, target);
4657 
4658  add_path(ordered_rel, sorted_path);
4659  }
4660 
4661  /*
4662  * If incremental sort is enabled, then try it as well. Unlike
4663  * with regular sorts, we can't just look at the cheapest path,
4664  * because the cost of incremental sort depends on how well
4665  * presorted the path is. Additionally incremental sort may enable
4666  * a cheaper startup path to win out despite higher total cost.
4667  */
4669  continue;
4670 
4671  /* Likewise, if the path can't be used for incremental sort. */
4672  if (!presorted_keys)
4673  continue;
4674 
4675  /* Also consider incremental sort. */
4676  sorted_path = (Path *) create_incremental_sort_path(root,
4677  ordered_rel,
4678  input_path,
4679  root->sort_pathkeys,
4680  presorted_keys,
4681  limit_tuples);
4682 
4683  /* Add projection step if needed */
4684  if (sorted_path->pathtarget != target)
4685  sorted_path = apply_projection_to_path(root, ordered_rel,
4686  sorted_path, target);
4687 
4688  add_path(ordered_rel, sorted_path);
4689  }
4690  }
4691 
4692  /*
4693  * generate_gather_paths() will have already generated a simple Gather
4694  * path for the best parallel path, if any, and the loop above will have
4695  * considered sorting it. Similarly, generate_gather_paths() will also
4696  * have generated order-preserving Gather Merge plans which can be used
4697  * without sorting if they happen to match the sort_pathkeys, and the loop
4698  * above will have handled those as well. However, there's one more
4699  * possibility: it may make sense to sort the cheapest partial path
4700  * according to the required output order and then use Gather Merge.
4701  */
4702  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
4703  input_rel->partial_pathlist != NIL)
4704  {
4705  Path *cheapest_partial_path;
4706 
4707  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4708 
4709  /*
4710  * If cheapest partial path doesn't need a sort, this is redundant
4711  * with what's already been tried.
4712  */
4714  cheapest_partial_path->pathkeys))
4715  {
4716  Path *path;
4717  double total_groups;
4718 
4719  path = (Path *) create_sort_path(root,
4720  ordered_rel,
4721  cheapest_partial_path,
4722  root->sort_pathkeys,
4723  limit_tuples);
4724 
4725  total_groups = cheapest_partial_path->rows *
4726  cheapest_partial_path->parallel_workers;
4727  path = (Path *)
4728  create_gather_merge_path(root, ordered_rel,
4729  path,
4730  path->pathtarget,
4731  root->sort_pathkeys, NULL,
4732  &total_groups);
4733 
4734  /* Add projection step if needed */
4735  if (path->pathtarget != target)
4736  path = apply_projection_to_path(root, ordered_rel,
4737  path, target);
4738 
4739  add_path(ordered_rel, path);
4740  }
4741 
4742  /*
4743  * Consider incremental sort with a gather merge on partial paths.
4744  *
4745  * We can also skip the entire loop when we only have a single-item
4746  * sort_pathkeys because then we can't possibly have a presorted
4747  * prefix of the list without having the list be fully sorted.
4748  */
4750  {
4751  ListCell *lc;
4752 
4753  foreach(lc, input_rel->partial_pathlist)
4754  {
4755  Path *input_path = (Path *) lfirst(lc);
4756  Path *sorted_path;
4757  bool is_sorted;
4758  int presorted_keys;
4759  double total_groups;
4760 
4761  /*
4762  * We don't care if this is the cheapest partial path - we
4763  * can't simply skip it, because it may be partially sorted in
4764  * which case we want to consider adding incremental sort
4765  * (instead of full sort, which is what happens above).
4766  */
4767 
4768  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4769  input_path->pathkeys,
4770  &presorted_keys);
4771 
4772  /* No point in adding incremental sort on fully sorted paths. */
4773  if (is_sorted)
4774  continue;
4775 
4776  if (presorted_keys == 0)
4777  continue;
4778 
4779  /* Since we have presorted keys, consider incremental sort. */
4780  sorted_path = (Path *) create_incremental_sort_path(root,
4781  ordered_rel,
4782  input_path,
4783  root->sort_pathkeys,
4784  presorted_keys,
4785  limit_tuples);
4786  total_groups = input_path->rows *
4787  input_path->parallel_workers;
4788  sorted_path = (Path *)
4789  create_gather_merge_path(root, ordered_rel,
4790  sorted_path,
4791  sorted_path->pathtarget,
4792  root->sort_pathkeys, NULL,
4793  &total_groups);
4794 
4795  /* Add projection step if needed */
4796  if (sorted_path->pathtarget != target)
4797  sorted_path = apply_projection_to_path(root, ordered_rel,
4798  sorted_path, target);
4799 
4800  add_path(ordered_rel, sorted_path);
4801  }
4802  }
4803  }
4804 
4805  /*
4806  * If there is an FDW that's responsible for all baserels of the query,
4807  * let it consider adding ForeignPaths.
4808  */
4809  if (ordered_rel->fdwroutine &&
4810  ordered_rel->fdwroutine->GetForeignUpperPaths)
4811  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
4812  input_rel, ordered_rel,
4813  NULL);
4814 
4815  /* Let extensions possibly add some more paths */
4817  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
4818  input_rel, ordered_rel, NULL);
4819 
4820  /*
4821  * No need to bother with set_cheapest here; grouping_planner does not
4822  * need us to do it.
4823  */
4824  Assert(ordered_rel->pathlist != NIL);
4825 
4826  return ordered_rel;
4827 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2734
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1183
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:139
Oid userid
Definition: pathnodes.h:733
int parallel_workers
Definition: pathnodes.h:1189
List * partial_pathlist
Definition: pathnodes.h:697
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:734
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2892
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define linitial(l)
Definition: pg_list.h:174
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
struct Path * cheapest_total_path
Definition: pathnodes.h:699
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
List * sort_pathkeys
Definition: pathnodes.h:299
Oid serverid
Definition: pathnodes.h:732
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:1860
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
List * pathkeys
Definition: pathnodes.h:1196
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
bool consider_parallel
Definition: pathnodes.h:689
List * pathlist
Definition: pathnodes.h:695
Cardinality rows
Definition: pathnodes.h:1192

◆ 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 3533 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().

3539 {
3540  Path *cheapest_path = input_rel->cheapest_total_path;
3541  RelOptInfo *partially_grouped_rel = NULL;
3542  double dNumGroups;
3544 
3545  /*
3546  * If this is the topmost grouping relation or if the parent relation is
3547  * doing some form of partitionwise aggregation, then we may be able to do
3548  * it at this level also. However, if the input relation is not
3549  * partitioned, partitionwise aggregate is impossible.
3550  */
3551  if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
3552  IS_PARTITIONED_REL(input_rel))
3553  {
3554  /*
3555  * If this is the topmost relation or if the parent relation is doing
3556  * full partitionwise aggregation, then we can do full partitionwise
3557  * aggregation provided that the GROUP BY clause contains all of the
3558  * partitioning columns at this level. Otherwise, we can do at most
3559  * partial partitionwise aggregation. But if partial aggregation is
3560  * not supported in general then we can't use it for partitionwise
3561  * aggregation either.
3562  */
3563  if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
3564  group_by_has_partkey(input_rel, extra->targetList,
3565  root->parse->groupClause))
3567  else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3569  else
3571  }
3572 
3573  /*
3574  * Before generating paths for grouped_rel, we first generate any possible
3575  * partially grouped paths; that way, later code can easily consider both
3576  * parallel and non-parallel approaches to grouping.
3577  */
3578  if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3579  {
3580  bool force_rel_creation;
3581 
3582  /*
3583  * If we're doing partitionwise aggregation at this level, force
3584  * creation of a partially_grouped_rel so we can add partitionwise
3585  * paths to it.
3586  */
3587  force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
3588 
3589  partially_grouped_rel =
3591  grouped_rel,
3592  input_rel,
3593  gd,
3594  extra,
3595  force_rel_creation);
3596  }
3597 
3598  /* Set out parameter. */
3599  *partially_grouped_rel_p = partially_grouped_rel;
3600 
3601  /* Apply partitionwise aggregation technique, if possible. */
3602  if (patype != PARTITIONWISE_AGGREGATE_NONE)
3603  create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
3604  partially_grouped_rel, agg_costs,
3605  gd, patype, extra);
3606 
3607  /* If we are doing partial aggregation only, return. */
3609  {
3610  Assert(partially_grouped_rel);
3611 
3612  if (partially_grouped_rel->pathlist)
3613  set_cheapest(partially_grouped_rel);
3614 
3615  return;
3616  }
3617 
3618  /* Gather any partially grouped partial paths. */
3619  if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
3620  {
3621  gather_grouping_paths(root, partially_grouped_rel);
3622  set_cheapest(partially_grouped_rel);
3623  }
3624 
3625  /*
3626  * Estimate number of groups.
3627  */
3628  dNumGroups = get_number_of_groups(root,
3629  cheapest_path->rows,
3630  gd,
3631  extra->targetList);
3632 
3633  /* Build final grouping paths */
3634  add_paths_to_grouping_rel(root, input_rel, grouped_rel,
3635  partially_grouped_rel, agg_costs, gd,
3636  dNumGroups, extra);
3637 
3638  /* Give a helpful error if we failed to find any implementation */
3639  if (grouped_rel->pathlist == NIL)
3640  ereport(ERROR,
3641  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3642  errmsg("could not implement GROUP BY"),
3643  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
3644 
3645  /*
3646  * If there is an FDW that's responsible for all baserels of the query,
3647  * let it consider adding ForeignPaths.
3648  */
3649  if (grouped_rel->fdwroutine &&
3650  grouped_rel->fdwroutine->GetForeignUpperPaths)
3652  input_rel, grouped_rel,
3653  extra);
3654 
3655  /* Let extensions possibly add some more paths */
3657  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
3658  input_rel, grouped_rel,
3659  extra);
3660 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:162
PartitionwiseAggregateType
Definition: pathnodes.h:2567
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3160
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6867
PartitionwiseAggregateType patype
Definition: pathnodes.h:2599
int errcode(int sqlerrcode)
Definition: elog.c:698
List * partial_pathlist
Definition: pathnodes.h:697
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:6482
#define ERROR
Definition: elog.h:46
struct Path * cheapest_total_path
Definition: pathnodes.h:699
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
int errdetail(const char *fmt,...)
Definition: elog.c:1042
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:6136
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define GROUPING_CAN_PARTIAL_AGG
Definition: pathnodes.h:2554
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:7233
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
List * groupClause
Definition: parsenodes.h:158
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:786
List * pathlist
Definition: pathnodes.h:695
Cardinality rows
Definition: pathnodes.h:1192
static bool group_by_has_partkey(RelOptInfo *input_rel, List *targetList, List *groupClause)
Definition: planner.c:7377

◆ create_partial_distinct_paths()

static void create_partial_distinct_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo final_distinct_rel 
)
static

Definition at line 4307 of file planner.c.

References add_partial_path(), AGG_HASHED, AGGSPLIT_SIMPLE, RelOptInfo::consider_parallel, create_agg_path(), create_final_distinct_paths(), create_upper_paths_hook, create_upper_unique_path(), PlannerInfo::distinct_pathkeys, Query::distinctClause, enable_hashagg, estimate_num_groups(), RelOptInfo::fdwroutine, fetch_upper_rel(), generate_gather_paths(), get_sortgrouplist_exprs(), FdwRoutine::GetForeignUpperPaths, grouping_is_hashable(), grouping_is_sortable(), Query::hasDistinctOn, lfirst, linitial, list_length(), NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), Path::pathtarget, RelOptInfo::reltarget, Path::rows, RelOptInfo::serverid, set_cheapest(), Query::targetList, PlannerInfo::upper_targets, UPPERREL_PARTIAL_DISTINCT, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by create_distinct_paths().

4309 {
4310  RelOptInfo *partial_distinct_rel;
4311  Query *parse;
4312  List *distinctExprs;
4313  double numDistinctRows;
4314  Path *cheapest_partial_path;
4315  ListCell *lc;
4316 
4317  /* nothing to do when there are no partial paths in the input rel */
4318  if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
4319  return;
4320 
4321  parse = root->parse;
4322 
4323  /* can't do parallel DISTINCT ON */
4324  if (parse->hasDistinctOn)
4325  return;
4326 
4327  partial_distinct_rel = fetch_upper_rel(root, UPPERREL_PARTIAL_DISTINCT,
4328  NULL);
4329  partial_distinct_rel->reltarget = root->upper_targets[UPPERREL_PARTIAL_DISTINCT];
4330  partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
4331 
4332  /*
4333  * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
4334  */
4335  partial_distinct_rel->serverid = input_rel->serverid;
4336  partial_distinct_rel->userid = input_rel->userid;
4337  partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4338  partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
4339 
4340  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4341 
4342  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4343  parse->targetList);
4344 
4345  /* estimate how many distinct rows we'll get from each worker */
4346  numDistinctRows = estimate_num_groups(root, distinctExprs,
4347  cheapest_partial_path->rows,
4348  NULL, NULL);
4349 
4350  /* first try adding unique paths atop of sorted paths */
4352  {
4353  foreach(lc, input_rel->partial_pathlist)
4354  {
4355  Path *path = (Path *) lfirst(lc);
4356 
4358  {
4359  add_partial_path(partial_distinct_rel, (Path *)
4361  partial_distinct_rel,
4362  path,
4364  numDistinctRows));
4365  }
4366  }
4367  }
4368 
4369  /*
4370  * Now try hash aggregate paths, if enabled and hashing is possible. Since
4371  * we're not on the hook to ensure we do our best to create at least one
4372  * path here, we treat enable_hashagg as a hard off-switch rather than the
4373  * slightly softer variant in create_final_distinct_paths.
4374  */
4376  {
4377  add_partial_path(partial_distinct_rel, (Path *)
4378  create_agg_path(root,
4379  partial_distinct_rel,
4380  cheapest_partial_path,
4381  cheapest_partial_path->pathtarget,
4382  AGG_HASHED,
4384  parse->distinctClause,
4385  NIL,
4386  NULL,
4387  numDistinctRows));
4388  }
4389 
4390  /*
4391  * If there is an FDW that's responsible for all baserels of the query,
4392  * let it consider adding ForeignPaths.
4393  */
4394  if (partial_distinct_rel->fdwroutine &&
4395  partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
4396  partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4398  input_rel,
4399  partial_distinct_rel,
4400  NULL);
4401 
4402  /* Let extensions possibly add some more partial paths */
4404  (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
4405  input_rel, partial_distinct_rel, NULL);
4406 
4407  if (partial_distinct_rel->partial_pathlist != NIL)
4408  {
4409  generate_gather_paths(root, partial_distinct_rel, true);
4410  set_cheapest(partial_distinct_rel);
4411 
4412  /*
4413  * Finally, create paths to distinctify the final result. This step
4414  * is needed to remove any duplicates due to combining rows from
4415  * parallel workers.
4416  */
4417  create_final_distinct_paths(root, partial_distinct_rel,
4418  final_distinct_rel);
4419  }
4420 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1183
Query * parse
Definition: pathnodes.h:162
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:3044
Oid userid
Definition: pathnodes.h:733
List * partial_pathlist
Definition: pathnodes.h:697
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:549
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2608
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:734
bool hasDistinctOn
Definition: parsenodes.h:137
List * targetList
Definition: parsenodes.h:150
#define linitial(l)
Definition: pg_list.h:174
List * distinctClause
Definition: parsenodes.h:167
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
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:3096
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:732
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
List * distinct_pathkeys
Definition: pathnodes.h:298
List * pathkeys
Definition: pathnodes.h:1196
#define lfirst(lc)
Definition: pg_list.h:169
static RelOptInfo * create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_rel)
Definition: planner.c:4430
static int list_length(const List *l)
Definition: pg_list.h:149
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:381
bool consider_parallel
Definition: pathnodes.h:689
bool enable_hashagg
Definition: costsize.c:140
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:529
Cardinality rows
Definition: pathnodes.h:1192
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:692
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: pathnodes.h:310

◆ 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 6482 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_incremental_sort_path(), create_sort_path(), enable_incremental_sort, 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, list_length(), make_partial_grouping_target(), MemSet, NIL, parse(), PlannerInfo::parse, GroupPathExtraData::partial_costs_set, RelOptInfo::partial_pathlist, PARTITIONWISE_AGGREGATE_PARTIAL, Path::pathkeys, pathkeys_contained_in(), pathkeys_count_contained_in(), RelOptInfo::pathlist, GroupPathExtraData::patype, RelOptInfo::relids, RelOptInfo::reloptkind, RelOptInfo::reltarget, Path::rows, RelOptInfo::serverid, GroupPathExtraData::targetList, UPPERREL_PARTIAL_GROUP_AGG, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by create_ordinary_grouping_paths().

6488 {
6489  Query *parse = root->parse;
6490  RelOptInfo *partially_grouped_rel;
6491  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
6492  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6493  Path *cheapest_partial_path = NULL;
6494  Path *cheapest_total_path = NULL;
6495  double dNumPartialGroups = 0;
6496  double dNumPartialPartialGroups = 0;
6497  ListCell *lc;
6498  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6499  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6500 
6501  /*
6502  * Consider whether we should generate partially aggregated non-partial
6503  * paths. We can only do this if we have a non-partial path, and only if
6504  * the parent of the input rel is performing partial partitionwise
6505  * aggregation. (Note that extra->patype is the type of partitionwise
6506  * aggregation being used at the parent level, not this level.)
6507  */
6508  if (input_rel->pathlist != NIL &&
6510  cheapest_total_path = input_rel->cheapest_total_path;
6511 
6512  /*
6513  * If parallelism is possible for grouped_rel, then we should consider
6514  * generating partially-grouped partial paths. However, if the input rel
6515  * has no partial paths, then we can't.
6516  */
6517  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
6518  cheapest_partial_path = linitial(input_rel->partial_pathlist);
6519 
6520  /*
6521  * If we can't partially aggregate partial paths, and we can't partially
6522  * aggregate non-partial paths, then don't bother creating the new
6523  * RelOptInfo at all, unless the caller specified force_rel_creation.
6524  */
6525  if (cheapest_total_path == NULL &&
6526  cheapest_partial_path == NULL &&
6527  !force_rel_creation)
6528  return NULL;
6529 
6530  /*
6531  * Build a new upper relation to represent the result of partially
6532  * aggregating the rows from the input relation.
6533  */
6534  partially_grouped_rel = fetch_upper_rel(root,
6536  grouped_rel->relids);
6537  partially_grouped_rel->consider_parallel =
6538  grouped_rel->consider_parallel;
6539  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
6540  partially_grouped_rel->serverid = grouped_rel->serverid;
6541  partially_grouped_rel->userid = grouped_rel->userid;
6542  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
6543  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
6544 
6545  /*
6546  * Build target list for partial aggregate paths. These paths cannot just
6547  * emit the same tlist as regular aggregate paths, because (1) we must
6548  * include Vars and Aggrefs needed in HAVING, which might not appear in
6549  * the result tlist, and (2) the Aggrefs must be set in partial mode.
6550  */
6551  partially_grouped_rel->reltarget =
6552  make_partial_grouping_target(root, grouped_rel->reltarget,
6553  extra->havingQual);
6554 
6555  if (!extra->partial_costs_set)
6556  {
6557  /*
6558  * Collect statistics about aggregates for estimating costs of
6559  * performing aggregation in parallel.
6560  */
6561  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
6562  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
6563  if (parse->hasAggs)
6564  {
6565  /* partial phase */
6567  agg_partial_costs);
6568 
6569  /* final phase */
6571  agg_final_costs);
6572  }
6573 
6574  extra->partial_costs_set = true;
6575  }
6576 
6577  /* Estimate number of partial groups. */
6578  if (cheapest_total_path != NULL)
6579  dNumPartialGroups =
6580  get_number_of_groups(root,
6581  cheapest_total_path->rows,
6582  gd,
6583  extra->targetList);
6584  if (cheapest_partial_path != NULL)
6585  dNumPartialPartialGroups =
6586  get_number_of_groups(root,
6587  cheapest_partial_path->rows,
6588  gd,
6589  extra->targetList);
6590 
6591  if (can_sort && cheapest_total_path != NULL)
6592  {
6593  /* This should have been checked previously */
6594  Assert(parse->hasAggs || parse->groupClause);
6595 
6596  /*
6597  * Use any available suitably-sorted path as input, and also consider
6598  * sorting the cheapest partial path.
6599  */
6600  foreach(lc, input_rel->pathlist)
6601  {
6602  Path *path = (Path *) lfirst(lc);
6603  bool is_sorted;
6604 
6605  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6606  path->pathkeys);
6607  if (path == cheapest_total_path || is_sorted)
6608  {
6609  /* Sort the cheapest partial path, if it isn't already */
6610  if (!is_sorted)
6611  path = (Path *) create_sort_path(root,
6612  partially_grouped_rel,
6613  path,
6614  root->group_pathkeys,
6615  -1.0);
6616 
6617  if (parse->hasAggs)
6618  add_path(partially_grouped_rel, (Path *)
6619  create_agg_path(root,
6620  partially_grouped_rel,
6621  path,
6622  partially_grouped_rel->reltarget,
6623  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6625  parse->groupClause,
6626  NIL,
6627  agg_partial_costs,
6628  dNumPartialGroups));
6629  else
6630  add_path(partially_grouped_rel, (Path *)
6631  create_group_path(root,
6632  partially_grouped_rel,
6633  path,
6634  parse->groupClause,
6635  NIL,
6636  dNumPartialGroups));
6637  }
6638  }
6639 
6640  /*
6641  * Consider incremental sort on all partial paths, if enabled.
6642  *
6643  * We can also skip the entire loop when we only have a single-item
6644  * group_pathkeys because then we can't possibly have a presorted
6645  * prefix of the list without having the list be fully sorted.
6646  */
6648  {
6649  foreach(lc, input_rel->pathlist)
6650  {
6651  Path *path = (Path *) lfirst(lc);
6652  bool is_sorted;
6653  int presorted_keys;
6654 
6655  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6656  path->pathkeys,
6657  &presorted_keys);
6658 
6659  /* Ignore already sorted paths */
6660  if (is_sorted)
6661  continue;
6662 
6663  if (presorted_keys == 0)
6664  continue;
6665 
6666  /* Since we have presorted keys, consider incremental sort. */
6667  path = (Path *) create_incremental_sort_path(root,
6668  partially_grouped_rel,
6669  path,
6670  root->group_pathkeys,
6671  presorted_keys,
6672  -1.0);
6673 
6674  if (parse->hasAggs)
6675  add_path(partially_grouped_rel, (Path *)
6676  create_agg_path(root,
6677  partially_grouped_rel,
6678  path,
6679  partially_grouped_rel->reltarget,
6680  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6682  parse->groupClause,
6683  NIL,
6684  agg_partial_costs,
6685  dNumPartialGroups));
6686  else
6687  add_path(partially_grouped_rel, (Path *)
6688  create_group_path(root,
6689  partially_grouped_rel,
6690  path,
6691  parse->groupClause,
6692  NIL,
6693  dNumPartialGroups));
6694  }
6695  }
6696 
6697  }
6698 
6699  if (can_sort && cheapest_partial_path != NULL)
6700  {
6701  /* Similar to above logic, but for partial paths. */
6702  foreach(lc, input_rel->partial_pathlist)
6703  {
6704  Path *path = (Path *) lfirst(lc);
6705  Path *path_original = path;
6706  bool is_sorted;
6707  int presorted_keys;
6708 
6709  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6710  path->pathkeys,
6711  &presorted_keys);
6712 
6713  if (path == cheapest_partial_path || is_sorted)
6714  {
6715  /* Sort the cheapest partial path, if it isn't already */
6716  if (!is_sorted)
6717  path = (Path *) create_sort_path(root,
6718  partially_grouped_rel,
6719  path,
6720  root->group_pathkeys,
6721  -1.0);
6722 
6723  if (parse->hasAggs)
6724  add_partial_path(partially_grouped_rel, (Path *)
6725  create_agg_path(root,
6726  partially_grouped_rel,
6727  path,
6728  partially_grouped_rel->reltarget,
6729  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6731  parse->groupClause,
6732  NIL,
6733  agg_partial_costs,
6734  dNumPartialPartialGroups));
6735  else
6736  add_partial_path(partially_grouped_rel, (Path *)
6737  create_group_path(root,
6738  partially_grouped_rel,
6739  path,
6740  parse->groupClause,
6741  NIL,
6742  dNumPartialPartialGroups));
6743  }
6744 
6745  /*
6746  * Now we may consider incremental sort on this path, but only
6747  * when the path is not already sorted and when incremental sort
6748  * is enabled.
6749  */
6750  if (is_sorted || !enable_incremental_sort)
6751  continue;
6752 
6753  /* Restore the input path (we might have added Sort on top). */
6754  path = path_original;
6755 
6756  /* no shared prefix, not point in building incremental sort */
6757  if (presorted_keys == 0)
6758  continue;
6759 
6760  /*
6761  * We should have already excluded pathkeys of length 1 because
6762  * then presorted_keys > 0 would imply is_sorted was true.
6763  */
6764  Assert(list_length(root->group_pathkeys) != 1);
6765 
6766  path = (Path *) create_incremental_sort_path(root,
6767  partially_grouped_rel,
6768  path,
6769  root->group_pathkeys,
6770  presorted_keys,
6771  -1.0);
6772 
6773  if (parse->hasAggs)
6774  add_partial_path(partially_grouped_rel, (Path *)
6775  create_agg_path(root,
6776  partially_grouped_rel,
6777  path,
6778  partially_grouped_rel->reltarget,
6779  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6781  parse->groupClause,
6782  NIL,
6783  agg_partial_costs,
6784  dNumPartialPartialGroups));
6785  else
6786  add_partial_path(partially_grouped_rel, (Path *)
6787  create_group_path(root,
6788  partially_grouped_rel,
6789  path,
6790  parse->groupClause,
6791  NIL,
6792  dNumPartialPartialGroups));
6793  }
6794  }
6795 
6796  /*
6797  * Add a partially-grouped HashAgg Path where possible
6798  */
6799  if (can_hash && cheapest_total_path != NULL)
6800  {
6801  /* Checked above */
6802  Assert(parse->hasAggs || parse->groupClause);
6803 
6804  add_path(partially_grouped_rel, (Path *)
6805  create_agg_path(root,
6806  partially_grouped_rel,
6807  cheapest_total_path,
6808  partially_grouped_rel->reltarget,
6809  AGG_HASHED,
6811  parse->groupClause,
6812  NIL,
6813  agg_partial_costs,
6814  dNumPartialGroups));
6815  }
6816 
6817  /*
6818  * Now add a partially-grouped HashAgg partial Path where possible
6819  */
6820  if (can_hash && cheapest_partial_path != NULL)
6821  {
6822  add_partial_path(partially_grouped_rel, (Path *)
6823  create_agg_path(root,
6824  partially_grouped_rel,
6825  cheapest_partial_path,
6826  partially_grouped_rel->reltarget,
6827  AGG_HASHED,
6829  parse->groupClause,
6830  NIL,
6831  agg_partial_costs,
6832  dNumPartialPartialGroups));
6833  }
6834 
6835  /*
6836  * If there is an FDW that's responsible for all baserels of the query,
6837  * let it consider adding partially grouped ForeignPaths.
6838  */
6839  if (partially_grouped_rel->fdwroutine &&
6840  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
6841  {
6842  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
6843 
6844  fdwroutine->GetForeignUpperPaths(root,
6846  input_rel, partially_grouped_rel,
6847  extra);
6848  }
6849 
6850  return partially_grouped_rel;
6851 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
List * group_pathkeys
Definition: pathnodes.h:296
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:162
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:139
RelOptKind reloptkind
Definition: pathnodes.h:678
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3160
Oid userid
Definition: pathnodes.h:733
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:2592
bool hasAggs
Definition: parsenodes.h:133
PartitionwiseAggregateType patype
Definition: pathnodes.h:2599
List * partial_pathlist
Definition: pathnodes.h:697
#define MemSet(start, val, len)
Definition: c.h:1008
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:538
bool useridiscurrent
Definition: pathnodes.h:734
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2892
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2552
#define linitial(l)
Definition: pg_list.h:174
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
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:3096
struct Path * cheapest_total_path
Definition: pathnodes.h:699
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
Relids relids
Definition: pathnodes.h:681
Oid serverid
Definition: pathnodes.h:732
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2553
List * pathkeys
Definition: pathnodes.h:1196
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:4945
static int list_length(const List *l)
Definition: pg_list.h:149
bool consider_parallel
Definition: pathnodes.h:689
List * groupClause
Definition: parsenodes.h:158
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
List * pathlist
Definition: pathnodes.h:695
Cardinality rows
Definition: pathnodes.h:1192
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2985
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2593
struct PathTarget * reltarget
Definition: pathnodes.h:692
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ 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 7233 of file planner.c.

References add_paths_to_append_rel(), adjust_appendrel_attrs(), Assert, bms_next_member(), copy_pathtarget(), create_ordinary_grouping_paths(), PathTarget::exprs, find_appinfos_by_relids(), GroupPathExtraData::havingQual, i, IS_DUMMY_REL, lappend(), RelOptInfo::live_parts, make_grouping_rel(), NIL, 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().

7241 {
7242  List *grouped_live_children = NIL;
7243  List *partially_grouped_live_children = NIL;
7244  PathTarget *target = grouped_rel->reltarget;
7245  bool partial_grouping_valid = true;
7246  int i;
7247 
7250  partially_grouped_rel != NULL);
7251 
7252  /* Add paths for partitionwise aggregation/grouping. */
7253  i = -1;
7254  while ((i = bms_next_member(input_rel->live_parts, i)) >= 0)
7255  {
7256  RelOptInfo *child_input_rel = input_rel->part_rels[i];
7257  PathTarget *child_target;
7258  AppendRelInfo **appinfos;
7259  int nappinfos;
7260  GroupPathExtraData child_extra;
7261  RelOptInfo *child_grouped_rel;
7262  RelOptInfo *child_partially_grouped_rel;
7263 
7264  Assert(child_input_rel != NULL);
7265 
7266  /* Dummy children can be ignored. */
7267  if (IS_DUMMY_REL(child_input_rel))
7268  continue;
7269 
7270  child_target = copy_pathtarget(target);
7271 
7272  /*
7273  * Copy the given "extra" structure as is and then override the
7274  * members specific to this child.
7275  */
7276  memcpy(&child_extra, extra, sizeof(child_extra));
7277 
7278  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7279  &nappinfos);
7280 
7281  child_target->exprs = (List *)
7283  (Node *) target->exprs,
7284  nappinfos, appinfos);
7285 
7286  /* Translate havingQual and targetList. */
7287  child_extra.havingQual = (Node *)
7289  extra->havingQual,
7290  nappinfos, appinfos);
7291  child_extra.targetList = (List *)
7293  (Node *) extra->targetList,
7294  nappinfos, appinfos);
7295 
7296  /*
7297  * extra->patype was the value computed for our parent rel; patype is
7298  * the value for this relation. For the child, our value is its
7299  * parent rel's value.
7300  */
7301  child_extra.patype = patype;
7302 
7303  /*
7304  * Create grouping relation to hold fully aggregated grouping and/or
7305  * aggregation paths for the child.
7306  */
7307  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7308  child_target,
7309  extra->target_parallel_safe,
7310  child_extra.havingQual);
7311 
7312  /* Create grouping paths for this child relation. */
7313  create_ordinary_grouping_paths(root, child_input_rel,
7314  child_grouped_rel,
7315  agg_costs, gd, &child_extra,
7316  &child_partially_grouped_rel);
7317 
7318  if (child_partially_grouped_rel)
7319  {
7320  partially_grouped_live_children =
7321  lappend(partially_grouped_live_children,
7322  child_partially_grouped_rel);
7323  }
7324  else
7325  partial_grouping_valid = false;
7326 
7327  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7328  {
7329  set_cheapest(child_grouped_rel);
7330  grouped_live_children = lappend(grouped_live_children,
7331  child_grouped_rel);
7332  }
7333 
7334  pfree(appinfos);
7335  }
7336 
7337  /*
7338  * Try to create append paths for partially grouped children. For full
7339  * partitionwise aggregation, we might have paths in the partial_pathlist
7340  * if parallel aggregation is possible. For partial partitionwise
7341  * aggregation, we may have paths in both pathlist and partial_pathlist.
7342  *
7343  * NB: We must have a partially grouped path for every child in order to
7344  * generate a partially grouped path for this relation.
7345  */
7346  if (partially_grouped_rel && partial_grouping_valid)
7347  {
7348  Assert(partially_grouped_live_children != NIL);
7349 
7350  add_paths_to_append_rel(root, partially_grouped_rel,
7351  partially_grouped_live_children);
7352 
7353  /*
7354  * We need call set_cheapest, since the finalization step will use the
7355  * cheapest path from the rel.
7356  */
7357  if (partially_grouped_rel->pathlist)
7358  set_cheapest(partially_grouped_rel);
7359  }
7360 
7361  /* If possible, create append paths for fully grouped children. */
7362  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7363  {
7364  Assert(grouped_live_children != NIL);
7365 
7366  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7367  }
7368 }
#define NIL
Definition: pg_list.h:65
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:646
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3395
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1285
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
Definition: nodes.h:536
PartitionwiseAggregateType patype
Definition: pathnodes.h:2599
Bitmapset * live_parts
Definition: pathnodes.h:770
void pfree(void *pointer)
Definition: mcxt.c:1169
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1466
Relids relids
Definition: pathnodes.h:681
List * lappend(List *list, void *datum)
Definition: list.c:336
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:715
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1110
#define Assert(condition)
Definition: c.h:804
struct RelOptInfo ** part_rels
Definition: pathnodes.h:768
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:3533
int i
List * pathlist
Definition: pathnodes.h:695
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:692
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:195

◆ 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 4034 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_count_contained_in(), RelOptInfo::pathlist, RelOptInfo::serverid, set_cheapest(), UPPERREL_WINDOW, RelOptInfo::userid, RelOptInfo::useridiscurrent, and PlannerInfo::window_pathkeys.

Referenced by grouping_planner().

4041 {
4042  RelOptInfo *window_rel;
4043  ListCell *lc;
4044 
4045  /* For now, do all work in the (WINDOW, NULL) upperrel */
4046  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4047 
4048  /*
4049  * If the input relation is not parallel-safe, then the window relation
4050  * can't be parallel-safe, either. Otherwise, we need to examine the
4051  * target list and active windows for non-parallel-safe constructs.
4052  */
4053  if (input_rel->consider_parallel && output_target_parallel_safe &&
4054  is_parallel_safe(root, (Node *) activeWindows))
4055  window_rel->consider_parallel = true;
4056 
4057  /*
4058  * If the input rel belongs to a single FDW, so does the window rel.
4059  */
4060  window_rel->serverid = input_rel->serverid;
4061  window_rel->userid = input_rel->userid;
4062  window_rel->useridiscurrent = input_rel->useridiscurrent;
4063  window_rel->fdwroutine = input_rel->fdwroutine;
4064 
4065  /*
4066  * Consider computing window functions starting from the existing
4067  * cheapest-total path (which will likely require a sort) as well as any
4068  * existing paths that satisfy or partially satisfy root->window_pathkeys.
4069  */
4070  foreach(lc, input_rel->pathlist)
4071  {
4072  Path *path = (Path *) lfirst(lc);
4073  int presorted_keys;
4074 
4075  if (path == input_rel->cheapest_total_path ||
4077  &presorted_keys) ||
4078  presorted_keys > 0)
4080  window_rel,
4081  path,
4082  input_target,
4083  output_target,
4084  wflists,
4085  activeWindows);
4086  }
4087 
4088  /*
4089  * If there is an FDW that's responsible for all baserels of the query,
4090  * let it consider adding ForeignPaths.
4091  */
4092  if (window_rel->fdwroutine &&
4093  window_rel->fdwroutine->GetForeignUpperPaths)
4094  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4095  input_rel, window_rel,
4096  NULL);
4097 
4098  /* Let extensions possibly add some more paths */
4100  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4101  input_rel, window_rel, NULL);
4102 
4103  /* Now choose the best path(s) */
4104  set_cheapest(window_rel);
4105 
4106  return window_rel;
4107 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
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:4121
Oid userid
Definition: pathnodes.h:733
Definition: nodes.h:536
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:734
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:639
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
struct Path * cheapest_total_path
Definition: pathnodes.h:699
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:736
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:732
List * window_pathkeys
Definition: pathnodes.h:297
List * pathkeys
Definition: pathnodes.h:1196
#define lfirst(lc)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:689
List * pathlist
Definition: pathnodes.h:695

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 5807 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().

5808 {
5809  Node *result;
5810 
5811  /*
5812  * Convert named-argument function calls, insert default arguments and
5813  * simplify constant subexprs
5814  */
5815  result = eval_const_expressions(NULL, (Node *) expr);
5816 
5817  /* Fill in opfuncid values if missing */
5818  fix_opfuncids(result);
5819 
5820  return (Expr *) result;
5821 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:536
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2094

◆ expression_planner_with_deps()

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

Definition at line 5834 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().

5837 {
5838  Node *result;
5839  PlannerGlobal glob;
5840  PlannerInfo root;
5841 
5842  /* Make up dummy planner state so we can use setrefs machinery */
5843  MemSet(&glob, 0, sizeof(glob));
5844  glob.type = T_PlannerGlobal;
5845  glob.relationOids = NIL;
5846  glob.invalItems = NIL;
5847 
5848  MemSet(&root, 0, sizeof(root));
5849  root.type = T_PlannerInfo;
5850  root.glob = &glob;
5851 
5852  /*
5853  * Convert named-argument function calls, insert default arguments and
5854  * simplify constant subexprs. Collect identities of inlined functions
5855  * and elided domains, too.
5856  */
5857  result = eval_const_expressions(&root, (Node *) expr);
5858 
5859  /* Fill in opfuncid values if missing */
5860  fix_opfuncids(result);
5861 
5862  /*
5863  * Now walk the finished expression to find anything else we ought to
5864  * record as an expression dependency.
5865  */
5866  (void) extract_query_dependencies_walker(result, &root);
5867 
5868  *relationOids = glob.relationOids;
5869  *invalItems = glob.invalItems;
5870 
5871  return (Expr *) result;
5872 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:536
#define MemSet(start, val, len)
Definition: c.h:1008
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2094
PlannerGlobal * glob
Definition: pathnodes.h:164
List * invalItems
Definition: pathnodes.h:112
NodeTag type
Definition: pathnodes.h:160
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3080
NodeTag type
Definition: pathnodes.h:92
List * relationOids
Definition: pathnodes.h:110

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

Definition at line 2812 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().

2813 {
2814  int num_sets_raw = list_length(groupingSets);
2815  int num_empty = 0;
2816  int num_sets = 0; /* distinct sets */
2817  int num_chains = 0;
2818  List *result = NIL;
2819  List **results;
2820  List **orig_sets;
2821  Bitmapset **set_masks;
2822  int *chains;
2823  short **adjacency;
2824  short *adjacency_buf;
2826  int i;
2827  int j;
2828  int j_size;
2829  ListCell *lc1 = list_head(groupingSets);
2830  ListCell *lc;
2831 
2832  /*
2833  * Start by stripping out empty sets. The algorithm doesn't require this,
2834  * but the planner currently needs all empty sets to be returned in the
2835  * first list, so we strip them here and add them back after.
2836  */
2837  while (lc1 && lfirst(lc1) == NIL)
2838  {
2839  ++num_empty;
2840  lc1 = lnext(groupingSets, lc1);
2841  }
2842 
2843  /* bail out now if it turns out that all we had were empty sets. */
2844  if (!lc1)
2845  return list_make1(groupingSets);
2846 
2847  /*----------
2848  * We don't strictly need to remove duplicate sets here, but if we don't,
2849  * they tend to become scattered through the result, which is a bit
2850  * confusing (and irritating if we ever decide to optimize them out).
2851  * So we remove them here and add them back after.
2852  *
2853  * For each non-duplicate set, we fill in the following:
2854  *
2855  * orig_sets[i] = list of the original set lists
2856  * set_masks[i] = bitmapset for testing inclusion
2857  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
2858  *
2859  * chains[i] will be the result group this set is assigned to.
2860  *
2861  * We index all of these from 1 rather than 0 because it is convenient
2862  * to leave 0 free for the NIL node in the graph algorithm.
2863  *----------
2864  */
2865  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
2866  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
2867  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
2868  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
2869 
2870  j_size = 0;
2871  j = 0;
2872  i = 1;
2873 
2874  for_each_cell(lc, groupingSets, lc1)
2875  {
2876  List *candidate = (List *) lfirst(lc);
2877  Bitmapset *candidate_set = NULL;
2878  ListCell *lc2;
2879  int dup_of = 0;
2880 
2881  foreach(lc2, candidate)
2882  {
2883  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
2884  }
2885 
2886  /* we can only be a dup if we're the same length as a previous set */
2887  if (j_size == list_length(candidate))
2888  {
2889  int k;
2890 
2891  for (k = j; k < i; ++k)
2892  {
2893  if (bms_equal(set_masks[k], candidate_set))
2894  {
2895  dup_of = k;
2896  break;
2897  }
2898  }
2899  }
2900  else if (j_size < list_length(candidate))
2901  {
2902  j_size = list_length(candidate);
2903  j = i;
2904  }
2905 
2906  if (dup_of > 0)
2907  {
2908  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
2909  bms_free(candidate_set);
2910  }
2911  else
2912  {
2913  int k;
2914  int n_adj = 0;
2915 
2916  orig_sets[i] = list_make1(candidate);
2917  set_masks[i] = candidate_set;
2918 
2919  /* fill in adjacency list; no need to compare equal-size sets */
2920 
2921  for (k = j - 1; k > 0; --k)
2922  {
2923  if (bms_is_subset(set_masks[k], candidate_set))
2924  adjacency_buf[++n_adj] = k;
2925  }
2926 
2927  if (n_adj > 0)
2928  {
2929  adjacency_buf[0] = n_adj;
2930  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
2931  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
2932  }
2933  else
2934  adjacency[i] = NULL;
2935 
2936  ++i;
2937  }
2938  }
2939 
2940  num_sets = i - 1;
2941 
2942  /*
2943  * Apply the graph matching algorithm to do the work.
2944  */
2945  state = BipartiteMatch(num_sets, num_sets, adjacency);
2946 
2947  /*
2948  * Now, the state->pair* fields have the info we need to assign sets to
2949  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
2950  * pair_vu[v] = u (both will be true, but we check both so that we can do
2951  * it in one pass)
2952  */
2953  chains = palloc0((num_sets + 1) * sizeof(int));
2954 
2955  for (i = 1; i <= num_sets; ++i)
2956  {
2957  int u = state->pair_vu[i];
2958  int v = state->pair_uv[i];
2959 
2960  if (u > 0 && u < i)
2961  chains[i] = chains[u];
2962  else if (v > 0 && v < i)
2963  chains[i] = chains[v];
2964  else
2965  chains[i] = ++num_chains;
2966  }
2967 
2968  /* build result lists. */
2969  results = palloc0((num_chains + 1) * sizeof(List *));
2970 
2971  for (i = 1; i <= num_sets; ++i)
2972  {
2973  int c = chains[i];
2974 
2975  Assert(c > 0);
2976 
2977  results[c] = list_concat(results[c], orig_sets[i]);
2978  }
2979 
2980  /* push any empty sets back on the first list. */
2981  while (num_empty-- > 0)
2982  results[1] = lcons(NIL, results[1]);
2983 
2984  /* make result list */
2985  for (i = 1; i <= num_chains; ++i)
2986  result = lappend(result, results[i]);
2987 
2988  /*
2989  * Free all the things.
2990  *
2991  * (This is over-fussy for small sets but for large sets we could have
2992  * tied up a nontrivial amount of memory.)
2993  */
2994  BipartiteMatchFree(state);
2995  pfree(results);
2996  pfree(chains);
2997  for (i = 1; i <= num_sets; ++i)
2998  if (adjacency[i])
2999  pfree(adjacency[i]);
3000  pfree(adjacency);
3001  pfree(adjacency_buf);
3002  pfree(orig_sets);
3003  for (i = 1; i <= num_sets; ++i)
3004  bms_free(set_masks[i]);
3005  pfree(set_masks);
3006 
3007  return result;
3008 }
#define NIL
Definition: pg_list.h:65
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
void BipartiteMatchFree(BipartiteMatchState *state)
#define list_make1(x1)
Definition: pg_list.h:206
void pfree(void *pointer)
Definition: mcxt.c:1169
#define lfirst_int(lc)
Definition: pg_list.h:170
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:336
void * palloc0(Size size)
Definition: mcxt.c:1093
BipartiteMatchState * BipartiteMatch(int u_size, int v_size, short **adjacency)
List * lcons(void *datum, List *list)
Definition: list.c:468
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Definition: regguts.h:317
static int list_length(const List *l)
Definition: pg_list.h:149
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
void * palloc(Size size)
Definition: mcxt.c:1062
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 6867 of file planner.c.

References add_path(), create_gather_merge_path(), create_incremental_sort_path(), create_sort_path(), enable_incremental_sort, generate_useful_gather_paths(), PlannerInfo::group_pathkeys, lfirst, linitial, list_length(), Path::parallel_workers, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), pathkeys_count_contained_in(), RelOptInfo::reltarget, and Path::rows.

Referenced by add_paths_to_grouping_rel(), and create_ordinary_grouping_paths().

6868 {
6869  ListCell *lc;
6870  Path *cheapest_partial_path;
6871 
6872  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
6873  generate_useful_gather_paths(root, rel, true);
6874 
6875  /* Try cheapest partial path + explicit Sort + Gather Merge. */
6876  cheapest_partial_path = linitial(rel->partial_pathlist);
6878  cheapest_partial_path->pathkeys))
6879  {
6880  Path *path;
6881  double total_groups;
6882 
6883  total_groups =
6884  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
6885  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
6886  root->group_pathkeys,
6887  -1.0);
6888  path = (Path *)
6890  rel,
6891  path,
6892  rel->reltarget,
6893  root->group_pathkeys,
6894  NULL,
6895  &total_groups);
6896 
6897  add_path(rel, path);
6898  }
6899 
6900  /*
6901  * Consider incremental sort on all partial paths, if enabled.
6902  *
6903  * We can also skip the entire loop when we only have a single-item
6904  * group_pathkeys because then we can't possibly have a presorted prefix
6905  * of the list without having the list be fully sorted.
6906  */
6908  return;
6909 
6910  /* also consider incremental sort on partial paths, if enabled */
6911  foreach(lc, rel->partial_pathlist)
6912  {
6913  Path *path = (Path *) lfirst(lc);
6914  bool is_sorted;
6915  int presorted_keys;
6916  double total_groups;
6917 
6918  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6919  path->pathkeys,
6920  &presorted_keys);
6921 
6922  if (is_sorted)
6923  continue;
6924 
6925  if (presorted_keys == 0)
6926  continue;
6927 
6928  path = (Path *) create_incremental_sort_path(root,
6929  rel,
6930  path,
6931  root->group_pathkeys,
6932  presorted_keys,
6933  -1.0);
6934 
6935  path = (Path *)
6937  rel,
6938  path,
6939  rel->reltarget,
6940  root->group_pathkeys,
6941  NULL,
6942  &total_groups);
6943 
6944  add_path(rel, path);
6945  }
6946 }
List * group_pathkeys
Definition: pathnodes.h:296
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:139
int parallel_workers
Definition: pathnodes.h:1189
List * partial_pathlist
Definition: pathnodes.h:697
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2892
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define linitial(l)
Definition: pg_list.h:174
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2746
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:1860
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
List * pathkeys
Definition: pathnodes.h:1196
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
Cardinality rows
Definition: pathnodes.h:1192
struct PathTarget * reltarget
Definition: pathnodes.h:692

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

Definition at line 5648 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().

5649 {
5650  Path *best_path = rel->cheapest_total_path;
5651  ListCell *l;
5652 
5653  /* If all tuples will be retrieved, just return the cheapest-total path */
5654  if (tuple_fraction <= 0.0)
5655  return best_path;
5656 
5657  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5658  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5659  tuple_fraction /= best_path->rows;
5660 
5661  foreach(l, rel->pathlist)
5662  {
5663  Path *path = (Path *) lfirst(l);
5664 
5665  if (path == rel->cheapest_total_path ||
5666  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5667  continue;
5668 
5669  best_path = path;
5670  }
5671 
5672  return best_path;
5673 }
struct Path * cheapest_total_path
Definition: pathnodes.h:699
#define lfirst(lc)
Definition: pg_list.h:169
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: pathnodes.h:695
Cardinality rows
Definition: pathnodes.h:1192

◆ 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 3160 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().

3164 {
3165  Query *parse = root->parse;
3166  double dNumGroups;
3167 
3168  if (parse->groupClause)
3169  {
3170  List *groupExprs;
3171 
3172  if (parse->groupingSets)
3173  {
3174  /* Add up the estimates for each grouping set */
3175  ListCell *lc;
3176  ListCell *lc2;
3177 
3178  Assert(gd); /* keep Coverity happy */
3179 
3180  dNumGroups = 0;
3181 
3182  foreach(lc, gd->rollups)
3183  {
3184  RollupData *rollup = lfirst_node(RollupData, lc);
3185  ListCell *lc;
3186 
3187  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3188  target_list);
3189 
3190  rollup->numGroups = 0.0;
3191 
3192  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3193  {
3194  List *gset = (List *) lfirst(lc);
3196  double numGroups = estimate_num_groups(root,
3197  groupExprs,
3198  path_rows,
3199  &gset,
3200  NULL);
3201 
3202  gs->numGroups = numGroups;
3203  rollup->numGroups += numGroups;
3204  }
3205 
3206  dNumGroups += rollup->numGroups;
3207  }
3208 
3209  if (gd->hash_sets_idx)
3210  {
3211  ListCell *lc;
3212 
3213  gd->dNumHashGroups = 0;
3214 
3215  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3216  target_list);
3217 
3218  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3219  {
3220  List *gset = (List *) lfirst(lc);
3222  double numGroups = estimate_num_groups(root,
3223  groupExprs,
3224  path_rows,
3225  &gset,
3226  NULL);
3227 
3228  gs->numGroups = numGroups;
3229  gd->dNumHashGroups += numGroups;
3230  }
3231 
3232  dNumGroups += gd->dNumHashGroups;
3233  }
3234  }
3235  else
3236  {
3237  /* Plain GROUP BY */
3238  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3239  target_list);
3240 
3241  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3242  NULL, NULL);
3243  }
3244  }
3245  else if (parse->groupingSets)
3246  {
3247  /* Empty grouping sets ... one result row for each one */
3248  dNumGroups = list_length(parse->groupingSets);
3249  }
3250  else if (parse->hasAggs || root->hasHavingQual)
3251  {
3252  /* Plain aggregation, one result row */
3253  dNumGroups = 1;
3254  }
3255  else
3256  {
3257  /* Not grouping */
3258  dNumGroups = 1;
3259  }
3260 
3261  return dNumGroups;
3262 }
Query * parse
Definition: pathnodes.h:162
List * groupClause
Definition: pathnodes.h:1793
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
Cardinality numGroups
Definition: pathnodes.h:1796
bool hasAggs
Definition: parsenodes.h:133
List * hash_sets_idx
Definition: planner.c:109
List * groupingSets
Definition: parsenodes.h:161
double dNumHashGroups
Definition: planner.c:110
#define lfirst_node(type, lc)
Definition: pg_list.h:172
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:381
List * unsortable_sets
Definition: planner.c:114
Cardinality numGroups
Definition: pathnodes.h:1787
List * groupClause
Definition: parsenodes.h:158
bool hasHavingQual
Definition: pathnodes.h:348
Definition: pg_list.h:50
List * gsets_data
Definition: pathnodes.h:1795
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673
List * gsets
Definition: pathnodes.h:1794

◆ group_by_has_partkey()

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

Definition at line 7377 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().

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

◆ grouping_planner()

static void grouping_planner ( PlannerInfo root,
double  tuple_fraction 
)
static

Definition at line 1234 of file planner.c.

References standard_qp_extra::activeWindows, add_partial_path(), add_path(), adjust_appendrel_attrs_multilevel(), adjust_inherited_attnums_multilevel(), adjust_paths_for_srfs(), PlannerInfo::all_result_relids, apply_scanjoin_target_to_paths(), Assert, assign_special_exec_param(), bms_membership(), BMS_MULTIPLE, bms_next_member(), Query::canSetTag, RelOptInfo::cheapest_total_path, CMD_SELECT, CMD_UPDATE, 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_base_rel(), find_window_functions(), FdwRoutine::GetForeignUpperPaths, standard_qp_extra::groupClause, Query::groupClause, Query::groupingSets, Query::hasAggs, PlannerInfo::hasHavingQual, PlannerInfo::hasRecursion, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, IS_DUMMY_REL, is_parallel_safe(), lappend(), lappend_int(), LCS_asString(), PlannerInfo::leaf_result_relids, lfirst, limit_needed(), FinalPathExtraData::limit_needed, PlannerInfo::limit_tuples, FinalPathExtraData::limit_tuples, Query::limitCount, Query::limitOffset, Query::limitOption, 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(), NIL, WindowFuncLists::numWindowFuncs, FinalPathExtraData::offset_est, Query::onConflict, parse(), PlannerInfo::parse, PlannerInfo::partColsUpdated, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, Path::pathtarget, plan_set_operations(), postprocess_setop_tlist(), preprocess_aggrefs(), preprocess_groupclause(), preprocess_grouping_sets(), preprocess_limit(), preprocess_minmax_aggregates(), preprocess_targetlist(), PlannerInfo::processed_tlist, PlannerInfo::query_level, query_planner(), RelOptInfo::relid, RelOptInfo::relids, 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::update_colnos, PlannerInfo::upper_targets, UPPERREL_DISTINCT, UPPERREL_FINAL, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, UPPERREL_PARTIAL_DISTINCT, UPPERREL_WINDOW, RelOptInfo::userid, RelOptInfo::useridiscurrent, Query::windowClause, and Query::withCheckOptions.

Referenced by subquery_planner().

1235 {
1236  Query *parse = root->parse;
1237  int64 offset_est = 0;
1238  int64 count_est = 0;
1239  double limit_tuples = -1.0;
1240  bool have_postponed_srfs = false;
1241  PathTarget *final_target;
1242  List *final_targets;
1243  List *final_targets_contain_srfs;
1244  bool final_target_parallel_safe;
1245  RelOptInfo *current_rel;
1246  RelOptInfo *final_rel;
1247  FinalPathExtraData extra;
1248  ListCell *lc;
1249 
1250  /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1251  if (parse->limitCount || parse->limitOffset)
1252  {
1253  tuple_fraction = preprocess_limit(root, tuple_fraction,
1254  &offset_est, &count_est);
1255 
1256  /*
1257  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1258  * estimate the effects of using a bounded sort.
1259  */
1260  if (count_est > 0 && offset_est >= 0)
1261  limit_tuples = (double) count_est + (double) offset_est;
1262  }
1263 
1264  /* Make tuple_fraction accessible to lower-level routines */
1265  root->tuple_fraction = tuple_fraction;
1266 
1267  if (parse->setOperations)
1268  {
1269  /*
1270  * If there's a top-level ORDER BY, assume we have to fetch all the
1271  * tuples. This might be too simplistic given all the hackery below
1272  * to possibly avoid the sort; but the odds of accurate estimates here
1273  * are pretty low anyway. XXX try to get rid of this in favor of
1274  * letting plan_set_operations generate both fast-start and
1275  * cheapest-total paths.
1276  */
1277  if (parse->sortClause)
1278  root->tuple_fraction = 0.0;
1279 
1280  /*
1281  * Construct Paths for set operations. The results will not need any
1282  * work except perhaps a top-level sort and/or LIMIT. Note that any
1283  * special work for recursive unions is the responsibility of
1284  * plan_set_operations.
1285  */
1286  current_rel = plan_set_operations(root);
1287 
1288  /*
1289  * We should not need to call preprocess_targetlist, since we must be
1290  * in a SELECT query node. Instead, use the processed_tlist returned
1291  * by plan_set_operations (since this tells whether it returned any
1292  * resjunk columns!), and transfer any sort key information from the
1293  * original tlist.
1294  */
1295  Assert(parse->commandType == CMD_SELECT);
1296 
1297  /* for safety, copy processed_tlist instead of modifying in-place */
1298  root->processed_tlist =
1300  parse->targetList);
1301 
1302  /* Also extract the PathTarget form of the setop result tlist */
1303  final_target = current_rel->cheapest_total_path->pathtarget;
1304 
1305  /* And check whether it's parallel safe */
1306  final_target_parallel_safe =
1307  is_parallel_safe(root, (Node *) final_target->exprs);
1308 
1309  /* The setop result tlist couldn't contain any SRFs */
1310  Assert(!parse->hasTargetSRFs);
1311  final_targets = final_targets_contain_srfs = NIL;
1312 
1313  /*
1314  * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1315  * checked already, but let's make sure).
1316  */
1317  if (parse->rowMarks)
1318  ereport(ERROR,
1319  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1320  /*------
1321  translator: %s is a SQL row locking clause such as FOR UPDATE */
1322  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1324  parse->rowMarks)->strength))));
1325 
1326  /*
1327  * Calculate pathkeys that represent result ordering requirements
1328  */
1329  Assert(parse->distinctClause == NIL);
1331  parse->sortClause,
1332  root->processed_tlist);
1333  }
1334  else
1335  {
1336  /* No set operations, do regular planning */
1337  PathTarget *sort_input_target;
1338  List *sort_input_targets;
1339  List *sort_input_targets_contain_srfs;
1340  bool sort_input_target_parallel_safe;
1341  PathTarget *grouping_target;
1342  List *grouping_targets;
1343  List *grouping_targets_contain_srfs;
1344  bool grouping_target_parallel_safe;
1345  PathTarget *scanjoin_target;
1346  List *scanjoin_targets;
1347  List *scanjoin_targets_contain_srfs;
1348  bool scanjoin_target_parallel_safe;
1349  bool scanjoin_target_same_exprs;
1350  bool have_grouping;
1351  WindowFuncLists *wflists = NULL;
1352  List *activeWindows = NIL;
1353  grouping_sets_data *gset_data = NULL;
1354  standard_qp_extra qp_extra;
1355 
1356  /* A recursive query should always have setOperations */
1357  Assert(!root->hasRecursion);
1358 
1359  /* Preprocess grouping sets and GROUP BY clause, if any */
1360  if (parse->groupingSets)
1361  {
1362  gset_data = preprocess_grouping_sets(root);
1363  }
1364  else
1365  {
1366  /* Preprocess regular GROUP BY clause, if any */
1367  if (parse->groupClause)
1368  parse->groupClause = preprocess_groupclause(root, NIL);
1369  }
1370 
1371  /*
1372  * Preprocess targetlist. Note that much of the remaining planning
1373  * work will be done with the PathTarget representation of tlists, but
1374  * we must also maintain the full representation of the final tlist so
1375  * that we can transfer its decoration (resnames etc) to the topmost
1376  * tlist of the finished Plan. This is kept in processed_tlist.
1377  */
1378  preprocess_targetlist(root);
1379 
1380  /*
1381  * Mark all the aggregates with resolved aggtranstypes, and detect
1382  * aggregates that are duplicates or can share transition state. We
1383  * must do this before slicing and dicing the tlist into various
1384  * pathtargets, else some copies of the Aggref nodes might escape
1385  * being marked.
1386  */
1387  if (parse->hasAggs)
1388  {
1389  preprocess_aggrefs(root, (Node *) root->processed_tlist);
1390  preprocess_aggrefs(root, (Node *) parse->havingQual);
1391  }
1392 
1393  /*
1394  * Locate any window functions in the tlist. (We don't need to look
1395  * anywhere else, since expressions used in ORDER BY will be in there
1396  * too.) Note that they could all have been eliminated by constant
1397  * folding, in which case we don't need to do any more work.
1398  */
1399  if (parse->hasWindowFuncs)
1400  {
1401  wflists = find_window_functions((Node *) root->processed_tlist,
1402  list_length(parse->windowClause));
1403  if (wflists->numWindowFuncs > 0)
1404  activeWindows = select_active_windows(root, wflists);
1405  else
1406  parse->hasWindowFuncs = false;
1407  }
1408 
1409  /*
1410  * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1411  * adding logic between here and the query_planner() call. Anything
1412  * that is needed in MIN/MAX-optimizable cases will have to be
1413  * duplicated in planagg.c.
1414  */
1415  if (parse->hasAggs)
1417 
1418  /*
1419  * Figure out whether there's a hard limit on the number of rows that
1420  * query_planner's result subplan needs to return. Even if we know a
1421  * hard limit overall, it doesn't apply if the query has any
1422  * grouping/aggregation operations, or SRFs in the tlist.
1423  */
1424  if (parse->groupClause ||
1425  parse->groupingSets ||
1426  parse->distinctClause ||
1427  parse->hasAggs ||
1428  parse->hasWindowFuncs ||
1429  parse->hasTargetSRFs ||
1430  root->hasHavingQual)
1431  root->limit_tuples = -1.0;
1432  else
1433  root->limit_tuples = limit_tuples;
1434 
1435  /* Set up data needed by standard_qp_callback */
1436  qp_extra.activeWindows = activeWindows;
1437  qp_extra.groupClause = (gset_data
1438  ? (gset_data->rollups ? linitial_node(RollupData, gset_data->rollups)->groupClause : NIL)
1439  : parse->groupClause);
1440 
1441  /*
1442  * Generate the best unsorted and presorted paths for the scan/join
1443  * portion of this Query, ie the processing represented by the
1444  * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1445  * We also generate (in standard_qp_callback) pathkey representations
1446  * of the query's sort clause, distinct clause, etc.
1447  */
1448  current_rel = query_planner(root, standard_qp_callback, &qp_extra);
1449 
1450  /*
1451  * Convert the query's result tlist into PathTarget format.
1452  *
1453  * Note: this cannot be done before query_planner() has performed
1454  * appendrel expansion, because that might add resjunk entries to
1455  * root->processed_tlist. Waiting till afterwards is also helpful
1456  * because the target width estimates can use per-Var width numbers
1457  * that were obtained within query_planner().
1458  */
1459  final_target = create_pathtarget(root, root->processed_tlist);
1460  final_target_parallel_safe =
1461  is_parallel_safe(root, (Node *) final_target->exprs);
1462 
1463  /*
1464  * If ORDER BY was given, consider whether we should use a post-sort
1465  * projection, and compute the adjusted target for preceding steps if
1466  * so.
1467  */
1468  if (parse->sortClause)
1469  {
1470  sort_input_target = make_sort_input_target(root,
1471  final_target,
1472  &have_postponed_srfs);
1473  sort_input_target_parallel_safe =
1474  is_parallel_safe(root, (Node *) sort_input_target->exprs);
1475  }
1476  else
1477  {
1478  sort_input_target = final_target;
1479  sort_input_target_parallel_safe = final_target_parallel_safe;
1480  }
1481 
1482  /*
1483  * If we have window functions to deal with, the output from any
1484  * grouping step needs to be what the window functions want;
1485  * otherwise, it should be sort_input_target.
1486  */
1487  if (activeWindows)
1488  {
1489  grouping_target = make_window_input_target(root,
1490  final_target,
1491  activeWindows);
1492  grouping_target_parallel_safe =
1493  is_parallel_safe(root, (Node *) grouping_target->exprs);
1494  }
1495  else
1496  {
1497  grouping_target = sort_input_target;
1498  grouping_target_parallel_safe = sort_input_target_parallel_safe;
1499  }
1500 
1501  /*
1502  * If we have grouping or aggregation to do, the topmost scan/join
1503  * plan node must emit what the grouping step wants; otherwise, it
1504  * should emit grouping_target.
1505  */
1506  have_grouping = (parse->groupClause || parse->groupingSets ||
1507  parse->hasAggs || root->hasHavingQual);
1508  if (have_grouping)
1509  {
1510  scanjoin_target = make_group_input_target(root, final_target);
1511  scanjoin_target_parallel_safe =
1512  is_parallel_safe(root, (Node *) scanjoin_target->exprs);
1513  }
1514  else
1515  {
1516  scanjoin_target = grouping_target;
1517  scanjoin_target_parallel_safe = grouping_target_parallel_safe;
1518  }
1519 
1520  /*
1521  * If there are any SRFs in the targetlist, we must separate each of
1522  * these PathTargets into SRF-computing and SRF-free targets. Replace
1523  * each of the named targets with a SRF-free version, and remember the
1524  * list of additional projection steps we need to add afterwards.
1525  */
1526  if (parse->hasTargetSRFs)
1527  {
1528  /* final_target doesn't recompute any SRFs in sort_input_target */
1529  split_pathtarget_at_srfs(root, final_target, sort_input_target,
1530  &final_targets,
1531  &final_targets_contain_srfs);
1532  final_target = linitial_node(PathTarget, final_targets);
1533  Assert(!linitial_int(final_targets_contain_srfs));
1534  /* likewise for sort_input_target vs. grouping_target */
1535  split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
1536  &sort_input_targets,
1537  &sort_input_targets_contain_srfs);
1538  sort_input_target = linitial_node(PathTarget, sort_input_targets);
1539  Assert(!linitial_int(sort_input_targets_contain_srfs));
1540  /* likewise for grouping_target vs. scanjoin_target */
1541  split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
1542  &grouping_targets,
1543  &grouping_targets_contain_srfs);
1544  grouping_target = linitial_node(PathTarget, grouping_targets);
1545  Assert(!linitial_int(grouping_targets_contain_srfs));
1546  /* scanjoin_target will not have any SRFs precomputed for it */
1547  split_pathtarget_at_srfs(root, scanjoin_target, NULL,
1548  &scanjoin_targets,
1549  &scanjoin_targets_contain_srfs);
1550  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
1551  Assert(!linitial_int(scanjoin_targets_contain_srfs));
1552  }
1553  else
1554  {
1555  /* initialize lists; for most of these, dummy values are OK */
1556  final_targets = final_targets_contain_srfs = NIL;
1557  sort_input_targets = sort_input_targets_contain_srfs = NIL;
1558  grouping_targets = grouping_targets_contain_srfs = NIL;
1559  scanjoin_targets = list_make1(scanjoin_target);
1560  scanjoin_targets_contain_srfs = NIL;
1561  }
1562 
1563  /* Apply scan/join target. */
1564  scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
1565  && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
1566  apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
1567  scanjoin_targets_contain_srfs,
1568  scanjoin_target_parallel_safe,
1569  scanjoin_target_same_exprs);
1570 
1571  /*
1572  * Save the various upper-rel PathTargets we just computed into
1573  * root->upper_targets[]. The core code doesn't use this, but it
1574  * provides a convenient place for extensions to get at the info. For
1575  * consistency, we save all the intermediate targets, even though some
1576  * of the corresponding upperrels might not be needed for this query.
1577  */
1578  root->upper_targets[UPPERREL_FINAL] = final_target;
1579  root->upper_targets[UPPERREL_ORDERED] = final_target;
1580  root->upper_targets[UPPERREL_PARTIAL_DISTINCT] = sort_input_target;
1581  root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
1582  root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
1583  root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
1584 
1585  /*
1586  * If we have grouping and/or aggregation, consider ways to implement
1587  * that. We build a new upperrel representing the output of this
1588  * phase.
1589  */
1590  if (have_grouping)
1591  {
1592  current_rel = create_grouping_paths(root,
1593  current_rel,
1594  grouping_target,
1595  grouping_target_parallel_safe,
1596  gset_data);
1597  /* Fix things up if grouping_target contains SRFs */
1598  if (parse->hasTargetSRFs)
1599  adjust_paths_for_srfs(root, current_rel,
1600  grouping_targets,
1601  grouping_targets_contain_srfs);
1602  }
1603 
1604  /*
1605  * If we have window functions, consider ways to implement those. We
1606  * build a new upperrel representing the output of this phase.
1607  */
1608  if (activeWindows)
1609  {
1610  current_rel = create_window_paths(root,
1611  current_rel,
1612  grouping_target,
1613  sort_input_target,
1614  sort_input_target_parallel_safe,
1615  wflists,
1616  activeWindows);
1617  /* Fix things up if sort_input_target contains SRFs */
1618  if (parse->hasTargetSRFs)
1619  adjust_paths_for_srfs(root, current_rel,
1620  sort_input_targets,
1621  sort_input_targets_contain_srfs);
1622  }
1623 
1624  /*
1625  * If there is a DISTINCT clause, consider ways to implement that. We
1626  * build a new upperrel representing the output of this phase.
1627  */
1628  if (parse->distinctClause)
1629  {
1630  current_rel = create_distinct_paths(root,
1631  current_rel);
1632  }
1633  } /* end of if (setOperations) */
1634 
1635  /*
1636  * If ORDER BY was given, consider ways to implement that, and generate a
1637  * new upperrel containing only paths that emit the correct ordering and
1638  * project the correct final_target. We can apply the original
1639  * limit_tuples limit in sort costing here, but only if there are no
1640  * postponed SRFs.
1641  */
1642  if (parse->sortClause)
1643  {
1644  current_rel = create_ordered_paths(root,
1645  current_rel,
1646  final_target,
1647  final_target_parallel_safe,
1648  have_postponed_srfs ? -1.0 :
1649  limit_tuples);
1650  /* Fix things up if final_target contains SRFs */
1651  if (parse->hasTargetSRFs)
1652  adjust_paths_for_srfs(root, current_rel,
1653  final_targets,
1654  final_targets_contain_srfs);
1655  }
1656 
1657  /*
1658  * Now we are prepared to build the final-output upperrel.
1659  */
1660  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1661 
1662  /*
1663  * If the input rel is marked consider_parallel and there's nothing that's
1664  * not parallel-safe in the LIMIT clause, then the final_rel can be marked
1665  * consider_parallel as well. Note that if the query has rowMarks or is
1666  * not a SELECT, consider_parallel will be false for every relation in the
1667  * query.
1668  */
1669  if (current_rel->consider_parallel &&
1670  is_parallel_safe(root, parse->limitOffset) &&
1671  is_parallel_safe(root, parse->limitCount))
1672  final_rel->consider_parallel = true;
1673 
1674  /*
1675  * If the current_rel belongs to a single FDW, so does the final_rel.
1676  */
1677  final_rel->serverid = current_rel->serverid;
1678  final_rel->userid = current_rel->userid;
1679  final_rel->useridiscurrent = current_rel->useridiscurrent;
1680  final_rel->fdwroutine = current_rel->fdwroutine;
1681 
1682  /*
1683  * Generate paths for the final_rel. Insert all surviving paths, with
1684  * LockRows, Limit, and/or ModifyTable steps added if needed.
1685  */
1686  foreach(lc, current_rel->pathlist)
1687  {
1688  Path *path = (Path *) lfirst(lc);
1689 
1690  /*
1691  * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
1692  * (Note: we intentionally test parse->rowMarks not root->rowMarks
1693  * here. If there are only non-locking rowmarks, they should be
1694  * handled by the ModifyTable node instead. However, root->rowMarks
1695  * is what goes into the LockRows node.)
1696  */
1697  if (parse->rowMarks)
1698  {
1699  path = (Path *) create_lockrows_path(root, final_rel, path,
1700  root->rowMarks,
1702  }
1703 
1704  /*
1705  * If there is a LIMIT/OFFSET clause, add the LIMIT node.
1706  */
1707  if (limit_needed(parse))
1708  {
1709  path = (Path *) create_limit_path(root, final_rel, path,
1710  parse->limitOffset,
1711  parse->limitCount,
1712  parse->limitOption,
1713  offset_est, count_est);
1714  }
1715 
1716  /*
1717  * If this is an INSERT/UPDATE/DELETE, add the ModifyTable node.
1718  */
1719  if (parse->commandType != CMD_SELECT)
1720  {
1721  Index rootRelation;
1722  List *resultRelations = NIL;
1723  List *updateColnosLists = NIL;
1724  List *withCheckOptionLists = NIL;
1725  List *returningLists = NIL;
1726  List *rowMarks;
1727 
1729  {
1730  /* Inherited UPDATE/DELETE */
1731  RelOptInfo *top_result_rel = find_base_rel(root,
1732  parse->resultRelation);
1733  int resultRelation = -1;
1734 
1735  /* Add only leaf children to ModifyTable. */
1736  while ((resultRelation = bms_next_member(root->leaf_result_relids,
1737  resultRelation)) >= 0)
1738  {
1739  RelOptInfo *this_result_rel = find_base_rel(root,
1740  resultRelation);
1741 
1742  /*
1743  * Also exclude any leaf rels that have turned dummy since
1744  * being added to the list, for example, by being excluded
1745  * by constraint exclusion.
1746  */
1747  if (IS_DUMMY_REL(this_result_rel))
1748  continue;
1749 
1750  /* Build per-target-rel lists needed by ModifyTable */
1751  resultRelations = lappend_int(resultRelations,
1752  resultRelation);
1753  if (parse->commandType == CMD_UPDATE)
1754  {
1755  List *update_colnos = root->update_colnos;
1756 
1757  if (this_result_rel != top_result_rel)
1758  update_colnos =
1760  update_colnos,
1761  this_result_rel->relid,
1762  top_result_rel->relid);
1763  updateColnosLists = lappend(updateColnosLists,
1764  update_colnos);
1765  }
1766  if (parse->withCheckOptions)
1767  {
1768  List *withCheckOptions = parse->withCheckOptions;
1769 
1770  if (this_result_rel != top_result_rel)
1771  withCheckOptions = (List *)
1773  (Node *) withCheckOptions,
1774  this_result_rel->relids,
1775  top_result_rel->relids);
1776  withCheckOptionLists = lappend(withCheckOptionLists,
1777  withCheckOptions);
1778  }
1779  if (parse->returningList)
1780  {
1781  List *returningList = parse->returningList;
1782 
1783  if (this_result_rel != top_result_rel)
1784  returningList = (List *)
1786  (Node *) returningList,
1787  this_result_rel->relids,
1788  top_result_rel->relids);
1789  returningLists = lappend(returningLists,
1790  returningList);
1791  }
1792  }
1793 
1794  if (resultRelations == NIL)
1795  {
1796  /*
1797  * We managed to exclude every child rel, so generate a
1798  * dummy one-relation plan using info for the top target
1799  * rel (even though that may not be a leaf target).
1800  * Although it's clear that no data will be updated or
1801  * deleted, we still need to have a ModifyTable node so
1802  * that any statement triggers will be executed. (This
1803  * could be cleaner if we fixed nodeModifyTable.c to allow
1804  * zero target relations, but that probably wouldn't be a
1805  * net win.)
1806  */
1807  resultRelations = list_make1_int(parse->resultRelation);
1808  if (parse->commandType == CMD_UPDATE)
1809  updateColnosLists = list_make1(root->update_colnos);
1810  if (parse->withCheckOptions)
1811  withCheckOptionLists = list_make1(parse->withCheckOptions);
1812  if (parse->returningList)
1813  returningLists = list_make1(parse->returningList);
1814  }
1815  }
1816  else
1817  {
1818  /* Single-relation INSERT/UPDATE/DELETE. */
1819  resultRelations = list_make1_int(parse->resultRelation);
1820  if (parse->commandType == CMD_UPDATE)
1821  updateColnosLists = list_make1(root->update_colnos);
1822  if (parse->withCheckOptions)
1823  withCheckOptionLists = list_make1(parse->withCheckOptions);
1824  if (parse->returningList)
1825  returningLists = list_make1(parse->returningList);
1826  }
1827 
1828  /*
1829  * If target is a partition root table, we need to mark the
1830  * ModifyTable node appropriately for that.
1831  */
1832  if (rt_fetch(parse->resultRelation, parse->rtable)->relkind ==
1833  RELKIND_PARTITIONED_TABLE)
1834  rootRelation = parse->resultRelation;
1835  else
1836  rootRelation = 0;
1837 
1838  /*
1839  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
1840  * will have dealt with fetching non-locked marked rows, else we
1841  * need to have ModifyTable do that.
1842  */
1843  if (parse->rowMarks)
1844  rowMarks = NIL;
1845  else
1846  rowMarks = root->rowMarks;
1847 
1848  path = (Path *)
1849  create_modifytable_path(root, final_rel,
1850  path,
1851  parse->commandType,
1852  parse->canSetTag,
1853  parse->resultRelation,
1854  rootRelation,
1855  root->partColsUpdated,
1856  resultRelations,
1857  updateColnosLists,
1858  withCheckOptionLists,
1859  returningLists,
1860  rowMarks,
1861  parse->onConflict,
1863  }
1864 
1865  /* And shove it into final_rel */
1866  add_path(final_rel, path);
1867  }
1868 
1869  /*
1870  * Generate partial paths for final_rel, too, if outer query levels might
1871  * be able to make use of them.
1872  */
1873  if (final_rel->consider_parallel && root->query_level > 1 &&
1874  !limit_needed(parse))
1875  {
1876  Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
1877  foreach(lc, current_rel->partial_pathlist)
1878  {
1879  Path *partial_path = (Path *) lfirst(lc);
1880 
1881  add_partial_path(final_rel, partial_path);
1882  }
1883  }
1884 
1885  extra.limit_needed = limit_needed(parse);
1886  extra.limit_tuples = limit_tuples;
1887  extra.count_est = count_est;
1888  extra.offset_est = offset_est;
1889 
1890  /*
1891  * If there is an FDW that's responsible for all baserels of the query,
1892  * let it consider adding ForeignPaths.
1893  */
1894  if (final_rel->fdwroutine &&
1895  final_rel->fdwroutine->GetForeignUpperPaths)
1897  current_rel, final_rel,
1898  &extra);
1899 
1900  /* Let extensions possibly add some more paths */
1902  (*create_upper_paths_hook) (root, UPPERREL_FINAL,
1903  current_rel, final_rel, &extra);
1904 
1905  /* Note: currently, we leave it to callers to do set_cheapest() */
1906 }
RelOptInfo * plan_set_operations(PlannerInfo *root)
Definition: prepunion.c:103
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
Node * limitOffset
Definition: parsenodes.h:171
#define NIL
Definition: pg_list.h:65
List * rowMarks
Definition: pathnodes.h:288
Relids all_result_relids
Definition: pathnodes.h:276
static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
Definition: planner.c:2304
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:6997
PathTarget * pathtarget
Definition: pathnodes.h:1183
Query * parse
Definition: pathnodes.h:162
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3078
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * sortClause
Definition: parsenodes.h:169
List * adjust_inherited_attnums_multilevel(PlannerInfo *root, List *attnums, Index child_relid, Index top_parent_relid)
Definition: appendinfo.c:648
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3564
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3149
OnConflictExpr * onConflict
Definition: parsenodes.h:154
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:1125
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:2709
Oid userid
Definition: pathnodes.h:733
List * withCheckOptions
Definition: parsenodes.h:183
void preprocess_targetlist(PlannerInfo *root)
Definition: preptlist.c:62
void split_pathtarget_at_srfs(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition: tlist.c:870
bool hasAggs
Definition: parsenodes.h:133
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
int resultRelation
Definition: parsenodes.h:130
int numWindowFuncs
Definition: clauses.h:21
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition: clauses.c:225