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

Go to the source code of this file.

Data Structures

struct  standard_qp_extra
 
struct  grouping_sets_data
 
struct  WindowClauseSortData
 

Macros

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

Functions

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

Variables

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

Macro Definition Documentation

◆ EXPRKIND_APPINFO

#define EXPRKIND_APPINFO   7

Definition at line 88 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 91 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 87 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 89 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 81 of file planner.c.

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

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 83 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 92 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 93 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 90 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 82 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 85 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 86 of file planner.c.

Referenced by subquery_planner().

Function Documentation

◆ add_paths_to_grouping_rel()

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

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

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

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

◆ apply_scanjoin_target_to_paths()

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

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

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

◆ can_partial_agg()

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

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

6949 {
6950  Query *parse = root->parse;
6951 
6952  if (!parse->hasAggs && parse->groupClause == NIL)
6953  {
6954  /*
6955  * We don't know how to do parallel aggregation unless we have either
6956  * some aggregates or a grouping clause.
6957  */
6958  return false;
6959  }
6960  else if (parse->groupingSets)
6961  {
6962  /* We don't know how to do grouping sets in parallel. */
6963  return false;
6964  }
6965  else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
6966  {
6967  /* Insufficient support for partial mode. */
6968  return false;
6969  }
6970 
6971  /* Everything looks good. */
6972  return true;
6973 }
#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 5434 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().

5435 {
5436  const WindowClauseSortData *wcsa = a;
5437  const WindowClauseSortData *wcsb = b;
5438  ListCell *item_a;
5439  ListCell *item_b;
5440 
5441  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5442  {
5445 
5446  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5447  return -1;
5448  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5449  return 1;
5450  else if (sca->sortop > scb->sortop)
5451  return -1;
5452  else if (sca->sortop < scb->sortop)
5453  return 1;
5454  else if (sca->nulls_first && !scb->nulls_first)
5455  return -1;
5456  else if (!sca->nulls_first && scb->nulls_first)
5457  return 1;
5458  /* no need to compare eqop, since it is fully determined by sortop */
5459  }
5460 
5461  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5462  return -1;
5463  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5464  return 1;
5465 
5466  return 0;
5467 }
#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 4185 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().

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

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

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

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

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

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

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

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

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

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

◆ create_window_paths()

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

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

4553 {
4554  RelOptInfo *window_rel;
4555  ListCell *lc;
4556 
4557  /* For now, do all work in the (WINDOW, NULL) upperrel */
4558  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4559 
4560  /*
4561  * If the input relation is not parallel-safe, then the window relation
4562  * can't be parallel-safe, either. Otherwise, we need to examine the
4563  * target list and active windows for non-parallel-safe constructs.
4564  */
4565  if (input_rel->consider_parallel && output_target_parallel_safe &&
4566  is_parallel_safe(root, (Node *) activeWindows))
4567  window_rel->consider_parallel = true;
4568 
4569  /*
4570  * If the input rel belongs to a single FDW, so does the window rel.
4571  */
4572  window_rel->serverid = input_rel->serverid;
4573  window_rel->userid = input_rel->userid;
4574  window_rel->useridiscurrent = input_rel->useridiscurrent;
4575  window_rel->fdwroutine = input_rel->fdwroutine;
4576 
4577  /*
4578  * Consider computing window functions starting from the existing
4579  * cheapest-total path (which will likely require a sort) as well as any
4580  * existing paths that satisfy root->window_pathkeys (which won't).
4581  */
4582  foreach(lc, input_rel->pathlist)
4583  {
4584  Path *path = (Path *) lfirst(lc);
4585 
4586  if (path == input_rel->cheapest_total_path ||
4589  window_rel,
4590  path,
4591  input_target,
4592  output_target,
4593  wflists,
4594  activeWindows);
4595  }
4596 
4597  /*
4598  * If there is an FDW that's responsible for all baserels of the query,
4599  * let it consider adding ForeignPaths.
4600  */
4601  if (window_rel->fdwroutine &&
4602  window_rel->fdwroutine->GetForeignUpperPaths)
4603  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4604  input_rel, window_rel,
4605  NULL);
4606 
4607  /* Let extensions possibly add some more paths */
4609  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4610  input_rel, window_rel, NULL);
4611 
4612  /* Now choose the best path(s) */
4613  set_cheapest(window_rel);
4614 
4615  return window_rel;
4616 }
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:4630
Oid userid
Definition: pathnodes.h:691
Definition: nodes.h:525
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
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:1177
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:244
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 6045 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().

6046 {
6047  Node *result;
6048 
6049  /*
6050  * Convert named-argument function calls, insert default arguments and
6051  * simplify constant subexprs
6052  */
6053  result = eval_const_expressions(NULL, (Node *) expr);
6054 
6055  /* Fill in opfuncid values if missing */
6056  fix_opfuncids(result);
6057 
6058  return (Expr *) result;
6059 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1587
Definition: nodes.h:525
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 6072 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().

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

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

◆ gather_grouping_paths()

static void gather_grouping_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

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

6909 {
6910  Path *cheapest_partial_path;
6911 
6912  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
6913  generate_gather_paths(root, rel, true);
6914 
6915  /* Try cheapest partial path + explicit Sort + Gather Merge. */
6916  cheapest_partial_path = linitial(rel->partial_pathlist);
6918  cheapest_partial_path->pathkeys))
6919  {
6920  Path *path;
6921  double total_groups;
6922 
6923  total_groups =
6924  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
6925  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
6926  root->group_pathkeys,
6927  -1.0);
6928  path = (Path *)
6930  rel,
6931  path,
6932  rel->reltarget,
6933  root->group_pathkeys,
6934  NULL,
6935  &total_groups);
6936 
6937  add_path(rel, path);
6938  }
6939 }
List * group_pathkeys
Definition: pathnodes.h:298
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
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:1753
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2766
List * pathkeys
Definition: pathnodes.h: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 5886 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().

5887 {
5888  Path *best_path = rel->cheapest_total_path;
5889  ListCell *l;
5890 
5891  /* If all tuples will be retrieved, just return the cheapest-total path */
5892  if (tuple_fraction <= 0.0)
5893  return best_path;
5894 
5895  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5896  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5897  tuple_fraction /= best_path->rows;
5898 
5899  foreach(l, rel->pathlist)
5900  {
5901  Path *path = (Path *) lfirst(l);
5902 
5903  if (path == rel->cheapest_total_path ||
5904  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5905  continue;
5906 
5907  best_path = path;
5908  }
5909 
5910  return best_path;
5911 }
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:117
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 3679 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().

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

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

◆ grouping_planner()

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

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

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

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