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_aggregate.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 "nodes/supportnodes.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/parse_relation.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  grouping_sets_data
 
struct  WindowClauseSortData
 
struct  standard_qp_extra
 

Macros

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

Functions

static Nodepreprocess_expression (PlannerInfo *root, Node *expr, int kind)
 
static void preprocess_qual_conditions (PlannerInfo *root, Node *jtnode)
 
static void grouping_planner (PlannerInfo *root, double tuple_fraction)
 
static grouping_sets_datapreprocess_grouping_sets (PlannerInfo *root)
 
static Listremap_to_groupclause_idx (List *groupClause, List *gsets, int *tleref_to_colnum_map)
 
static void preprocess_rowmarks (PlannerInfo *root)
 
static double preprocess_limit (PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
 
static void remove_useless_groupby_columns (PlannerInfo *root)
 
static Listpreprocess_groupclause (PlannerInfo *root, List *force)
 
static Listextract_rollup_sets (List *groupingSets)
 
static Listreorder_grouping_sets (List *groupingSets, List *sortclause)
 
static void standard_qp_callback (PlannerInfo *root, void *extra)
 
static double get_number_of_groups (PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
 
static RelOptInfocreate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, grouping_sets_data *gd)
 
static bool is_degenerate_grouping (PlannerInfo *root)
 
static void create_degenerate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
 
static RelOptInfomake_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
 
static void create_ordinary_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
 
static void consider_groupingsets_paths (PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
 
static RelOptInfocreate_window_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, WindowFuncLists *wflists, List *activeWindows)
 
static void create_one_window_path (PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, WindowFuncLists *wflists, List *activeWindows)
 
static RelOptInfocreate_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel)
 
static void create_partial_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel)
 
static RelOptInfocreate_final_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_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 void optimize_window_clauses (PlannerInfo *root, WindowFuncLists *wflists)
 
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)
 
static bool has_volatile_pathkey (List *keys)
 
static void adjust_group_pathkeys_for_groupagg (PlannerInfo *root)
 
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 debug_parallel_query = DEBUG_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 91 of file planner.c.

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 94 of file planner.c.

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 90 of file planner.c.

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 92 of file planner.c.

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 84 of file planner.c.

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 86 of file planner.c.

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 87 of file planner.c.

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 95 of file planner.c.

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 96 of file planner.c.

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 93 of file planner.c.

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 85 of file planner.c.

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 88 of file planner.c.

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 89 of file planner.c.

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

6828 {
6829  Query *parse = root->parse;
6830  Path *cheapest_path = input_rel->cheapest_total_path;
6831  ListCell *lc;
6832  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6833  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6834  List *havingQual = (List *) extra->havingQual;
6835  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6836 
6837  if (can_sort)
6838  {
6839  /*
6840  * Use any available suitably-sorted path as input, and also consider
6841  * sorting the cheapest-total path and incremental sort on any paths
6842  * with presorted keys.
6843  */
6844  foreach(lc, input_rel->pathlist)
6845  {
6846  Path *path = (Path *) lfirst(lc);
6847  bool is_sorted;
6848  int presorted_keys;
6849 
6850  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6851  path->pathkeys,
6852  &presorted_keys);
6853 
6854  if (!is_sorted)
6855  {
6856  /*
6857  * Try at least sorting the cheapest path and also try
6858  * incrementally sorting any path which is partially sorted
6859  * already (no need to deal with paths which have presorted
6860  * keys when incremental sort is disabled unless it's the
6861  * cheapest input path).
6862  */
6863  if (path != cheapest_path &&
6864  (presorted_keys == 0 || !enable_incremental_sort))
6865  continue;
6866 
6867  /*
6868  * We've no need to consider both a sort and incremental sort.
6869  * We'll just do a sort if there are no presorted keys and an
6870  * incremental sort when there are presorted keys.
6871  */
6872  if (presorted_keys == 0 || !enable_incremental_sort)
6873  path = (Path *) create_sort_path(root,
6874  grouped_rel,
6875  path,
6876  root->group_pathkeys,
6877  -1.0);
6878  else
6879  path = (Path *) create_incremental_sort_path(root,
6880  grouped_rel,
6881  path,
6882  root->group_pathkeys,
6883  presorted_keys,
6884  -1.0);
6885  }
6886 
6887  /* Now decide what to stick atop it */
6888  if (parse->groupingSets)
6889  {
6890  consider_groupingsets_paths(root, grouped_rel,
6891  path, true, can_hash,
6892  gd, agg_costs, dNumGroups);
6893  }
6894  else if (parse->hasAggs)
6895  {
6896  /*
6897  * We have aggregation, possibly with plain GROUP BY. Make an
6898  * AggPath.
6899  */
6900  add_path(grouped_rel, (Path *)
6901  create_agg_path(root,
6902  grouped_rel,
6903  path,
6904  grouped_rel->reltarget,
6905  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6907  root->processed_groupClause,
6908  havingQual,
6909  agg_costs,
6910  dNumGroups));
6911  }
6912  else if (parse->groupClause)
6913  {
6914  /*
6915  * We have GROUP BY without aggregation or grouping sets. Make
6916  * a GroupPath.
6917  */
6918  add_path(grouped_rel, (Path *)
6919  create_group_path(root,
6920  grouped_rel,
6921  path,
6922  root->processed_groupClause,
6923  havingQual,
6924  dNumGroups));
6925  }
6926  else
6927  {
6928  /* Other cases should have been handled above */
6929  Assert(false);
6930  }
6931  }
6932 
6933  /*
6934  * Instead of operating directly on the input relation, we can
6935  * consider finalizing a partially aggregated path.
6936  */
6937  if (partially_grouped_rel != NULL)
6938  {
6939  foreach(lc, partially_grouped_rel->pathlist)
6940  {
6941  Path *path = (Path *) lfirst(lc);
6942  bool is_sorted;
6943  int presorted_keys;
6944 
6945  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
6946  path->pathkeys,
6947  &presorted_keys);
6948 
6949  if (!is_sorted)
6950  {
6951  /*
6952  * Try at least sorting the cheapest path and also try
6953  * incrementally sorting any path which is partially
6954  * sorted already (no need to deal with paths which have
6955  * presorted keys when incremental sort is disabled unless
6956  * it's the cheapest input path).
6957  */
6958  if (path != partially_grouped_rel->cheapest_total_path &&
6959  (presorted_keys == 0 || !enable_incremental_sort))
6960  continue;
6961 
6962  /*
6963  * We've no need to consider both a sort and incremental
6964  * sort. We'll just do a sort if there are no pre-sorted
6965  * keys and an incremental sort when there are presorted
6966  * keys.
6967  */
6968  if (presorted_keys == 0 || !enable_incremental_sort)
6969  path = (Path *) create_sort_path(root,
6970  grouped_rel,
6971  path,
6972  root->group_pathkeys,
6973  -1.0);
6974  else
6975  path = (Path *) create_incremental_sort_path(root,
6976  grouped_rel,
6977  path,
6978  root->group_pathkeys,
6979  presorted_keys,
6980  -1.0);
6981  }
6982 
6983  if (parse->hasAggs)
6984  add_path(grouped_rel, (Path *)
6985  create_agg_path(root,
6986  grouped_rel,
6987  path,
6988  grouped_rel->reltarget,
6989  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6991  root->processed_groupClause,
6992  havingQual,
6993  agg_final_costs,
6994  dNumGroups));
6995  else
6996  add_path(grouped_rel, (Path *)
6997  create_group_path(root,
6998  grouped_rel,
6999  path,
7000  root->processed_groupClause,
7001  havingQual,
7002  dNumGroups));
7003 
7004  }
7005  }
7006  }
7007 
7008  if (can_hash)
7009  {
7010  if (parse->groupingSets)
7011  {
7012  /*
7013  * Try for a hash-only groupingsets path over unsorted input.
7014  */
7015  consider_groupingsets_paths(root, grouped_rel,
7016  cheapest_path, false, true,
7017  gd, agg_costs, dNumGroups);
7018  }
7019  else
7020  {
7021  /*
7022  * Generate a HashAgg Path. We just need an Agg over the
7023  * cheapest-total input path, since input order won't matter.
7024  */
7025  add_path(grouped_rel, (Path *)
7026  create_agg_path(root, grouped_rel,
7027  cheapest_path,
7028  grouped_rel->reltarget,
7029  AGG_HASHED,
7031  root->processed_groupClause,
7032  havingQual,
7033  agg_costs,
7034  dNumGroups));
7035  }
7036 
7037  /*
7038  * Generate a Finalize HashAgg Path atop of the cheapest partially
7039  * grouped path, assuming there is one
7040  */
7041  if (partially_grouped_rel && partially_grouped_rel->pathlist)
7042  {
7043  Path *path = partially_grouped_rel->cheapest_total_path;
7044 
7045  add_path(grouped_rel, (Path *)
7046  create_agg_path(root,
7047  grouped_rel,
7048  path,
7049  grouped_rel->reltarget,
7050  AGG_HASHED,
7052  root->processed_groupClause,
7053  havingQual,
7054  agg_final_costs,
7055  dNumGroups));
7056  }
7057  }
7058 
7059  /*
7060  * When partitionwise aggregate is used, we might have fully aggregated
7061  * paths in the partial pathlist, because add_paths_to_append_rel() will
7062  * consider a path for grouped_rel consisting of a Parallel Append of
7063  * non-partial paths from each child.
7064  */
7065  if (grouped_rel->partial_pathlist != NIL)
7066  gather_grouping_paths(root, grouped_rel);
7067 }
bool enable_incremental_sort
Definition: costsize.c:141
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
@ AGG_SORTED
Definition: nodes.h:365
@ AGG_HASHED
Definition: nodes.h:366
@ AGG_PLAIN
Definition: nodes.h:364
@ AGGSPLIT_FINAL_DESERIAL
Definition: nodes.h:391
@ AGGSPLIT_SIMPLE
Definition: nodes.h:387
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:359
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2959
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:3003
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2910
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:3114
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:3213
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:3212
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:7409
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:4088
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:715
AggClauseCosts agg_final_costs
Definition: pathnodes.h:3253
Definition: pg_list.h:54
List * pathkeys
Definition: pathnodes.h:1633
List * group_pathkeys
Definition: pathnodes.h:385
List * processed_groupClause
Definition: pathnodes.h:430
Query * parse
Definition: pathnodes.h:199
struct PathTarget * reltarget
Definition: pathnodes.h:878
List * pathlist
Definition: pathnodes.h:883
struct Path * cheapest_total_path
Definition: pathnodes.h:887
List * partial_pathlist
Definition: pathnodes.h:885

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, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, GroupPathExtraData::havingQual, if(), lfirst, NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_count_contained_in(), RelOptInfo::pathlist, PlannerInfo::processed_groupClause, and RelOptInfo::reltarget.

Referenced by create_ordinary_grouping_paths().

◆ adjust_group_pathkeys_for_groupagg()

static void adjust_group_pathkeys_for_groupagg ( PlannerInfo root)
static

Definition at line 3238 of file planner.c.

