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 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 preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 92 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 93 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 90 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 82 of file planner.c.

Referenced by 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 5982 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().

5988 {
5989  Query *parse = root->parse;
5990  Path *cheapest_path = input_rel->cheapest_total_path;
5991  ListCell *lc;
5992  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
5993  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
5994  List *havingQual = (List *) extra->havingQual;
5995  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
5996 
5997  if (can_sort)
5998  {
5999  /*
6000  * Use any available suitably-sorted path as input, and also consider
6001  * sorting the cheapest-total path.
6002  */
6003  foreach(lc, input_rel->pathlist)
6004  {
6005  Path *path = (Path *) lfirst(lc);
6006  Path *path_original = path;
6007  bool is_sorted;
6008  int presorted_keys;
6009 
6010  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6011  path->pathkeys,
6012  &presorted_keys);
6013 
6014  if (path == cheapest_path || is_sorted)
6015  {
6016  /* Sort the cheapest-total path if it isn't already sorted */
6017  if (!is_sorted)
6018  path = (Path *) create_sort_path(root,
6019  grouped_rel,
6020  path,
6021  root->group_pathkeys,
6022  -1.0);
6023 
6024  /* Now decide what to stick atop it */
6025  if (parse->groupingSets)
6026  {
6027  consider_groupingsets_paths(root, grouped_rel,
6028  path, true, can_hash,
6029  gd, agg_costs, dNumGroups);
6030  }
6031  else if (parse->hasAggs)
6032  {
6033  /*
6034  * We have aggregation, possibly with plain GROUP BY. Make
6035  * an AggPath.
6036  */
6037  add_path(grouped_rel, (Path *)
6038  create_agg_path(root,
6039  grouped_rel,
6040  path,
6041  grouped_rel->reltarget,
6042  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6044  parse->groupClause,
6045  havingQual,
6046  agg_costs,
6047  dNumGroups));
6048  }
6049  else if (parse->groupClause)
6050  {
6051  /*
6052  * We have GROUP BY without aggregation or grouping sets.
6053  * Make a GroupPath.
6054  */
6055  add_path(grouped_rel, (Path *)
6056  create_group_path(root,
6057  grouped_rel,
6058  path,
6059  parse->groupClause,
6060  havingQual,
6061  dNumGroups));
6062  }
6063  else
6064  {
6065  /* Other cases should have been handled above */
6066  Assert(false);
6067  }
6068  }
6069 
6070  /*
6071  * Now we may consider incremental sort on this path, but only
6072  * when the path is not already sorted and when incremental sort
6073  * is enabled.
6074  */
6075  if (is_sorted || !enable_incremental_sort)
6076  continue;
6077 
6078  /* Restore the input path (we might have added Sort on top). */
6079  path = path_original;
6080 
6081  /* no shared prefix, no point in building incremental sort */
6082  if (presorted_keys == 0)
6083  continue;
6084 
6085  /*
6086  * We should have already excluded pathkeys of length 1 because
6087  * then presorted_keys > 0 would imply is_sorted was true.
6088  */
6089  Assert(list_length(root->group_pathkeys) != 1);
6090 
6091  path = (Path *) create_incremental_sort_path(root,
6092  grouped_rel,
6093  path,
6094  root->group_pathkeys,
6095  presorted_keys,
6096  -1.0);
6097 
6098  /* Now decide what to stick atop it */
6099  if (parse->groupingSets)
6100  {
6101  consider_groupingsets_paths(root, grouped_rel,
6102  path, true, can_hash,
6103  gd, agg_costs, dNumGroups);
6104  }
6105  else if (parse->hasAggs)
6106  {
6107  /*
6108  * We have aggregation, possibly with plain GROUP BY. Make an
6109  * AggPath.
6110  */
6111  add_path(grouped_rel, (Path *)
6112  create_agg_path(root,
6113  grouped_rel,
6114  path,
6115  grouped_rel->reltarget,
6116  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6118  parse->groupClause,
6119  havingQual,
6120  agg_costs,
6121  dNumGroups));
6122  }
6123  else if (parse->groupClause)
6124  {
6125  /*
6126  * We have GROUP BY without aggregation or grouping sets. Make
6127  * a GroupPath.
6128  */
6129  add_path(grouped_rel, (Path *)
6130  create_group_path(root,
6131  grouped_rel,
6132  path,
6133  parse->groupClause,
6134  havingQual,
6135  dNumGroups));
6136  }
6137  else
6138  {
6139  /* Other cases should have been handled above */
6140  Assert(false);
6141  }
6142  }
6143 
6144  /*
6145  * Instead of operating directly on the input relation, we can
6146  * consider finalizing a partially aggregated path.
6147  */
6148  if (partially_grouped_rel != NULL)
6149  {
6150  foreach(lc, partially_grouped_rel->pathlist)
6151  {
6152  Path *path = (Path *) lfirst(lc);
6153  Path *path_original = path;
6154  bool is_sorted;
6155  int presorted_keys;
6156 
6157  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6158  path->pathkeys,
6159  &presorted_keys);
6160 
6161  /*
6162  * Insert a Sort node, if required. But there's no point in
6163  * sorting anything but the cheapest path.
6164  */
6165  if (!is_sorted)
6166  {
6167  if (path != partially_grouped_rel->cheapest_total_path)
6168  continue;
6169  path = (Path *) create_sort_path(root,
6170  grouped_rel,
6171  path,
6172  root->group_pathkeys,
6173  -1.0);
6174  }
6175 
6176  if (parse->hasAggs)
6177  add_path(grouped_rel, (Path *)
6178  create_agg_path(root,
6179  grouped_rel,
6180  path,
6181  grouped_rel->reltarget,
6182  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6184  parse->groupClause,
6185  havingQual,
6186  agg_final_costs,
6187  dNumGroups));
6188  else
6189  add_path(grouped_rel, (Path *)
6190  create_group_path(root,
6191  grouped_rel,
6192  path,
6193  parse->groupClause,
6194  havingQual,
6195  dNumGroups));
6196 
6197  /*
6198  * Now we may consider incremental sort on this path, but only
6199  * when the path is not already sorted and when incremental
6200  * sort is enabled.
6201  */
6202  if (is_sorted || !enable_incremental_sort)
6203  continue;
6204 
6205  /* Restore the input path (we might have added Sort on top). */
6206  path = path_original;
6207 
6208  /* no shared prefix, not point in building incremental sort */
6209  if (presorted_keys == 0)
6210  continue;
6211 
6212  /*
6213  * We should have already excluded pathkeys of length 1
6214  * because then presorted_keys > 0 would imply is_sorted was
6215  * true.
6216  */
6217  Assert(list_length(root->group_pathkeys) != 1);
6218 
6219  path = (Path *) create_incremental_sort_path(root,
6220  grouped_rel,
6221  path,
6222  root->group_pathkeys,
6223  presorted_keys,
6224  -1.0);
6225 
6226  if (parse->hasAggs)
6227  add_path(grouped_rel, (Path *)
6228  create_agg_path(root,
6229  grouped_rel,
6230  path,
6231  grouped_rel->reltarget,
6232  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6234  parse->groupClause,
6235  havingQual,
6236  agg_final_costs,
6237  dNumGroups));
6238  else
6239  add_path(grouped_rel, (Path *)
6240  create_group_path(root,
6241  grouped_rel,
6242  path,
6243  parse->groupClause,
6244  havingQual,
6245  dNumGroups));
6246  }
6247  }
6248  }
6249 
6250  if (can_hash)
6251  {
6252  if (parse->groupingSets)
6253  {
6254  /*
6255  * Try for a hash-only groupingsets path over unsorted input.
6256  */
6257  consider_groupingsets_paths(root, grouped_rel,
6258  cheapest_path, false, true,
6259  gd, agg_costs, dNumGroups);
6260  }
6261  else
6262  {
6263  /*
6264  * Generate a HashAgg Path. We just need an Agg over the
6265  * cheapest-total input path, since input order won't matter.
6266  */
6267  add_path(grouped_rel, (Path *)
6268  create_agg_path(root, grouped_rel,
6269  cheapest_path,
6270  grouped_rel->reltarget,
6271  AGG_HASHED,
6273  parse->groupClause,
6274  havingQual,
6275  agg_costs,
6276  dNumGroups));
6277  }
6278 
6279  /*
6280  * Generate a Finalize HashAgg Path atop of the cheapest partially
6281  * grouped path, assuming there is one
6282  */
6283  if (partially_grouped_rel && partially_grouped_rel->pathlist)
6284  {
6285  Path *path = partially_grouped_rel->cheapest_total_path;
6286 
6287  add_path(grouped_rel, (Path *)
6288  create_agg_path(root,
6289  grouped_rel,
6290  path,
6291  grouped_rel->reltarget,
6292  AGG_HASHED,
6294  parse->groupClause,
6295  havingQual,
6296  agg_final_costs,
6297  dNumGroups));
6298  }
6299  }
6300 
6301  /*
6302  * When partitionwise aggregate is used, we might have fully aggregated
6303  * paths in the partial pathlist, because add_paths_to_append_rel() will
6304  * consider a path for grouped_rel consisting of a Parallel Append of
6305  * non-partial paths from each child.
6306  */
6307  if (grouped_rel->partial_pathlist != NIL)
6308  gather_grouping_paths(root, grouped_rel);
6309 }
List * group_pathkeys
Definition: pathnodes.h:295
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
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:3661
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6713
bool hasAggs
Definition: parsenodes.h:133
List * groupingSets
Definition: parsenodes.h:161
List * partial_pathlist
Definition: pathnodes.h:692
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:2541
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:694
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:2542
List * pathkeys
Definition: pathnodes.h:1188
#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:690
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:2582
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:687
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

