PostgreSQL Source Code  git master
planner.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/parallel.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "foreign/fdwapi.h"
#include "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/appendinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/inherit.h"
#include "optimizer/optimizer.h"
#include "optimizer/paramassign.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/parse_agg.h"
#include "partitioning/partdesc.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
 
struct  WindowClauseSortData
 

Macros

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

Functions

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

Variables

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

Macro Definition Documentation

◆ EXPRKIND_APPINFO

#define EXPRKIND_APPINFO   7

Definition at line 89 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 92 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 88 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 90 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 82 of file planner.c.

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

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 85 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 93 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 94 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 91 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 83 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 86 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

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

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

◆ adjust_paths_for_srfs()

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

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

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

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

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

Referenced by grouping_planner().

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

◆ can_partial_agg()

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

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

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

◆ common_prefix_cmp()

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

Definition at line 5435 of file planner.c.

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

Referenced by select_active_windows().

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

◆ consider_groupingsets_paths()

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

Definition at line 4186 of file planner.c.

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

Referenced by add_paths_to_grouping_rel().

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

◆ create_degenerate_grouping_paths()

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

Definition at line 3985 of file planner.c.

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

Referenced by create_grouping_paths().

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

◆ create_distinct_paths()

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

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

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

◆ create_grouping_paths()

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

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

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

◆ create_one_window_path()

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

Definition at line 4631 of file planner.c.

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

Referenced by create_window_paths().

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

◆ create_ordered_paths()

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

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

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

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

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

Referenced by create_grouping_paths(), and create_partitionwise_grouping_paths().

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

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

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

◆ create_partitionwise_grouping_paths()

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

Definition at line 7223 of file planner.c.

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

Referenced by create_ordinary_grouping_paths().

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

◆ create_window_paths()

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

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

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

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 6046 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

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

6047 {
6048  Node *result;
6049 
6050  /*
6051  * Convert named-argument function calls, insert default arguments and
6052  * simplify constant subexprs
6053  */
6054  result = eval_const_expressions(NULL, (Node *) expr);
6055 
6056  /* Fill in opfuncid values if missing */
6057  fix_opfuncids(result);
6058 
6059  return (Expr *) result;
6060 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1588
Definition: nodes.h:524
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2253

◆ expression_planner_with_deps()

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

Definition at line 6073 of file planner.c.

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

Referenced by GetCachedExpression().

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

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

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

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

◆ gather_grouping_paths()

static void gather_grouping_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

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

6910 {
6911  Path *cheapest_partial_path;
6912 
6913  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
6914  generate_gather_paths(root, rel, true);
6915 
6916  /* Try cheapest partial path + explicit Sort + Gather Merge. */
6917  cheapest_partial_path = linitial(rel->partial_pathlist);
6919  cheapest_partial_path->pathkeys))
6920  {
6921  Path *path;
6922  double total_groups;
6923 
6924  total_groups =
6925  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
6926  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
6927  root->group_pathkeys,
6928  -1.0);
6929  path = (Path *)
6931  rel,
6932  path,
6933  rel->reltarget,
6934  root->group_pathkeys,
6935  NULL,
6936  &total_groups);
6937 
6938  add_path(rel, path);
6939  }
6940 }
List * group_pathkeys
Definition: pathnodes.h:298
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:423
int parallel_workers
Definition: pathnodes.h:1121
List * partial_pathlist
Definition: pathnodes.h:657
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2682
#define linitial(l)
Definition: pg_list.h:195
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1754
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2767
List * pathkeys
Definition: pathnodes.h:1128
double rows
Definition: pathnodes.h:1124
struct PathTarget * reltarget
Definition: pathnodes.h:652

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

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

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

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

◆ group_by_has_partkey()

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

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

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

◆ grouping_planner()

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

Definition at line 1829 of file planner.c.

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

Referenced by inheritance_planner(), and subquery_planner().

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

◆ inheritance_planner()

static void inheritance_planner ( PlannerInfo root)
static

Definition at line 1208 of file planner.c.

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

Referenced by subquery_planner().

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