PostgreSQL Source Code  git master
planner.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/htup_details.h"
#include "access/parallel.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "jit/jit.h"
#include "lib/bipartite_match.h"
#include "lib/knapsack.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.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 "optimizer/var.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/parse_agg.h"
#include "rewrite/rewriteManip.h"
#include "storage/dsm_impl.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/lsyscache.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
 

Macros

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

Functions

static Nodepreprocess_expression (PlannerInfo *root, Node *expr, int kind)
 
static void preprocess_qual_conditions (PlannerInfo *root, Node *jtnode)
 
static void inheritance_planner (PlannerInfo *root)
 
static void grouping_planner (PlannerInfo *root, bool inheritance_update, double tuple_fraction)
 
static grouping_sets_datapreprocess_grouping_sets (PlannerInfo *root)
 
static Listremap_to_groupclause_idx (List *groupClause, List *gsets, int *tleref_to_colnum_map)
 
static void preprocess_rowmarks (PlannerInfo *root)
 
static double preprocess_limit (PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
 
static bool limit_needed (Query *parse)
 
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 Size estimate_hashagg_tablesize (Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
 
static RelOptInfocreate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, const AggClauseCosts *agg_costs, grouping_sets_data *gd)
 
static bool is_degenerate_grouping (PlannerInfo *root)
 
static void create_degenerate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
 
static RelOptInfomake_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
 
static void create_ordinary_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
 
static void consider_groupingsets_paths (PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
 
static RelOptInfocreate_window_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, List *tlist, WindowFuncLists *wflists, List *activeWindows)
 
static void create_one_window_path (PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, List *tlist, WindowFuncLists *wflists, List *activeWindows)
 
static RelOptInfocreate_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel)
 
static RelOptInfocreate_ordered_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
 
static PathTargetmake_group_input_target (PlannerInfo *root, PathTarget *final_target)
 