◆ adjust_paths_for_srfs()

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

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

5539 {
5540  ListCell *lc;
5541 
5542  Assert(list_length(targets) == list_length(targets_contain_srfs));
5543  Assert(!linitial_int(targets_contain_srfs));
5544 
5545  /* If no SRFs appear at this plan level, nothing to do */
5546  if (list_length(targets) == 1)
5547  return;
5548 
5549  /*
5550  * Stack SRF-evaluation nodes atop each path for the rel.
5551  *
5552  * In principle we should re-run set_cheapest() here to identify the
5553  * cheapest path, but it seems unlikely that adding the same tlist eval
5554  * costs to all the paths would change that, so we don't bother. Instead,
5555  * just assume that the cheapest-startup and cheapest-total paths remain
5556  * so. (There should be no parameterized paths anymore, so we needn't
5557  * worry about updating cheapest_parameterized_paths.)
5558  */
5559  foreach(lc, rel->pathlist)
5560  {
5561  Path *subpath = (Path *) lfirst(lc);
5562  Path *newpath = subpath;
5563  ListCell *lc1,
5564  *lc2;
5565 
5566  Assert(subpath->param_info == NULL);
5567  forboth(lc1, targets, lc2, targets_contain_srfs)
5568  {
5569  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5570  bool contains_srfs = (bool) lfirst_int(lc2);
5571 
5572  /* If this level doesn't contain SRFs, do regular projection */
5573  if (contains_srfs)
5574  newpath = (Path *) create_set_projection_path(root,
5575  rel,
5576  newpath,
5577  thistarget);
5578  else
5579  newpath = (Path *) apply_projection_to_path(root,
5580  rel,
5581  newpath,
5582  thistarget);
5583  }
5584  lfirst(lc) = newpath;
5585  if (subpath == rel->cheapest_startup_path)
5586  rel->cheapest_startup_path = newpath;
5587  if (subpath == rel->cheapest_total_path)
5588  rel->cheapest_total_path = newpath;
5589  }
5590 
5591  /* Likewise for partial paths, if any */
5592  foreach(lc, rel->partial_pathlist)
5593  {
5594  Path *subpath = (Path *) lfirst(lc);
5595  Path *newpath = subpath;
5596  ListCell *lc1,
5597  *lc2;
5598 
5599  Assert(subpath->param_info == NULL);
5600  forboth(lc1, targets, lc2, targets_contain_srfs)
5601  {
5602  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5603  bool contains_srfs = (bool) lfirst_int(lc2);
5604 
5605  /* If this level doesn't contain SRFs, do regular projection */
5606  if (contains_srfs)
5607  newpath = (Path *) create_set_projection_path(root,
5608  rel,
5609  newpath,
5610  thistarget);
5611  else
5612  {
5613  /* avoid apply_projection_to_path, in case of multiple refs */
5614  newpath = (Path *) create_projection_path(root,
5615  rel,
5616  newpath,
5617  thistarget);
5618  }
5619  }
5620  lfirst(lc) = newpath;
5621  }
5622 }
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:693
ParamPathInfo * param_info
Definition: pathnodes.h:1177
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2626
List * partial_pathlist
Definition: pathnodes.h:692
#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:694
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:690
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 6843 of file planner.c.

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

Referenced by grouping_planner().

6849 {
6850  bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
6851  PathTarget *scanjoin_target;
6852  ListCell *lc;
6853 
6854  /* This recurses, so be paranoid. */
6856 
6857  /*
6858  * If the rel is partitioned, we want to drop its existing paths and
6859  * generate new ones. This function would still be correct if we kept the
6860  * existing paths: we'd modify them to generate the correct target above
6861  * the partitioning Append, and then they'd compete on cost with paths
6862  * generating the target below the Append. However, in our current cost
6863  * model the latter way is always the same or cheaper cost, so modifying
6864  * the existing paths would just be useless work. Moreover, when the cost
6865  * is the same, varying roundoff errors might sometimes allow an existing
6866  * path to be picked, resulting in undesirable cross-platform plan
6867  * variations. So we drop old paths and thereby force the work to be done
6868  * below the Append, except in the case of a non-parallel-safe target.
6869  *
6870  * Some care is needed, because we have to allow
6871  * generate_useful_gather_paths to see the old partial paths in the next
6872  * stanza. Hence, zap the main pathlist here, then allow
6873  * generate_useful_gather_paths to add path(s) to the main list, and
6874  * finally zap the partial pathlist.
6875  */
6876  if (rel_is_partitioned)
6877  rel->pathlist = NIL;
6878 
6879  /*
6880  * If the scan/join target is not parallel-safe, partial paths cannot
6881  * generate it.
6882  */
6883  if (!scanjoin_target_parallel_safe)
6884  {
6885  /*
6886  * Since we can't generate the final scan/join target in parallel
6887  * workers, this is our last opportunity to use any partial paths that
6888  * exist; so build Gather path(s) that use them and emit whatever the
6889  * current reltarget is. We don't do this in the case where the
6890  * target is parallel-safe, since we will be able to generate superior
6891  * paths by doing it after the final scan/join target has been
6892  * applied.
6893  */
6894  generate_useful_gather_paths(root, rel, false);
6895 
6896  /* Can't use parallel query above this level. */
6897  rel->partial_pathlist = NIL;
6898  rel->consider_parallel = false;
6899  }
6900 
6901  /* Finish dropping old paths for a partitioned rel, per comment above */
6902  if (rel_is_partitioned)
6903  rel->partial_pathlist = NIL;
6904 
6905  /* Extract SRF-free scan/join target. */
6906  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
6907 
6908  /*
6909  * Apply the SRF-free scan/join target to each existing path.
6910  *
6911  * If the tlist exprs are the same, we can just inject the sortgroupref
6912  * information into the existing pathtargets. Otherwise, replace each
6913  * path with a projection path that generates the SRF-free scan/join
6914  * target. This can't change the ordering of paths within rel->pathlist,
6915  * so we just modify the list in place.
6916  */
6917  foreach(lc, rel->pathlist)
6918  {
6919  Path *subpath = (Path *) lfirst(lc);
6920 
6921  /* Shouldn't have any parameterized paths anymore */
6922  Assert(subpath->param_info == NULL);
6923 
6924  if (tlist_same_exprs)
6925  subpath->pathtarget->sortgrouprefs =
6926  scanjoin_target->sortgrouprefs;
6927  else
6928  {
6929  Path *newpath;
6930 
6931  newpath = (Path *) create_projection_path(root, rel, subpath,
6932  scanjoin_target);
6933  lfirst(lc) = newpath;
6934  }
6935  }
6936 
6937  /* Likewise adjust the targets for any partial paths. */
6938  foreach(lc, rel->partial_pathlist)
6939  {
6940  Path *subpath = (Path *) lfirst(lc);
6941 
6942  /* Shouldn't have any parameterized paths anymore */
6943  Assert(subpath->param_info == NULL);
6944 
6945  if (tlist_same_exprs)
6946  subpath->pathtarget->sortgrouprefs =
6947  scanjoin_target->sortgrouprefs;
6948  else
6949  {
6950  Path *newpath;
6951 
6952  newpath = (Path *) create_projection_path(root, rel, subpath,
6953  scanjoin_target);
6954  lfirst(lc) = newpath;
6955  }
6956  }
6957 
6958  /*
6959  * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
6960  * atop each existing path. (Note that this function doesn't look at the
6961  * cheapest-path fields, which is a good thing because they're bogus right
6962  * now.)
6963  */
6964  if (root->parse->hasTargetSRFs)
6965  adjust_paths_for_srfs(root, rel,
6966  scanjoin_targets,
6967  scanjoin_targets_contain_srfs);
6968 
6969  /*
6970  * Update the rel's target to be the final (with SRFs) scan/join target.
6971  * This now matches the actual output of all the paths, and we might get
6972  * confused in createplan.c if they don't agree. We must do this now so
6973  * that any append paths made in the next part will use the correct
6974  * pathtarget (cf. create_append_path).
6975  *
6976  * Note that this is also necessary if GetForeignUpperPaths() gets called
6977  * on the final scan/join relation or on any of its children, since the
6978  * FDW might look at the rel's target to create ForeignPaths.
6979  */
6980  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
6981 
6982  /*
6983  * If the relation is partitioned, recursively apply the scan/join target
6984  * to all partitions, and generate brand-new Append paths in which the
6985  * scan/join target is computed below the Append rather than above it.
6986  * Since Append is not projection-capable, that might save a separate
6987  * Result node, and it also is important for partitionwise aggregate.
6988  */
6989  if (rel_is_partitioned)
6990  {
6991  List *live_children = NIL;
6992  int partition_idx;
6993 
6994  /* Adjust each partition. */
6995  for (partition_idx = 0; partition_idx < rel->nparts; partition_idx++)
6996  {
6997  RelOptInfo *child_rel = rel->part_rels[partition_idx];
6998  AppendRelInfo **appinfos;
6999  int nappinfos;
7000  List *child_scanjoin_targets = NIL;
7001  ListCell *lc;
7002 
7003  /* Pruned or dummy children can be ignored. */
7004  if (child_rel == NULL || IS_DUMMY_REL(child_rel))
7005  continue;
7006 
7007  /* Translate scan/join targets for this child. */
7008  appinfos = find_appinfos_by_relids(root, child_rel->relids,
7009  &nappinfos);
7010  foreach(lc, scanjoin_targets)
7011  {
7012  PathTarget *target = lfirst_node(PathTarget, lc);
7013 
7014  target = copy_pathtarget(target);
7015  target->exprs = (List *)
7017  (Node *) target->exprs,
7018  nappinfos, appinfos);
7019  child_scanjoin_targets = lappend(child_scanjoin_targets,
7020  target);
7021  }
7022  pfree(appinfos);
7023 
7024  /* Recursion does the real work. */
7025  apply_scanjoin_target_to_paths(root, child_rel,
7026  child_scanjoin_targets,
7027  scanjoin_targets_contain_srfs,
7028  scanjoin_target_parallel_safe,
7030 
7031  /* Save non-dummy children for Append paths. */
7032  if (!IS_DUMMY_REL(child_rel))
7033  live_children = lappend(live_children, child_rel);
7034  }
7035 
7036  /* Build new paths for this relation by appending child paths. */
7037  add_paths_to_append_rel(root, rel, live_children);
7038  }
7039 
7040  /*
7041  * Consider generating Gather or Gather Merge paths. We must only do this
7042  * if the relation is parallel safe, and we don't do it for child rels to
7043  * avoid creating multiple Gather nodes within the same plan. We must do
7044  * this after all paths have been generated and before set_cheapest, since
7045  * one of the generated paths may turn out to be the cheapest one.
7046  */
7047  if (rel->consider_parallel && !IS_OTHER_REL(rel))
7048  generate_useful_gather_paths(root, rel, false);
7049 
7050  /*
7051  * Reassess which paths are the cheapest, now that we've potentially added
7052  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
7053  * this relation.
7054  */
7055  set_cheapest(rel);
7056 }
#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:6843
PathTarget * pathtarget
Definition: pathnodes.h:1175
Query * parse
Definition: pathnodes.h:161
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:664
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1285
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2626
List * partial_pathlist
Definition: pathnodes.h:692
#define linitial_node(type, l)
Definition: pg_list.h:177
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:5537
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:1458
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void check_stack_depth(void)
Definition: postgres.c:3469
int nparts
Definition: pathnodes.h:756
Index * sortgrouprefs
Definition: pathnodes.h:1103
Relids relids
Definition: pathnodes.h:676
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:1102
#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:763
bool consider_parallel
Definition: pathnodes.h:684
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:207
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:778
List * pathlist
Definition: pathnodes.h:690
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:687
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 6801 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().