3239 {
3240  List *grouppathkeys = root->group_pathkeys;
3241  List *bestpathkeys;
3242  Bitmapset *bestaggs;
3243  Bitmapset *unprocessed_aggs;
3244  ListCell *lc;
3245  int i;
3246 
3247  /* Shouldn't be here if there are grouping sets */
3248  Assert(root->parse->groupingSets == NIL);
3249  /* Shouldn't be here unless there are some ordered aggregates */
3250  Assert(root->numOrderedAggs > 0);
3251 
3252  /* Do nothing if disabled */
3254  return;
3255 
3256  /*
3257  * Make a first pass over all AggInfos to collect a Bitmapset containing
3258  * the indexes of all AggInfos to be processed below.
3259  */
3260  unprocessed_aggs = NULL;
3261  foreach(lc, root->agginfos)
3262  {
3263  AggInfo *agginfo = lfirst_node(AggInfo, lc);
3264  Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3265 
3266  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
3267  continue;
3268 
3269  /* only add aggregates with a DISTINCT or ORDER BY */
3270  if (aggref->aggdistinct != NIL || aggref->aggorder != NIL)
3271  unprocessed_aggs = bms_add_member(unprocessed_aggs,
3272  foreach_current_index(lc));
3273  }
3274 
3275  /*
3276  * Now process all the unprocessed_aggs to find the best set of pathkeys
3277  * for the given set of aggregates.
3278  *
3279  * On the first outer loop here 'bestaggs' will be empty. We'll populate
3280  * this during the first loop using the pathkeys for the very first
3281  * AggInfo then taking any stronger pathkeys from any other AggInfos with
3282  * a more strict set of compatible pathkeys. Once the outer loop is
3283  * complete, we mark off all the aggregates with compatible pathkeys then
3284  * remove those from the unprocessed_aggs and repeat the process to try to
3285  * find another set of pathkeys that are suitable for a larger number of
3286  * aggregates. The outer loop will stop when there are not enough
3287  * unprocessed aggregates for it to be possible to find a set of pathkeys
3288  * to suit a larger number of aggregates.
3289  */
3290  bestpathkeys = NIL;
3291  bestaggs = NULL;
3292  while (bms_num_members(unprocessed_aggs) > bms_num_members(bestaggs))
3293  {
3294  Bitmapset *aggindexes = NULL;
3295  List *currpathkeys = NIL;
3296 
3297  i = -1;
3298  while ((i = bms_next_member(unprocessed_aggs, i)) >= 0)
3299  {
3300  AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3301  Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3302  List *sortlist;
3303  List *pathkeys;
3304 
3305  if (aggref->aggdistinct != NIL)
3306  sortlist = aggref->aggdistinct;
3307  else
3308  sortlist = aggref->aggorder;
3309 
3310  pathkeys = make_pathkeys_for_sortclauses(root, sortlist,
3311  aggref->args);
3312 
3313  /*
3314  * Ignore Aggrefs which have volatile functions in their ORDER BY
3315  * or DISTINCT clause.
3316  */
3317  if (has_volatile_pathkey(pathkeys))
3318  {
3319  unprocessed_aggs = bms_del_member(unprocessed_aggs, i);
3320  continue;
3321  }
3322 
3323  /*
3324  * When not set yet, take the pathkeys from the first unprocessed
3325  * aggregate.
3326  */
3327  if (currpathkeys == NIL)
3328  {
3329  currpathkeys = pathkeys;
3330 
3331  /* include the GROUP BY pathkeys, if they exist */
3332  if (grouppathkeys != NIL)
3333  currpathkeys = append_pathkeys(list_copy(grouppathkeys),
3334  currpathkeys);
3335 
3336  /* record that we found pathkeys for this aggregate */
3337  aggindexes = bms_add_member(aggindexes, i);
3338  }
3339  else
3340  {
3341  /* now look for a stronger set of matching pathkeys */
3342 
3343  /* include the GROUP BY pathkeys, if they exist */
3344  if (grouppathkeys != NIL)
3345  pathkeys = append_pathkeys(list_copy(grouppathkeys),
3346  pathkeys);
3347 
3348  /* are 'pathkeys' compatible or better than 'currpathkeys'? */
3349  switch (compare_pathkeys(currpathkeys, pathkeys))
3350  {
3351  case PATHKEYS_BETTER2:
3352  /* 'pathkeys' are stronger, use these ones instead */
3353  currpathkeys = pathkeys;
3354  /* FALLTHROUGH */
3355 
3356  case PATHKEYS_BETTER1:
3357  /* 'pathkeys' are less strict */
3358  /* FALLTHROUGH */
3359 
3360  case PATHKEYS_EQUAL:
3361  /* mark this aggregate as covered by 'currpathkeys' */
3362  aggindexes = bms_add_member(aggindexes, i);
3363  break;
3364 
3365  case PATHKEYS_DIFFERENT:
3366  break;
3367  }
3368  }
3369  }
3370 
3371  /* remove the aggregates that we've just processed */
3372  unprocessed_aggs = bms_del_members(unprocessed_aggs, aggindexes);
3373 
3374  /*
3375  * If this pass included more aggregates than the previous best then
3376  * use these ones as the best set.
3377  */
3378  if (bms_num_members(aggindexes) > bms_num_members(bestaggs))
3379  {
3380  bestaggs = aggindexes;
3381  bestpathkeys = currpathkeys;
3382  }
3383  }
3384 
3385  /*
3386  * If we found any ordered aggregates, update root->group_pathkeys to add
3387  * the best set of aggregate pathkeys. Note that bestpathkeys includes
3388  * the original GROUP BY pathkeys already.
3389  */
3390  if (bestpathkeys != NIL)
3391  root->group_pathkeys = bestpathkeys;
3392 
3393  /*
3394  * Now that we've found the best set of aggregates we can set the
3395  * presorted flag to indicate to the executor that it needn't bother
3396  * performing a sort for these Aggrefs. We're able to do this now as
3397  * there's no chance of a Hash Aggregate plan as create_grouping_paths
3398  * will not mark the GROUP BY as GROUPING_CAN_USE_HASH due to the presence
3399  * of ordered aggregates.
3400  */
3401  i = -1;
3402  while ((i = bms_next_member(bestaggs, i)) >= 0)
3403  {
3404  AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3405 
3406  foreach(lc, agginfo->aggrefs)
3407  {
3408  Aggref *aggref = lfirst_node(Aggref, lc);
3409 
3410  aggref->aggpresorted = true;
3411  }
3412  }
3413 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1106
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:685
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:993
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:793
bool enable_presorted_aggregate
Definition: costsize.c:154
int i
Definition: isn.c:73
List * list_copy(const List *oldlist)
Definition: list.c:1572
List * append_pathkeys(List *target, List *source)
Definition: pathkeys.c:105
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:1133
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:301
@ PATHKEYS_BETTER2
Definition: paths.h:201
@ PATHKEYS_BETTER1
Definition: paths.h:200
@ PATHKEYS_DIFFERENT
Definition: paths.h:202
@ PATHKEYS_EQUAL
Definition: paths.h:199
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define linitial_node(type, l)
Definition: pg_list.h:181
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
#define foreach_current_index(cell)
Definition: pg_list.h:403
static bool has_volatile_pathkey(List *keys)
Definition: planner.c:3193
List * aggrefs
Definition: pathnodes.h:3334
List * aggdistinct
Definition: primnodes.h:452
List * args
Definition: primnodes.h:446
List * aggorder
Definition: primnodes.h:449
int numOrderedAggs
Definition: pathnodes.h:511
List * agginfos
Definition: pathnodes.h:507
List * groupingSets
Definition: parsenodes.h:200

References Aggref::aggdistinct, PlannerInfo::agginfos, Aggref::aggorder, AggInfo::aggrefs, append_pathkeys(), Aggref::args, Assert(), bms_add_member(), bms_del_member(), bms_del_members(), bms_next_member(), bms_num_members(), compare_pathkeys(), enable_presorted_aggregate, foreach_current_index, PlannerInfo::group_pathkeys, Query::groupingSets, has_volatile_pathkey(), i, lfirst_node, linitial_node, list_copy(), list_nth_node, make_pathkeys_for_sortclauses(), NIL, PlannerInfo::numOrderedAggs, PlannerInfo::parse, PATHKEYS_BETTER1, PATHKEYS_BETTER2, PATHKEYS_DIFFERENT, and PATHKEYS_EQUAL.

Referenced by standard_qp_callback().

◆ adjust_paths_for_srfs()

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

Definition at line 6373 of file planner.c.

6375 {
6376  ListCell *lc;
6377 
6378  Assert(list_length(targets) == list_length(targets_contain_srfs));
6379  Assert(!linitial_int(targets_contain_srfs));
6380 
6381  /* If no SRFs appear at this plan level, nothing to do */
6382  if (list_length(targets) == 1)
6383  return;
6384 
6385  /*
6386  * Stack SRF-evaluation nodes atop each path for the rel.
6387  *
6388  * In principle we should re-run set_cheapest() here to identify the
6389  * cheapest path, but it seems unlikely that adding the same tlist eval
6390  * costs to all the paths would change that, so we don't bother. Instead,
6391  * just assume that the cheapest-startup and cheapest-total paths remain
6392  * so. (There should be no parameterized paths anymore, so we needn't
6393  * worry about updating cheapest_parameterized_paths.)
6394  */
6395  foreach(lc, rel->pathlist)
6396  {
6397  Path *subpath = (Path *) lfirst(lc);
6398  Path *newpath = subpath;
6399  ListCell *lc1,
6400  *lc2;
6401 
6402  Assert(subpath->param_info == NULL);
6403  forboth(lc1, targets, lc2, targets_contain_srfs)
6404  {
6405  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6406  bool contains_srfs = (bool) lfirst_int(lc2);
6407 
6408  /* If this level doesn't contain SRFs, do regular projection */
6409  if (contains_srfs)
6410  newpath = (Path *) create_set_projection_path(root,
6411  rel,
6412  newpath,
6413  thistarget);
6414  else
6415  newpath = (Path *) apply_projection_to_path(root,
6416  rel,
6417  newpath,
6418  thistarget);
6419  }
6420  lfirst(lc) = newpath;
6421  if (subpath == rel->cheapest_startup_path)
6422  rel->cheapest_startup_path = newpath;
6423  if (subpath == rel->cheapest_total_path)
6424  rel->cheapest_total_path = newpath;
6425  }
6426 
6427  /* Likewise for partial paths, if any */
6428  foreach(lc, rel->partial_pathlist)
6429  {
6430  Path *subpath = (Path *) lfirst(lc);
6431  Path *newpath = subpath;
6432  ListCell *lc1,
6433  *lc2;
6434 
6435  Assert(subpath->param_info == NULL);
6436  forboth(lc1, targets, lc2, targets_contain_srfs)
6437  {
6438  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6439  bool contains_srfs = (bool) lfirst_int(lc2);
6440 
6441  /* If this level doesn't contain SRFs, do regular projection */
6442  if (contains_srfs)
6443  newpath = (Path *) create_set_projection_path(root,
6444  rel,
6445  newpath,
6446  thistarget);
6447  else
6448  {
6449  /* avoid apply_projection_to_path, in case of multiple refs */
6450  newpath = (Path *) create_projection_path(root,
6451  rel,
6452  newpath,
6453  thistarget);
6454  }
6455  }
6456  lfirst(lc) = newpath;
6457  }
6458 }
unsigned char bool
Definition: c.h:445
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2644
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2841
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2752
static int list_length(const List *l)
Definition: pg_list.h:152
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467
#define lfirst_int(lc)
Definition: pg_list.h:173
#define linitial_int(l)
Definition: pg_list.h:179
struct Path * cheapest_startup_path
Definition: pathnodes.h:886

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(), RelOptInfo::partial_pathlist, RelOptInfo::pathlist, and subpath().

Referenced by apply_scanjoin_target_to_paths(), and grouping_planner().

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

7545 {
7546  bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
7547  PathTarget *scanjoin_target;
7548  ListCell *lc;
7549 
7550  /* This recurses, so be paranoid. */
7552 
7553  /*
7554  * If the rel is partitioned, we want to drop its existing paths and
7555  * generate new ones. This function would still be correct if we kept the
7556  * existing paths: we'd modify them to generate the correct target above
7557  * the partitioning Append, and then they'd compete on cost with paths
7558  * generating the target below the Append. However, in our current cost
7559  * model the latter way is always the same or cheaper cost, so modifying
7560  * the existing paths would just be useless work. Moreover, when the cost
7561  * is the same, varying roundoff errors might sometimes allow an existing
7562  * path to be picked, resulting in undesirable cross-platform plan
7563  * variations. So we drop old paths and thereby force the work to be done
7564  * below the Append, except in the case of a non-parallel-safe target.
7565  *
7566  * Some care is needed, because we have to allow
7567  * generate_useful_gather_paths to see the old partial paths in the next
7568  * stanza. Hence, zap the main pathlist here, then allow
7569  * generate_useful_gather_paths to add path(s) to the main list, and
7570  * finally zap the partial pathlist.
7571  */
7572  if (rel_is_partitioned)
7573  rel->pathlist = NIL;
7574 
7575  /*
7576  * If the scan/join target is not parallel-safe, partial paths cannot
7577  * generate it.
7578  */
7579  if (!scanjoin_target_parallel_safe)
7580  {
7581  /*
7582  * Since we can't generate the final scan/join target in parallel
7583  * workers, this is our last opportunity to use any partial paths that
7584  * exist; so build Gather path(s) that use them and emit whatever the
7585  * current reltarget is. We don't do this in the case where the
7586  * target is parallel-safe, since we will be able to generate superior
7587  * paths by doing it after the final scan/join target has been
7588  * applied.
7589  */
7590  generate_useful_gather_paths(root, rel, false);
7591 
7592  /* Can't use parallel query above this level. */
7593  rel->partial_pathlist = NIL;
7594  rel->consider_parallel = false;
7595  }
7596 
7597  /* Finish dropping old paths for a partitioned rel, per comment above */
7598  if (rel_is_partitioned)
7599  rel->partial_pathlist = NIL;
7600 
7601  /* Extract SRF-free scan/join target. */
7602  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
7603 
7604  /*
7605  * Apply the SRF-free scan/join target to each existing path.
7606  *
7607  * If the tlist exprs are the same, we can just inject the sortgroupref
7608  * information into the existing pathtargets. Otherwise, replace each
7609  * path with a projection path that generates the SRF-free scan/join
7610  * target. This can't change the ordering of paths within rel->pathlist,
7611  * so we just modify the list in place.
7612  */
7613  foreach(lc, rel->pathlist)
7614  {
7615  Path *subpath = (Path *) lfirst(lc);
7616 
7617  /* Shouldn't have any parameterized paths anymore */
7618  Assert(subpath->param_info == NULL);
7619 
7620  if (tlist_same_exprs)
7621  subpath->pathtarget->sortgrouprefs =
7622  scanjoin_target->sortgrouprefs;
7623  else
7624  {
7625  Path *newpath;
7626 
7627  newpath = (Path *) create_projection_path(root, rel, subpath,
7628  scanjoin_target);
7629  lfirst(lc) = newpath;
7630  }
7631  }
7632 
7633  /* Likewise adjust the targets for any partial paths. */
7634  foreach(lc, rel->partial_pathlist)
7635  {
7636  Path *subpath = (Path *) lfirst(lc);
7637 
7638  /* Shouldn't have any parameterized paths anymore */
7639  Assert(subpath->param_info == NULL);
7640 
7641  if (tlist_same_exprs)
7642  subpath->pathtarget->sortgrouprefs =
7643  scanjoin_target->sortgrouprefs;
7644  else
7645  {
7646  Path *newpath;
7647 
7648  newpath = (Path *) create_projection_path(root, rel, subpath,
7649  scanjoin_target);
7650  lfirst(lc) = newpath;
7651  }
7652  }
7653 
7654  /*
7655  * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
7656  * atop each existing path. (Note that this function doesn't look at the
7657  * cheapest-path fields, which is a good thing because they're bogus right
7658  * now.)
7659  */
7660  if (root->parse->hasTargetSRFs)
7661  adjust_paths_for_srfs(root, rel,
7662  scanjoin_targets,
7663  scanjoin_targets_contain_srfs);
7664 
7665  /*
7666  * Update the rel's target to be the final (with SRFs) scan/join target.
7667  * This now matches the actual output of all the paths, and we might get
7668  * confused in createplan.c if they don't agree. We must do this now so
7669  * that any append paths made in the next part will use the correct
7670  * pathtarget (cf. create_append_path).
7671  *
7672  * Note that this is also necessary if GetForeignUpperPaths() gets called
7673  * on the final scan/join relation or on any of its children, since the
7674  * FDW might look at the rel's target to create ForeignPaths.
7675  */
7676  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
7677 
7678  /*
7679  * If the relation is partitioned, recursively apply the scan/join target
7680  * to all partitions, and generate brand-new Append paths in which the
7681  * scan/join target is computed below the Append rather than above it.
7682  * Since Append is not projection-capable, that might save a separate
7683  * Result node, and it also is important for partitionwise aggregate.
7684  */
7685  if (rel_is_partitioned)
7686  {
7687  List *live_children = NIL;
7688  int i;
7689 
7690  /* Adjust each partition. */
7691  i = -1;
7692  while ((i = bms_next_member(rel->live_parts, i)) >= 0)
7693  {
7694  RelOptInfo *child_rel = rel->part_rels[i];
7695  AppendRelInfo **appinfos;
7696  int nappinfos;
7697  List *child_scanjoin_targets = NIL;
7698 
7699  Assert(child_rel != NULL);
7700 
7701  /* Dummy children can be ignored. */
7702  if (IS_DUMMY_REL(child_rel))
7703  continue;
7704 
7705  /* Translate scan/join targets for this child. */
7706  appinfos = find_appinfos_by_relids(root, child_rel->relids,
7707  &nappinfos);
7708  foreach(lc, scanjoin_targets)
7709  {
7710  PathTarget *target = lfirst_node(PathTarget, lc);
7711 
7712  target = copy_pathtarget(target);
7713  target->exprs = (List *)
7715  (Node *) target->exprs,
7716  nappinfos, appinfos);
7717  child_scanjoin_targets = lappend(child_scanjoin_targets,
7718  target);
7719  }
7720  pfree(appinfos);
7721 
7722  /* Recursion does the real work. */
7723  apply_scanjoin_target_to_paths(root, child_rel,
7724  child_scanjoin_targets,
7725  scanjoin_targets_contain_srfs,
7726  scanjoin_target_parallel_safe,
7728 
7729  /* Save non-dummy children for Append paths. */
7730  if (!IS_DUMMY_REL(child_rel))
7731  live_children = lappend(live_children, child_rel);
7732  }
7733 
7734  /* Build new paths for this relation by appending child paths. */
7735  add_paths_to_append_rel(root, rel, live_children);
7736  }
7737 
7738  /*
7739  * Consider generating Gather or Gather Merge paths. We must only do this
7740  * if the relation is parallel safe, and we don't do it for child rels to
7741  * avoid creating multiple Gather nodes within the same plan. We must do
7742  * this after all paths have been generated and before set_cheapest, since
7743  * one of the generated paths may turn out to be the cheapest one.
7744  */
7745  if (rel->consider_parallel && !IS_OTHER_REL(rel))
7746  generate_useful_gather_paths(root, rel, false);
7747 
7748  /*
7749  * Reassess which paths are the cheapest, now that we've potentially added
7750  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
7751  * this relation.
7752  */
7753  set_cheapest(rel);
7754 }
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3198
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1305
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:733
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:196
List * lappend(List *list, void *datum)
Definition: list.c:338
void pfree(void *pointer)
Definition: mcxt.c:1456
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1914
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:1041
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:839
#define llast_node(type, l)
Definition: pg_list.h:202
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:7539
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:6373
void check_stack_depth(void)
Definition: postgres.c:3523
Definition: nodes.h:129
List * exprs
Definition: pathnodes.h:1501
Relids relids
Definition: pathnodes.h:856
bool consider_parallel
Definition: pathnodes.h:872
Bitmapset * live_parts
Definition: pathnodes.h:1018
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:218
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:657

References add_paths_to_append_rel(), adjust_appendrel_attrs(), adjust_paths_for_srfs(), Assert(), bms_next_member(), check_stack_depth(), RelOptInfo::consider_parallel, copy_pathtarget(), create_projection_path(), PathTarget::exprs, find_appinfos_by_relids(), generate_useful_gather_paths(), i, IS_DUMMY_REL, IS_OTHER_REL, IS_PARTITIONED_REL, lappend(), lfirst, lfirst_node, linitial_node, RelOptInfo::live_parts, llast_node, NIL, PlannerInfo::parse, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, pfree(), RelOptInfo::relids, RelOptInfo::reltarget, set_cheapest(), subpath(), and tlist_same_exprs().

Referenced by grouping_planner().

◆ can_partial_agg()

static bool can_partial_agg ( PlannerInfo root)
static

Definition at line 7497 of file planner.c.

7498 {
7499  Query *parse = root->parse;
7500 
7501  if (!parse->hasAggs && parse->groupClause == NIL)
7502  {
7503  /*
7504  * We don't know how to do parallel aggregation unless we have either
7505  * some aggregates or a grouping clause.
7506  */
7507  return false;
7508  }
7509  else if (parse->groupingSets)
7510  {
7511  /* We don't know how to do grouping sets in parallel. */
7512  return false;
7513  }
7514  else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
7515  {
7516  /* Insufficient support for partial mode. */
7517  return false;
7518  }
7519 
7520  /* Everything looks good. */
7521  return true;
7522 }
bool hasNonPartialAggs
Definition: pathnodes.h:513
bool hasNonSerialAggs
Definition: pathnodes.h:515

References PlannerInfo::hasNonPartialAggs, PlannerInfo::hasNonSerialAggs, NIL, parse(), and PlannerInfo::parse.

Referenced by create_grouping_paths().

◆ common_prefix_cmp()

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

Definition at line 5844 of file planner.c.

5845 {
5846  const WindowClauseSortData *wcsa = a;
5847  const WindowClauseSortData *wcsb = b;
5848  ListCell *item_a;
5849  ListCell *item_b;
5850 
5851  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5852  {
5855 
5856  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5857  return -1;
5858  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5859  return 1;
5860  else if (sca->sortop > scb->sortop)
5861  return -1;
5862  else if (sca->sortop < scb->sortop)
5863  return 1;
5864  else if (sca->nulls_first && !scb->nulls_first)
5865  return -1;
5866  else if (!sca->nulls_first && scb->nulls_first)
5867  return 1;
5868  /* no need to compare eqop, since it is fully determined by sortop */
5869  }
5870 
5871  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5872  return -1;
5873  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5874  return 1;
5875 
5876  return 0;
5877 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69
Index tleSortGroupRef
Definition: parsenodes.h:1392

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

Referenced by select_active_windows().

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

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

References add_path(), AGG_HASHED, AGG_MIXED, AGG_SORTED, grouping_sets_data::any_hashable, Assert(), bms_is_empty, bms_is_member(), create_groupingsets_path(), DiscreteKnapsack(), grouping_sets_data::dNumHashGroups, estimate_hashagg_tablesize(), for_each_cell, for_each_from, get_hash_memory_limit(), PlannerInfo::group_pathkeys, RollupData::groupClause, RollupData::gsets, RollupData::gsets_data, RollupData::hashable, 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().

◆ create_degenerate_grouping_paths()

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

Definition at line 3885 of file planner.c.

3887 {
3888  Query *parse = root->parse;
3889  int nrows;
3890  Path *path;
3891 
3892  nrows = list_length(parse->groupingSets);
3893  if (nrows > 1)
3894  {
3895  /*
3896  * Doesn't seem worthwhile writing code to cons up a generate_series
3897  * or a values scan to emit multiple rows. Instead just make N clones
3898  * and append them. (With a volatile HAVING clause, this means you
3899  * might get between 0 and N output rows. Offhand I think that's
3900  * desired.)
3901  */
3902  List *paths = NIL;
3903 
3904  while (--nrows >= 0)
3905  {
3906  path = (Path *)
3907  create_group_result_path(root, grouped_rel,
3908  grouped_rel->reltarget,
3909  (List *) parse->havingQual);
3910  paths = lappend(paths, path);
3911  }
3912  path = (Path *)
3913  create_append_path(root,
3914  grouped_rel,
3915  paths,
3916  NIL,
3917  NIL,
3918  NULL,
3919  0,
3920  false,
3921  -1);
3922  }
3923  else
3924  {
3925  /* No grouping sets, or just one, so one output row */
3926  path = (Path *)
3927  create_group_result_path(root, grouped_rel,
3928  grouped_rel->reltarget,
3929  (List *) parse->havingQual);
3930  }
3931 
3932  add_path(grouped_rel, path);
3933 }
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition: pathnode.c:1242
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1516

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

Referenced by create_grouping_paths().

◆ create_distinct_paths()

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

Definition at line 4667 of file planner.c.

4668 {
4669  RelOptInfo *distinct_rel;
4670 
4671  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4672  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4673 
4674  /*
4675  * We don't compute anything at this level, so distinct_rel will be
4676  * parallel-safe if the input rel is parallel-safe. In particular, if
4677  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4678  * output those expressions, and will not be parallel-safe unless those
4679  * expressions are parallel-safe.
4680  */
4681  distinct_rel->consider_parallel = input_rel->consider_parallel;
4682 
4683  /*
4684  * If the input rel belongs to a single FDW, so does the distinct_rel.
4685  */
4686  distinct_rel->serverid = input_rel->serverid;
4687  distinct_rel->userid = input_rel->userid;
4688  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4689  distinct_rel->fdwroutine = input_rel->fdwroutine;
4690 
4691  /* build distinct paths based on input_rel's pathlist */
4692  create_final_distinct_paths(root, input_rel, distinct_rel);
4693 
4694  /* now build distinct paths based on input_rel's partial_pathlist */
4695  create_partial_distinct_paths(root, input_rel, distinct_rel);
4696 
4697  /* Give a helpful error if we failed to create any paths */
4698  if (distinct_rel->pathlist == NIL)
4699  ereport(ERROR,
4700  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4701  errmsg("could not implement DISTINCT"),
4702  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4703 
4704  /*
4705  * If there is an FDW that's responsible for all baserels of the query,
4706  * let it consider adding ForeignPaths.
4707  */
4708  if (distinct_rel->fdwroutine &&
4709  distinct_rel->fdwroutine->GetForeignUpperPaths)
4710  distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4712  input_rel,
4713  distinct_rel,
4714  NULL);
4715 
4716  /* Let extensions possibly add some more paths */
4718  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
4719  distinct_rel, NULL);
4720 
4721  /* Now choose the best path(s) */
4722  set_cheapest(distinct_rel);
4723 
4724  return distinct_rel;
4725 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
@ UPPERREL_DISTINCT
Definition: pathnodes.h:77
static void create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel)
Definition: planner.c:4736
static RelOptInfo * create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_rel)
Definition: planner.c:4900
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:80
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1443
bool useridiscurrent
Definition: pathnodes.h:947
Oid userid
Definition: pathnodes.h:945
Oid serverid
Definition: pathnodes.h:943

