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, grouping_sets_data *gd)
 
static bool is_degenerate_grouping (PlannerInfo *root)
 
static void create_degenerate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
 
static RelOptInfomake_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
 
static void create_ordinary_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
 
static void consider_groupingsets_paths (PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
 
static RelOptInfocreate_window_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, WindowFuncLists *wflists, List *activeWindows)
 
static void create_one_window_path (PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, WindowFuncLists *wflists, List *activeWindows)
 
static RelOptInfocreate_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel)
 
static RelOptInfocreate_ordered_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
 
static PathTargetmake_group_input_target (PlannerInfo *root, PathTarget *final_target)
 
static PathTargetmake_partial_grouping_target (PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
 
static Listpostprocess_setop_tlist (List *new_tlist, List *orig_tlist)
 
static Listselect_active_windows (PlannerInfo *root, WindowFuncLists *wflists)
 
static PathTargetmake_window_input_target (PlannerInfo *root, PathTarget *final_target, List *activeWindows)
 
static Listmake_pathkeys_for_window (PlannerInfo *root, WindowClause *wc, List *tlist)
 
static PathTargetmake_sort_input_target (PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
 
static void adjust_paths_for_srfs (PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
 
static void add_paths_to_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, double dNumGroups, GroupPathExtraData *extra)
 
static RelOptInfocreate_partial_grouping_paths (PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *input_rel, grouping_sets_data *gd, GroupPathExtraData *extra, bool force_rel_creation)
 
static void gather_grouping_paths (PlannerInfo *root, RelOptInfo *rel)
 
static bool can_partial_agg (PlannerInfo *root)
 
static void apply_scanjoin_target_to_paths (PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
 
static void create_partitionwise_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, PartitionwiseAggregateType patype, GroupPathExtraData *extra)
 
static bool group_by_has_partkey (RelOptInfo *input_rel, List *targetList, List *groupClause)
 
static int common_prefix_cmp (const void *a, const void *b)
 
PlannedStmtplanner (Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
PlannedStmtstandard_planner (Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
 
PlannerInfosubquery_planner (PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
 
Exprpreprocess_phv_expression (PlannerInfo *root, Expr *expr)
 
RowMarkType select_rowmark_type (RangeTblEntry *rte, LockClauseStrength strength)
 
bool limit_needed (Query *parse)
 
void mark_partial_aggref (Aggref *agg, AggSplit aggsplit)
 
Pathget_cheapest_fractional_path (RelOptInfo *rel, double tuple_fraction)
 
Exprexpression_planner (Expr *expr)
 
Exprexpression_planner_with_deps (Expr *expr, List **relationOids, List **invalItems)
 
bool plan_cluster_use_sort (Oid tableOid, Oid indexOid)
 
int plan_create_index_workers (Oid tableOid, Oid indexOid)
 

Variables

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

Macro Definition Documentation

◆ EXPRKIND_APPINFO

#define EXPRKIND_APPINFO   7

Definition at line 88 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 91 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 87 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 89 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 81 of file planner.c.

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

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 83 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 92 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 93 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 90 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 82 of file planner.c.

Referenced by 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 6495 of file planner.c.

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

Referenced by create_ordinary_grouping_paths().

6501 {
6502  Query *parse = root->parse;
6503  Path *cheapest_path = input_rel->cheapest_total_path;
6504  ListCell *lc;
6505  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6506  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6507  List *havingQual = (List *) extra->havingQual;
6508  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6509 
6510  if (can_sort)
6511  {
6512  /*
6513  * Use any available suitably-sorted path as input, and also consider
6514  * sorting the cheapest-total path.
6515  */
6516  foreach(lc, input_rel->pathlist)
6517  {
6518  Path *path = (Path *) lfirst(lc);
6519  Path *path_original = path;
6520  bool is_sorted;
6521  int presorted_keys;
6522 
6523  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6524  path->pathkeys,
6525  &presorted_keys);
6526 
6527  if (path == cheapest_path || is_sorted)
6528  {
6529  /* Sort the cheapest-total path if it isn't already sorted */
6530  if (!is_sorted)
6531  path = (Path *) create_sort_path(root,
6532  grouped_rel,
6533  path,
6534  root->group_pathkeys,
6535  -1.0);
6536 
6537  /* Now decide what to stick atop it */
6538  if (parse->groupingSets)
6539  {
6540  consider_groupingsets_paths(root, grouped_rel,
6541  path, true, can_hash,
6542  gd, agg_costs, dNumGroups);
6543  }
6544  else if (parse->hasAggs)
6545  {
6546  /*
6547  * We have aggregation, possibly with plain GROUP BY. Make
6548  * an AggPath.
6549  */
6550  add_path(grouped_rel, (Path *)
6551  create_agg_path(root,
6552  grouped_rel,
6553  path,
6554  grouped_rel->reltarget,
6555  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6557  parse->groupClause,
6558  havingQual,
6559  agg_costs,
6560  dNumGroups));
6561  }
6562  else if (parse->groupClause)
6563  {
6564  /*
6565  * We have GROUP BY without aggregation or grouping sets.
6566  * Make a GroupPath.
6567  */
6568  add_path(grouped_rel, (Path *)
6569  create_group_path(root,
6570  grouped_rel,
6571  path,
6572  parse->groupClause,
6573  havingQual,
6574  dNumGroups));
6575  }
6576  else
6577  {
6578  /* Other cases should have been handled above */
6579  Assert(false);
6580  }
6581  }
6582 
6583  /*
6584  * Now we may consider incremental sort on this path, but only
6585  * when the path is not already sorted and when incremental sort
6586  * is enabled.
6587  */
6588  if (is_sorted || !enable_incremental_sort)
6589  continue;
6590 
6591  /* Restore the input path (we might have added Sort on top). */
6592  path = path_original;
6593 
6594  /* no shared prefix, no point in building incremental sort */
6595  if (presorted_keys == 0)
6596  continue;
6597 
6598  /*
6599  * We should have already excluded pathkeys of length 1 because
6600  * then presorted_keys > 0 would imply is_sorted was true.
6601  */
6602  Assert(list_length(root->group_pathkeys) != 1);
6603 
6604  path = (Path *) create_incremental_sort_path(root,
6605  grouped_rel,
6606  path,
6607  root->group_pathkeys,
6608  presorted_keys,
6609  -1.0);
6610 
6611  /* Now decide what to stick atop it */
6612  if (parse->groupingSets)
6613  {
6614  consider_groupingsets_paths(root, grouped_rel,
6615  path, true, can_hash,
6616  gd, agg_costs, dNumGroups);
6617  }
6618  else if (parse->hasAggs)
6619  {
6620  /*
6621  * We have aggregation, possibly with plain GROUP BY. Make an
6622  * AggPath.
6623  */
6624  add_path(grouped_rel, (Path *)
6625  create_agg_path(root,
6626  grouped_rel,
6627  path,
6628  grouped_rel->reltarget,
6629  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6631  parse->groupClause,
6632  havingQual,
6633  agg_costs,
6634  dNumGroups));
6635  }
6636  else if (parse->groupClause)
6637  {
6638  /*
6639  * We have GROUP BY without aggregation or grouping sets. Make
6640  * a GroupPath.
6641  */
6642  add_path(grouped_rel, (Path *)
6643  create_group_path(root,
6644  grouped_rel,
6645  path,
6646  parse->groupClause,
6647  havingQual,
6648  dNumGroups));
6649  }
6650  else
6651  {
6652  /* Other cases should have been handled above */
6653  Assert(false);
6654  }
6655  }
6656 
6657  /*
6658  * Instead of operating directly on the input relation, we can
6659  * consider finalizing a partially aggregated path.
6660  */
6661  if (partially_grouped_rel != NULL)
6662  {
6663  foreach(lc, partially_grouped_rel->pathlist)
6664  {
6665  Path *path = (Path *) lfirst(lc);
6666  Path *path_original = path;
6667  bool is_sorted;
6668  int presorted_keys;
6669 
6670  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6671  path->pathkeys,
6672  &presorted_keys);
6673 
6674  /*
6675  * Insert a Sort node, if required. But there's no point in
6676  * sorting anything but the cheapest path.
6677  */
6678  if (!is_sorted)
6679  {
6680  if (path != partially_grouped_rel->cheapest_total_path)
6681  continue;
6682  path = (Path *) create_sort_path(root,
6683  grouped_rel,
6684  path,
6685  root->group_pathkeys,
6686  -1.0);
6687  }
6688 
6689  if (parse->hasAggs)
6690  add_path(grouped_rel, (Path *)
6691  create_agg_path(root,
6692  grouped_rel,
6693  path,
6694  grouped_rel->reltarget,
6695  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6697  parse->groupClause,
6698  havingQual,
6699  agg_final_costs,
6700  dNumGroups));
6701  else
6702  add_path(grouped_rel, (Path *)
6703  create_group_path(root,
6704  grouped_rel,
6705  path,
6706  parse->groupClause,
6707  havingQual,
6708  dNumGroups));
6709 
6710  /*
6711  * Now we may consider incremental sort on this path, but only
6712  * when the path is not already sorted and when incremental
6713  * sort is enabled.
6714  */
6715  if (is_sorted || !enable_incremental_sort)
6716  continue;
6717 
6718  /* Restore the input path (we might have added Sort on top). */
6719  path = path_original;
6720 
6721  /* no shared prefix, not point in building incremental sort */
6722  if (presorted_keys == 0)
6723  continue;
6724 
6725  /*
6726  * We should have already excluded pathkeys of length 1
6727  * because then presorted_keys > 0 would imply is_sorted was
6728  * true.
6729  */
6730  Assert(list_length(root->group_pathkeys) != 1);
6731 
6732  path = (Path *) create_incremental_sort_path(root,
6733  grouped_rel,
6734  path,
6735  root->group_pathkeys,
6736  presorted_keys,
6737  -1.0);
6738 
6739  if (parse->hasAggs)
6740  add_path(grouped_rel, (Path *)
6741  create_agg_path(root,
6742  grouped_rel,
6743  path,
6744  grouped_rel->reltarget,
6745  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6747  parse->groupClause,
6748  havingQual,
6749  agg_final_costs,
6750  dNumGroups));
6751  else
6752  add_path(grouped_rel, (Path *)
6753  create_group_path(root,
6754  grouped_rel,
6755  path,
6756  parse->groupClause,
6757  havingQual,
6758  dNumGroups));
6759  }
6760  }
6761  }
6762 
6763  if (can_hash)
6764  {
6765  if (parse->groupingSets)
6766  {
6767  /*
6768  * Try for a hash-only groupingsets path over unsorted input.
6769  */
6770  consider_groupingsets_paths(root, grouped_rel,
6771  cheapest_path, false, true,
6772  gd, agg_costs, dNumGroups);
6773  }
6774  else
6775  {
6776  /*
6777  * Generate a HashAgg Path. We just need an Agg over the
6778  * cheapest-total input path, since input order won't matter.
6779  */
6780  add_path(grouped_rel, (Path *)
6781  create_agg_path(root, grouped_rel,
6782  cheapest_path,
6783  grouped_rel->reltarget,
6784  AGG_HASHED,
6786  parse->groupClause,
6787  havingQual,
6788  agg_costs,
6789  dNumGroups));
6790  }
6791 
6792  /*
6793  * Generate a Finalize HashAgg Path atop of the cheapest partially
6794  * grouped path, assuming there is one
6795  */
6796  if (partially_grouped_rel && partially_grouped_rel->pathlist)
6797  {
6798  Path *path = partially_grouped_rel->cheapest_total_path;
6799 
6800  add_path(grouped_rel, (Path *)
6801  create_agg_path(root,
6802  grouped_rel,
6803  path,
6804  grouped_rel->reltarget,
6805  AGG_HASHED,
6807  parse->groupClause,
6808  havingQual,
6809  agg_final_costs,
6810  dNumGroups));
6811  }
6812  }
6813 
6814  /*
6815  * When partitionwise aggregate is used, we might have fully aggregated
6816  * paths in the partial pathlist, because add_paths_to_append_rel() will
6817  * consider a path for grouped_rel consisting of a Parallel Append of
6818  * non-partial paths from each child.
6819  */
6820  if (grouped_rel->partial_pathlist != NIL)
6821  gather_grouping_paths(root, grouped_rel);
6822 }
List * group_pathkeys
Definition: pathnodes.h:294
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:173
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:138
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:4174
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:7226
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
List * partial_pathlist
Definition: pathnodes.h:682
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2802
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2456
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:3006
struct Path * cheapest_total_path
Definition: pathnodes.h:684
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2457
List * pathkeys
Definition: pathnodes.h:1162
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * groupClause
Definition: parsenodes.h:148
List * pathlist
Definition: pathnodes.h:680
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2895
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2497
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:677
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 6050 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().

6052 {
6053  ListCell *lc;
6054 
6055  Assert(list_length(targets) == list_length(targets_contain_srfs));
6056  Assert(!linitial_int(targets_contain_srfs));
6057 
6058  /* If no SRFs appear at this plan level, nothing to do */
6059  if (list_length(targets) == 1)
6060  return;
6061 
6062  /*
6063  * Stack SRF-evaluation nodes atop each path for the rel.
6064  *
6065  * In principle we should re-run set_cheapest() here to identify the
6066  * cheapest path, but it seems unlikely that adding the same tlist eval
6067  * costs to all the paths would change that, so we don't bother. Instead,
6068  * just assume that the cheapest-startup and cheapest-total paths remain
6069  * so. (There should be no parameterized paths anymore, so we needn't
6070  * worry about updating cheapest_parameterized_paths.)
6071  */
6072  foreach(lc, rel->pathlist)
6073  {
6074  Path *subpath = (Path *) lfirst(lc);
6075  Path *newpath = subpath;
6076  ListCell *lc1,
6077  *lc2;
6078 
6079  Assert(subpath->param_info == NULL);
6080  forboth(lc1, targets, lc2, targets_contain_srfs)
6081  {
6082  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6083  bool contains_srfs = (bool) lfirst_int(lc2);
6084 
6085  /* If this level doesn't contain SRFs, do regular projection */
6086  if (contains_srfs)
6087  newpath = (Path *) create_set_projection_path(root,
6088  rel,
6089  newpath,
6090  thistarget);
6091  else
6092  newpath = (Path *) apply_projection_to_path(root,
6093  rel,
6094  newpath,
6095  thistarget);
6096  }
6097  lfirst(lc) = newpath;
6098  if (subpath == rel->cheapest_startup_path)
6099  rel->cheapest_startup_path = newpath;
6100  if (subpath == rel->cheapest_total_path)
6101  rel->cheapest_total_path = newpath;
6102  }
6103 
6104  /* Likewise for partial paths, if any */
6105  foreach(lc, rel->partial_pathlist)
6106  {
6107  Path *subpath = (Path *) lfirst(lc);
6108  Path *newpath = subpath;
6109  ListCell *lc1,
6110  *lc2;
6111 
6112  Assert(subpath->param_info == NULL);
6113  forboth(lc1, targets, lc2, targets_contain_srfs)
6114  {
6115  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6116  bool contains_srfs = (bool) lfirst_int(lc2);
6117 
6118  /* If this level doesn't contain SRFs, do regular projection */
6119  if (contains_srfs)
6120  newpath = (Path *) create_set_projection_path(root,
6121  rel,
6122  newpath,
6123  thistarget);
6124  else
6125  {
6126  /* avoid apply_projection_to_path, in case of multiple refs */
6127  newpath = (Path *) create_projection_path(root,
6128  rel,
6129  newpath,
6130  thistarget);
6131  }
6132  }
6133  lfirst(lc) = newpath;
6134  }
6135 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2644
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:434
struct Path * cheapest_startup_path
Definition: pathnodes.h:683
ParamPathInfo * param_info
Definition: pathnodes.h:1151
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2553
List * partial_pathlist
Definition: pathnodes.h:682
#define linitial_int(l)
Definition: pg_list.h:175
#define lfirst_int(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:172
struct Path * cheapest_total_path
Definition: pathnodes.h:684
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2733
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * pathlist
Definition: pathnodes.h:680
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
unsigned char bool
Definition: c.h:379

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

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

Referenced by grouping_planner().

7362 {
7363  bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
7364  PathTarget *scanjoin_target;
7365  ListCell *lc;
7366 
7367  /* This recurses, so be paranoid. */
7369 
7370  /*
7371  * If the rel is partitioned, we want to drop its existing paths and
7372  * generate new ones. This function would still be correct if we kept the
7373  * existing paths: we'd modify them to generate the correct target above
7374  * the partitioning Append, and then they'd compete on cost with paths
7375  * generating the target below the Append. However, in our current cost
7376  * model the latter way is always the same or cheaper cost, so modifying
7377  * the existing paths would just be useless work. Moreover, when the cost
7378  * is the same, varying roundoff errors might sometimes allow an existing
7379  * path to be picked, resulting in undesirable cross-platform plan
7380  * variations. So we drop old paths and thereby force the work to be done
7381  * below the Append, except in the case of a non-parallel-safe target.
7382  *
7383  * Some care is needed, because we have to allow generate_gather_paths to
7384  * see the old partial paths in the next stanza. Hence, zap the main
7385  * pathlist here, then allow generate_gather_paths to add path(s) to the
7386  * main list, and finally zap the partial pathlist.
7387  */
7388  if (rel_is_partitioned)
7389  rel->pathlist = NIL;
7390 
7391  /*
7392  * If the scan/join target is not parallel-safe, partial paths cannot
7393  * generate it.
7394  */
7395  if (!scanjoin_target_parallel_safe)
7396  {
7397  /*
7398  * Since we can't generate the final scan/join target in parallel
7399  * workers, this is our last opportunity to use any partial paths that
7400  * exist; so build Gather path(s) that use them and emit whatever the
7401  * current reltarget is. We don't do this in the case where the
7402  * target is parallel-safe, since we will be able to generate superior
7403  * paths by doing it after the final scan/join target has been
7404  * applied.
7405  */
7406  generate_useful_gather_paths(root, rel, false);
7407 
7408  /* Can't use parallel query above this level. */
7409  rel->partial_pathlist = NIL;
7410  rel->consider_parallel = false;
7411  }
7412 
7413  /* Finish dropping old paths for a partitioned rel, per comment above */
7414  if (rel_is_partitioned)
7415  rel->partial_pathlist = NIL;
7416 
7417  /* Extract SRF-free scan/join target. */
7418  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
7419 
7420  /*
7421  * Apply the SRF-free scan/join target to each existing path.
7422  *
7423  * If the tlist exprs are the same, we can just inject the sortgroupref
7424  * information into the existing pathtargets. Otherwise, replace each
7425  * path with a projection path that generates the SRF-free scan/join
7426  * target. This can't change the ordering of paths within rel->pathlist,
7427  * so we just modify the list in place.
7428  */
7429  foreach(lc, rel->pathlist)
7430  {
7431  Path *subpath = (Path *) lfirst(lc);
7432 
7433  /* Shouldn't have any parameterized paths anymore */
7434  Assert(subpath->param_info == NULL);
7435 
7436  if (tlist_same_exprs)
7437  subpath->pathtarget->sortgrouprefs =
7438  scanjoin_target->sortgrouprefs;
7439  else
7440  {
7441  Path *newpath;
7442 
7443  newpath = (Path *) create_projection_path(root, rel, subpath,
7444  scanjoin_target);
7445  lfirst(lc) = newpath;
7446  }
7447  }
7448 
7449  /* Likewise adjust the targets for any partial paths. */
7450  foreach(lc, rel->partial_pathlist)
7451  {
7452  Path *subpath = (Path *) lfirst(lc);
7453 
7454  /* Shouldn't have any parameterized paths anymore */
7455  Assert(subpath->param_info == NULL);
7456 
7457  if (tlist_same_exprs)
7458  subpath->pathtarget->sortgrouprefs =
7459  scanjoin_target->sortgrouprefs;
7460  else
7461  {
7462  Path *newpath;
7463 
7464  newpath = (Path *) create_projection_path(root, rel, subpath,
7465  scanjoin_target);
7466  lfirst(lc) = newpath;
7467  }
7468  }
7469 
7470  /*
7471  * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
7472  * atop each existing path. (Note that this function doesn't look at the
7473  * cheapest-path fields, which is a good thing because they're bogus right
7474  * now.)
7475  */
7476  if (root->parse->hasTargetSRFs)
7477  adjust_paths_for_srfs(root, rel,
7478  scanjoin_targets,
7479  scanjoin_targets_contain_srfs);
7480 
7481  /*
7482  * Update the rel's target to be the final (with SRFs) scan/join target.
7483  * This now matches the actual output of all the paths, and we might get
7484  * confused in createplan.c if they don't agree. We must do this now so
7485  * that any append paths made in the next part will use the correct
7486  * pathtarget (cf. create_append_path).
7487  *
7488  * Note that this is also necessary if GetForeignUpperPaths() gets called
7489  * on the final scan/join relation or on any of its children, since the
7490  * FDW might look at the rel's target to create ForeignPaths.
7491  */
7492  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
7493 
7494  /*
7495  * If the relation is partitioned, recursively apply the scan/join target
7496  * to all partitions, and generate brand-new Append paths in which the
7497  * scan/join target is computed below the Append rather than above it.
7498  * Since Append is not projection-capable, that might save a separate
7499  * Result node, and it also is important for partitionwise aggregate.
7500  */
7501  if (rel_is_partitioned)
7502  {
7503  List *live_children = NIL;
7504  int partition_idx;
7505 
7506  /* Adjust each partition. */
7507  for (partition_idx = 0; partition_idx < rel->nparts; partition_idx++)
7508  {
7509  RelOptInfo *child_rel = rel->part_rels[partition_idx];
7510  AppendRelInfo **appinfos;
7511  int nappinfos;
7512  List *child_scanjoin_targets = NIL;
7513  ListCell *lc;
7514 
7515  /* Pruned or dummy children can be ignored. */
7516  if (child_rel == NULL || IS_DUMMY_REL(child_rel))
7517  continue;
7518 
7519  /* Translate scan/join targets for this child. */
7520  appinfos = find_appinfos_by_relids(root, child_rel->relids,
7521  &nappinfos);
7522  foreach(lc, scanjoin_targets)
7523  {
7524  PathTarget *target = lfirst_node(PathTarget, lc);
7525 
7526  target = copy_pathtarget(target);
7527  target->exprs = (List *)
7529  (Node *) target->exprs,
7530  nappinfos, appinfos);
7531  child_scanjoin_targets = lappend(child_scanjoin_targets,
7532  target);
7533  }
7534  pfree(appinfos);
7535 
7536  /* Recursion does the real work. */
7537  apply_scanjoin_target_to_paths(root, child_rel,
7538  child_scanjoin_targets,
7539  scanjoin_targets_contain_srfs,
7540  scanjoin_target_parallel_safe,
7542 
7543  /* Save non-dummy children for Append paths. */
7544  if (!IS_DUMMY_REL(child_rel))
7545  live_children = lappend(live_children, child_rel);
7546  }
7547 
7548  /* Build new paths for this relation by appending child paths. */
7549  add_paths_to_append_rel(root, rel, live_children);
7550  }
7551 
7552  /*
7553  * Consider generating Gather or Gather Merge paths. We must only do this
7554  * if the relation is parallel safe, and we don't do it for child rels to
7555  * avoid creating multiple Gather nodes within the same plan. We must do
7556  * this after all paths have been generated and before set_cheapest, since
7557  * one of the generated paths may turn out to be the cheapest one.
7558  */
7559  if (rel->consider_parallel && !IS_OTHER_REL(rel))
7560  generate_useful_gather_paths(root, rel, false);
7561 
7562  /*
7563  * Reassess which paths are the cheapest, now that we've potentially added
7564  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
7565  * this relation.
7566  */
7567  set_cheapest(rel);
7568 }
#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:7356
PathTarget * pathtarget
Definition: pathnodes.h:1149
Query * parse
Definition: pathnodes.h:173
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:654
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1289
ParamPathInfo * param_info
Definition: pathnodes.h:1151
Definition: nodes.h:527
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2553
List * partial_pathlist
Definition: pathnodes.h:682
#define linitial_node(type, l)
Definition: pg_list.h:177
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:6050
void pfree(void *pointer)
Definition: mcxt.c:1057
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2877
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1423
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void check_stack_depth(void)
Definition: postgres.c:3317
int nparts
Definition: pathnodes.h:744
Index * sortgrouprefs
Definition: pathnodes.h:1079
Relids relids
Definition: pathnodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:321
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:728
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1078
#define llast_node(type, l)
Definition: pg_list.h:197
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
struct RelOptInfo ** part_rels
Definition: pathnodes.h:751
bool consider_parallel
Definition: pathnodes.h:674
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:240
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:766
List * pathlist
Definition: pathnodes.h:680
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:677
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)
static

Definition at line 7314 of file planner.c.

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

Referenced by create_grouping_paths().

7315 {
7316  Query *parse = root->parse;
7317 
7318  if (!parse->hasAggs && parse->groupClause == NIL)
7319  {
7320  /*
7321  * We don't know how to do parallel aggregation unless we have either
7322  * some aggregates or a grouping clause.
7323  */
7324  return false;
7325  }
7326  else if (parse->groupingSets)
7327  {
7328  /* We don't know how to do grouping sets in parallel. */
7329  return false;
7330  }
7331  else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
7332  {
7333  /* Insufficient support for partial mode. */
7334  return false;
7335  }
7336 
7337  /* Everything looks good. */
7338  return true;
7339 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:173
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
bool hasNonSerialAggs
Definition: pathnodes.h:354
List * groupClause
Definition: parsenodes.h:148
bool hasNonPartialAggs
Definition: pathnodes.h:353
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 5555 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().

5556 {
5557  const WindowClauseSortData *wcsa = a;
5558  const WindowClauseSortData *wcsb = b;
5559  ListCell *item_a;
5560  ListCell *item_b;
5561 
5562  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5563  {
5566 
5567  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5568  return -1;
5569  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5570  return 1;
5571  else if (sca->sortop > scb->sortop)
5572  return -1;
5573  else if (sca->sortop < scb->sortop)
5574  return 1;
5575  else if (sca->nulls_first && !scb->nulls_first)
5576  return -1;
5577  else if (!sca->nulls_first && scb->nulls_first)
5578  return 1;
5579  /* no need to compare eqop, since it is fully determined by sortop */
5580  }
5581 
5582  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5583  return -1;
5584  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5585  return 1;
5586 
5587  return 0;
5588 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:434
Index tleSortGroupRef
Definition: parsenodes.h:1263
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:149

◆ consider_groupingsets_paths()

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

Definition at line 4174 of file planner.c.

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

Referenced by add_paths_to_grouping_rel().

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

◆ create_degenerate_grouping_paths()

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

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

3975 {
3976  Query *parse = root->parse;
3977  int nrows;
3978  Path *path;
3979 
3980  nrows = list_length(parse->groupingSets);
3981  if (nrows > 1)
3982  {
3983  /*
3984  * Doesn't seem worthwhile writing code to cons up a generate_series
3985  * or a values scan to emit multiple rows. Instead just make N clones
3986  * and append them. (With a volatile HAVING clause, this means you
3987  * might get between 0 and N output rows. Offhand I think that's
3988  * desired.)
3989  */
3990  List *paths = NIL;
3991 
3992  while (--nrows >= 0)
3993  {
3994  path = (Path *)
3995  create_group_result_path(root, grouped_rel,
3996  grouped_rel->reltarget,
3997  (List *) parse->havingQual);
3998  paths = lappend(paths, path);
3999  }
4000  path = (Path *)
4001  create_append_path(root,
4002  grouped_rel,
4003  paths,
4004  NIL,
4005  NIL,
4006  NULL,
4007  0,
4008  false,
4009  NIL,
4010  -1);
4011  }
4012  else
4013  {
4014  /* No grouping sets, or just one, so one output row */
4015  path = (Path *)
4016  create_group_result_path(root, grouped_rel,
4017  grouped_rel->reltarget,
4018  (List *) parse->havingQual);
4019  }
4020 
4021  add_path(grouped_rel, path);
4022 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:173
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:1215
List * lappend(List *list, void *datum)
Definition: list.c:321
static int list_length(const List *l)
Definition: pg_list.h:149
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1479
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:677
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 4743 of file planner.c.

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

Referenced by grouping_planner().

4745 {
4746  Query *parse = root->parse;
4747  Path *cheapest_input_path = input_rel->cheapest_total_path;
4748  RelOptInfo *distinct_rel;
4749  double numDistinctRows;
4750  bool allow_hash;
4751  Path *path;
4752  ListCell *lc;
4753 
4754  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4755  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4756 
4757  /*
4758  * We don't compute anything at this level, so distinct_rel will be
4759  * parallel-safe if the input rel is parallel-safe. In particular, if
4760  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4761  * output those expressions, and will not be parallel-safe unless those
4762  * expressions are parallel-safe.
4763  */
4764  distinct_rel->consider_parallel = input_rel->consider_parallel;
4765 
4766  /*
4767  * If the input rel belongs to a single FDW, so does the distinct_rel.
4768  */
4769  distinct_rel->serverid = input_rel->serverid;
4770  distinct_rel->userid = input_rel->userid;
4771  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4772  distinct_rel->fdwroutine = input_rel->fdwroutine;
4773 
4774  /* Estimate number of distinct rows there will be */
4775  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4776  root->hasHavingQual)
4777  {
4778  /*
4779  * If there was grouping or aggregation, use the number of input rows
4780  * as the estimated number of DISTINCT rows (ie, assume the input is
4781  * already mostly unique).
4782  */
4783  numDistinctRows = cheapest_input_path->rows;
4784  }
4785  else
4786  {
4787  /*
4788  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4789  */
4790  List *distinctExprs;
4791 
4792  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4793  parse->targetList);
4794  numDistinctRows = estimate_num_groups(root, distinctExprs,
4795  cheapest_input_path->rows,
4796  NULL);
4797  }
4798 
4799  /*
4800  * Consider sort-based implementations of DISTINCT, if possible.
4801  */
4803  {
4804  /*
4805  * First, if we have any adequately-presorted paths, just stick a
4806  * Unique node on those. Then consider doing an explicit sort of the
4807  * cheapest input path and Unique'ing that.
4808  *
4809  * When we have DISTINCT ON, we must sort by the more rigorous of
4810  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4811  * Also, if we do have to do an explicit sort, we might as well use
4812  * the more rigorous ordering to avoid a second sort later. (Note
4813  * that the parser will have ensured that one clause is a prefix of
4814  * the other.)
4815  */
4816  List *needed_pathkeys;
4817 
4818  if (parse->hasDistinctOn &&
4820  list_length(root->sort_pathkeys))
4821  needed_pathkeys = root->sort_pathkeys;
4822  else
4823  needed_pathkeys = root->distinct_pathkeys;
4824 
4825  foreach(lc, input_rel->pathlist)
4826  {
4827  Path *path = (Path *) lfirst(lc);
4828 
4829  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4830  {
4831  add_path(distinct_rel, (Path *)
4832  create_upper_unique_path(root, distinct_rel,
4833  path,
4835  numDistinctRows));
4836  }
4837  }
4838 
4839  /* For explicit-sort case, always use the more rigorous clause */
4840  if (list_length(root->distinct_pathkeys) <
4841  list_length(root->sort_pathkeys))
4842  {
4843  needed_pathkeys = root->sort_pathkeys;
4844  /* Assert checks that parser didn't mess up... */
4846  needed_pathkeys));
4847  }
4848  else
4849  needed_pathkeys = root->distinct_pathkeys;
4850 
4851  path = cheapest_input_path;
4852  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4853  path = (Path *) create_sort_path(root, distinct_rel,
4854  path,
4855  needed_pathkeys,
4856  -1.0);
4857 
4858  add_path(distinct_rel, (Path *)
4859  create_upper_unique_path(root, distinct_rel,
4860  path,
4862  numDistinctRows));
4863  }
4864 
4865  /*
4866  * Consider hash-based implementations of DISTINCT, if possible.
4867  *
4868  * If we were not able to make any other types of path, we *must* hash or
4869  * die trying. If we do have other choices, there are two things that
4870  * should prevent selection of hashing: if the query uses DISTINCT ON
4871  * (because it won't really have the expected behavior if we hash), or if
4872  * enable_hashagg is off.
4873  *
4874  * Note: grouping_is_hashable() is much more expensive to check than the
4875  * other gating conditions, so we want to do it last.
4876  */
4877  if (distinct_rel->pathlist == NIL)
4878  allow_hash = true; /* we have no alternatives */
4879  else if (parse->hasDistinctOn || !enable_hashagg)
4880  allow_hash = false; /* policy-based decision not to hash */
4881  else
4882  allow_hash = true; /* default */
4883 
4884  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4885  {
4886  /* Generate hashed aggregate path --- no sort needed */
4887  add_path(distinct_rel, (Path *)
4888  create_agg_path(root,
4889  distinct_rel,
4890  cheapest_input_path,
4891  cheapest_input_path->pathtarget,
4892  AGG_HASHED,
4894  parse->distinctClause,
4895  NIL,
4896  NULL,
4897  numDistinctRows));
4898  }
4899 
4900  /* Give a helpful error if we failed to find any implementation */
4901  if (distinct_rel->pathlist == NIL)
4902  ereport(ERROR,
4903  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4904  errmsg("could not implement DISTINCT"),
4905  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4906 
4907  /*
4908  * If there is an FDW that's responsible for all baserels of the query,
4909  * let it consider adding ForeignPaths.
4910  */
4911  if (distinct_rel->fdwroutine &&
4912  distinct_rel->fdwroutine->GetForeignUpperPaths)
4913  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4914  input_rel, distinct_rel,
4915  NULL);
4916 
4917  /* Let extensions possibly add some more paths */
4919  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4920  input_rel, distinct_rel, NULL);
4921 
4922  /* Now choose the best path(s) */
4923  set_cheapest(distinct_rel);
4924 
4925  return distinct_rel;
4926 }
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:3360
PathTarget * pathtarget
Definition: pathnodes.h:1149
Query * parse
Definition: pathnodes.h:173
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:2954
Oid userid
Definition: pathnodes.h:716
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
int errcode(int sqlerrcode)
Definition: elog.c:691
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:717
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:1189
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:3006
struct Path * cheapest_total_path
Definition: pathnodes.h:684
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:719
int errdetail(const char *fmt,...)
Definition: elog.c:1035
List * sort_pathkeys
Definition: pathnodes.h:297
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:715
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
List * distinct_pathkeys
Definition: pathnodes.h:296
#define ereport(elevel,...)
Definition: elog.h:155
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
List * pathkeys
Definition: pathnodes.h:1162
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
static int list_length(const List *l)
Definition: pg_list.h:149
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
bool consider_parallel
Definition: pathnodes.h:674
bool enable_hashagg
Definition: costsize.c:139
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:902
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:562
bool hasHavingQual
Definition: pathnodes.h:341
List * pathlist
Definition: pathnodes.h:680
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,
grouping_sets_data gd 
)
static