static PathTargetmake_partial_grouping_target (PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
 
static Listpostprocess_setop_tlist (List *new_tlist, List *orig_tlist)
 
static Listselect_active_windows (PlannerInfo *root, WindowFuncLists *wflists)
 
static PathTargetmake_window_input_target (PlannerInfo *root, PathTarget *final_target, List *activeWindows)
 
static Listmake_pathkeys_for_window (PlannerInfo *root, WindowClause *wc, List *tlist)
 
static PathTargetmake_sort_input_target (PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
 
static void adjust_paths_for_srfs (PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
 
static void add_paths_to_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, double dNumGroups, GroupPathExtraData *extra)
 
static RelOptInfocreate_partial_grouping_paths (PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *input_rel, grouping_sets_data *gd, GroupPathExtraData *extra, bool force_rel_creation)
 
static void gather_grouping_paths (PlannerInfo *root, RelOptInfo *rel)
 
static bool can_partial_agg (PlannerInfo *root, const AggClauseCosts *agg_costs)
 
static void apply_scanjoin_target_to_paths (PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
 
static void create_partitionwise_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, PartitionwiseAggregateType patype, GroupPathExtraData *extra)
 
static bool group_by_has_partkey (RelOptInfo *input_rel, List *targetList, List *groupClause)
 
PlannedStmtplanner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannedStmtstandard_planner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannerInfosubquery_planner (PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
 
Exprpreprocess_phv_expression (PlannerInfo *root, Expr *expr)
 
bool is_dummy_plan (Plan *plan)
 
RowMarkType select_rowmark_type (RangeTblEntry *rte, LockClauseStrength strength)
 
void mark_partial_aggref (Aggref *agg, AggSplit aggsplit)
 
Pathget_cheapest_fractional_path (RelOptInfo *rel, double tuple_fraction)
 
Exprexpression_planner (Expr *expr)
 
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 82 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 85 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 81 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 83 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 75 of file planner.c.

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

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 77 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 78 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 86 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 87 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 76 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 79 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 80 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 6160 of file planner.c.

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

Referenced by create_ordinary_grouping_paths().

6166 {
6167  Query *parse = root->parse;
6168  Path *cheapest_path = input_rel->cheapest_total_path;
6169  ListCell *lc;
6170  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6171  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6172  List *havingQual = (List *) extra->havingQual;
6173  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6174 
6175  if (can_sort)
6176  {
6177  /*
6178  * Use any available suitably-sorted path as input, and also consider
6179  * sorting the cheapest-total path.
6180  */
6181  foreach(lc, input_rel->pathlist)
6182  {
6183  Path *path = (Path *) lfirst(lc);
6184  bool is_sorted;
6185 
6186  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6187  path->pathkeys);
6188  if (path == cheapest_path || is_sorted)
6189  {
6190  /* Sort the cheapest-total path if it isn't already sorted */
6191  if (!is_sorted)
6192  path = (Path *) create_sort_path(root,
6193  grouped_rel,
6194  path,
6195  root->group_pathkeys,
6196  -1.0);
6197 
6198  /* Now decide what to stick atop it */
6199  if (parse->groupingSets)
6200  {
6201  consider_groupingsets_paths(root, grouped_rel,
6202  path, true, can_hash,
6203  gd, agg_costs, dNumGroups);
6204  }
6205  else if (parse->hasAggs)
6206  {
6207  /*
6208  * We have aggregation, possibly with plain GROUP BY. Make
6209  * an AggPath.
6210  */
6211  add_path(grouped_rel, (Path *)
6212  create_agg_path(root,
6213  grouped_rel,
6214  path,
6215  grouped_rel->reltarget,
6216  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6218  parse->groupClause,
6219  havingQual,
6220  agg_costs,
6221  dNumGroups));
6222  }
6223  else if (parse->groupClause)
6224  {
6225  /*
6226  * We have GROUP BY without aggregation or grouping sets.
6227  * Make a GroupPath.
6228  */
6229  add_path(grouped_rel, (Path *)
6230  create_group_path(root,
6231  grouped_rel,
6232  path,
6233  parse->groupClause,
6234  havingQual,
6235  dNumGroups));
6236  }
6237  else
6238  {
6239  /* Other cases should have been handled above */
6240  Assert(false);
6241  }
6242  }
6243  }
6244 
6245  /*
6246  * Instead of operating directly on the input relation, we can
6247  * consider finalizing a partially aggregated path.
6248  */
6249  if (partially_grouped_rel != NULL)
6250  {
6251  foreach(lc, partially_grouped_rel->pathlist)
6252  {
6253  Path *path = (Path *) lfirst(lc);
6254 
6255  /*
6256  * Insert a Sort node, if required. But there's no point in
6257  * sorting anything but the cheapest path.
6258  */
6259  if (!pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
6260  {
6261  if (path != partially_grouped_rel->cheapest_total_path)
6262  continue;
6263  path = (Path *) create_sort_path(root,
6264  grouped_rel,
6265  path,
6266  root->group_pathkeys,
6267  -1.0);
6268  }
6269 
6270  if (parse->hasAggs)
6271  add_path(grouped_rel, (Path *)
6272  create_agg_path(root,
6273  grouped_rel,
6274  path,
6275  grouped_rel->reltarget,
6276  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6278  parse->groupClause,
6279  havingQual,
6280  agg_final_costs,
6281  dNumGroups));
6282  else
6283  add_path(grouped_rel, (Path *)
6284  create_group_path(root,
6285  grouped_rel,
6286  path,
6287  parse->groupClause,
6288  havingQual,
6289  dNumGroups));
6290  }
6291  }
6292  }
6293 
6294  if (can_hash)
6295  {
6296  Size hashaggtablesize;
6297 
6298  if (parse->groupingSets)
6299  {
6300  /*
6301  * Try for a hash-only groupingsets path over unsorted input.
6302  */
6303  consider_groupingsets_paths(root, grouped_rel,
6304  cheapest_path, false, true,
6305  gd, agg_costs, dNumGroups);
6306  }
6307  else
6308  {
6309  hashaggtablesize = estimate_hashagg_tablesize(cheapest_path,
6310  agg_costs,
6311  dNumGroups);
6312 
6313  /*
6314  * Provided that the estimated size of the hashtable does not
6315  * exceed work_mem, we'll generate a HashAgg Path, although if we
6316  * were unable to sort above, then we'd better generate a Path, so
6317  * that we at least have one.
6318  */
6319  if (hashaggtablesize < work_mem * 1024L ||
6320  grouped_rel->pathlist == NIL)
6321  {
6322  /*
6323  * We just need an Agg over the cheapest-total input path,
6324  * since input order won't matter.
6325  */
6326  add_path(grouped_rel, (Path *)
6327  create_agg_path(root, grouped_rel,
6328  cheapest_path,
6329  grouped_rel->reltarget,
6330  AGG_HASHED,
6332  parse->groupClause,
6333  havingQual,
6334  agg_costs,
6335  dNumGroups));
6336  }
6337  }
6338 
6339  /*
6340  * Generate a Finalize HashAgg Path atop of the cheapest partially
6341  * grouped path, assuming there is one. Once again, we'll only do this
6342  * if it looks as though the hash table won't exceed work_mem.
6343  */
6344  if (partially_grouped_rel && partially_grouped_rel->pathlist)
6345  {
6346  Path *path = partially_grouped_rel->cheapest_total_path;
6347 
6348  hashaggtablesize = estimate_hashagg_tablesize(path,
6349  agg_final_costs,
6350  dNumGroups);
6351 
6352  if (hashaggtablesize < work_mem * 1024L)
6353  add_path(grouped_rel, (Path *)
6354  create_agg_path(root,
6355  grouped_rel,
6356  path,
6357  grouped_rel->reltarget,
6358  AGG_HASHED,
6360  parse->groupClause,
6361  havingQual,
6362  agg_final_costs,
6363  dNumGroups));
6364  }
6365  }
6366 
6367  /*
6368  * When partitionwise aggregate is used, we might have fully aggregated
6369  * paths in the partial pathlist, because add_paths_to_append_rel() will
6370  * consider a path for grouped_rel consisting of a Parallel Append of
6371  * non-partial paths from each child.
6372  */
6373  if (grouped_rel->partial_pathlist != NIL)
6374  gather_grouping_paths(root, grouped_rel);
6375 }
List * group_pathkeys
Definition: relation.h:276
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static void consider_groupingsets_paths(PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:4077
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6697
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
List * partial_pathlist
Definition: relation.h:628
#define GROUPING_CAN_USE_SORT
Definition: relation.h:2333
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:2786
struct Path * cheapest_total_path
Definition: relation.h:630
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3649
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
int work_mem
Definition: globals.c:122
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2631
List * pathkeys
Definition: relation.h:1092
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
#define GROUPING_CAN_USE_HASH
Definition: relation.h:2334
size_t Size
Definition: c.h:433
List * groupClause
Definition: parsenodes.h:148
List * pathlist
Definition: relation.h:626
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2675
AggClauseCosts agg_final_costs
Definition: relation.h:2374
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:623
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ adjust_paths_for_srfs()

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

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

5780 {
5781  ListCell *lc;
5782 
5783  Assert(list_length(targets) == list_length(targets_contain_srfs));
5784  Assert(!linitial_int(targets_contain_srfs));
5785 
5786  /* If no SRFs appear at this plan level, nothing to do */
5787  if (list_length(targets) == 1)
5788  return;
5789 
5790  /*
5791  * Stack SRF-evaluation nodes atop each path for the rel.
5792  *
5793  * In principle we should re-run set_cheapest() here to identify the
5794  * cheapest path, but it seems unlikely that adding the same tlist eval
5795  * costs to all the paths would change that, so we don't bother. Instead,
5796  * just assume that the cheapest-startup and cheapest-total paths remain
5797  * so. (There should be no parameterized paths anymore, so we needn't
5798  * worry about updating cheapest_parameterized_paths.)
5799  */
5800  foreach(lc, rel->pathlist)
5801  {
5802  Path *subpath = (Path *) lfirst(lc);
5803  Path *newpath = subpath;
5804  ListCell *lc1,
5805  *lc2;
5806 
5807  Assert(subpath->param_info == NULL);
5808  forboth(lc1, targets, lc2, targets_contain_srfs)
5809  {
5810  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5811  bool contains_srfs = (bool) lfirst_int(lc2);
5812 
5813  /* If this level doesn't contain SRFs, do regular projection */
5814  if (contains_srfs)
5815  newpath = (Path *) create_set_projection_path(root,
5816  rel,
5817  newpath,
5818  thistarget);
5819  else
5820  newpath = (Path *) apply_projection_to_path(root,
5821  rel,
5822  newpath,
5823  thistarget);
5824  }
5825  lfirst(lc) = newpath;
5826  if (subpath == rel->cheapest_startup_path)
5827  rel->cheapest_startup_path = newpath;
5828  if (subpath == rel->cheapest_total_path)
5829  rel->cheapest_total_path = newpath;
5830  }
5831 
5832  /* Likewise for partial paths, if any */
5833  foreach(lc, rel->partial_pathlist)
5834  {
5835  Path *subpath = (Path *) lfirst(lc);
5836  Path *newpath = subpath;
5837  ListCell *lc1,
5838  *lc2;
5839 
5840  Assert(subpath->param_info == NULL);
5841  forboth(lc1, targets, lc2, targets_contain_srfs)
5842  {
5843  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5844  bool contains_srfs = (bool) lfirst_int(lc2);
5845 
5846  /* If this level doesn't contain SRFs, do regular projection */
5847  if (contains_srfs)
5848  newpath = (Path *) create_set_projection_path(root,
5849  rel,
5850  newpath,
5851  thistarget);
5852  else
5853  {
5854  /* avoid apply_projection_to_path, in case of multiple refs */
5855  newpath = (Path *) create_projection_path(root,
5856  rel,
5857  newpath,
5858  thistarget);
5859  }
5860  }
5861  lfirst(lc) = newpath;
5862  }
5863 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2475
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
struct Path * cheapest_startup_path
Definition: relation.h:629
ParamPathInfo * param_info
Definition: relation.h:1081
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2384
List * partial_pathlist
Definition: relation.h:628
char bool
Definition: c.h:275
#define linitial_int(l)
Definition: pg_list.h:112
#define lfirst_int(lc)
Definition: pg_list.h:107
#define lfirst_node(type, lc)
Definition: pg_list.h:109
struct Path * cheapest_total_path
Definition: relation.h:630
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2564
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
List * pathlist
Definition: relation.h:626
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234

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

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

Referenced by grouping_planner().

6785 {
6786  ListCell *lc;
6787  PathTarget *scanjoin_target;
6788  bool is_dummy_rel = IS_DUMMY_REL(rel);
6789 
6791 
6792  /*
6793  * If the scan/join target is not parallel-safe, partial paths cannot
6794  * generate it.
6795  */
6796  if (!scanjoin_target_parallel_safe)
6797  {
6798  /*
6799  * Since we can't generate the final scan/join target, this is our
6800  * last opportunity to use any partial paths that exist. We don't do
6801  * this if the case where the target is parallel-safe, since we will
6802  * be able to generate superior paths by doing it after the final
6803  * scan/join target has been applied.
6804  *
6805  * Note that this may invalidate rel->cheapest_total_path, so we must
6806  * not rely on it after this point without first calling set_cheapest.
6807  */
6808  generate_gather_paths(root, rel, false);
6809 
6810  /* Can't use parallel query above this level. */
6811  rel->partial_pathlist = NIL;
6812  rel->consider_parallel = false;
6813  }
6814 
6815  /*
6816  * Update the reltarget. This may not be strictly necessary in all cases,
6817  * but it is at least necessary when create_append_path() gets called
6818  * below directly or indirectly, since that function uses the reltarget as
6819  * the pathtarget for the resulting path. It seems like a good idea to do
6820  * it unconditionally.
6821  */
6822  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
6823 
6824  /* Special case: handle dummy relations separately. */
6825  if (is_dummy_rel)
6826  {
6827  /*
6828  * Since this is a dummy rel, it's got a single Append path with no
6829  * child paths. Replace it with a new path having the final scan/join
6830  * target. (Note that since Append is not projection-capable, it
6831  * would be bad to handle this using the general purpose code below;
6832  * we'd end up putting a ProjectionPath on top of the existing Append
6833  * node, which would cause this relation to stop appearing to be a
6834  * dummy rel.)
6835  */
6836  rel->pathlist = list_make1(create_append_path(root, rel, NIL, NIL,
6837  NULL, 0, false, NIL,
6838  -1));
6839  rel->partial_pathlist = NIL;
6840  set_cheapest(rel);
6841  Assert(IS_DUMMY_REL(rel));
6842 
6843  /*
6844  * Forget about any child relations. There's no point in adjusting
6845  * them and no point in using them for later planning stages (in
6846  * particular, partitionwise aggregate).
6847  */
6848  rel->nparts = 0;
6849  rel->part_rels = NULL;
6850  rel->boundinfo = NULL;
6851 
6852  return;
6853  }
6854 
6855  /* Extract SRF-free scan/join target. */
6856  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
6857 
6858  /*
6859  * Adjust each input path. If the tlist exprs are the same, we can just
6860  * inject the sortgroupref information into the existing pathtarget.
6861  * Otherwise, replace each path with a projection path that generates the
6862  * SRF-free scan/join target. This can't change the ordering of paths
6863  * within rel->pathlist, so we just modify the list in place.
6864  */
6865  foreach(lc, rel->pathlist)
6866  {
6867  Path *subpath = (Path *) lfirst(lc);
6868  Path *newpath;
6869 
6870  Assert(subpath->param_info == NULL);
6871 
6872  if (tlist_same_exprs)
6873  subpath->pathtarget->sortgrouprefs =
6874  scanjoin_target->sortgrouprefs;
6875  else
6876  {
6877  newpath = (Path *) create_projection_path(root, rel, subpath,
6878  scanjoin_target);
6879  lfirst(lc) = newpath;
6880  }
6881  }
6882 
6883  /* Same for partial paths. */
6884  foreach(lc, rel->partial_pathlist)
6885  {
6886  Path *subpath = (Path *) lfirst(lc);
6887  Path *newpath;
6888 
6889  /* Shouldn't have any parameterized paths anymore */
6890  Assert(subpath->param_info == NULL);
6891 
6892  if (tlist_same_exprs)
6893  subpath->pathtarget->sortgrouprefs =
6894  scanjoin_target->sortgrouprefs;
6895  else
6896  {
6897  newpath = (Path *) create_projection_path(root,
6898  rel,
6899  subpath,
6900  scanjoin_target);
6901  lfirst(lc) = newpath;
6902  }
6903  }
6904 
6905  /* Now fix things up if scan/join target contains SRFs */
6906  if (root->parse->hasTargetSRFs)
6907  adjust_paths_for_srfs(root, rel,
6908  scanjoin_targets,
6909  scanjoin_targets_contain_srfs);
6910 
6911  /*
6912  * If the relation is partitioned, recurseively apply the same changes to
6913  * all partitions and generate new Append paths. Since Append is not
6914  * projection-capable, that might save a separate Result node, and it also
6915  * is important for partitionwise aggregate.
6916  */
6917  if (rel->part_scheme && rel->part_rels)
6918  {
6919  int partition_idx;
6920  List *live_children = NIL;
6921 
6922  /* Adjust each partition. */
6923  for (partition_idx = 0; partition_idx < rel->nparts; partition_idx++)
6924  {
6925  RelOptInfo *child_rel = rel->part_rels[partition_idx];
6926  ListCell *lc;
6927  AppendRelInfo **appinfos;
6928  int nappinfos;
6929  List *child_scanjoin_targets = NIL;
6930 
6931  /* Translate scan/join targets for this child. */
6932  appinfos = find_appinfos_by_relids(root, child_rel->relids,
6933  &nappinfos);
6934  foreach(lc, scanjoin_targets)
6935  {
6936  PathTarget *target = lfirst_node(PathTarget, lc);
6937 
6938  target = copy_pathtarget(target);
6939  target->exprs = (List *)
6941  (Node *) target->exprs,
6942  nappinfos, appinfos);
6943  child_scanjoin_targets = lappend(child_scanjoin_targets,
6944  target);
6945  }
6946  pfree(appinfos);
6947 
6948  /* Recursion does the real work. */
6949  apply_scanjoin_target_to_paths(root, child_rel,
6950  child_scanjoin_targets,
6951  scanjoin_targets_contain_srfs,
6952  scanjoin_target_parallel_safe,
6954 
6955  /* Save non-dummy children for Append paths. */
6956  if (!IS_DUMMY_REL(child_rel))
6957  live_children = lappend(live_children, child_rel);
6958  }
6959 
6960  /* Build new paths for this relation by appending child paths. */
6961  if (live_children != NIL)
6962  add_paths_to_append_rel(root, rel, live_children);
6963  }
6964 
6965  /*
6966  * Consider generating Gather or Gather Merge paths. We must only do this
6967  * if the relation is parallel safe, and we don't do it for child rels to
6968  * avoid creating multiple Gather nodes within the same plan. We must do
6969  * this after all paths have been generated and before set_cheapest, since
6970  * one of the generated paths may turn out to be the cheapest one.
6971  */
6972  if (rel->consider_parallel && !IS_OTHER_REL(rel))
6973  generate_gather_paths(root, rel, false);
6974 
6975  /*
6976  * Reassess which paths are the cheapest, now that we've potentially added
6977  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
6978  * this relation.
6979  */
6980  set_cheapest(rel);
6981 }
#define NIL
Definition: pg_list.h:69
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:629
static bool is_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1194
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:6779
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1219
PathTarget * pathtarget
Definition: relation.h:1079
Query * parse
Definition: relation.h:169
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1377
ParamPathInfo * param_info
Definition: relation.h:1081
Definition: nodes.h:517
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2384
List * partial_pathlist
Definition: relation.h:628
#define IS_OTHER_REL(rel)
Definition: relation.h:600
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2546
#define linitial_node(type, l)
Definition: pg_list.h:114
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:5778
#define list_make1(x1)
Definition: pg_list.h:139
void pfree(void *pointer)
Definition: mcxt.c:1031
#define IS_DUMMY_REL(r)
Definition: relation.h:1317
#define lfirst_node(type, lc)
Definition: pg_list.h:109
void check_stack_depth(void)
Definition: postgres.c:3155
int nparts
Definition: relation.h:685
Index * sortgrouprefs
Definition: relation.h:1009
Relids relids
Definition: relation.h:612
List * lappend(List *list, void *datum)
Definition: list.c:128
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: prepunion.c:2047
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: relation.h:1008
struct PartitionBoundInfoData * boundinfo
Definition: relation.h:686
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: prepunion.c:2618
#define llast_node(type, l)
Definition: pg_list.h:134
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
struct RelOptInfo ** part_rels
Definition: relation.h:688
bool consider_parallel
Definition: relation.h:620
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:221
PartitionScheme part_scheme
Definition: relation.h:684
List * pathlist
Definition: relation.h:626
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:623
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234

◆ can_partial_agg()

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

Definition at line 6737 of file planner.c.

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

Referenced by create_grouping_paths().

6738 {
6739  Query *parse = root->parse;
6740 
6741  if (!parse->hasAggs && parse->groupClause == NIL)
6742  {
6743  /*
6744  * We don't know how to do parallel aggregation unless we have either
6745  * some aggregates or a grouping clause.
6746  */
6747  return false;
6748  }
6749  else if (parse->groupingSets)
6750  {
6751  /* We don't know how to do grouping sets in parallel. */
6752  return false;
6753  }
6754  else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
6755  {
6756  /* Insufficient support for partial mode. */
6757  return false;
6758  }
6759 
6760  /* Everything looks good. */
6761  return true;
6762 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
bool hasNonSerial
Definition: relation.h:62
bool hasNonPartial
Definition: relation.h:61
List * groupClause
Definition: parsenodes.h:148
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

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

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

Referenced by add_paths_to_grouping_rel().

4085 {
4086  Query *parse = root->parse;
4087 
4088  /*
4089  * If we're not being offered sorted input, then only consider plans that
4090  * can be done entirely by hashing.
4091  *
4092  * We can hash everything if it looks like it'll fit in work_mem. But if
4093  * the input is actually sorted despite not being advertised as such, we
4094  * prefer to make use of that in order to use less memory.
4095  *
4096  * If none of the grouping sets are sortable, then ignore the work_mem
4097  * limit and generate a path anyway, since otherwise we'll just fail.
4098  */
4099  if (!is_sorted)
4100  {
4101  List *new_rollups = NIL;
4102  RollupData *unhashed_rollup = NULL;
4103  List *sets_data;
4104  List *empty_sets_data = NIL;
4105  List *empty_sets = NIL;
4106  ListCell *lc;
4107  ListCell *l_start = list_head(gd->rollups);
4108  AggStrategy strat = AGG_HASHED;
4109  Size hashsize;
4110  double exclude_groups = 0.0;
4111 
4112  Assert(can_hash);
4113 
4114  /*
4115  * If the input is coincidentally sorted usefully (which can happen
4116  * even if is_sorted is false, since that only means that our caller
4117  * has set up the sorting for us), then save some hashtable space by
4118  * making use of that. But we need to watch out for degenerate cases:
4119  *
4120  * 1) If there are any empty grouping sets, then group_pathkeys might
4121  * be NIL if all non-empty grouping sets are unsortable. In this case,
4122  * there will be a rollup containing only empty groups, and the
4123  * pathkeys_contained_in test is vacuously true; this is ok.
4124  *
4125  * XXX: the above relies on the fact that group_pathkeys is generated
4126  * from the first rollup. If we add the ability to consider multiple
4127  * sort orders for grouping input, this assumption might fail.
4128  *
4129  * 2) If there are no empty sets and only unsortable sets, then the
4130  * rollups list will be empty (and thus l_start == NULL), and
4131  * group_pathkeys will be NIL; we must ensure that the vacuously-true
4132  * pathkeys_contain_in test doesn't cause us to crash.
4133  */
4134  if (l_start != NULL &&
4136  {
4137  unhashed_rollup = lfirst_node(RollupData, l_start);
4138  exclude_groups = unhashed_rollup->numGroups;
4139  l_start = lnext(l_start);
4140  }
4141 
4142  hashsize = estimate_hashagg_tablesize(path,
4143  agg_costs,
4144  dNumGroups - exclude_groups);
4145 
4146  /*
4147  * gd->rollups is empty if we have only unsortable columns to work
4148  * with. Override work_mem in that case; otherwise, we'll rely on the
4149  * sorted-input case to generate usable mixed paths.
4150  */
4151  if (hashsize > work_mem * 1024L && gd->rollups)
4152  return; /* nope, won't fit */
4153 
4154  /*
4155  * We need to burst the existing rollups list into individual grouping
4156  * sets and recompute a groupClause for each set.
4157  */
4158  sets_data = list_copy(gd->unsortable_sets);
4159 
4160  for_each_cell(lc, l_start)
4161  {
4162  RollupData *rollup = lfirst_node(RollupData, lc);
4163 
4164  /*
4165  * If we find an unhashable rollup that's not been skipped by the
4166  * "actually sorted" check above, we can't cope; we'd need sorted
4167  * input (with a different sort order) but we can't get that here.
4168  * So bail out; we'll get a valid path from the is_sorted case
4169  * instead.
4170  *
4171  * The mere presence of empty grouping sets doesn't make a rollup
4172  * unhashable (see preprocess_grouping_sets), we handle those
4173  * specially below.
4174  */
4175  if (!rollup->hashable)
4176  return;
4177  else
4178  sets_data = list_concat(sets_data, list_copy(rollup->gsets_data));
4179  }
4180  foreach(lc, sets_data)
4181  {
4183  List *gset = gs->set;
4184  RollupData *rollup;
4185 
4186  if (gset == NIL)
4187  {
4188  /* Empty grouping sets can't be hashed. */
4189  empty_sets_data = lappend(empty_sets_data, gs);
4190  empty_sets = lappend(empty_sets, NIL);
4191  }
4192  else
4193  {
4194  rollup = makeNode(RollupData);
4195 
4196  rollup->groupClause = preprocess_groupclause(root, gset);
4197  rollup->gsets_data = list_make1(gs);
4198  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4199  rollup->gsets_data,
4200  gd->tleref_to_colnum_map);
4201  rollup->numGroups = gs->numGroups;
4202  rollup->hashable = true;
4203  rollup->is_hashed = true;
4204  new_rollups = lappend(new_rollups, rollup);
4205  }
4206  }
4207 
4208  /*
4209  * If we didn't find anything nonempty to hash, then bail. We'll
4210  * generate a path from the is_sorted case.
4211  */
4212  if (new_rollups == NIL)
4213  return;
4214 
4215  /*
4216  * If there were empty grouping sets they should have been in the
4217  * first rollup.
4218  */
4219  Assert(!unhashed_rollup || !empty_sets);
4220 
4221  if (unhashed_rollup)
4222  {
4223  new_rollups = lappend(new_rollups, unhashed_rollup);
4224  strat = AGG_MIXED;
4225  }
4226  else if (empty_sets)
4227  {
4228  RollupData *rollup = makeNode(RollupData);
4229 
4230  rollup->groupClause = NIL;
4231  rollup->gsets_data = empty_sets_data;
4232  rollup->gsets = empty_sets;
4233  rollup->numGroups = list_length(empty_sets);
4234  rollup->hashable = false;
4235  rollup->is_hashed = false;
4236  new_rollups = lappend(new_rollups, rollup);
4237  strat = AGG_MIXED;
4238  }
4239 
4240  add_path(grouped_rel, (Path *)
4242  grouped_rel,
4243  path,
4244  (List *) parse->havingQual,
4245  strat,
4246  new_rollups,
4247  agg_costs,
4248  dNumGroups));
4249  return;
4250  }
4251 
4252  /*
4253  * If we have sorted input but nothing we can do with it, bail.
4254  */
4255  if (list_length(gd->rollups) == 0)
4256  return;
4257 
4258  /*
4259  * Given sorted input, we try and make two paths: one sorted and one mixed
4260  * sort/hash. (We need to try both because hashagg might be disabled, or
4261  * some columns might not be sortable.)
4262  *
4263  * can_hash is passed in as false if some obstacle elsewhere (such as
4264  * ordered aggs) means that we shouldn't consider hashing at all.
4265  */
4266  if (can_hash && gd->any_hashable)
4267  {
4268  List *rollups = NIL;
4269  List *hash_sets = list_copy(gd->unsortable_sets);
4270  double availspace = (work_mem * 1024.0);
4271  ListCell *lc;
4272 
4273  /*
4274  * Account first for space needed for groups we can't sort at all.
4275  */
4276  availspace -= (double) estimate_hashagg_tablesize(path,
4277  agg_costs,
4278  gd->dNumHashGroups);
4279 
4280  if (availspace > 0 && list_length(gd->rollups) > 1)
4281  {
4282  double scale;
4283  int num_rollups = list_length(gd->rollups);
4284  int k_capacity;
4285  int *k_weights = palloc(num_rollups * sizeof(int));
4286  Bitmapset *hash_items = NULL;
4287  int i;
4288 
4289  /*
4290  * We treat this as a knapsack problem: the knapsack capacity
4291  * represents work_mem, the item weights are the estimated memory
4292  * usage of the hashtables needed to implement a single rollup,
4293  * and we really ought to use the cost saving as the item value;
4294  * however, currently the costs assigned to sort nodes don't
4295  * reflect the comparison costs well, and so we treat all items as
4296  * of equal value (each rollup we hash instead saves us one sort).
4297  *
4298  * To use the discrete knapsack, we need to scale the values to a
4299  * reasonably small bounded range. We choose to allow a 5% error
4300  * margin; we have no more than 4096 rollups in the worst possible
4301  * case, which with a 5% error margin will require a bit over 42MB
4302  * of workspace. (Anyone wanting to plan queries that complex had
4303  * better have the memory for it. In more reasonable cases, with
4304  * no more than a couple of dozen rollups, the memory usage will
4305  * be negligible.)
4306  *
4307  * k_capacity is naturally bounded, but we clamp the values for
4308  * scale and weight (below) to avoid overflows or underflows (or
4309  * uselessly trying to use a scale factor less than 1 byte).
4310  */
4311  scale = Max(availspace / (20.0 * num_rollups), 1.0);
4312  k_capacity = (int) floor(availspace / scale);
4313 
4314  /*
4315  * We leave the first rollup out of consideration since it's the
4316  * one that matches the input sort order. We assign indexes "i"
4317  * to only those entries considered for hashing; the second loop,
4318  * below, must use the same condition.
4319  */
4320  i = 0;
4322  {
4323  RollupData *rollup = lfirst_node(RollupData, lc);
4324 
4325  if (rollup->hashable)
4326  {
4327  double sz = estimate_hashagg_tablesize(path,
4328  agg_costs,
4329  rollup->numGroups);
4330 
4331  /*
4332  * If sz is enormous, but work_mem (and hence scale) is
4333  * small, avoid integer overflow here.
4334  */
4335  k_weights[i] = (int) Min(floor(sz / scale),
4336  k_capacity + 1.0);
4337  ++i;
4338  }
4339  }
4340 
4341  /*
4342  * Apply knapsack algorithm; compute the set of items which
4343  * maximizes the value stored (in this case the number of sorts
4344  * saved) while keeping the total size (approximately) within
4345  * capacity.
4346  */
4347  if (i > 0)
4348  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4349 
4350  if (!bms_is_empty(hash_items))
4351  {
4352  rollups = list_make1(linitial(gd->rollups));
4353 
4354  i = 0;
4356  {
4357  RollupData *rollup = lfirst_node(RollupData, lc);
4358 
4359  if (rollup->hashable)
4360  {
4361  if (bms_is_member(i, hash_items))
4362  hash_sets = list_concat(hash_sets,
4363  list_copy(rollup->gsets_data));
4364  else
4365  rollups = lappend(rollups, rollup);
4366  ++i;
4367  }
4368  else
4369  rollups = lappend(rollups, rollup);
4370  }
4371  }
4372  }
4373 
4374  if (!rollups && hash_sets)
4375  rollups = list_copy(gd->rollups);
4376 
4377  foreach(lc, hash_sets)
4378  {
4380  RollupData *rollup = makeNode(RollupData);
4381 
4382  Assert(gs->set != NIL);
4383 
4384  rollup->groupClause = preprocess_groupclause(root, gs->set);
4385  rollup->gsets_data = list_make1(gs);
4386  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4387  rollup->gsets_data,
4388  gd->tleref_to_colnum_map);
4389  rollup->numGroups = gs->numGroups;
4390  rollup->hashable = true;
4391  rollup->is_hashed = true;
4392  rollups = lcons(rollup, rollups);
4393  }
4394 
4395  if (rollups)
4396  {
4397  add_path(grouped_rel, (Path *)
4399  grouped_rel,
4400  path,
4401  (List *) parse->havingQual,
4402  AGG_MIXED,
4403  rollups,
4404  agg_costs,
4405  dNumGroups));
4406  }
4407  }
4408 
4409  /*
4410  * Now try the simple sorted case.
4411  */
4412  if (!gd->unsortable_sets)
4413  add_path(grouped_rel, (Path *)
4415  grouped_rel,
4416  path,
4417  (List *) parse->havingQual,
4418  AGG_SORTED,
4419  gd->rollups,
4420  agg_costs,
4421  dNumGroups));
4422 }
List * group_pathkeys
Definition: relation.h:276
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
List * groupClause
Definition: relation.h:1613
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:3078
#define Min(x, y)
Definition: c.h:857
bool is_hashed
Definition: relation.h:1618
List * list_copy(const List *oldlist)
Definition: list.c:1160
int scale
Definition: pgbench.c:120
double dNumHashGroups
Definition: planner.c:105
List * list_concat(List *list1, List *list2)
Definition: list.c:321
double numGroups
Definition: relation.h:1616
#define list_make1(x1)
Definition: pg_list.h:139
#define linitial(l)
Definition: pg_list.h:111
int * tleref_to_colnum_map
Definition: planner.c:110
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3649
List * lappend(List *list, void *datum)
Definition: list.c:128
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:729
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
static List * remap_to_groupclause_idx(List *groupClause, List *gsets, int *tleref_to_colnum_map)
Definition: planner.c:2433
int work_mem
Definition: globals.c:122
List * lcons(void *datum, List *list)
Definition: list.c:259
List * pathkeys
Definition: relation.h:1092
#define Max(x, y)
Definition: c.h:851
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
size_t Size
Definition: c.h:433
static int list_length(const List *l)
Definition: pg_list.h:89
List * unsortable_sets
Definition: planner.c:109
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
AggStrategy
Definition: nodes.h:743
void * palloc(Size size)
Definition: mcxt.c:924
int i
double numGroups
Definition: relation.h:1607
bool hashable
Definition: relation.h:1617
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:45
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:486
List * gsets_data
Definition: relation.h:1615
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:2852
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1614

◆ create_degenerate_grouping_paths()

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

Definition at line 3875 of file planner.c.

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

Referenced by create_grouping_paths().

3877 {
3878  Query *parse = root->parse;
3879  int nrows;
3880  Path *path;
3881 
3882  nrows = list_length(parse->groupingSets);
3883  if (nrows > 1)
3884  {
3885  /*
3886  * Doesn't seem worthwhile writing code to cons up a generate_series
3887  * or a values scan to emit multiple rows. Instead just make N clones
3888  * and append them. (With a volatile HAVING clause, this means you
3889  * might get between 0 and N output rows. Offhand I think that's
3890  * desired.)
3891  */
3892  List *paths = NIL;
3893 
3894  while (--nrows >= 0)
3895  {
3896  path = (Path *)
3897  create_result_path(root, grouped_rel,
3898  grouped_rel->reltarget,
3899  (List *) parse->havingQual);
3900  paths = lappend(paths, path);
3901  }
3902  path = (Path *)
3903  create_append_path(root,
3904  grouped_rel,
3905  paths,
3906  NIL,
3907  NULL,
3908  0,
3909  false,
3910  NIL,
3911  -1);
3912  }
3913  else
3914  {
3915  /* No grouping sets, or just one, so one output row */
3916  path = (Path *)
3917  create_result_path(root, grouped_rel,
3918  grouped_rel->reltarget,
3919  (List *) parse->havingQual);
3920  }
3921 
3922  add_path(grouped_rel, path);
3923 }
#define NIL
Definition: pg_list.h:69
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1219
Query * parse
Definition: relation.h:169
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * groupingSets
Definition: parsenodes.h:150
List * lappend(List *list, void *datum)
Definition: list.c:128
static int list_length(const List *l)
Definition: pg_list.h:89
ResultPath * create_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *resconstantqual)
Definition: pathnode.c:1439
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:623
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ create_distinct_paths()

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

Definition at line 4621 of file planner.c.

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

Referenced by grouping_planner().

4623 {
4624  Query *parse = root->parse;
4625  Path *cheapest_input_path = input_rel->cheapest_total_path;
4626  RelOptInfo *distinct_rel;
4627  double numDistinctRows;
4628  bool allow_hash;
4629  Path *path;
4630  ListCell *lc;
4631 
4632  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4633  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4634 
4635  /*
4636  * We don't compute anything at this level, so distinct_rel will be
4637  * parallel-safe if the input rel is parallel-safe. In particular, if
4638  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4639  * output those expressions, and will not be parallel-safe unless those
4640  * expressions are parallel-safe.
4641  */
4642  distinct_rel->consider_parallel = input_rel->consider_parallel;
4643 
4644  /*
4645  * If the input rel belongs to a single FDW, so does the distinct_rel.
4646  */
4647  distinct_rel->serverid = input_rel->serverid;
4648  distinct_rel->userid = input_rel->userid;
4649  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4650  distinct_rel->fdwroutine = input_rel->fdwroutine;
4651 
4652  /* Estimate number of distinct rows there will be */
4653  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4654  root->hasHavingQual)
4655  {
4656  /*
4657  * If there was grouping or aggregation, use the number of input rows
4658  * as the estimated number of DISTINCT rows (ie, assume the input is
4659  * already mostly unique).
4660  */
4661  numDistinctRows = cheapest_input_path->rows;
4662  }
4663  else
4664  {
4665  /*
4666  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4667  */
4668  List *distinctExprs;
4669 
4670  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4671  parse->targetList);
4672  numDistinctRows = estimate_num_groups(root, distinctExprs,
4673  cheapest_input_path->rows,
4674  NULL);
4675  }
4676 
4677  /*
4678  * Consider sort-based implementations of DISTINCT, if possible.
4679  */
4681  {
4682  /*
4683  * First, if we have any adequately-presorted paths, just stick a
4684  * Unique node on those. Then consider doing an explicit sort of the
4685  * cheapest input path and Unique'ing that.
4686  *
4687  * When we have DISTINCT ON, we must sort by the more rigorous of
4688  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4689  * Also, if we do have to do an explicit sort, we might as well use
4690  * the more rigorous ordering to avoid a second sort later. (Note
4691  * that the parser will have ensured that one clause is a prefix of
4692  * the other.)
4693  */
4694  List *needed_pathkeys;
4695 
4696  if (parse->hasDistinctOn &&
4698  list_length(root->sort_pathkeys))
4699  needed_pathkeys = root->sort_pathkeys;
4700  else
4701  needed_pathkeys = root->distinct_pathkeys;
4702 
4703  foreach(lc, input_rel->pathlist)
4704  {
4705  Path *path = (Path *) lfirst(lc);
4706 
4707  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4708  {
4709  add_path(distinct_rel, (Path *)
4710  create_upper_unique_path(root, distinct_rel,
4711  path,
4713  numDistinctRows));
4714  }
4715  }
4716 
4717  /* For explicit-sort case, always use the more rigorous clause */
4718  if (list_length(root->distinct_pathkeys) <
4719  list_length(root->sort_pathkeys))
4720  {
4721  needed_pathkeys = root->sort_pathkeys;
4722  /* Assert checks that parser didn't mess up... */
4724  needed_pathkeys));
4725  }
4726  else
4727  needed_pathkeys = root->distinct_pathkeys;
4728 
4729  path = cheapest_input_path;
4730  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4731  path = (Path *) create_sort_path(root, distinct_rel,
4732  path,
4733  needed_pathkeys,
4734  -1.0);
4735 
4736  add_path(distinct_rel, (Path *)
4737  create_upper_unique_path(root, distinct_rel,
4738  path,
4740  numDistinctRows));
4741  }
4742 
4743  /*
4744  * Consider hash-based implementations of DISTINCT, if possible.
4745  *
4746  * If we were not able to make any other types of path, we *must* hash or
4747  * die trying. If we do have other choices, there are several things that
4748  * should prevent selection of hashing: if the query uses DISTINCT ON
4749  * (because it won't really have the expected behavior if we hash), or if
4750  * enable_hashagg is off, or if it looks like the hashtable will exceed
4751  * work_mem.
4752  *
4753  * Note: grouping_is_hashable() is much more expensive to check than the
4754  * other gating conditions, so we want to do it last.
4755  */
4756  if (distinct_rel->pathlist == NIL)
4757  allow_hash = true; /* we have no alternatives */
4758  else if (parse->hasDistinctOn || !enable_hashagg)
4759  allow_hash = false; /* policy-based decision not to hash */
4760  else
4761  {
4762  Size hashentrysize;
4763 
4764  /* Estimate per-hash-entry space at tuple width... */
4765  hashentrysize = MAXALIGN(cheapest_input_path->pathtarget->width) +
4767  /* plus the per-hash-entry overhead */
4768  hashentrysize += hash_agg_entry_size(0);
4769 
4770  /* Allow hashing only if hashtable is predicted to fit in work_mem */
4771  allow_hash = (hashentrysize * numDistinctRows <= work_mem * 1024L);
4772  }
4773 
4774  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4775  {
4776  /* Generate hashed aggregate path --- no sort needed */
4777  add_path(distinct_rel, (Path *)
4778  create_agg_path(root,
4779  distinct_rel,
4780  cheapest_input_path,
4781  cheapest_input_path->pathtarget,
4782  AGG_HASHED,
4784  parse->distinctClause,
4785  NIL,
4786  NULL,
4787  numDistinctRows));
4788  }
4789 
4790  /* Give a helpful error if we failed to find any implementation */
4791  if (distinct_rel->pathlist == NIL)
4792  ereport(ERROR,
4793  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4794  errmsg("could not implement DISTINCT"),
4795  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4796 
4797  /*
4798  * If there is an FDW that's responsible for all baserels of the query,
4799  * let it consider adding ForeignPaths.
4800  */
4801  if (distinct_rel->fdwroutine &&
4802  distinct_rel->fdwroutine->GetForeignUpperPaths)
4803  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4804  input_rel, distinct_rel,
4805  NULL);
4806 
4807  /* Let extensions possibly add some more paths */
4809  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4810  input_rel, distinct_rel, NULL);
4811 
4812  /* Now choose the best path(s) */
4813  set_cheapest(distinct_rel);
4814 
4815  return distinct_rel;
4816 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:204
#define NIL
Definition: pg_list.h:69
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3419
PathTarget * pathtarget
Definition: relation.h:1079
Query * parse
Definition: relation.h:169
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:2734
Oid userid
Definition: relation.h:660
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
int errcode(int sqlerrcode)
Definition: elog.c:575
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:71
bool useridiscurrent
Definition: relation.h:661
bool hasDistinctOn
Definition: parsenodes.h:129
List * targetList
Definition: parsenodes.h:140
List * distinctClause
Definition: parsenodes.h:156
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1145
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:2786
struct Path * cheapest_total_path
Definition: relation.h:630
struct FdwRoutine * fdwroutine
Definition: relation.h:663
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * sort_pathkeys
Definition: relation.h:279
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: relation.h:659
#define SizeofMinimalTupleHeader
Definition: htup_details.h:667
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
int work_mem
Definition: globals.c:122
List * distinct_pathkeys
Definition: relation.h:278
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2631
List * pathkeys
Definition: relation.h:1092
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1088
size_t Size
Definition: c.h:433
static int list_length(const List *l)
Definition: pg_list.h:89
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:1424
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
#define MAXALIGN(LEN)
Definition: c.h:652
bool consider_parallel
Definition: relation.h:620
bool enable_hashagg
Definition: costsize.c:131
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
bool hasHavingQual
Definition: relation.h:318
List * pathlist
Definition: relation.h:626
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ create_grouping_paths()

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