References RelOptInfo::consider_parallel, create_final_distinct_paths(), create_partial_distinct_paths(), create_upper_paths_hook, ereport, errcode(), errdetail(), errmsg(), ERROR, fetch_upper_rel(), NIL, RelOptInfo::pathlist, RelOptInfo::serverid, set_cheapest(), UPPERREL_DISTINCT, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by grouping_planner().

◆ create_final_distinct_paths()

static RelOptInfo * create_final_distinct_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo distinct_rel 
)
static

Definition at line 4900 of file planner.c.

4902 {
4903  Query *parse = root->parse;
4904  Path *cheapest_input_path = input_rel->cheapest_total_path;
4905  double numDistinctRows;
4906  bool allow_hash;
4907 
4908  /* Estimate number of distinct rows there will be */
4909  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4910  root->hasHavingQual)
4911  {
4912  /*
4913  * If there was grouping or aggregation, use the number of input rows
4914  * as the estimated number of DISTINCT rows (ie, assume the input is
4915  * already mostly unique).
4916  */
4917  numDistinctRows = cheapest_input_path->rows;
4918  }
4919  else
4920  {
4921  /*
4922  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4923  */
4924  List *distinctExprs;
4925 
4926  distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
4927  parse->targetList);
4928  numDistinctRows = estimate_num_groups(root, distinctExprs,
4929  cheapest_input_path->rows,
4930  NULL, NULL);
4931  }
4932 
4933  /*
4934  * Consider sort-based implementations of DISTINCT, if possible.
4935  */
4937  {
4938  /*
4939  * Firstly, if we have any adequately-presorted paths, just stick a
4940  * Unique node on those. We also, consider doing an explicit sort of
4941  * the cheapest input path and Unique'ing that. If any paths have
4942  * presorted keys then we'll create an incremental sort atop of those
4943  * before adding a unique node on the top.
4944  *
4945  * When we have DISTINCT ON, we must sort by the more rigorous of
4946  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4947  * Also, if we do have to do an explicit sort, we might as well use
4948  * the more rigorous ordering to avoid a second sort later. (Note
4949  * that the parser will have ensured that one clause is a prefix of
4950  * the other.)
4951  */
4952  List *needed_pathkeys;
4953  ListCell *lc;
4954  double limittuples = root->distinct_pathkeys == NIL ? 1.0 : -1.0;
4955 
4956  if (parse->hasDistinctOn &&
4958  list_length(root->sort_pathkeys))
4959  needed_pathkeys = root->sort_pathkeys;
4960  else
4961  needed_pathkeys = root->distinct_pathkeys;
4962 
4963  foreach(lc, input_rel->pathlist)
4964  {
4965  Path *input_path = (Path *) lfirst(lc);
4966  Path *sorted_path;
4967  bool is_sorted;
4968  int presorted_keys;
4969 
4970  is_sorted = pathkeys_count_contained_in(needed_pathkeys,
4971  input_path->pathkeys,
4972  &presorted_keys);
4973 
4974  if (is_sorted)
4975  sorted_path = input_path;
4976  else
4977  {
4978  /*
4979  * Try at least sorting the cheapest path and also try
4980  * incrementally sorting any path which is partially sorted
4981  * already (no need to deal with paths which have presorted
4982  * keys when incremental sort is disabled unless it's the
4983  * cheapest input path).
4984  */
4985  if (input_path != cheapest_input_path &&
4986  (presorted_keys == 0 || !enable_incremental_sort))
4987  continue;
4988 
4989  /*
4990  * We've no need to consider both a sort and incremental sort.
4991  * We'll just do a sort if there are no presorted keys and an
4992  * incremental sort when there are presorted keys.
4993  */
4994  if (presorted_keys == 0 || !enable_incremental_sort)
4995  sorted_path = (Path *) create_sort_path(root,
4996  distinct_rel,
4997  input_path,
4998  needed_pathkeys,
4999  limittuples);
5000  else
5001  sorted_path = (Path *) create_incremental_sort_path(root,
5002  distinct_rel,
5003  input_path,
5004  needed_pathkeys,
5005  presorted_keys,
5006  limittuples);
5007  }
5008 
5009  /*
5010  * distinct_pathkeys may have become empty if all of the pathkeys
5011  * were determined to be redundant. If all of the pathkeys are
5012  * redundant then each DISTINCT target must only allow a single
5013  * value, therefore all resulting tuples must be identical (or at
5014  * least indistinguishable by an equality check). We can uniquify
5015  * these tuples simply by just taking the first tuple. All we do
5016  * here is add a path to do "LIMIT 1" atop of 'sorted_path'. When
5017  * doing a DISTINCT ON we may still have a non-NIL sort_pathkeys
5018  * list, so we must still only do this with paths which are
5019  * correctly sorted by sort_pathkeys.
5020  */
5021  if (root->distinct_pathkeys == NIL)
5022  {
5023  Node *limitCount;
5024 
5025  limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5026  sizeof(int64),
5027  Int64GetDatum(1), false,
5028  FLOAT8PASSBYVAL);
5029 
5030  /*
5031  * If the query already has a LIMIT clause, then we could end
5032  * up with a duplicate LimitPath in the final plan. That does
5033  * not seem worth troubling over too much.
5034  */
5035  add_path(distinct_rel, (Path *)
5036  create_limit_path(root, distinct_rel, sorted_path,
5037  NULL, limitCount,
5038  LIMIT_OPTION_COUNT, 0, 1));
5039  }
5040  else
5041  {
5042  add_path(distinct_rel, (Path *)
5043  create_upper_unique_path(root, distinct_rel,
5044  sorted_path,
5046  numDistinctRows));
5047  }
5048  }
5049  }
5050 
5051  /*
5052  * Consider hash-based implementations of DISTINCT, if possible.
5053  *
5054  * If we were not able to make any other types of path, we *must* hash or
5055  * die trying. If we do have other choices, there are two things that
5056  * should prevent selection of hashing: if the query uses DISTINCT ON
5057  * (because it won't really have the expected behavior if we hash), or if
5058  * enable_hashagg is off.
5059  *
5060  * Note: grouping_is_hashable() is much more expensive to check than the
5061  * other gating conditions, so we want to do it last.
5062  */
5063  if (distinct_rel->pathlist == NIL)
5064  allow_hash = true; /* we have no alternatives */
5065  else if (parse->hasDistinctOn || !enable_hashagg)
5066  allow_hash = false; /* policy-based decision not to hash */
5067  else
5068  allow_hash = true; /* default */
5069 
5070  if (allow_hash && grouping_is_hashable(root->processed_distinctClause))
5071  {
5072  /* Generate hashed aggregate path --- no sort needed */
5073  add_path(distinct_rel, (Path *)
5074  create_agg_path(root,
5075  distinct_rel,
5076  cheapest_input_path,
5077  cheapest_input_path->pathtarget,
5078  AGG_HASHED,
5081  NIL,
5082  NULL,
5083  numDistinctRows));
5084  }
5085 
5086  return distinct_rel;
5087 }
#define FLOAT8PASSBYVAL
Definition: c.h:624
bool enable_hashagg
Definition: costsize.c:142
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1790
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:302
@ LIMIT_OPTION_COUNT
Definition: nodes.h:441
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:3763
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:3062
#define InvalidOid
Definition: postgres_ext.h:36
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3386
Cardinality rows
Definition: pathnodes.h:1628
List * distinct_pathkeys
Definition: pathnodes.h:397
bool hasHavingQual
Definition: pathnodes.h:493
List * sort_pathkeys
Definition: pathnodes.h:399
List * processed_distinctClause
Definition: pathnodes.h:442
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:392
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:540
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:560

References add_path(), AGG_HASHED, AGGSPLIT_SIMPLE, RelOptInfo::cheapest_total_path, create_agg_path(), create_incremental_sort_path(), create_limit_path(), create_sort_path(), create_upper_unique_path(), PlannerInfo::distinct_pathkeys, enable_hashagg, enable_incremental_sort, estimate_num_groups(), FLOAT8PASSBYVAL, get_sortgrouplist_exprs(), grouping_is_hashable(), grouping_is_sortable(), PlannerInfo::hasHavingQual, Int64GetDatum(), InvalidOid, lfirst, LIMIT_OPTION_COUNT, list_length(), makeConst(), NIL, parse(), PlannerInfo::parse, Path::pathkeys, pathkeys_count_contained_in(), RelOptInfo::pathlist, PlannerInfo::processed_distinctClause, Path::rows, and PlannerInfo::sort_pathkeys.

Referenced by create_distinct_paths(), and create_partial_distinct_paths().

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

3703 {
3704  Query *parse = root->parse;
3705  RelOptInfo *grouped_rel;
3706  RelOptInfo *partially_grouped_rel;
3707  AggClauseCosts agg_costs;
3708 
3709  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3710  get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &agg_costs);
3711 
3712  /*
3713  * Create grouping relation to hold fully aggregated grouping and/or
3714  * aggregation paths.
3715  */
3716  grouped_rel = make_grouping_rel(root, input_rel, target,
3717  target_parallel_safe, parse->havingQual);
3718 
3719  /*
3720  * Create either paths for a degenerate grouping or paths for ordinary
3721  * grouping, as appropriate.
3722  */
3723  if (is_degenerate_grouping(root))
3724  create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3725  else
3726  {
3727  int flags = 0;
3728  GroupPathExtraData extra;
3729 
3730  /*
3731  * Determine whether it's possible to perform sort-based
3732  * implementations of grouping. (Note that if processed_groupClause
3733  * is empty, grouping_is_sortable() is trivially true, and all the
3734  * pathkeys_contained_in() tests will succeed too, so that we'll
3735  * consider every surviving input path.)
3736  *
3737  * If we have grouping sets, we might be able to sort some but not all
3738  * of them; in this case, we need can_sort to be true as long as we
3739  * must consider any sorted-input plan.
3740  */
3741  if ((gd && gd->rollups != NIL)
3743  flags |= GROUPING_CAN_USE_SORT;
3744 
3745  /*
3746  * Determine whether we should consider hash-based implementations of
3747  * grouping.
3748  *
3749  * Hashed aggregation only applies if we're grouping. If we have
3750  * grouping sets, some groups might be hashable but others not; in
3751  * this case we set can_hash true as long as there is nothing globally
3752  * preventing us from hashing (and we should therefore consider plans
3753  * with hashes).
3754  *
3755  * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3756  * BY aggregates. (Doing so would imply storing *all* the input
3757  * values in the hash table, and/or running many sorts in parallel,
3758  * either of which seems like a certain loser.) We similarly don't
3759  * support ordered-set aggregates in hashed aggregation, but that case
3760  * is also included in the numOrderedAggs count.
3761  *
3762  * Note: grouping_is_hashable() is much more expensive to check than
3763  * the other gating conditions, so we want to do it last.
3764  */
3765  if ((parse->groupClause != NIL &&
3766  root->numOrderedAggs == 0 &&
3768  flags |= GROUPING_CAN_USE_HASH;
3769 
3770  /*
3771  * Determine whether partial aggregation is possible.
3772  */
3773  if (can_partial_agg(root))
3774  flags |= GROUPING_CAN_PARTIAL_AGG;
3775 
3776  extra.flags = flags;
3777  extra.target_parallel_safe = target_parallel_safe;
3778  extra.havingQual = parse->havingQual;
3779  extra.targetList = parse->targetList;
3780  extra.partial_costs_set = false;
3781 
3782  /*
3783  * Determine whether partitionwise aggregation is in theory possible.
3784  * It can be disabled by the user, and for now, we don't try to
3785  * support grouping sets. create_ordinary_grouping_paths() will check
3786  * additional conditions, such as whether input_rel is partitioned.
3787  */
3788  if (enable_partitionwise_aggregate && !parse->groupingSets)
3790  else
3792 
3793  create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3794  &agg_costs, gd, &extra,
3795  &partially_grouped_rel);
3796  }
3797 
3798  set_cheapest(grouped_rel);
3799  return grouped_rel;
3800 }
#define MemSet(start, val, len)
Definition: c.h:1009
bool enable_partitionwise_aggregate
Definition: costsize.c:150
@ PARTITIONWISE_AGGREGATE_FULL
Definition: pathnodes.h:3230
@ PARTITIONWISE_AGGREGATE_NONE
Definition: pathnodes.h:3229
#define GROUPING_CAN_PARTIAL_AGG
Definition: pathnodes.h:3214
static void create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
Definition: planner.c:3885
static bool is_degenerate_grouping(PlannerInfo *root)
Definition: planner.c:3864
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:3949
static bool can_partial_agg(PlannerInfo *root)
Definition: planner.c:7497
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3811
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:561
PartitionwiseAggregateType patype
Definition: pathnodes.h:3259

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(), GROUPING_CAN_PARTIAL_AGG, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, grouping_is_hashable(), grouping_is_sortable(), 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, PlannerInfo::processed_groupClause, grouping_sets_data::rollups, set_cheapest(), GroupPathExtraData::target_parallel_safe, and GroupPathExtraData::targetList.

Referenced by grouping_planner().

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

4544 {
4545  PathTarget *window_target;
4546  ListCell *l;
4547  List *topqual = NIL;
4548 
4549  /*
4550  * Since each window clause could require a different sort order, we stack
4551  * up a WindowAgg node for each clause, with sort steps between them as
4552  * needed. (We assume that select_active_windows chose a good order for
4553  * executing the clauses in.)
4554  *
4555  * input_target should contain all Vars and Aggs needed for the result.
4556  * (In some cases we wouldn't need to propagate all of these all the way
4557  * to the top, since they might only be needed as inputs to WindowFuncs.
4558  * It's probably not worth trying to optimize that though.) It must also
4559  * contain all window partitioning and sorting expressions, to ensure
4560  * they're computed only once at the bottom of the stack (that's critical
4561  * for volatile functions). As we climb up the stack, we'll add outputs
4562  * for the WindowFuncs computed at each level.
4563  */
4564  window_target = input_target;
4565 
4566  foreach(l, activeWindows)
4567  {
4569  List *window_pathkeys;
4570  int presorted_keys;
4571  bool is_sorted;
4572  bool topwindow;
4573 
4574  window_pathkeys = make_pathkeys_for_window(root,
4575  wc,
4576  root->processed_tlist);
4577 
4578  is_sorted = pathkeys_count_contained_in(window_pathkeys,
4579  path->pathkeys,
4580  &presorted_keys);
4581 
4582  /* Sort if necessary */
4583  if (!is_sorted)
4584  {
4585  /*
4586  * No presorted keys or incremental sort disabled, just perform a
4587  * complete sort.
4588  */
4589  if (presorted_keys == 0 || !enable_incremental_sort)
4590  path = (Path *) create_sort_path(root, window_rel,
4591  path,
4592  window_pathkeys,
4593  -1.0);
4594  else
4595  {
4596  /*
4597  * Since we have presorted keys and incremental sort is
4598  * enabled, just use incremental sort.
4599  */
4600  path = (Path *) create_incremental_sort_path(root,
4601  window_rel,
4602  path,
4603  window_pathkeys,
4604  presorted_keys,
4605  -1.0);
4606  }
4607  }
4608 
4609  if (lnext(activeWindows, l))
4610  {
4611  /*
4612  * Add the current WindowFuncs to the output target for this
4613  * intermediate WindowAggPath. We must copy window_target to
4614  * avoid changing the previous path's target.
4615  *
4616  * Note: a WindowFunc adds nothing to the target's eval costs; but
4617  * we do need to account for the increase in tlist width.
4618  */
4619  ListCell *lc2;
4620 
4621  window_target = copy_pathtarget(window_target);
4622  foreach(lc2, wflists->windowFuncs[wc->winref])
4623  {
4624  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4625 
4626  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4627  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4628  }
4629  }
4630  else
4631  {
4632  /* Install the goal target in the topmost WindowAgg */
4633  window_target = output_target;
4634  }
4635 
4636  /* mark the final item in the list as the top-level window */
4637  topwindow = foreach_current_index(l) == list_length(activeWindows) - 1;
4638 
4639  /*
4640  * Accumulate all of the runConditions from each intermediate
4641  * WindowClause. The top-level WindowAgg must pass these as a qual so
4642  * that it filters out unwanted tuples correctly.
4643  */
4644  if (!topwindow)
4645  topqual = list_concat(topqual, wc->runCondition);
4646 
4647  path = (Path *)
4648  create_windowagg_path(root, window_rel, path, window_target,
4649  wflists->windowFuncs[wc->winref],
4650  wc, topwindow ? topqual : NIL, topwindow);
4651  }
4652 
4653  add_path(window_rel, path);
4654 }
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2560
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause, List *qual, bool topwindow)
Definition: pathnode.c:3427
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:6033
List * processed_tlist
Definition: pathnodes.h:453
List ** windowFuncs
Definition: clauses.h:23
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:695

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

Referenced by create_window_paths().

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