Definition at line 3786 of file planner.c.

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

Referenced by grouping_planner().

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

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

Referenced by create_window_paths().

4633 {
4634  PathTarget *window_target;
4635  ListCell *l;
4636 
4637  /*
4638  * Since each window clause could require a different sort order, we stack
4639  * up a WindowAgg node for each clause, with sort steps between them as
4640  * needed. (We assume that select_active_windows chose a good order for
4641  * executing the clauses in.)
4642  *
4643  * input_target should contain all Vars and Aggs needed for the result.
4644  * (In some cases we wouldn't need to propagate all of these all the way
4645  * to the top, since they might only be needed as inputs to WindowFuncs.
4646  * It's probably not worth trying to optimize that though.) It must also
4647  * contain all window partitioning and sorting expressions, to ensure
4648  * they're computed only once at the bottom of the stack (that's critical
4649  * for volatile functions). As we climb up the stack, we'll add outputs
4650  * for the WindowFuncs computed at each level.
4651  */
4652  window_target = input_target;
4653 
4654  foreach(l, activeWindows)
4655  {
4657  List *window_pathkeys;
4658  int presorted_keys;
4659  bool is_sorted;
4660 
4661  window_pathkeys = make_pathkeys_for_window(root,
4662  wc,
4663  root->processed_tlist);
4664 
4665  is_sorted = pathkeys_count_contained_in(window_pathkeys,
4666  path->pathkeys,
4667  &presorted_keys);
4668 
4669  /* Sort if necessary */
4670  if (!is_sorted)
4671  {
4672  /*
4673  * No presorted keys or incremental sort disabled, just perform a
4674  * complete sort.
4675  */
4676  if (presorted_keys == 0 || !enable_incremental_sort)
4677  path = (Path *) create_sort_path(root, window_rel,
4678  path,
4679  window_pathkeys,
4680  -1.0);
4681  else
4682  {
4683  /*
4684  * Since we have presorted keys and incremental sort is
4685  * enabled, just use incremental sort.
4686  */
4687  path = (Path *) create_incremental_sort_path(root,
4688  window_rel,
4689  path,
4690  window_pathkeys,
4691  presorted_keys,
4692  -1.0);
4693  }
4694  }
4695 
4696  if (lnext(activeWindows, l))
4697  {
4698  /*
4699  * Add the current WindowFuncs to the output target for this
4700  * intermediate WindowAggPath. We must copy window_target to
4701  * avoid changing the previous path's target.
4702  *
4703  * Note: a WindowFunc adds nothing to the target's eval costs; but
4704  * we do need to account for the increase in tlist width.
4705  */
4706  ListCell *lc2;
4707 
4708  window_target = copy_pathtarget(window_target);
4709  foreach(lc2, wflists->windowFuncs[wc->winref])
4710  {
4711  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4712 
4713  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4714  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4715  }
4716  }
4717  else
4718  {
4719  /* Install the goal target in the topmost WindowAgg */
4720  window_target = output_target;
4721  }
4722 
4723  path = (Path *)
4724  create_windowagg_path(root, window_rel, path, window_target,
4725  wflists->windowFuncs[wc->winref],
4726  wc);
4727  }
4728 
4729  add_path(window_rel, path);
4730 }
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:672
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:138
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:710
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2802
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5742
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2471
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
List * pathkeys
Definition: pathnodes.h:1162
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause)
Definition: pathnode.c:3305
Oid wintype
Definition: primnodes.h:382
List * processed_tlist
Definition: pathnodes.h:319
Definition: pg_list.h:50
List ** windowFuncs
Definition: clauses.h:23