6802 {
6803  Query *parse = root->parse;
6804 
6805  if (!parse->hasAggs && parse->groupClause == NIL)
6806  {
6807  /*
6808  * We don't know how to do parallel aggregation unless we have either
6809  * some aggregates or a grouping clause.
6810  */
6811  return false;
6812  }
6813  else if (parse->groupingSets)
6814  {
6815  /* We don't know how to do grouping sets in parallel. */
6816  return false;
6817  }
6818  else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
6819  {
6820  /* Insufficient support for partial mode. */
6821  return false;
6822  }
6823 
6824  /* Everything looks good. */
6825  return true;
6826 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
bool hasAggs
Definition: parsenodes.h:133
List * groupingSets
Definition: parsenodes.h:161
bool hasNonSerialAggs
Definition: pathnodes.h:360
List * groupClause
Definition: parsenodes.h:158
bool hasNonPartialAggs
Definition: pathnodes.h:359
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

◆ common_prefix_cmp()

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

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

5043 {
5044  const WindowClauseSortData *wcsa = a;
5045  const WindowClauseSortData *wcsb = b;
5046  ListCell *item_a;
5047  ListCell *item_b;
5048 
5049  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5050  {
5053 
5054  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5055  return -1;
5056  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5057  return 1;
5058  else if (sca->sortop > scb->sortop)
5059  return -1;
5060  else if (sca->sortop < scb->sortop)
5061  return 1;
5062  else if (sca->nulls_first && !scb->nulls_first)
5063  return -1;
5064  else if (!sca->nulls_first && scb->nulls_first)
5065  return 1;
5066  /* no need to compare eqop, since it is fully determined by sortop */
5067  }
5068 
5069  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5070  return -1;
5071  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5072  return 1;
5073 
5074  return 0;
5075 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
Index tleSortGroupRef
Definition: parsenodes.h:1283
#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 3661 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().

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

◆ create_degenerate_grouping_paths()

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

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

3463 {
3464  Query *parse = root->parse;
3465  int nrows;
3466  Path *path;
3467 
3468  nrows = list_length(parse->groupingSets);
3469  if (nrows > 1)
3470  {
3471  /*
3472  * Doesn't seem worthwhile writing code to cons up a generate_series
3473  * or a values scan to emit multiple rows. Instead just make N clones
3474  * and append them. (With a volatile HAVING clause, this means you
3475  * might get between 0 and N output rows. Offhand I think that's
3476  * desired.)
3477  */
3478  List *paths = NIL;
3479 
3480  while (--nrows >= 0)
3481  {
3482  path = (Path *)
3483  create_group_result_path(root, grouped_rel,
3484  grouped_rel->reltarget,
3485  (List *) parse->havingQual);
3486  paths = lappend(paths, path);
3487  }
3488  path = (Path *)
3489  create_append_path(root,
3490  grouped_rel,
3491  paths,
3492  NIL,
3493  NIL,
3494  NULL,
3495  0,
3496  false,
3497  -1);
3498  }
3499  else
3500  {
3501  /* No grouping sets, or just one, so one output row */
3502  path = (Path *)
3503  create_group_result_path(root, grouped_rel,
3504  grouped_rel->reltarget,
3505  (List *) parse->havingQual);
3506  }
3507 
3508  add_path(grouped_rel, path);
3509 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
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:687
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

◆ create_distinct_paths()

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

Definition at line 4230 of file planner.c.

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

Referenced by grouping_planner().

4232 {
4233  Query *parse = root->parse;
4234  Path *cheapest_input_path = input_rel->cheapest_total_path;
4235  RelOptInfo *distinct_rel;
4236  double numDistinctRows;
4237  bool allow_hash;
4238  Path *path;
4239  ListCell *lc;
4240 
4241  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4242  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4243 
4244  /*
4245  * We don't compute anything at this level, so distinct_rel will be
4246  * parallel-safe if the input rel is parallel-safe. In particular, if
4247  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4248  * output those expressions, and will not be parallel-safe unless those
4249  * expressions are parallel-safe.
4250  */
4251  distinct_rel->consider_parallel = input_rel->consider_parallel;
4252 
4253  /*
4254  * If the input rel belongs to a single FDW, so does the distinct_rel.
4255  */
4256  distinct_rel->serverid = input_rel->serverid;
4257  distinct_rel->userid = input_rel->userid;
4258  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4259  distinct_rel->fdwroutine = input_rel->fdwroutine;
4260 
4261  /* Estimate number of distinct rows there will be */
4262  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4263  root->hasHavingQual)
4264  {
4265  /*
4266  * If there was grouping or aggregation, use the number of input rows
4267  * as the estimated number of DISTINCT rows (ie, assume the input is
4268  * already mostly unique).
4269  */
4270  numDistinctRows = cheapest_input_path->rows;
4271  }
4272  else
4273  {
4274  /*
4275  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4276  */
4277  List *distinctExprs;
4278 
4279  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4280  parse->targetList);
4281  numDistinctRows = estimate_num_groups(root, distinctExprs,
4282  cheapest_input_path->rows,
4283  NULL, NULL);
4284  }
4285 
4286  /*
4287  * Consider sort-based implementations of DISTINCT, if possible.
4288  */
4290  {
4291  /*
4292  * First, if we have any adequately-presorted paths, just stick a
4293  * Unique node on those. Then consider doing an explicit sort of the
4294  * cheapest input path and Unique'ing that.
4295  *
4296  * When we have DISTINCT ON, we must sort by the more rigorous of
4297  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4298  * Also, if we do have to do an explicit sort, we might as well use
4299  * the more rigorous ordering to avoid a second sort later. (Note
4300  * that the parser will have ensured that one clause is a prefix of
4301  * the other.)
4302  */
4303  List *needed_pathkeys;
4304 
4305  if (parse->hasDistinctOn &&
4307  list_length(root->sort_pathkeys))
4308  needed_pathkeys = root->sort_pathkeys;
4309  else
4310  needed_pathkeys = root->distinct_pathkeys;
4311 
4312  foreach(lc, input_rel->pathlist)
4313  {
4314  Path *path = (Path *) lfirst(lc);
4315 
4316  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4317  {
4318  add_path(distinct_rel, (Path *)
4319  create_upper_unique_path(root, distinct_rel,
4320  path,
4322  numDistinctRows));
4323  }
4324  }
4325 
4326  /* For explicit-sort case, always use the more rigorous clause */
4327  if (list_length(root->distinct_pathkeys) <
4328  list_length(root->sort_pathkeys))
4329  {
4330  needed_pathkeys = root->sort_pathkeys;
4331  /* Assert checks that parser didn't mess up... */
4333  needed_pathkeys));
4334  }
4335  else
4336  needed_pathkeys = root->distinct_pathkeys;
4337 
4338  path = cheapest_input_path;
4339  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4340  path = (Path *) create_sort_path(root, distinct_rel,
4341  path,
4342  needed_pathkeys,
4343  -1.0);
4344 
4345  add_path(distinct_rel, (Path *)
4346  create_upper_unique_path(root, distinct_rel,
4347  path,
4349  numDistinctRows));
4350  }
4351 
4352  /*
4353  * Consider hash-based implementations of DISTINCT, if possible.
4354  *
4355  * If we were not able to make any other types of path, we *must* hash or
4356  * die trying. If we do have other choices, there are two things that
4357  * should prevent selection of hashing: if the query uses DISTINCT ON
4358  * (because it won't really have the expected behavior if we hash), or if
4359  * enable_hashagg is off.
4360  *
4361  * Note: grouping_is_hashable() is much more expensive to check than the
4362  * other gating conditions, so we want to do it last.
4363  */
4364  if (distinct_rel->pathlist == NIL)
4365  allow_hash = true; /* we have no alternatives */
4366  else if (parse->hasDistinctOn || !enable_hashagg)
4367  allow_hash = false; /* policy-based decision not to hash */
4368  else
4369  allow_hash = true; /* default */
4370 
4371  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4372  {
4373  /* Generate hashed aggregate path --- no sort needed */
4374  add_path(distinct_rel, (Path *)
4375  create_agg_path(root,
4376  distinct_rel,
4377  cheapest_input_path,
4378  cheapest_input_path->pathtarget,
4379  AGG_HASHED,
4381  parse->distinctClause,
4382  NIL,
4383  NULL,
4384  numDistinctRows));
4385  }
4386 
4387  /* Give a helpful error if we failed to find any implementation */
4388  if (distinct_rel->pathlist == NIL)
4389  ereport(ERROR,
4390  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4391  errmsg("could not implement DISTINCT"),
4392  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4393 
4394  /*
4395  * If there is an FDW that's responsible for all baserels of the query,
4396  * let it consider adding ForeignPaths.
4397  */
4398  if (distinct_rel->fdwroutine &&
4399  distinct_rel->fdwroutine->GetForeignUpperPaths)
4400  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4401  input_rel, distinct_rel,
4402  NULL);
4403 
4404  /* Let extensions possibly add some more paths */
4406  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4407  input_rel, distinct_rel, NULL);
4408 
4409  /* Now choose the best path(s) */
4410  set_cheapest(distinct_rel);
4411 
4412  return distinct_rel;
4413 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1175
Query * parse
Definition: pathnodes.h:161
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
Oid userid
Definition: pathnodes.h:728
bool hasAggs
Definition: parsenodes.h:133
List * groupingSets
Definition: parsenodes.h:161
int errcode(int sqlerrcode)
Definition: elog.c:698
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:549
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:729
bool hasDistinctOn
Definition: parsenodes.h:137
List * targetList
Definition: parsenodes.h:150
List * distinctClause
Definition: parsenodes.h:167
#define ERROR
Definition: elog.h:46
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1207
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:694
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:731
int errdetail(const char *fmt,...)
Definition: elog.c:1042
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:298
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:727
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
List * distinct_pathkeys
Definition: pathnodes.h:297
#define ereport(elevel,...)
Definition: elog.h:157
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2941
List * pathkeys
Definition: pathnodes.h:1188
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1184
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:684
bool enable_hashagg
Definition: costsize.c:140
List * groupClause
Definition: parsenodes.h:158
int errmsg(const char *fmt,...)
Definition: elog.c:909
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:529
bool hasHavingQual
Definition: pathnodes.h:347
List * pathlist
Definition: pathnodes.h:690
Definition: pg_list.h:50
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

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

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

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