Definition at line 3691 of file planner.c.

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

Referenced by grouping_planner().

3697 {
3698  Query *parse = root->parse;
3699  RelOptInfo *grouped_rel;
3700  RelOptInfo *partially_grouped_rel;
3701 
3702  /*
3703  * Create grouping relation to hold fully aggregated grouping and/or
3704  * aggregation paths.
3705  */
3706  grouped_rel = make_grouping_rel(root, input_rel, target,
3707  target_parallel_safe, parse->havingQual);
3708 
3709  /*
3710  * Create either paths for a degenerate grouping or paths for ordinary
3711  * grouping, as appropriate.
3712  */
3713  if (is_degenerate_grouping(root))
3714  create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3715  else
3716  {
3717  int flags = 0;
3718  GroupPathExtraData extra;
3719 
3720  /*
3721  * Determine whether it's possible to perform sort-based
3722  * implementations of grouping. (Note that if groupClause is empty,
3723  * grouping_is_sortable() is trivially true, and all the
3724  * pathkeys_contained_in() tests will succeed too, so that we'll
3725  * consider every surviving input path.)
3726  *
3727  * If we have grouping sets, we might be able to sort some but not all
3728  * of them; in this case, we need can_sort to be true as long as we
3729  * must consider any sorted-input plan.
3730  */
3731  if ((gd && gd->rollups != NIL)
3732  || grouping_is_sortable(parse->groupClause))
3733  flags |= GROUPING_CAN_USE_SORT;
3734 
3735  /*
3736  * Determine whether we should consider hash-based implementations of
3737  * grouping.
3738  *
3739  * Hashed aggregation only applies if we're grouping. If we have
3740  * grouping sets, some groups might be hashable but others not; in
3741  * this case we set can_hash true as long as there is nothing globally
3742  * preventing us from hashing (and we should therefore consider plans
3743  * with hashes).
3744  *
3745  * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3746  * BY aggregates. (Doing so would imply storing *all* the input
3747  * values in the hash table, and/or running many sorts in parallel,
3748  * either of which seems like a certain loser.) We similarly don't
3749  * support ordered-set aggregates in hashed aggregation, but that case
3750  * is also included in the numOrderedAggs count.
3751  *
3752  * Note: grouping_is_hashable() is much more expensive to check than
3753  * the other gating conditions, so we want to do it last.
3754  */
3755  if ((parse->groupClause != NIL &&
3756  agg_costs->numOrderedAggs == 0 &&
3757  (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause))))
3758  flags |= GROUPING_CAN_USE_HASH;
3759 
3760  /*
3761  * Determine whether partial aggregation is possible.
3762  */
3763  if (can_partial_agg(root, agg_costs))
3764  flags |= GROUPING_CAN_PARTIAL_AGG;
3765 
3766  extra.flags = flags;
3767  extra.target_parallel_safe = target_parallel_safe;
3768  extra.havingQual = parse->havingQual;
3769  extra.targetList = parse->targetList;
3770  extra.partial_costs_set = false;
3771 
3772  /*
3773  * Determine whether partitionwise aggregation is in theory possible.
3774  * It can be disabled by the user, and for now, we don't try to
3775  * support grouping sets. create_ordinary_grouping_paths() will check
3776  * additional conditions, such as whether input_rel is partitioned.
3777  */
3780  else
3782 
3783  create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3784  agg_costs, gd, &extra,
3785  &partially_grouped_rel);
3786  }
3787 
3788  set_cheapest(grouped_rel);
3789  return grouped_rel;
3790 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3801
static void create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
Definition: planner.c:3875
List * groupingSets
Definition: parsenodes.h:150
PartitionwiseAggregateType patype
Definition: relation.h:2380
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
bool enable_partitionwise_aggregate
Definition: costsize.c:138
List * targetList
Definition: parsenodes.h:140
#define GROUPING_CAN_USE_SORT
Definition: relation.h:2333
static bool is_degenerate_grouping(PlannerInfo *root)
Definition: planner.c:3854
int numOrderedAggs
Definition: relation.h:60
#define GROUPING_CAN_PARTIAL_AGG
Definition: relation.h:2335
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
static bool can_partial_agg(PlannerInfo *root, const AggClauseCosts *agg_costs)
Definition: planner.c:6737
#define GROUPING_CAN_USE_HASH
Definition: relation.h:2334
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:3939
List * groupClause
Definition: parsenodes.h:148
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
Node * havingQual
Definition: parsenodes.h:152
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
bool target_parallel_safe
Definition: relation.h:2377

◆ create_one_window_path()

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

Definition at line 4526 of file planner.c.

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

Referenced by create_window_paths().

4534 {
4535  PathTarget *window_target;
4536  ListCell *l;
4537 
4538  /*
4539  * Since each window clause could require a different sort order, we stack
4540  * up a WindowAgg node for each clause, with sort steps between them as
4541  * needed. (We assume that select_active_windows chose a good order for
4542  * executing the clauses in.)
4543  *
4544  * input_target should contain all Vars and Aggs needed for the result.
4545  * (In some cases we wouldn't need to propagate all of these all the way
4546  * to the top, since they might only be needed as inputs to WindowFuncs.
4547  * It's probably not worth trying to optimize that though.) It must also
4548  * contain all window partitioning and sorting expressions, to ensure
4549  * they're computed only once at the bottom of the stack (that's critical
4550  * for volatile functions). As we climb up the stack, we'll add outputs
4551  * for the WindowFuncs computed at each level.
4552  */
4553  window_target = input_target;
4554 
4555  foreach(l, activeWindows)
4556  {
4558  List *window_pathkeys;
4559 
4560  window_pathkeys = make_pathkeys_for_window(root,
4561  wc,
4562  tlist);
4563 
4564  /* Sort if necessary */
4565  if (!pathkeys_contained_in(window_pathkeys, path->pathkeys))
4566  {
4567  path = (Path *) create_sort_path(root, window_rel,
4568  path,
4569  window_pathkeys,
4570  -1.0);
4571  }
4572 
4573  if (lnext(l))
4574  {
4575  /*
4576  * Add the current WindowFuncs to the output target for this
4577  * intermediate WindowAggPath. We must copy window_target to
4578  * avoid changing the previous path's target.
4579  *
4580  * Note: a WindowFunc adds nothing to the target's eval costs; but
4581  * we do need to account for the increase in tlist width.
4582  */
4583  ListCell *lc2;
4584 
4585  window_target = copy_pathtarget(window_target);
4586  foreach(lc2, wflists->windowFuncs[wc->winref])
4587  {
4588  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4589 
4590  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4591  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4592  }
4593  }
4594  else
4595  {
4596  /* Install the goal target in the topmost WindowAgg */
4597  window_target = output_target;
4598  }
4599 
4600  path = (Path *)
4601  create_windowagg_path(root, window_rel, path, window_target,
4602  wflists->windowFuncs[wc->winref],
4603  wc,
4604  window_pathkeys);
4605  }
4606 
4607  add_path(window_rel, path);
4608 }
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:629
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5469
#define lnext(lc)
Definition: pg_list.h:105
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause, List *winpathkeys)
Definition: pathnode.c:3081
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2332
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2631
List * pathkeys
Definition: relation.h:1092
Oid wintype
Definition: primnodes.h:357
Definition: pg_list.h:45
List ** windowFuncs
Definition: clauses.h:27

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

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

Referenced by grouping_planner().