◆ create_ordered_paths()

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

Definition at line 4946 of file planner.c.

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

Referenced by grouping_planner().

4951 {
4952  Path *cheapest_input_path = input_rel->cheapest_total_path;
4953  RelOptInfo *ordered_rel;
4954  ListCell *lc;
4955 
4956  /* For now, do all work in the (ORDERED, NULL) upperrel */
4957  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4958 
4959  /*
4960  * If the input relation is not parallel-safe, then the ordered relation
4961  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4962  * target list is parallel-safe.
4963  */
4964  if (input_rel->consider_parallel && target_parallel_safe)
4965  ordered_rel->consider_parallel = true;
4966 
4967  /*
4968  * If the input rel belongs to a single FDW, so does the ordered_rel.
4969  */
4970  ordered_rel->serverid = input_rel->serverid;
4971  ordered_rel->userid = input_rel->userid;
4972  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4973  ordered_rel->fdwroutine = input_rel->fdwroutine;
4974 
4975  foreach(lc, input_rel->pathlist)
4976  {
4977  Path *input_path = (Path *) lfirst(lc);
4978  Path *sorted_path = input_path;
4979  bool is_sorted;
4980  int presorted_keys;
4981 
4982  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
4983  input_path->pathkeys, &presorted_keys);
4984 
4985  if (is_sorted)
4986  {
4987  /* Use the input path as is, but add a projection step if needed */
4988  if (sorted_path->pathtarget != target)
4989  sorted_path = apply_projection_to_path(root, ordered_rel,
4990  sorted_path, target);
4991 
4992  add_path(ordered_rel, sorted_path);
4993  }
4994  else
4995  {
4996  /*
4997  * Try adding an explicit sort, but only to the cheapest total
4998  * path since a full sort should generally add the same cost to
4999  * all paths.
5000  */
5001  if (input_path == cheapest_input_path)
5002  {
5003  /*
5004  * Sort the cheapest input path. An explicit sort here can
5005  * take advantage of LIMIT.
5006  */
5007  sorted_path = (Path *) create_sort_path(root,
5008  ordered_rel,
5009  input_path,
5010  root->sort_pathkeys,
5011  limit_tuples);
5012  /* Add projection step if needed */
5013  if (sorted_path->pathtarget != target)
5014  sorted_path = apply_projection_to_path(root, ordered_rel,
5015  sorted_path, target);
5016 
5017  add_path(ordered_rel, sorted_path);
5018  }
5019 
5020  /*
5021  * If incremental sort is enabled, then try it as well. Unlike
5022  * with regular sorts, we can't just look at the cheapest path,
5023  * because the cost of incremental sort depends on how well
5024  * presorted the path is. Additionally incremental sort may enable
5025  * a cheaper startup path to win out despite higher total cost.
5026  */
5028  continue;
5029 
5030  /* Likewise, if the path can't be used for incremental sort. */
5031  if (!presorted_keys)
5032  continue;
5033 
5034  /* Also consider incremental sort. */
5035  sorted_path = (Path *) create_incremental_sort_path(root,
5036  ordered_rel,
5037  input_path,
5038  root->sort_pathkeys,
5039  presorted_keys,
5040  limit_tuples);
5041 
5042  /* Add projection step if needed */
5043  if (sorted_path->pathtarget != target)
5044  sorted_path = apply_projection_to_path(root, ordered_rel,
5045  sorted_path, target);
5046 
5047  add_path(ordered_rel, sorted_path);
5048  }
5049  }
5050 
5051  /*
5052  * generate_gather_paths() will have already generated a simple Gather
5053  * path for the best parallel path, if any, and the loop above will have
5054  * considered sorting it. Similarly, generate_gather_paths() will also
5055  * have generated order-preserving Gather Merge plans which can be used
5056  * without sorting if they happen to match the sort_pathkeys, and the loop
5057  * above will have handled those as well. However, there's one more
5058  * possibility: it may make sense to sort the cheapest partial path
5059  * according to the required output order and then use Gather Merge.
5060  */
5061  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5062  input_rel->partial_pathlist != NIL)
5063  {
5064  Path *cheapest_partial_path;
5065 
5066  cheapest_partial_path = linitial(input_rel->partial_pathlist);
5067 
5068  /*
5069  * If cheapest partial path doesn't need a sort, this is redundant
5070  * with what's already been tried.
5071  */
5073  cheapest_partial_path->pathkeys))
5074  {
5075  Path *path;
5076  double total_groups;
5077 
5078  path = (Path *) create_sort_path(root,
5079  ordered_rel,
5080  cheapest_partial_path,
5081  root->sort_pathkeys,
5082  limit_tuples);
5083 
5084  total_groups = cheapest_partial_path->rows *
5085  cheapest_partial_path->parallel_workers;
5086  path = (Path *)
5087  create_gather_merge_path(root, ordered_rel,
5088  path,
5089  path->pathtarget,
5090  root->sort_pathkeys, NULL,
5091  &total_groups);
5092 
5093  /* Add projection step if needed */
5094  if (path->pathtarget != target)
5095  path = apply_projection_to_path(root, ordered_rel,
5096  path, target);
5097 
5098  add_path(ordered_rel, path);
5099  }
5100 
5101  /*
5102  * Consider incremental sort with a gather merge on partial paths.
5103  *
5104  * We can also skip the entire loop when we only have a single-item
5105  * sort_pathkeys because then we can't possibly have a presorted
5106  * prefix of the list without having the list be fully sorted.
5107  */
5109  {
5110  ListCell *lc;
5111 
5112  foreach(lc, input_rel->partial_pathlist)
5113  {
5114  Path *input_path = (Path *) lfirst(lc);
5115  Path *sorted_path;
5116  bool is_sorted;
5117  int presorted_keys;
5118  double total_groups;
5119 
5120  /*
5121  * We don't care if this is the cheapest partial path - we
5122  * can't simply skip it, because it may be partially sorted in
5123  * which case we want to consider adding incremental sort
5124  * (instead of full sort, which is what happens above).
5125  */
5126 
5127  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5128  input_path->pathkeys,
5129  &presorted_keys);
5130 
5131  /* No point in adding incremental sort on fully sorted paths. */
5132  if (is_sorted)
5133  continue;
5134 
5135  if (presorted_keys == 0)
5136  continue;
5137 
5138  /* Since we have presorted keys, consider incremental sort. */
5139  sorted_path = (Path *) create_incremental_sort_path(root,
5140  ordered_rel,
5141  input_path,
5142  root->sort_pathkeys,
5143  presorted_keys,
5144  limit_tuples);
5145  total_groups = input_path->rows *
5146  input_path->parallel_workers;
5147  sorted_path = (Path *)
5148  create_gather_merge_path(root, ordered_rel,
5149  sorted_path,
5150  sorted_path->pathtarget,
5151  root->sort_pathkeys, NULL,
5152  &total_groups);
5153 
5154  /* Add projection step if needed */
5155  if (sorted_path->pathtarget != target)
5156  sorted_path = apply_projection_to_path(root, ordered_rel,
5157  sorted_path, target);
5158 
5159  add_path(ordered_rel, sorted_path);
5160  }
5161  }
5162  }
5163 
5164  /*
5165  * If there is an FDW that's responsible for all baserels of the query,
5166  * let it consider adding ForeignPaths.
5167  */
5168  if (ordered_rel->fdwroutine &&
5169  ordered_rel->fdwroutine->GetForeignUpperPaths)
5170  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5171  input_rel, ordered_rel,
5172  NULL);
5173 
5174  /* Let extensions possibly add some more paths */
5176  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5177  input_rel, ordered_rel, NULL);
5178 
5179  /*
5180  * No need to bother with set_cheapest here; grouping_planner does not
5181  * need us to do it.
5182  */
5183  Assert(ordered_rel->pathlist != NIL);
5184 
5185  return ordered_rel;
5186 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2644
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1149
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:138
Oid userid
Definition: pathnodes.h:716
int parallel_workers
Definition: pathnodes.h:1155
List * partial_pathlist
Definition: pathnodes.h:682
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:717
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2802
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define linitial(l)
Definition: pg_list.h:174
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1189
struct Path * cheapest_total_path
Definition: pathnodes.h:684
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:719
List * sort_pathkeys
Definition: pathnodes.h:297
Oid serverid
Definition: pathnodes.h:715
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:1787
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
List * pathkeys
Definition: pathnodes.h:1162
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
static int list_length(const List *l)
Definition: pg_list.h:149
bool consider_parallel
Definition: pathnodes.h:674
List * pathlist
Definition: pathnodes.h:680

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

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

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

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