4120 {
4121  PathTarget *window_target;
4122  ListCell *l;
4123 
4124  /*
4125  * Since each window clause could require a different sort order, we stack
4126  * up a WindowAgg node for each clause, with sort steps between them as
4127  * needed. (We assume that select_active_windows chose a good order for
4128  * executing the clauses in.)
4129  *
4130  * input_target should contain all Vars and Aggs needed for the result.
4131  * (In some cases we wouldn't need to propagate all of these all the way
4132  * to the top, since they might only be needed as inputs to WindowFuncs.
4133  * It's probably not worth trying to optimize that though.) It must also
4134  * contain all window partitioning and sorting expressions, to ensure
4135  * they're computed only once at the bottom of the stack (that's critical
4136  * for volatile functions). As we climb up the stack, we'll add outputs
4137  * for the WindowFuncs computed at each level.
4138  */
4139  window_target = input_target;
4140 
4141  foreach(l, activeWindows)
4142  {
4144  List *window_pathkeys;
4145  int presorted_keys;
4146  bool is_sorted;
4147 
4148  window_pathkeys = make_pathkeys_for_window(root,
4149  wc,
4150  root->processed_tlist);
4151 
4152  is_sorted = pathkeys_count_contained_in(window_pathkeys,
4153  path->pathkeys,
4154  &presorted_keys);
4155 
4156  /* Sort if necessary */
4157  if (!is_sorted)
4158  {
4159  /*
4160  * No presorted keys or incremental sort disabled, just perform a
4161  * complete sort.
4162  */
4163  if (presorted_keys == 0 || !enable_incremental_sort)
4164  path = (Path *) create_sort_path(root, window_rel,
4165  path,
4166  window_pathkeys,
4167  -1.0);
4168  else
4169  {
4170  /*
4171  * Since we have presorted keys and incremental sort is
4172  * enabled, just use incremental sort.
4173  */
4174  path = (Path *) create_incremental_sort_path(root,
4175  window_rel,
4176  path,
4177  window_pathkeys,
4178  presorted_keys,
4179  -1.0);
4180  }
4181  }
4182 
4183  if (lnext(activeWindows, l))
4184  {
4185  /*
4186  * Add the current WindowFuncs to the output target for this
4187  * intermediate WindowAggPath. We must copy window_target to
4188  * avoid changing the previous path's target.
4189  *
4190  * Note: a WindowFunc adds nothing to the target's eval costs; but
4191  * we do need to account for the increase in tlist width.
4192  */
4193  ListCell *lc2;
4194 
4195  window_target = copy_pathtarget(window_target);
4196  foreach(lc2, wflists->windowFuncs[wc->winref])
4197  {
4198  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4199 
4200  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4201  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4202  }
4203  }
4204  else
4205  {
4206  /* Install the goal target in the topmost WindowAgg */
4207  window_target = output_target;
4208  }
4209 
4210  path = (Path *)
4211  create_windowagg_path(root, window_rel, path, window_target,
4212  wflists->windowFuncs[wc->winref],
4213  wc);
4214  }
4215 
4216  add_path(window_rel, path);
4217 }
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:5229
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:1188
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:320
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 4433 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().

