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 Listgroupclause_apply_groupingset (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, PathTarget *target)
 
static void create_partial_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel, PathTarget *target)
 
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)
 
static Pathmake_ordered_path (PlannerInfo *root, RelOptInfo *rel, Path *path, Path *cheapest_path, List *pathkeys)
 

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

6798 {
6799  Query *parse = root->parse;
6800  Path *cheapest_path = input_rel->cheapest_total_path;
6801  ListCell *lc;
6802  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6803  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6804  List *havingQual = (List *) extra->havingQual;
6805  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6806 
6807  if (can_sort)
6808  {
6809  /*
6810  * Use any available suitably-sorted path as input, and also consider
6811  * sorting the cheapest-total path and incremental sort on any paths
6812  * with presorted keys.
6813  */
6814  foreach(lc, input_rel->pathlist)
6815  {
6816  ListCell *lc2;
6817  Path *path = (Path *) lfirst(lc);
6818  Path *path_save = path;
6819  List *pathkey_orderings = NIL;
6820 
6821  /* generate alternative group orderings that might be useful */
6822  pathkey_orderings = get_useful_group_keys_orderings(root, path);
6823 
6824  Assert(list_length(pathkey_orderings) > 0);
6825 
6826  foreach(lc2, pathkey_orderings)
6827  {
6828  PathKeyInfo *info = (PathKeyInfo *) lfirst(lc2);
6829 
6830  /* restore the path (we replace it in the loop) */
6831  path = path_save;
6832 
6833  path = make_ordered_path(root,
6834  grouped_rel,
6835  path,
6836  cheapest_path,
6837  info->pathkeys);
6838  if (path == NULL)
6839  continue;
6840 
6841  /* Now decide what to stick atop it */
6842  if (parse->groupingSets)
6843  {
6844  consider_groupingsets_paths(root, grouped_rel,
6845  path, true, can_hash,
6846  gd, agg_costs, dNumGroups);
6847  }
6848  else if (parse->hasAggs)
6849  {
6850  /*
6851  * We have aggregation, possibly with plain GROUP BY. Make
6852  * an AggPath.
6853  */
6854  add_path(grouped_rel, (Path *)
6855  create_agg_path(root,
6856  grouped_rel,
6857  path,
6858  grouped_rel->reltarget,
6859  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6861  info->clauses,
6862  havingQual,
6863  agg_costs,
6864  dNumGroups));
6865  }
6866  else if (parse->groupClause)
6867  {
6868  /*
6869  * We have GROUP BY without aggregation or grouping sets.
6870  * Make a GroupPath.
6871  */
6872  add_path(grouped_rel, (Path *)
6873  create_group_path(root,
6874  grouped_rel,
6875  path,
6876  info->clauses,
6877  havingQual,
6878  dNumGroups));
6879  }
6880  else
6881  {
6882  /* Other cases should have been handled above */
6883  Assert(false);
6884  }
6885  }
6886  }
6887 
6888  /*
6889  * Instead of operating directly on the input relation, we can
6890  * consider finalizing a partially aggregated path.
6891  */
6892  if (partially_grouped_rel != NULL)
6893  {
6894  foreach(lc, partially_grouped_rel->pathlist)
6895  {
6896  ListCell *lc2;
6897  Path *path = (Path *) lfirst(lc);
6898  Path *path_save = path;
6899  List *pathkey_orderings = NIL;
6900 
6901  /* generate alternative group orderings that might be useful */
6902  pathkey_orderings = get_useful_group_keys_orderings(root, path);
6903 
6904  Assert(list_length(pathkey_orderings) > 0);
6905 
6906  /* process all potentially interesting grouping reorderings */
6907  foreach(lc2, pathkey_orderings)
6908  {
6909  PathKeyInfo *info = (PathKeyInfo *) lfirst(lc2);
6910 
6911  /* restore the path (we replace it in the loop) */
6912  path = path_save;
6913 
6914  path = make_ordered_path(root,
6915  grouped_rel,
6916  path,
6917  partially_grouped_rel->cheapest_total_path,
6918  info->pathkeys);
6919 
6920  if (path == NULL)
6921  continue;
6922 
6923  if (parse->hasAggs)
6924  add_path(grouped_rel, (Path *)
6925  create_agg_path(root,
6926  grouped_rel,
6927  path,
6928  grouped_rel->reltarget,
6929  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6931  info->clauses,
6932  havingQual,
6933  agg_final_costs,
6934  dNumGroups));
6935  else
6936  add_path(grouped_rel, (Path *)
6937  create_group_path(root,
6938  grouped_rel,
6939  path,
6940  info->clauses,
6941  havingQual,
6942  dNumGroups));
6943 
6944  }
6945  }
6946  }
6947  }
6948 
6949  if (can_hash)
6950  {
6951  if (parse->groupingSets)
6952  {
6953  /*
6954  * Try for a hash-only groupingsets path over unsorted input.
6955  */
6956  consider_groupingsets_paths(root, grouped_rel,
6957  cheapest_path, false, true,
6958  gd, agg_costs, dNumGroups);
6959  }
6960  else
6961  {
6962  /*
6963  * Generate a HashAgg Path. We just need an Agg over the
6964  * cheapest-total input path, since input order won't matter.
6965  */
6966  add_path(grouped_rel, (Path *)
6967  create_agg_path(root, grouped_rel,
6968  cheapest_path,
6969  grouped_rel->reltarget,
6970  AGG_HASHED,
6972  root->processed_groupClause,
6973  havingQual,
6974  agg_costs,
6975  dNumGroups));
6976  }
6977 
6978  /*
6979  * Generate a Finalize HashAgg Path atop of the cheapest partially
6980  * grouped path, assuming there is one
6981  */
6982  if (partially_grouped_rel && partially_grouped_rel->pathlist)
6983  {
6984  Path *path = partially_grouped_rel->cheapest_total_path;
6985 
6986  add_path(grouped_rel, (Path *)
6987  create_agg_path(root,
6988  grouped_rel,
6989  path,
6990  grouped_rel->reltarget,
6991  AGG_HASHED,
6993  root->processed_groupClause,
6994  havingQual,
6995  agg_final_costs,
6996  dNumGroups));
6997  }
6998  }
6999 
7000  /*
7001  * When partitionwise aggregate is used, we might have fully aggregated
7002  * paths in the partial pathlist, because add_paths_to_append_rel() will
7003  * consider a path for grouped_rel consisting of a Parallel Append of
7004  * non-partial paths from each child.
7005  */
7006  if (grouped_rel->partial_pathlist != NIL)
7007  gather_grouping_paths(root, grouped_rel);
7008 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
@ AGG_SORTED
Definition: nodes.h:344
@ AGG_HASHED
Definition: nodes.h:345
@ AGG_PLAIN
Definition: nodes.h:343
@ AGGSPLIT_FINAL_DESERIAL
Definition: nodes.h:370
@ AGGSPLIT_SIMPLE
Definition: nodes.h:366
List * get_useful_group_keys_orderings(PlannerInfo *root, Path *path)
Definition: pathkeys.c:487
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:3029
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:3140
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:3228
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:3227
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: planner.c:7326
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:3998
static Path * make_ordered_path(PlannerInfo *root, RelOptInfo *rel, Path *path, Path *cheapest_path, List *pathkeys)
Definition: planner.c:6741
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:3268
Definition: pg_list.h:54
List * pathkeys
Definition: pathnodes.h:1467
List * clauses
Definition: pathnodes.h:1468
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, PathKeyInfo::clauses, consider_groupingsets_paths(), create_agg_path(), create_group_path(), GroupPathExtraData::flags, gather_grouping_paths(), get_useful_group_keys_orderings(), GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, GroupPathExtraData::havingQual, if(), lfirst, list_length(), make_ordered_path(), NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, PathKeyInfo::pathkeys, 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 3148 of file planner.c.

3149 {
3150  List *grouppathkeys = root->group_pathkeys;
3151  List *bestpathkeys;
3152  Bitmapset *bestaggs;
3153  Bitmapset *unprocessed_aggs;
3154  ListCell *lc;
3155  int i;
3156 
3157  /* Shouldn't be here if there are grouping sets */
3158  Assert(root->parse->groupingSets == NIL);
3159  /* Shouldn't be here unless there are some ordered aggregates */
3160  Assert(root->numOrderedAggs > 0);
3161 
3162  /* Do nothing if disabled */
3164  return;
3165 
3166  /*
3167  * Make a first pass over all AggInfos to collect a Bitmapset containing
3168  * the indexes of all AggInfos to be processed below.
3169  */
3170  unprocessed_aggs = NULL;
3171  foreach(lc, root->agginfos)
3172  {
3173  AggInfo *agginfo = lfirst_node(AggInfo, lc);
3174  Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3175 
3176  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
3177  continue;
3178 
3179  /* only add aggregates with a DISTINCT or ORDER BY */
3180  if (aggref->aggdistinct != NIL || aggref->aggorder != NIL)
3181  unprocessed_aggs = bms_add_member(unprocessed_aggs,
3182  foreach_current_index(lc));
3183  }
3184 
3185  /*
3186  * Now process all the unprocessed_aggs to find the best set of pathkeys
3187  * for the given set of aggregates.
3188  *
3189  * On the first outer loop here 'bestaggs' will be empty. We'll populate
3190  * this during the first loop using the pathkeys for the very first
3191  * AggInfo then taking any stronger pathkeys from any other AggInfos with
3192  * a more strict set of compatible pathkeys. Once the outer loop is
3193  * complete, we mark off all the aggregates with compatible pathkeys then
3194  * remove those from the unprocessed_aggs and repeat the process to try to
3195  * find another set of pathkeys that are suitable for a larger number of
3196  * aggregates. The outer loop will stop when there are not enough
3197  * unprocessed aggregates for it to be possible to find a set of pathkeys
3198  * to suit a larger number of aggregates.
3199  */
3200  bestpathkeys = NIL;
3201  bestaggs = NULL;
3202  while (bms_num_members(unprocessed_aggs) > bms_num_members(bestaggs))
3203  {
3204  Bitmapset *aggindexes = NULL;
3205  List *currpathkeys = NIL;
3206 
3207  i = -1;
3208  while ((i = bms_next_member(unprocessed_aggs, i)) >= 0)
3209  {
3210  AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3211  Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3212  List *sortlist;
3213  List *pathkeys;
3214 
3215  if (aggref->aggdistinct != NIL)
3216  sortlist = aggref->aggdistinct;
3217  else
3218  sortlist = aggref->aggorder;
3219 
3220  pathkeys = make_pathkeys_for_sortclauses(root, sortlist,
3221  aggref->args);
3222 
3223  /*
3224  * Ignore Aggrefs which have volatile functions in their ORDER BY
3225  * or DISTINCT clause.
3226  */
3227  if (has_volatile_pathkey(pathkeys))
3228  {
3229  unprocessed_aggs = bms_del_member(unprocessed_aggs, i);
3230  continue;
3231  }
3232 
3233  /*
3234  * When not set yet, take the pathkeys from the first unprocessed
3235  * aggregate.
3236  */
3237  if (currpathkeys == NIL)
3238  {
3239  currpathkeys = pathkeys;
3240 
3241  /* include the GROUP BY pathkeys, if they exist */
3242  if (grouppathkeys != NIL)
3243  currpathkeys = append_pathkeys(list_copy(grouppathkeys),
3244  currpathkeys);
3245 
3246  /* record that we found pathkeys for this aggregate */
3247  aggindexes = bms_add_member(aggindexes, i);
3248  }
3249  else
3250  {
3251  /* now look for a stronger set of matching pathkeys */
3252 
3253  /* include the GROUP BY pathkeys, if they exist */
3254  if (grouppathkeys != NIL)
3255  pathkeys = append_pathkeys(list_copy(grouppathkeys),
3256  pathkeys);
3257 
3258  /* are 'pathkeys' compatible or better than 'currpathkeys'? */
3259  switch (compare_pathkeys(currpathkeys, pathkeys))
3260  {
3261  case PATHKEYS_BETTER2:
3262  /* 'pathkeys' are stronger, use these ones instead */
3263  currpathkeys = pathkeys;
3264  /* FALLTHROUGH */
3265 
3266  case PATHKEYS_BETTER1:
3267  /* 'pathkeys' are less strict */
3268  /* FALLTHROUGH */
3269 
3270  case PATHKEYS_EQUAL:
3271  /* mark this aggregate as covered by 'currpathkeys' */
3272  aggindexes = bms_add_member(aggindexes, i);
3273  break;
3274 
3275  case PATHKEYS_DIFFERENT:
3276  break;
3277  }
3278  }
3279  }
3280 
3281  /* remove the aggregates that we've just processed */
3282  unprocessed_aggs = bms_del_members(unprocessed_aggs, aggindexes);
3283 
3284  /*
3285  * If this pass included more aggregates than the previous best then
3286  * use these ones as the best set.
3287  */
3288  if (bms_num_members(aggindexes) > bms_num_members(bestaggs))
3289  {
3290  bestaggs = aggindexes;
3291  bestpathkeys = currpathkeys;
3292  }
3293  }
3294 
3295  /*
3296  * If we found any ordered aggregates, update root->group_pathkeys to add
3297  * the best set of aggregate pathkeys. Note that bestpathkeys includes
3298  * the original GROUP BY pathkeys already.
3299  */
3300  if (bestpathkeys != NIL)
3301  root->group_pathkeys = bestpathkeys;
3302 
3303  /*
3304  * Now that we've found the best set of aggregates we can set the
3305  * presorted flag to indicate to the executor that it needn't bother
3306  * performing a sort for these Aggrefs. We're able to do this now as
3307  * there's no chance of a Hash Aggregate plan as create_grouping_paths
3308  * will not mark the GROUP BY as GROUPING_CAN_USE_HASH due to the presence
3309  * of ordered aggregates.
3310  */
3311  i = -1;
3312  while ((i = bms_next_member(bestaggs, i)) >= 0)
3313  {
3314  AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3315 
3316  foreach(lc, agginfo->aggrefs)
3317  {
3318  Aggref *aggref = lfirst_node(Aggref, lc);
3319 
3320  aggref->aggpresorted = true;
3321  }
3322  }
3323 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1319
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:764
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:828
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1174
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:881
bool enable_presorted_aggregate
Definition: costsize.c:154
int i
Definition: isn.c:73
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * append_pathkeys(List *target, List *source)
Definition: pathkeys.c:108
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:1349
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:304
@ 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 foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
static bool has_volatile_pathkey(List *keys)
Definition: planner.c:3103
List * aggrefs
Definition: pathnodes.h:3349
List * aggdistinct
Definition: primnodes.h:460
List * args
Definition: primnodes.h:454
List * aggorder
Definition: primnodes.h:457
int numOrderedAggs
Definition: pathnodes.h:511
List * group_pathkeys
Definition: pathnodes.h:385
List * agginfos
Definition: pathnodes.h:507
List * groupingSets
Definition: parsenodes.h:193

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

6293 {
6294  ListCell *lc;
6295 
6296  Assert(list_length(targets) == list_length(targets_contain_srfs));
6297  Assert(!linitial_int(targets_contain_srfs));
6298 
6299  /* If no SRFs appear at this plan level, nothing to do */
6300  if (list_length(targets) == 1)
6301  return;
6302 
6303  /*
6304  * Stack SRF-evaluation nodes atop each path for the rel.
6305  *
6306  * In principle we should re-run set_cheapest() here to identify the
6307  * cheapest path, but it seems unlikely that adding the same tlist eval
6308  * costs to all the paths would change that, so we don't bother. Instead,
6309  * just assume that the cheapest-startup and cheapest-total paths remain
6310  * so. (There should be no parameterized paths anymore, so we needn't
6311  * worry about updating cheapest_parameterized_paths.)
6312  */
6313  foreach(lc, rel->pathlist)
6314  {
6315  Path *subpath = (Path *) lfirst(lc);
6316  Path *newpath = subpath;
6317  ListCell *lc1,
6318  *lc2;
6319 
6320  Assert(subpath->param_info == NULL);
6321  forboth(lc1, targets, lc2, targets_contain_srfs)
6322  {
6323  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6324  bool contains_srfs = (bool) lfirst_int(lc2);
6325 
6326  /* If this level doesn't contain SRFs, do regular projection */
6327  if (contains_srfs)
6328  newpath = (Path *) create_set_projection_path(root,
6329  rel,
6330  newpath,
6331  thistarget);
6332  else
6333  newpath = (Path *) apply_projection_to_path(root,
6334  rel,
6335  newpath,
6336  thistarget);
6337  }
6338  lfirst(lc) = newpath;
6339  if (subpath == rel->cheapest_startup_path)
6340  rel->cheapest_startup_path = newpath;
6341  if (subpath == rel->cheapest_total_path)
6342  rel->cheapest_total_path = newpath;
6343  }
6344 
6345  /* Likewise for partial paths, if any */
6346  foreach(lc, rel->partial_pathlist)
6347  {
6348  Path *subpath = (Path *) lfirst(lc);
6349  Path *newpath = subpath;
6350  ListCell *lc1,
6351  *lc2;
6352 
6353  Assert(subpath->param_info == NULL);
6354  forboth(lc1, targets, lc2, targets_contain_srfs)
6355  {
6356  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
6357  bool contains_srfs = (bool) lfirst_int(lc2);
6358 
6359  /* If this level doesn't contain SRFs, do regular projection */
6360  if (contains_srfs)
6361  newpath = (Path *) create_set_projection_path(root,
6362  rel,
6363  newpath,
6364  thistarget);
6365  else
6366  {
6367  /* avoid apply_projection_to_path, in case of multiple refs */
6368  newpath = (Path *) create_projection_path(root,
6369  rel,
6370  newpath,
6371  thistarget);
6372  }
6373  }
6374  lfirst(lc) = newpath;
6375  }
6376 }
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:2670
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2867
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2778
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#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 7442 of file planner.c.

7448 {
7449  bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
7450  PathTarget *scanjoin_target;
7451  ListCell *lc;
7452 
7453  /* This recurses, so be paranoid. */
7455 
7456  /*
7457  * If the rel is partitioned, we want to drop its existing paths and
7458  * generate new ones. This function would still be correct if we kept the
7459  * existing paths: we'd modify them to generate the correct target above
7460  * the partitioning Append, and then they'd compete on cost with paths
7461  * generating the target below the Append. However, in our current cost
7462  * model the latter way is always the same or cheaper cost, so modifying
7463  * the existing paths would just be useless work. Moreover, when the cost
7464  * is the same, varying roundoff errors might sometimes allow an existing
7465  * path to be picked, resulting in undesirable cross-platform plan
7466  * variations. So we drop old paths and thereby force the work to be done
7467  * below the Append, except in the case of a non-parallel-safe target.
7468  *
7469  * Some care is needed, because we have to allow
7470  * generate_useful_gather_paths to see the old partial paths in the next
7471  * stanza. Hence, zap the main pathlist here, then allow
7472  * generate_useful_gather_paths to add path(s) to the main list, and
7473  * finally zap the partial pathlist.
7474  */
7475  if (rel_is_partitioned)
7476  rel->pathlist = NIL;
7477 
7478  /*
7479  * If the scan/join target is not parallel-safe, partial paths cannot
7480  * generate it.
7481  */
7482  if (!scanjoin_target_parallel_safe)
7483  {
7484  /*
7485  * Since we can't generate the final scan/join target in parallel
7486  * workers, this is our last opportunity to use any partial paths that
7487  * exist; so build Gather path(s) that use them and emit whatever the
7488  * current reltarget is. We don't do this in the case where the
7489  * target is parallel-safe, since we will be able to generate superior
7490  * paths by doing it after the final scan/join target has been
7491  * applied.
7492  */
7493  generate_useful_gather_paths(root, rel, false);
7494 
7495  /* Can't use parallel query above this level. */
7496  rel->partial_pathlist = NIL;
7497  rel->consider_parallel = false;
7498  }
7499 
7500  /* Finish dropping old paths for a partitioned rel, per comment above */
7501  if (rel_is_partitioned)
7502  rel->partial_pathlist = NIL;
7503 
7504  /* Extract SRF-free scan/join target. */
7505  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
7506 
7507  /*
7508  * Apply the SRF-free scan/join target to each existing path.
7509  *
7510  * If the tlist exprs are the same, we can just inject the sortgroupref
7511  * information into the existing pathtargets. Otherwise, replace each
7512  * path with a projection path that generates the SRF-free scan/join
7513  * target. This can't change the ordering of paths within rel->pathlist,
7514  * so we just modify the list in place.
7515  */
7516  foreach(lc, rel->pathlist)
7517  {
7518  Path *subpath = (Path *) lfirst(lc);
7519 
7520  /* Shouldn't have any parameterized paths anymore */
7521  Assert(subpath->param_info == NULL);
7522 
7523  if (tlist_same_exprs)
7524  subpath->pathtarget->sortgrouprefs =
7525  scanjoin_target->sortgrouprefs;
7526  else
7527  {
7528  Path *newpath;
7529 
7530  newpath = (Path *) create_projection_path(root, rel, subpath,
7531  scanjoin_target);
7532  lfirst(lc) = newpath;
7533  }
7534  }
7535 
7536  /* Likewise adjust the targets for any partial paths. */
7537  foreach(lc, rel->partial_pathlist)
7538  {
7539  Path *subpath = (Path *) lfirst(lc);
7540 
7541  /* Shouldn't have any parameterized paths anymore */
7542  Assert(subpath->param_info == NULL);
7543 
7544  if (tlist_same_exprs)
7545  subpath->pathtarget->sortgrouprefs =
7546  scanjoin_target->sortgrouprefs;
7547  else
7548  {
7549  Path *newpath;
7550 
7551  newpath = (Path *) create_projection_path(root, rel, subpath,
7552  scanjoin_target);
7553  lfirst(lc) = newpath;
7554  }
7555  }
7556 
7557  /*
7558  * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
7559  * atop each existing path. (Note that this function doesn't look at the
7560  * cheapest-path fields, which is a good thing because they're bogus right
7561  * now.)
7562  */
7563  if (root->parse->hasTargetSRFs)
7564  adjust_paths_for_srfs(root, rel,
7565  scanjoin_targets,
7566  scanjoin_targets_contain_srfs);
7567 
7568  /*
7569  * Update the rel's target to be the final (with SRFs) scan/join target.
7570  * This now matches the actual output of all the paths, and we might get
7571  * confused in createplan.c if they don't agree. We must do this now so
7572  * that any append paths made in the next part will use the correct
7573  * pathtarget (cf. create_append_path).
7574  *
7575  * Note that this is also necessary if GetForeignUpperPaths() gets called
7576  * on the final scan/join relation or on any of its children, since the
7577  * FDW might look at the rel's target to create ForeignPaths.
7578  */
7579  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
7580 
7581  /*
7582  * If the relation is partitioned, recursively apply the scan/join target
7583  * to all partitions, and generate brand-new Append paths in which the
7584  * scan/join target is computed below the Append rather than above it.
7585  * Since Append is not projection-capable, that might save a separate
7586  * Result node, and it also is important for partitionwise aggregate.
7587  */
7588  if (rel_is_partitioned)
7589  {
7590  List *live_children = NIL;
7591  int i;
7592 
7593  /* Adjust each partition. */
7594  i = -1;
7595  while ((i = bms_next_member(rel->live_parts, i)) >= 0)
7596  {
7597  RelOptInfo *child_rel = rel->part_rels[i];
7598  AppendRelInfo **appinfos;
7599  int nappinfos;
7600  List *child_scanjoin_targets = NIL;
7601 
7602  Assert(child_rel != NULL);
7603 
7604  /* Dummy children can be ignored. */
7605  if (IS_DUMMY_REL(child_rel))
7606  continue;
7607 
7608  /* Translate scan/join targets for this child. */
7609  appinfos = find_appinfos_by_relids(root, child_rel->relids,
7610  &nappinfos);
7611  foreach(lc, scanjoin_targets)
7612  {
7613  PathTarget *target = lfirst_node(PathTarget, lc);
7614 
7615  target = copy_pathtarget(target);
7616  target->exprs = (List *)
7618  (Node *) target->exprs,
7619  nappinfos, appinfos);
7620  child_scanjoin_targets = lappend(child_scanjoin_targets,
7621  target);
7622  }
7623  pfree(appinfos);
7624 
7625  /* Recursion does the real work. */
7626  apply_scanjoin_target_to_paths(root, child_rel,
7627  child_scanjoin_targets,
7628  scanjoin_targets_contain_srfs,
7629  scanjoin_target_parallel_safe,
7631 
7632  /* Save non-dummy children for Append paths. */
7633  if (!IS_DUMMY_REL(child_rel))
7634  live_children = lappend(live_children, child_rel);
7635  }
7636 
7637  /* Build new paths for this relation by appending child paths. */
7638  add_paths_to_append_rel(root, rel, live_children);
7639  }
7640 
7641  /*
7642  * Consider generating Gather or Gather Merge paths. We must only do this
7643  * if the relation is parallel safe, and we don't do it for child rels to
7644  * avoid creating multiple Gather nodes within the same plan. We must do
7645  * this after all paths have been generated and before set_cheapest, since
7646  * one of the generated paths may turn out to be the cheapest one.
7647  */
7648  if (rel->consider_parallel && !IS_OTHER_REL(rel))
7649  generate_useful_gather_paths(root, rel, false);
7650 
7651  /*
7652  * Reassess which paths are the cheapest, now that we've potentially added
7653  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
7654  * this relation.
7655  */
7656  set_cheapest(rel);
7657 }
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3200
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:339
void pfree(void *pointer)
Definition: mcxt.c:1431
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1926
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:1043
#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:7442
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:6291
void check_stack_depth(void)
Definition: postgres.c:3523
Definition: nodes.h:129
List * exprs
Definition: pathnodes.h:1513
Relids relids
Definition: pathnodes.h:856
bool consider_parallel
Definition: pathnodes.h:872
Bitmapset * live_parts
Definition: pathnodes.h:1020
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 7400 of file planner.c.

7401 {
7402  Query *parse = root->parse;
7403 
7404  if (!parse->hasAggs && parse->groupClause == NIL)
7405  {
7406  /*
7407  * We don't know how to do parallel aggregation unless we have either
7408  * some aggregates or a grouping clause.
7409  */
7410  return false;
7411  }
7412  else if (parse->groupingSets)
7413  {
7414  /* We don't know how to do grouping sets in parallel. */
7415  return false;
7416  }
7417  else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
7418  {
7419  /* Insufficient support for partial mode. */
7420  return false;
7421  }
7422 
7423  /* Everything looks good. */
7424  return true;
7425 }
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 5762 of file planner.c.

5763 {
5764  const WindowClauseSortData *wcsa = a;
5765  const WindowClauseSortData *wcsb = b;
5766  ListCell *item_a;
5767  ListCell *item_b;
5768 
5769  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5770  {
5773 
5774  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5775  return -1;
5776  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5777  return 1;
5778  else if (sca->sortop > scb->sortop)
5779  return -1;
5780  else if (sca->sortop < scb->sortop)
5781  return 1;
5782  else if (sca->nulls_first && !scb->nulls_first)
5783  return -1;
5784  else if (!sca->nulls_first && scb->nulls_first)
5785  return 1;
5786  /* no need to compare eqop, since it is fully determined by sortop */
5787  }
5788 
5789  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5790  return -1;
5791  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5792  return 1;
5793 
5794  return 0;
5795 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69
Index tleSortGroupRef
Definition: parsenodes.h:1385

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

4006 {
4007  Query *parse = root->parse;
4008  Size hash_mem_limit = get_hash_memory_limit();
4009 
4010  /*
4011  * If we're not being offered sorted input, then only consider plans that
4012  * can be done entirely by hashing.
4013  *
4014  * We can hash everything if it looks like it'll fit in hash_mem. But if
4015  * the input is actually sorted despite not being advertised as such, we
4016  * prefer to make use of that in order to use less memory.
4017  *
4018  * If none of the grouping sets are sortable, then ignore the hash_mem
4019  * limit and generate a path anyway, since otherwise we'll just fail.
4020  */
4021  if (!is_sorted)
4022  {
4023  List *new_rollups = NIL;
4024  RollupData *unhashed_rollup = NULL;
4025  List *sets_data;
4026  List *empty_sets_data = NIL;
4027  List *empty_sets = NIL;
4028  ListCell *lc;
4029  ListCell *l_start = list_head(gd->rollups);
4030  AggStrategy strat = AGG_HASHED;
4031  double hashsize;
4032  double exclude_groups = 0.0;
4033 
4034  Assert(can_hash);
4035 
4036  /*
4037  * If the input is coincidentally sorted usefully (which can happen
4038  * even if is_sorted is false, since that only means that our caller
4039  * has set up the sorting for us), then save some hashtable space by
4040  * making use of that. But we need to watch out for degenerate cases:
4041  *
4042  * 1) If there are any empty grouping sets, then group_pathkeys might
4043  * be NIL if all non-empty grouping sets are unsortable. In this case,
4044  * there will be a rollup containing only empty groups, and the
4045  * pathkeys_contained_in test is vacuously true; this is ok.
4046  *
4047  * XXX: the above relies on the fact that group_pathkeys is generated
4048  * from the first rollup. If we add the ability to consider multiple
4049  * sort orders for grouping input, this assumption might fail.
4050  *
4051  * 2) If there are no empty sets and only unsortable sets, then the
4052  * rollups list will be empty (and thus l_start == NULL), and
4053  * group_pathkeys will be NIL; we must ensure that the vacuously-true
4054  * pathkeys_contained_in test doesn't cause us to crash.
4055  */
4056  if (l_start != NULL &&
4058  {
4059  unhashed_rollup = lfirst_node(RollupData, l_start);
4060  exclude_groups = unhashed_rollup->numGroups;
4061  l_start = lnext(gd->rollups, l_start);
4062  }
4063 
4064  hashsize = estimate_hashagg_tablesize(root,
4065  path,
4066  agg_costs,
4067  dNumGroups - exclude_groups);
4068 
4069  /*
4070  * gd->rollups is empty if we have only unsortable columns to work
4071  * with. Override hash_mem in that case; otherwise, we'll rely on the
4072  * sorted-input case to generate usable mixed paths.
4073  */
4074  if (hashsize > hash_mem_limit && gd->rollups)
4075  return; /* nope, won't fit */
4076 
4077  /*
4078  * We need to burst the existing rollups list into individual grouping
4079  * sets and recompute a groupClause for each set.
4080  */
4081  sets_data = list_copy(gd->unsortable_sets);
4082 
4083  for_each_cell(lc, gd->rollups, l_start)
4084  {
4085  RollupData *rollup = lfirst_node(RollupData, lc);
4086 
4087  /*
4088  * If we find an unhashable rollup that's not been skipped by the
4089  * "actually sorted" check above, we can't cope; we'd need sorted
4090  * input (with a different sort order) but we can't get that here.
4091  * So bail out; we'll get a valid path from the is_sorted case
4092  * instead.
4093  *
4094  * The mere presence of empty grouping sets doesn't make a rollup
4095  * unhashable (see preprocess_grouping_sets), we handle those
4096  * specially below.
4097  */
4098  if (!rollup->hashable)
4099  return;
4100 
4101  sets_data = list_concat(sets_data, rollup->gsets_data);
4102  }
4103  foreach(lc, sets_data)
4104  {
4106  List *gset = gs->set;
4107  RollupData *rollup;
4108 
4109  if (gset == NIL)
4110  {
4111  /* Empty grouping sets can't be hashed. */
4112  empty_sets_data = lappend(empty_sets_data, gs);
4113  empty_sets = lappend(empty_sets, NIL);
4114  }
4115  else
4116  {
4117  rollup = makeNode(RollupData);
4118 
4119  rollup->groupClause = groupclause_apply_groupingset(root, gset);
4120  rollup->gsets_data = list_make1(gs);
4121  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4122  rollup->gsets_data,
4123  gd->tleref_to_colnum_map);
4124  rollup->numGroups = gs->numGroups;
4125  rollup->hashable = true;
4126  rollup->is_hashed = true;
4127  new_rollups = lappend(new_rollups, rollup);
4128  }
4129  }
4130 
4131  /*
4132  * If we didn't find anything nonempty to hash, then bail. We'll
4133  * generate a path from the is_sorted case.
4134  */
4135  if (new_rollups == NIL)
4136  return;
4137 
4138  /*
4139  * If there were empty grouping sets they should have been in the
4140  * first rollup.
4141  */
4142  Assert(!unhashed_rollup || !empty_sets);
4143 
4144  if (unhashed_rollup)
4145  {
4146  new_rollups = lappend(new_rollups, unhashed_rollup);
4147  strat = AGG_MIXED;
4148  }
4149  else if (empty_sets)
4150  {
4151  RollupData *rollup = makeNode(RollupData);
4152 
4153  rollup->groupClause = NIL;
4154  rollup->gsets_data = empty_sets_data;
4155  rollup->gsets = empty_sets;
4156  rollup->numGroups = list_length(empty_sets);
4157  rollup->hashable = false;
4158  rollup->is_hashed = false;
4159  new_rollups = lappend(new_rollups, rollup);
4160  strat = AGG_MIXED;
4161  }
4162 
4163  add_path(grouped_rel, (Path *)
4165  grouped_rel,
4166  path,
4167  (List *) parse->havingQual,
4168  strat,
4169  new_rollups,
4170  agg_costs));
4171  return;
4172  }
4173 
4174  /*
4175  * If we have sorted input but nothing we can do with it, bail.
4176  */
4177  if (gd->rollups == NIL)
4178  return;
4179 
4180  /*
4181  * Given sorted input, we try and make two paths: one sorted and one mixed
4182  * sort/hash. (We need to try both because hashagg might be disabled, or
4183  * some columns might not be sortable.)
4184  *
4185  * can_hash is passed in as false if some obstacle elsewhere (such as
4186  * ordered aggs) means that we shouldn't consider hashing at all.
4187  */
4188  if (can_hash && gd->any_hashable)
4189  {
4190  List *rollups = NIL;
4191  List *hash_sets = list_copy(gd->unsortable_sets);
4192  double availspace = hash_mem_limit;
4193  ListCell *lc;
4194 
4195  /*
4196  * Account first for space needed for groups we can't sort at all.
4197  */
4198  availspace -= estimate_hashagg_tablesize(root,
4199  path,
4200  agg_costs,
4201  gd->dNumHashGroups);
4202 
4203  if (availspace > 0 && list_length(gd->rollups) > 1)
4204  {
4205  double scale;
4206  int num_rollups = list_length(gd->rollups);
4207  int k_capacity;
4208  int *k_weights = palloc(num_rollups * sizeof(int));
4209  Bitmapset *hash_items = NULL;
4210  int i;
4211 
4212  /*
4213  * We treat this as a knapsack problem: the knapsack capacity
4214  * represents hash_mem, the item weights are the estimated memory
4215  * usage of the hashtables needed to implement a single rollup,
4216  * and we really ought to use the cost saving as the item value;
4217  * however, currently the costs assigned to sort nodes don't
4218  * reflect the comparison costs well, and so we treat all items as
4219  * of equal value (each rollup we hash instead saves us one sort).
4220  *
4221  * To use the discrete knapsack, we need to scale the values to a
4222  * reasonably small bounded range. We choose to allow a 5% error
4223  * margin; we have no more than 4096 rollups in the worst possible
4224  * case, which with a 5% error margin will require a bit over 42MB
4225  * of workspace. (Anyone wanting to plan queries that complex had
4226  * better have the memory for it. In more reasonable cases, with
4227  * no more than a couple of dozen rollups, the memory usage will
4228  * be negligible.)
4229  *
4230  * k_capacity is naturally bounded, but we clamp the values for
4231  * scale and weight (below) to avoid overflows or underflows (or
4232  * uselessly trying to use a scale factor less than 1 byte).
4233  */
4234  scale = Max(availspace / (20.0 * num_rollups), 1.0);
4235  k_capacity = (int) floor(availspace / scale);
4236 
4237  /*
4238  * We leave the first rollup out of consideration since it's the
4239  * one that matches the input sort order. We assign indexes "i"
4240  * to only those entries considered for hashing; the second loop,
4241  * below, must use the same condition.
4242  */
4243  i = 0;
4244  for_each_from(lc, gd->rollups, 1)
4245  {
4246  RollupData *rollup = lfirst_node(RollupData, lc);
4247 
4248  if (rollup->hashable)
4249  {
4250  double sz = estimate_hashagg_tablesize(root,
4251  path,
4252  agg_costs,
4253  rollup->numGroups);
4254 
4255  /*
4256  * If sz is enormous, but hash_mem (and hence scale) is
4257  * small, avoid integer overflow here.
4258  */
4259  k_weights[i] = (int) Min(floor(sz / scale),
4260  k_capacity + 1.0);
4261  ++i;
4262  }
4263  }
4264 
4265  /*
4266  * Apply knapsack algorithm; compute the set of items which
4267  * maximizes the value stored (in this case the number of sorts
4268  * saved) while keeping the total size (approximately) within
4269  * capacity.
4270  */
4271  if (i > 0)
4272  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4273 
4274  if (!bms_is_empty(hash_items))
4275  {
4276  rollups = list_make1(linitial(gd->rollups));
4277 
4278  i = 0;
4279  for_each_from(lc, gd->rollups, 1)
4280  {
4281  RollupData *rollup = lfirst_node(RollupData, lc);
4282 
4283  if (rollup->hashable)
4284  {
4285  if (bms_is_member(i, hash_items))
4286  hash_sets = list_concat(hash_sets,
4287  rollup->gsets_data);
4288  else
4289  rollups = lappend(rollups, rollup);
4290  ++i;
4291  }
4292  else
4293  rollups = lappend(rollups, rollup);
4294  }
4295  }
4296  }
4297 
4298  if (!rollups && hash_sets)
4299  rollups = list_copy(gd->rollups);
4300 
4301  foreach(lc, hash_sets)
4302  {
4304  RollupData *rollup = makeNode(RollupData);
4305 
4306  Assert(gs->set != NIL);
4307 
4308  rollup->groupClause = groupclause_apply_groupingset(root, gs->set);
4309  rollup->gsets_data = list_make1(gs);
4310  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4311  rollup->gsets_data,
4312  gd->tleref_to_colnum_map);
4313  rollup->numGroups = gs->numGroups;
4314  rollup->hashable = true;
4315  rollup->is_hashed = true;
4316  rollups = lcons(rollup, rollups);
4317  }
4318 
4319  if (rollups)
4320  {
4321  add_path(grouped_rel, (Path *)
4323  grouped_rel,
4324  path,
4325  (List *) parse->havingQual,
4326  AGG_MIXED,
4327  rollups,
4328  agg_costs));
4329  }
4330  }
4331 
4332  /*
4333  * Now try the simple sorted case.
4334  */
4335  if (!gd->unsortable_sets)
4336  add_path(grouped_rel, (Path *)
4338  grouped_rel,
4339  path,
4340  (List *) parse->havingQual,
4341  AGG_SORTED,
4342  gd->rollups,
4343  agg_costs));
4344 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:523
#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:561
List * lcons(void *datum, List *list)
Definition: list.c:495
void * palloc(Size size)
Definition: mcxt.c:1201
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3596
AggStrategy
Definition: nodes.h:342
@ AGG_MIXED
Definition: nodes.h:346
#define makeNode(_type_)
Definition: nodes.h:155
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:343
GroupingSetsPath * create_groupingsets_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *having_qual, AggStrategy aggstrategy, List *rollups, const AggClauseCosts *agg_costs)
Definition: pathnode.c:3222
#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 * groupclause_apply_groupingset(PlannerInfo *root, List *force)
Definition: planner.c:2807
static List * remap_to_groupclause_idx(List *groupClause, List *gsets, int *tleref_to_colnum_map)
Definition: planner.c:2203
double estimate_hashagg_tablesize(PlannerInfo *root, Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: selfuncs.c:3917
Cardinality numGroups
Definition: pathnodes.h:2253
List * pathkeys
Definition: pathnodes.h:1645
Cardinality numGroups
Definition: pathnodes.h:2264
List * groupClause
Definition: pathnodes.h:2261
List * gsets_data
Definition: pathnodes.h:2263
bool hashable
Definition: pathnodes.h:2265
List * gsets
Definition: pathnodes.h:2262
bool is_hashed
Definition: pathnodes.h:2266
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, groupclause_apply_groupingset(), 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(), 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 3795 of file planner.c.

3797 {
3798  Query *parse = root->parse;
3799  int nrows;
3800  Path *path;
3801 
3802  nrows = list_length(parse->groupingSets);
3803  if (nrows > 1)
3804  {
3805  /*
3806  * Doesn't seem worthwhile writing code to cons up a generate_series
3807  * or a values scan to emit multiple rows. Instead just make N clones
3808  * and append them. (With a volatile HAVING clause, this means you
3809  * might get between 0 and N output rows. Offhand I think that's
3810  * desired.)
3811  */
3812  List *paths = NIL;
3813 
3814  while (--nrows >= 0)
3815  {
3816  path = (Path *)
3817  create_group_result_path(root, grouped_rel,
3818  grouped_rel->reltarget,
3819  (List *) parse->havingQual);
3820  paths = lappend(paths, path);
3821  }
3822  path = (Path *)
3823  create_append_path(root,
3824  grouped_rel,
3825  paths,
3826  NIL,
3827  NIL,
3828  NULL,
3829  0,
3830  false,
3831  -1);
3832  }
3833  else
3834  {
3835  /* No grouping sets, or just one, so one output row */
3836  path = (Path *)
3837  create_group_result_path(root, grouped_rel,
3838  grouped_rel->reltarget,
3839  (List *) parse->havingQual);
3840  }
3841 
3842  add_path(grouped_rel, path);
3843 }
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:1246
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1520

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,
PathTarget target 
)
static