5112 {
5113  Path *cheapest_input_path = input_rel->cheapest_total_path;
5114  RelOptInfo *ordered_rel;
5115  ListCell *lc;
5116 
5117  /* For now, do all work in the (ORDERED, NULL) upperrel */
5118  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
5119 
5120  /*
5121  * If the input relation is not parallel-safe, then the ordered relation
5122  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
5123  * target list is parallel-safe.
5124  */
5125  if (input_rel->consider_parallel && target_parallel_safe)
5126  ordered_rel->consider_parallel = true;
5127 
5128  /*
5129  * If the input rel belongs to a single FDW, so does the ordered_rel.
5130  */
5131  ordered_rel->serverid = input_rel->serverid;
5132  ordered_rel->userid = input_rel->userid;
5133  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
5134  ordered_rel->fdwroutine = input_rel->fdwroutine;
5135 
5136  foreach(lc, input_rel->pathlist)
5137  {
5138  Path *input_path = (Path *) lfirst(lc);
5139  Path *sorted_path;
5140  bool is_sorted;
5141  int presorted_keys;
5142 
5143  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5144  input_path->pathkeys, &presorted_keys);
5145 
5146  if (is_sorted)
5147  sorted_path = input_path;
5148  else
5149  {
5150  /*
5151  * Try at least sorting the cheapest path and also try
5152  * incrementally sorting any path which is partially sorted
5153  * already (no need to deal with paths which have presorted keys
5154  * when incremental sort is disabled unless it's the cheapest
5155  * input path).
5156  */
5157  if (input_path != cheapest_input_path &&
5158  (presorted_keys == 0 || !enable_incremental_sort))
5159  continue;
5160 
5161  /*
5162  * We've no need to consider both a sort and incremental sort.
5163  * We'll just do a sort if there are no presorted keys and an
5164  * incremental sort when there are presorted keys.
5165  */
5166  if (presorted_keys == 0 || !enable_incremental_sort)
5167  sorted_path = (Path *) create_sort_path(root,
5168  ordered_rel,
5169  input_path,
5170  root->sort_pathkeys,
5171  limit_tuples);
5172  else
5173  sorted_path = (Path *) create_incremental_sort_path(root,
5174  ordered_rel,
5175  input_path,
5176  root->sort_pathkeys,
5177  presorted_keys,
5178  limit_tuples);
5179  }
5180 
5181  /* Add projection step if needed */
5182  if (sorted_path->pathtarget != target)
5183  sorted_path = apply_projection_to_path(root, ordered_rel,
5184  sorted_path, target);
5185 
5186  add_path(ordered_rel, sorted_path);
5187  }
5188 
5189  /*
5190  * generate_gather_paths() will have already generated a simple Gather
5191  * path for the best parallel path, if any, and the loop above will have
5192  * considered sorting it. Similarly, generate_gather_paths() will also
5193  * have generated order-preserving Gather Merge plans which can be used
5194  * without sorting if they happen to match the sort_pathkeys, and the loop
5195  * above will have handled those as well. However, there's one more
5196  * possibility: it may make sense to sort the cheapest partial path
5197  * according to the required output order and then use Gather Merge.
5198  */
5199  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5200  input_rel->partial_pathlist != NIL)
5201  {
5202  Path *cheapest_partial_path;
5203 
5204  cheapest_partial_path = linitial(input_rel->partial_pathlist);
5205 
5206  /*
5207  * If cheapest partial path doesn't need a sort, this is redundant
5208  * with what's already been tried.
5209  */
5211  cheapest_partial_path->pathkeys))
5212  {
5213  Path *path;
5214  double total_groups;
5215 
5216  path = (Path *) create_sort_path(root,
5217  ordered_rel,
5218  cheapest_partial_path,
5219  root->sort_pathkeys,
5220  limit_tuples);
5221 
5222  total_groups = cheapest_partial_path->rows *
5223  cheapest_partial_path->parallel_workers;
5224  path = (Path *)
5225  create_gather_merge_path(root, ordered_rel,
5226  path,
5227  path->pathtarget,
5228  root->sort_pathkeys, NULL,
5229  &total_groups);
5230 
5231  /* Add projection step if needed */
5232  if (path->pathtarget != target)
5233  path = apply_projection_to_path(root, ordered_rel,
5234  path, target);
5235 
5236  add_path(ordered_rel, path);
5237  }
5238 
5239  /*
5240  * Consider incremental sort with a gather merge on partial paths.
5241  *
5242  * We can also skip the entire loop when we only have a single-item
5243  * sort_pathkeys because then we can't possibly have a presorted
5244  * prefix of the list without having the list be fully sorted.
5245  */
5247  {
5248  foreach(lc, input_rel->partial_pathlist)
5249  {
5250  Path *input_path = (Path *) lfirst(lc);
5251  Path *sorted_path;
5252  bool is_sorted;
5253  int presorted_keys;
5254  double total_groups;
5255 
5256  /*
5257  * We don't care if this is the cheapest partial path - we
5258  * can't simply skip it, because it may be partially sorted in
5259  * which case we want to consider adding incremental sort
5260  * (instead of full sort, which is what happens above).
5261  */
5262 
5263  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5264  input_path->pathkeys,
5265  &presorted_keys);
5266 
5267  /* No point in adding incremental sort on fully sorted paths. */
5268  if (is_sorted)
5269  continue;
5270 
5271  if (presorted_keys == 0)
5272  continue;
5273 
5274  /* Since we have presorted keys, consider incremental sort. */
5275  sorted_path = (Path *) create_incremental_sort_path(root,
5276  ordered_rel,
5277  input_path,
5278  root->sort_pathkeys,
5279  presorted_keys,
5280  limit_tuples);
5281  total_groups = input_path->rows *
5282  input_path->parallel_workers;
5283  sorted_path = (Path *)
5284  create_gather_merge_path(root, ordered_rel,
5285  sorted_path,
5286  sorted_path->pathtarget,
5287  root->sort_pathkeys, NULL,
5288  &total_groups);
5289 
5290  /* Add projection step if needed */
5291  if (sorted_path->pathtarget != target)
5292  sorted_path = apply_projection_to_path(root, ordered_rel,
5293  sorted_path, target);
5294 
5295  add_path(ordered_rel, sorted_path);
5296  }
5297  }
5298  }
5299 
5300  /*
5301  * If there is an FDW that's responsible for all baserels of the query,
5302  * let it consider adding ForeignPaths.
5303  */
5304  if (ordered_rel->fdwroutine &&
5305  ordered_rel->fdwroutine->GetForeignUpperPaths)
5306  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5307  input_rel, ordered_rel,
5308  NULL);
5309 
5310  /* Let extensions possibly add some more paths */
5312  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5313  input_rel, ordered_rel, NULL);
5314 
5315  /*
5316  * No need to bother with set_cheapest here; grouping_planner does not
5317  * need us to do it.
5318  */
5319  Assert(ordered_rel->pathlist != NIL);
5320 
5321  return ordered_rel;
5322 }
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1873
@ UPPERREL_ORDERED
Definition: pathnodes.h:78
int parallel_workers
Definition: pathnodes.h:1625

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, fetch_upper_rel(), lfirst, linitial, list_length(), NIL, Path::parallel_workers, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), pathkeys_count_contained_in(), RelOptInfo::pathlist, Path::rows, RelOptInfo::serverid, PlannerInfo::sort_pathkeys, UPPERREL_ORDERED, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by grouping_planner().

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

3955 {
3956  Path *cheapest_path = input_rel->cheapest_total_path;
3957  RelOptInfo *partially_grouped_rel = NULL;
3958  double dNumGroups;
3960 
3961  /*
3962  * If this is the topmost grouping relation or if the parent relation is
3963  * doing some form of partitionwise aggregation, then we may be able to do
3964  * it at this level also. However, if the input relation is not
3965  * partitioned, partitionwise aggregate is impossible.
3966  */
3967  if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
3968  IS_PARTITIONED_REL(input_rel))
3969  {
3970  /*
3971  * If this is the topmost relation or if the parent relation is doing
3972  * full partitionwise aggregation, then we can do full partitionwise
3973  * aggregation provided that the GROUP BY clause contains all of the
3974  * partitioning columns at this level. Otherwise, we can do at most
3975  * partial partitionwise aggregation. But if partial aggregation is
3976  * not supported in general then we can't use it for partitionwise
3977  * aggregation either.
3978  *
3979  * Check parse->groupClause not processed_groupClause, because it's
3980  * okay if some of the partitioning columns were proved redundant.
3981  */
3982  if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
3983  group_by_has_partkey(input_rel, extra->targetList,
3984  root->parse->groupClause))
3986  else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3988  else
3990  }
3991 
3992  /*
3993  * Before generating paths for grouped_rel, we first generate any possible
3994  * partially grouped paths; that way, later code can easily consider both
3995  * parallel and non-parallel approaches to grouping.
3996  */
3997  if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3998  {
3999  bool force_rel_creation;
4000 
4001  /*
4002  * If we're doing partitionwise aggregation at this level, force
4003  * creation of a partially_grouped_rel so we can add partitionwise
4004  * paths to it.
4005  */
4006  force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
4007 
4008  partially_grouped_rel =
4010  grouped_rel,
4011  input_rel,
4012  gd,
4013  extra,
4014  force_rel_creation);
4015  }
4016 
4017  /* Set out parameter. */
4018  *partially_grouped_rel_p = partially_grouped_rel;
4019 
4020  /* Apply partitionwise aggregation technique, if possible. */
4021  if (patype != PARTITIONWISE_AGGREGATE_NONE)
4022  create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
4023  partially_grouped_rel, agg_costs,
4024  gd, patype, extra);
4025 
4026  /* If we are doing partial aggregation only, return. */
4028  {
4029  Assert(partially_grouped_rel);
4030 
4031  if (partially_grouped_rel->pathlist)
4032  set_cheapest(partially_grouped_rel);
4033 
4034  return;
4035  }
4036 
4037  /* Gather any partially grouped partial paths. */
4038  if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
4039  {
4040  gather_grouping_paths(root, partially_grouped_rel);
4041  set_cheapest(partially_grouped_rel);
4042  }
4043 
4044  /*
4045  * Estimate number of groups.
4046  */
4047  dNumGroups = get_number_of_groups(root,
4048  cheapest_path->rows,
4049  gd,
4050  extra->targetList);
4051 
4052  /* Build final grouping paths */
4053  add_paths_to_grouping_rel(root, input_rel, grouped_rel,
4054  partially_grouped_rel, agg_costs, gd,
4055  dNumGroups, extra);
4056 
4057  /* Give a helpful error if we failed to find any implementation */
4058  if (grouped_rel->pathlist == NIL)
4059  ereport(ERROR,
4060  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4061  errmsg("could not implement GROUP BY"),
4062  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4063 
4064  /*
4065  * If there is an FDW that's responsible for all baserels of the query,
4066  * let it consider adding ForeignPaths.
4067  */
4068  if (grouped_rel->fdwroutine &&
4069  grouped_rel->fdwroutine->GetForeignUpperPaths)
4070  grouped_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG,
4071  input_rel, grouped_rel,
4072  extra);
4073 
4074  /* Let extensions possibly add some more paths */
4076  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4077  input_rel, grouped_rel,
4078  extra);
4079 }
PartitionwiseAggregateType
Definition: pathnodes.h:3228
@ PARTITIONWISE_AGGREGATE_PARTIAL
Definition: pathnodes.h:3231
@ UPPERREL_GROUP_AGG
Definition: pathnodes.h:74
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:7086
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:6822
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3576
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:7774
static bool group_by_has_partkey(RelOptInfo *input_rel, List *targetList, List *groupClause)
Definition: planner.c:7918
List * groupClause
Definition: parsenodes.h:197

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, GroupPathExtraData::flags, gather_grouping_paths(), get_number_of_groups(), 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().

◆ create_partial_distinct_paths()

static void create_partial_distinct_paths ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo final_distinct_rel 
)
static

Definition at line 4736 of file planner.c.

4738 {
4739  RelOptInfo *partial_distinct_rel;
4740  Query *parse;
4741  List *distinctExprs;
4742  double numDistinctRows;
4743  Path *cheapest_partial_path;
4744  ListCell *lc;
4745 
4746  /* nothing to do when there are no partial paths in the input rel */
4747  if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
4748  return;
4749 
4750  parse = root->parse;
4751 
4752  /* can't do parallel DISTINCT ON */
4753  if (parse->hasDistinctOn)
4754  return;
4755 
4756  partial_distinct_rel = fetch_upper_rel(root, UPPERREL_PARTIAL_DISTINCT,
4757  NULL);
4758  partial_distinct_rel->reltarget = root->upper_targets[UPPERREL_PARTIAL_DISTINCT];
4759  partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
4760 
4761  /*
4762  * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
4763  */
4764  partial_distinct_rel->serverid = input_rel->serverid;
4765  partial_distinct_rel->userid = input_rel->userid;
4766  partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4767  partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
4768 
4769  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4770 
4771  distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
4772  parse->targetList);
4773 
4774  /* estimate how many distinct rows we'll get from each worker */
4775  numDistinctRows = estimate_num_groups(root, distinctExprs,
4776  cheapest_partial_path->rows,
4777  NULL, NULL);
4778 
4779  /*
4780  * Try sorting the cheapest path and incrementally sorting any paths with
4781  * presorted keys and put a unique paths atop of those.
4782  */
4784  {
4785  foreach(lc, input_rel->partial_pathlist)
4786  {
4787  Path *input_path = (Path *) lfirst(lc);
4788  Path *sorted_path;
4789  bool is_sorted;
4790  int presorted_keys;
4791 
4793  input_path->pathkeys,
4794  &presorted_keys);
4795 
4796  if (is_sorted)
4797  sorted_path = input_path;
4798  else
4799  {
4800  /*
4801  * Try at least sorting the cheapest path and also try
4802  * incrementally sorting any path which is partially sorted
4803  * already (no need to deal with paths which have presorted
4804  * keys when incremental sort is disabled unless it's the
4805  * cheapest partial path).
4806  */
4807  if (input_path != cheapest_partial_path &&
4808  (presorted_keys == 0 || !enable_incremental_sort))
4809  continue;
4810 
4811  /*
4812  * We've no need to consider both a sort and incremental sort.
4813  * We'll just do a sort if there are no presorted keys and an
4814  * incremental sort when there are presorted keys.
4815  */
4816  if (presorted_keys == 0 || !enable_incremental_sort)
4817  sorted_path = (Path *) create_sort_path(root,
4818  partial_distinct_rel,
4819  input_path,
4820  root->distinct_pathkeys,
4821  -1.0);
4822  else
4823  sorted_path = (Path *) create_incremental_sort_path(root,
4824  partial_distinct_rel,
4825  input_path,
4826  root->distinct_pathkeys,
4827  presorted_keys,
4828  -1.0);
4829  }
4830 
4831  add_partial_path(partial_distinct_rel, (Path *)
4832  create_upper_unique_path(root, partial_distinct_rel,
4833  sorted_path,
4835  numDistinctRows));
4836  }
4837  }
4838 
4839  /*
4840  * Now try hash aggregate paths, if enabled and hashing is possible. Since
4841  * we're not on the hook to ensure we do our best to create at least one
4842  * path here, we treat enable_hashagg as a hard off-switch rather than the
4843  * slightly softer variant in create_final_distinct_paths.
4844  */
4846  {
4847  add_partial_path(partial_distinct_rel, (Path *)
4848  create_agg_path(root,
4849  partial_distinct_rel,
4850  cheapest_partial_path,
4851  cheapest_partial_path->pathtarget,
4852  AGG_HASHED,
4855  NIL,
4856  NULL,
4857  numDistinctRows));
4858  }
4859 
4860  /*
4861  * If there is an FDW that's responsible for all baserels of the query,
4862  * let it consider adding ForeignPaths.
4863  */
4864  if (partial_distinct_rel->fdwroutine &&
4865  partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
4866  partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4868  input_rel,
4869  partial_distinct_rel,
4870  NULL);
4871 
4872  /* Let extensions possibly add some more partial paths */
4874  (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
4875  input_rel, partial_distinct_rel, NULL);
4876 
4877  if (partial_distinct_rel->partial_pathlist != NIL)
4878  {
4879  generate_gather_paths(root, partial_distinct_rel, true);
4880  set_cheapest(partial_distinct_rel);
4881 
4882  /*
4883  * Finally, create paths to distinctify the final result. This step
4884  * is needed to remove any duplicates due to combining rows from
4885  * parallel workers.
4886  */
4887  create_final_distinct_paths(root, partial_distinct_rel,
4888  final_distinct_rel);
4889  }
4890 }
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3060
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
@ UPPERREL_PARTIAL_DISTINCT
Definition: pathnodes.h:76

References add_partial_path(), AGG_HASHED, AGGSPLIT_SIMPLE, RelOptInfo::consider_parallel, create_agg_path(), create_final_distinct_paths(), create_incremental_sort_path(), create_sort_path(), create_upper_paths_hook, create_upper_unique_path(), PlannerInfo::distinct_pathkeys, enable_hashagg, enable_incremental_sort, estimate_num_groups(), fetch_upper_rel(), generate_gather_paths(), get_sortgrouplist_exprs(), grouping_is_hashable(), grouping_is_sortable(), lfirst, linitial, list_length(), NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_count_contained_in(), PlannerInfo::processed_distinctClause, RelOptInfo::reltarget, Path::rows, RelOptInfo::serverid, set_cheapest(), UPPERREL_PARTIAL_DISTINCT, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by create_distinct_paths().

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