4438 {
4439  Path *cheapest_input_path = input_rel->cheapest_total_path;
4440  RelOptInfo *ordered_rel;
4441  ListCell *lc;
4442 
4443  /* For now, do all work in the (ORDERED, NULL) upperrel */
4444  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4445 
4446  /*
4447  * If the input relation is not parallel-safe, then the ordered relation
4448  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4449  * target list is parallel-safe.
4450  */
4451  if (input_rel->consider_parallel && target_parallel_safe)
4452  ordered_rel->consider_parallel = true;
4453 
4454  /*
4455  * If the input rel belongs to a single FDW, so does the ordered_rel.
4456  */
4457  ordered_rel->serverid = input_rel->serverid;
4458  ordered_rel->userid = input_rel->userid;
4459  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4460  ordered_rel->fdwroutine = input_rel->fdwroutine;
4461 
4462  foreach(lc, input_rel->pathlist)
4463  {
4464  Path *input_path = (Path *) lfirst(lc);
4465  Path *sorted_path = input_path;
4466  bool is_sorted;
4467  int presorted_keys;
4468 
4469  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4470  input_path->pathkeys, &presorted_keys);
4471 
4472  if (is_sorted)
4473  {
4474  /* Use the input path as is, but add a projection step if needed */
4475  if (sorted_path->pathtarget != target)
4476  sorted_path = apply_projection_to_path(root, ordered_rel,
4477  sorted_path, target);
4478 
4479  add_path(ordered_rel, sorted_path);
4480  }
4481  else
4482  {
4483  /*
4484  * Try adding an explicit sort, but only to the cheapest total
4485  * path since a full sort should generally add the same cost to
4486  * all paths.
4487  */
4488  if (input_path == cheapest_input_path)
4489  {
4490  /*
4491  * Sort the cheapest input path. An explicit sort here can
4492  * take advantage of LIMIT.
4493  */
4494  sorted_path = (Path *) create_sort_path(root,
4495  ordered_rel,
4496  input_path,
4497  root->sort_pathkeys,
4498  limit_tuples);
4499  /* Add projection step if needed */
4500  if (sorted_path->pathtarget != target)
4501  sorted_path = apply_projection_to_path(root, ordered_rel,
4502  sorted_path, target);
4503 
4504  add_path(ordered_rel, sorted_path);
4505  }
4506 
4507  /*
4508  * If incremental sort is enabled, then try it as well. Unlike
4509  * with regular sorts, we can't just look at the cheapest path,
4510  * because the cost of incremental sort depends on how well
4511  * presorted the path is. Additionally incremental sort may enable
4512  * a cheaper startup path to win out despite higher total cost.
4513  */
4515  continue;
4516 
4517  /* Likewise, if the path can't be used for incremental sort. */
4518  if (!presorted_keys)
4519  continue;
4520 
4521  /* Also consider incremental sort. */
4522  sorted_path = (Path *) create_incremental_sort_path(root,
4523  ordered_rel,
4524  input_path,
4525  root->sort_pathkeys,
4526  presorted_keys,
4527  limit_tuples);
4528 
4529  /* Add projection step if needed */
4530  if (sorted_path->pathtarget != target)
4531  sorted_path = apply_projection_to_path(root, ordered_rel,
4532  sorted_path, target);
4533 
4534  add_path(ordered_rel, sorted_path);
4535  }
4536  }
4537 
4538  /*
4539  * generate_gather_paths() will have already generated a simple Gather
4540  * path for the best parallel path, if any, and the loop above will have
4541  * considered sorting it. Similarly, generate_gather_paths() will also
4542  * have generated order-preserving Gather Merge plans which can be used
4543  * without sorting if they happen to match the sort_pathkeys, and the loop
4544  * above will have handled those as well. However, there's one more
4545  * possibility: it may make sense to sort the cheapest partial path
4546  * according to the required output order and then use Gather Merge.
4547  */
4548  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
4549  input_rel->partial_pathlist != NIL)
4550  {
4551  Path *cheapest_partial_path;
4552 
4553  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4554 
4555  /*
4556  * If cheapest partial path doesn't need a sort, this is redundant
4557  * with what's already been tried.
4558  */
4560  cheapest_partial_path->pathkeys))
4561  {
4562  Path *path;
4563  double total_groups;
4564 
4565  path = (Path *) create_sort_path(root,
4566  ordered_rel,
4567  cheapest_partial_path,
4568  root->sort_pathkeys,
4569  limit_tuples);
4570 
4571  total_groups = cheapest_partial_path->rows *
4572  cheapest_partial_path->parallel_workers;
4573  path = (Path *)
4574  create_gather_merge_path(root, ordered_rel,
4575  path,
4576  path->pathtarget,
4577  root->sort_pathkeys, NULL,
4578  &total_groups);
4579 
4580  /* Add projection step if needed */
4581  if (path->pathtarget != target)
4582  path = apply_projection_to_path(root, ordered_rel,
4583  path, target);
4584 
4585  add_path(ordered_rel, path);
4586  }
4587 
4588  /*
4589  * Consider incremental sort with a gather merge on partial paths.
4590  *
4591  * We can also skip the entire loop when we only have a single-item
4592  * sort_pathkeys because then we can't possibly have a presorted
4593  * prefix of the list without having the list be fully sorted.
4594  */
4596  {
4597  ListCell *lc;
4598 
4599  foreach(lc, input_rel->partial_pathlist)
4600  {
4601  Path *input_path = (Path *) lfirst(lc);
4602  Path *sorted_path;
4603  bool is_sorted;
4604  int presorted_keys;
4605  double total_groups;
4606 
4607  /*
4608  * We don't care if this is the cheapest partial path - we
4609  * can't simply skip it, because it may be partially sorted in
4610  * which case we want to consider adding incremental sort
4611  * (instead of full sort, which is what happens above).
4612  */
4613 
4614  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4615  input_path->pathkeys,
4616  &presorted_keys);
4617 
4618  /* No point in adding incremental sort on fully sorted paths. */
4619  if (is_sorted)
4620  continue;
4621 
4622  if (presorted_keys == 0)
4623  continue;
4624 
4625  /* Since we have presorted keys, consider incremental sort. */
4626  sorted_path = (Path *) create_incremental_sort_path(root,
4627  ordered_rel,
4628  input_path,
4629  root->sort_pathkeys,
4630  presorted_keys,
4631  limit_tuples);
4632  total_groups = input_path->rows *
4633  input_path->parallel_workers;
4634  sorted_path = (Path *)
4635  create_gather_merge_path(root, ordered_rel,
4636  sorted_path,
4637  sorted_path->pathtarget,
4638  root->sort_pathkeys, NULL,
4639  &total_groups);
4640 
4641  /* Add projection step if needed */
4642  if (sorted_path->pathtarget != target)
4643  sorted_path = apply_projection_to_path(root, ordered_rel,
4644  sorted_path, target);
4645 
4646  add_path(ordered_rel, sorted_path);
4647  }
4648  }
4649  }
4650 
4651  /*
4652  * If there is an FDW that's responsible for all baserels of the query,
4653  * let it consider adding ForeignPaths.
4654  */
4655  if (ordered_rel->fdwroutine &&
4656  ordered_rel->fdwroutine->GetForeignUpperPaths)
4657  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
4658  input_rel, ordered_rel,
4659  NULL);
4660 
4661  /* Let extensions possibly add some more paths */
4663  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
4664  input_rel, ordered_rel, NULL);
4665 
4666  /*
4667  * No need to bother with set_cheapest here; grouping_planner does not
4668  * need us to do it.
4669  */
4670  Assert(ordered_rel->pathlist != NIL);
4671 
4672  return ordered_rel;
4673 }
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:1175
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:728
int parallel_workers
Definition: pathnodes.h:1181
List * partial_pathlist
Definition: pathnodes.h:692
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:729
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:1207
struct Path * cheapest_total_path
Definition: pathnodes.h:694
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:731
List * sort_pathkeys
Definition: pathnodes.h:298
Oid serverid
Definition: pathnodes.h:727
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:1188
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1184
static int list_length(const List *l)
Definition: pg_list.h:149
bool consider_parallel
Definition: pathnodes.h:684
List * pathlist
Definition: pathnodes.h:690

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

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

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