Referenced by create_ordinary_grouping_paths().

6847 {
6848  Query *parse = root->parse;
6849  RelOptInfo *partially_grouped_rel;
6850  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
6851  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6852  Path *cheapest_partial_path = NULL;
6853  Path *cheapest_total_path = NULL;
6854  double dNumPartialGroups = 0;
6855  double dNumPartialPartialGroups = 0;
6856  ListCell *lc;
6857  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6858  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6859 
6860  /*
6861  * Consider whether we should generate partially aggregated non-partial
6862  * paths. We can only do this if we have a non-partial path, and only if
6863  * the parent of the input rel is performing partial partitionwise
6864  * aggregation. (Note that extra->patype is the type of partitionwise
6865  * aggregation being used at the parent level, not this level.)
6866  */
6867  if (input_rel->pathlist != NIL &&
6869  cheapest_total_path = input_rel->cheapest_total_path;
6870 
6871  /*
6872  * If parallelism is possible for grouped_rel, then we should consider
6873  * generating partially-grouped partial paths. However, if the input rel
6874  * has no partial paths, then we can't.
6875  */
6876  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
6877  cheapest_partial_path = linitial(input_rel->partial_pathlist);
6878 
6879  /*
6880  * If we can't partially aggregate partial paths, and we can't partially
6881  * aggregate non-partial paths, then don't bother creating the new
6882  * RelOptInfo at all, unless the caller specified force_rel_creation.
6883  */
6884  if (cheapest_total_path == NULL &&
6885  cheapest_partial_path == NULL &&
6886  !force_rel_creation)
6887  return NULL;
6888 
6889  /*
6890  * Build a new upper relation to represent the result of partially
6891  * aggregating the rows from the input relation.
6892  */
6893  partially_grouped_rel = fetch_upper_rel(root,
6895  grouped_rel->relids);
6896  partially_grouped_rel->consider_parallel =
6897  grouped_rel->consider_parallel;
6898  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
6899  partially_grouped_rel->serverid = grouped_rel->serverid;
6900  partially_grouped_rel->userid = grouped_rel->userid;
6901  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
6902  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
6903 
6904  /*
6905  * Build target list for partial aggregate paths. These paths cannot just
6906  * emit the same tlist as regular aggregate paths, because (1) we must
6907  * include Vars and Aggrefs needed in HAVING, which might not appear in
6908  * the result tlist, and (2) the Aggrefs must be set in partial mode.
6909  */
6910  partially_grouped_rel->reltarget =
6911  make_partial_grouping_target(root, grouped_rel->reltarget,
6912  extra->havingQual);
6913 
6914  if (!extra->partial_costs_set)
6915  {
6916  /*
6917  * Collect statistics about aggregates for estimating costs of
6918  * performing aggregation in parallel.
6919  */
6920  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
6921  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
6922  if (parse->hasAggs)
6923  {
6924  /* partial phase */
6926  agg_partial_costs);
6927 
6928  /* final phase */
6930  agg_final_costs);
6931  }
6932 
6933  extra->partial_costs_set = true;
6934  }
6935 
6936  /* Estimate number of partial groups. */
6937  if (cheapest_total_path != NULL)
6938  dNumPartialGroups =
6939  get_number_of_groups(root,
6940  cheapest_total_path->rows,
6941  gd,
6942  extra->targetList);
6943  if (cheapest_partial_path != NULL)
6944  dNumPartialPartialGroups =
6945  get_number_of_groups(root,
6946  cheapest_partial_path->rows,
6947  gd,
6948  extra->targetList);
6949 
6950  if (can_sort && cheapest_total_path != NULL)
6951  {
6952  /* This should have been checked previously */
6953  Assert(parse->hasAggs || parse->groupClause);
6954 
6955  /*
6956  * Use any available suitably-sorted path as input, and also consider
6957  * sorting the cheapest partial path.
6958  */
6959  foreach(lc, input_rel->pathlist)
6960  {
6961  Path *path = (Path *) lfirst(lc);
6962  bool is_sorted;
6963 
6964  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6965  path->pathkeys);
6966  if (path == cheapest_total_path || is_sorted)
6967  {
6968  /* Sort the cheapest partial path, if it isn't already */
6969  if (!is_sorted)
6970  path = (Path *) create_sort_path(root,
6971  partially_grouped_rel,
6972  path,
6973  root->group_pathkeys,
6974  -1.0);
6975 
6976  if (parse->hasAggs)
6977  add_path(partially_grouped_rel, (Path *)
6978  create_agg_path(root,
6979  partially_grouped_rel,
6980  path,
6981  partially_grouped_rel->reltarget,
6982  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6984  parse->groupClause,
6985  NIL,
6986  agg_partial_costs,
6987  dNumPartialGroups));
6988  else
6989  add_path(partially_grouped_rel, (Path *)
6990  create_group_path(root,
6991  partially_grouped_rel,
6992  path,
6993  parse->groupClause,
6994  NIL,
6995  dNumPartialGroups));
6996  }
6997  }
6998 
6999  /*
7000  * Consider incremental sort on all partial paths, if enabled.
7001  *
7002  * We can also skip the entire loop when we only have a single-item
7003  * group_pathkeys because then we can't possibly have a presorted
7004  * prefix of the list without having the list be fully sorted.
7005  */
7007  {
7008  foreach(lc, input_rel->pathlist)
7009  {
7010  Path *path = (Path *) lfirst(lc);
7011  bool is_sorted;
7012  int presorted_keys;
7013 
7014  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7015  path->pathkeys,
7016  &presorted_keys);
7017 
7018  /* Ignore already sorted paths */
7019  if (is_sorted)
7020  continue;
7021 
7022  if (presorted_keys == 0)
7023  continue;
7024 
7025  /* Since we have presorted keys, consider incremental sort. */
7026  path = (Path *) create_incremental_sort_path(root,
7027  partially_grouped_rel,
7028  path,
7029  root->group_pathkeys,
7030  presorted_keys,
7031  -1.0);
7032 
7033  if (parse->hasAggs)
7034  add_path(partially_grouped_rel, (Path *)
7035  create_agg_path(root,
7036  partially_grouped_rel,
7037  path,
7038  partially_grouped_rel->reltarget,
7039  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7041  parse->groupClause,
7042  NIL,
7043  agg_partial_costs,
7044  dNumPartialGroups));
7045  else
7046  add_path(partially_grouped_rel, (Path *)
7047  create_group_path(root,
7048  partially_grouped_rel,
7049  path,
7050  parse->groupClause,
7051  NIL,
7052  dNumPartialGroups));
7053  }
7054  }
7055 
7056  }
7057 
7058  if (can_sort && cheapest_partial_path != NULL)
7059  {
7060  /* Similar to above logic, but for partial paths. */
7061  foreach(lc, input_rel->partial_pathlist)
7062  {
7063  Path *path = (Path *) lfirst(lc);
7064  Path *path_original = path;
7065  bool is_sorted;
7066  int presorted_keys;
7067 
7068  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7069  path->pathkeys,
7070  &presorted_keys);
7071 
7072  if (path == cheapest_partial_path || is_sorted)
7073  {
7074  /* Sort the cheapest partial path, if it isn't already */
7075  if (!is_sorted)
7076  path = (Path *) create_sort_path(root,
7077  partially_grouped_rel,
7078  path,
7079  root->group_pathkeys,
7080  -1.0);
7081 
7082  if (parse->hasAggs)
7083  add_partial_path(partially_grouped_rel, (Path *)
7084  create_agg_path(root,
7085  partially_grouped_rel,
7086  path,
7087  partially_grouped_rel->reltarget,
7088  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7090  parse->groupClause,
7091  NIL,
7092  agg_partial_costs,
7093  dNumPartialPartialGroups));
7094  else
7095  add_partial_path(partially_grouped_rel, (Path *)
7096  create_group_path(root,
7097  partially_grouped_rel,
7098  path,
7099  parse->groupClause,
7100  NIL,
7101  dNumPartialPartialGroups));
7102  }
7103 
7104  /*
7105  * Now we may consider incremental sort on this path, but only
7106  * when the path is not already sorted and when incremental sort
7107  * is enabled.
7108  */
7109  if (is_sorted || !enable_incremental_sort)
7110  continue;
7111 
7112  /* Restore the input path (we might have added Sort on top). */
7113  path = path_original;
7114 
7115  /* no shared prefix, not point in building incremental sort */
7116  if (presorted_keys == 0)
7117  continue;
7118 
7119  /*
7120  * We should have already excluded pathkeys of length 1 because
7121  * then presorted_keys > 0 would imply is_sorted was true.
7122  */
7123  Assert(list_length(root->group_pathkeys) != 1);
7124 
7125  path = (Path *) create_incremental_sort_path(root,
7126  partially_grouped_rel,
7127  path,
7128  root->group_pathkeys,
7129  presorted_keys,
7130  -1.0);
7131 
7132  if (parse->hasAggs)
7133  add_partial_path(partially_grouped_rel, (Path *)
7134  create_agg_path(root,
7135  partially_grouped_rel,
7136  path,
7137  partially_grouped_rel->reltarget,
7138  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7140  parse->groupClause,
7141  NIL,
7142  agg_partial_costs,
7143  dNumPartialPartialGroups));
7144  else
7145  add_partial_path(partially_grouped_rel, (Path *)
7146  create_group_path(root,
7147  partially_grouped_rel,
7148  path,
7149  parse->groupClause,
7150  NIL,
7151  dNumPartialPartialGroups));
7152  }
7153  }
7154 
7155  /*
7156  * Add a partially-grouped HashAgg Path where possible
7157  */
7158  if (can_hash && cheapest_total_path != NULL)
7159  {
7160  /* Checked above */
7161  Assert(parse->hasAggs || parse->groupClause);
7162 
7163  add_path(partially_grouped_rel, (Path *)
7164  create_agg_path(root,
7165  partially_grouped_rel,
7166  cheapest_total_path,
7167  partially_grouped_rel->reltarget,
7168  AGG_HASHED,
7170  parse->groupClause,
7171  NIL,
7172  agg_partial_costs,
7173  dNumPartialGroups));
7174  }
7175 
7176  /*
7177  * Now add a partially-grouped HashAgg partial Path where possible
7178  */
7179  if (can_hash && cheapest_partial_path != NULL)
7180  {
7181  add_partial_path(partially_grouped_rel, (Path *)
7182  create_agg_path(root,
7183  partially_grouped_rel,
7184  cheapest_partial_path,
7185  partially_grouped_rel->reltarget,
7186  AGG_HASHED,
7188  parse->groupClause,
7189  NIL,
7190  agg_partial_costs,
7191  dNumPartialPartialGroups));
7192  }
7193 
7194  /*
7195  * If there is an FDW that's responsible for all baserels of the query,
7196  * let it consider adding partially grouped ForeignPaths.
7197  */
7198  if (partially_grouped_rel->fdwroutine &&
7199  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
7200  {
7201  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
7202 
7203  fdwroutine->GetForeignUpperPaths(root,
7205  input_rel, partially_grouped_rel,
7206  extra);
7207  }
7208 
7209  return partially_grouped_rel;
7210 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
List * group_pathkeys
Definition: pathnodes.h:294
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:173
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:138
RelOptKind reloptkind
Definition: pathnodes.h:663
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3666
Oid userid
Definition: pathnodes.h:716
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:2496
bool hasAggs
Definition: parsenodes.h:125
PartitionwiseAggregateType patype
Definition: pathnodes.h:2503
List * partial_pathlist
Definition: pathnodes.h:682
#define MemSet(start, val, len)
Definition: c.h:1004
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:542
bool useridiscurrent
Definition: pathnodes.h:717
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2802
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2456
#define linitial(l)
Definition: pg_list.h:174
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1189
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:3006
struct Path * cheapest_total_path
Definition: pathnodes.h:684
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:719
Relids relids
Definition: pathnodes.h:666
Oid serverid
Definition: pathnodes.h:715
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2457
List * pathkeys
Definition: pathnodes.h:1162
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:5304
static int list_length(const List *l)
Definition: pg_list.h:149
bool consider_parallel
Definition: pathnodes.h:674
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:680
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2895
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2497
struct PathTarget * reltarget
Definition: pathnodes.h:677
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 7588 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().

7596 {
7597  int nparts = input_rel->nparts;
7598  int cnt_parts;
7599  List *grouped_live_children = NIL;
7600  List *partially_grouped_live_children = NIL;
7601  PathTarget *target = grouped_rel->reltarget;
7602  bool partial_grouping_valid = true;
7603 
7606  partially_grouped_rel != NULL);
7607 
7608  /* Add paths for partitionwise aggregation/grouping. */
7609  for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
7610  {
7611  RelOptInfo *child_input_rel = input_rel->part_rels[cnt_parts];
7612  PathTarget *child_target = copy_pathtarget(target);
7613  AppendRelInfo **appinfos;
7614  int nappinfos;
7615  GroupPathExtraData child_extra;
7616  RelOptInfo *child_grouped_rel;
7617  RelOptInfo *child_partially_grouped_rel;
7618 
7619  /* Pruned or dummy children can be ignored. */
7620  if (child_input_rel == NULL || IS_DUMMY_REL(child_input_rel))
7621  continue;
7622 
7623  /*
7624  * Copy the given "extra" structure as is and then override the
7625  * members specific to this child.
7626  */
7627  memcpy(&child_extra, extra, sizeof(child_extra));
7628 
7629  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7630  &nappinfos);
7631 
7632  child_target->exprs = (List *)
7634  (Node *) target->exprs,
7635  nappinfos, appinfos);
7636 
7637  /* Translate havingQual and targetList. */
7638  child_extra.havingQual = (Node *)
7640  extra->havingQual,
7641  nappinfos, appinfos);
7642  child_extra.targetList = (List *)
7644  (Node *) extra->targetList,
7645  nappinfos, appinfos);
7646 
7647  /*
7648  * extra->patype was the value computed for our parent rel; patype is
7649  * the value for this relation. For the child, our value is its
7650  * parent rel's value.
7651  */
7652  child_extra.patype = patype;
7653 
7654  /*
7655  * Create grouping relation to hold fully aggregated grouping and/or
7656  * aggregation paths for the child.
7657  */
7658  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7659  child_target,
7660  extra->target_parallel_safe,
7661  child_extra.havingQual);
7662 
7663  /* Create grouping paths for this child relation. */
7664  create_ordinary_grouping_paths(root, child_input_rel,
7665  child_grouped_rel,
7666  agg_costs, gd, &child_extra,
7667  &child_partially_grouped_rel);
7668 
7669  if (child_partially_grouped_rel)
7670  {
7671  partially_grouped_live_children =
7672  lappend(partially_grouped_live_children,
7673  child_partially_grouped_rel);
7674  }
7675  else
7676  partial_grouping_valid = false;
7677 
7678  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7679  {
7680  set_cheapest(child_grouped_rel);
7681  grouped_live_children = lappend(grouped_live_children,
7682  child_grouped_rel);
7683  }
7684 
7685  pfree(appinfos);
7686  }
7687 
7688  /*
7689  * Try to create append paths for partially grouped children. For full
7690  * partitionwise aggregation, we might have paths in the partial_pathlist
7691  * if parallel aggregation is possible. For partial partitionwise
7692  * aggregation, we may have paths in both pathlist and partial_pathlist.
7693  *
7694  * NB: We must have a partially grouped path for every child in order to
7695  * generate a partially grouped path for this relation.
7696  */
7697  if (partially_grouped_rel && partial_grouping_valid)
7698  {
7699  Assert(partially_grouped_live_children != NIL);
7700 
7701  add_paths_to_append_rel(root, partially_grouped_rel,
7702  partially_grouped_live_children);
7703 
7704  /*
7705  * We need call set_cheapest, since the finalization step will use the
7706  * cheapest path from the rel.
7707  */
7708  if (partially_grouped_rel->pathlist)
7709  set_cheapest(partially_grouped_rel);
7710  }
7711 
7712  /* If possible, create append paths for fully grouped children. */
7713  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7714  {
7715  Assert(grouped_live_children != NIL);
7716 
7717  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7718  }
7719 }
#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:3899
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1289
Definition: nodes.h:527
PartitionwiseAggregateType patype
Definition: pathnodes.h:2503
void pfree(void *pointer)
Definition: mcxt.c:1057
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1423
int nparts
Definition: pathnodes.h:744
Relids relids
Definition: pathnodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:321
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:728
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1078
#define Assert(condition)
Definition: c.h:800
struct RelOptInfo ** part_rels
Definition: pathnodes.h:751
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:4038
List * pathlist
Definition: pathnodes.h:680
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:677
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 4539 of file planner.c.

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