4838 {
4839  Path *cheapest_input_path = input_rel->cheapest_total_path;
4840  RelOptInfo *ordered_rel;
4841  ListCell *lc;
4842 
4843  /* For now, do all work in the (ORDERED, NULL) upperrel */
4844  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4845 
4846  /*
4847  * If the input relation is not parallel-safe, then the ordered relation
4848  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4849  * target list is parallel-safe.
4850  */
4851  if (input_rel->consider_parallel && target_parallel_safe)
4852  ordered_rel->consider_parallel = true;
4853 
4854  /*
4855  * If the input rel belongs to a single FDW, so does the ordered_rel.
4856  */
4857  ordered_rel->serverid = input_rel->serverid;
4858  ordered_rel->userid = input_rel->userid;
4859  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4860  ordered_rel->fdwroutine = input_rel->fdwroutine;
4861 
4862  foreach(lc, input_rel->pathlist)
4863  {
4864  Path *path = (Path *) lfirst(lc);
4865  bool is_sorted;
4866 
4867  is_sorted = pathkeys_contained_in(root->sort_pathkeys,
4868  path->pathkeys);
4869  if (path == cheapest_input_path || is_sorted)
4870  {
4871  if (!is_sorted)
4872  {
4873  /* An explicit sort here can take advantage of LIMIT */
4874  path = (Path *) create_sort_path(root,
4875  ordered_rel,
4876  path,
4877  root->sort_pathkeys,
4878  limit_tuples);
4879  }
4880 
4881  /* Add projection step if needed */
4882  if (path->pathtarget != target)
4883  path = apply_projection_to_path(root, ordered_rel,
4884  path, target);
4885 
4886  add_path(ordered_rel, path);
4887  }
4888  }
4889 
4890  /*
4891  * generate_gather_paths() will have already generated a simple Gather
4892  * path for the best parallel path, if any, and the loop above will have
4893  * considered sorting it. Similarly, generate_gather_paths() will also
4894  * have generated order-preserving Gather Merge plans which can be used
4895  * without sorting if they happen to match the sort_pathkeys, and the loop
4896  * above will have handled those as well. However, there's one more
4897  * possibility: it may make sense to sort the cheapest partial path
4898  * according to the required output order and then use Gather Merge.
4899  */
4900  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
4901  input_rel->partial_pathlist != NIL)
4902  {
4903  Path *cheapest_partial_path;
4904 
4905  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4906 
4907  /*
4908  * If cheapest partial path doesn't need a sort, this is redundant
4909  * with what's already been tried.
4910  */
4912  cheapest_partial_path->pathkeys))
4913  {
4914  Path *path;
4915  double total_groups;
4916 
4917  path = (Path *) create_sort_path(root,
4918  ordered_rel,
4919  cheapest_partial_path,
4920  root->sort_pathkeys,
4921  limit_tuples);
4922 
4923  total_groups = cheapest_partial_path->rows *
4924  cheapest_partial_path->parallel_workers;
4925  path = (Path *)
4926  create_gather_merge_path(root, ordered_rel,
4927  path,
4928  path->pathtarget,
4929  root->sort_pathkeys, NULL,
4930  &total_groups);
4931 
4932  /* Add projection step if needed */
4933  if (path->pathtarget != target)
4934  path = apply_projection_to_path(root, ordered_rel,
4935  path, target);
4936 
4937  add_path(ordered_rel, path);
4938  }
4939  }
4940 
4941  /*
4942  * If there is an FDW that's responsible for all baserels of the query,
4943  * let it consider adding ForeignPaths.
4944  */
4945  if (ordered_rel->fdwroutine &&
4946  ordered_rel->fdwroutine->GetForeignUpperPaths)
4947  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
4948  input_rel, ordered_rel,
4949  NULL);
4950 
4951  /* Let extensions possibly add some more paths */
4953  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
4954  input_rel, ordered_rel, NULL);
4955 
4956  /*
4957  * No need to bother with set_cheapest here; grouping_planner does not
4958  * need us to do it.
4959  */
4960  Assert(ordered_rel->pathlist != NIL);
4961 
4962  return ordered_rel;
4963 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2475
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:204
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:1079
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Oid userid
Definition: relation.h:660
int parallel_workers
Definition: relation.h:1085
List * partial_pathlist
Definition: relation.h:628
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:71
bool useridiscurrent
Definition: relation.h:661
#define linitial(l)
Definition: pg_list.h:111
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1145
struct Path * cheapest_total_path
Definition: relation.h:630
struct FdwRoutine * fdwroutine
Definition: relation.h:663
List * sort_pathkeys
Definition: relation.h:279
Oid serverid
Definition: relation.h:659
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1741
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2631
List * pathkeys
Definition: relation.h:1092
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1088
bool consider_parallel
Definition: relation.h:620
List * pathlist
Definition: relation.h:626

◆ 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 3939 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_DUMMY_REL, NIL, PlannerInfo::parse, RelOptInfo::part_rels, RelOptInfo::part_scheme, 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().

3945 {
3946  Path *cheapest_path = input_rel->cheapest_total_path;
3947  RelOptInfo *partially_grouped_rel = NULL;
3948  double dNumGroups;
3950 
3951  /*
3952  * If this is the topmost grouping relation or if the parent relation is
3953  * doing some form of partitionwise aggregation, then we may be able to do
3954  * it at this level also. However, if the input relation is not
3955  * partitioned, partitionwise aggregate is impossible, and if it is dummy,
3956  * partitionwise aggregate is pointless.
3957  */
3958  if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
3959  input_rel->part_scheme && input_rel->part_rels &&
3960  !IS_DUMMY_REL(input_rel))
3961  {
3962  /*
3963  * If this is the topmost relation or if the parent relation is doing
3964  * full partitionwise aggregation, then we can do full partitionwise
3965  * aggregation provided that the GROUP BY clause contains all of the
3966  * partitioning columns at this level. Otherwise, we can do at most
3967  * partial partitionwise aggregation. But if partial aggregation is
3968  * not supported in general then we can't use it for partitionwise
3969  * aggregation either.
3970  */
3971  if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
3972  group_by_has_partkey(input_rel, extra->targetList,
3973  root->parse->groupClause))
3975  else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3977  else
3979  }
3980 
3981  /*
3982  * Before generating paths for grouped_rel, we first generate any possible
3983  * partially grouped paths; that way, later code can easily consider both
3984  * parallel and non-parallel approaches to grouping.
3985  */
3986  if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3987  {
3988  bool force_rel_creation;
3989 
3990  /*
3991  * If we're doing partitionwise aggregation at this level, force
3992  * creation of a partially_grouped_rel so we can add partitionwise
3993  * paths to it.
3994  */
3995  force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
3996 
3997  partially_grouped_rel =
3999  grouped_rel,
4000  input_rel,
4001  gd,
4002  extra,
4003  force_rel_creation);
4004  }
4005 
4006  /* Set out parameter. */
4007  *partially_grouped_rel_p = partially_grouped_rel;
4008 
4009  /* Apply partitionwise aggregation technique, if possible. */
4010  if (patype != PARTITIONWISE_AGGREGATE_NONE)
4011  create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
4012  partially_grouped_rel, agg_costs,
4013  gd, patype, extra);
4014 
4015  /* If we are doing partial aggregation only, return. */
4017  {
4018  Assert(partially_grouped_rel);
4019 
4020  if (partially_grouped_rel->pathlist)
4021  set_cheapest(partially_grouped_rel);
4022 
4023  return;
4024  }
4025 
4026  /* Gather any partially grouped partial paths. */
4027  if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
4028  {
4029  gather_grouping_paths(root, partially_grouped_rel);
4030  set_cheapest(partially_grouped_rel);
4031  }
4032 
4033  /*
4034  * Estimate number of groups.
4035  */
4036  dNumGroups = get_number_of_groups(root,
4037  cheapest_path->rows,
4038  gd,
4039  extra->targetList);
4040 
4041  /* Build final grouping paths */
4042  add_paths_to_grouping_rel(root, input_rel, grouped_rel,
4043  partially_grouped_rel, agg_costs, gd,
4044  dNumGroups, extra);
4045 
4046  /* Give a helpful error if we failed to find any implementation */
4047  if (grouped_rel->pathlist == NIL)
4048  ereport(ERROR,
4049  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4050  errmsg("could not implement GROUP BY"),
4051  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4052 
4053  /*
4054  * If there is an FDW that's responsible for all baserels of the query,
4055  * let it consider adding ForeignPaths.
4056  */
4057  if (grouped_rel->fdwroutine &&
4058  grouped_rel->fdwroutine->GetForeignUpperPaths)
4060  input_rel, grouped_rel,
4061  extra);
4062 
4063  /* Let extensions possibly add some more paths */
4065  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4066  input_rel, grouped_rel,
4067  extra);
4068 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:204
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3536
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:6697
PartitionwiseAggregateType patype
Definition: relation.h:2380
int errcode(int sqlerrcode)
Definition: elog.c:575
List * partial_pathlist
Definition: relation.h:628
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:71
PartitionwiseAggregateType
Definition: relation.h:2348
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:6394
#define ERROR
Definition: elog.h:43
#define IS_DUMMY_REL(r)
Definition: relation.h:1317
struct Path * cheapest_total_path
Definition: relation.h:630
struct FdwRoutine * fdwroutine
Definition: relation.h:663
int errdetail(const char *fmt,...)
Definition: elog.c:873
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:6160
#define ereport(elevel, rest)
Definition: elog.h:122
#define GROUPING_CAN_PARTIAL_AGG
Definition: relation.h:2335
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
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:7001
#define Assert(condition)
Definition: c.h:699
double rows
Definition: relation.h:1088
struct RelOptInfo ** part_rels
Definition: relation.h:688
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:797
PartitionScheme part_scheme
Definition: relation.h:684
List * pathlist
Definition: relation.h:626
static bool group_by_has_partkey(RelOptInfo *input_rel, List *targetList, List *groupClause)
Definition: planner.c:7143

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

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

Referenced by create_ordinary_grouping_paths().

6400 {
6401  Query *parse = root->parse;
6402  RelOptInfo *partially_grouped_rel;
6403  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
6404  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6405  Path *cheapest_partial_path = NULL;
6406  Path *cheapest_total_path = NULL;
6407  double dNumPartialGroups = 0;
6408  double dNumPartialPartialGroups = 0;
6409  ListCell *lc;
6410  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6411  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6412 
6413  /*
6414  * Consider whether we should generate partially aggregated non-partial
6415  * paths. We can only do this if we have a non-partial path, and only if
6416  * the parent of the input rel is performing partial partitionwise
6417  * aggregation. (Note that extra->patype is the type of partitionwise
6418  * aggregation being used at the parent level, not this level.)
6419  */
6420  if (input_rel->pathlist != NIL &&
6422  cheapest_total_path = input_rel->cheapest_total_path;
6423 
6424  /*
6425  * If parallelism is possible for grouped_rel, then we should consider
6426  * generating partially-grouped partial paths. However, if the input rel
6427  * has no partial paths, then we can't.
6428  */
6429  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
6430  cheapest_partial_path = linitial(input_rel->partial_pathlist);
6431 
6432  /*
6433  * If we can't partially aggregate partial paths, and we can't partially
6434  * aggregate non-partial paths, then don't bother creating the new
6435  * RelOptInfo at all, unless the caller specified force_rel_creation.
6436  */
6437  if (cheapest_total_path == NULL &&
6438  cheapest_partial_path == NULL &&
6439  !force_rel_creation)
6440  return NULL;
6441 
6442  /*
6443  * Build a new upper relation to represent the result of partially
6444  * aggregating the rows from the input relation.
6445  */
6446  partially_grouped_rel = fetch_upper_rel(root,
6448  grouped_rel->relids);
6449  partially_grouped_rel->consider_parallel =
6450  grouped_rel->consider_parallel;
6451  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
6452  partially_grouped_rel->serverid = grouped_rel->serverid;
6453  partially_grouped_rel->userid = grouped_rel->userid;
6454  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
6455  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
6456 
6457  /*
6458  * Build target list for partial aggregate paths. These paths cannot just
6459  * emit the same tlist as regular aggregate paths, because (1) we must
6460  * include Vars and Aggrefs needed in HAVING, which might not appear in
6461  * the result tlist, and (2) the Aggrefs must be set in partial mode.
6462  */
6463  partially_grouped_rel->reltarget =
6464  make_partial_grouping_target(root, grouped_rel->reltarget,
6465  extra->havingQual);
6466 
6467  if (!extra->partial_costs_set)
6468  {
6469  /*
6470  * Collect statistics about aggregates for estimating costs of
6471  * performing aggregation in parallel.
6472  */
6473  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
6474  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
6475  if (parse->hasAggs)
6476  {
6477  List *partial_target_exprs;
6478 
6479  /* partial phase */
6480  partial_target_exprs = partially_grouped_rel->reltarget->exprs;
6481  get_agg_clause_costs(root, (Node *) partial_target_exprs,
6483  agg_partial_costs);
6484 
6485  /* final phase */
6486  get_agg_clause_costs(root, (Node *) grouped_rel->reltarget->exprs,
6488  agg_final_costs);
6489  get_agg_clause_costs(root, extra->havingQual,
6491  agg_final_costs);
6492  }
6493 
6494  extra->partial_costs_set = true;
6495  }
6496 
6497  /* Estimate number of partial groups. */
6498  if (cheapest_total_path != NULL)
6499  dNumPartialGroups =
6500  get_number_of_groups(root,
6501  cheapest_total_path->rows,
6502  gd,
6503  extra->targetList);
6504  if (cheapest_partial_path != NULL)
6505  dNumPartialPartialGroups =
6506  get_number_of_groups(root,
6507  cheapest_partial_path->rows,
6508  gd,
6509  extra->targetList);
6510 
6511  if (can_sort && cheapest_total_path != NULL)
6512  {
6513  /* This should have been checked previously */
6514  Assert(parse->hasAggs || parse->groupClause);
6515 
6516  /*
6517  * Use any available suitably-sorted path as input, and also consider
6518  * sorting the cheapest partial path.
6519  */
6520  foreach(lc, input_rel->pathlist)
6521  {
6522  Path *path = (Path *) lfirst(lc);
6523  bool is_sorted;
6524 
6525  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6526  path->pathkeys);
6527  if (path == cheapest_total_path || is_sorted)
6528  {
6529  /* Sort the cheapest partial path, if it isn't already */
6530  if (!is_sorted)
6531  path = (Path *) create_sort_path(root,
6532  partially_grouped_rel,
6533  path,
6534  root->group_pathkeys,
6535  -1.0);
6536 
6537  if (parse->hasAggs)
6538  add_path(partially_grouped_rel, (Path *)
6539  create_agg_path(root,
6540  partially_grouped_rel,
6541  path,
6542  partially_grouped_rel->reltarget,
6543  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6545  parse->groupClause,
6546  NIL,
6547  agg_partial_costs,
6548  dNumPartialGroups));
6549  else
6550  add_path(partially_grouped_rel, (Path *)
6551  create_group_path(root,
6552  partially_grouped_rel,
6553  path,
6554  parse->groupClause,
6555  NIL,
6556  dNumPartialGroups));
6557  }
6558  }
6559  }
6560 
6561  if (can_sort && cheapest_partial_path != NULL)
6562  {
6563  /* Similar to above logic, but for partial paths. */
6564  foreach(lc, input_rel->partial_pathlist)
6565  {
6566  Path *path = (Path *) lfirst(lc);
6567  bool is_sorted;
6568 
6569  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6570  path->pathkeys);
6571  if (path == cheapest_partial_path || is_sorted)
6572  {
6573  /* Sort the cheapest partial path, if it isn't already */
6574  if (!is_sorted)
6575  path = (Path *) create_sort_path(root,
6576  partially_grouped_rel,
6577  path,
6578  root->group_pathkeys,
6579  -1.0);
6580 
6581  if (parse->hasAggs)
6582  add_partial_path(partially_grouped_rel, (Path *)
6583  create_agg_path(root,
6584  partially_grouped_rel,
6585  path,
6586  partially_grouped_rel->reltarget,
6587  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6589  parse->groupClause,
6590  NIL,
6591  agg_partial_costs,
6592  dNumPartialPartialGroups));
6593  else
6594  add_partial_path(partially_grouped_rel, (Path *)
6595  create_group_path(root,
6596  partially_grouped_rel,
6597  path,
6598  parse->groupClause,
6599  NIL,
6600  dNumPartialPartialGroups));
6601  }
6602  }
6603  }
6604 
6605  if (can_hash && cheapest_total_path != NULL)
6606  {
6607  Size hashaggtablesize;
6608 
6609  /* Checked above */
6610  Assert(parse->hasAggs || parse->groupClause);
6611 
6612  hashaggtablesize =
6613  estimate_hashagg_tablesize(cheapest_total_path,
6614  agg_partial_costs,
6615  dNumPartialGroups);
6616 
6617  /*
6618  * Tentatively produce a partial HashAgg Path, depending on if it
6619  * looks as if the hash table will fit in work_mem.
6620  */
6621  if (hashaggtablesize < work_mem * 1024L &&
6622  cheapest_total_path != NULL)
6623  {
6624  add_path(partially_grouped_rel, (Path *)
6625  create_agg_path(root,
6626  partially_grouped_rel,
6627  cheapest_total_path,
6628  partially_grouped_rel->reltarget,
6629  AGG_HASHED,
6631  parse->groupClause,
6632  NIL,
6633  agg_partial_costs,
6634  dNumPartialGroups));
6635  }
6636  }
6637 
6638  if (can_hash && cheapest_partial_path != NULL)
6639  {
6640  Size hashaggtablesize;
6641 
6642  hashaggtablesize =
6643  estimate_hashagg_tablesize(cheapest_partial_path,
6644  agg_partial_costs,
6645  dNumPartialPartialGroups);
6646 
6647  /* Do the same for partial paths. */
6648  if (hashaggtablesize < work_mem * 1024L &&
6649  cheapest_partial_path != NULL)
6650  {
6651  add_partial_path(partially_grouped_rel, (Path *)
6652  create_agg_path(root,
6653  partially_grouped_rel,
6654  cheapest_partial_path,
6655  partially_grouped_rel->reltarget,
6656  AGG_HASHED,
6658  parse->groupClause,
6659  NIL,
6660  agg_partial_costs,
6661  dNumPartialPartialGroups));
6662  }
6663  }
6664 
6665  /*
6666  * If there is an FDW that's responsible for all baserels of the query,
6667  * let it consider adding partially grouped ForeignPaths.
6668  */
6669  if (partially_grouped_rel->fdwroutine &&
6670  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
6671  {
6672  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
6673 
6674  fdwroutine->GetForeignUpperPaths(root,
6676  input_rel, partially_grouped_rel,
6677  extra);
6678  }
6679 
6680  return partially_grouped_rel;
6681 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:204
List * group_pathkeys
Definition: relation.h:276
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
RelOptKind reloptkind
Definition: relation.h:609
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3536
Oid userid
Definition: relation.h:660
AggClauseCosts agg_partial_costs
Definition: relation.h:2373
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:468
bool hasAggs
Definition: parsenodes.h:125
Definition: nodes.h:517
PartitionwiseAggregateType patype
Definition: relation.h:2380
List * partial_pathlist
Definition: relation.h:628
#define MemSet(start, val, len)
Definition: c.h:908
bool useridiscurrent
Definition: relation.h:661
#define GROUPING_CAN_USE_SORT
Definition: relation.h:2333
#define linitial(l)
Definition: pg_list.h:111
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1145
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:2786
struct Path * cheapest_total_path
Definition: relation.h:630
struct FdwRoutine * fdwroutine
Definition: relation.h:663
Relids relids
Definition: relation.h:612
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3649
Oid serverid
Definition: relation.h:659
List * exprs
Definition: relation.h:1008
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
int work_mem
Definition: globals.c:122
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2631
List * pathkeys
Definition: relation.h:1092
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1088
#define GROUPING_CAN_USE_HASH
Definition: relation.h:2334
size_t Size
Definition: c.h:433
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:5081
bool consider_parallel
Definition: relation.h:620
List * groupClause
Definition: parsenodes.h:148
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:762
List * pathlist
Definition: relation.h:626
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2675
AggClauseCosts agg_final_costs
Definition: relation.h:2374
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:623
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ 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 7001 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(), mark_dummy_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().

7009 {
7010  int nparts = input_rel->nparts;
7011  int cnt_parts;
7012  List *grouped_live_children = NIL;
7013  List *partially_grouped_live_children = NIL;
7014  PathTarget *target = grouped_rel->reltarget;
7015 
7018  partially_grouped_rel != NULL);
7019 
7020  /* Add paths for partitionwise aggregation/grouping. */
7021  for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
7022  {
7023  RelOptInfo *child_input_rel = input_rel->part_rels[cnt_parts];
7024  PathTarget *child_target = copy_pathtarget(target);
7025  AppendRelInfo **appinfos;
7026  int nappinfos;
7027  GroupPathExtraData child_extra;
7028  RelOptInfo *child_grouped_rel;
7029  RelOptInfo *child_partially_grouped_rel;
7030 
7031  /* Input child rel must have a path */
7032  Assert(child_input_rel->pathlist != NIL);
7033 
7034  /*
7035  * Copy the given "extra" structure as is and then override the
7036  * members specific to this child.
7037  */
7038  memcpy(&child_extra, extra, sizeof(child_extra));
7039 
7040  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7041  &nappinfos);
7042 
7043  child_target->exprs = (List *)
7045  (Node *) target->exprs,
7046  nappinfos, appinfos);
7047 
7048  /* Translate havingQual and targetList. */
7049  child_extra.havingQual = (Node *)
7051  extra->havingQual,
7052  nappinfos, appinfos);
7053  child_extra.targetList = (List *)
7055  (Node *) extra->targetList,
7056  nappinfos, appinfos);
7057 
7058  /*
7059  * extra->patype was the value computed for our parent rel; patype is
7060  * the value for this relation. For the child, our value is its
7061  * parent rel's value.
7062  */
7063  child_extra.patype = patype;
7064 
7065  /*
7066  * Create grouping relation to hold fully aggregated grouping and/or
7067  * aggregation paths for the child.
7068  */
7069  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7070  child_target,
7071  extra->target_parallel_safe,
7072  child_extra.havingQual);
7073 
7074  /* Ignore empty children. They contribute nothing. */
7075  if (IS_DUMMY_REL(child_input_rel))
7076  {
7077  mark_dummy_rel(child_grouped_rel);
7078 
7079  continue;
7080  }
7081 
7082  /* Create grouping paths for this child relation. */
7083  create_ordinary_grouping_paths(root, child_input_rel,
7084  child_grouped_rel,
7085  agg_costs, gd, &child_extra,
7086  &child_partially_grouped_rel);
7087 
7088  if (child_partially_grouped_rel)
7089  {
7090  partially_grouped_live_children =
7091  lappend(partially_grouped_live_children,
7092  child_partially_grouped_rel);
7093  }
7094 
7095  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7096  {
7097  set_cheapest(child_grouped_rel);
7098  grouped_live_children = lappend(grouped_live_children,
7099  child_grouped_rel);
7100  }
7101 
7102  pfree(appinfos);
7103  }
7104 
7105  /*
7106  * All children can't be dummy at this point. If they are, then the parent
7107  * too marked as dummy.
7108  */
7109  Assert(grouped_live_children != NIL ||
7110  partially_grouped_live_children != NIL);
7111 
7112  /*
7113  * Try to create append paths for partially grouped children. For full
7114  * partitionwise aggregation, we might have paths in the partial_pathlist
7115  * if parallel aggregation is possible. For partial partitionwise
7116  * aggregation, we may have paths in both pathlist and partial_pathlist.
7117  */
7118  if (partially_grouped_rel)
7119  {
7120  add_paths_to_append_rel(root, partially_grouped_rel,
7121  partially_grouped_live_children);
7122 
7123  /*
7124  * We need call set_cheapest, since the finalization step will use the
7125  * cheapest path from the rel.
7126  */
7127  if (partially_grouped_rel->pathlist)
7128  set_cheapest(partially_grouped_rel);
7129  }
7130 
7131  /* If possible, create append paths for fully grouped children. */
7132  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7133  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7134 }
#define NIL
Definition: pg_list.h:69
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:629
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3801
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1377
Definition: nodes.h:517
PartitionwiseAggregateType patype
Definition: relation.h:2380
void pfree(void *pointer)
Definition: mcxt.c:1031
#define IS_DUMMY_REL(r)
Definition: relation.h:1317
int nparts
Definition: relation.h:685
Relids relids
Definition: relation.h:612
List * lappend(List *list, void *datum)
Definition: list.c:128
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: prepunion.c:2047
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: relation.h:1008
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1215
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: prepunion.c:2618
#define Assert(condition)
Definition: c.h:699
struct RelOptInfo ** part_rels
Definition: relation.h:688
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:3939
List * pathlist
Definition: relation.h:626
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:623
bool target_parallel_safe
Definition: relation.h:2377