6334 {
6335  Query *parse = root->parse;
6336  RelOptInfo *partially_grouped_rel;
6337  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
6338  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6339  Path *cheapest_partial_path = NULL;
6340  Path *cheapest_total_path = NULL;
6341  double dNumPartialGroups = 0;
6342  double dNumPartialPartialGroups = 0;
6343  ListCell *lc;
6344  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6345  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6346 
6347  /*
6348  * Consider whether we should generate partially aggregated non-partial
6349  * paths. We can only do this if we have a non-partial path, and only if
6350  * the parent of the input rel is performing partial partitionwise
6351  * aggregation. (Note that extra->patype is the type of partitionwise
6352  * aggregation being used at the parent level, not this level.)
6353  */
6354  if (input_rel->pathlist != NIL &&
6356  cheapest_total_path = input_rel->cheapest_total_path;
6357 
6358  /*
6359  * If parallelism is possible for grouped_rel, then we should consider
6360  * generating partially-grouped partial paths. However, if the input rel
6361  * has no partial paths, then we can't.
6362  */
6363  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
6364  cheapest_partial_path = linitial(input_rel->partial_pathlist);
6365 
6366  /*
6367  * If we can't partially aggregate partial paths, and we can't partially
6368  * aggregate non-partial paths, then don't bother creating the new
6369  * RelOptInfo at all, unless the caller specified force_rel_creation.
6370  */
6371  if (cheapest_total_path == NULL &&
6372  cheapest_partial_path == NULL &&
6373  !force_rel_creation)
6374  return NULL;
6375 
6376  /*
6377  * Build a new upper relation to represent the result of partially
6378  * aggregating the rows from the input relation.
6379  */
6380  partially_grouped_rel = fetch_upper_rel(root,
6382  grouped_rel->relids);
6383  partially_grouped_rel->consider_parallel =
6384  grouped_rel->consider_parallel;
6385  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
6386  partially_grouped_rel->serverid = grouped_rel->serverid;
6387  partially_grouped_rel->userid = grouped_rel->userid;
6388  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
6389  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
6390 
6391  /*
6392  * Build target list for partial aggregate paths. These paths cannot just
6393  * emit the same tlist as regular aggregate paths, because (1) we must
6394  * include Vars and Aggrefs needed in HAVING, which might not appear in
6395  * the result tlist, and (2) the Aggrefs must be set in partial mode.
6396  */
6397  partially_grouped_rel->reltarget =
6398  make_partial_grouping_target(root, grouped_rel->reltarget,
6399  extra->havingQual);
6400 
6401  if (!extra->partial_costs_set)
6402  {
6403  /*
6404  * Collect statistics about aggregates for estimating costs of
6405  * performing aggregation in parallel.
6406  */
6407  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
6408  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
6409  if (parse->hasAggs)
6410  {
6411  /* partial phase */
6413  agg_partial_costs);
6414 
6415  /* final phase */
6417  agg_final_costs);
6418  }
6419 
6420  extra->partial_costs_set = true;
6421  }
6422 
6423  /* Estimate number of partial groups. */
6424  if (cheapest_total_path != NULL)
6425  dNumPartialGroups =
6426  get_number_of_groups(root,
6427  cheapest_total_path->rows,
6428  gd,
6429  extra->targetList);
6430  if (cheapest_partial_path != NULL)
6431  dNumPartialPartialGroups =
6432  get_number_of_groups(root,
6433  cheapest_partial_path->rows,
6434  gd,
6435  extra->targetList);
6436 
6437  if (can_sort && cheapest_total_path != NULL)
6438  {
6439  /* This should have been checked previously */
6440  Assert(parse->hasAggs || parse->groupClause);
6441 
6442  /*
6443  * Use any available suitably-sorted path as input, and also consider
6444  * sorting the cheapest partial path.
6445  */
6446  foreach(lc, input_rel->pathlist)
6447  {
6448  Path *path = (Path *) lfirst(lc);
6449  bool is_sorted;
6450 
6451  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6452  path->pathkeys);
6453  if (path == cheapest_total_path || is_sorted)
6454  {
6455  /* Sort the cheapest partial path, if it isn't already */
6456  if (!is_sorted)
6457  path = (Path *) create_sort_path(root,
6458  partially_grouped_rel,
6459  path,
6460  root->group_pathkeys,
6461  -1.0);
6462 
6463  if (parse->hasAggs)
6464  add_path(partially_grouped_rel, (Path *)
6465  create_agg_path(root,
6466  partially_grouped_rel,
6467  path,
6468  partially_grouped_rel->reltarget,
6469  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6471  parse->groupClause,
6472  NIL,
6473  agg_partial_costs,
6474  dNumPartialGroups));
6475  else
6476  add_path(partially_grouped_rel, (Path *)
6477  create_group_path(root,
6478  partially_grouped_rel,
6479  path,
6480  parse->groupClause,
6481  NIL,
6482  dNumPartialGroups));
6483  }
6484  }
6485 
6486  /*
6487  * Consider incremental sort on all partial paths, if enabled.
6488  *
6489  * We can also skip the entire loop when we only have a single-item
6490  * group_pathkeys because then we can't possibly have a presorted
6491  * prefix of the list without having the list be fully sorted.
6492  */
6494  {
6495  foreach(lc, input_rel->pathlist)
6496  {
6497  Path *path = (Path *) lfirst(lc);
6498  bool is_sorted;
6499  int presorted_keys;
6500 
6501  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6502  path->pathkeys,
6503  &presorted_keys);
6504 
6505  /* Ignore already sorted paths */
6506  if (is_sorted)
6507  continue;
6508 
6509  if (presorted_keys == 0)
6510  continue;
6511 
6512  /* Since we have presorted keys, consider incremental sort. */
6513  path = (Path *) create_incremental_sort_path(root,
6514  partially_grouped_rel,
6515  path,
6516  root->group_pathkeys,
6517  presorted_keys,
6518  -1.0);
6519 
6520  if (parse->hasAggs)
6521  add_path(partially_grouped_rel, (Path *)
6522  create_agg_path(root,
6523  partially_grouped_rel,
6524  path,
6525  partially_grouped_rel->reltarget,
6526  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6528  parse->groupClause,
6529  NIL,
6530  agg_partial_costs,
6531  dNumPartialGroups));
6532  else
6533  add_path(partially_grouped_rel, (Path *)
6534  create_group_path(root,
6535  partially_grouped_rel,
6536  path,
6537  parse->groupClause,
6538  NIL,
6539  dNumPartialGroups));
6540  }
6541  }
6542 
6543  }
6544 
6545  if (can_sort && cheapest_partial_path != NULL)
6546  {
6547  /* Similar to above logic, but for partial paths. */
6548  foreach(lc, input_rel->partial_pathlist)
6549  {
6550  Path *path = (Path *) lfirst(lc);
6551  Path *path_original = path;
6552  bool is_sorted;
6553  int presorted_keys;
6554 
6555  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6556  path->pathkeys,
6557  &presorted_keys);
6558 
6559  if (path == cheapest_partial_path || is_sorted)
6560  {
6561  /* Sort the cheapest partial path, if it isn't already */
6562  if (!is_sorted)
6563  path = (Path *) create_sort_path(root,
6564  partially_grouped_rel,
6565  path,
6566  root->group_pathkeys,
6567  -1.0);
6568 
6569  if (parse->hasAggs)
6570  add_partial_path(partially_grouped_rel, (Path *)
6571  create_agg_path(root,
6572  partially_grouped_rel,
6573  path,
6574  partially_grouped_rel->reltarget,
6575  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6577  parse->groupClause,
6578  NIL,
6579  agg_partial_costs,
6580  dNumPartialPartialGroups));
6581  else
6582  add_partial_path(partially_grouped_rel, (Path *)
6583  create_group_path(root,
6584  partially_grouped_rel,
6585  path,
6586  parse->groupClause,
6587  NIL,
6588  dNumPartialPartialGroups));
6589  }
6590 
6591  /*
6592  * Now we may consider incremental sort on this path, but only
6593  * when the path is not already sorted and when incremental sort
6594  * is enabled.
6595  */
6596  if (is_sorted || !enable_incremental_sort)
6597  continue;
6598 
6599  /* Restore the input path (we might have added Sort on top). */
6600  path = path_original;
6601 
6602  /* no shared prefix, not point in building incremental sort */
6603  if (presorted_keys == 0)
6604  continue;
6605 
6606  /*
6607  * We should have already excluded pathkeys of length 1 because
6608  * then presorted_keys > 0 would imply is_sorted was true.
6609  */
6610  Assert(list_length(root->group_pathkeys) != 1);
6611 
6612  path = (Path *) create_incremental_sort_path(root,
6613  partially_grouped_rel,
6614  path,
6615  root->group_pathkeys,
6616  presorted_keys,
6617  -1.0);
6618 
6619  if (parse->hasAggs)
6620  add_partial_path(partially_grouped_rel, (Path *)
6621  create_agg_path(root,
6622  partially_grouped_rel,
6623  path,
6624  partially_grouped_rel->reltarget,
6625  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6627  parse->groupClause,
6628  NIL,
6629  agg_partial_costs,
6630  dNumPartialPartialGroups));
6631  else
6632  add_partial_path(partially_grouped_rel, (Path *)
6633  create_group_path(root,
6634  partially_grouped_rel,
6635  path,
6636  parse->groupClause,
6637  NIL,
6638  dNumPartialPartialGroups));
6639  }
6640  }
6641 
6642  /*
6643  * Add a partially-grouped HashAgg Path where possible
6644  */
6645  if (can_hash && cheapest_total_path != NULL)
6646  {
6647  /* Checked above */
6648  Assert(parse->hasAggs || parse->groupClause);
6649 
6650  add_path(partially_grouped_rel, (Path *)
6651  create_agg_path(root,
6652  partially_grouped_rel,
6653  cheapest_total_path,
6654  partially_grouped_rel->reltarget,
6655  AGG_HASHED,
6657  parse->groupClause,
6658  NIL,
6659  agg_partial_costs,
6660  dNumPartialGroups));
6661  }
6662 
6663  /*
6664  * Now add a partially-grouped HashAgg partial Path where possible
6665  */
6666  if (can_hash && cheapest_partial_path != NULL)
6667  {
6668  add_partial_path(partially_grouped_rel, (Path *)
6669  create_agg_path(root,
6670  partially_grouped_rel,
6671  cheapest_partial_path,
6672  partially_grouped_rel->reltarget,
6673  AGG_HASHED,
6675  parse->groupClause,
6676  NIL,
6677  agg_partial_costs,
6678  dNumPartialPartialGroups));
6679  }
6680 
6681  /*
6682  * If there is an FDW that's responsible for all baserels of the query,
6683  * let it consider adding partially grouped ForeignPaths.
6684  */
6685  if (partially_grouped_rel->fdwroutine &&
6686  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
6687  {
6688  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
6689 
6690  fdwroutine->GetForeignUpperPaths(root,
6692  input_rel, partially_grouped_rel,
6693  extra);
6694  }
6695 
6696  return partially_grouped_rel;
6697 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
List * group_pathkeys
Definition: pathnodes.h:295
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
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:673
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3152
Oid userid
Definition: pathnodes.h:728
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:2581
bool hasAggs
Definition: parsenodes.h:133
PartitionwiseAggregateType patype
Definition: pathnodes.h:2588
List * partial_pathlist
Definition: pathnodes.h:692
#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:729
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:2541
#define linitial(l)
Definition: pg_list.h:174
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1207
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:694
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:731
Relids relids
Definition: pathnodes.h:676
Oid serverid
Definition: pathnodes.h:727
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:2542
List * pathkeys
Definition: pathnodes.h:1188
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1184
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:4791
static int list_length(const List *l)
Definition: pg_list.h:149
bool consider_parallel
Definition: pathnodes.h:684
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:690
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:2582
struct PathTarget * reltarget
Definition: pathnodes.h:687
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

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

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

Referenced by create_ordinary_grouping_paths().

7084 {
7085  int nparts = input_rel->nparts;
7086  int cnt_parts;
7087  List *grouped_live_children = NIL;
7088  List *partially_grouped_live_children = NIL;
7089  PathTarget *target = grouped_rel->reltarget;
7090  bool partial_grouping_valid = true;
7091 
7094  partially_grouped_rel != NULL);
7095 
7096  /* Add paths for partitionwise aggregation/grouping. */
7097  for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
7098  {
7099  RelOptInfo *child_input_rel = input_rel->part_rels[cnt_parts];
7100  PathTarget *child_target = copy_pathtarget(target);
7101  AppendRelInfo **appinfos;
7102  int nappinfos;
7103  GroupPathExtraData child_extra;
7104  RelOptInfo *child_grouped_rel;
7105  RelOptInfo *child_partially_grouped_rel;
7106 
7107  /* Pruned or dummy children can be ignored. */
7108  if (child_input_rel == NULL || IS_DUMMY_REL(child_input_rel))
7109  continue;
7110 
7111  /*
7112  * Copy the given "extra" structure as is and then override the
7113  * members specific to this child.
7114  */
7115  memcpy(&child_extra, extra, sizeof(child_extra));
7116 
7117  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7118  &nappinfos);
7119 
7120  child_target->exprs = (List *)
7122  (Node *) target->exprs,
7123  nappinfos, appinfos);
7124 
7125  /* Translate havingQual and targetList. */
7126  child_extra.havingQual = (Node *)
7128  extra->havingQual,
7129  nappinfos, appinfos);
7130  child_extra.targetList = (List *)
7132  (Node *) extra->targetList,
7133  nappinfos, appinfos);
7134 
7135  /*
7136  * extra->patype was the value computed for our parent rel; patype is
7137  * the value for this relation. For the child, our value is its
7138  * parent rel's value.
7139  */
7140  child_extra.patype = patype;
7141 
7142  /*
7143  * Create grouping relation to hold fully aggregated grouping and/or
7144  * aggregation paths for the child.
7145  */
7146  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7147  child_target,
7148  extra->target_parallel_safe,
7149  child_extra.havingQual);
7150 
7151  /* Create grouping paths for this child relation. */
7152  create_ordinary_grouping_paths(root, child_input_rel,
7153  child_grouped_rel,
7154  agg_costs, gd, &child_extra,
7155  &child_partially_grouped_rel);
7156 
7157  if (child_partially_grouped_rel)
7158  {
7159  partially_grouped_live_children =
7160  lappend(partially_grouped_live_children,
7161  child_partially_grouped_rel);
7162  }
7163  else
7164  partial_grouping_valid = false;
7165 
7166  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7167  {
7168  set_cheapest(child_grouped_rel);
7169  grouped_live_children = lappend(grouped_live_children,
7170  child_grouped_rel);
7171  }
7172 
7173  pfree(appinfos);
7174  }
7175 
7176  /*
7177  * Try to create append paths for partially grouped children. For full
7178  * partitionwise aggregation, we might have paths in the partial_pathlist
7179  * if parallel aggregation is possible. For partial partitionwise
7180  * aggregation, we may have paths in both pathlist and partial_pathlist.
7181  *
7182  * NB: We must have a partially grouped path for every child in order to
7183  * generate a partially grouped path for this relation.
7184  */
7185  if (partially_grouped_rel && partial_grouping_valid)
7186  {
7187  Assert(partially_grouped_live_children != NIL);
7188 
7189  add_paths_to_append_rel(root, partially_grouped_rel,
7190  partially_grouped_live_children);
7191 
7192  /*
7193  * We need call set_cheapest, since the finalization step will use the
7194  * cheapest path from the rel.
7195  */
7196  if (partially_grouped_rel->pathlist)
7197  set_cheapest(partially_grouped_rel);
7198  }
7199 
7200  /* If possible, create append paths for fully grouped children. */
7201  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7202  {
7203  Assert(grouped_live_children != NIL);
7204 
7205  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7206  }
7207 }
#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:3387
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1285
Definition: nodes.h:539
PartitionwiseAggregateType patype
Definition: pathnodes.h:2588
void pfree(void *pointer)
Definition: mcxt.c:1169
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1458
int nparts
Definition: pathnodes.h:756
Relids relids
Definition: pathnodes.h:676
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:1102
#define Assert(condition)
Definition: c.h:804
struct RelOptInfo ** part_rels
Definition: pathnodes.h:763
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:3525
List * pathlist
Definition: pathnodes.h:690
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:687
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 4026 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().