Referenced by grouping_planner().

4546 {
4547  RelOptInfo *window_rel;
4548  ListCell *lc;
4549 
4550  /* For now, do all work in the (WINDOW, NULL) upperrel */
4551  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4552 
4553  /*
4554  * If the input relation is not parallel-safe, then the window relation
4555  * can't be parallel-safe, either. Otherwise, we need to examine the
4556  * target list and active windows for non-parallel-safe constructs.
4557  */
4558  if (input_rel->consider_parallel && output_target_parallel_safe &&
4559  is_parallel_safe(root, (Node *) activeWindows))
4560  window_rel->consider_parallel = true;
4561 
4562  /*
4563  * If the input rel belongs to a single FDW, so does the window rel.
4564  */
4565  window_rel->serverid = input_rel->serverid;
4566  window_rel->userid = input_rel->userid;
4567  window_rel->useridiscurrent = input_rel->useridiscurrent;
4568  window_rel->fdwroutine = input_rel->fdwroutine;
4569 
4570  /*
4571  * Consider computing window functions starting from the existing
4572  * cheapest-total path (which will likely require a sort) as well as any
4573  * existing paths that satisfy or partially satisfy root->window_pathkeys.
4574  */
4575  foreach(lc, input_rel->pathlist)
4576  {
4577  Path *path = (Path *) lfirst(lc);
4578  int presorted_keys;
4579 
4580  if (path == input_rel->cheapest_total_path ||
4582  &presorted_keys) ||
4583  presorted_keys > 0)
4585  window_rel,
4586  path,
4587  input_target,
4588  output_target,
4589  wflists,
4590  activeWindows);
4591  }
4592 
4593  /*
4594  * If there is an FDW that's responsible for all baserels of the query,
4595  * let it consider adding ForeignPaths.
4596  */
4597  if (window_rel->fdwroutine &&
4598  window_rel->fdwroutine->GetForeignUpperPaths)
4599  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4600  input_rel, window_rel,
4601  NULL);
4602 
4603  /* Let extensions possibly add some more paths */
4605  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4606  input_rel, window_rel, NULL);
4607 
4608  /* Now choose the best path(s) */
4609  set_cheapest(window_rel);
4610 
4611  return window_rel;
4612 }
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:4626
Oid userid
Definition: pathnodes.h:716
Definition: nodes.h:527
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:77
bool useridiscurrent
Definition: pathnodes.h:717
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:566
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1189
struct Path * cheapest_total_path
Definition: pathnodes.h:684
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:719
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: pathnodes.h:715
List * window_pathkeys
Definition: pathnodes.h:295
List * pathkeys
Definition: pathnodes.h:1162
#define lfirst(lc)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:674
List * pathlist
Definition: pathnodes.h:680