◆ create_window_paths()

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

Definition at line 4439 of file planner.c.

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

Referenced by grouping_planner().

4447 {
4448  RelOptInfo *window_rel;
4449  ListCell *lc;
4450 
4451  /* For now, do all work in the (WINDOW, NULL) upperrel */
4452  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4453 
4454  /*
4455  * If the input relation is not parallel-safe, then the window relation
4456  * can't be parallel-safe, either. Otherwise, we need to examine the
4457  * target list and active windows for non-parallel-safe constructs.
4458  */
4459  if (input_rel->consider_parallel && output_target_parallel_safe &&
4460  is_parallel_safe(root, (Node *) activeWindows))
4461  window_rel->consider_parallel = true;
4462 
4463  /*
4464  * If the input rel belongs to a single FDW, so does the window rel.
4465  */
4466  window_rel->serverid = input_rel->serverid;
4467  window_rel->userid = input_rel->userid;
4468  window_rel->useridiscurrent = input_rel->useridiscurrent;
4469  window_rel->fdwroutine = input_rel->fdwroutine;
4470 
4471  /*
4472  * Consider computing window functions starting from the existing
4473  * cheapest-total path (which will likely require a sort) as well as any
4474  * existing paths that satisfy root->window_pathkeys (which won't).
4475  */
4476  foreach(lc, input_rel->pathlist)
4477  {
4478  Path *path = (Path *) lfirst(lc);
4479 
4480  if (path == input_rel->cheapest_total_path ||
4483  window_rel,
4484  path,
4485  input_target,
4486  output_target,
4487  tlist,
4488  wflists,
4489  activeWindows);
4490  }
4491 
4492  /*
4493  * If there is an FDW that's responsible for all baserels of the query,
4494  * let it consider adding ForeignPaths.
4495  */
4496  if (window_rel->fdwroutine &&
4497  window_rel->fdwroutine->GetForeignUpperPaths)
4498  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4499  input_rel, window_rel,
4500  NULL);
4501 
4502  /* Let extensions possibly add some more paths */
4504  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4505  input_rel, window_rel, NULL);
4506 
4507  /* Now choose the best path(s) */
4508  set_cheapest(window_rel);
4509 
4510  return window_rel;
4511 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:204
Oid userid
Definition: relation.h:660
Definition: nodes.h:517
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:71
bool useridiscurrent
Definition: relation.h:661
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1088
static void create_one_window_path(PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, List *tlist, WindowFuncLists *wflists, List *activeWindows)
Definition: planner.c:4526
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1145
struct Path * cheapest_total_path
Definition: relation.h:630
struct FdwRoutine * fdwroutine
Definition: relation.h:663
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: relation.h:659
List * window_pathkeys
Definition: relation.h:277
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
List * pathkeys
Definition: relation.h:1092
#define lfirst(lc)
Definition: pg_list.h:106
bool consider_parallel
Definition: relation.h:620
List * pathlist
Definition: relation.h:626

◆ estimate_hashagg_tablesize()

static Size estimate_hashagg_tablesize ( Path path,
const AggClauseCosts agg_costs,
double  dNumGroups 
)
static

Definition at line 3649 of file planner.c.

References hash_agg_entry_size(), MAXALIGN, AggClauseCosts::numAggs, Path::pathtarget, SizeofMinimalTupleHeader, AggClauseCosts::transitionSpace, and PathTarget::width.

Referenced by add_paths_to_grouping_rel(), consider_groupingsets_paths(), and create_partial_grouping_paths().

3651 {
3652  Size hashentrysize;
3653 
3654  /* Estimate per-hash-entry space at tuple width... */
3655  hashentrysize = MAXALIGN(path->pathtarget->width) +
3657 
3658  /* plus space for pass-by-ref transition values... */
3659  hashentrysize += agg_costs->transitionSpace;
3660  /* plus the per-hash-entry overhead */
3661  hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
3662 
3663  /*
3664  * Note that this disregards the effect of fill-factor and growth policy
3665  * of the hash-table. That's probably ok, given default the default
3666  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3667  * "double-in-size" growth policies here.
3668  */
3669  return hashentrysize * dNumGroups;
3670 }
PathTarget * pathtarget
Definition: relation.h:1079
#define SizeofMinimalTupleHeader
Definition: htup_details.h:667
size_t Size
Definition: c.h:433
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:1424
#define MAXALIGN(LEN)
Definition: c.h:652
Size transitionSpace
Definition: relation.h:65

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 5888 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

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

5889 {
5890  Node *result;
5891 
5892  /*
5893  * Convert named-argument function calls, insert default arguments and
5894  * simplify constant subexprs
5895  */
5896  result = eval_const_expressions(NULL, (Node *) expr);
5897 
5898  /* Fill in opfuncid values if missing */
5899  fix_opfuncids(result);
5900 
5901  return (Expr *) result;
5902 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
Definition: nodes.h:517
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2460

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

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

3182 {
3183  int num_sets_raw = list_length(groupingSets);
3184  int num_empty = 0;
3185  int num_sets = 0; /* distinct sets */
3186  int num_chains = 0;
3187  List *result = NIL;
3188  List **results;
3189  List **orig_sets;
3190  Bitmapset **set_masks;
3191  int *chains;
3192  short **adjacency;
3193  short *adjacency_buf;
3195  int i;
3196  int j;
3197  int j_size;
3198  ListCell *lc1 = list_head(groupingSets);
3199  ListCell *lc;
3200 
3201  /*
3202  * Start by stripping out empty sets. The algorithm doesn't require this,
3203  * but the planner currently needs all empty sets to be returned in the
3204  * first list, so we strip them here and add them back after.
3205  */
3206  while (lc1 && lfirst(lc1) == NIL)
3207  {
3208  ++num_empty;
3209  lc1 = lnext(lc1);
3210  }
3211 
3212  /* bail out now if it turns out that all we had were empty sets. */
3213  if (!lc1)
3214  return list_make1(groupingSets);
3215 
3216  /*----------
3217  * We don't strictly need to remove duplicate sets here, but if we don't,
3218  * they tend to become scattered through the result, which is a bit
3219  * confusing (and irritating if we ever decide to optimize them out).
3220  * So we remove them here and add them back after.
3221  *
3222  * For each non-duplicate set, we fill in the following:
3223  *
3224  * orig_sets[i] = list of the original set lists
3225  * set_masks[i] = bitmapset for testing inclusion
3226  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3227  *
3228  * chains[i] will be the result group this set is assigned to.
3229  *
3230  * We index all of these from 1 rather than 0 because it is convenient
3231  * to leave 0 free for the NIL node in the graph algorithm.
3232  *----------
3233  */
3234  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3235  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3236  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3237  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3238 
3239  j_size = 0;
3240  j = 0;
3241  i = 1;
3242 
3243  for_each_cell(lc, lc1)
3244  {
3245  List *candidate = (List *) lfirst(lc);
3246  Bitmapset *candidate_set = NULL;
3247  ListCell *lc2;
3248  int dup_of = 0;
3249 
3250  foreach(lc2, candidate)
3251  {
3252  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3253  }
3254 
3255  /* we can only be a dup if we're the same length as a previous set */
3256  if (j_size == list_length(candidate))
3257  {
3258  int k;
3259 
3260  for (k = j; k < i; ++k)
3261  {
3262  if (bms_equal(set_masks[k], candidate_set))
3263  {
3264  dup_of = k;
3265  break;
3266  }
3267  }
3268  }
3269  else if (j_size < list_length(candidate))
3270  {
3271  j_size = list_length(candidate);
3272  j = i;
3273  }
3274 
3275  if (dup_of > 0)
3276  {
3277  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3278  bms_free(candidate_set);
3279  }
3280  else
3281  {
3282  int k;
3283  int n_adj = 0;
3284 
3285  orig_sets[i] = list_make1(candidate);
3286  set_masks[i] = candidate_set;
3287 
3288  /* fill in adjacency list; no need to compare equal-size sets */
3289 
3290  for (k = j - 1; k > 0; --k)
3291  {
3292  if (bms_is_subset(set_masks[k], candidate_set))
3293  adjacency_buf[++n_adj] = k;
3294  }
3295 
3296  if (n_adj > 0)
3297  {
3298  adjacency_buf[0] = n_adj;
3299  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3300  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3301  }
3302  else
3303  adjacency[i] = NULL;
3304 
3305  ++i;
3306  }
3307  }
3308 
3309  num_sets = i - 1;
3310 
3311  /*
3312  * Apply the graph matching algorithm to do the work.
3313  */
3314  state = BipartiteMatch(num_sets, num_sets, adjacency);
3315 
3316  /*
3317  * Now, the state->pair* fields have the info we need to assign sets to
3318  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3319  * pair_vu[v] = u (both will be true, but we check both so that we can do
3320  * it in one pass)
3321  */
3322  chains = palloc0((num_sets + 1) * sizeof(int));
3323 
3324  for (i = 1; i <= num_sets; ++i)
3325  {
3326  int u = state->pair_vu[i];
3327  int v = state->pair_uv[i];
3328 
3329  if (u > 0 && u < i)
3330  chains[i] = chains[u];
3331  else if (v > 0 && v < i)
3332  chains[i] = chains[v];
3333  else
3334  chains[i] = ++num_chains;
3335  }
3336 
3337  /* build result lists. */
3338  results = palloc0((num_chains + 1) * sizeof(List *));
3339 
3340  for (i = 1; i <= num_sets; ++i)
3341  {
3342  int c = chains[i];
3343 
3344  Assert(c > 0);
3345 
3346  results[c] = list_concat(results[c], orig_sets[i]);
3347  }
3348 
3349  /* push any empty sets back on the first list. */
3350  while (num_empty-- > 0)
3351  results[1] = lcons(NIL, results[1]);
3352 
3353  /* make result list */
3354  for (i = 1; i <= num_chains; ++i)
3355  result = lappend(result, results[i]);
3356 
3357  /*
3358  * Free all the things.
3359  *
3360  * (This is over-fussy for small sets but for large sets we could have
3361  * tied up a nontrivial amount of memory.)
3362  */
3363  BipartiteMatchFree(state);
3364  pfree(results);
3365  pfree(chains);
3366  for (i = 1; i <= num_sets; ++i)
3367  if (adjacency[i])
3368  pfree(adjacency[i]);
3369  pfree(adjacency);
3370  pfree(adjacency_buf);
3371  pfree(orig_sets);
3372  for (i = 1; i <= num_sets; ++i)
3373  bms_free(set_masks[i]);
3374  pfree(set_masks);
3375 
3376  return result;
3377 }
#define NIL
Definition: pg_list.h:69
List * list_concat(List *list1, List *list2)
Definition: list.c:321
void BipartiteMatchFree(BipartiteMatchState *state)
#define list_make1(x1)
Definition: pg_list.h:139
void pfree(void *pointer)
Definition: mcxt.c:1031
#define lfirst_int(lc)
Definition: pg_list.h:107
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:374
char * c
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc0(Size size)
Definition: mcxt.c:955
BipartiteMatchState * BipartiteMatch(int u_size, int v_size, short **adjacency)
List * lcons(void *datum, List *list)
Definition: list.c:259
void bms_free(Bitmapset *a)
Definition: bitmapset.c:267
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Definition: regguts.h:298
static int list_length(const List *l)
Definition: pg_list.h:89
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
void * palloc(Size size)
Definition: mcxt.c:924
int i
Definition: pg_list.h:45
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:153

◆ gather_grouping_paths()

static void gather_grouping_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 6697 of file planner.c.

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

Referenced by add_paths_to_grouping_rel(), and create_ordinary_grouping_paths().

6698 {
6699  Path *cheapest_partial_path;
6700 
6701  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
6702  generate_gather_paths(root, rel, true);
6703 
6704  /* Try cheapest partial path + explicit Sort + Gather Merge. */
6705  cheapest_partial_path = linitial(rel->partial_pathlist);
6707  cheapest_partial_path->pathkeys))
6708  {
6709  Path *path;
6710  double total_groups;
6711 
6712  total_groups =
6713  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
6714  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
6715  root->group_pathkeys,
6716  -1.0);
6717  path = (Path *)
6719  rel,
6720  path,
6721  rel->reltarget,
6722  root->group_pathkeys,
6723  NULL,
6724  &total_groups);
6725 
6726  add_path(rel, path);
6727  }
6728 }
List * group_pathkeys
Definition: relation.h:276
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
int parallel_workers
Definition: relation.h:1085
List * partial_pathlist
Definition: relation.h:628
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2546
#define linitial(l)
Definition: pg_list.h:111
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1741
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2631
List * pathkeys
Definition: relation.h:1092
double rows
Definition: relation.h:1088
struct PathTarget * reltarget
Definition: relation.h:623

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