7092 {
7093  Query *parse = root->parse;
7094  RelOptInfo *partially_grouped_rel;
7095  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
7096  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7097  Path *cheapest_partial_path = NULL;
7098  Path *cheapest_total_path = NULL;
7099  double dNumPartialGroups = 0;
7100  double dNumPartialPartialGroups = 0;
7101  ListCell *lc;
7102  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7103  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7104 
7105  /*
7106  * Consider whether we should generate partially aggregated non-partial
7107  * paths. We can only do this if we have a non-partial path, and only if
7108  * the parent of the input rel is performing partial partitionwise
7109  * aggregation. (Note that extra->patype is the type of partitionwise
7110  * aggregation being used at the parent level, not this level.)
7111  */
7112  if (input_rel->pathlist != NIL &&
7114  cheapest_total_path = input_rel->cheapest_total_path;
7115 
7116  /*
7117  * If parallelism is possible for grouped_rel, then we should consider
7118  * generating partially-grouped partial paths. However, if the input rel
7119  * has no partial paths, then we can't.
7120  */
7121  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
7122  cheapest_partial_path = linitial(input_rel->partial_pathlist);
7123 
7124  /*
7125  * If we can't partially aggregate partial paths, and we can't partially
7126  * aggregate non-partial paths, then don't bother creating the new
7127  * RelOptInfo at all, unless the caller specified force_rel_creation.
7128  */
7129  if (cheapest_total_path == NULL &&
7130  cheapest_partial_path == NULL &&
7131  !force_rel_creation)
7132  return NULL;
7133 
7134  /*
7135  * Build a new upper relation to represent the result of partially
7136  * aggregating the rows from the input relation.
7137  */
7138  partially_grouped_rel = fetch_upper_rel(root,
7140  grouped_rel->relids);
7141  partially_grouped_rel->consider_parallel =
7142  grouped_rel->consider_parallel;
7143  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
7144  partially_grouped_rel->serverid = grouped_rel->serverid;
7145  partially_grouped_rel->userid = grouped_rel->userid;
7146  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
7147  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
7148 
7149  /*
7150  * Build target list for partial aggregate paths. These paths cannot just
7151  * emit the same tlist as regular aggregate paths, because (1) we must
7152  * include Vars and Aggrefs needed in HAVING, which might not appear in
7153  * the result tlist, and (2) the Aggrefs must be set in partial mode.
7154  */
7155  partially_grouped_rel->reltarget =
7156  make_partial_grouping_target(root, grouped_rel->reltarget,
7157  extra->havingQual);
7158 
7159  if (!extra->partial_costs_set)
7160  {
7161  /*
7162  * Collect statistics about aggregates for estimating costs of
7163  * performing aggregation in parallel.
7164  */
7165  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
7166  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
7167  if (parse->hasAggs)
7168  {
7169  /* partial phase */
7171  agg_partial_costs);
7172 
7173  /* final phase */
7175  agg_final_costs);
7176  }
7177 
7178  extra->partial_costs_set = true;
7179  }
7180 
7181  /* Estimate number of partial groups. */
7182  if (cheapest_total_path != NULL)
7183  dNumPartialGroups =
7184  get_number_of_groups(root,
7185  cheapest_total_path->rows,
7186  gd,
7187  extra->targetList);
7188  if (cheapest_partial_path != NULL)
7189  dNumPartialPartialGroups =
7190  get_number_of_groups(root,
7191  cheapest_partial_path->rows,
7192  gd,
7193  extra->targetList);
7194 
7195  if (can_sort && cheapest_total_path != NULL)
7196  {
7197  /* This should have been checked previously */
7198  Assert(parse->hasAggs || parse->groupClause);
7199 
7200  /*
7201  * Use any available suitably-sorted path as input, and also consider
7202  * sorting the cheapest partial path.
7203  */
7204  foreach(lc, input_rel->pathlist)
7205  {
7206  Path *path = (Path *) lfirst(lc);
7207  bool is_sorted;
7208  int presorted_keys;
7209 
7210  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7211  path->pathkeys,
7212  &presorted_keys);
7213  if (!is_sorted)
7214  {
7215  /*
7216  * Try at least sorting the cheapest path and also try
7217  * incrementally sorting any path which is partially sorted
7218  * already (no need to deal with paths which have presorted
7219  * keys when incremental sort is disabled unless it's the
7220  * cheapest input path).
7221  */
7222  if (path != cheapest_total_path &&
7223  (presorted_keys == 0 || !enable_incremental_sort))
7224  continue;
7225 
7226  /*
7227  * We've no need to consider both a sort and incremental sort.
7228  * We'll just do a sort if there are no presorted keys and an
7229  * incremental sort when there are presorted keys.
7230  */
7231  if (presorted_keys == 0 || !enable_incremental_sort)
7232  path = (Path *) create_sort_path(root,
7233  partially_grouped_rel,
7234  path,
7235  root->group_pathkeys,
7236  -1.0);
7237  else
7238  path = (Path *) create_incremental_sort_path(root,
7239  partially_grouped_rel,
7240  path,
7241  root->group_pathkeys,
7242  presorted_keys,
7243  -1.0);
7244  }
7245 
7246  if (parse->hasAggs)
7247  add_path(partially_grouped_rel, (Path *)
7248  create_agg_path(root,
7249  partially_grouped_rel,
7250  path,
7251  partially_grouped_rel->reltarget,
7252  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7254  root->processed_groupClause,
7255  NIL,
7256  agg_partial_costs,
7257  dNumPartialGroups));
7258  else
7259  add_path(partially_grouped_rel, (Path *)
7260  create_group_path(root,
7261  partially_grouped_rel,
7262  path,
7263  root->processed_groupClause,
7264  NIL,
7265  dNumPartialGroups));
7266  }
7267  }
7268 
7269  if (can_sort && cheapest_partial_path != NULL)
7270  {
7271  /* Similar to above logic, but for partial paths. */
7272  foreach(lc, input_rel->partial_pathlist)
7273  {
7274  Path *path = (Path *) lfirst(lc);
7275  bool is_sorted;
7276  int presorted_keys;
7277 
7278  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7279  path->pathkeys,
7280  &presorted_keys);
7281 
7282  if (!is_sorted)
7283  {
7284  /*
7285  * Try at least sorting the cheapest path and also try
7286  * incrementally sorting any path which is partially sorted
7287  * already (no need to deal with paths which have presorted
7288  * keys when incremental sort is disabled unless it's the
7289  * cheapest input path).
7290  */
7291  if (path != cheapest_partial_path &&
7292  (presorted_keys == 0 || !enable_incremental_sort))
7293  continue;
7294 
7295  /*
7296  * We've no need to consider both a sort and incremental sort.
7297  * We'll just do a sort if there are no presorted keys and an
7298  * incremental sort when there are presorted keys.
7299  */
7300  if (presorted_keys == 0 || !enable_incremental_sort)
7301  path = (Path *) create_sort_path(root,
7302  partially_grouped_rel,
7303  path,
7304  root->group_pathkeys,
7305  -1.0);
7306  else
7307  path = (Path *) create_incremental_sort_path(root,
7308  partially_grouped_rel,
7309  path,
7310  root->group_pathkeys,
7311  presorted_keys,
7312  -1.0);
7313  }
7314 
7315  if (parse->hasAggs)
7316  add_partial_path(partially_grouped_rel, (Path *)
7317  create_agg_path(root,
7318  partially_grouped_rel,
7319  path,
7320  partially_grouped_rel->reltarget,
7321  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7323  root->processed_groupClause,
7324  NIL,
7325  agg_partial_costs,
7326  dNumPartialPartialGroups));
7327  else
7328  add_partial_path(partially_grouped_rel, (Path *)
7329  create_group_path(root,
7330  partially_grouped_rel,
7331  path,
7332  root->processed_groupClause,
7333  NIL,
7334  dNumPartialPartialGroups));
7335  }
7336  }
7337 
7338  /*
7339  * Add a partially-grouped HashAgg Path where possible
7340  */
7341  if (can_hash && cheapest_total_path != NULL)
7342  {
7343  /* Checked above */
7344  Assert(parse->hasAggs || parse->groupClause);
7345 
7346  add_path(partially_grouped_rel, (Path *)
7347  create_agg_path(root,
7348  partially_grouped_rel,
7349  cheapest_total_path,
7350  partially_grouped_rel->reltarget,
7351  AGG_HASHED,
7353  root->processed_groupClause,
7354  NIL,
7355  agg_partial_costs,
7356  dNumPartialGroups));
7357  }
7358 
7359  /*
7360  * Now add a partially-grouped HashAgg partial Path where possible
7361  */
7362  if (can_hash && cheapest_partial_path != NULL)
7363  {
7364  add_partial_path(partially_grouped_rel, (Path *)
7365  create_agg_path(root,
7366  partially_grouped_rel,
7367  cheapest_partial_path,
7368  partially_grouped_rel->reltarget,
7369  AGG_HASHED,
7371  root->processed_groupClause,
7372  NIL,
7373  agg_partial_costs,
7374  dNumPartialPartialGroups));
7375  }
7376 
7377  /*
7378  * If there is an FDW that's responsible for all baserels of the query,
7379  * let it consider adding partially grouped ForeignPaths.
7380  */
7381  if (partially_grouped_rel->fdwroutine &&
7382  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
7383  {
7384  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
7385 
7386  fdwroutine->GetForeignUpperPaths(root,
7388  input_rel, partially_grouped_rel,
7389  extra);
7390  }
7391 
7392  return partially_grouped_rel;
7393 }
@ AGGSPLIT_INITIAL_SERIAL
Definition: nodes.h:389
@ UPPERREL_PARTIAL_GROUP_AGG
Definition: pathnodes.h:72
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:5441
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:3252
RelOptKind reloptkind
Definition: pathnodes.h:850

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, fetch_upper_rel(), GroupPathExtraData::flags, get_agg_clause_costs(), get_number_of_groups(), FdwRoutine::GetForeignUpperPaths, PlannerInfo::group_pathkeys, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, GroupPathExtraData::havingQual, lfirst, linitial, make_partial_grouping_target(), MemSet, NIL, parse(), PlannerInfo::parse, GroupPathExtraData::partial_costs_set, RelOptInfo::partial_pathlist, PARTITIONWISE_AGGREGATE_PARTIAL, Path::pathkeys, pathkeys_count_contained_in(), RelOptInfo::pathlist, GroupPathExtraData::patype, PlannerInfo::processed_groupClause, 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().

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

7782 {
7783  List *grouped_live_children = NIL;
7784  List *partially_grouped_live_children = NIL;
7785  PathTarget *target = grouped_rel->reltarget;
7786  bool partial_grouping_valid = true;
7787  int i;
7788 
7791  partially_grouped_rel != NULL);
7792 
7793  /* Add paths for partitionwise aggregation/grouping. */
7794  i = -1;
7795  while ((i = bms_next_member(input_rel->live_parts, i)) >= 0)
7796  {
7797  RelOptInfo *child_input_rel = input_rel->part_rels[i];
7798  PathTarget *child_target;
7799  AppendRelInfo **appinfos;
7800  int nappinfos;
7801  GroupPathExtraData child_extra;
7802  RelOptInfo *child_grouped_rel;
7803  RelOptInfo *child_partially_grouped_rel;
7804 
7805  Assert(child_input_rel != NULL);
7806 
7807  /* Dummy children can be ignored. */
7808  if (IS_DUMMY_REL(child_input_rel))
7809  continue;
7810 
7811  child_target = copy_pathtarget(target);
7812 
7813  /*
7814  * Copy the given "extra" structure as is and then override the
7815  * members specific to this child.
7816  */
7817  memcpy(&child_extra, extra, sizeof(child_extra));
7818 
7819  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7820  &nappinfos);
7821 
7822  child_target->exprs = (List *)
7824  (Node *) target->exprs,
7825  nappinfos, appinfos);
7826 
7827  /* Translate havingQual and targetList. */
7828  child_extra.havingQual = (Node *)
7830  extra->havingQual,
7831  nappinfos, appinfos);
7832  child_extra.targetList = (List *)
7834  (Node *) extra->targetList,
7835  nappinfos, appinfos);
7836 
7837  /*
7838  * extra->patype was the value computed for our parent rel; patype is
7839  * the value for this relation. For the child, our value is its
7840  * parent rel's value.
7841  */
7842  child_extra.patype = patype;
7843 
7844  /*
7845  * Create grouping relation to hold fully aggregated grouping and/or
7846  * aggregation paths for the child.
7847  */
7848  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7849  child_target,
7850  extra->target_parallel_safe,
7851  child_extra.havingQual);
7852 
7853  /* Create grouping paths for this child relation. */
7854  create_ordinary_grouping_paths(root, child_input_rel,
7855  child_grouped_rel,
7856  agg_costs, gd, &child_extra,
7857  &child_partially_grouped_rel);
7858 
7859  if (child_partially_grouped_rel)
7860  {
7861  partially_grouped_live_children =
7862  lappend(partially_grouped_live_children,
7863  child_partially_grouped_rel);
7864  }
7865  else
7866  partial_grouping_valid = false;
7867 
7868  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7869  {
7870  set_cheapest(child_grouped_rel);
7871  grouped_live_children = lappend(grouped_live_children,
7872  child_grouped_rel);
7873  }
7874 
7875  pfree(appinfos);
7876  }
7877 
7878  /*
7879  * Try to create append paths for partially grouped children. For full
7880  * partitionwise aggregation, we might have paths in the partial_pathlist
7881  * if parallel aggregation is possible. For partial partitionwise
7882  * aggregation, we may have paths in both pathlist and partial_pathlist.
7883  *
7884  * NB: We must have a partially grouped path for every child in order to
7885  * generate a partially grouped path for this relation.
7886  */
7887  if (partially_grouped_rel && partial_grouping_valid)
7888  {
7889  Assert(partially_grouped_live_children != NIL);
7890 
7891  add_paths_to_append_rel(root, partially_grouped_rel,
7892  partially_grouped_live_children);
7893 
7894  /*
7895  * We need call set_cheapest, since the finalization step will use the
7896  * cheapest path from the rel.
7897  */
7898  if (partially_grouped_rel->pathlist)
7899  set_cheapest(partially_grouped_rel);
7900  }
7901 
7902  /* If possible, create append paths for fully grouped children. */
7903  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7904  {
7905  Assert(grouped_live_children != NIL);
7906 
7907  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7908  }
7909 }

References add_paths_to_append_rel(), adjust_appendrel_attrs(), Assert(), bms_next_member(), copy_pathtarget(), create_ordinary_grouping_paths(), PathTarget::exprs, find_appinfos_by_relids(), GroupPathExtraData::havingQual, i, IS_DUMMY_REL, lappend(), RelOptInfo::live_parts, make_grouping_rel(), NIL, 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().

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

4457 {
4458  RelOptInfo *window_rel;
4459  ListCell *lc;
4460 
4461  /* For now, do all work in the (WINDOW, NULL) upperrel */
4462  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4463 
4464  /*
4465  * If the input relation is not parallel-safe, then the window relation
4466  * can't be parallel-safe, either. Otherwise, we need to examine the
4467  * target list and active windows for non-parallel-safe constructs.
4468  */
4469  if (input_rel->consider_parallel && output_target_parallel_safe &&
4470  is_parallel_safe(root, (Node *) activeWindows))
4471  window_rel->consider_parallel = true;
4472 
4473  /*
4474  * If the input rel belongs to a single FDW, so does the window rel.
4475  */
4476  window_rel->serverid = input_rel->serverid;
4477  window_rel->userid = input_rel->userid;
4478  window_rel->useridiscurrent = input_rel->useridiscurrent;
4479  window_rel->fdwroutine = input_rel->fdwroutine;
4480 
4481  /*
4482  * Consider computing window functions starting from the existing
4483  * cheapest-total path (which will likely require a sort) as well as any
4484  * existing paths that satisfy or partially satisfy root->window_pathkeys.
4485  */
4486  foreach(lc, input_rel->pathlist)
4487  {
4488  Path *path = (Path *) lfirst(lc);
4489  int presorted_keys;
4490 
4491  if (path == input_rel->cheapest_total_path ||
4493  &presorted_keys) ||
4494  presorted_keys > 0)
4496  window_rel,
4497  path,
4498  input_target,
4499  output_target,
4500  wflists,
4501  activeWindows);
4502  }
4503 
4504  /*
4505  * If there is an FDW that's responsible for all baserels of the query,
4506  * let it consider adding ForeignPaths.
4507  */
4508  if (window_rel->fdwroutine &&
4509  window_rel->fdwroutine->GetForeignUpperPaths)
4510  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4511  input_rel, window_rel,
4512  NULL);
4513 
4514  /* Let extensions possibly add some more paths */
4516  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4517  input_rel, window_rel, NULL);
4518 
4519  /* Now choose the best path(s) */
4520  set_cheapest(window_rel);
4521 
4522  return window_rel;
4523 }
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:670
@ UPPERREL_WINDOW
Definition: pathnodes.h:75
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:4537
List * window_pathkeys
Definition: pathnodes.h:395

References RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_one_window_path(), create_upper_paths_hook, fetch_upper_rel(), 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().

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 6489 of file planner.c.

6490 {
6491  Node *result;
6492 
6493  /*
6494  * Convert named-argument function calls, insert default arguments and
6495  * simplify constant subexprs
6496  */
6497  result = eval_const_expressions(NULL, (Node *) expr);
6498 
6499  /* Fill in opfuncid values if missing */
6500  fix_opfuncids(result);
6501 
6502  return (Expr *) result;
6503 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2171
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1748

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

◆ expression_planner_with_deps()

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

Definition at line 6516 of file planner.c.

6519 {
6520  Node *result;
6521  PlannerGlobal glob;
6522  PlannerInfo root;
6523 
6524  /* Make up dummy planner state so we can use setrefs machinery */
6525  MemSet(&glob, 0, sizeof(glob));
6526  glob.type = T_PlannerGlobal;
6527  glob.relationOids = NIL;
6528  glob.invalItems = NIL;
6529 
6530  MemSet(&root, 0, sizeof(root));
6531  root.type = T_PlannerInfo;
6532  root.glob = &glob;
6533 
6534  /*
6535  * Convert named-argument function calls, insert default arguments and
6536  * simplify constant subexprs. Collect identities of inlined functions
6537  * and elided domains, too.
6538  */
6539  result = eval_const_expressions(&root, (Node *) expr);
6540 
6541  /* Fill in opfuncid values if missing */
6542  fix_opfuncids(result);
6543 
6544  /*
6545  * Now walk the finished expression to find anything else we ought to
6546  * record as an expression dependency.
6547  */
6548  (void) extract_query_dependencies_walker(result, &root);
6549 
6550  *relationOids = glob.relationOids;
6551  *invalItems = glob.invalItems;
6552 
6553  return (Expr *) result;
6554 }
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3555
List * invalItems
Definition: pathnodes.h:132
List * relationOids
Definition: pathnodes.h:129
PlannerGlobal * glob
Definition: pathnodes.h:202

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

Referenced by GetCachedExpression().

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

Definition at line 2933 of file planner.c.

2934 {
2935  int num_sets_raw = list_length(groupingSets);
2936  int num_empty = 0;
2937  int num_sets = 0; /* distinct sets */
2938  int num_chains = 0;
2939  List *result = NIL;
2940  List **results;
2941  List **orig_sets;
2942  Bitmapset **set_masks;
2943  int *chains;
2944  short **adjacency;
2945  short *adjacency_buf;
2947  int i;
2948  int j;
2949  int j_size;
2950  ListCell *lc1 = list_head(groupingSets);
2951  ListCell *lc;
2952 
2953  /*
2954  * Start by stripping out empty sets. The algorithm doesn't require this,
2955  * but the planner currently needs all empty sets to be returned in the
2956  * first list, so we strip them here and add them back after.
2957  */
2958  while (lc1 && lfirst(lc1) == NIL)
2959  {
2960  ++num_empty;
2961  lc1 = lnext(groupingSets, lc1);
2962  }
2963 
2964  /* bail out now if it turns out that all we had were empty sets. */
2965  if (!lc1)
2966  return list_make1(groupingSets);
2967 
2968  /*----------
2969  * We don't strictly need to remove duplicate sets here, but if we don't,
2970  * they tend to become scattered through the result, which is a bit
2971  * confusing (and irritating if we ever decide to optimize them out).
2972  * So we remove them here and add them back after.
2973  *
2974  * For each non-duplicate set, we fill in the following:
2975  *
2976  * orig_sets[i] = list of the original set lists
2977  * set_masks[i] = bitmapset for testing inclusion
2978  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
2979  *
2980  * chains[i] will be the result group this set is assigned to.
2981  *
2982  * We index all of these from 1 rather than 0 because it is convenient
2983  * to leave 0 free for the NIL node in the graph algorithm.
2984  *----------
2985  */
2986  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
2987  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
2988  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
2989  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
2990 
2991  j_size = 0;
2992  j = 0;
2993  i = 1;
2994 
2995  for_each_cell(lc, groupingSets, lc1)
2996  {
2997  List *candidate = (List *) lfirst(lc);
2998  Bitmapset *candidate_set = NULL;
2999  ListCell *lc2;
3000  int dup_of = 0;
3001 
3002  foreach(lc2, candidate)
3003  {
3004  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3005  }
3006 
3007  /* we can only be a dup if we're the same length as a previous set */
3008  if (j_size == list_length(candidate))
3009  {
3010  int k;
3011 
3012  for (k = j; k < i; ++k)
3013  {
3014  if (bms_equal(set_masks[k], candidate_set))
3015  {
3016  dup_of = k;
3017  break;
3018  }
3019  }
3020  }
3021  else if (j_size < list_length(candidate))
3022  {
3023  j_size = list_length(candidate);
3024  j = i;
3025  }
3026 
3027  if (dup_of > 0)
3028  {
3029  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3030  bms_free(candidate_set);
3031  }
3032  else
3033  {
3034  int k;
3035  int n_adj = 0;
3036 
3037  orig_sets[i] = list_make1(candidate);
3038  set_masks[i] = candidate_set;
3039 
3040  /* fill in adjacency list; no need to compare equal-size sets */
3041 
3042  for (k = j - 1; k > 0; --k)
3043  {
3044  if (bms_is_subset(set_masks[k], candidate_set))
3045  adjacency_buf[++n_adj] = k;
3046  }
3047 
3048  if (n_adj > 0)
3049  {
3050  adjacency_buf[0] = n_adj;
3051  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3052  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3053  }
3054  else
3055  adjacency[i] = NULL;
3056 
3057  ++i;
3058  }
3059  }
3060 
3061  num_sets = i - 1;
3062 
3063  /*
3064  * Apply the graph matching algorithm to do the work.
3065  */
3066  state = BipartiteMatch(num_sets, num_sets, adjacency);
3067 
3068  /*
3069  * Now, the state->pair* fields have the info we need to assign sets to
3070  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3071  * pair_vu[v] = u (both will be true, but we check both so that we can do
3072  * it in one pass)
3073  */
3074  chains = palloc0((num_sets + 1) * sizeof(int));
3075 
3076  for (i = 1; i <= num_sets; ++i)
3077  {
3078  int u = state->pair_vu[i];
3079  int v = state->pair_uv[i];
3080 
3081  if (u > 0 && u < i)
3082  chains[i] = chains[u];
3083  else if (v > 0 && v < i)
3084  chains[i] = chains[v];
3085  else
3086  chains[i] = ++num_chains;
3087  }
3088 
3089  /* build result lists. */
3090  results = palloc0((num_chains + 1) * sizeof(List *));
3091 
3092  for (i = 1; i <= num_sets; ++i)
3093  {
3094  int c = chains[i];
3095 
3096  Assert(c > 0);
3097 
3098  results[c] = list_concat(results[c], orig_sets[i]);
3099  }
3100 
3101  /* push any empty sets back on the first list. */
3102  while (num_empty-- > 0)
3103  results[1] = lcons(NIL, results[1]);
3104 
3105  /* make result list */
3106  for (i = 1; i <= num_chains; ++i)
3107  result = lappend(result, results[i]);
3108 
3109  /*
3110  * Free all the things.
3111  *
3112  * (This is over-fussy for small sets but for large sets we could have
3113  * tied up a nontrivial amount of memory.)
3114  */
3116  pfree(results);
3117  pfree(chains);
3118  for (i = 1; i <= num_sets; ++i)
3119  if (adjacency[i])
3120  pfree(adjacency[i]);
3121  pfree(adjacency);
3122  pfree(adjacency_buf);
3123  pfree(orig_sets);
3124  for (i = 1; i <= num_sets; ++i)
3125  bms_free(set_masks[i]);
3126  pfree(set_masks);
3127 
3128  return result;
3129 }
void BipartiteMatchFree(BipartiteMatchState *state)
BipartiteMatchState * BipartiteMatch(int u_size, int v_size, short **adjacency)
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:97
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:363
void bms_free(Bitmapset *a)
Definition: bitmapset.c:194
int j
Definition: isn.c:74
void * palloc0(Size size)
Definition: mcxt.c:1257
char * c
Definition: regguts.h:323

References Assert(), BipartiteMatch(), BipartiteMatchFree(), bms_add_member(), bms_equal(), bms_free(), bms_is_subset(), for_each_cell, i, j, lappend(), lcons(), lfirst, lfirst_int, list_concat(), list_head(), list_length(), list_make1, lnext(), NIL, palloc(), palloc0(), and pfree().

Referenced by preprocess_grouping_sets().

◆ gather_grouping_paths()

static void gather_grouping_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 7409 of file planner.c.

7410 {
7411  ListCell *lc;
7412  Path *cheapest_partial_path;
7413 
7414  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
7415  generate_useful_gather_paths(root, rel, true);
7416 
7417  /* Try cheapest partial path + explicit Sort + Gather Merge. */
7418  cheapest_partial_path = linitial(rel->partial_pathlist);
7420  cheapest_partial_path->pathkeys))
7421  {
7422  Path *path;
7423  double total_groups;
7424 
7425  total_groups =
7426  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
7427  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
7428  root->group_pathkeys,
7429  -1.0);
7430  path = (Path *)
7432  rel,
7433  path,
7434  rel->reltarget,
7435  root->group_pathkeys,
7436  NULL,
7437  &total_groups);
7438 
7439  add_path(rel, path);
7440  }
7441 
7442  /*
7443  * Consider incremental sort on all partial paths, if enabled.
7444  *
7445  * We can also skip the entire loop when we only have a single-item
7446  * group_pathkeys because then we can't possibly have a presorted prefix
7447  * of the list without having the list be fully sorted.
7448  */
7450  return;
7451 
7452  /* also consider incremental sort on partial paths, if enabled */
7453  foreach(lc, rel->partial_pathlist)
7454  {
7455  Path *path = (Path *) lfirst(lc);
7456  bool is_sorted;
7457  int presorted_keys;
7458  double total_groups;
7459 
7460  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7461  path->pathkeys,
7462  &presorted_keys);
7463 
7464  if (is_sorted)
7465  continue;
7466 
7467  if (presorted_keys == 0)
7468  continue;
7469 
7470  path = (Path *) create_incremental_sort_path(root,
7471  rel,
7472  path,
7473  root->group_pathkeys,
7474  presorted_keys,
7475  -1.0);
7476 
7477  path = (Path *)
7479  rel,
7480  path,
7481  rel->reltarget,
7482  root->group_pathkeys,
7483  NULL,
7484  &total_groups);
7485 
7486  add_path(rel, path);
7487  }
7488 }

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

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