◆ expression_planner()

Expr* expression_planner ( Expr expr)

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

6167 {
6168  Node *result;
6169 
6170  /*
6171  * Convert named-argument function calls, insert default arguments and
6172  * simplify constant subexprs
6173  */
6174  result = eval_const_expressions(NULL, (Node *) expr);
6175 
6176  /* Fill in opfuncid values if missing */
6177  fix_opfuncids(result);
6178 
6179  return (Expr *) result;
6180 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1636
Definition: nodes.h:527
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:1999

◆ expression_planner_with_deps()

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

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

6196 {
6197  Node *result;
6198  PlannerGlobal glob;
6199  PlannerInfo root;
6200 
6201  /* Make up dummy planner state so we can use setrefs machinery */
6202  MemSet(&glob, 0, sizeof(glob));
6203  glob.type = T_PlannerGlobal;
6204  glob.relationOids = NIL;
6205  glob.invalItems = NIL;
6206 
6207  MemSet(&root, 0, sizeof(root));
6208  root.type = T_PlannerInfo;
6209  root.glob = &glob;
6210 
6211  /*
6212  * Convert named-argument function calls, insert default arguments and
6213  * simplify constant subexprs. Collect identities of inlined functions
6214  * and elided domains, too.
6215  */
6216  result = eval_const_expressions(&root, (Node *) expr);
6217 
6218  /* Fill in opfuncid values if missing */
6219  fix_opfuncids(result);
6220 
6221  /*
6222  * Now walk the finished expression to find anything else we ought to
6223  * record as an expression dependency.
6224  */
6225  (void) extract_query_dependencies_walker(result, &root);
6226 
6227  *relationOids = glob.relationOids;
6228  *invalItems = glob.invalItems;
6229 
6230  return (Expr *) result;
6231 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1636
Definition: nodes.h:527
#define MemSet(start, val, len)
Definition: c.h:1004
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:1999
PlannerGlobal * glob
Definition: pathnodes.h:175
List * invalItems
Definition: pathnodes.h:123
NodeTag type
Definition: pathnodes.h:171
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3006
NodeTag type
Definition: pathnodes.h:103
List * relationOids
Definition: pathnodes.h:121

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

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

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

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

Referenced by add_paths_to_grouping_rel(), and create_ordinary_grouping_paths().

7227 {
7228  ListCell *lc;
7229  Path *cheapest_partial_path;
7230 
7231  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
7232  generate_useful_gather_paths(root, rel, true);
7233 
7234  /* Try cheapest partial path + explicit Sort + Gather Merge. */
7235  cheapest_partial_path = linitial(rel->partial_pathlist);
7237  cheapest_partial_path->pathkeys))
7238  {
7239  Path *path;
7240  double total_groups;
7241 
7242  total_groups =
7243  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
7244  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
7245  root->group_pathkeys,
7246  -1.0);
7247  path = (Path *)
7249  rel,
7250  path,
7251  rel->reltarget,
7252  root->group_pathkeys,
7253  NULL,
7254  &total_groups);
7255 
7256  add_path(rel, path);
7257  }
7258 
7259  /*
7260  * Consider incremental sort on all partial paths, if enabled.
7261  *
7262  * We can also skip the entire loop when we only have a single-item
7263  * group_pathkeys because then we can't possibly have a presorted prefix
7264  * of the list without having the list be fully sorted.
7265  */
7267  return;
7268 
7269  /* also consider incremental sort on partial paths, if enabled */
7270  foreach(lc, rel->partial_pathlist)
7271  {
7272  Path *path = (Path *) lfirst(lc);
7273  bool is_sorted;
7274  int presorted_keys;
7275  double total_groups;
7276 
7277  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7278  path->pathkeys,
7279  &presorted_keys);
7280 
7281  if (is_sorted)
7282  continue;
7283 
7284  if (presorted_keys == 0)
7285  continue;
7286 
7287  path = (Path *) create_incremental_sort_path(root,
7288  rel,
7289  path,
7290  root->group_pathkeys,
7291  presorted_keys,
7292  -1.0);
7293 
7294  path = (Path *)
7296  rel,
7297  path,
7298  rel->reltarget,
7299  root->group_pathkeys,
7300  NULL,
7301  &total_groups);
7302 
7303  add_path(rel, path);
7304  }
7305 }
List * group_pathkeys
Definition: pathnodes.h:294
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:138
int parallel_workers
Definition: pathnodes.h:1155
List * partial_pathlist
Definition: pathnodes.h:682
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2802
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define linitial(l)
Definition: pg_list.h:174
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2877
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:1787
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
List * pathkeys
Definition: pathnodes.h:1162
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
static int list_length(const List *l)
Definition: pg_list.h:149
struct PathTarget * reltarget
Definition: pathnodes.h:677

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