Definition at line 4580 of file planner.c.

4582 {
4583  RelOptInfo *distinct_rel;
4584 
4585  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4586  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4587 
4588  /*
4589  * We don't compute anything at this level, so distinct_rel will be
4590  * parallel-safe if the input rel is parallel-safe. In particular, if
4591  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4592  * output those expressions, and will not be parallel-safe unless those
4593  * expressions are parallel-safe.
4594  */
4595  distinct_rel->consider_parallel = input_rel->consider_parallel;
4596 
4597  /*
4598  * If the input rel belongs to a single FDW, so does the distinct_rel.
4599  */
4600  distinct_rel->serverid = input_rel->serverid;
4601  distinct_rel->userid = input_rel->userid;
4602  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4603  distinct_rel->fdwroutine = input_rel->fdwroutine;
4604 
4605  /* build distinct paths based on input_rel's pathlist */
4606  create_final_distinct_paths(root, input_rel, distinct_rel);
4607 
4608  /* now build distinct paths based on input_rel's partial_pathlist */
4609  create_partial_distinct_paths(root, input_rel, distinct_rel, target);
4610 
4611  /* Give a helpful error if we failed to create any paths */
4612  if (distinct_rel->pathlist == NIL)
4613  ereport(ERROR,
4614  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4615  errmsg("could not implement DISTINCT"),
4616  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4617 
4618  /*
4619  * If there is an FDW that's responsible for all baserels of the query,
4620  * let it consider adding ForeignPaths.
4621  */
4622  if (distinct_rel->fdwroutine &&
4623  distinct_rel->fdwroutine->GetForeignUpperPaths)
4624  distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4626  input_rel,
4627  distinct_rel,
4628  NULL);
4629 
4630  /* Let extensions possibly add some more paths */
4632  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
4633  distinct_rel, NULL);
4634 
4635  /* Now choose the best path(s) */
4636  set_cheapest(distinct_rel);
4637 
4638  return distinct_rel;
4639 }
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
@ UPPERREL_DISTINCT
Definition: pathnodes.h:77
static RelOptInfo * create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_rel)
Definition: planner.c:4849
static void create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel, PathTarget *target)
Definition: planner.c:4650
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:1463
bool useridiscurrent
Definition: pathnodes.h:949
Oid userid
Definition: pathnodes.h:947
Oid serverid
Definition: pathnodes.h:945

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