Definition at line 6330 of file planner.c.

6331 {
6332  Path *best_path = rel->cheapest_total_path;
6333  ListCell *l;
6334 
6335  /* If all tuples will be retrieved, just return the cheapest-total path */
6336  if (tuple_fraction <= 0.0)
6337  return best_path;
6338 
6339  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
6340  if (tuple_fraction >= 1.0 && best_path->rows > 0)
6341  tuple_fraction /= best_path->rows;
6342 
6343  foreach(l, rel->pathlist)
6344  {
6345  Path *path = (Path *) lfirst(l);
6346 
6347  if (path == rel->cheapest_total_path ||
6348  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
6349  continue;
6350 
6351  best_path = path;
6352  }
6353 
6354  return best_path;
6355 }
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117

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

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

3580 {
3581  Query *parse = root->parse;
3582  double dNumGroups;
3583 
3584  if (parse->groupClause)
3585  {
3586  List *groupExprs;
3587 
3588  if (parse->groupingSets)
3589  {
3590  /* Add up the estimates for each grouping set */
3591  ListCell *lc;
3592 
3593  Assert(gd); /* keep Coverity happy */
3594 
3595  dNumGroups = 0;
3596 
3597  foreach(lc, gd->rollups)
3598  {
3599  RollupData *rollup = lfirst_node(RollupData, lc);
3600  ListCell *lc2;
3601  ListCell *lc3;
3602 
3603  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3604  target_list);
3605 
3606  rollup->numGroups = 0.0;
3607 
3608  forboth(lc2, rollup->gsets, lc3, rollup->gsets_data)
3609  {
3610  List *gset = (List *) lfirst(lc2);
3612  double numGroups = estimate_num_groups(root,
3613  groupExprs,
3614  path_rows,
3615  &gset,
3616  NULL);
3617 
3618  gs->numGroups = numGroups;
3619  rollup->numGroups += numGroups;
3620  }
3621 
3622  dNumGroups += rollup->numGroups;
3623  }
3624 
3625  if (gd->hash_sets_idx)
3626  {
3627  ListCell *lc2;
3628 
3629  gd->dNumHashGroups = 0;
3630 
3631  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3632  target_list);
3633 
3634  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3635  {
3636  List *gset = (List *) lfirst(lc);
3638  double numGroups = estimate_num_groups(root,
3639  groupExprs,
3640  path_rows,
3641  &gset,
3642  NULL);
3643 
3644  gs->numGroups = numGroups;
3645  gd->dNumHashGroups += numGroups;
3646  }
3647 
3648  dNumGroups += gd->dNumHashGroups;
3649  }
3650  }
3651  else
3652  {
3653  /* Plain GROUP BY -- estimate based on optimized groupClause */
3655  target_list);
3656 
3657  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3658  NULL, NULL);
3659  }
3660  }
3661  else if (parse->groupingSets)
3662  {
3663  /* Empty grouping sets ... one result row for each one */
3664  dNumGroups = list_length(parse->groupingSets);
3665  }
3666  else if (parse->hasAggs || root->hasHavingQual)
3667  {
3668  /* Plain aggregation, one result row */
3669  dNumGroups = 1;
3670  }
3671  else
3672  {
3673  /* Not grouping */
3674  dNumGroups = 1;
3675  }
3676 
3677  return dNumGroups;
3678 }
List * hash_sets_idx
Definition: planner.c:104

References Assert(), grouping_sets_data::dNumHashGroups, estimate_num_groups(), forboth, get_sortgrouplist_exprs(), RollupData::groupClause, RollupData::gsets, RollupData::gsets_data, grouping_sets_data::hash_sets_idx, PlannerInfo::hasHavingQual, lfirst, lfirst_node, list_length(), GroupingSetData::numGroups, RollupData::numGroups, parse(), PlannerInfo::parse, PlannerInfo::processed_groupClause, grouping_sets_data::rollups, and grouping_sets_data::unsortable_sets.

Referenced by create_ordinary_grouping_paths(), and create_partial_grouping_paths().

◆ group_by_has_partkey()

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

Definition at line 7918 of file planner.c.

7921 {
7922  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7923  int cnt = 0;
7924  int partnatts;
7925 
7926  /* Input relation should be partitioned. */
7927  Assert(input_rel->part_scheme);
7928 
7929  /* Rule out early, if there are no partition keys present. */
7930  if (!input_rel->partexprs)
7931  return false;
7932 
7933  partnatts = input_rel->part_scheme->partnatts;
7934 
7935  for (cnt = 0; cnt < partnatts; cnt++)
7936  {
7937  List *partexprs = input_rel->partexprs[cnt];
7938  ListCell *lc;
7939  bool found = false;
7940 
7941  foreach(lc, partexprs)
7942  {
7943  Expr *partexpr = lfirst(lc);
7944 
7945  if (list_member(groupexprs, partexpr))
7946  {
7947  found = true;
7948  break;
7949  }
7950  }
7951 
7952  /*
7953  * If none of the partition key expressions match with any of the
7954  * GROUP BY expression, return false.
7955  */
7956  if (!found)
7957  return false;
7958  }
7959 
7960  return true;
7961 }
bool list_member(const List *list, const void *datum)
Definition: list.c:660

References Assert(), get_sortgrouplist_exprs(), lfirst, and list_member().

Referenced by create_ordinary_grouping_paths().

◆ grouping_planner()

static void grouping_planner ( PlannerInfo root,
double  tuple_fraction 
)
static

Definition at line 1293 of file planner.c.