6008 {
6009  Path *best_path = rel->cheapest_total_path;
6010  ListCell *l;
6011 
6012  /* If all tuples will be retrieved, just return the cheapest-total path */
6013  if (tuple_fraction <= 0.0)
6014  return best_path;
6015 
6016  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
6017  if (tuple_fraction >= 1.0 && best_path->rows > 0)
6018  tuple_fraction /= best_path->rows;
6019 
6020  foreach(l, rel->pathlist)
6021  {
6022  Path *path = (Path *) lfirst(l);
6023 
6024  if (path == rel->cheapest_total_path ||
6025  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
6026  continue;
6027 
6028  best_path = path;
6029  }
6030 
6031  return best_path;
6032 }
struct Path * cheapest_total_path
Definition: pathnodes.h:684
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: pathnodes.h:680

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

3670 {
3671  Query *parse = root->parse;
3672  double dNumGroups;
3673 
3674  if (parse->groupClause)
3675  {
3676  List *groupExprs;
3677 
3678  if (parse->groupingSets)
3679  {
3680  /* Add up the estimates for each grouping set */
3681  ListCell *lc;
3682  ListCell *lc2;
3683 
3684  Assert(gd); /* keep Coverity happy */
3685 
3686  dNumGroups = 0;
3687 
3688  foreach(lc, gd->rollups)
3689  {
3690  RollupData *rollup = lfirst_node(RollupData, lc);
3691  ListCell *lc;
3692 
3693  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3694  target_list);
3695 
3696  rollup->numGroups = 0.0;
3697 
3698  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3699  {
3700  List *gset = (List *) lfirst(lc);
3702  double numGroups = estimate_num_groups(root,
3703  groupExprs,
3704  path_rows,
3705  &gset);
3706 
3707  gs->numGroups = numGroups;
3708  rollup->numGroups += numGroups;
3709  }
3710 
3711  dNumGroups += rollup->numGroups;
3712  }
3713 
3714  if (gd->hash_sets_idx)
3715  {
3716  ListCell *lc;
3717 
3718  gd->dNumHashGroups = 0;
3719 
3720  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3721  target_list);
3722 
3723  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3724  {
3725  List *gset = (List *) lfirst(lc);
3727  double numGroups = estimate_num_groups(root,
3728  groupExprs,
3729  path_rows,
3730  &gset);
3731 
3732  gs->numGroups = numGroups;
3733  gd->dNumHashGroups += numGroups;
3734  }
3735 
3736  dNumGroups += gd->dNumHashGroups;
3737  }
3738  }
3739  else
3740  {
3741  /* Plain GROUP BY */
3742  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3743  target_list);
3744 
3745  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3746  NULL);
3747  }
3748  }
3749  else if (parse->groupingSets)
3750  {
3751  /* Empty grouping sets ... one result row for each one */
3752  dNumGroups = list_length(parse->groupingSets);
3753  }
3754  else if (parse->hasAggs || root->hasHavingQual)
3755  {
3756  /* Plain aggregation, one result row */
3757  dNumGroups = 1;
3758  }
3759  else
3760  {
3761  /* Not grouping */
3762  dNumGroups = 1;
3763  }
3764 
3765  return dNumGroups;
3766 }
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3360
Query * parse
Definition: pathnodes.h:173
List * groupClause
Definition: pathnodes.h:1731
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:434
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:1734
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
List * unsortable_sets
Definition: planner.c:114
List * groupClause
Definition: parsenodes.h:148
double numGroups
Definition: pathnodes.h:1725
bool hasHavingQual
Definition: pathnodes.h:341
Definition: pg_list.h:50
List * gsets_data
Definition: pathnodes.h:1733
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648
List * gsets
Definition: pathnodes.h:1732