4851 {
4852  Query *parse = root->parse;
4853  Path *cheapest_input_path = input_rel->cheapest_total_path;
4854  double numDistinctRows;
4855  bool allow_hash;
4856 
4857  /* Estimate number of distinct rows there will be */
4858  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4859  root->hasHavingQual)
4860  {
4861  /*
4862  * If there was grouping or aggregation, use the number of input rows
4863  * as the estimated number of DISTINCT rows (ie, assume the input is
4864  * already mostly unique).
4865  */
4866  numDistinctRows = cheapest_input_path->rows;
4867  }
4868  else
4869  {
4870  /*
4871  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4872  */
4873  List *distinctExprs;
4874 
4875  distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
4876  parse->targetList);
4877  numDistinctRows = estimate_num_groups(root, distinctExprs,
4878  cheapest_input_path->rows,
4879  NULL, NULL);
4880  }
4881 
4882  /*
4883  * Consider sort-based implementations of DISTINCT, if possible.
4884  */
4886  {
4887  /*
4888  * Firstly, if we have any adequately-presorted paths, just stick a
4889  * Unique node on those. We also, consider doing an explicit sort of
4890  * the cheapest input path and Unique'ing that. If any paths have
4891  * presorted keys then we'll create an incremental sort atop of those
4892  * before adding a unique node on the top.
4893  *
4894  * When we have DISTINCT ON, we must sort by the more rigorous of
4895  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4896  * Also, if we do have to do an explicit sort, we might as well use
4897  * the more rigorous ordering to avoid a second sort later. (Note
4898  * that the parser will have ensured that one clause is a prefix of
4899  * the other.)
4900  */
4901  List *needed_pathkeys;
4902  ListCell *lc;
4903  double limittuples = root->distinct_pathkeys == NIL ? 1.0 : -1.0;
4904 
4905  if (parse->hasDistinctOn &&
4907  list_length(root->sort_pathkeys))
4908  needed_pathkeys = root->sort_pathkeys;
4909  else
4910  needed_pathkeys = root->distinct_pathkeys;
4911 
4912  foreach(lc, input_rel->pathlist)
4913  {
4914  Path *input_path = (Path *) lfirst(lc);
4915  Path *sorted_path;
4916  bool is_sorted;
4917  int presorted_keys;
4918 
4919  is_sorted = pathkeys_count_contained_in(needed_pathkeys,
4920  input_path->pathkeys,
4921  &presorted_keys);
4922 
4923  if (is_sorted)
4924  sorted_path = input_path;
4925  else
4926  {
4927  /*
4928  * Try at least sorting the cheapest path and also try
4929  * incrementally sorting any path which is partially sorted
4930  * already (no need to deal with paths which have presorted
4931  * keys when incremental sort is disabled unless it's the
4932  * cheapest input path).
4933  */
4934  if (input_path != cheapest_input_path &&
4935  (presorted_keys == 0 || !enable_incremental_sort))
4936  continue;
4937 
4938  /*
4939  * We've no need to consider both a sort and incremental sort.
4940  * We'll just do a sort if there are no presorted keys and an
4941  * incremental sort when there are presorted keys.
4942  */
4943  if (presorted_keys == 0 || !enable_incremental_sort)
4944  sorted_path = (Path *) create_sort_path(root,
4945  distinct_rel,
4946  input_path,
4947  needed_pathkeys,
4948  limittuples);
4949  else
4950  sorted_path = (Path *) create_incremental_sort_path(root,
4951  distinct_rel,
4952  input_path,
4953  needed_pathkeys,
4954  presorted_keys,
4955  limittuples);
4956  }
4957 
4958  /*
4959  * distinct_pathkeys may have become empty if all of the pathkeys
4960  * were determined to be redundant. If all of the pathkeys are
4961  * redundant then each DISTINCT target must only allow a single
4962  * value, therefore all resulting tuples must be identical (or at
4963  * least indistinguishable by an equality check). We can uniquify
4964  * these tuples simply by just taking the first tuple. All we do
4965  * here is add a path to do "LIMIT 1" atop of 'sorted_path'. When
4966  * doing a DISTINCT ON we may still have a non-NIL sort_pathkeys
4967  * list, so we must still only do this with paths which are
4968  * correctly sorted by sort_pathkeys.
4969  */
4970  if (root->distinct_pathkeys == NIL)
4971  {
4972  Node *limitCount;
4973 
4974  limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
4975  sizeof(int64),
4976  Int64GetDatum(1), false,
4977  FLOAT8PASSBYVAL);
4978 
4979  /*
4980  * If the query already has a LIMIT clause, then we could end
4981  * up with a duplicate LimitPath in the final plan. That does
4982  * not seem worth troubling over too much.
4983  */
4984  add_path(distinct_rel, (Path *)
4985  create_limit_path(root, distinct_rel, sorted_path,
4986  NULL, limitCount,
4987  LIMIT_OPTION_COUNT, 0, 1));
4988  }
4989  else
4990  {
4991  add_path(distinct_rel, (Path *)
4992  create_upper_unique_path(root, distinct_rel,
4993  sorted_path,
4995  numDistinctRows));
4996  }
4997  }
4998  }
4999 
5000  /*
5001  * Consider hash-based implementations of DISTINCT, if possible.
5002  *
5003  * If we were not able to make any other types of path, we *must* hash or
5004  * die trying. If we do have other choices, there are two things that
5005  * should prevent selection of hashing: if the query uses DISTINCT ON
5006  * (because it won't really have the expected behavior if we hash), or if
5007  * enable_hashagg is off.
5008  *
5009  * Note: grouping_is_hashable() is much more expensive to check than the
5010  * other gating conditions, so we want to do it last.
5011  */
5012  if (distinct_rel->pathlist == NIL)
5013  allow_hash = true; /* we have no alternatives */
5014  else if (parse->hasDistinctOn || !enable_hashagg)
5015  allow_hash = false; /* policy-based decision not to hash */
5016  else
5017  allow_hash = true; /* default */
5018 
5019  if (allow_hash && grouping_is_hashable(root->processed_distinctClause))
5020  {
5021  /* Generate hashed aggregate path --- no sort needed */
5022  add_path(distinct_rel, (Path *)
5023  create_agg_path(root,
5024  distinct_rel,
5025  cheapest_input_path,
5026  cheapest_input_path->pathtarget,
5027  AGG_HASHED,
5030  NIL,
5031  NULL,
5032  numDistinctRows));
5033  }
5034 
5035  return distinct_rel;
5036 }
#define FLOAT8PASSBYVAL
Definition: c.h:624
bool enable_hashagg
Definition: costsize.c:142
bool enable_incremental_sort
Definition: costsize.c:141
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1807
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:420
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:575
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2985
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:3805
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:3088
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2936
#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:3416
Cardinality rows
Definition: pathnodes.h:1640
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 3608 of file planner.c.