1294 {
1295  Query *parse = root->parse;
1296  int64 offset_est = 0;
1297  int64 count_est = 0;
1298  double limit_tuples = -1.0;
1299  bool have_postponed_srfs = false;
1300  PathTarget *final_target;
1301  List *final_targets;
1302  List *final_targets_contain_srfs;
1303  bool final_target_parallel_safe;
1304  RelOptInfo *current_rel;
1305  RelOptInfo *final_rel;
1306  FinalPathExtraData extra;
1307  ListCell *lc;
1308 
1309  /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1310  if (parse->limitCount || parse->limitOffset)
1311  {
1312  tuple_fraction = preprocess_limit(root, tuple_fraction,
1313  &offset_est, &count_est);
1314 
1315  /*
1316  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1317  * estimate the effects of using a bounded sort.
1318  */
1319  if (count_est > 0 && offset_est >= 0)
1320  limit_tuples = (double) count_est + (double) offset_est;
1321  }
1322 
1323  /* Make tuple_fraction accessible to lower-level routines */
1324  root->tuple_fraction = tuple_fraction;
1325 
1326  if (parse->setOperations)
1327  {
1328  /*
1329  * If there's a top-level ORDER BY, assume we have to fetch all the
1330  * tuples. This might be too simplistic given all the hackery below
1331  * to possibly avoid the sort; but the odds of accurate estimates here
1332  * are pretty low anyway. XXX try to get rid of this in favor of
1333  * letting plan_set_operations generate both fast-start and
1334  * cheapest-total paths.
1335  */
1336  if (parse->sortClause)
1337  root->tuple_fraction = 0.0;
1338 
1339  /*
1340  * Construct Paths for set operations. The results will not need any
1341  * work except perhaps a top-level sort and/or LIMIT. Note that any
1342  * special work for recursive unions is the responsibility of
1343  * plan_set_operations.
1344  */
1345  current_rel = plan_set_operations(root);
1346 
1347  /*
1348  * We should not need to call preprocess_targetlist, since we must be
1349  * in a SELECT query node. Instead, use the processed_tlist returned
1350  * by plan_set_operations (since this tells whether it returned any
1351  * resjunk columns!), and transfer any sort key information from the
1352  * original tlist.
1353  */
1354  Assert(parse->commandType == CMD_SELECT);
1355 
1356  /* for safety, copy processed_tlist instead of modifying in-place */
1357  root->processed_tlist =
1359  parse->targetList);
1360 
1361  /* Also extract the PathTarget form of the setop result tlist */
1362  final_target = current_rel->cheapest_total_path->pathtarget;
1363 
1364  /* And check whether it's parallel safe */
1365  final_target_parallel_safe =
1366  is_parallel_safe(root, (Node *) final_target->exprs);
1367 
1368  /* The setop result tlist couldn't contain any SRFs */
1369  Assert(!parse->hasTargetSRFs);
1370  final_targets = final_targets_contain_srfs = NIL;
1371 
1372  /*
1373  * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1374  * checked already, but let's make sure).
1375  */
1376  if (parse->rowMarks)
1377  ereport(ERROR,
1378  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1379  /*------
1380  translator: %s is a SQL row locking clause such as FOR UPDATE */
1381  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1383  parse->rowMarks)->strength))));
1384 
1385  /*
1386  * Calculate pathkeys that represent result ordering requirements
1387  */
1388  Assert(parse->distinctClause == NIL);
1390  parse->sortClause,
1391  root->processed_tlist);
1392  }
1393  else
1394  {
1395  /* No set operations, do regular planning */
1396  PathTarget *sort_input_target;
1397  List *sort_input_targets;
1398  List *sort_input_targets_contain_srfs;
1399  bool sort_input_target_parallel_safe;
1400  PathTarget *grouping_target;
1401  List *grouping_targets;
1402  List *grouping_targets_contain_srfs;
1403  bool grouping_target_parallel_safe;
1404  PathTarget *scanjoin_target;
1405  List *scanjoin_targets;
1406  List *scanjoin_targets_contain_srfs;
1407  bool scanjoin_target_parallel_safe;
1408  bool scanjoin_target_same_exprs;
1409  bool have_grouping;
1410  WindowFuncLists *wflists = NULL;
1411  List *activeWindows = NIL;
1412  grouping_sets_data *gset_data = NULL;
1413  standard_qp_extra qp_extra;
1414 
1415  /* A recursive query should always have setOperations */
1416  Assert(!root->hasRecursion);
1417 
1418  /* Preprocess grouping sets and GROUP BY clause, if any */
1419  if (parse->groupingSets)
1420  {
1421  gset_data = preprocess_grouping_sets(root);
1422  }
1423  else if (parse->groupClause)
1424  {
1425  /* Preprocess regular GROUP BY clause, if any */
1427  /* Remove any redundant GROUP BY columns */
1429  }
1430 
1431  /*
1432  * Preprocess targetlist. Note that much of the remaining planning
1433  * work will be done with the PathTarget representation of tlists, but
1434  * we must also maintain the full representation of the final tlist so
1435  * that we can transfer its decoration (resnames etc) to the topmost
1436  * tlist of the finished Plan. This is kept in processed_tlist.
1437  */
1438  preprocess_targetlist(root);
1439 
1440  /*
1441  * Mark all the aggregates with resolved aggtranstypes, and detect
1442  * aggregates that are duplicates or can share transition state. We
1443  * must do this before slicing and dicing the tlist into various
1444  * pathtargets, else some copies of the Aggref nodes might escape
1445  * being marked.
1446  */
1447  if (parse->hasAggs)
1448  {
1449  preprocess_aggrefs(root, (Node *) root->processed_tlist);
1450  preprocess_aggrefs(root, (Node *) parse->havingQual);
1451  }
1452 
1453  /*
1454  * Locate any window functions in the tlist. (We don't need to look
1455  * anywhere else, since expressions used in ORDER BY will be in there
1456  * too.) Note that they could all have been eliminated by constant
1457  * folding, in which case we don't need to do any more work.
1458  */
1459  if (parse->hasWindowFuncs)
1460  {
1461  wflists = find_window_functions((Node *) root->processed_tlist,
1462  list_length(parse->windowClause));
1463  if (wflists->numWindowFuncs > 0)
1464  {
1465  /*
1466  * See if any modifications can be made to each WindowClause
1467  * to allow the executor to execute the WindowFuncs more
1468  * quickly.
1469  */
1470  optimize_window_clauses(root, wflists);
1471 
1472  activeWindows = select_active_windows(root, wflists);
1473  }
1474  else
1475  parse->hasWindowFuncs = false;
1476  }
1477 
1478  /*
1479  * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1480  * adding logic between here and the query_planner() call. Anything
1481  * that is needed in MIN/MAX-optimizable cases will have to be
1482  * duplicated in planagg.c.
1483  */
1484  if (parse->hasAggs)
1486 
1487  /*
1488  * Figure out whether there's a hard limit on the number of rows that
1489  * query_planner's result subplan needs to return. Even if we know a
1490  * hard limit overall, it doesn't apply if the query has any
1491  * grouping/aggregation operations, or SRFs in the tlist.
1492  */
1493  if (parse->groupClause ||
1494  parse->groupingSets ||
1495  parse->distinctClause ||
1496  parse->hasAggs ||
1497  parse->hasWindowFuncs ||
1498  parse->hasTargetSRFs ||
1499  root->hasHavingQual)
1500  root->limit_tuples = -1.0;
1501  else
1502  root->limit_tuples = limit_tuples;
1503 
1504  /* Set up data needed by standard_qp_callback */
1505  qp_extra.activeWindows = activeWindows;
1506  qp_extra.gset_data = gset_data;
1507 
1508  /*
1509  * Generate the best unsorted and presorted paths for the scan/join
1510  * portion of this Query, ie the processing represented by the
1511  * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1512  * We also generate (in standard_qp_callback) pathkey representations
1513  * of the query's sort clause, distinct clause, etc.
1514  */
1515  current_rel = query_planner(root, standard_qp_callback, &qp_extra);
1516 
1517  /*
1518  * Convert the query's result tlist into PathTarget format.
1519  *
1520  * Note: this cannot be done before query_planner() has performed
1521  * appendrel expansion, because that might add resjunk entries to
1522  * root->processed_tlist. Waiting till afterwards is also helpful
1523  * because the target width estimates can use per-Var width numbers
1524  * that were obtained within query_planner().
1525  */
1526  final_target = create_pathtarget(root, root->processed_tlist);
1527  final_target_parallel_safe =
1528  is_parallel_safe(root, (Node *) final_target->exprs);
1529 
1530  /*
1531  * If ORDER BY was given, consider whether we should use a post-sort
1532  * projection, and compute the adjusted target for preceding steps if
1533  * so.
1534  */
1535  if (parse->sortClause)
1536  {
1537  sort_input_target = make_sort_input_target(root,
1538  final_target,
1539  &have_postponed_srfs);
1540  sort_input_target_parallel_safe =
1541  is_parallel_safe(root, (Node *) sort_input_target->exprs);
1542  }
1543  else
1544  {
1545  sort_input_target = final_target;
1546  sort_input_target_parallel_safe = final_target_parallel_safe;
1547  }
1548 
1549  /*
1550  * If we have window functions to deal with, the output from any
1551  * grouping step needs to be what the window functions want;
1552  * otherwise, it should be sort_input_target.
1553  */
1554  if (activeWindows)
1555  {
1556  grouping_target = make_window_input_target(root,
1557  final_target,
1558  activeWindows);
1559  grouping_target_parallel_safe =
1560  is_parallel_safe(root, (Node *) grouping_target->exprs);
1561  }
1562  else
1563  {
1564  grouping_target = sort_input_target;
1565  grouping_target_parallel_safe = sort_input_target_parallel_safe;
1566  }
1567 
1568  /*
1569  * If we have grouping or aggregation to do, the topmost scan/join
1570  * plan node must emit what the grouping step wants; otherwise, it
1571  * should emit grouping_target.
1572  */
1573  have_grouping = (parse->groupClause || parse->groupingSets ||
1574  parse->hasAggs || root->hasHavingQual);
1575  if (have_grouping)
1576  {
1577  scanjoin_target = make_group_input_target(root, final_target);
1578  scanjoin_target_parallel_safe =
1579  is_parallel_safe(root, (Node *) scanjoin_target->exprs);
1580  }
1581  else
1582  {
1583  scanjoin_target = grouping_target;
1584  scanjoin_target_parallel_safe = grouping_target_parallel_safe;
1585  }
1586 
1587  /*
1588  * If there are any SRFs in the targetlist, we must separate each of
1589  * these PathTargets into SRF-computing and SRF-free targets. Replace
1590  * each of the named targets with a SRF-free version, and remember the
1591  * list of additional projection steps we need to add afterwards.
1592  */
1593  if (parse->hasTargetSRFs)
1594  {
1595  /* final_target doesn't recompute any SRFs in sort_input_target */
1596  split_pathtarget_at_srfs(root, final_target, sort_input_target,
1597  &final_targets,
1598  &final_targets_contain_srfs);
1599  final_target = linitial_node(PathTarget, final_targets);
1600  Assert(!linitial_int(final_targets_contain_srfs));
1601  /* likewise for sort_input_target vs. grouping_target */
1602  split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
1603  &sort_input_targets,
1604  &sort_input_targets_contain_srfs);
1605  sort_input_target = linitial_node(PathTarget, sort_input_targets);
1606  Assert(!linitial_int(sort_input_targets_contain_srfs));
1607  /* likewise for grouping_target vs. scanjoin_target */
1608  split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
1609  &grouping_targets,
1610  &grouping_targets_contain_srfs);
1611  grouping_target = linitial_node(PathTarget, grouping_targets);
1612  Assert(!linitial_int(grouping_targets_contain_srfs));
1613  /* scanjoin_target will not have any SRFs precomputed for it */
1614  split_pathtarget_at_srfs(root, scanjoin_target, NULL,
1615  &scanjoin_targets,
1616  &scanjoin_targets_contain_srfs);
1617  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
1618  Assert(!linitial_int(scanjoin_targets_contain_srfs));
1619  }
1620  else
1621  {
1622  /* initialize lists; for most of these, dummy values are OK */
1623  final_targets = final_targets_contain_srfs = NIL;
1624  sort_input_targets = sort_input_targets_contain_srfs = NIL;
1625  grouping_targets = grouping_targets_contain_srfs = NIL;
1626  scanjoin_targets = list_make1(scanjoin_target);
1627  scanjoin_targets_contain_srfs = NIL;
1628  }
1629 
1630  /* Apply scan/join target. */
1631  scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
1632  && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
1633  apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
1634  scanjoin_targets_contain_srfs,
1635  scanjoin_target_parallel_safe,
1636  scanjoin_target_same_exprs);
1637 
1638  /*
1639  * Save the various upper-rel PathTargets we just computed into
1640  * root->upper_targets[]. The core code doesn't use this, but it
1641  * provides a convenient place for extensions to get at the info. For
1642  * consistency, we save all the intermediate targets, even though some
1643  * of the corresponding upperrels might not be needed for this query.
1644  */
1645  root->upper_targets[UPPERREL_FINAL] = final_target;
1646  root->upper_targets[UPPERREL_ORDERED] = final_target;
1647  root->upper_targets[UPPERREL_PARTIAL_DISTINCT] = sort_input_target;
1648  root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
1649  root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
1650  root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
1651 
1652  /*
1653  * If we have grouping and/or aggregation, consider ways to implement
1654  * that. We build a new upperrel representing the output of this
1655  * phase.
1656  */
1657  if (have_grouping)
1658  {
1659  current_rel = create_grouping_paths(root,
1660  current_rel,
1661  grouping_target,
1662  grouping_target_parallel_safe,
1663  gset_data);
1664  /* Fix things up if grouping_target contains SRFs */
1665  if (parse->hasTargetSRFs)
1666  adjust_paths_for_srfs(root, current_rel,
1667  grouping_targets,
1668  grouping_targets_contain_srfs);
1669  }
1670 
1671  /*
1672  * If we have window functions, consider ways to implement those. We
1673  * build a new upperrel representing the output of this phase.
1674  */
1675  if (activeWindows)
1676  {
1677  current_rel = create_window_paths(root,
1678  current_rel,
1679  grouping_target,
1680  sort_input_target,
1681  sort_input_target_parallel_safe,
1682  wflists,
1683  activeWindows);
1684  /* Fix things up if sort_input_target contains SRFs */
1685  if (parse->hasTargetSRFs)
1686  adjust_paths_for_srfs(root, current_rel,
1687  sort_input_targets,
1688  sort_input_targets_contain_srfs);
1689  }
1690 
1691  /*
1692  * If there is a DISTINCT clause, consider ways to implement that. We
1693  * build a new upperrel representing the output of this phase.
1694  */
1695  if (parse->distinctClause)
1696  {
1697  current_rel = create_distinct_paths(root,
1698  current_rel);
1699  }
1700  } /* end of if (setOperations) */
1701 
1702  /*
1703  * If ORDER BY was given, consider ways to implement that, and generate a
1704  * new upperrel containing only paths that emit the correct ordering and
1705  * project the correct final_target. We can apply the original
1706  * limit_tuples limit in sort costing here, but only if there are no
1707  * postponed SRFs.
1708  */
1709  if (parse->sortClause)
1710  {
1711  current_rel = create_ordered_paths(root,
1712  current_rel,
1713  final_target,
1714  final_target_parallel_safe,
1715  have_postponed_srfs ? -1.0 :
1716  limit_tuples);
1717  /* Fix things up if final_target contains SRFs */
1718  if (parse->hasTargetSRFs)
1719  adjust_paths_for_srfs(root, current_rel,
1720  final_targets,
1721  final_targets_contain_srfs);
1722  }
1723 
1724  /*
1725  * Now we are prepared to build the final-output upperrel.
1726  */
1727  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1728 
1729  /*
1730  * If the input rel is marked consider_parallel and there's nothing that's
1731  * not parallel-safe in the LIMIT clause, then the final_rel can be marked
1732  * consider_parallel as well. Note that if the query has rowMarks or is
1733  * not a SELECT, consider_parallel will be false for every relation in the
1734  * query.
1735  */
1736  if (current_rel->consider_parallel &&
1737  is_parallel_safe(root, parse->limitOffset) &&
1738  is_parallel_safe(root, parse->limitCount))
1739  final_rel->consider_parallel = true;
1740 
1741  /*
1742  * If the current_rel belongs to a single FDW, so does the final_rel.
1743  */
1744  final_rel->serverid = current_rel->serverid;
1745  final_rel->userid = current_rel->userid;
1746  final_rel->useridiscurrent = current_rel->useridiscurrent;
1747  final_rel->fdwroutine = current_rel->fdwroutine;
1748 
1749  /*
1750  * Generate paths for the final_rel. Insert all surviving paths, with
1751  * LockRows, Limit, and/or ModifyTable steps added if needed.
1752  */
1753  foreach(lc, current_rel->pathlist)
1754  {
1755  Path *path = (Path *) lfirst(lc);
1756 
1757  /*
1758  * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
1759  * (Note: we intentionally test parse->rowMarks not root->rowMarks
1760  * here. If there are only non-locking rowmarks, they should be
1761  * handled by the ModifyTable node instead. However, root->rowMarks
1762  * is what goes into the LockRows node.)
1763  */
1764  if (parse->rowMarks)
1765  {
1766  path = (Path *) create_lockrows_path(root, final_rel, path,
1767  root->rowMarks,
1769  }
1770 
1771  /*
1772  * If there is a LIMIT/OFFSET clause, add the LIMIT node.
1773  */
1774  if (limit_needed(parse))
1775  {
1776  path = (Path *) create_limit_path(root, final_rel, path,
1777  parse->limitOffset,
1778  parse->limitCount,
1779  parse->limitOption,
1780  offset_est, count_est);
1781  }
1782 
1783  /*
1784  * If this is an INSERT/UPDATE/DELETE/MERGE, add the ModifyTable node.
1785  */
1786  if (parse->commandType != CMD_SELECT)
1787  {
1788  Index rootRelation;
1789  List *resultRelations = NIL;
1790  List *updateColnosLists = NIL;
1791  List *withCheckOptionLists = NIL;
1792  List *returningLists = NIL;
1793  List *mergeActionLists = NIL;
1794  List *rowMarks;
1795 
1797  {
1798  /* Inherited UPDATE/DELETE/MERGE */
1799  RelOptInfo *top_result_rel = find_base_rel(root,
1800  parse->resultRelation);
1801  int resultRelation = -1;
1802 
1803  /* Add only leaf children to ModifyTable. */
1804  while ((resultRelation = bms_next_member(root->leaf_result_relids,
1805  resultRelation)) >= 0)
1806  {
1807  RelOptInfo *this_result_rel = find_base_rel(root,
1808  resultRelation);
1809 
1810  /*
1811  * Also exclude any leaf rels that have turned dummy since
1812  * being added to the list, for example, by being excluded
1813  * by constraint exclusion.
1814  */
1815  if (IS_DUMMY_REL(this_result_rel))
1816  continue;
1817 
1818  /* Build per-target-rel lists needed by ModifyTable */
1819  resultRelations = lappend_int(resultRelations,
1820  resultRelation);
1821  if (parse->commandType == CMD_UPDATE)
1822  {
1823  List *update_colnos = root->update_colnos;
1824 
1825  if (this_result_rel != top_result_rel)
1826  update_colnos =
1828  update_colnos,
1829  this_result_rel->relid,
1830  top_result_rel->relid);
1831  updateColnosLists = lappend(updateColnosLists,
1832  update_colnos);
1833  }
1834  if (parse->withCheckOptions)
1835  {
1836  List *withCheckOptions = parse->withCheckOptions;
1837 
1838  if (this_result_rel != top_result_rel)
1839  withCheckOptions = (List *)
1841  (Node *) withCheckOptions,
1842  this_result_rel,
1843  top_result_rel);
1844  withCheckOptionLists = lappend(withCheckOptionLists,
1845  withCheckOptions);
1846  }
1847  if (parse->returningList)
1848  {
1849  List *returningList = parse->returningList;
1850 
1851  if (this_result_rel != top_result_rel)
1852  returningList = (List *)
1854  (Node *) returningList,
1855  this_result_rel,
1856  top_result_rel);
1857  returningLists = lappend(returningLists,
1858  returningList);
1859  }
1860  if (parse->mergeActionList)
1861  {
1862  ListCell *l;
1863  List *mergeActionList = NIL;
1864 
1865  /*
1866  * Copy MergeActions and translate stuff that
1867  * references attribute numbers.
1868  */
1869  foreach(l, parse->mergeActionList)
1870  {
1871  MergeAction *action = lfirst(l),
1872  *leaf_action = copyObject(action);
1873 
1874  leaf_action->qual =
1876  (Node *) action->qual,
1877  this_result_rel,
1878  top_result_rel);
1879  leaf_action->targetList = (List *)
1881  (Node *) action->targetList,
1882  this_result_rel,
1883  top_result_rel);
1884  if (leaf_action->commandType == CMD_UPDATE)
1885  leaf_action->updateColnos =
1887  action->updateColnos,
1888  this_result_rel->relid,
1889  top_result_rel->relid);
1890  mergeActionList = lappend(mergeActionList,
1891  leaf_action);
1892  }
1893 
1894  mergeActionLists = lappend(mergeActionLists,
1895  mergeActionList);
1896  }
1897  }
1898 
1899  if (resultRelations == NIL)
1900  {
1901  /*
1902  * We managed to exclude every child rel, so generate a
1903  * dummy one-relation plan using info for the top target
1904  * rel (even though that may not be a leaf target).
1905  * Although it's clear that no data will be updated or
1906  * deleted, we still need to have a ModifyTable node so
1907  * that any statement triggers will be executed. (This
1908  * could be cleaner if we fixed nodeModifyTable.c to allow
1909  * zero target relations, but that probably wouldn't be a
1910  * net win.)
1911  */
1912  resultRelations = list_make1_int(parse->resultRelation);
1913  if (parse->commandType == CMD_UPDATE)
1914  updateColnosLists = list_make1(root->update_colnos);
1915  if (parse->withCheckOptions)
1916  withCheckOptionLists = list_make1(parse->withCheckOptions);
1917  if (parse->returningList)
1918  returningLists = list_make1(parse->returningList);
1919  if (parse->mergeActionList)
1920  mergeActionLists = list_make1(parse->mergeActionList);
1921  }
1922  }
1923  else
1924  {
1925  /* Single-relation INSERT/UPDATE/DELETE/MERGE. */
1926  resultRelations = list_make1_int(parse->resultRelation);
1927  if (parse->commandType == CMD_UPDATE)
1928  updateColnosLists = list_make1(root->update_colnos);
1929  if (parse->withCheckOptions)
1930  withCheckOptionLists = list_make1(parse->withCheckOptions);
1931  if (parse->returningList)
1932  returningLists = list_make1(parse->returningList);
1933  if (parse->mergeActionList)
1934  mergeActionLists = list_make1(parse->mergeActionList);
1935  }
1936 
1937  /*
1938  * If target is a partition root table, we need to mark the
1939  * ModifyTable node appropriately for that.
1940  */
1941  if (rt_fetch(parse->resultRelation, parse->rtable)->relkind ==
1942  RELKIND_PARTITIONED_TABLE)
1943  rootRelation = parse->resultRelation;
1944  else
1945  rootRelation = 0;
1946 
1947  /*
1948  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
1949  * will have dealt with fetching non-locked marked rows, else we
1950  * need to have ModifyTable do that.
1951  */
1952  if (parse->rowMarks)
1953  rowMarks = NIL;
1954  else
1955  rowMarks = root->rowMarks;
1956 
1957  path = (Path *)
1958  create_modifytable_path(root, final_rel,
1959  path,
1960  parse->commandType,
1961  parse->canSetTag,
1962  parse->resultRelation,
1963  rootRelation,
1964  root->partColsUpdated,
1965  resultRelations,
1966  updateColnosLists,
1967  withCheckOptionLists,
1968  returningLists,
1969  rowMarks,
1970  parse->onConflict,
1971  mergeActionLists,
1973  }
1974 
1975  /* And shove it into final_rel */
1976  add_path(final_rel, path);
1977  }
1978 
1979  /*
1980  * Generate partial paths for final_rel, too, if outer query levels might
1981  * be able to make use of them.
1982  */
1983  if (final_rel->consider_parallel && root->query_level > 1 &&
1984  !limit_needed(parse))
1985  {
1986  Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
1987  foreach(lc, current_rel->partial_pathlist)
1988  {
1989  Path *partial_path = (Path *) lfirst(lc);
1990 
1991  add_partial_path(final_rel, partial_path);
1992  }
1993  }
1994 
1995  extra.limit_needed = limit_needed(parse);
1996  extra.limit_tuples = limit_tuples;
1997  extra.count_est = count_est;
1998  extra.offset_est = offset_est;
1999 
2000  /*
2001  * If there is an FDW that's responsible for all baserels of the query,
2002  * let it consider adding ForeignPaths.
2003  */
2004  if (final_rel->fdwroutine &&
2005  final_rel->fdwroutine->GetForeignUpperPaths)
2006  final_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_FINAL,
2007  current_rel, final_rel,
2008  &extra);
2009 
2010  /* Let extensions possibly add some more paths */
2012  (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2013  current_rel, final_rel, &extra);
2014 
2015  /* Note: currently, we leave it to callers to do set_cheapest() */
2016 }
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, RelOptInfo *childrel, RelOptInfo *parentrel)
Definition: appendinfo.c:521
List * adjust_inherited_attnums_multilevel(PlannerInfo *root, List *attnums, Index child_relid, Index top_parent_relid)
Definition: appendinfo.c:662
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:712
@ BMS_MULTIPLE
Definition: bitmapset.h:73
unsigned int Index
Definition: c.h:603
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition: clauses.c:229
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
List * lappend_int(List *list, int datum)
Definition: list.c:356
#define copyObject(obj)
Definition: nodes.h:244
@ CMD_UPDATE
Definition: nodes.h:277
@ CMD_SELECT
Definition: nodes.h:276
int assign_special_exec_param(PlannerInfo *root)
Definition: paramassign.c:612
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3197
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3602
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, CmdType operation, bool canSetTag, Index nominalRelation, Index rootRelation, bool partColsUpdated, List *resultRelations, List *updateColnosLists, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, List *mergeActionLists, int epqParam)
Definition: pathnode.c:3664
@ UPPERREL_FINAL
Definition: pathnodes.h:79
#define list_make1_int(x1)
Definition: pg_list.h:227
void preprocess_minmax_aggregates(PlannerInfo *root)
Definition: planagg.c:73
RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra)
Definition: planmain.c:55
static List * postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
Definition: planner.c:5579
static void remove_useless_groupby_columns(PlannerInfo *root)
Definition: planner.c:2665
static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
Definition: planner.c:2421
static PathTarget * make_window_input_target(PlannerInfo *root, PathTarget *final_target, List *activeWindows)
Definition: planner.c:5913
static RelOptInfo * create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel)
Definition: planner.c:4667
static void optimize_window_clauses(PlannerInfo *root, WindowFuncLists *wflists)
Definition: planner.c:5616
static PathTarget * make_sort_input_target(PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
Definition: planner.c:6159
static grouping_sets_data * preprocess_grouping_sets(PlannerInfo *root)
Definition: planner.c:2025
static PathTarget * make_group_input_target(PlannerInfo *root, PathTarget *final_target)
Definition: planner.c:5353
static List * select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
Definition: planner.c:5756
bool limit_needed(Query *parse)
Definition: planner.c:2606
static RelOptInfo * create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
Definition: planner.c:5107
static RelOptInfo * create_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, grouping_sets_data *gd)
Definition: planner.c:3698
static void standard_qp_callback(PlannerInfo *root, void *extra)
Definition: planner.c:3419
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:4450
void preprocess_aggrefs(PlannerInfo *root, Node *clause)
Definition: prepagg.c:111
void preprocess_targetlist(PlannerInfo *root)
Definition: preptlist.c:62
RelOptInfo * plan_set_operations(PlannerInfo *root)
Definition: prepunion.c:104
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:405
Cardinality limit_tuples
Definition: pathnodes.h:3275
bool partColsUpdated
Definition: pathnodes.h:546
bool hasRecursion
Definition: pathnodes.h:501
Index query_level
Definition: pathnodes.h:205
List * rowMarks
Definition: pathnodes.h:368
Cardinality limit_tuples
Definition: pathnodes.h:480
Selectivity tuple_fraction
Definition: pathnodes.h:478
List * update_colnos
Definition: pathnodes.h:461
Relids all_result_relids
Definition: pathnodes.h:351
Relids leaf_result_relids
Definition: pathnodes.h:353
Index relid
Definition: pathnodes.h:903
int numWindowFuncs
Definition: clauses.h:21
List * activeWindows
Definition: planner.c:127
grouping_sets_data * gset_data
Definition: planner.c:128
void split_pathtarget_at_srfs(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition: tlist.c:881
#define create_pathtarget(root, tlist)
Definition: tlist.h:53

References generate_unaccent_rules::action, standard_qp_extra::activeWindows, add_partial_path(), add_path(), adjust_appendrel_attrs_multilevel(), adjust_inherited_attnums_multilevel(), adjust_paths_for_srfs(), PlannerInfo::all_result_relids, apply_scanjoin_target_to_paths(), Assert(), assign_special_exec_param(), bms_membership(), BMS_MULTIPLE, bms_next_member(), RelOptInfo::cheapest_total_path, CMD_SELECT, CMD_UPDATE, 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(), equal(), ereport, errcode(), errmsg(), ERROR, PathTarget::exprs, fetch_upper_rel(), find_base_rel(), find_window_functions(), standard_qp_extra::gset_data, PlannerInfo::hasHavingQual, PlannerInfo::hasRecursion, IS_DUMMY_REL, is_parallel_safe(), lappend(), lappend_int(), LCS_asString(), PlannerInfo::leaf_result_relids, lfirst, limit_needed(), FinalPathExtraData::limit_needed, PlannerInfo::limit_tuples, FinalPathExtraData::limit_tuples, 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, optimize_window_clauses(), parse(), PlannerInfo::parse, PlannerInfo::partColsUpdated, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, plan_set_operations(), postprocess_setop_tlist(), preprocess_aggrefs(), preprocess_groupclause(), preprocess_grouping_sets(), preprocess_limit(), preprocess_minmax_aggregates(), preprocess_targetlist(), PlannerInfo::processed_groupClause, PlannerInfo::processed_tlist, PlannerInfo::query_level, query_planner(), RelOptInfo::relid, RelOptInfo::reltarget, remove_useless_groupby_columns(), PlannerInfo::rowMarks, rt_fetch, select_active_windows(), RelOptInfo::serverid, PlannerInfo::sort_pathkeys, split_pathtarget_at_srfs(), standard_qp_callback(), PlannerInfo::tuple_fraction, PlannerInfo::update_colnos, UPPERREL_DISTINCT, UPPERREL_FINAL, UPPERREL_GROUP_AGG, UPPERREL_ORDERED, UPPERREL_PARTIAL_DISTINCT, UPPERREL_WINDOW, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by subquery_planner().

◆ has_volatile_pathkey()

static bool has_volatile_pathkey ( List keys)
static

Definition at line 3193 of file planner.c.

3194 {
3195  ListCell *lc;
3196 
3197  foreach(lc, keys)
3198  {
3199  PathKey *pathkey = lfirst_node(PathKey, lc);
3200 
3201  if (pathkey->pk_eclass->ec_has_volatile)
3202  return true;
3203  }
3204 
3205  return false;
3206 }

References lfirst_node.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ is_degenerate_grouping()

static bool is_degenerate_grouping ( PlannerInfo root)
static

Definition at line 3864 of file planner.c.

3865 {
3866  Query *parse = root->parse;
3867 
3868  return (root->hasHavingQual || parse->groupingSets) &&
3869  !parse->hasAggs && parse->groupClause == NIL;
3870 }

References PlannerInfo::hasHavingQual, NIL, parse(), and PlannerInfo::parse.

Referenced by create_grouping_paths().

◆ limit_needed()

bool limit_needed ( Query parse)

Definition at line 2606 of file planner.c.

2607 {
2608  Node *node;
2609 
2610  node = parse->limitCount;
2611  if (node)
2612  {
2613  if (IsA(node, Const))
2614  {
2615  /* NULL indicates LIMIT ALL, ie, no limit */
2616  if (!((Const *) node)->constisnull)
2617  return true; /* LIMIT with a constant value */
2618  }
2619  else
2620  return true; /* non-constant LIMIT */
2621  }
2622 
2623  node = parse->limitOffset;
2624  if (node)
2625  {
2626  if (IsA(node, Const))
2627  {
2628  /* Treat NULL as no offset; the executor would too */
2629  if (!((Const *) node)->constisnull)
2630  {
2631  int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2632 
2633  if (offset != 0)
2634  return true; /* OFFSET with a nonzero value */
2635  }
2636  }
2637  else
2638  return true; /* non-constant OFFSET */
2639  }
2640 
2641  return false; /* don't need a Limit plan node */
2642 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:385

References DatumGetInt64(), IsA, and parse().

Referenced by grouping_planner(), and set_rel_consider_parallel().

◆ make_group_input_target()

static PathTarget * make_group_input_target ( PlannerInfo root,
PathTarget final_target 
)
static

Definition at line 5353 of file planner.c.

5354 {
5355  Query *parse = root->parse;
5356  PathTarget *input_target;
5357  List *non_group_cols;
5358  List *non_group_vars;
5359  int i;
5360  ListCell *lc;
5361 
5362  /*
5363  * We must build a target containing all grouping columns, plus any other
5364  * Vars mentioned in the query's targetlist and HAVING qual.
5365  */
5366  input_target = create_empty_pathtarget();
5367  non_group_cols = NIL;
5368 
5369  i = 0;
5370  foreach(lc, final_target->exprs)
5371  {
5372  Expr *expr = (Expr *) lfirst(lc);
5373  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5374 
5375  if (sgref && root->processed_groupClause &&
5377  root->processed_groupClause) != NULL)
5378  {
5379  /*
5380  * It's a grouping column, so add it to the input target as-is.
5381  */
5382  add_column_to_pathtarget(input_target, expr, sgref);
5383  }
5384  else
5385  {
5386  /*
5387  * Non-grouping column, so just remember the expression for later
5388  * call to pull_var_clause.
5389  */
5390  non_group_cols = lappend(non_group_cols, expr);
5391  }
5392 
5393  i++;
5394  }
5395 
5396  /*
5397  * If there's a HAVING clause, we'll need the Vars it uses, too.
5398  */
5399  if (parse->havingQual)
5400  non_group_cols = lappend(non_group_cols, parse->havingQual);
5401 
5402  /*
5403  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5404  * add them to the input target if not already present. (A Var used
5405  * directly as a GROUP BY item will be present already.) Note this
5406  * includes Vars used in resjunk items, so we are covering the needs of
5407  * ORDER BY and window specifications. Vars used within Aggrefs and
5408  * WindowFuncs will be pulled out here, too.
5409  */
5410  non_group_vars = pull_var_clause((Node *) non_group_cols,
5414  add_new_columns_to_pathtarget(input_target, non_group_vars);
5415 
5416  /* clean up cruft */
5417  list_free(non_group_vars);
5418  list_free(non_group_cols);
5419 
5420  /* XXX this causes some redundant cost calculation ... */
5421  return set_pathtarget_cost_width(root, input_target);
5422 }
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:6259
void list_free(List *list)
Definition: list.c:1545
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:184
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:186
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:187
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1517
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:443
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:752
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:681
List * pull_var_clause(Node *node, int flags)
Definition: var.c:607

References add_column_to_pathtarget(), add_new_columns_to_pathtarget(), create_empty_pathtarget(), PathTarget::exprs, get_pathtarget_sortgroupref, get_sortgroupref_clause_noerr(), i, lappend(), lfirst, list_free(), NIL, parse(), PlannerInfo::parse, PlannerInfo::processed_groupClause, pull_var_clause(), PVC_INCLUDE_PLACEHOLDERS, PVC_RECURSE_AGGREGATES, PVC_RECURSE_WINDOWFUNCS, and set_pathtarget_cost_width().

Referenced by grouping_planner().

◆ make_grouping_rel()

static RelOptInfo * make_grouping_rel ( PlannerInfo root,
RelOptInfo input_rel,
PathTarget target,
bool  target_parallel_safe,
Node havingQual 
)
static

Definition at line 3811 of file planner.c.

3814 {
3815  RelOptInfo *grouped_rel;
3816 
3817  if (IS_OTHER_REL(input_rel))
3818  {
3819  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG,
3820  input_rel->relids);
3821  grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
3822  }
3823  else
3824  {
3825  /*
3826  * By tradition, the relids set for the main grouping relation is
3827  * NULL. (This could be changed, but might require adjustments
3828  * elsewhere.)
3829  */
3830  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
3831  }
3832 
3833  /* Set target. */
3834  grouped_rel->reltarget = target;
3835 
3836  /*
3837  * If the input relation is not parallel-safe, then the grouped relation
3838  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
3839  * target list and HAVING quals are parallel-safe.
3840  */
3841  if (input_rel->consider_parallel && target_parallel_safe &&
3842  is_parallel_safe(root, (Node *) havingQual))
3843  grouped_rel->consider_parallel = true;
3844 
3845  /*
3846  * If the input rel belongs to a single FDW, so does the grouped rel.
3847  */
3848  grouped_rel->serverid = input_rel->serverid;
3849  grouped_rel->userid = input_rel->userid;
3850  grouped_rel->useridiscurrent = input_rel->useridiscurrent;
3851  grouped_rel->fdwroutine = input_rel->fdwroutine;
3852 
3853  return grouped_rel;
3854 }
@ RELOPT_OTHER_UPPER_REL
Definition: pathnodes.h:817

References RelOptInfo::consider_parallel, fetch_upper_rel(), IS_OTHER_REL, is_parallel_safe(), RelOptInfo::relids, RELOPT_OTHER_UPPER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, RelOptInfo::serverid, UPPERREL_GROUP_AGG, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by create_grouping_paths(), and create_partitionwise_grouping_paths().

◆ make_partial_grouping_target()

static PathTarget * make_partial_grouping_target ( PlannerInfo root,
PathTarget grouping_target,
Node havingQual 
)
static

Definition at line 5441 of file planner.c.

5444 {
5445  PathTarget *partial_target;
5446  List *non_group_cols;
5447  List *non_group_exprs;
5448  int i;
5449  ListCell *lc;
5450 
5451  partial_target = create_empty_pathtarget();
5452  non_group_cols = NIL;
5453 
5454  i = 0;
5455  foreach(lc, grouping_target->exprs)
5456  {
5457  Expr *expr = (Expr *) lfirst(lc);
5458  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
5459 
5460  if (sgref && root->processed_groupClause &&
5462  root->processed_groupClause) != NULL)
5463  {
5464  /*
5465  * It's a grouping column, so add it to the partial_target as-is.
5466  * (This allows the upper agg step to repeat the grouping calcs.)
5467  */
5468  add_column_to_pathtarget(partial_target, expr, sgref);
5469  }
5470  else
5471  {
5472  /*
5473  * Non-grouping column, so just remember the expression for later
5474  * call to pull_var_clause.
5475  */
5476  non_group_cols = lappend(non_group_cols, expr);
5477  }
5478 
5479  i++;
5480  }
5481 
5482  /*
5483  * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
5484  */
5485  if (havingQual)
5486  non_group_cols = lappend(non_group_cols, havingQual);
5487 
5488  /*
5489  * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
5490  * non-group cols (plus HAVING), and add them to the partial_target if not
5491  * already present. (An expression used directly as a GROUP BY item will
5492  * be present already.) Note this includes Vars used in resjunk items, so
5493  * we are covering the needs of ORDER BY and window specifications.
5494  */
5495  non_group_exprs = pull_var_clause((Node *) non_group_cols,
5499 
5500  add_new_columns_to_pathtarget(partial_target, non_group_exprs);
5501 
5502  /*
5503  * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5504  * are at the top level of the target list, so we can just scan the list
5505  * rather than recursing through the expression trees.
5506  */
5507  foreach(lc, partial_target->exprs)
5508  {
5509  Aggref *aggref = (Aggref *) lfirst(lc);
5510 
5511  if (IsA(aggref, Aggref))
5512  {
5513  Aggref *newaggref;
5514 
5515  /*
5516  * We shouldn't need to copy the substructure of the Aggref node,
5517  * but flat-copy the node itself to avoid damaging other trees.
5518  */
5519  newaggref = makeNode(Aggref);
5520  memcpy(newaggref, aggref, sizeof(Aggref));
5521 
5522  /* For now, assume serialization is required */
5524 
5525  lfirst(lc) = newaggref;
5526  }
5527  }
5528 
5529  /* clean up cruft */
5530  list_free(non_group_exprs);
5531  list_free(non_group_cols);
5532 
5533  /* XXX this causes some redundant cost calculation ... */
5534  return set_pathtarget_cost_width(root, partial_target);
5535 }
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:183
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition: planner.c:5544

References add_column_to_pathtarget(), add_new_columns_to_pathtarget(), AGGSPLIT_INITIAL_SERIAL, create_empty_pathtarget(), PathTarget::exprs, get_pathtarget_sortgroupref, get_sortgroupref_clause_noerr(), i, IsA, lappend(), lfirst, list_free(), makeNode, mark_partial_aggref(), NIL, PlannerInfo::processed_groupClause, pull_var_clause(), PVC_INCLUDE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, and set_pathtarget_cost_width().

Referenced by create_partial_grouping_paths().

◆ make_pathkeys_for_window()

static List * make_pathkeys_for_window ( PlannerInfo root,
WindowClause wc,
List tlist 
)
static

Definition at line 6033 of file planner.c.

6035 {
6036  List *window_pathkeys = NIL;
6037 
6038  /* Throw error if can't sort */
6040  ereport(ERROR,
6041  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6042  errmsg("could not implement window PARTITION BY"),
6043  errdetail("Window partitioning columns must be of sortable datatypes.")));
6045  ereport(ERROR,
6046  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6047  errmsg("could not implement window ORDER BY"),
6048  errdetail("Window ordering columns must be of sortable datatypes.")));
6049 
6050  /*
6051  * First fetch the pathkeys for the PARTITION BY clause. We can safely
6052  * remove any clauses from the wc->partitionClause for redundant pathkeys.
6053  */
6054  if (wc->partitionClause != NIL)
6055  {
6056  bool sortable;
6057 
6058  window_pathkeys = make_pathkeys_for_sortclauses_extended(root,
6059  &wc->partitionClause,
6060  tlist,
6061  true,
6062  &sortable);
6063 
6064  Assert(sortable);
6065  }
6066 
6067  /*
6068  * In principle, we could also consider removing redundant ORDER BY items
6069  * too as doing so does not alter the result of peer row checks done by
6070  * the executor. However, we must *not* remove the ordering column for
6071  * RANGE OFFSET cases, as the executor needs that for in_range tests even
6072  * if it's known to be equal to some partitioning column.
6073  */
6074  if (wc->orderClause != NIL)
6075  {
6076  List *orderby_pathkeys;
6077 
6078  orderby_pathkeys = make_pathkeys_for_sortclauses(root,
6079  wc->orderClause,
6080  tlist);
6081 
6082  /* Okay, make the combined pathkeys */
6083  if (window_pathkeys != NIL)
6084  window_pathkeys = append_pathkeys(window_pathkeys, orderby_pathkeys);
6085  else
6086  window_pathkeys = orderby_pathkeys;
6087  }
6088 
6089  return window_pathkeys;
6090 }
List * make_pathkeys_for_sortclauses_extended(PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool *sortable)
Definition: pathkeys.c:1170
List * partitionClause
Definition: parsenodes.h:1496
List * orderClause
Definition: parsenodes.h:1498