5736 {
5737  Path *best_path = rel->cheapest_total_path;
5738  ListCell *l;
5739 
5740  /* If all tuples will be retrieved, just return the cheapest-total path */
5741  if (tuple_fraction <= 0.0)
5742  return best_path;
5743 
5744  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5745  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5746  tuple_fraction /= best_path->rows;
5747 
5748  foreach(l, rel->pathlist)
5749  {
5750  Path *path = (Path *) lfirst(l);
5751 
5752  if (path == rel->cheapest_total_path ||
5753  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5754  continue;
5755 
5756  best_path = path;
5757  }
5758 
5759  return best_path;
5760 }
struct Path * cheapest_total_path
Definition: relation.h:630
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1088
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: relation.h:626

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

3540 {
3541  Query *parse = root->parse;
3542  double dNumGroups;
3543 
3544  if (parse->groupClause)
3545  {
3546  List *groupExprs;
3547 
3548  if (parse->groupingSets)
3549  {
3550  /* Add up the estimates for each grouping set */
3551  ListCell *lc;
3552  ListCell *lc2;
3553 
3554  Assert(gd); /* keep Coverity happy */
3555 
3556  dNumGroups = 0;
3557 
3558  foreach(lc, gd->rollups)
3559  {
3560  RollupData *rollup = lfirst_node(RollupData, lc);
3561  ListCell *lc;
3562 
3563  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3564  target_list);
3565 
3566  rollup->numGroups = 0.0;
3567 
3568  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3569  {
3570  List *gset = (List *) lfirst(lc);
3572  double numGroups = estimate_num_groups(root,
3573  groupExprs,
3574  path_rows,
3575  &gset);
3576 
3577  gs->numGroups = numGroups;
3578  rollup->numGroups += numGroups;
3579  }
3580 
3581  dNumGroups += rollup->numGroups;
3582  }
3583 
3584  if (gd->hash_sets_idx)
3585  {
3586  ListCell *lc;
3587 
3588  gd->dNumHashGroups = 0;
3589 
3590  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3591  target_list);
3592 
3593  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3594  {
3595  List *gset = (List *) lfirst(lc);
3597  double numGroups = estimate_num_groups(root,
3598  groupExprs,
3599  path_rows,
3600  &gset);
3601 
3602  gs->numGroups = numGroups;
3603  gd->dNumHashGroups += numGroups;
3604  }
3605 
3606  dNumGroups += gd->dNumHashGroups;
3607  }
3608  }
3609  else
3610  {
3611  /* Plain GROUP BY */
3612  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3613  target_list);
3614 
3615  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3616  NULL);
3617  }
3618  }
3619  else if (parse->groupingSets)
3620  {
3621  /* Empty grouping sets ... one result row for each one */
3622  dNumGroups = list_length(parse->groupingSets);
3623  }
3624  else if (parse->hasAggs || root->hasHavingQual)
3625  {
3626  /* Plain aggregation, one result row */
3627  dNumGroups = 1;
3628  }
3629  else
3630  {
3631  /* Not grouping */
3632  dNumGroups = 1;
3633  }
3634 
3635  return dNumGroups;
3636 }
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3419
Query * parse
Definition: relation.h:169
List * groupClause
Definition: relation.h:1613
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
bool hasAggs
Definition: parsenodes.h:125
List * hash_sets_idx
Definition: planner.c:104
List * groupingSets
Definition: parsenodes.h:150
double dNumHashGroups
Definition: planner.c:105
double numGroups
Definition: relation.h:1616
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
List * unsortable_sets
Definition: planner.c:109
List * groupClause
Definition: parsenodes.h:148
double numGroups
Definition: relation.h:1607
bool hasHavingQual
Definition: relation.h:318
Definition: pg_list.h:45
List * gsets_data
Definition: relation.h:1615
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1614

◆ group_by_has_partkey()

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

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

7146 {
7147  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7148  int cnt = 0;
7149  int partnatts;
7150 
7151  /* Input relation should be partitioned. */
7152  Assert(input_rel->part_scheme);
7153 
7154  /* Rule out early, if there are no partition keys present. */
7155  if (!input_rel->partexprs)
7156  return false;
7157 
7158  partnatts = input_rel->part_scheme->partnatts;
7159 
7160  for (cnt = 0; cnt < partnatts; cnt++)
7161  {
7162  List *partexprs = input_rel->partexprs[cnt];
7163  ListCell *lc;
7164  bool found = false;
7165 
7166  foreach(lc, partexprs)
7167  {
7168  Expr *partexpr = lfirst(lc);
7169 
7170  if (list_member(groupexprs, partexpr))
7171  {
7172  found = true;
7173  break;
7174  }
7175  }
7176 
7177  /*
7178  * If none of the partition key expressions match with any of the
7179  * GROUP BY expression, return false.
7180  */
7181  if (!found)
7182  return false;
7183  }
7184 
7185  return true;
7186 }
List ** partexprs
Definition: relation.h:690
bool list_member(const List *list, const void *datum)
Definition: list.c:444
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
PartitionScheme part_scheme
Definition: relation.h:684
Definition: pg_list.h:45

◆ grouping_planner()

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

Definition at line 1665 of file planner.c.

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

Referenced by inheritance_planner(), and subquery_planner().