◆ group_by_has_partkey()

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

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

7731 {
7732  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7733  int cnt = 0;
7734  int partnatts;
7735 
7736  /* Input relation should be partitioned. */
7737  Assert(input_rel->part_scheme);
7738 
7739  /* Rule out early, if there are no partition keys present. */
7740  if (!input_rel->partexprs)
7741  return false;
7742 
7743  partnatts = input_rel->part_scheme->partnatts;
7744 
7745  for (cnt = 0; cnt < partnatts; cnt++)
7746  {
7747  List *partexprs = input_rel->partexprs[cnt];
7748  ListCell *lc;
7749  bool found = false;
7750 
7751  foreach(lc, partexprs)
7752  {
7753  Expr *partexpr = lfirst(lc);
7754 
7755  if (list_member(groupexprs, partexpr))
7756  {
7757  found = true;
7758  break;
7759  }
7760  }
7761 
7762  /*
7763  * If none of the partition key expressions match with any of the
7764  * GROUP BY expression, return false.
7765  */
7766  if (!found)
7767  return false;
7768  }
7769 
7770  return true;
7771 }
List ** partexprs
Definition: pathnodes.h:754
bool list_member(const List *list, const void *datum)
Definition: list.c:613
#define Assert(condition)
Definition: c.h:800
#define lfirst(lc)
Definition: pg_list.h:169
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
PartitionScheme part_scheme
Definition: pathnodes.h:743
Definition: pg_list.h:50

◆ grouping_planner()

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

Definition at line 1827 of file planner.c.

References standard_qp_extra::activeWindows, add_partial_path(), add_path(), adjust_paths_for_srfs(), 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(), 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, Query::limitOption, linitial_int, linitial_node, list_length(), list_make1, list_make1_int, make_group_input_target(), make_pathkeys_for_sortclauses(), make_sort_input_target(), make_window_input_target(), NIL, WindowFuncLists::numWindowFuncs, FinalPathExtraData::offset_est, Query::onConflict, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, Path::pathtarget, plan_set_operations(), postprocess_setop_tlist(), preprocess_aggrefs(), preprocess_groupclause(), preprocess_grouping_sets(), preprocess_limit(), preprocess_minmax_aggregates(), preprocess_targetlist(), PlannerInfo::processed_tlist, PlannerInfo::query_level, query_planner(), RelOptInfo::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().

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

◆ inheritance_planner()

static void inheritance_planner ( PlannerInfo root)
static

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

1204 {
1205  Query *parse = root->parse;
1206  int top_parentRTindex = parse->resultRelation;
1207  List *select_rtable;
1208  List *select_appinfos;
1209  List *child_appinfos;
1210  List *old_child_rtis;
1211  List *new_child_rtis;
1212  Bitmapset *subqueryRTindexes;
1213  Index next_subquery_rti;
1214  int nominalRelation = -1;
1215  Index rootRelation = 0;
1216  List *final_rtable = NIL;
1217  List *final_rowmarks = NIL;
1218  List *final_appendrels = NIL;
1219  int save_rel_array_size = 0;
1220  RelOptInfo **save_rel_array = NULL;
1221  AppendRelInfo **save_append_rel_array = NULL;
1222  List *subpaths = NIL;
1223  List *subroots = NIL;
1224  List *resultRelations = NIL;
1225  List *withCheckOptionLists = NIL;
1226  List *returningLists = NIL;
1227  List *rowMarks;
1228  RelOptInfo *final_rel;
1229  ListCell *lc;
1230  ListCell *lc2;
1231  Index rti;
1232  RangeTblEntry *parent_rte;
1233  Bitmapset *parent_relids;
1234  Query **parent_parses;
1235 
1236  /* Should only get here for UPDATE or DELETE */
1237  Assert(parse->commandType == CMD_UPDATE ||
1238  parse->commandType == CMD_DELETE);
1239 
1240  /*
1241  * We generate a modified instance of the original Query for each target
1242  * relation, plan that, and put all the plans into a list that will be
1243  * controlled by a single ModifyTable node. All the instances share the
1244  * same rangetable, but each instance must have its own set of subquery
1245  * RTEs within the finished rangetable because (1) they are likely to get
1246  * scribbled on during planning, and (2) it's not inconceivable that
1247  * subqueries could get planned differently in different cases. We need
1248  * not create duplicate copies of other RTE kinds, in particular not the
1249  * target relations, because they don't have either of those issues. Not
1250  * having to duplicate the target relations is important because doing so
1251  * (1) would result in a rangetable of length O(N^2) for N targets, with
1252  * at least O(N^3) work expended here; and (2) would greatly complicate
1253  * management of the rowMarks list.
1254  *
1255  * To begin with, generate a bitmapset of the relids of the subquery RTEs.
1256  */
1257  subqueryRTindexes = NULL;
1258  rti = 1;
1259  foreach(lc, parse->rtable)
1260  {
1262 
1263  if (rte->rtekind == RTE_SUBQUERY)
1264  subqueryRTindexes = bms_add_member(subqueryRTindexes, rti);
1265  rti++;
1266  }
1267 
1268  /*
1269  * If the parent RTE is a partitioned table, we should use that as the
1270  * nominal target relation, because the RTEs added for partitioned tables
1271  * (including the root parent) as child members of the inheritance set do
1272  * not appear anywhere else in the plan, so the confusion explained below
1273  * for non-partitioning inheritance cases is not possible.
1274  */
1275  parent_rte = rt_fetch(top_parentRTindex, parse->rtable);
1276  Assert(parent_rte->inh);
1277  if (parent_rte->relkind == RELKIND_PARTITIONED_TABLE)
1278  {
1279  nominalRelation = top_parentRTindex;
1280  rootRelation = top_parentRTindex;
1281  }
1282 
1283  /*
1284  * Before generating the real per-child-relation plans, do a cycle of
1285  * planning as though the query were a SELECT. The objective here is to
1286  * find out which child relations need to be processed, using the same
1287  * expansion and pruning logic as for a SELECT. We'll then pull out the
1288  * RangeTblEntry-s generated for the child rels, and make use of the
1289  * AppendRelInfo entries for them to guide the real planning. (This is
1290  * rather inefficient; we could perhaps stop short of making a full Path
1291  * tree. But this whole function is inefficient and slated for
1292  * destruction, so let's not contort query_planner for that.)
1293  */
1294  {
1295  PlannerInfo *subroot;
1296 
1297  /*
1298  * Flat-copy the PlannerInfo to prevent modification of the original.
1299  */
1300  subroot = makeNode(PlannerInfo);
1301  memcpy(subroot, root, sizeof(PlannerInfo));
1302 
1303  /*
1304  * Make a deep copy of the parsetree for this planning cycle to mess
1305  * around with, and change it to look like a SELECT. (Hack alert: the
1306  * target RTE still has updatedCols set if this is an UPDATE, so that
1307  * expand_partitioned_rtentry will correctly update
1308  * subroot->partColsUpdated.)
1309  */
1310  subroot->parse = copyObject(root->parse);
1311 
1312  subroot->parse->commandType = CMD_SELECT;
1313  subroot->parse->resultRelation = 0;
1314 
1315  /*
1316  * Ensure the subroot has its own copy of the original
1317  * append_rel_list, since it'll be scribbled on. (Note that at this
1318  * point, the list only contains AppendRelInfos for flattened UNION
1319  * ALL subqueries.)
1320  */
1321  subroot->append_rel_list = copyObject(root->append_rel_list);
1322 
1323  /*
1324  * Better make a private copy of the rowMarks, too.
1325  */
1326  subroot->rowMarks = copyObject(root->rowMarks);
1327 
1328  /* There shouldn't be any OJ info to translate, as yet */
1329  Assert(subroot->join_info_list == NIL);
1330  /* and we haven't created PlaceHolderInfos, either */
1331  Assert(subroot->placeholder_list == NIL);
1332 
1333  /* Generate Path(s) for accessing this result relation */
1334  grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
1335 
1336  /* Extract the info we need. */
1337  select_rtable = subroot->parse->rtable;
1338  select_appinfos = subroot->append_rel_list;
1339 
1340  /*
1341  * We need to propagate partColsUpdated back, too. (The later
1342  * planning cycles will not set this because they won't run
1343  * expand_partitioned_rtentry for the UPDATE target.)
1344  */
1345  root->partColsUpdated = subroot->partColsUpdated;
1346  }
1347 
1348  /*----------
1349  * Since only one rangetable can exist in the final plan, we need to make
1350  * sure that it contains all the RTEs needed for any child plan. This is
1351  * complicated by the need to use separate subquery RTEs for each child.
1352  * We arrange the final rtable as follows:
1353  * 1. All original rtable entries (with their original RT indexes).
1354  * 2. All the relation RTEs generated for children of the target table.
1355  * 3. Subquery RTEs for children after the first. We need N * (K - 1)
1356  * RT slots for this, if there are N subqueries and K child tables.
1357  * 4. Additional RTEs generated during the child planning runs, such as
1358  * children of inheritable RTEs other than the target table.
1359  * We assume that each child planning run will create an identical set
1360  * of type-4 RTEs.
1361  *
1362  * So the next thing to do is append the type-2 RTEs (the target table's
1363  * children) to the original rtable. We look through select_appinfos
1364  * to find them.
1365  *
1366  * To identify which AppendRelInfos are relevant as we thumb through
1367  * select_appinfos, we need to look for both direct and indirect children
1368  * of top_parentRTindex, so we use a bitmap of known parent relids.
1369  * expand_inherited_rtentry() always processes a parent before any of that
1370  * parent's children, so we should see an intermediate parent before its
1371  * children.
1372  *----------
1373  */
1374  child_appinfos = NIL;
1375  old_child_rtis =