3613 {
3614  Query *parse = root->parse;
3615  RelOptInfo *grouped_rel;
3616  RelOptInfo *partially_grouped_rel;
3617  AggClauseCosts agg_costs;
3618 
3619  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3620  get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &agg_costs);
3621 
3622  /*
3623  * Create grouping relation to hold fully aggregated grouping and/or
3624  * aggregation paths.
3625  */
3626  grouped_rel = make_grouping_rel(root, input_rel, target,
3627  target_parallel_safe, parse->havingQual);
3628 
3629  /*
3630  * Create either paths for a degenerate grouping or paths for ordinary
3631  * grouping, as appropriate.
3632  */
3633  if (is_degenerate_grouping(root))
3634  create_degenerate_grouping_paths(root, input_rel, grouped_rel);
3635  else
3636  {
3637  int flags = 0;
3638  GroupPathExtraData extra;
3639 
3640  /*
3641  * Determine whether it's possible to perform sort-based
3642  * implementations of grouping. (Note that if processed_groupClause
3643  * is empty, grouping_is_sortable() is trivially true, and all the
3644  * pathkeys_contained_in() tests will succeed too, so that we'll
3645  * consider every surviving input path.)
3646  *
3647  * If we have grouping sets, we might be able to sort some but not all
3648  * of them; in this case, we need can_sort to be true as long as we
3649  * must consider any sorted-input plan.
3650  */
3651  if ((gd && gd->rollups != NIL)
3653  flags |= GROUPING_CAN_USE_SORT;
3654 
3655  /*
3656  * Determine whether we should consider hash-based implementations of
3657  * grouping.
3658  *
3659  * Hashed aggregation only applies if we're grouping. If we have
3660  * grouping sets, some groups might be hashable but others not; in
3661  * this case we set can_hash true as long as there is nothing globally
3662  * preventing us from hashing (and we should therefore consider plans
3663  * with hashes).
3664  *
3665  * Executor doesn't support hashed aggregation with DISTINCT or ORDER
3666  * BY aggregates. (Doing so would imply storing *all* the input
3667  * values in the hash table, and/or running many sorts in parallel,
3668  * either of which seems like a certain loser.) We similarly don't
3669  * support ordered-set aggregates in hashed aggregation, but that case
3670  * is also included in the numOrderedAggs count.
3671  *
3672  * Note: grouping_is_hashable() is much more expensive to check than
3673  * the other gating conditions, so we want to do it last.
3674  */
3675  if ((parse->groupClause != NIL &&
3676  root->numOrderedAggs == 0 &&
3678  flags |= GROUPING_CAN_USE_HASH;
3679 
3680  /*
3681  * Determine whether partial aggregation is possible.
3682  */
3683  if (can_partial_agg(root))
3684  flags |= GROUPING_CAN_PARTIAL_AGG;
3685 
3686  extra.flags = flags;
3687  extra.target_parallel_safe = target_parallel_safe;
3688  extra.havingQual = parse->havingQual;
3689  extra.targetList = parse->targetList;
3690  extra.partial_costs_set = false;
3691 
3692  /*
3693  * Determine whether partitionwise aggregation is in theory possible.
3694  * It can be disabled by the user, and for now, we don't try to
3695  * support grouping sets. create_ordinary_grouping_paths() will check
3696  * additional conditions, such as whether input_rel is partitioned.
3697  */
3698  if (enable_partitionwise_aggregate && !parse->groupingSets)
3700  else
3702 
3703  create_ordinary_grouping_paths(root, input_rel, grouped_rel,
3704  &agg_costs, gd, &extra,
3705  &partially_grouped_rel);
3706  }
3707 
3708  set_cheapest(grouped_rel);
3709  return grouped_rel;
3710 }
#define MemSet(start, val, len)
Definition: c.h:1009
bool enable_partitionwise_aggregate
Definition: costsize.c:150
@ PARTITIONWISE_AGGREGATE_FULL
Definition: pathnodes.h:3245
@ PARTITIONWISE_AGGREGATE_NONE
Definition: pathnodes.h:3244
#define GROUPING_CAN_PARTIAL_AGG
Definition: pathnodes.h:3229
static void create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
Definition: planner.c:3795
static bool is_degenerate_grouping(PlannerInfo *root)
Definition: planner.c:3774
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:3859
static bool can_partial_agg(PlannerInfo *root)
Definition: planner.c:7400
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3721
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:561
PartitionwiseAggregateType patype
Definition: pathnodes.h:3274

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

4454 {
4455  PathTarget *window_target;
4456  ListCell *l;
4457  List *topqual = NIL;
4458 
4459  /*
4460  * Since each window clause could require a different sort order, we stack
4461  * up a WindowAgg node for each clause, with sort steps between them as
4462  * needed. (We assume that select_active_windows chose a good order for
4463  * executing the clauses in.)
4464  *
4465  * input_target should contain all Vars and Aggs needed for the result.
4466  * (In some cases we wouldn't need to propagate all of these all the way
4467  * to the top, since they might only be needed as inputs to WindowFuncs.
4468  * It's probably not worth trying to optimize that though.) It must also
4469  * contain all window partitioning and sorting expressions, to ensure
4470  * they're computed only once at the bottom of the stack (that's critical
4471  * for volatile functions). As we climb up the stack, we'll add outputs
4472  * for the WindowFuncs computed at each level.
4473  */
4474  window_target = input_target;
4475 
4476  foreach(l, activeWindows)
4477  {
4479  List *window_pathkeys;
4480  int presorted_keys;
4481  bool is_sorted;
4482  bool topwindow;
4483 
4484  window_pathkeys = make_pathkeys_for_window(root,
4485  wc,
4486  root->processed_tlist);
4487 
4488  is_sorted = pathkeys_count_contained_in(window_pathkeys,
4489  path->pathkeys,
4490  &presorted_keys);
4491 
4492  /* Sort if necessary */
4493  if (!is_sorted)
4494  {
4495  /*
4496  * No presorted keys or incremental sort disabled, just perform a
4497  * complete sort.
4498  */
4499  if (presorted_keys == 0 || !enable_incremental_sort)
4500  path = (Path *) create_sort_path(root, window_rel,
4501  path,
4502  window_pathkeys,
4503  -1.0);
4504  else
4505  {
4506  /*
4507  * Since we have presorted keys and incremental sort is
4508  * enabled, just use incremental sort.
4509  */
4510  path = (Path *) create_incremental_sort_path(root,
4511  window_rel,
4512  path,
4513  window_pathkeys,
4514  presorted_keys,
4515  -1.0);
4516  }
4517  }
4518 
4519  if (lnext(activeWindows, l))
4520  {
4521  /*
4522  * Add the current WindowFuncs to the output target for this
4523  * intermediate WindowAggPath. We must copy window_target to
4524  * avoid changing the previous path's target.
4525  *
4526  * Note: a WindowFunc adds nothing to the target's eval costs; but
4527  * we do need to account for the increase in tlist width.
4528  */
4529  int64 tuple_width = window_target->width;
4530  ListCell *lc2;
4531 
4532  window_target = copy_pathtarget(window_target);
4533  foreach(lc2, wflists->windowFuncs[wc->winref])
4534  {
4535  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4536 
4537  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4538  tuple_width += get_typavgwidth(wfunc->wintype, -1);
4539  }
4540  window_target->width = clamp_width_est(tuple_width);
4541  }
4542  else
4543  {
4544  /* Install the goal target in the topmost WindowAgg */
4545  window_target = output_target;
4546  }
4547 
4548  /* mark the final item in the list as the top-level window */
4549  topwindow = foreach_current_index(l) == list_length(activeWindows) - 1;
4550 
4551  /*
4552  * Accumulate all of the runConditions from each intermediate
4553  * WindowClause. The top-level WindowAgg must pass these as a qual so
4554  * that it filters out unwanted tuples correctly.
4555  */
4556  if (!topwindow)
4557  topqual = list_concat(topqual, wc->runCondition);
4558 
4559  path = (Path *)
4560  create_windowagg_path(root, window_rel, path, window_target,
4561  wflists->windowFuncs[wc->winref],
4562  wc, topwindow ? topqual : NIL, topwindow);
4563  }
4564 
4565  add_path(window_rel, path);
4566 }
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:232
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2533
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause, List *qual, bool topwindow)
Definition: pathnode.c:3469
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5951
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(), clamp_width_est(), 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 5056 of file planner.c.

5061 {
5062  Path *cheapest_input_path = input_rel->cheapest_total_path;
5063  RelOptInfo *ordered_rel;
5064  ListCell *lc;
5065 
5066  /* For now, do all work in the (ORDERED, NULL) upperrel */
5067  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
5068 
5069  /*
5070  * If the input relation is not parallel-safe, then the ordered relation
5071  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
5072  * target list is parallel-safe.
5073  */
5074  if (input_rel->consider_parallel && target_parallel_safe)
5075  ordered_rel->consider_parallel = true;
5076 
5077  /*
5078  * If the input rel belongs to a single FDW, so does the ordered_rel.
5079  */
5080  ordered_rel->serverid = input_rel->serverid;
5081  ordered_rel->userid = input_rel->userid;
5082  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
5083  ordered_rel->fdwroutine = input_rel->fdwroutine;
5084 
5085  foreach(lc, input_rel->pathlist)
5086  {
5087  Path *input_path = (Path *) lfirst(lc);
5088  Path *sorted_path;
5089  bool is_sorted;
5090  int presorted_keys;
5091 
5092  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5093  input_path->pathkeys, &presorted_keys);
5094 
5095  if (is_sorted)
5096  sorted_path = input_path;
5097  else
5098  {
5099  /*
5100  * Try at least sorting the cheapest path and also try
5101  * incrementally sorting any path which is partially sorted
5102  * already (no need to deal with paths which have presorted keys
5103  * when incremental sort is disabled unless it's the cheapest
5104  * input path).
5105  */
5106  if (input_path != cheapest_input_path &&
5107  (presorted_keys == 0 || !enable_incremental_sort))
5108  continue;
5109 
5110  /*
5111  * We've no need to consider both a sort and incremental sort.
5112  * We'll just do a sort if there are no presorted keys and an
5113  * incremental sort when there are presorted keys.
5114  */
5115  if (presorted_keys == 0 || !enable_incremental_sort)
5116  sorted_path = (Path *) create_sort_path(root,
5117  ordered_rel,
5118  input_path,
5119  root->sort_pathkeys,
5120  limit_tuples);
5121  else
5122  sorted_path = (Path *) create_incremental_sort_path(root,
5123  ordered_rel,
5124  input_path,
5125  root->sort_pathkeys,
5126  presorted_keys,
5127  limit_tuples);
5128  }
5129 
5130  /* Add projection step if needed */
5131  if (sorted_path->pathtarget != target)
5132  sorted_path = apply_projection_to_path(root, ordered_rel,
5133  sorted_path, target);
5134 
5135  add_path(ordered_rel, sorted_path);
5136  }
5137 
5138  /*
5139  * generate_gather_paths() will have already generated a simple Gather
5140  * path for the best parallel path, if any, and the loop above will have
5141  * considered sorting it. Similarly, generate_gather_paths() will also
5142  * have generated order-preserving Gather Merge plans which can be used
5143  * without sorting if they happen to match the sort_pathkeys, and the loop
5144  * above will have handled those as well. However, there's one more
5145  * possibility: it may make sense to sort the cheapest partial path or
5146  * incrementally sort any partial path that is partially sorted according
5147  * to the required output order and then use Gather Merge.
5148  */
5149  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5150  input_rel->partial_pathlist != NIL)
5151  {
5152  Path *cheapest_partial_path;
5153 
5154  cheapest_partial_path = linitial(input_rel->partial_pathlist);
5155 
5156  foreach(lc, input_rel->partial_pathlist)
5157  {
5158  Path *input_path = (Path *) lfirst(lc);
5159  Path *sorted_path;
5160  bool is_sorted;
5161  int presorted_keys;
5162  double total_groups;
5163 
5164  is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5165  input_path->pathkeys,
5166  &presorted_keys);
5167 
5168  if (is_sorted)
5169  continue;
5170 
5171  /*
5172  * Try at least sorting the cheapest path and also try
5173  * incrementally sorting any path which is partially sorted
5174  * already (no need to deal with paths which have presorted keys
5175  * when incremental sort is disabled unless it's the cheapest
5176  * partial path).
5177  */
5178  if (input_path != cheapest_partial_path &&
5179  (presorted_keys == 0 || !enable_incremental_sort))
5180  continue;
5181 
5182  /*
5183  * We've no need to consider both a sort and incremental sort.
5184  * We'll just do a sort if there are no presorted keys and an
5185  * incremental sort when there are presorted keys.
5186  */
5187  if (presorted_keys == 0 || !enable_incremental_sort)
5188  sorted_path = (Path *) create_sort_path(root,
5189  ordered_rel,
5190  input_path,
5191  root->sort_pathkeys,
5192  limit_tuples);
5193  else
5194  sorted_path = (Path *) create_incremental_sort_path(root,
5195  ordered_rel,
5196  input_path,
5197  root->sort_pathkeys,
5198  presorted_keys,
5199  limit_tuples);
5200  total_groups = input_path->rows *
5201  input_path->parallel_workers;
5202  sorted_path = (Path *)
5203  create_gather_merge_path(root, ordered_rel,
5204  sorted_path,
5205  sorted_path->pathtarget,
5206  root->sort_pathkeys, NULL,
5207  &total_groups);
5208 
5209  /* Add projection step if needed */
5210  if (sorted_path->pathtarget != target)
5211  sorted_path = apply_projection_to_path(root, ordered_rel,
5212  sorted_path, target);
5213 
5214  add_path(ordered_rel, sorted_path);
5215  }
5216  }
5217 
5218  /*
5219  * If there is an FDW that's responsible for all baserels of the query,
5220  * let it consider adding ForeignPaths.
5221  */
5222  if (ordered_rel->fdwroutine &&
5223  ordered_rel->fdwroutine->GetForeignUpperPaths)
5224  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5225  input_rel, ordered_rel,
5226  NULL);
5227 
5228  /* Let extensions possibly add some more paths */
5230  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5231  input_rel, ordered_rel, NULL);
5232 
5233  /*
5234  * No need to bother with set_cheapest here; grouping_planner does not
5235  * need us to do it.
5236  */
5237  Assert(ordered_rel->pathlist != NIL);
5238 
5239  return ordered_rel;
5240 }
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1877
@ UPPERREL_ORDERED
Definition: pathnodes.h:78
int parallel_workers
Definition: pathnodes.h:1637

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, NIL, Path::parallel_workers, RelOptInfo::partial_pathlist, Path::pathkeys, 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 3859 of file planner.c.