1667 {
1668  Query *parse = root->parse;
1669  List *tlist;
1670  int64 offset_est = 0;
1671  int64 count_est = 0;
1672  double limit_tuples = -1.0;
1673  bool have_postponed_srfs = false;
1674  PathTarget *final_target;
1675  List *final_targets;
1676  List *final_targets_contain_srfs;
1677  bool final_target_parallel_safe;
1678  RelOptInfo *current_rel;
1679  RelOptInfo *final_rel;
1680  ListCell *lc;
1681 
1682  /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1683  if (parse->limitCount || parse->limitOffset)
1684  {
1685  tuple_fraction = preprocess_limit(root, tuple_fraction,
1686  &offset_est, &count_est);
1687 
1688  /*
1689  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1690  * estimate the effects of using a bounded sort.
1691  */
1692  if (count_est > 0 && offset_est >= 0)
1693  limit_tuples = (double) count_est + (double) offset_est;
1694  }
1695 
1696  /* Make tuple_fraction accessible to lower-level routines */
1697  root->tuple_fraction = tuple_fraction;
1698 
1699  if (parse->setOperations)
1700  {
1701  /*
1702  * If there's a top-level ORDER BY, assume we have to fetch all the
1703  * tuples. This might be too simplistic given all the hackery below
1704  * to possibly avoid the sort; but the odds of accurate estimates here
1705  * are pretty low anyway. XXX try to get rid of this in favor of
1706  * letting plan_set_operations generate both fast-start and
1707  * cheapest-total paths.
1708  */
1709  if (parse->sortClause)
1710  root->tuple_fraction = 0.0;
1711 
1712  /*
1713  * Construct Paths for set operations. The results will not need any
1714  * work except perhaps a top-level sort and/or LIMIT. Note that any
1715  * special work for recursive unions is the responsibility of
1716  * plan_set_operations.
1717  */
1718  current_rel = plan_set_operations(root);
1719 
1720  /*
1721  * We should not need to call preprocess_targetlist, since we must be
1722  * in a SELECT query node. Instead, use the targetlist returned by
1723  * plan_set_operations (since this tells whether it returned any
1724  * resjunk columns!), and transfer any sort key information from the
1725  * original tlist.
1726  */
1727  Assert(parse->commandType == CMD_SELECT);
1728 
1729  tlist = root->processed_tlist; /* from plan_set_operations */
1730 
1731  /* for safety, copy processed_tlist instead of modifying in-place */
1732  tlist = postprocess_setop_tlist(copyObject(tlist), parse->targetList);
1733 
1734  /* Save aside the final decorated tlist */
1735  root->processed_tlist = tlist;
1736 
1737  /* Also extract the PathTarget form of the setop result tlist */
1738  final_target = current_rel->cheapest_total_path->pathtarget;
1739 
1740  /* And check whether it's parallel safe */
1741  final_target_parallel_safe =
1742  is_parallel_safe(root, (Node *) final_target->exprs);
1743 
1744  /* The setop result tlist couldn't contain any SRFs */
1745  Assert(!parse->hasTargetSRFs);
1746  final_targets = final_targets_contain_srfs = NIL;
1747 
1748  /*
1749  * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1750  * checked already, but let's make sure).
1751  */
1752  if (parse->rowMarks)
1753  ereport(ERROR,
1754  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1755  /*------
1756  translator: %s is a SQL row locking clause such as FOR UPDATE */
1757  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1759  parse->rowMarks)->strength))));
1760 
1761  /*
1762  * Calculate pathkeys that represent result ordering requirements
1763  */
1764  Assert(parse->distinctClause == NIL);
1766  parse->sortClause,
1767  tlist);
1768  }
1769  else
1770  {
1771  /* No set operations, do regular planning */
1772  PathTarget *sort_input_target;
1773  List *sort_input_targets;
1774  List *sort_input_targets_contain_srfs;
1775  bool sort_input_target_parallel_safe;
1776  PathTarget *grouping_target;
1777  List *grouping_targets;
1778  List *grouping_targets_contain_srfs;
1779  bool grouping_target_parallel_safe;
1780  PathTarget *scanjoin_target;
1781  List *scanjoin_targets;
1782  List *scanjoin_targets_contain_srfs;
1783  bool scanjoin_target_parallel_safe;
1784  bool scanjoin_target_same_exprs;
1785  bool have_grouping;
1786  AggClauseCosts agg_costs;
1787  WindowFuncLists *wflists = NULL;
1788  List *activeWindows = NIL;
1789  grouping_sets_data *gset_data = NULL;
1790  standard_qp_extra qp_extra;
1791 
1792  /* A recursive query should always have setOperations */
1793  Assert(!root->hasRecursion);
1794 
1795  /* Preprocess grouping sets and GROUP BY clause, if any */
1796  if (parse->groupingSets)
1797  {
1798  gset_data = preprocess_grouping_sets(root);
1799  }
1800  else
1801  {
1802  /* Preprocess regular GROUP BY clause, if any */
1803  if (parse->groupClause)
1804  parse->groupClause = preprocess_groupclause(root, NIL);
1805  }
1806 
1807  /* Preprocess targetlist */
1808  tlist = preprocess_targetlist(root);
1809 
1810  /*
1811  * We are now done hacking up the query's targetlist. Most of the
1812  * remaining planning work will be done with the PathTarget
1813  * representation of tlists, but save aside the full representation so
1814  * that we can transfer its decoration (resnames etc) to the topmost
1815  * tlist of the finished Plan.
1816  */
1817  root->processed_tlist = tlist;
1818 
1819  /*
1820  * Collect statistics about aggregates for estimating costs, and mark
1821  * all the aggregates with resolved aggtranstypes. We must do this
1822  * before slicing and dicing the tlist into various pathtargets, else
1823  * some copies of the Aggref nodes might escape being marked with the
1824  * correct transtypes.
1825  *
1826  * Note: currently, we do not detect duplicate aggregates here. This
1827  * may result in somewhat-overestimated cost, which is fine for our
1828  * purposes since all Paths will get charged the same. But at some
1829  * point we might wish to do that detection in the planner, rather
1830  * than during executor startup.
1831  */
1832  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
1833  if (parse->hasAggs)
1834  {
1835  get_agg_clause_costs(root, (Node *) tlist, AGGSPLIT_SIMPLE,
1836  &agg_costs);
1838  &agg_costs);
1839  }
1840 
1841  /*
1842  * Locate any window functions in the tlist. (We don't need to look
1843  * anywhere else, since expressions used in ORDER BY will be in there
1844  * too.) Note that they could all have been eliminated by constant
1845  * folding, in which case we don't need to do any more work.
1846  */
1847  if (parse->hasWindowFuncs)
1848  {
1849  wflists = find_window_functions((Node *) tlist,
1850  list_length(parse->windowClause));
1851  if (wflists->numWindowFuncs > 0)
1852  activeWindows = select_active_windows(root, wflists);
1853  else
1854  parse->hasWindowFuncs = false;
1855  }
1856 
1857  /*
1858  * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1859  * adding logic between here and the query_planner() call. Anything
1860  * that is needed in MIN/MAX-optimizable cases will have to be
1861  * duplicated in planagg.c.
1862  */
1863  if (parse->hasAggs)
1864  preprocess_minmax_aggregates(root, tlist);
1865 
1866  /*
1867  * Figure out whether there's a hard limit on the number of rows that
1868  * query_planner's result subplan needs to return. Even if we know a
1869  * hard limit overall, it doesn't apply if the query has any
1870  * grouping/aggregation operations, or SRFs in the tlist.
1871  */
1872  if (parse->groupClause ||
1873  parse->groupingSets ||
1874  parse->distinctClause ||
1875  parse->hasAggs ||
1876  parse->hasWindowFuncs ||
1877  parse->hasTargetSRFs ||
1878  root->hasHavingQual)
1879  root->limit_tuples = -1.0;
1880  else
1881  root->limit_tuples = limit_tuples;
1882 
1883  /* Set up data needed by standard_qp_callback */
1884  qp_extra.tlist = tlist;
1885  qp_extra.activeWindows = activeWindows;
1886  qp_extra.groupClause = (gset_data
1887  ? (gset_data->rollups ? linitial_node(RollupData, gset_data->rollups)->groupClause : NIL)
1888  : parse->groupClause);
1889 
1890  /*
1891  * Generate the best unsorted and presorted paths for the scan/join
1892  * portion of this Query, ie the processing represented by the
1893  * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1894  * We also generate (in standard_qp_callback) pathkey representations
1895  * of the query's sort clause, distinct clause, etc.
1896  */
1897  current_rel = query_planner(root, tlist,
1898  standard_qp_callback, &qp_extra);
1899 
1900  /*
1901  * Convert the query's result tlist into PathTarget format.
1902  *
1903  * Note: it's desirable to not do this till after query_planner(),
1904  * because the target width estimates can use per-Var width numbers
1905  * that were obtained within query_planner().
1906  */
1907  final_target = create_pathtarget(root, tlist);
1908  final_target_parallel_safe =
1909  is_parallel_safe(root, (Node *) final_target->exprs);
1910 
1911  /*
1912  * If ORDER BY was given, consider whether we should use a post-sort
1913  * projection, and compute the adjusted target for preceding steps if
1914  * so.
1915  */
1916  if (parse->sortClause)
1917  {
1918  sort_input_target = make_sort_input_target(root,
1919  final_target,
1920  &have_postponed_srfs);
1921  sort_input_target_parallel_safe =
1922  is_parallel_safe(root, (Node *) sort_input_target->exprs);
1923  }
1924  else
1925  {
1926  sort_input_target = final_target;
1927  sort_input_target_parallel_safe = final_target_parallel_safe;
1928  }
1929 
1930  /*
1931  * If we have window functions to deal with, the output from any
1932  * grouping step needs to be what the window functions want;
1933  * otherwise, it should be sort_input_target.
1934  */
1935  if (activeWindows)
1936  {
1937  grouping_target = make_window_input_target(root,
1938  final_target,
1939  activeWindows);
1940  grouping_target_parallel_safe =
1941  is_parallel_safe(root, (Node *) grouping_target->exprs);
1942  }
1943  else
1944  {
1945  grouping_target = sort_input_target;
1946  grouping_target_parallel_safe = sort_input_target_parallel_safe;
1947  }
1948 
1949  /*
1950  * If we have grouping or aggregation to do, the topmost scan/join
1951  * plan node must emit what the grouping step wants; otherwise, it
1952  * should emit grouping_target.
1953  */
1954  have_grouping = (parse->groupClause || parse->groupingSets ||
1955  parse->hasAggs || root->hasHavingQual);
1956  if (have_grouping)
1957  {
1958  scanjoin_target = make_group_input_target(root, final_target);
1959  scanjoin_target_parallel_safe =
1960  is_parallel_safe(root, (Node *) grouping_target->exprs);
1961  }
1962  else
1963  {
1964  scanjoin_target = grouping_target;
1965  scanjoin_target_parallel_safe = grouping_target_parallel_safe;
1966  }
1967 
1968  /*
1969  * If there are any SRFs in the targetlist, we must separate each of
1970  * these PathTargets into SRF-computing and SRF-free targets. Replace
1971  * each of the named targets with a SRF-free version, and remember the
1972  * list of additional projection steps we need to add afterwards.
1973  */
1974  if (parse->hasTargetSRFs)
1975  {
1976  /* final_target doesn't recompute any SRFs in sort_input_target */
1977  split_pathtarget_at_srfs(root, final_target, sort_input_target,
1978  &final_targets,
1979  &final_targets_contain_srfs);
1980  final_target = linitial_node(PathTarget, final_targets);
1981  Assert(!linitial_int(final_targets_contain_srfs));
1982  /* likewise for sort_input_target vs. grouping_target */
1983  split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
1984  &sort_input_targets,
1985  &sort_input_targets_contain_srfs);
1986  sort_input_target = linitial_node(PathTarget, sort_input_targets);
1987  Assert(!linitial_int(sort_input_targets_contain_srfs));
1988  /* likewise for grouping_target vs. scanjoin_target */
1989  split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
1990  &grouping_targets,
1991  &grouping_targets_contain_srfs);
1992  grouping_target = linitial_node(PathTarget, grouping_targets);
1993  Assert(!linitial_int(grouping_targets_contain_srfs));
1994  /* scanjoin_target will not have any SRFs precomputed for it */
1995  split_pathtarget_at_srfs(root, scanjoin_target, NULL,
1996  &scanjoin_targets,
1997  &scanjoin_targets_contain_srfs);
1998  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
1999  Assert(!linitial_int(scanjoin_targets_contain_srfs));
2000  }
2001  else
2002  {
2003  /* initialize lists; for most of these, dummy values are OK */
2004  final_targets = final_targets_contain_srfs = NIL;
2005  sort_input_targets = sort_input_targets_contain_srfs = NIL;
2006  grouping_targets = grouping_targets_contain_srfs = NIL;
2007  scanjoin_targets = list_make1(scanjoin_target);
2008  scanjoin_targets_contain_srfs = NIL;
2009  }
2010 
2011  /* Apply scan/join target. */
2012  scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
2013  && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
2014  apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
2015  scanjoin_targets_contain_srfs,
2016  scanjoin_target_parallel_safe,
2017  scanjoin_target_same_exprs);
2018 
2019  /*
2020  * Save the various upper-rel PathTargets we just computed into
2021  * root->upper_targets[]. The core code doesn't use this, but it
2022  * provides a convenient place for extensions to get at the info. For
2023  * consistency, we save all the intermediate targets, even though some
2024  * of the corresponding upperrels might not be needed for this query.
2025  */
2026  root->upper_targets[UPPERREL_FINAL] = final_target;
2027  root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
2028  root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
2029 
2030  /*
2031  * If we have grouping and/or aggregation, consider ways to implement
2032  * that. We build a new upperrel representing the output of this
2033  * phase.
2034  */
2035  if (have_grouping)
2036  {
2037  current_rel = create_grouping_paths(root,
2038  current_rel,
2039  grouping_target,
2040  grouping_target_parallel_safe,
2041  &agg_costs,
2042  gset_data);
2043  /* Fix things up if grouping_target contains SRFs */
2044  if (parse->hasTargetSRFs)
2045  adjust_paths_for_srfs(root, current_rel,
2046  grouping_targets,
2047  grouping_targets_contain_srfs);
2048  }
2049 
2050  /*
2051  * If we have window functions, consider ways to implement those. We
2052  * build a new upperrel representing the output of this phase.
2053  */
2054  if (activeWindows)
2055  {
2056  current_rel = create_window_paths(root,
2057  current_rel,
2058  grouping_target,
2059  sort_input_target,
2060  sort_input_target_parallel_safe,
2061  tlist,
2062  wflists,
2063  activeWindows);
2064  /* Fix things up if sort_input_target contains SRFs */
2065  if (parse->hasTargetSRFs)
2066  adjust_paths_for_srfs(root, current_rel,
2067  sort_input_targets,
2068  sort_input_targets_contain_srfs);
2069  }
2070 
2071  /*
2072  * If there is a DISTINCT clause, consider ways to implement that. We
2073  * build a new upperrel representing the output of this phase.
2074  */
2075  if (parse->distinctClause)
2076  {
2077  current_rel = create_distinct_paths(root,
2078  current_rel);
2079  }
2080  } /* end of if (setOperations) */
2081 
2082  /*
2083  * If ORDER BY was given, consider ways to implement that, and generate a
2084  * new upperrel containing only paths that emit the correct ordering and
2085  * project the correct final_target. We can apply the original
2086  * limit_tuples limit in sort costing here, but only if there are no
2087  * postponed SRFs.
2088  */
2089  if (parse->sortClause)
2090  {
2091  current_rel = create_ordered_paths(root,
2092  current_rel,
2093  final_target,
2094  final_target_parallel_safe,
2095  have_postponed_srfs ? -1.0 :
2096  limit_tuples);
2097  /* Fix things up if final_target contains SRFs */
2098  if (parse->hasTargetSRFs)
2099  adjust_paths_for_srfs(root, current_rel,
2100  final_targets,
2101  final_targets_contain_srfs);
2102  }
2103 
2104  /*
2105  * Now we are prepared to build the final-output upperrel.
2106  */
2107  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
2108 
2109  /*
2110  * If the input rel is marked consider_parallel and there's nothing that's
2111  * not parallel-safe in the LIMIT clause, then the final_rel can be marked
2112  * consider_parallel as well. Note that if the query has rowMarks or is
2113  * not a SELECT, consider_parallel will be false for every relation in the
2114  * query.
2115  */
2116  if (current_rel->consider_parallel &&
2117  is_parallel_safe(root, parse->limitOffset) &&
2118  is_parallel_safe(root, parse->limitCount))
2119  final_rel->consider_parallel = true;
2120 
2121  /*
2122  * If the current_rel belongs to a single FDW, so does the final_rel.
2123  */
2124  final_rel->serverid = current_rel->serverid;
2125  final_rel->userid = current_rel->userid;
2126  final_rel->useridiscurrent = current_rel->useridiscurrent;
2127  final_rel->fdwroutine = current_rel->fdwroutine;
2128 
2129  /*
2130  * Generate paths for the final_rel. Insert all surviving paths, with
2131  * LockRows, Limit, and/or ModifyTable steps added if needed.
2132  */
2133  foreach(lc, current_rel->pathlist)
2134  {
2135  Path *path = (Path *) lfirst(lc);
2136 
2137  /*
2138  * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
2139  * (Note: we intentionally test parse->rowMarks not root->rowMarks
2140  * here. If there are only non-locking rowmarks, they should be
2141  * handled by the ModifyTable node instead. However, root->rowMarks
2142  * is what goes into the LockRows node.)
2143  */
2144  if (parse->rowMarks)
2145  {
2146  path = (Path *) create_lockrows_path(root, final_rel, path,
2147  root->rowMarks,
2148  SS_assign_special_param(root));
2149  }
2150 
2151  /*
2152  * If there is a LIMIT/OFFSET clause, add the LIMIT node.
2153  */
2154  if (limit_needed(parse))
2155  {
2156  path = (Path *) create_limit_path(root, final_rel, path,
2157  parse->limitOffset,
2158  parse->limitCount,
2159  offset_est, count_est);
2160  }
2161 
2162  /*
2163  * If this is an INSERT/UPDATE/DELETE, and we're not being called from
2164  * inheritance_planner, add the ModifyTable node.
2165  */
2166  if (parse->commandType != CMD_SELECT && !inheritance_update)
2167  {
2168  List *withCheckOptionLists;
2169  List *returningLists;
2170  List *rowMarks;
2171 
2172  /*
2173  * Set up the WITH CHECK OPTION and RETURNING lists-of-lists, if
2174  * needed.
2175  */
2176  if (parse->withCheckOptions)
2177  withCheckOptionLists = list_make1(parse->withCheckOptions);
2178  else
2179  withCheckOptionLists = NIL;
2180 
2181  if (parse->returningList)
2182  returningLists = list_make1(parse->returningList);
2183  else
2184  returningLists = NIL;
2185 
2186  /*
2187  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
2188  * will have dealt with fetching non-locked marked rows, else we
2189  * need to have ModifyTable do that.
2190  */
2191  if (parse->rowMarks)
2192  rowMarks = NIL;
2193  else
2194  rowMarks = root->rowMarks;
2195 
2196  path = (Path *)
2197  create_modifytable_path(root, final_rel,
2198  parse->commandType,
2199  parse->canSetTag,
2200  parse->resultRelation,
2201  NIL,
2202  false,
2204  list_make1(path),
2205  list_make1(root),
2206  withCheckOptionLists,
2207  returningLists,
2208  rowMarks,
2209  parse->onConflict,
2210  SS_assign_special_param(root));
2211  }
2212 
2213  /* And shove it into final_rel */
2214  add_path(final_rel, path);
2215  }
2216 
2217  /*
2218  * Generate partial paths for final_rel, too, if outer query levels might
2219  * be able to make use of them.
2220  */
2221  if (final_rel->consider_parallel && root->query_level > 1 &&
2222  !limit_needed(parse))
2223  {
2224  Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
2225  foreach(lc, current_rel->partial_pathlist)
2226  {
2227  Path *partial_path = (Path *) lfirst(lc);
2228 
2229  add_partial_path(final_rel, partial_path);
2230  }
2231  }
2232 
2233  /*
2234  * If there is an FDW that's responsible for all baserels of the query,
2235  * let it consider adding ForeignPaths.
2236  */
2237  if (final_rel->fdwroutine &&
2238  final_rel->fdwroutine->GetForeignUpperPaths)
2240  current_rel, final_rel,
2241  NULL);
2242 
2243  /* Let extensions possibly add some more paths */
2245  (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2246  current_rel, final_rel, NULL);
2247 
2248  /* Note: currently, we leave it to callers to do set_cheapest() */
2249 }
RelOptInfo * plan_set_operations(PlannerInfo *root)
Definition: prepunion.c:142
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:204
Node * limitOffset
Definition: parsenodes.h:160
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:268
static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
Definition: planner.c:2679
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:6779
PathTarget * pathtarget
Definition: relation.h:1079
Query * parse
Definition: relation.h:169
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:2619
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * sortClause
Definition: parsenodes.h:158
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3252
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
OnConflictExpr * onConflict
Definition: parsenodes.h:144
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:874
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:3078
RelOptInfo * query_planner(PlannerInfo *root, List *tlist, query_pathkeys_callback qp_callback, void *qp_extra)
Definition: planmain.c:54
Oid userid
Definition: relation.h:660
List * withCheckOptions
Definition: parsenodes.h:171
void split_pathtarget_at_srfs(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition: tlist.c:840
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:468
bool hasAggs
Definition: parsenodes.h:125
int resultRelation
Definition: parsenodes.h:122
int numWindowFuncs
Definition: clauses.h:25
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition: clauses.c:741
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
List * partial_pathlist
Definition: relation.h:628
static RelOptInfo * create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel)
Definition: planner.c:4621
#define MemSet(start, val, len)
Definition: c.h:908
List * tlist
Definition: planner.c:92
static PathTarget * make_group_input_target(PlannerInfo *root, PathTarget *final_target)
Definition: planner.c:4994
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:71
bool useridiscurrent
Definition: relation.h:661
void preprocess_minmax_aggregates(PlannerInfo *root, List *tlist)
Definition: planagg.c:75
List * rowMarks
Definition: parsenodes.h:163
#define linitial_node(type, l)
Definition: pg_list.h:114
LimitPath * create_limit_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, Node *limitOffset, Node *limitCount, int64 offset_est, int64 count_est)
Definition: pathnode.c:3415
bool hasRecursion
Definition: relation.h:321
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
static List * postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
Definition: planner.c:5219
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:5778
#define list_make1(x1)
Definition: pg_list.h:139
#define linitial_int(l)
Definition: pg_list.h:112
static RelOptInfo * create_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, const AggClauseCosts *agg_costs, grouping_sets_data *gd)
Definition: planner.c:3691
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, bool partColsUpdated, List *resultRelations, List *subpaths, List *subroots, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: pathnode.c:3313
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1088
double tuple_fraction
Definition: relation.h:306
List * distinctClause
Definition: parsenodes.h:156
#define ERROR
Definition: elog.h:43
static bool limit_needed(Query *parse)
Definition: planner.c:2864
List * preprocess_targetlist(PlannerInfo *root)
Definition: preptlist.c:70
double limit_tuples
Definition: relation.h:307
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1145
struct Path * cheapest_total_path
Definition: relation.h:630
Node * limitCount
Definition: parsenodes.h:161
static PathTarget * make_window_input_target(PlannerInfo *root, PathTarget *final_target, List *activeWindows)
Definition: planner.c:5349
struct FdwRoutine * fdwroutine
Definition: relation.h:663
static void standard_qp_callback(PlannerInfo *root, void *extra)
Definition: planner.c:3446
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
static RelOptInfo * create_window_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, List *tlist, WindowFuncLists *wflists, List *activeWindows)
Definition: planner.c:4439
static grouping_sets_data * preprocess_grouping_sets(PlannerInfo *root)
Definition: planner.c:2258
List * returningList
Definition: parsenodes.h:146
#define list_make1_int(x1)
Definition: pg_list.h:145
#define ereport(elevel, rest)
Definition: elog.h:122
List * sort_pathkeys
Definition: relation.h:279
Oid serverid
Definition: relation.h:659
List * exprs
Definition: relation.h:1008
static RelOptInfo * create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
Definition: planner.c:4833
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
List * groupClause
Definition: planner.c:94
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:126
bool canSetTag
Definition: parsenodes.h:118
static int list_length(const List *l)
Definition: pg_list.h:89
bool consider_parallel
Definition: relation.h:620
Index query_level
Definition: relation.h:173
List * activeWindows
Definition: planner.c:93
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:797
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:762
static List * select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
Definition: planner.c:5252
bool hasHavingQual
Definition: relation.h:318
List * pathlist
Definition: relation.h:626
#define copyObject(obj)
Definition: nodes.h:630
Node * havingQual
Definition: parsenodes.h:152
List * processed_tlist
Definition: relation.h:296
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:623
static PathTarget * make_sort_input_target(PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
Definition: planner.c:5564
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: relation.h:290

◆ inheritance_planner()

static void inheritance_planner ( PlannerInfo root)
static

Definition at line 1156 of file planner.c.

References add_path(), adjust_appendrel_attrs(), PlannerInfo::append_rel_list, Assert, bms_add_member(), bms_is_member(), bms_make_singleton(), bms_next_member(), bms_overlap(), Query::canSetTag, ChangeVarNodes(), RelOptInfo::cheapest_total_path, AppendRelInfo::child_relid, CMD_INSERT, Query::commandType, copyObject, create_modifytable_path(), fetch_upper_rel(), grouping_planner(), i, RangeTblEntry::inh, INHKIND_INHERITED, INHKIND_PARTITIONED, PlannerInfo::inhTargetKind, PlannerInfo::init_plans, IS_DUMMY_PATH, PlannerInfo::join_info_list, lappend(), lappend_int(), lfirst_node, list_concat(), list_copy_tail(), list_length(), makeNode, NIL, Query::onConflict, palloc0(), AppendRelInfo::parent_relid, parse(), PlannerInfo::parse, PlannerInfo::partColsUpdated, PlannerInfo::placeholder_list, pull_varnos(), RangeTblEntry::relkind, Query::resultRelation, Query::returningList, Query::rowMarks, PlannerInfo::rowMarks, rt_fetch, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblEntry::securityQuals, set_cheapest(), set_dummy_rel_pathlist(), PlannerInfo::simple_rel_array, PlannerInfo::simple_rel_array_size, PlannerInfo::simple_rte_array, SS_assign_special_param(), subpath(), AppendRelInfo::translated_vars, UPPERREL_FINAL, and Query::withCheckOptions.

Referenced by subquery_planner().

1157 {
1158  Query *parse = root->parse;
1159  int top_parentRTindex = parse->resultRelation;
1160  Bitmapset *subqueryRTindexes;
1161  Bitmapset *modifiableARIindexes;
1162  int nominalRelation = -1;
1163  List *final_rtable = NIL;
1164  int save_rel_array_size = 0;
1165  RelOptInfo **save_rel_array = NULL;
1166  List *subpaths = NIL;
1167  List *subroots = NIL;
1168  List *resultRelations = NIL;
1169  List *withCheckOptionLists = NIL;
1170  List *returningLists = NIL;
1171  List *rowMarks;
1172  RelOptInfo *final_rel;
1173  ListCell *lc;
1174  Index rti;
1175  RangeTblEntry *parent_rte;
1176  Relids partitioned_relids = NULL;
1177  List *partitioned_rels = NIL;
1178  PlannerInfo *parent_root;
1179  Query *parent_parse;
1180  Bitmapset *parent_relids = bms_make_singleton(top_parentRTindex);
1181  PlannerInfo **parent_roots = NULL;
1182 
1183  Assert(parse->commandType != CMD_INSERT);
1184 
1185  /*
1186  * We generate a modified instance of the original Query for each target
1187  * relation, plan that, and put all the plans into a list that will be
1188  * controlled by a single ModifyTable node. All the instances share the
1189  * same rangetable, but each instance must have its own set of subquery
1190  * RTEs within the finished rangetable because (1) they are likely to get
1191  * scribbled on during planning, and (2) it's not inconceivable that
1192  * subqueries could get planned differently in different cases. We need
1193  * not create duplicate copies of other RTE kinds, in particular not the
1194  * target relations, because they don't have either of those issues. Not
1195  * having to duplicate the target relations is important because doing so
1196  * (1) would result in a rangetable of length O(N^2) for N targets, with
1197  * at least O(N^3) work expended here; and (2) would greatly complicate
1198  * management of the rowMarks list.
1199  *
1200  * To begin with, generate a bitmapset of the relids of the subquery RTEs.
1201  */
1202  subqueryRTindexes = NULL;
1203  rti = 1;
1204  foreach(lc, parse->rtable)
1205  {
1207 
1208  if (rte->rtekind == RTE_SUBQUERY)
1209  subqueryRTindexes = bms_add_member(subqueryRTindexes, rti);
1210  rti++;
1211  }
1212 
1213  /*
1214  * Next, we want to identify which AppendRelInfo items contain references
1215  * to any of the aforesaid subquery RTEs. These items will need to be
1216  * copied and modified to adjust their subquery references; whereas the
1217  * other ones need not be touched. It's worth being tense over this
1218  * because we can usually avoid processing most of the AppendRelInfo
1219  * items, thereby saving O(N^2) space and time when the target is a large
1220  * inheritance tree. We can identify AppendRelInfo items by their
1221  * child_relid, since that should be unique within the list.
1222  */
1223  modifiableARIindexes = NULL;
1224  if (subqueryRTindexes != NULL)
1225  {
1226  foreach(lc, root->append_rel_list)
1227  {
1228  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
1229 
1230  if (bms_is_member(appinfo->parent_relid, subqueryRTindexes) ||
1231  bms_is_member(appinfo->child_relid, subqueryRTindexes) ||
1233  subqueryRTindexes))
1234  modifiableARIindexes = bms_add_member(modifiableARIindexes,
1235  appinfo->child_relid);
1236  }
1237  }
1238 
1239  /*
1240  * If the parent RTE is a partitioned table, we should use that as the
1241  * nominal relation, because the RTEs added for partitioned tables
1242  * (including the root parent) as child members of the inheritance set do
1243  * not appear anywhere else in the plan. The situation is exactly the
1244  * opposite in the case of non-partitioned inheritance parent as described
1245  * below. For the same reason, collect the list of descendant partitioned
1246  * tables to be saved in ModifyTable node, so that executor can lock those
1247  * as well.
1248  */
1249  parent_rte = rt_fetch(top_parentRTindex, root->parse->rtable);
1250  if (parent_rte->relkind == RELKIND_PARTITIONED_TABLE)
1251  {
1252  nominalRelation = top_parentRTindex;
1253 
1254  /*
1255  * Root parent's RT index is always present in the partitioned_rels of
1256  * the ModifyTable node, if one is needed at all.
1257  */
1258  partitioned_relids = bms_make_singleton(top_parentRTindex);
1259  }
1260 
1261  /*
1262  * The PlannerInfo for each child is obtained by translating the relevant
1263  * members of the PlannerInfo for its immediate parent, which we find
1264  * using the parent_relid in its AppendRelInfo. We save the PlannerInfo
1265  * for each parent in an array indexed by relid for fast retrieval. Since
1266  * the maximum number of parents is limited by the number of RTEs in the
1267  * query, we use that number to allocate the array. An extra entry is
1268  * needed since relids start from 1.
1269  */
1270  parent_roots = (PlannerInfo **) palloc0((list_length(parse->rtable) + 1) *
1271  sizeof(PlannerInfo *));
1272  parent_roots[top_parentRTindex] = root;
1273 
1274  /*
1275  * And now we can get on with generating a plan for each child table.
1276  */
1277  foreach(lc, root->append_rel_list)
1278  {
1279  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
1280  PlannerInfo *subroot;
1281  RangeTblEntry *child_rte;
1282  RelOptInfo *sub_final_rel;
1283  Path *subpath;
1284 
1285  /* append_rel_list contains all append rels; ignore others */
1286  if (!bms_is_member(appinfo->parent_relid, parent_relids))
1287  continue;
1288 
1289  /*
1290  * expand_inherited_rtentry() always processes a parent before any of
1291  * that parent's children, so the parent_root for this relation should
1292  * already be available.
1293  */
1294  parent_root = parent_roots[appinfo->parent_relid];
1295  Assert(parent_root != NULL);
1296  parent_parse = parent_root->parse;
1297 
1298  /*
1299  * We need a working copy of the PlannerInfo so that we can control
1300  * propagation of information back to the main copy.
1301  */
1302  subroot = makeNode(PlannerInfo);
1303  memcpy(subroot, parent_root, sizeof(PlannerInfo));
1304 
1305  /*
1306  * Generate modified query with this rel as target. We first apply
1307  * adjust_appendrel_attrs, which copies the Query and changes
1308  * references to the parent RTE to refer to the current child RTE,
1309  * then fool around with subquery RTEs.
1310  */
1311  subroot->parse = (Query *)
1312  adjust_appendrel_attrs(parent_root,
1313  (Node *) parent_parse,
1314  1, &appinfo);
1315 
1316  /*
1317  * If there are securityQuals attached to the parent, move them to the
1318  * child rel (they've already been transformed properly for that).
1319  */
1320  parent_rte = rt_fetch(appinfo->parent_relid, subroot->parse->rtable);
1321  child_rte = rt_fetch(appinfo->child_relid, subroot->parse->rtable);
1322  child_rte->securityQuals = parent_rte->securityQuals;
1323  parent_rte->securityQuals = NIL;
1324 
1325  /*
1326  * The rowMarks list might contain references to subquery RTEs, so
1327  * make a copy that we can apply ChangeVarNodes to. (Fortunately, the
1328  * executor doesn't need to see the modified copies --- we can just
1329  * pass it the original rowMarks list.)
1330  */
1331  subroot->rowMarks = copyObject(parent_root->rowMarks);
1332 
1333  /*
1334  * The append_rel_list likewise might contain references to subquery
1335  * RTEs (if any subqueries were flattenable UNION ALLs). So prepare
1336  * to apply ChangeVarNodes to that, too. As explained above, we only
1337  * want to copy items that actually contain such references; the rest
1338  * can just get linked into the subroot's append_rel_list.
1339  *
1340  * If we know there are no such references, we can just use the outer
1341  * append_rel_list unmodified.
1342  */
1343  if (modifiableARIindexes != NULL)
1344  {
1345  ListCell *lc2;
1346 
1347  subroot->append_rel_list = NIL;
1348  foreach(lc2, parent_root->append_rel_list)
1349  {
1350  AppendRelInfo *appinfo2 = lfirst_node(AppendRelInfo, lc2);
1351 
1352  if (bms_is_member(appinfo2->child_relid, modifiableARIindexes))
1353  appinfo2 = copyObject(appinfo2);
1354 
1355  subroot->append_rel_list = lappend(subroot->append_rel_list,
1356  appinfo2);
1357  }
1358  }
1359 
1360  /*
1361  * Add placeholders to the child Query's rangetable list to fill the
1362  * RT indexes already reserved for subqueries in previous children.
1363  * These won't be referenced, so there's no need to make them very
1364  * valid-looking.
1365  */
1366  while (list_length(subroot->parse->rtable) < list_length(final_rtable))
1367  subroot->parse->rtable = lappend(subroot->parse->rtable,
1369 
1370  /*
1371  * If this isn't the first child Query, generate duplicates of all
1372  * subquery RTEs, and adjust Var numbering to reference the
1373  * duplicates. To simplify the loop logic, we scan the original rtable
1374  * not the copy just made by adjust_appendrel_attrs; that should be OK
1375  * since subquery RTEs couldn't contain any references to the target
1376  * rel.
1377  */
1378  if (final_rtable != NIL && subqueryRTindexes != NULL)
1379  {
1380  ListCell *lr;
1381 
1382  rti = 1;
1383  foreach(lr, parent_parse->rtable)
1384  {
1386 
1387  if (bms_is_member(rti, subqueryRTindexes))
1388  {
1389  Index newrti;
1390 
1391  /*
1392  * The RTE can't contain any references to its own RT
1393  * index, except in its securityQuals, so we can save a
1394  * few cycles by applying ChangeVarNodes to the rest of
1395  * the rangetable before we append the RTE to it.
1396  */
1397  newrti = list_length(subroot->parse->rtable) + 1;
1398  ChangeVarNodes((Node *) subroot->parse, rti, newrti, 0);
1399  ChangeVarNodes((Node *) subroot->rowMarks, rti, newrti, 0);
1400  /* Skip processing unchanging parts of append_rel_list */
1401  if (modifiableARIindexes != NULL)
1402  {
1403  ListCell *lc2;
1404 
1405  foreach(lc2, subroot->append_rel_list)
1406  {
1407  AppendRelInfo *appinfo2 = lfirst_node(AppendRelInfo, lc2);
1408 
1409  if (bms_is_member(appinfo2->child_relid,
1410  modifiableARIindexes))
1411  ChangeVarNodes((Node *) appinfo2, rti, newrti, 0);
1412  }
1413  }
1414  rte = copyObject(rte);
1415  ChangeVarNodes((Node *) rte->securityQuals, rti, newrti, 0);
1416  subroot->parse->rtable = lappend(subroot->parse->rtable,
1417  rte);
1418  }
1419  rti++;
1420  }
1421  }
1422 
1423  /* There shouldn't be any OJ info to translate, as yet */
1424  Assert(subroot->join_info_list == NIL);
1425  /* and we haven't created PlaceHolderInfos, either */
1426  Assert(subroot->placeholder_list == NIL);
1427 
1428  /*
1429  * Mark if we're planning a query to a partitioned table or an
1430  * inheritance parent.
1431  */
1432  subroot->inhTargetKind =
1433  partitioned_relids ? INHKIND_PARTITIONED : INHKIND_INHERITED;
1434 
1435  /*
1436  * If the child is further partitioned, remember it as a parent. Since
1437  * a partitioned table does not have any data, we don't need to create
1438  * a plan for it. We do, however, need to remember the PlannerInfo for
1439  * use when processing its children.
1440  */
1441  if (child_rte->inh)
1442  {
1443  Assert(child_rte->relkind == RELKIND_PARTITIONED_TABLE);
1444  parent_relids =
1445  bms_add_member(parent_relids, appinfo->child_relid);
1446  parent_roots[appinfo->child_relid] = subroot;
1447 
1448  continue;
1449  }
1450 
1451  /* Generate Path(s) for accessing this result relation */
1452  grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
1453 
1454  /*
1455  * Set the nomimal target relation of the ModifyTable node if not
1456  * already done. We use the inheritance parent RTE as the nominal
1457  * target relation if it's a partitioned table (see just above this
1458  * loop). In the non-partitioned parent case, we'll use the first
1459  * child relation (even if it's excluded) as the nominal target
1460  * relation. Because of the way expand_inherited_rtentry works, the
1461  * latter should be the RTE representing the parent table in its role
1462  * as a simple member of the inheritance set.
1463  *
1464  * It would be logically cleaner to *always* use the inheritance
1465  * parent RTE as the nominal relation; but that RTE is not otherwise
1466  * referenced in the plan in the non-partitioned inheritance case.
1467  * Instead the duplicate child RTE created by expand_inherited_rtentry
1468  * is used elsewhere in the plan, so using the original parent RTE
1469  * would give rise to confusing use of multiple aliases in EXPLAIN
1470  * output for what the user will think is the "same" table. OTOH,
1471  * it's not a problem in the partitioned inheritance case, because the
1472  * duplicate child RTE added for the parent does not appear anywhere
1473  * else in the plan tree.
1474  */
1475  if (nominalRelation < 0)
1476  nominalRelation = appinfo->child_relid;
1477 
1478  /*
1479  * Select cheapest path in case there's more than one. We always run
1480  * modification queries to conclusion, so we care only for the
1481  * cheapest-total path.
1482  */
1483  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
1484  set_cheapest(sub_final_rel);
1485  subpath = sub_final_rel->cheapest_total_path;
1486 
1487  /*
1488  * If this child rel was excluded by constraint exclusion, exclude it
1489  * from the result plan.
1490  */
1491  if (IS_DUMMY_PATH(subpath))
1492  continue;
1493 
1494  /*
1495  * Add the current parent's RT index to the partitione_rels set if
1496  * we're going to create the ModifyTable path for a partitioned root
1497  * table.
1498  */
1499  if (partitioned_relids)
1500  partitioned_relids = bms_add_member(partitioned_relids,
1501  appinfo->parent_relid);
1502 
1503  /*
1504  * If this is the first non-excluded child, its post-planning rtable
1505  * becomes the initial contents of final_rtable; otherwise, append
1506  * just its modified subquery RTEs to final_rtable.
1507  */
1508  if (final_rtable == NIL)
1509  final_rtable = subroot->parse->rtable;
1510  else
1511  final_rtable = list_concat(final_rtable,
1512  list_copy_tail(subroot->parse->rtable,
1513  list_length(final_rtable)));
1514 
1515  /*
1516  * We need to collect all the RelOptInfos from all child plans into
1517  * the main PlannerInfo, since setrefs.c will need them. We use the
1518  * last child's simple_rel_array (previous ones are too short), so we
1519  * have to propagate forward the RelOptInfos that were already built
1520  * in previous children.
1521  */
1522  Assert(subroot->simple_rel_array_size >= save_rel_array_size);
1523  for (rti = 1; rti < save_rel_array_size; rti++)
1524  {
1525  RelOptInfo *brel = save_rel_array[rti];
1526 
1527  if (brel)
1528  subroot->simple_rel_array[rti] = brel;
1529  }
1530  save_rel_array_size = subroot->simple_rel_array_size;
1531  save_rel_array = subroot->simple_rel_array;
1532 
1533  /* Make sure any initplans from this rel get into the outer list */
1534  root->init_plans = subroot->init_plans;
1535 
1536  /* Build list of sub-paths */
1537  subpaths = lappend(subpaths, subpath);
1538 
1539  /* Build list of modified subroots, too */
1540  subroots = lappend(subroots, subroot);
1541 
1542  /* Build list of target-relation RT indexes */
1543  resultRelations = lappend_int(resultRelations, appinfo->child_relid);
1544 
1545  /* Build lists of per-relation WCO and RETURNING targetlists */
1546  if (parse->withCheckOptions)
1547  withCheckOptionLists = lappend(withCheckOptionLists,
1548  subroot->parse->withCheckOptions);
1549  if (parse->returningList)
1550  returningLists = lappend(returningLists,
1551  subroot->parse->returningList);
1552 
1553  Assert(!parse->onConflict);
1554  }
1555 
1556  /* Result path must go into outer query's FINAL upperrel */
1557  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1558 
1559  /*
1560  * We don't currently worry about setting final_rel's consider_parallel
1561  * flag in this case, nor about allowing FDWs or create_upper_paths_hook
1562  * to get control here.
1563  */
1564 
1565  /*
1566  * If we managed to exclude every child rel, return a dummy plan; it
1567  * doesn't even need a ModifyTable node.
1568  */
1569  if (subpaths == NIL)
1570  {
1571  set_dummy_rel_pathlist(final_rel);
1572  return;
1573  }
1574 
1575  /*
1576  * Put back the final adjusted rtable into the master copy of the Query.
1577  * (We mustn't do this if we found no non-excluded children.)
1578  */
1579  parse->rtable = final_rtable;
1580  root->simple_rel_array_size = save_rel_array_size;
1581  root->simple_rel_array = save_rel_array;
1582  /* Must reconstruct master's simple_rte_array, too */
1583  root->simple_rte_array = (RangeTblEntry **)
1584  palloc0((list_length(final_rtable) + 1) * sizeof(RangeTblEntry *));
1585  rti = 1;
1586  foreach(lc, final_rtable)
1587  {
1589 
1590  root->simple_rte_array[rti++] = rte;
1591  }
1592 
1593  /*
1594  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node will
1595  * have dealt with fetching non-locked marked rows, else we need to have
1596  * ModifyTable do that.
1597  */
1598  if (parse->rowMarks)
1599  rowMarks = NIL;
1600  else
1601  rowMarks = root->rowMarks;
1602 
1603  if (partitioned_relids)
1604  {
1605  int i;
1606 
1607  i = -1;
1608  while ((i = bms_next_member(partitioned_relids, i)) >= 0)
1609  partitioned_rels = lappend_int(partitioned_rels, i);
1610 
1611  /*
1612  * If we're going to create ModifyTable at all, the list should
1613  * contain at least one member, that is, the root parent's index.
1614  */
1615  Assert(list_length(partitioned_rels) >= 1);
1616  }
1617 
1618  /* Create Path representing a ModifyTable to do the UPDATE/DELETE work */
1619  add_path(final_rel, (Path *)
1620  create_modifytable_path(root, final_rel,
1621  parse->commandType,
1622  parse->canSetTag,
1623  nominalRelation,
1624  partitioned_rels,
1625  root->partColsUpdated,
1626  resultRelations,
1627  subpaths,
1628  subroots,
1629  withCheckOptionLists,
1630  returningLists,
1631  rowMarks,
1632  NULL,
1633  SS_assign_special_param(root)));
1634 }
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:268
Query * parse
Definition: relation.h:169
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * join_info_list
Definition: relation.h:264
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
OnConflictExpr * onConflict
Definition: parsenodes.h:144
List * withCheckOptions
Definition: parsenodes.h:171
List * securityQuals
Definition: parsenodes.h:1075
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1075
int resultRelation
Definition: parsenodes.h:122
Definition: nodes.h:517
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
List * rowMarks
Definition: parsenodes.h:163
List * translated_vars
Definition: relation.h:2152
struct RelOptInfo ** simple_rel_array
Definition: relation.h:193
#define IS_DUMMY_PATH(p)
Definition: relation.h:1313
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, bool partColsUpdated, List *resultRelations, List *subpaths, List *subroots, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: pathnode.c:3313
void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:2018
List * rtable
Definition: parsenodes.h:137
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1145
#define lfirst_node(type, lc)
Definition: pg_list.h:109
struct Path * cheapest_total_path
Definition: relation.h:630
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:245
bool partColsUpdated
Definition: relation.h:335
List * returningList
Definition: parsenodes.h:146
int simple_rel_array_size
Definition: relation.h:194
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Relids pull_varnos(Node *node)
Definition: var.c:95
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
RangeTblEntry ** simple_rte_array
Definition: relation.h:202
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: prepunion.c:2047
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
void * palloc0(Size size)
Definition: mcxt.c:955
List * append_rel_list
Definition: relation.h:266
unsigned int Index
Definition: c.h:442
List * init_plans
Definition: relation.h:242
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
InheritanceKind inhTargetKind
Definition: relation.h:312
bool canSetTag
Definition: parsenodes.h:118
static int list_length(const List *l)
Definition: pg_list.h:89
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
RTEKind rtekind
Definition: parsenodes.h:962
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:509
static void grouping_planner(PlannerInfo *root, bool inheritance_update, double tuple_fraction)
Definition: planner.c:1665
int i
List * placeholder_list
Definition: relation.h:270
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
Index child_relid
Definition: relation.h:2125
#define copyObject(obj)
Definition: nodes.h:630
Index parent_relid
Definition: relation.h:2124
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ is_degenerate_grouping()

static bool is_degenerate_grouping ( PlannerInfo root)
static

Definition at line 3854 of file planner.c.

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

Referenced by create_grouping_paths().

3855 {
3856  Query *parse = root->parse;
3857 
3858  return (root->hasHavingQual || parse->groupingSets) &&
3859  !parse->hasAggs && parse->groupClause == NIL;
3860 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
List * groupClause
Definition: parsenodes.h:148
bool hasHavingQual
Definition: relation.h:318
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ is_dummy_plan()

bool is_dummy_plan ( Plan plan)

Definition at line 2477 of file planner.c.

References Const::constisnull, Const::constvalue, DatumGetBool, IsA, linitial, and list_length().

2478 {
2479  if (IsA(plan, Result))
2480  {
2481  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2482 
2483  if (list_length(rcqual) == 1)
2484  {
2485  Const *constqual = (Const *) linitial(rcqual);
2486 
2487  if (constqual && IsA(constqual, Const))
2488  {
2489  if (!constqual->constisnull &&
2490  !DatumGetBool(constqual->constvalue))
2491  return true;
2492  }
2493  }
2494  }
2495  return false;