4033 {
4034  RelOptInfo *window_rel;
4035  ListCell *lc;
4036 
4037  /* For now, do all work in the (WINDOW, NULL) upperrel */
4038  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4039 
4040  /*
4041  * If the input relation is not parallel-safe, then the window relation
4042  * can't be parallel-safe, either. Otherwise, we need to examine the
4043  * target list and active windows for non-parallel-safe constructs.
4044  */
4045  if (input_rel->consider_parallel && output_target_parallel_safe &&
4046  is_parallel_safe(root, (Node *) activeWindows))
4047  window_rel->consider_parallel = true;
4048 
4049  /*
4050  * If the input rel belongs to a single FDW, so does the window rel.
4051  */
4052  window_rel->serverid = input_rel->serverid;
4053  window_rel->userid = input_rel->userid;
4054  window_rel->useridiscurrent = input_rel->useridiscurrent;
4055  window_rel->fdwroutine = input_rel->fdwroutine;
4056 
4057  /*
4058  * Consider computing window functions starting from the existing
4059  * cheapest-total path (which will likely require a sort) as well as any
4060  * existing paths that satisfy or partially satisfy root->window_pathkeys.
4061  */
4062  foreach(lc, input_rel->pathlist)
4063  {
4064  Path *path = (Path *) lfirst(lc);
4065  int presorted_keys;
4066 
4067  if (path == input_rel->cheapest_total_path ||
4069  &presorted_keys) ||
4070  presorted_keys > 0)
4072  window_rel,
4073  path,
4074  input_target,
4075  output_target,
4076  wflists,
4077  activeWindows);
4078  }
4079 
4080  /*
4081  * If there is an FDW that's responsible for all baserels of the query,
4082  * let it consider adding ForeignPaths.
4083  */
4084  if (window_rel->fdwroutine &&
4085  window_rel->fdwroutine->GetForeignUpperPaths)
4086  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4087  input_rel, window_rel,
4088  NULL);
4089 
4090  /* Let extensions possibly add some more paths */
4092  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4093  input_rel, window_rel, NULL);
4094 
4095  /* Now choose the best path(s) */
4096  set_cheapest(window_rel);
4097 
4098  return window_rel;
4099 }
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:4113
Oid userid
Definition: pathnodes.h:728
Definition: nodes.h:539
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:729
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:638
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1207
struct Path * cheapest_total_path
Definition: pathnodes.h:694
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:731
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:727
List * window_pathkeys
Definition: pathnodes.h:296
List * pathkeys
Definition: pathnodes.h:1188
#define lfirst(lc)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:684
List * pathlist
Definition: pathnodes.h:690

◆ expression_planner()

Expr* expression_planner ( Expr expr)

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