3865 {
3866  Path *cheapest_path = input_rel->cheapest_total_path;
3867  RelOptInfo *partially_grouped_rel = NULL;
3868  double dNumGroups;
3870 
3871  /*
3872  * If this is the topmost grouping relation or if the parent relation is
3873  * doing some form of partitionwise aggregation, then we may be able to do
3874  * it at this level also. However, if the input relation is not
3875  * partitioned, partitionwise aggregate is impossible.
3876  */
3877  if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
3878  IS_PARTITIONED_REL(input_rel))
3879  {
3880  /*
3881  * If this is the topmost relation or if the parent relation is doing
3882  * full partitionwise aggregation, then we can do full partitionwise
3883  * aggregation provided that the GROUP BY clause contains all of the
3884  * partitioning columns at this level. Otherwise, we can do at most
3885  * partial partitionwise aggregation. But if partial aggregation is
3886  * not supported in general then we can't use it for partitionwise
3887  * aggregation either.
3888  *
3889  * Check parse->groupClause not processed_groupClause, because it's
3890  * okay if some of the partitioning columns were proved redundant.
3891  */
3892  if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
3893  group_by_has_partkey(input_rel, extra->targetList,
3894  root->parse->groupClause))
3896  else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3898  else
3900  }
3901 
3902  /*
3903  * Before generating paths for grouped_rel, we first generate any possible
3904  * partially grouped paths; that way, later code can easily consider both
3905  * parallel and non-parallel approaches to grouping.
3906  */
3907  if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
3908  {
3909  bool force_rel_creation;
3910 
3911  /*
3912  * If we're doing partitionwise aggregation at this level, force
3913  * creation of a partially_grouped_rel so we can add partitionwise
3914  * paths to it.
3915  */
3916  force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
3917 
3918  partially_grouped_rel =
3920  grouped_rel,
3921  input_rel,
3922  gd,
3923  extra,
3924  force_rel_creation);
3925  }
3926 
3927  /* Set out parameter. */
3928  *partially_grouped_rel_p = partially_grouped_rel;
3929 
3930  /* Apply partitionwise aggregation technique, if possible. */
3931  if (patype != PARTITIONWISE_AGGREGATE_NONE)
3932  create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
3933  partially_grouped_rel, agg_costs,
3934  gd, patype, extra);
3935 
3936  /* If we are doing partial aggregation only, return. */
3938  {
3939  Assert(partially_grouped_rel);
3940 
3941  if (partially_grouped_rel->pathlist)
3942  set_cheapest(partially_grouped_rel);
3943 
3944  return;
3945  }
3946 
3947  /* Gather any partially grouped partial paths. */
3948  if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
3949  {
3950  gather_grouping_paths(root, partially_grouped_rel);
3951  set_cheapest(partially_grouped_rel);
3952  }
3953 
3954  /*
3955  * Estimate number of groups.
3956  */
3957  dNumGroups = get_number_of_groups(root,
3958  cheapest_path->rows,
3959  gd,
3960  extra->targetList);
3961 
3962  /* Build final grouping paths */
3963  add_paths_to_grouping_rel(root, input_rel, grouped_rel,
3964  partially_grouped_rel, agg_costs, gd,
3965  dNumGroups, extra);
3966 
3967  /* Give a helpful error if we failed to find any implementation */
3968  if (grouped_rel->pathlist == NIL)
3969  ereport(ERROR,
3970  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3971  errmsg("could not implement GROUP BY"),
3972  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
3973 
3974  /*
3975  * If there is an FDW that's responsible for all baserels of the query,
3976  * let it consider adding ForeignPaths.
3977  */
3978  if (grouped_rel->fdwroutine &&
3979  grouped_rel->fdwroutine->GetForeignUpperPaths)
3980  grouped_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG,
3981  input_rel, grouped_rel,
3982  extra);
3983 
3984  /* Let extensions possibly add some more paths */
3986  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
3987  input_rel, grouped_rel,
3988  extra);
3989 }
PartitionwiseAggregateType
Definition: pathnodes.h:3243
@ PARTITIONWISE_AGGREGATE_PARTIAL
Definition: pathnodes.h:3246
@ 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:7027
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:6792
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3486
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:7677
static bool group_by_has_partkey(RelOptInfo *input_rel, List *targetList, List *groupClause)
Definition: planner.c:7821
List * groupClause
Definition: parsenodes.h:190

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,
PathTarget target 
)
static

Definition at line 4650 of file planner.c.

4653 {
4654  RelOptInfo *partial_distinct_rel;
4655  Query *parse;
4656  List *distinctExprs;
4657  double numDistinctRows;
4658  Path *cheapest_partial_path;
4659  ListCell *lc;
4660 
4661  /* nothing to do when there are no partial paths in the input rel */
4662  if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
4663  return;
4664 
4665  parse = root->parse;
4666 
4667  /* can't do parallel DISTINCT ON */
4668  if (parse->hasDistinctOn)
4669  return;
4670 
4671  partial_distinct_rel = fetch_upper_rel(root, UPPERREL_PARTIAL_DISTINCT,
4672  NULL);
4673  partial_distinct_rel->reltarget = target;
4674  partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
4675 
4676  /*
4677  * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
4678  */
4679  partial_distinct_rel->serverid = input_rel->serverid;
4680  partial_distinct_rel->userid = input_rel->userid;
4681  partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4682  partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
4683 
4684  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4685 
4686  distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
4687  parse->targetList);
4688 
4689  /* estimate how many distinct rows we'll get from each worker */
4690  numDistinctRows = estimate_num_groups(root, distinctExprs,
4691  cheapest_partial_path->rows,
4692  NULL, NULL);
4693 
4694  /*
4695  * Try sorting the cheapest path and incrementally sorting any paths with
4696  * presorted keys and put a unique paths atop of those.
4697  */
4699  {
4700  foreach(lc, input_rel->partial_pathlist)
4701  {
4702  Path *input_path = (Path *) lfirst(lc);
4703  Path *sorted_path;
4704  bool is_sorted;
4705  int presorted_keys;
4706 
4708  input_path->pathkeys,
4709  &presorted_keys);
4710 
4711  if (is_sorted)
4712  sorted_path = input_path;
4713  else
4714  {
4715  /*
4716  * Try at least sorting the cheapest path and also try
4717  * incrementally sorting any path which is partially sorted
4718  * already (no need to deal with paths which have presorted
4719  * keys when incremental sort is disabled unless it's the
4720  * cheapest partial path).
4721  */
4722  if (input_path != cheapest_partial_path &&
4723  (presorted_keys == 0 || !enable_incremental_sort))
4724  continue;
4725 
4726  /*
4727  * We've no need to consider both a sort and incremental sort.
4728  * We'll just do a sort if there are no presorted keys and an
4729  * incremental sort when there are presorted keys.
4730  */
4731  if (presorted_keys == 0 || !enable_incremental_sort)
4732  sorted_path = (Path *) create_sort_path(root,
4733  partial_distinct_rel,
4734  input_path,
4735  root->distinct_pathkeys,
4736  -1.0);
4737  else
4738  sorted_path = (Path *) create_incremental_sort_path(root,
4739  partial_distinct_rel,
4740  input_path,
4741  root->distinct_pathkeys,
4742  presorted_keys,
4743  -1.0);
4744  }
4745 
4746  /*
4747  * An empty distinct_pathkeys means all tuples have the same value
4748  * for the DISTINCT clause. See create_final_distinct_paths()
4749  */
4750  if (root->distinct_pathkeys == NIL)
4751  {
4752  Node *limitCount;
4753 
4754  limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
4755  sizeof(int64),
4756  Int64GetDatum(1), false,
4757  FLOAT8PASSBYVAL);
4758 
4759  /*
4760  * Apply a LimitPath onto the partial path to restrict the
4761  * tuples from each worker to 1. create_final_distinct_paths
4762  * will need to apply an additional LimitPath to restrict this
4763  * to a single row after the Gather node. If the query
4764  * already has a LIMIT clause, then we could end up with three
4765  * Limit nodes in the final plan. Consolidating the top two
4766  * of these could be done, but does not seem worth troubling
4767  * over.
4768  */
4769  add_partial_path(partial_distinct_rel, (Path *)
4770  create_limit_path(root, partial_distinct_rel,
4771  sorted_path,
4772  NULL,
4773  limitCount,
4775  0, 1));
4776  }
4777  else
4778  {
4779  add_partial_path(partial_distinct_rel, (Path *)
4780  create_upper_unique_path(root, partial_distinct_rel,
4781  sorted_path,
4783  numDistinctRows));
4784  }
4785  }
4786  }
4787 
4788  /*
4789  * Now try hash aggregate paths, if enabled and hashing is possible. Since
4790  * we're not on the hook to ensure we do our best to create at least one
4791  * path here, we treat enable_hashagg as a hard off-switch rather than the
4792  * slightly softer variant in create_final_distinct_paths.
4793  */
4795  {
4796  add_partial_path(partial_distinct_rel, (Path *)
4797  create_agg_path(root,
4798  partial_distinct_rel,
4799  cheapest_partial_path,
4800  cheapest_partial_path->pathtarget,
4801  AGG_HASHED,
4804  NIL,
4805  NULL,
4806  numDistinctRows));
4807  }
4808 
4809  /*
4810  * If there is an FDW that's responsible for all baserels of the query,
4811  * let it consider adding ForeignPaths.
4812  */
4813  if (partial_distinct_rel->fdwroutine &&
4814  partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
4815  partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
4817  input_rel,
4818  partial_distinct_rel,
4819  NULL);
4820 
4821  /* Let extensions possibly add some more partial paths */
4823  (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
4824  input_rel, partial_distinct_rel, NULL);
4825 
4826  if (partial_distinct_rel->partial_pathlist != NIL)
4827  {
4828  generate_useful_gather_paths(root, partial_distinct_rel, true);
4829  set_cheapest(partial_distinct_rel);
4830 
4831  /*
4832  * Finally, create paths to distinctify the final result. This step
4833  * is needed to remove any duplicates due to combining rows from
4834  * parallel workers.
4835  */
4836  create_final_distinct_paths(root, partial_distinct_rel,
4837  final_distinct_rel);
4838  }
4839 }
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_limit_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(), FLOAT8PASSBYVAL, generate_useful_gather_paths(), get_sortgrouplist_exprs(), grouping_is_hashable(), grouping_is_sortable(), Int64GetDatum(), InvalidOid, lfirst, LIMIT_OPTION_COUNT, linitial, list_length(), makeConst(), 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 7027 of file planner.c.