References append_pathkeys(), Assert(), ereport, errcode(), errdetail(), errmsg(), ERROR, grouping_is_sortable(), make_pathkeys_for_sortclauses(), make_pathkeys_for_sortclauses_extended(), NIL, WindowClause::orderClause, and WindowClause::partitionClause.

Referenced by create_one_window_path(), and standard_qp_callback().

◆ make_sort_input_target()

static PathTarget * make_sort_input_target ( PlannerInfo root,
PathTarget final_target,
bool have_postponed_srfs 
)
static

Definition at line 6159 of file planner.c.

6162 {
6163  Query *parse = root->parse;
6164  PathTarget *input_target;
6165  int ncols;
6166  bool *col_is_srf;
6167  bool *postpone_col;
6168  bool have_srf;
6169  bool have_volatile;
6170  bool have_expensive;
6171  bool have_srf_sortcols;
6172  bool postpone_srfs;
6173  List *postponable_cols;
6174  List *postponable_vars;
6175  int i;
6176  ListCell *lc;
6177 
6178  /* Shouldn't get here unless query has ORDER BY */
6179  Assert(parse->sortClause);
6180 
6181  *have_postponed_srfs = false; /* default result */
6182 
6183  /* Inspect tlist and collect per-column information */
6184  ncols = list_length(final_target->exprs);
6185  col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
6186  postpone_col = (bool *) palloc0(ncols * sizeof(bool));
6187  have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
6188 
6189  i = 0;
6190  foreach(lc, final_target->exprs)
6191  {
6192  Expr *expr = (Expr *) lfirst(lc);
6193 
6194  /*
6195  * If the column has a sortgroupref, assume it has to be evaluated
6196  * before sorting. Generally such columns would be ORDER BY, GROUP
6197  * BY, etc targets. One exception is columns that were removed from
6198  * GROUP BY by remove_useless_groupby_columns() ... but those would
6199  * only be Vars anyway. There don't seem to be any cases where it
6200  * would be worth the trouble to double-check.
6201  */
6202  if (get_pathtarget_sortgroupref(final_target, i) == 0)
6203  {
6204  /*
6205  * Check for SRF or volatile functions. Check the SRF case first
6206  * because we must know whether we have any postponed SRFs.
6207  */
6208  if (parse->hasTargetSRFs &&
6209  expression_returns_set((Node *) expr))
6210  {
6211  /* We'll decide below whether these are postponable */
6212  col_is_srf[i] = true;
6213  have_srf = true;
6214  }
6215  else if (contain_volatile_functions((Node *) expr))
6216  {
6217  /* Unconditionally postpone */
6218  postpone_col[i] = true;
6219  have_volatile = true;
6220  }
6221  else
6222  {
6223  /*
6224  * Else check the cost. XXX it's annoying to have to do this
6225  * when set_pathtarget_cost_width() just did it. Refactor to
6226  * allow sharing the work?
6227  */
6228  QualCost cost;
6229 
6230  cost_qual_eval_node(&cost, (Node *) expr, root);
6231 
6232  /*
6233  * We arbitrarily define "expensive" as "more than 10X
6234  * cpu_operator_cost". Note this will take in any PL function
6235  * with default cost.