5654 {
5655  Node *result;
5656 
5657  /*
5658  * Convert named-argument function calls, insert default arguments and
5659  * simplify constant subexprs
5660  */
5661  result = eval_const_expressions(NULL, (Node *) expr);
5662 
5663  /* Fill in opfuncid values if missing */
5664  fix_opfuncids(result);
5665 
5666  return (Expr *) result;
5667 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:539
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2093

◆ expression_planner_with_deps()

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

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

5683 {
5684  Node *result;
5685  PlannerGlobal glob;
5686  PlannerInfo root;
5687 
5688  /* Make up dummy planner state so we can use setrefs machinery */
5689  MemSet(&glob, 0, sizeof(glob));
5690  glob.type = T_PlannerGlobal;
5691  glob.relationOids = NIL;
5692  glob.invalItems = NIL;
5693 
5694  MemSet(&root, 0, sizeof(root));
5695  root.type = T_PlannerInfo;
5696  root.glob = &glob;
5697 
5698  /*
5699  * Convert named-argument function calls, insert default arguments and
5700  * simplify constant subexprs. Collect identities of inlined functions
5701  * and elided domains, too.
5702  */
5703  result = eval_const_expressions(&root, (Node *) expr);
5704 
5705  /* Fill in opfuncid values if missing */
5706  fix_opfuncids(result);
5707 
5708  /*
5709  * Now walk the finished expression to find anything else we ought to
5710  * record as an expression dependency.
5711  */
5712  (void) extract_query_dependencies_walker(result, &root);
5713 
5714  *relationOids = glob.relationOids;
5715  *invalItems = glob.invalItems;
5716 
5717  return (Expr *) result;
5718 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:539
#define MemSet(start, val, len)
Definition: c.h:1008
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2093
PlannerGlobal * glob
Definition: pathnodes.h:163
List * invalItems
Definition: pathnodes.h:111
NodeTag type
Definition: pathnodes.h:159
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3069
NodeTag type
Definition: pathnodes.h:91
List * relationOids
Definition: pathnodes.h:109

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

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

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

6714 {
6715  ListCell *lc;
6716  Path *cheapest_partial_path;
6717 
6718  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
6719  generate_useful_gather_paths(root, rel, true);
6720 
6721  /* Try cheapest partial path + explicit Sort + Gather Merge. */
6722  cheapest_partial_path = linitial(rel->partial_pathlist);
6724  cheapest_partial_path->pathkeys))
6725  {
6726  Path *path;
6727  double total_groups;
6728 
6729  total_groups =
6730  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
6731  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
6732  root->group_pathkeys,
6733  -1.0);
6734  path = (Path *)
6736  rel,
6737  path,
6738  rel->reltarget,
6739  root->group_pathkeys,
6740  NULL,
6741  &total_groups);
6742 
6743  add_path(rel, path);
6744  }
6745 
6746  /*
6747  * Consider incremental sort on all partial paths, if enabled.
6748  *
6749  * We can also skip the entire loop when we only have a single-item
6750  * group_pathkeys because then we can't possibly have a presorted prefix
6751  * of the list without having the list be fully sorted.
6752  */
6754  return;
6755 
6756  /* also consider incremental sort on partial paths, if enabled */
6757  foreach(lc, rel->partial_pathlist)
6758  {
6759  Path *path = (Path *) lfirst(lc);
6760  bool is_sorted;
6761  int presorted_keys;
6762  double total_groups;
6763 
6764  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6765  path->pathkeys,
6766  &presorted_keys);
6767 
6768  if (is_sorted)
6769  continue;
6770 
6771  if (presorted_keys == 0)
6772  continue;
6773 
6774  path = (Path *) create_incremental_sort_path(root,
6775  rel,
6776  path,
6777  root->group_pathkeys,
6778  presorted_keys,
6779  -1.0);
6780 
6781  path = (Path *)
6783  rel,
6784  path,
6785  rel->reltarget,
6786  root->group_pathkeys,
6787  NULL,
6788  &total_groups);
6789 
6790  add_path(rel, path);
6791  }
6792 }
List * group_pathkeys
Definition: pathnodes.h:295
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:1181
List * partial_pathlist
Definition: pathnodes.h:692
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:1188
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1184
static int list_length(const List *l)
Definition: pg_list.h:149
struct PathTarget * reltarget
Definition: pathnodes.h:687

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

5495 {
5496  Path *best_path = rel->cheapest_total_path;
5497  ListCell *l;
5498 
5499  /* If all tuples will be retrieved, just return the cheapest-total path */
5500  if (tuple_fraction <= 0.0)
5501  return best_path;
5502 
5503  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5504  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5505  tuple_fraction /= best_path->rows;
5506 
5507  foreach(l, rel->pathlist)
5508  {
5509  Path *path = (Path *) lfirst(l);
5510 
5511  if (path == rel->cheapest_total_path ||
5512  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5513  continue;
5514 
5515  best_path = path;
5516  }
5517 
5518  return best_path;
5519 }
struct Path * cheapest_total_path
Definition: pathnodes.h:694
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1184
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: pathnodes.h:690

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

3156 {
3157  Query *parse = root->parse;
3158  double dNumGroups;
3159 
3160  if (parse->groupClause)
3161  {
3162  List *groupExprs;
3163 
3164  if (parse->groupingSets)
3165  {
3166  /* Add up the estimates for each grouping set */
3167  ListCell *lc;
3168  ListCell *lc2;
3169 
3170  Assert(gd); /* keep Coverity happy */
3171 
3172  dNumGroups = 0;
3173 
3174  foreach(lc, gd->rollups)
3175  {
3176  RollupData *rollup = lfirst_node(RollupData, lc);
3177  ListCell *lc;
3178 
3179  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3180  target_list);
3181 
3182  rollup->numGroups = 0.0;
3183 
3184  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3185  {
3186  List *gset = (List *) lfirst(lc);
3188  double numGroups = estimate_num_groups(root,
3189  groupExprs,
3190  path_rows,
3191  &gset,
3192  NULL);
3193 
3194  gs->numGroups = numGroups;
3195  rollup->numGroups += numGroups;
3196  }
3197 
3198  dNumGroups += rollup->numGroups;
3199  }
3200 
3201  if (gd->hash_sets_idx)
3202  {
3203  ListCell *lc;
3204 
3205  gd->dNumHashGroups = 0;
3206 
3207  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3208  target_list);
3209 
3210  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3211  {
3212  List *gset = (List *) lfirst(lc);
3214  double numGroups = estimate_num_groups(root,
3215  groupExprs,
3216  path_rows,
3217  &gset,
3218  NULL);
3219 
3220  gs->numGroups = numGroups;
3221  gd->dNumHashGroups += numGroups;
3222  }
3223 
3224  dNumGroups += gd->dNumHashGroups;
3225  }
3226  }
3227  else
3228  {
3229  /* Plain GROUP BY */
3230  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3231  target_list);
3232 
3233  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3234  NULL, NULL);
3235  }
3236  }
3237  else if (parse->groupingSets)
3238  {
3239  /* Empty grouping sets ... one result row for each one */
3240  dNumGroups = list_length(parse->groupingSets);
3241  }
3242  else if (parse->hasAggs || root->hasHavingQual)
3243  {
3244  /* Plain aggregation, one result row */
3245  dNumGroups = 1;
3246  }
3247  else
3248  {
3249  /* Not grouping */
3250  dNumGroups = 1;
3251  }
3252 
3253  return dNumGroups;
3254 }
Query * parse
Definition: pathnodes.h:161
List * groupClause
Definition: pathnodes.h:1782
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
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
double numGroups
Definition: pathnodes.h:1785
#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
List * groupClause
Definition: parsenodes.h:158
double numGroups
Definition: pathnodes.h:1776
bool hasHavingQual
Definition: pathnodes.h:347
Definition: pg_list.h:50
List * gsets_data
Definition: pathnodes.h:1784
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665
List * gsets
Definition: pathnodes.h:1783

◆ group_by_has_partkey()

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

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

7219 {
7220  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7221  int cnt = 0;
7222  int partnatts;
7223 
7224  /* Input relation should be partitioned. */
7225  Assert(input_rel->part_scheme);
7226 
7227  /* Rule out early, if there are no partition keys present. */
7228  if (!input_rel->partexprs)
7229  return false;
7230 
7231  partnatts = input_rel->part_scheme->partnatts;
7232 
7233  for (cnt = 0; cnt < partnatts; cnt++)
7234  {
7235  List *partexprs = input_rel->partexprs[cnt];
7236  ListCell *lc;
7237  bool found = false;
7238 
7239  foreach(lc, partexprs)
7240  {
7241  Expr *partexpr = lfirst(lc);
7242 
7243  if (list_member(groupexprs, partexpr))
7244  {
7245  found = true;
7246  break;
7247  }
7248  }
7249 
7250  /*
7251  * If none of the partition key expressions match with any of the
7252  * GROUP BY expression, return false.
7253  */
7254  if (!found)
7255  return false;
7256  }
7257 
7258  return true;
7259 }
List ** partexprs
Definition: pathnodes.h:766
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:755
Definition: pg_list.h:50

◆ grouping_planner()

static void grouping_planner ( PlannerInfo root,
double  tuple_fraction 
)
static

Definition at line 1227 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_WINDOW, RelOptInfo::userid, RelOptInfo::useridiscurrent, Query::windowClause, and Query::withCheckOptions.

Referenced by subquery_planner().

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

◆ is_degenerate_grouping()

static bool is_degenerate_grouping ( PlannerInfo root)
static

Definition at line 3440 of file planner.c.

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

Referenced by create_grouping_paths().

3441 {
3442  Query *parse = root->parse;
3443 
3444  return (root->hasHavingQual || parse->groupingSets) &&
3445  !parse->hasAggs && parse->groupClause == NIL;
3446 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
bool hasAggs
Definition: parsenodes.h:133
List * groupingSets
Definition: parsenodes.h:161
List * groupClause
Definition: parsenodes.h:158
bool hasHavingQual
Definition: pathnodes.h:347
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:665

◆ limit_needed()

bool limit_needed ( Query parse)

Definition at line 2481 of file planner.c.

References DatumGetInt64, IsA, Query::limitCount, and Query::limitOffset.

Referenced by grouping_planner(), and set_rel_consider_parallel().

2482 {
2483  Node *node;
2484 
2485  node = parse->limitCount;
2486  if (node)
2487  {
2488  if (IsA(node, Const))
2489  {
2490  /* NULL indicates LIMIT ALL, ie, no limit */
2491  if (!((Const *) node)->constisnull)
2492  return true; /* LIMIT with a constant value */
2493  }
2494  else
2495  return true; /* non-constant LIMIT */
2496  }
2497 
2498  node = parse->limitOffset;
2499  if (node)
2500  {
2501  if (IsA(node, Const))
2502  {
2503  /* Treat NULL as no offset; the executor would too */
2504  if (!((Const *) node)->constisnull)
2505  {
2506  int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2507 
2508  if (offset != 0)
2509  return true; /* OFFSET with a nonzero value */
2510  }
2511  }
2512  else
2513  return true; /* non-constant OFFSET */
2514  }
2515 
2516  return false; /* don't need a Limit plan node */
2517 }