7033 {
7034  Query *parse = root->parse;
7035  RelOptInfo *partially_grouped_rel;
7036  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
7037  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7038  Path *cheapest_partial_path = NULL;
7039  Path *cheapest_total_path = NULL;
7040  double dNumPartialGroups = 0;
7041  double dNumPartialPartialGroups = 0;
7042  ListCell *lc;
7043  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7044  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7045 
7046  /*
7047  * Consider whether we should generate partially aggregated non-partial
7048  * paths. We can only do this if we have a non-partial path, and only if
7049  * the parent of the input rel is performing partial partitionwise
7050  * aggregation. (Note that extra->patype is the type of partitionwise
7051  * aggregation being used at the parent level, not this level.)
7052  */
7053  if (input_rel->pathlist != NIL &&
7055  cheapest_total_path = input_rel->cheapest_total_path;
7056 
7057  /*
7058  * If parallelism is possible for grouped_rel, then we should consider
7059  * generating partially-grouped partial paths. However, if the input rel
7060  * has no partial paths, then we can't.
7061  */
7062  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
7063  cheapest_partial_path = linitial(input_rel->partial_pathlist);
7064 
7065  /*
7066  * If we can't partially aggregate partial paths, and we can't partially
7067  * aggregate non-partial paths, then don't bother creating the new
7068  * RelOptInfo at all, unless the caller specified force_rel_creation.
7069  */
7070  if (cheapest_total_path == NULL &&
7071  cheapest_partial_path == NULL &&
7072  !force_rel_creation)
7073  return NULL;
7074 
7075  /*
7076  * Build a new upper relation to represent the result of partially
7077  * aggregating the rows from the input relation.
7078  */
7079  partially_grouped_rel = fetch_upper_rel(root,
7081  grouped_rel->relids);
7082  partially_grouped_rel->consider_parallel =
7083  grouped_rel->consider_parallel;
7084  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
7085  partially_grouped_rel->serverid = grouped_rel->serverid;
7086  partially_grouped_rel->userid = grouped_rel->userid;
7087  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
7088  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
7089 
7090  /*
7091  * Build target list for partial aggregate paths. These paths cannot just
7092  * emit the same tlist as regular aggregate paths, because (1) we must
7093  * include Vars and Aggrefs needed in HAVING, which might not appear in
7094  * the result tlist, and (2) the Aggrefs must be set in partial mode.
7095  */
7096  partially_grouped_rel->reltarget =
7097  make_partial_grouping_target(root, grouped_rel->reltarget,
7098  extra->havingQual);
7099 
7100  if (!extra->partial_costs_set)
7101  {
7102  /*
7103  * Collect statistics about aggregates for estimating costs of
7104  * performing aggregation in parallel.
7105  */
7106  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
7107  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
7108  if (parse->hasAggs)
7109  {
7110  /* partial phase */
7112  agg_partial_costs);
7113 
7114  /* final phase */
7116  agg_final_costs);
7117  }
7118 
7119  extra->partial_costs_set = true;
7120  }
7121 
7122  /* Estimate number of partial groups. */
7123  if (cheapest_total_path != NULL)
7124  dNumPartialGroups =
7125  get_number_of_groups(root,
7126  cheapest_total_path->rows,
7127  gd,
7128  extra->targetList);
7129  if (cheapest_partial_path != NULL)
7130  dNumPartialPartialGroups =
7131  get_number_of_groups(root,
7132  cheapest_partial_path->rows,
7133  gd,
7134  extra->targetList);
7135 
7136  if (can_sort && cheapest_total_path != NULL)
7137  {
7138  /* This should have been checked previously */
7139  Assert(parse->hasAggs || parse->groupClause);
7140 
7141  /*
7142  * Use any available suitably-sorted path as input, and also consider
7143  * sorting the cheapest partial path.
7144  */
7145  foreach(lc, input_rel->pathlist)
7146  {
7147  ListCell *lc2;
7148  Path *path = (Path *) lfirst(lc);
7149  Path *path_save = path;
7150  List *pathkey_orderings = NIL;
7151 
7152  /* generate alternative group orderings that might be useful */
7153  pathkey_orderings = get_useful_group_keys_orderings(root, path);
7154 
7155  Assert(list_length(pathkey_orderings) > 0);
7156 
7157  /* process all potentially interesting grouping reorderings */
7158  foreach(lc2, pathkey_orderings)
7159  {
7160  PathKeyInfo *info = (PathKeyInfo *) lfirst(lc2);
7161 
7162  /* restore the path (we replace it in the loop) */
7163  path = path_save;
7164 
7165  path = make_ordered_path(root,
7166  partially_grouped_rel,
7167  path,
7168  cheapest_total_path,
7169  info->pathkeys);
7170 
7171  if (path == NULL)
7172  continue;
7173 
7174  if (parse->hasAggs)
7175  add_path(partially_grouped_rel, (Path *)
7176  create_agg_path(root,
7177  partially_grouped_rel,
7178  path,
7179  partially_grouped_rel->reltarget,
7180  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7182  info->clauses,
7183  NIL,
7184  agg_partial_costs,
7185  dNumPartialGroups));
7186  else
7187  add_path(partially_grouped_rel, (Path *)
7188  create_group_path(root,
7189  partially_grouped_rel,
7190  path,
7191  info->clauses,
7192  NIL,
7193  dNumPartialGroups));
7194  }
7195  }
7196  }
7197 
7198  if (can_sort && cheapest_partial_path != NULL)
7199  {
7200  /* Similar to above logic, but for partial paths. */
7201  foreach(lc, input_rel->partial_pathlist)
7202  {
7203  ListCell *lc2;
7204  Path *path = (Path *) lfirst(lc);
7205  Path *path_save = path;
7206  List *pathkey_orderings = NIL;
7207 
7208  /* generate alternative group orderings that might be useful */
7209  pathkey_orderings = get_useful_group_keys_orderings(root, path);
7210 
7211  Assert(list_length(pathkey_orderings) > 0);
7212 
7213  /* process all potentially interesting grouping reorderings */
7214  foreach(lc2, pathkey_orderings)
7215  {
7216  PathKeyInfo *info = (PathKeyInfo *) lfirst(lc2);
7217 
7218 
7219  /* restore the path (we replace it in the loop) */
7220  path = path_save;
7221 
7222  path = make_ordered_path(root,
7223  partially_grouped_rel,
7224  path,
7225  cheapest_partial_path,
7226  info->pathkeys);
7227 
7228  if (path == NULL)
7229  continue;
7230 
7231  if (parse->hasAggs)
7232  add_partial_path(partially_grouped_rel, (Path *)
7233  create_agg_path(root,
7234  partially_grouped_rel,
7235  path,
7236  partially_grouped_rel->reltarget,
7237  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7239  info->clauses,
7240  NIL,
7241  agg_partial_costs,
7242  dNumPartialPartialGroups));
7243  else
7244  add_partial_path(partially_grouped_rel, (Path *)
7245  create_group_path(root,
7246  partially_grouped_rel,
7247  path,
7248  info->clauses,
7249  NIL,
7250  dNumPartialPartialGroups));
7251  }
7252  }
7253  }
7254 
7255  /*
7256  * Add a partially-grouped HashAgg Path where possible
7257  */
7258  if (can_hash && cheapest_total_path != NULL)
7259  {
7260  /* Checked above */
7261  Assert(parse->hasAggs || parse->groupClause);
7262 
7263  add_path(partially_grouped_rel, (Path *)
7264  create_agg_path(root,
7265  partially_grouped_rel,
7266  cheapest_total_path,
7267  partially_grouped_rel->reltarget,
7268  AGG_HASHED,
7270  root->processed_groupClause,
7271  NIL,
7272  agg_partial_costs,
7273  dNumPartialGroups));
7274  }
7275 
7276  /*
7277  * Now add a partially-grouped HashAgg partial Path where possible
7278  */
7279  if (can_hash && cheapest_partial_path != NULL)
7280  {
7281  add_partial_path(partially_grouped_rel, (Path *)
7282  create_agg_path(root,
7283  partially_grouped_rel,
7284  cheapest_partial_path,
7285  partially_grouped_rel->reltarget,
7286  AGG_HASHED,
7288  root->processed_groupClause,
7289  NIL,
7290  agg_partial_costs,
7291  dNumPartialPartialGroups));
7292  }
7293 
7294  /*
7295  * If there is an FDW that's responsible for all baserels of the query,
7296  * let it consider adding partially grouped ForeignPaths.
7297  */
7298  if (partially_grouped_rel->fdwroutine &&
7299  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
7300  {
7301  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
7302 
7303  fdwroutine->GetForeignUpperPaths(root,
7305  input_rel, partially_grouped_rel,
7306  extra);
7307  }
7308 
7309  return partially_grouped_rel;
7310 }
@ AGGSPLIT_INITIAL_SERIAL
Definition: nodes.h:368
@ UPPERREL_PARTIAL_GROUP_AGG
Definition: pathnodes.h:72
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:5359
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:226
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:3267
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, PathKeyInfo::clauses, RelOptInfo::consider_parallel, create_agg_path(), create_group_path(), fetch_upper_rel(), GroupPathExtraData::flags, get_agg_clause_costs(), get_number_of_groups(), get_useful_group_keys_orderings(), FdwRoutine::GetForeignUpperPaths, GROUPING_CAN_USE_HASH, GROUPING_CAN_USE_SORT, GroupPathExtraData::havingQual, lfirst, linitial, list_length(), make_ordered_path(), make_partial_grouping_target(), MemSet, NIL, parse(), PlannerInfo::parse, GroupPathExtraData::partial_costs_set, RelOptInfo::partial_pathlist, PARTITIONWISE_AGGREGATE_PARTIAL, PathKeyInfo::pathkeys, 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 7677 of file planner.c.

7685 {
7686  List *grouped_live_children = NIL;
7687  List *partially_grouped_live_children = NIL;
7688  PathTarget *target = grouped_rel->reltarget;
7689  bool partial_grouping_valid = true;
7690  int i;
7691 
7694  partially_grouped_rel != NULL);
7695 
7696  /* Add paths for partitionwise aggregation/grouping. */
7697  i = -1;
7698  while ((i = bms_next_member(input_rel->live_parts, i)) >= 0)
7699  {
7700  RelOptInfo *child_input_rel = input_rel->part_rels[i];
7701  PathTarget *child_target;
7702  AppendRelInfo **appinfos;
7703  int nappinfos;
7704  GroupPathExtraData child_extra;
7705  RelOptInfo *child_grouped_rel;
7706  RelOptInfo *child_partially_grouped_rel;
7707 
7708  Assert(child_input_rel != NULL);
7709 
7710  /* Dummy children can be ignored. */
7711  if (IS_DUMMY_REL(child_input_rel))
7712  continue;
7713 
7714  child_target = copy_pathtarget(target);
7715 
7716  /*
7717  * Copy the given "extra" structure as is and then override the
7718  * members specific to this child.
7719  */
7720  memcpy(&child_extra, extra, sizeof(child_extra));
7721 
7722  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7723  &nappinfos);
7724 
7725  child_target->exprs = (List *)
7727  (Node *) target->exprs,
7728  nappinfos, appinfos);
7729 
7730  /* Translate havingQual and targetList. */
7731  child_extra.havingQual = (Node *)
7733  extra->havingQual,
7734  nappinfos, appinfos);
7735  child_extra.targetList = (List *)
7737  (Node *) extra->targetList,
7738  nappinfos, appinfos);
7739 
7740  /*
7741  * extra->patype was the value computed for our parent rel; patype is
7742  * the value for this relation. For the child, our value is its
7743  * parent rel's value.
7744  */
7745  child_extra.patype = patype;
7746 
7747  /*
7748  * Create grouping relation to hold fully aggregated grouping and/or
7749  * aggregation paths for the child.
7750  */
7751  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7752  child_target,
7753  extra->target_parallel_safe,
7754  child_extra.havingQual);
7755 
7756  /* Create grouping paths for this child relation. */
7757  create_ordinary_grouping_paths(root, child_input_rel,
7758  child_grouped_rel,
7759  agg_costs, gd, &child_extra,
7760  &child_partially_grouped_rel);
7761 
7762  if (child_partially_grouped_rel)
7763  {
7764  partially_grouped_live_children =
7765  lappend(partially_grouped_live_children,
7766  child_partially_grouped_rel);
7767  }
7768  else
7769  partial_grouping_valid = false;
7770 
7771  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7772  {
7773  set_cheapest(child_grouped_rel);
7774  grouped_live_children = lappend(grouped_live_children,
7775  child_grouped_rel);
7776  }
7777 
7778  pfree(appinfos);
7779  }
7780 
7781  /*
7782  * Try to create append paths for partially grouped children. For full
7783  * partitionwise aggregation, we might have paths in the partial_pathlist
7784  * if parallel aggregation is possible. For partial partitionwise
7785  * aggregation, we may have paths in both pathlist and partial_pathlist.
7786  *
7787  * NB: We must have a partially grouped path for every child in order to
7788  * generate a partially grouped path for this relation.
7789  */
7790  if (partially_grouped_rel && partial_grouping_valid)
7791  {
7792  Assert(partially_grouped_live_children != NIL);
7793 
7794  add_paths_to_append_rel(root, partially_grouped_rel,
7795  partially_grouped_live_children);
7796 
7797  /*
7798  * We need call set_cheapest, since the finalization step will use the
7799  * cheapest path from the rel.
7800  */
7801  if (partially_grouped_rel->pathlist)
7802  set_cheapest(partially_grouped_rel);
7803  }
7804 
7805  /* If possible, create append paths for fully grouped children. */
7806  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7807  {
7808  Assert(grouped_live_children != NIL);
7809 
7810  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7811  }
7812 }

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

4367 {
4368  RelOptInfo *window_rel;
4369  ListCell *lc;
4370 
4371  /* For now, do all work in the (WINDOW, NULL) upperrel */
4372  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4373 
4374  /*
4375  * If the input relation is not parallel-safe, then the window relation
4376  * can't be parallel-safe, either. Otherwise, we need to examine the
4377  * target list and active windows for non-parallel-safe constructs.
4378  */
4379  if (input_rel->consider_parallel && output_target_parallel_safe &&
4380  is_parallel_safe(root, (Node *) activeWindows))
4381  window_rel->consider_parallel = true;
4382 
4383  /*
4384  * If the input rel belongs to a single FDW, so does the window rel.
4385  */
4386  window_rel->serverid = input_rel->serverid;
4387  window_rel->userid = input_rel->userid;
4388  window_rel->useridiscurrent = input_rel->useridiscurrent;
4389  window_rel->fdwroutine = input_rel->fdwroutine;
4390 
4391  /*
4392  * Consider computing window functions starting from the existing
4393  * cheapest-total path (which will likely require a sort) as well as any
4394  * existing paths that satisfy or partially satisfy root->window_pathkeys.
4395  */
4396  foreach(lc, input_rel->pathlist)
4397  {
4398  Path *path = (Path *) lfirst(lc);
4399  int presorted_keys;
4400 
4401  if (path == input_rel->cheapest_total_path ||
4403  &presorted_keys) ||
4404  presorted_keys > 0)
4406  window_rel,
4407  path,
4408  input_target,
4409  output_target,
4410  wflists,
4411  activeWindows);
4412  }
4413 
4414  /*
4415  * If there is an FDW that's responsible for all baserels of the query,
4416  * let it consider adding ForeignPaths.
4417  */
4418  if (window_rel->fdwroutine &&
4419  window_rel->fdwroutine->GetForeignUpperPaths)
4420  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4421  input_rel, window_rel,
4422  NULL);
4423 
4424  /* Let extensions possibly add some more paths */
4426  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4427  input_rel, window_rel, NULL);
4428 
4429  /* Now choose the best path(s) */
4430  set_cheapest(window_rel);
4431 
4432  return window_rel;
4433 }
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:736
@ 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:4447
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 6407 of file planner.c.

6408 {
6409  Node *result;
6410 
6411  /*
6412  * Convert named-argument function calls, insert default arguments and
6413  * simplify constant subexprs
6414  */
6415  result = eval_const_expressions(NULL, (Node *) expr);
6416 
6417  /* Fill in opfuncid values if missing */
6418  fix_opfuncids(result);
6419 
6420  return (Expr *) result;
6421 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2237
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1748

References eval_const_expressions(), and fix_opfuncids().

Referenced by ATExecAddColumn(), ATExecSetExpression(), ATPrepAlterColumnType(), BeginCopyFrom(), ComputePartitionAttrs(), contain_mutable_functions_after_planning(), contain_volatile_functions_after_planning(), 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 6434 of file planner.c.

6437 {
6438  Node *result;
6439  PlannerGlobal glob;
6440  PlannerInfo root;
6441 
6442  /* Make up dummy planner state so we can use setrefs machinery */
6443  MemSet(&glob, 0, sizeof(glob));
6444  glob.type = T_PlannerGlobal;
6445  glob.relationOids = NIL;
6446  glob.invalItems = NIL;
6447 
6448  MemSet(&root, 0, sizeof(root));
6449  root.type = T_PlannerInfo;
6450  root.glob = &glob;
6451 
6452  /*
6453  * Convert named-argument function calls, insert default arguments and
6454  * simplify constant subexprs. Collect identities of inlined functions
6455  * and elided domains, too.
6456  */
6457  result = eval_const_expressions(&root, (Node *) expr);
6458 
6459  /* Fill in opfuncid values if missing */
6460  fix_opfuncids(result);
6461 
6462  /*
6463  * Now walk the finished expression to find anything else we ought to
6464  * record as an expression dependency.
6465  */
6466  (void) extract_query_dependencies_walker(result, &root);
6467 
6468  *relationOids = glob.relationOids;
6469  *invalItems = glob.invalItems;
6470 
6471  return (Expr *) result;
6472 }
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3562
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 2843 of file planner.c.

2844 {
2845  int num_sets_raw = list_length(groupingSets);
2846  int num_empty = 0;
2847  int num_sets = 0; /* distinct sets */
2848  int num_chains = 0;
2849  List *result = NIL;
2850  List **results;
2851  List **orig_sets;
2852  Bitmapset **set_masks;
2853  int *chains;
2854  short **adjacency;
2855  short *adjacency_buf;
2857  int i;
2858  int j;
2859  int j_size;
2860  ListCell *lc1 = list_head(groupingSets);
2861  ListCell *lc;
2862 
2863  /*
2864  * Start by stripping out empty sets. The algorithm doesn't require this,
2865  * but the planner currently needs all empty sets to be returned in the
2866  * first list, so we strip them here and add them back after.
2867  */
2868  while (lc1 && lfirst(lc1) == NIL)
2869  {
2870  ++num_empty;
2871  lc1 = lnext(groupingSets, lc1);
2872  }
2873 
2874  /* bail out now if it turns out that all we had were empty sets. */
2875  if (!lc1)
2876  return list_make1(groupingSets);
2877 
2878  /*----------
2879  * We don't strictly need to remove duplicate sets here, but if we don't,
2880  * they tend to become scattered through the result, which is a bit
2881  * confusing (and irritating if we ever decide to optimize them out).
2882  * So we remove them here and add them back after.
2883  *
2884  * For each non-duplicate set, we fill in the following:
2885  *
2886  * orig_sets[i] = list of the original set lists
2887  * set_masks[i] = bitmapset for testing inclusion
2888  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
2889  *
2890  * chains[i] will be the result group this set is assigned to.
2891  *
2892  * We index all of these from 1 rather than 0 because it is convenient
2893  * to leave 0 free for the NIL node in the graph algorithm.
2894  *----------
2895  */
2896  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
2897  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
2898  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
2899  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
2900 
2901  j_size = 0;
2902  j = 0;
2903  i = 1;
2904 
2905  for_each_cell(lc, groupingSets, lc1)
2906  {
2907  List *candidate = (List *) lfirst(lc);
2908  Bitmapset *candidate_set = NULL;
2909  ListCell *lc2;
2910  int dup_of = 0;
2911 
2912  foreach(lc2, candidate)
2913  {
2914  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
2915  }
2916 
2917  /* we can only be a dup if we're the same length as a previous set */
2918  if (j_size == list_length(candidate))
2919  {
2920  int k;
2921 
2922  for (k = j; k < i; ++k)
2923  {
2924  if (bms_equal(set_masks[k], candidate_set))
2925  {
2926  dup_of = k;
2927  break;
2928  }
2929  }
2930  }
2931  else if (j_size < list_length(candidate))
2932  {
2933  j_size = list_length(candidate);
2934  j = i;
2935  }
2936 
2937  if (dup_of > 0)
2938  {
2939  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
2940  bms_free(candidate_set);
2941  }
2942  else
2943  {
2944  int k;
2945  int n_adj = 0;
2946 
2947  orig_sets[i] = list_make1(candidate);
2948  set_masks[i] = candidate_set;
2949 
2950  /* fill in adjacency list; no need to compare equal-size sets */
2951 
2952  for (k = j - 1; k > 0; --k)
2953  {
2954  if (bms_is_subset(set_masks[k], candidate_set))
2955  adjacency_buf[++n_adj] = k;
2956  }
2957 
2958  if (n_adj > 0)
2959  {
2960  adjacency_buf[0] = n_adj;
2961  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
2962  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
2963  }
2964  else
2965  adjacency[i] = NULL;
2966 
2967  ++i;
2968  }
2969  }
2970 
2971  num_sets = i - 1;
2972 
2973  /*
2974  * Apply the graph matching algorithm to do the work.
2975  */
2976  state = BipartiteMatch(num_sets, num_sets, adjacency);
2977 
2978  /*
2979  * Now, the state->pair* fields have the info we need to assign sets to
2980  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
2981  * pair_vu[v] = u (both will be true, but we check both so that we can do
2982  * it in one pass)
2983  */
2984  chains = palloc0((num_sets + 1) * sizeof(int));
2985 
2986  for (i = 1; i <= num_sets; ++i)
2987  {
2988  int u = state->pair_vu[i];
2989  int v = state->pair_uv[i];
2990 
2991  if (u > 0 && u < i)
2992  chains[i] = chains[u];
2993  else if (v > 0 && v < i)
2994  chains[i] = chains[v];
2995  else
2996  chains[i] = ++num_chains;
2997  }
2998 
2999  /* build result lists. */
3000  results = palloc0((num_chains + 1) * sizeof(List *));
3001 
3002  for (i = 1; i <= num_sets; ++i)
3003  {
3004  int c = chains[i];
3005 
3006  Assert(c > 0);
3007 
3008  results[c] = list_concat(results[c], orig_sets[i]);
3009  }
3010 
3011  /* push any empty sets back on the first list. */
3012  while (num_empty-- > 0)
3013  results[1] = lcons(NIL, results[1]);
3014 
3015  /* make result list */
3016  for (i = 1; i <= num_chains; ++i)
3017  result = lappend(result, results[i]);
3018 
3019  /*
3020  * Free all the things.
3021  *
3022  * (This is over-fussy for small sets but for large sets we could have
3023  * tied up a nontrivial amount of memory.)
3024  */
3026  pfree(results);
3027  pfree(chains);
3028  for (i = 1; i <= num_sets; ++i)
3029  if (adjacency[i])
3030  pfree(adjacency[i]);
3031  pfree(adjacency);
3032  pfree(adjacency_buf);
3033  pfree(orig_sets);
3034  for (i = 1; i <= num_sets; ++i)
3035  bms_free(set_masks[i]);
3036  pfree(set_masks);
3037 
3038  return result;
3039 }
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:155
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:425
void bms_free(Bitmapset *a)
Definition: bitmapset.c:252
int j
Definition: isn.c:74
void * palloc0(Size size)
Definition: mcxt.c:1232
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 7326 of file planner.c.

7327 {
7328  ListCell *lc;
7329  Path *cheapest_partial_path;
7330 
7331  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
7332  generate_useful_gather_paths(root, rel, true);
7333 
7334  cheapest_partial_path = linitial(rel->partial_pathlist);
7335 
7336  /* XXX Shouldn't this also consider the group-key-reordering? */
7337  foreach(lc, rel->partial_pathlist)
7338  {
7339  Path *path = (Path *) lfirst(lc);
7340  bool is_sorted;
7341  int presorted_keys;
7342  double total_groups;
7343 
7344  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7345  path->pathkeys,
7346  &presorted_keys);
7347 
7348  if (is_sorted)
7349  continue;
7350 
7351  /*
7352  * Try at least sorting the cheapest path and also try incrementally
7353  * sorting any path which is partially sorted already (no need to deal
7354  * with paths which have presorted keys when incremental sort is
7355  * disabled unless it's the cheapest input path).
7356  */
7357  if (path != cheapest_partial_path &&
7358  (presorted_keys == 0 || !enable_incremental_sort))
7359  continue;
7360 
7361  total_groups = path->rows * path->parallel_workers;
7362 
7363  /*
7364  * We've no need to consider both a sort and incremental sort. We'll
7365  * just do a sort if there are no presorted keys and an incremental
7366  * sort when there are presorted keys.
7367  */
7368  if (presorted_keys == 0 || !enable_incremental_sort)
7369  path = (Path *) create_sort_path(root, rel, path,
7370  root->group_pathkeys,
7371  -1.0);
7372  else
7373  path = (Path *) create_incremental_sort_path(root,
7374  rel,
7375  path,
7376  root->group_pathkeys,
7377  presorted_keys,
7378  -1.0);
7379 
7380  path = (Path *)
7382  rel,
7383  path,
7384  rel->reltarget,
7385  root->group_pathkeys,
7386  NULL,
7387  &total_groups);
7388 
7389  add_path(rel, path);
7390  }
7391 }

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, Path::parallel_workers, RelOptInfo::partial_pathlist, Path::pathkeys, 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 6248 of file planner.c.

6249 {
6250  Path *best_path = rel->cheapest_total_path;
6251  ListCell *l;
6252 
6253  /* If all tuples will be retrieved, just return the cheapest-total path */
6254  if (tuple_fraction <= 0.0)
6255  return best_path;
6256 
6257  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
6258  if (tuple_fraction >= 1.0 && best_path->rows > 0)
6259  tuple_fraction /= best_path->rows;
6260 
6261  foreach(l, rel->pathlist)
6262  {
6263  Path *path = (Path *) lfirst(l);
6264 
6265  if (path == rel->cheapest_total_path ||
6266  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
6267  continue;
6268 
6269  best_path = path;
6270  }
6271 
6272  return best_path;
6273 }
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 3486 of file planner.c.

3490 {
3491  Query *parse = root->parse;
3492  double dNumGroups;
3493 
3494  if (parse->groupClause)
3495  {
3496  List *groupExprs;
3497 
3498  if (parse->groupingSets)
3499  {
3500  /* Add up the estimates for each grouping set */
3501  ListCell *lc;
3502 
3503  Assert(gd); /* keep Coverity happy */
3504 
3505  dNumGroups = 0;
3506 
3507  foreach(lc, gd->rollups)
3508  {
3509  RollupData *rollup = lfirst_node(RollupData, lc);
3510  ListCell *lc2;
3511  ListCell *lc3;
3512 
3513  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3514  target_list);
3515 
3516  rollup->numGroups = 0.0;
3517 
3518  forboth(lc2, rollup->gsets, lc3, rollup->gsets_data)
3519  {
3520  List *gset = (List *) lfirst(lc2);
3522  double numGroups = estimate_num_groups(root,
3523  groupExprs,
3524  path_rows,
3525  &gset,
3526  NULL);
3527 
3528  gs->numGroups = numGroups;
3529  rollup->numGroups += numGroups;
3530  }
3531 
3532  dNumGroups += rollup->numGroups;
3533  }
3534 
3535  if (gd->hash_sets_idx)
3536  {
3537  ListCell *lc2;
3538 
3539  gd->dNumHashGroups = 0;
3540 
3541  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3542  target_list);
3543 
3544  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3545  {
3546  List *gset = (List *) lfirst(lc);
3548  double numGroups = estimate_num_groups(root,
3549  groupExprs,
3550  path_rows,
3551  &gset,
3552  NULL);
3553 
3554  gs->numGroups = numGroups;
3555  gd->dNumHashGroups += numGroups;
3556  }
3557 
3558  dNumGroups += gd->dNumHashGroups;
3559  }
3560  }
3561  else
3562  {
3563  /* Plain GROUP BY -- estimate based on optimized groupClause */
3565  target_list);
3566 
3567  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3568  NULL, NULL);
3569  }
3570  }
3571  else if (parse->groupingSets)
3572  {
3573  /* Empty grouping sets ... one result row for each one */
3574  dNumGroups = list_length(parse->groupingSets);
3575  }
3576  else if (parse->hasAggs || root->hasHavingQual)
3577  {
3578  /* Plain aggregation, one result row */
3579  dNumGroups = 1;
3580  }
3581  else
3582  {
3583  /* Not grouping */
3584  dNumGroups = 1;
3585  }
3586 
3587  return dNumGroups;
3588 }
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 7821 of file planner.c.

7824 {
7825  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7826  int cnt = 0;
7827  int partnatts;
7828 
7829  /* Input relation should be partitioned. */
7830  Assert(input_rel->part_scheme);
7831 
7832  /* Rule out early, if there are no partition keys present. */
7833  if (!input_rel->partexprs)
7834  return false;
7835 
7836  partnatts = input_rel->part_scheme->partnatts;
7837 
7838  for (cnt = 0; cnt < partnatts; cnt++)
7839  {
7840  List *partexprs = input_rel->partexprs[cnt];
7841  ListCell *lc;
7842  bool found = false;
7843 
7844  foreach(lc, partexprs)
7845  {
7846  Expr *partexpr = lfirst(lc);
7847 
7848  if (list_member(groupexprs, partexpr))
7849  {
7850  found = true;
7851  break;
7852  }
7853  }
7854 
7855  /*
7856  * If none of the partition key expressions match with any of the
7857  * GROUP BY expression, return false.
7858  */
7859  if (!found)
7860  return false;
7861  }
7862 
7863  return true;
7864 }
bool list_member(const List *list, const void *datum)
Definition: list.c:661

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

Referenced by create_ordinary_grouping_paths().

◆ groupclause_apply_groupingset()

static List * groupclause_apply_groupingset ( PlannerInfo root,
List force 
)
static

Definition at line 2807 of file planner.c.

2808 {
2809  Query *parse = root->parse;
2810  List *new_groupclause = NIL;
2811  ListCell *sl;
2812 
2813  foreach(sl, gset)
2814  {
2815  Index ref = lfirst_int(sl);
2816  SortGroupClause *cl = get_sortgroupref_clause(ref, parse->groupClause);
2817 
2818  new_groupclause = lappend(new_groupclause, cl);
2819  }
2820  return new_groupclause;
2821 }
unsigned int Index
Definition: c.h:603
SortGroupClause * get_sortgroupref_clause(Index sortref, List *clauses)
Definition: tlist.c:422

References get_sortgroupref_clause(), lappend(), lfirst_int, NIL, parse(), and PlannerInfo::parse.

Referenced by consider_groupingsets_paths(), and preprocess_grouping_sets().

◆ grouping_planner()

static void grouping_planner ( PlannerInfo root,
double  tuple_fraction 
)
static

Definition at line 1295 of file planner.c.

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

3104 {
3105  ListCell *lc;
3106 
3107  foreach(lc, keys)
3108  {
3109  PathKey *pathkey = lfirst_node(PathKey, lc);
3110 
3111  if (pathkey->pk_eclass->ec_has_volatile)
3112  return true;
3113  }
3114 
3115  return false;
3116 }

References lfirst_node.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ is_degenerate_grouping()

static bool is_degenerate_grouping ( PlannerInfo root)
static

Definition at line 3774 of file planner.c.

3775 {
3776  Query *parse = root->parse;
3777 
3778  return (root->hasHavingQual || parse->groupingSets) &&
3779  !parse->hasAggs && parse->groupClause == NIL;
3780 }

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

Referenced by create_grouping_paths().

◆ limit_needed()

bool limit_needed ( Query parse)

Definition at line 2603 of file planner.c.

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

5272 {
5273  Query *parse = root->parse;
5274  PathTarget *input_target;
5275  List *non_group_cols;
5276  List *non_group_vars;
5277  int i;
5278  ListCell *lc;
5279 
5280  /*
5281  * We must build a target containing all grouping columns, plus any other
5282  * Vars mentioned in the query's targetlist and HAVING qual.
5283  */
5284  input_target = create_empty_pathtarget();
5285  non_group_cols = NIL;
5286 
5287  i = 0;
5288  foreach(lc, final_target->exprs)
5289  {
5290  Expr *expr = (Expr *) lfirst(lc);
5291  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5292 
5293  if (sgref && root->processed_groupClause &&
5295  root->processed_groupClause) != NULL)
5296  {
5297  /*
5298  * It's a grouping column, so add it to the input target as-is.
5299  */
5300  add_column_to_pathtarget(input_target, expr, sgref);
5301  }
5302  else
5303  {
5304  /*
5305  * Non-grouping column, so just remember the expression for later
5306  * call to pull_var_clause.
5307  */
5308  non_group_cols = lappend(non_group_cols, expr);
5309  }
5310 
5311  i++;
5312  }
5313 
5314  /*
5315  * If there's a HAVING clause, we'll need the Vars it uses, too.
5316  */
5317  if (parse->havingQual)
5318  non_group_cols = lappend(non_group_cols, parse->havingQual);
5319 
5320  /*
5321  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5322  * add them to the input target if not already present. (A Var used
5323  * directly as a GROUP BY item will be present already.) Note this
5324  * includes Vars used in resjunk items, so we are covering the needs of
5325  * ORDER BY and window specifications. Vars used within Aggrefs and
5326  * WindowFuncs will be pulled out here, too.
5327  */
5328  non_group_vars = pull_var_clause((Node *) non_group_cols,
5332  add_new_columns_to_pathtarget(input_target, non_group_vars);
5333 
5334  /* clean up cruft */
5335  list_free(non_group_vars);
5336  list_free(non_group_cols);
5337 
5338  /* XXX this causes some redundant cost calculation ... */
5339  return set_pathtarget_cost_width(root, input_target);
5340 }
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:6287
void list_free(List *list)
Definition: list.c:1546
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:187
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:189
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
#define get_pathtarget_sortgroupref(target, colno)
Definition: pathnodes.h:1529
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 3721 of file planner.c.

3724 {
3725  RelOptInfo *grouped_rel;
3726 
3727  if (IS_OTHER_REL(input_rel))
3728  {
3729  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG,
3730  input_rel->relids);
3731  grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
3732  }
3733  else
3734  {
3735  /*
3736  * By tradition, the relids set for the main grouping relation is
3737  * NULL. (This could be changed, but might require adjustments
3738  * elsewhere.)
3739  */
3740  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
3741  }
3742 
3743  /* Set target. */
3744  grouped_rel->reltarget = target;
3745 
3746  /*
3747  * If the input relation is not parallel-safe, then the grouped relation
3748  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
3749  * target list and HAVING quals are parallel-safe.
3750  */
3751  if (input_rel->consider_parallel && target_parallel_safe &&
3752  is_parallel_safe(root, (Node *) havingQual))
3753  grouped_rel->consider_parallel = true;
3754 
3755  /*
3756  * If the input rel belongs to a single FDW, so does the grouped rel.
3757  */
3758  grouped_rel->serverid = input_rel->serverid;
3759  grouped_rel->userid = input_rel->userid;
3760  grouped_rel->useridiscurrent = input_rel->useridiscurrent;
3761  grouped_rel->fdwroutine = input_rel->fdwroutine;
3762 
3763  return grouped_rel;
3764 }
@ 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_ordered_path()

static Path* make_ordered_path ( PlannerInfo root,
RelOptInfo rel,
Path path,
Path cheapest_path,
List pathkeys 
)
static

Definition at line 6741 of file planner.c.

6743 {
6744  bool is_sorted;
6745  int presorted_keys;
6746 
6747  is_sorted = pathkeys_count_contained_in(pathkeys,
6748  path->pathkeys,
6749  &presorted_keys);
6750 
6751  if (!is_sorted)
6752  {
6753  /*
6754  * Try at least sorting the cheapest path and also try incrementally
6755  * sorting any path which is partially sorted already (no need to deal
6756  * with paths which have presorted keys when incremental sort is
6757  * disabled unless it's the cheapest input path).
6758  */
6759  if (path != cheapest_path &&
6760  (presorted_keys == 0 || !enable_incremental_sort))
6761  return NULL;
6762 
6763  /*
6764  * We've no need to consider both a sort and incremental sort. We'll
6765  * just do a sort if there are no presorted keys and an incremental
6766  * sort when there are presorted keys.
6767  */
6768  if (presorted_keys == 0 || !enable_incremental_sort)
6769  path = (Path *) create_sort_path(root,
6770  rel,
6771  path,
6772  pathkeys,
6773  -1.0);
6774  else
6775  path = (Path *) create_incremental_sort_path(root,
6776  rel,
6777  path,
6778  pathkeys,
6779  presorted_keys,
6780  -1.0);
6781  }
6782 
6783  return path;
6784 }

References create_incremental_sort_path(), create_sort_path(), enable_incremental_sort, Path::pathkeys, and pathkeys_count_contained_in().

Referenced by add_paths_to_grouping_rel(), and create_partial_grouping_paths().

◆ make_partial_grouping_target()

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

Definition at line 5359 of file planner.c.

5362 {
5363  PathTarget *partial_target;
5364  List *non_group_cols;
5365  List *non_group_exprs;
5366  int i;
5367  ListCell *lc;
5368 
5369  partial_target = create_empty_pathtarget();
5370  non_group_cols = NIL;
5371 
5372  i = 0;
5373  foreach(lc, grouping_target->exprs)
5374  {
5375  Expr *expr = (Expr *) lfirst(lc);
5376  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
5377 
5378  if (sgref && root->processed_groupClause &&
5380  root->processed_groupClause) != NULL)
5381  {
5382  /*
5383  * It's a grouping column, so add it to the partial_target as-is.
5384  * (This allows the upper agg step to repeat the grouping calcs.)
5385  */
5386  add_column_to_pathtarget(partial_target, expr, sgref);
5387  }
5388  else
5389  {
5390  /*
5391  * Non-grouping column, so just remember the expression for later
5392  * call to pull_var_clause.
5393  */
5394  non_group_cols = lappend(non_group_cols, expr);
5395  }
5396 
5397  i++;
5398  }
5399 
5400  /*
5401  * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
5402  */
5403  if (havingQual)
5404  non_group_cols = lappend(non_group_cols, havingQual);
5405 
5406  /*
5407  * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
5408  * non-group cols (plus HAVING), and add them to the partial_target if not
5409  * already present. (An expression used directly as a GROUP BY item will
5410  * be present already.) Note this includes Vars used in resjunk items, so
5411  * we are covering the needs of ORDER BY and window specifications.
5412  */
5413  non_group_exprs = pull_var_clause((Node *) non_group_cols,
5417 
5418  add_new_columns_to_pathtarget(partial_target, non_group_exprs);
5419 
5420  /*
5421  * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5422  * are at the top level of the target list, so we can just scan the list
5423  * rather than recursing through the expression trees.
5424  */
5425  foreach(lc, partial_target->exprs)
5426  {
5427  Aggref *aggref = (Aggref *) lfirst(lc);
5428 
5429  if (IsA(aggref, Aggref))
5430  {
5431  Aggref *newaggref;
5432 
5433  /*
5434  * We shouldn't need to copy the substructure of the Aggref node,
5435  * but flat-copy the node itself to avoid damaging other trees.
5436  */
5437  newaggref = makeNode(Aggref);
5438  memcpy(newaggref, aggref, sizeof(Aggref));
5439 
5440  /* For now, assume serialization is required */
5442 
5443  lfirst(lc) = newaggref;
5444  }
5445  }
5446 
5447  /* clean up cruft */
5448  list_free(non_group_exprs);
5449  list_free(non_group_cols);
5450 
5451  /* XXX this causes some redundant cost calculation ... */
5452  return set_pathtarget_cost_width(root, partial_target);
5453 }
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:186
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition: planner.c:5462

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

5953 {
5954  List *window_pathkeys = NIL;
5955 
5956  /* Throw error if can't sort */
5958  ereport(ERROR,
5959  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5960  errmsg("could not implement window PARTITION BY"),
5961  errdetail("Window partitioning columns must be of sortable datatypes.")));
5963  ereport(ERROR,
5964  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5965  errmsg("could not implement window ORDER BY"),
5966  errdetail("Window ordering columns must be of sortable datatypes.")));
5967 
5968  /*
5969  * First fetch the pathkeys for the PARTITION BY clause. We can safely
5970  * remove any clauses from the wc->partitionClause for redundant pathkeys.
5971  */
5972  if (wc->partitionClause != NIL)
5973  {
5974  bool sortable;
5975 
5976  window_pathkeys = make_pathkeys_for_sortclauses_extended(root,
5977  &wc->partitionClause,
5978  tlist,
5979  true,
5980  &sortable);
5981 
5982  Assert(sortable);
5983  }
5984 
5985  /*
5986  * In principle, we could also consider removing redundant ORDER BY items
5987  * too as doing so does not alter the result of peer row checks done by
5988  * the executor. However, we must *not* remove the ordering column for
5989  * RANGE OFFSET cases, as the executor needs that for in_range tests even
5990  * if it's known to be equal to some partitioning column.
5991  */
5992  if (wc->orderClause != NIL)
5993  {
5994  List *orderby_pathkeys;
5995 
5996  orderby_pathkeys = make_pathkeys_for_sortclauses(root,
5997  wc->orderClause,
5998  tlist);
5999 
6000  /* Okay, make the combined pathkeys */
6001  if (window_pathkeys != NIL)
6002  window_pathkeys = append_pathkeys(window_pathkeys, orderby_pathkeys);
6003  else
6004  window_pathkeys = orderby_pathkeys;
6005  }
6006 
6007  return window_pathkeys;
6008 }
List * make_pathkeys_for_sortclauses_extended(PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool *sortable)
Definition: pathkeys.c:1386
List * partitionClause
Definition: parsenodes.h:1489
List * orderClause
Definition: parsenodes.h:1491

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

6080 {
6081  Query *parse = root->parse;
6082  PathTarget *input_target;
6083  int ncols;
6084  bool *col_is_srf;
6085  bool *postpone_col;
6086  bool have_srf;
6087  bool have_volatile;
6088  bool have_expensive;
6089  bool have_srf_sortcols;
6090  bool postpone_srfs;
6091  List *postponable_cols;
6092  List *postponable_vars;
6093  int i;
6094  ListCell *lc;
6095 
6096  /* Shouldn't get here unless query has ORDER BY */
6097  Assert(parse->sortClause);
6098 
6099  *have_postponed_srfs = false; /* default result */
6100 
6101  /* Inspect tlist and collect per-column information */
6102  ncols = list_length(final_target->exprs);
6103  col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
6104  postpone_col = (bool *) palloc0(ncols * sizeof(bool));
6105  have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
6106 
6107  i = 0;
6108  foreach(lc, final_target->exprs)
6109  {
6110  Expr *expr = (Expr *) lfirst(lc);
6111 
6112  /*
6113  * If the column has a sortgroupref, assume it has to be evaluated
6114  * before sorting. Generally such columns would be ORDER BY, GROUP
6115  * BY, etc targets. One exception is columns that were removed from
6116  * GROUP BY by remove_useless_groupby_columns() ... but those would
6117  * only be Vars anyway. There don't seem to be any cases where it
6118  * would be worth the trouble to double-check.
6119  */
6120  if (get_pathtarget_sortgroupref(final_target, i) == 0)
6121  {
6122  /*
6123  * Check for SRF or volatile functions. Check the SRF case first
6124  * because we must know whether we have any postponed SRFs.