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

Go to the source code of this file.

Data Structures

struct  standard_qp_extra
 
struct  grouping_sets_data
 
struct  WindowClauseSortData
 

Macros

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

Functions

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

Variables

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

Macro Definition Documentation

◆ EXPRKIND_APPINFO

#define EXPRKIND_APPINFO   7

Definition at line 88 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 91 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 87 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 89 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 81 of file planner.c.

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

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 83 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 92 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 93 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 90 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 82 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 85 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 86 of file planner.c.

Referenced by subquery_planner().

Function Documentation

◆ add_paths_to_grouping_rel()

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

Definition at line 6482 of file planner.c.

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

Referenced by create_ordinary_grouping_paths().

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

◆ adjust_paths_for_srfs()

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

Definition at line 6040 of file planner.c.

References apply_projection_to_path(), Assert, RelOptInfo::cheapest_startup_path, RelOptInfo::cheapest_total_path, create_projection_path(), create_set_projection_path(), forboth, lfirst, lfirst_int, lfirst_node, linitial_int, list_length(), Path::param_info, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, and subpath().

Referenced by apply_scanjoin_target_to_paths(), and grouping_planner().

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

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

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

Referenced by grouping_planner().

7403 {
7404  bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
7405  PathTarget *scanjoin_target;
7406  ListCell *lc;
7407 
7408  /* This recurses, so be paranoid. */
7410 
7411  /*
7412  * If the rel is partitioned, we want to drop its existing paths and
7413  * generate new ones. This function would still be correct if we kept the
7414  * existing paths: we'd modify them to generate the correct target above
7415  * the partitioning Append, and then they'd compete on cost with paths
7416  * generating the target below the Append. However, in our current cost
7417  * model the latter way is always the same or cheaper cost, so modifying
7418  * the existing paths would just be useless work. Moreover, when the cost
7419  * is the same, varying roundoff errors might sometimes allow an existing
7420  * path to be picked, resulting in undesirable cross-platform plan
7421  * variations. So we drop old paths and thereby force the work to be done
7422  * below the Append, except in the case of a non-parallel-safe target.
7423  *
7424  * Some care is needed, because we have to allow generate_gather_paths to
7425  * see the old partial paths in the next stanza. Hence, zap the main
7426  * pathlist here, then allow generate_gather_paths to add path(s) to the
7427  * main list, and finally zap the partial pathlist.
7428  */
7429  if (rel_is_partitioned)
7430  rel->pathlist = NIL;
7431 
7432  /*
7433  * If the scan/join target is not parallel-safe, partial paths cannot
7434  * generate it.
7435  */
7436  if (!scanjoin_target_parallel_safe)
7437  {
7438  /*
7439  * Since we can't generate the final scan/join target in parallel
7440  * workers, this is our last opportunity to use any partial paths that
7441  * exist; so build Gather path(s) that use them and emit whatever the
7442  * current reltarget is. We don't do this in the case where the
7443  * target is parallel-safe, since we will be able to generate superior
7444  * paths by doing it after the final scan/join target has been
7445  * applied.
7446  */
7447  generate_useful_gather_paths(root, rel, false);
7448 
7449  /* Can't use parallel query above this level. */
7450  rel->partial_pathlist = NIL;
7451  rel->consider_parallel = false;
7452  }
7453 
7454  /* Finish dropping old paths for a partitioned rel, per comment above */
7455  if (rel_is_partitioned)
7456  rel->partial_pathlist = NIL;
7457 
7458  /* Extract SRF-free scan/join target. */
7459  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
7460 
7461  /*
7462  * Apply the SRF-free scan/join target to each existing path.
7463  *
7464  * If the tlist exprs are the same, we can just inject the sortgroupref
7465  * information into the existing pathtargets. Otherwise, replace each
7466  * path with a projection path that generates the SRF-free scan/join
7467  * target. This can't change the ordering of paths within rel->pathlist,
7468  * so we just modify the list in place.
7469  */
7470  foreach(lc, rel->pathlist)
7471  {
7472  Path *subpath = (Path *) lfirst(lc);
7473 
7474  /* Shouldn't have any parameterized paths anymore */
7475  Assert(subpath->param_info == NULL);
7476 
7477  if (tlist_same_exprs)
7478  subpath->pathtarget->sortgrouprefs =
7479  scanjoin_target->sortgrouprefs;
7480  else
7481  {
7482  Path *newpath;
7483 
7484  newpath = (Path *) create_projection_path(root, rel, subpath,
7485  scanjoin_target);
7486  lfirst(lc) = newpath;
7487  }
7488  }
7489 
7490  /* Likewise adjust the targets for any partial paths. */
7491  foreach(lc, rel->partial_pathlist)
7492  {
7493  Path *subpath = (Path *) lfirst(lc);
7494 
7495  /* Shouldn't have any parameterized paths anymore */
7496  Assert(subpath->param_info == NULL);
7497 
7498  if (tlist_same_exprs)
7499  subpath->pathtarget->sortgrouprefs =
7500  scanjoin_target->sortgrouprefs;
7501  else
7502  {
7503  Path *newpath;
7504 
7505  newpath = (Path *) create_projection_path(root, rel, subpath,
7506  scanjoin_target);
7507  lfirst(lc) = newpath;
7508  }
7509  }
7510 
7511  /*
7512  * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
7513  * atop each existing path. (Note that this function doesn't look at the
7514  * cheapest-path fields, which is a good thing because they're bogus right
7515  * now.)
7516  */
7517  if (root->parse->hasTargetSRFs)
7518  adjust_paths_for_srfs(root, rel,
7519  scanjoin_targets,
7520  scanjoin_targets_contain_srfs);
7521 
7522  /*
7523  * Update the rel's target to be the final (with SRFs) scan/join target.
7524  * This now matches the actual output of all the paths, and we might get
7525  * confused in createplan.c if they don't agree. We must do this now so
7526  * that any append paths made in the next part will use the correct
7527  * pathtarget (cf. create_append_path).
7528  *
7529  * Note that this is also necessary if GetForeignUpperPaths() gets called
7530  * on the final scan/join relation or on any of its children, since the
7531  * FDW might look at the rel's target to create ForeignPaths.
7532  */
7533  rel->reltarget = llast_node(PathTarget, scanjoin_targets);
7534 
7535  /*
7536  * If the relation is partitioned, recursively apply the scan/join target
7537  * to all partitions, and generate brand-new Append paths in which the
7538  * scan/join target is computed below the Append rather than above it.
7539  * Since Append is not projection-capable, that might save a separate
7540  * Result node, and it also is important for partitionwise aggregate.
7541  */
7542  if (rel_is_partitioned)
7543  {
7544  List *live_children = NIL;
7545  int partition_idx;
7546 
7547  /* Adjust each partition. */
7548  for (partition_idx = 0; partition_idx < rel->nparts; partition_idx++)
7549  {
7550  RelOptInfo *child_rel = rel->part_rels[partition_idx];
7551  AppendRelInfo **appinfos;
7552  int nappinfos;
7553  List *child_scanjoin_targets = NIL;
7554  ListCell *lc;
7555 
7556  /* Pruned or dummy children can be ignored. */
7557  if (child_rel == NULL || IS_DUMMY_REL(child_rel))
7558  continue;
7559 
7560  /* Translate scan/join targets for this child. */
7561  appinfos = find_appinfos_by_relids(root, child_rel->relids,
7562  &nappinfos);
7563  foreach(lc, scanjoin_targets)
7564  {
7565  PathTarget *target = lfirst_node(PathTarget, lc);
7566 
7567  target = copy_pathtarget(target);
7568  target->exprs = (List *)
7570  (Node *) target->exprs,
7571  nappinfos, appinfos);
7572  child_scanjoin_targets = lappend(child_scanjoin_targets,
7573  target);
7574  }
7575  pfree(appinfos);
7576 
7577  /* Recursion does the real work. */
7578  apply_scanjoin_target_to_paths(root, child_rel,
7579  child_scanjoin_targets,
7580  scanjoin_targets_contain_srfs,
7581  scanjoin_target_parallel_safe,
7583 
7584  /* Save non-dummy children for Append paths. */
7585  if (!IS_DUMMY_REL(child_rel))
7586  live_children = lappend(live_children, child_rel);
7587  }
7588 
7589  /* Build new paths for this relation by appending child paths. */
7590  add_paths_to_append_rel(root, rel, live_children);
7591  }
7592 
7593  /*
7594  * Consider generating Gather or Gather Merge paths. We must only do this
7595  * if the relation is parallel safe, and we don't do it for child rels to
7596  * avoid creating multiple Gather nodes within the same plan. We must do
7597  * this after all paths have been generated and before set_cheapest, since
7598  * one of the generated paths may turn out to be the cheapest one.
7599  */
7600  if (rel->consider_parallel && !IS_OTHER_REL(rel))
7601  generate_useful_gather_paths(root, rel, false);
7602 
7603  /*
7604  * Reassess which paths are the cheapest, now that we've potentially added
7605  * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
7606  * this relation.
7607  */
7608  set_cheapest(rel);
7609 }
#define NIL
Definition: pg_list.h:65
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:672
static void apply_scanjoin_target_to_paths(PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
Definition: planner.c:7397
PathTarget * pathtarget
Definition: pathnodes.h:1145
Query * parse
Definition: pathnodes.h:179
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:653
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1297
ParamPathInfo * param_info
Definition: pathnodes.h:1147
Definition: nodes.h:529
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2520
List * partial_pathlist
Definition: pathnodes.h:681
#define linitial_node(type, l)
Definition: pg_list.h:198
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:6040
void pfree(void *pointer)
Definition: mcxt.c:1056
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2816
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1418
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void check_stack_depth(void)
Definition: postgres.c:3312
int nparts
Definition: pathnodes.h:743
Index * sortgrouprefs
Definition: pathnodes.h:1075
Relids relids
Definition: pathnodes.h:665
List * lappend(List *list, void *datum)
Definition: list.c:321
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:728
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1074
#define llast_node(type, l)
Definition: pg_list.h:218
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
struct RelOptInfo ** part_rels
Definition: pathnodes.h:750
bool consider_parallel
Definition: pathnodes.h:673
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:240
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:766
List * pathlist
Definition: pathnodes.h:679
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:676
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:194

◆ can_partial_agg()

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

Definition at line 7355 of file planner.c.

References Query::groupClause, Query::groupingSets, Query::hasAggs, AggClauseCosts::hasNonPartial, AggClauseCosts::hasNonSerial, NIL, parse(), and PlannerInfo::parse.

Referenced by create_grouping_paths().

7356 {
7357  Query *parse = root->parse;
7358 
7359  if (!parse->hasAggs && parse->groupClause == NIL)
7360  {
7361  /*
7362  * We don't know how to do parallel aggregation unless we have either
7363  * some aggregates or a grouping clause.
7364  */
7365  return false;
7366  }
7367  else if (parse->groupingSets)
7368  {
7369  /* We don't know how to do grouping sets in parallel. */
7370  return false;
7371  }
7372  else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
7373  {
7374  /* Insufficient support for partial mode. */
7375  return false;
7376  }
7377 
7378  /* Everything looks good. */
7379  return true;
7380 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
bool hasNonSerial
Definition: pathnodes.h:61
bool hasNonPartial
Definition: pathnodes.h:60
List * groupClause
Definition: parsenodes.h:148
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ common_prefix_cmp()

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

Definition at line 5545 of file planner.c.

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

Referenced by select_active_windows().

5546 {
5547  const WindowClauseSortData *wcsa = a;
5548  const WindowClauseSortData *wcsb = b;
5549  ListCell *item_a;
5550  ListCell *item_b;
5551 
5552  forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
5553  {
5556 
5557  if (sca->tleSortGroupRef > scb->tleSortGroupRef)
5558  return -1;
5559  else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
5560  return 1;
5561  else if (sca->sortop > scb->sortop)
5562  return -1;
5563  else if (sca->sortop < scb->sortop)
5564  return 1;
5565  else if (sca->nulls_first && !scb->nulls_first)
5566  return -1;
5567  else if (!sca->nulls_first && scb->nulls_first)
5568  return 1;
5569  /* no need to compare eqop, since it is fully determined by sortop */
5570  }
5571 
5572  if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
5573  return -1;
5574  else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
5575  return 1;
5576 
5577  return 0;
5578 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:419
Index tleSortGroupRef
Definition: parsenodes.h:1257
#define lfirst_node(type, lc)
Definition: pg_list.h:193
static int list_length(const List *l)
Definition: pg_list.h:169

◆ consider_groupingsets_paths()

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

Definition at line 4189 of file planner.c.

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

Referenced by add_paths_to_grouping_rel().

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

◆ create_degenerate_grouping_paths()

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

Definition at line 3988 of file planner.c.

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

Referenced by create_grouping_paths().

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

◆ create_distinct_paths()

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

Definition at line 4727 of file planner.c.

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

Referenced by grouping_planner().

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

◆ create_grouping_paths()

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

Definition at line 3804 of file planner.c.

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

Referenced by grouping_planner().

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

◆ create_one_window_path()

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

Definition at line 4634 of file planner.c.

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

Referenced by create_window_paths().

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

◆ create_ordered_paths()

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

Definition at line 4936 of file planner.c.

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

Referenced by grouping_planner().

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

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

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

Referenced by create_grouping_paths(), and create_partitionwise_grouping_paths().

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

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

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

Referenced by create_ordinary_grouping_paths().

6858 {
6859  Query *parse = root->parse;
6860  RelOptInfo *partially_grouped_rel;
6861  AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
6862  AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
6863  Path *cheapest_partial_path = NULL;
6864  Path *cheapest_total_path = NULL;
6865  double dNumPartialGroups = 0;
6866  double dNumPartialPartialGroups = 0;
6867  ListCell *lc;
6868  bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
6869  bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
6870 
6871  /*
6872  * Consider whether we should generate partially aggregated non-partial
6873  * paths. We can only do this if we have a non-partial path, and only if
6874  * the parent of the input rel is performing partial partitionwise
6875  * aggregation. (Note that extra->patype is the type of partitionwise
6876  * aggregation being used at the parent level, not this level.)
6877  */
6878  if (input_rel->pathlist != NIL &&
6880  cheapest_total_path = input_rel->cheapest_total_path;
6881 
6882  /*
6883  * If parallelism is possible for grouped_rel, then we should consider
6884  * generating partially-grouped partial paths. However, if the input rel
6885  * has no partial paths, then we can't.
6886  */
6887  if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
6888  cheapest_partial_path = linitial(input_rel->partial_pathlist);
6889 
6890  /*
6891  * If we can't partially aggregate partial paths, and we can't partially
6892  * aggregate non-partial paths, then don't bother creating the new
6893  * RelOptInfo at all, unless the caller specified force_rel_creation.
6894  */
6895  if (cheapest_total_path == NULL &&
6896  cheapest_partial_path == NULL &&
6897  !force_rel_creation)
6898  return NULL;
6899 
6900  /*
6901  * Build a new upper relation to represent the result of partially
6902  * aggregating the rows from the input relation.
6903  */
6904  partially_grouped_rel = fetch_upper_rel(root,
6906  grouped_rel->relids);
6907  partially_grouped_rel->consider_parallel =
6908  grouped_rel->consider_parallel;
6909  partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
6910  partially_grouped_rel->serverid = grouped_rel->serverid;
6911  partially_grouped_rel->userid = grouped_rel->userid;
6912  partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
6913  partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
6914 
6915  /*
6916  * Build target list for partial aggregate paths. These paths cannot just
6917  * emit the same tlist as regular aggregate paths, because (1) we must
6918  * include Vars and Aggrefs needed in HAVING, which might not appear in
6919  * the result tlist, and (2) the Aggrefs must be set in partial mode.
6920  */
6921  partially_grouped_rel->reltarget =
6922  make_partial_grouping_target(root, grouped_rel->reltarget,
6923  extra->havingQual);
6924 
6925  if (!extra->partial_costs_set)
6926  {
6927  /*
6928  * Collect statistics about aggregates for estimating costs of
6929  * performing aggregation in parallel.
6930  */
6931  MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
6932  MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
6933  if (parse->hasAggs)
6934  {
6935  List *partial_target_exprs;
6936 
6937  /* partial phase */
6938  partial_target_exprs = partially_grouped_rel->reltarget->exprs;
6939  get_agg_clause_costs(root, (Node *) partial_target_exprs,
6941  agg_partial_costs);
6942 
6943  /* final phase */
6944  get_agg_clause_costs(root, (Node *) grouped_rel->reltarget->exprs,
6946  agg_final_costs);
6947  get_agg_clause_costs(root, extra->havingQual,
6949  agg_final_costs);
6950  }
6951 
6952  extra->partial_costs_set = true;
6953  }
6954 
6955  /* Estimate number of partial groups. */
6956  if (cheapest_total_path != NULL)
6957  dNumPartialGroups =
6958  get_number_of_groups(root,
6959  cheapest_total_path->rows,
6960  gd,
6961  extra->targetList);
6962  if (cheapest_partial_path != NULL)
6963  dNumPartialPartialGroups =
6964  get_number_of_groups(root,
6965  cheapest_partial_path->rows,
6966  gd,
6967  extra->targetList);
6968 
6969  if (can_sort && cheapest_total_path != NULL)
6970  {
6971  /* This should have been checked previously */
6972  Assert(parse->hasAggs || parse->groupClause);
6973 
6974  /*
6975  * Use any available suitably-sorted path as input, and also consider
6976  * sorting the cheapest partial path.
6977  */
6978  foreach(lc, input_rel->pathlist)
6979  {
6980  Path *path = (Path *) lfirst(lc);
6981  bool is_sorted;
6982 
6983  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6984  path->pathkeys);
6985  if (path == cheapest_total_path || is_sorted)
6986  {
6987  /* Sort the cheapest partial path, if it isn't already */
6988  if (!is_sorted)
6989  path = (Path *) create_sort_path(root,
6990  partially_grouped_rel,
6991  path,
6992  root->group_pathkeys,
6993  -1.0);
6994 
6995  if (parse->hasAggs)
6996  add_path(partially_grouped_rel, (Path *)
6997  create_agg_path(root,
6998  partially_grouped_rel,
6999  path,
7000  partially_grouped_rel->reltarget,
7001  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7003  parse->groupClause,
7004  NIL,
7005  agg_partial_costs,
7006  dNumPartialGroups));
7007  else
7008  add_path(partially_grouped_rel, (Path *)
7009  create_group_path(root,
7010  partially_grouped_rel,
7011  path,
7012  parse->groupClause,
7013  NIL,
7014  dNumPartialGroups));
7015  }
7016  }
7017 
7018  /*
7019  * Consider incremental sort on all partial paths, if enabled.
7020  *
7021  * We can also skip the entire loop when we only have a single-item
7022  * group_pathkeys because then we can't possibly have a presorted
7023  * prefix of the list without having the list be fully sorted.
7024  */
7026  {
7027  foreach(lc, input_rel->pathlist)
7028  {
7029  Path *path = (Path *) lfirst(lc);
7030  bool is_sorted;
7031  int presorted_keys;
7032 
7033  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7034  path->pathkeys,
7035  &presorted_keys);
7036 
7037  /* Ignore already sorted paths */
7038  if (is_sorted)
7039  continue;
7040 
7041  if (presorted_keys == 0)
7042  continue;
7043 
7044  /* Since we have presorted keys, consider incremental sort. */
7045  path = (Path *) create_incremental_sort_path(root,
7046  partially_grouped_rel,
7047  path,
7048  root->group_pathkeys,
7049  presorted_keys,
7050  -1.0);
7051 
7052  if (parse->hasAggs)
7053  add_path(partially_grouped_rel, (Path *)
7054  create_agg_path(root,
7055  partially_grouped_rel,
7056  path,
7057  partially_grouped_rel->reltarget,
7058  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7060  parse->groupClause,
7061  NIL,
7062  agg_partial_costs,
7063  dNumPartialGroups));
7064  else
7065  add_path(partially_grouped_rel, (Path *)
7066  create_group_path(root,
7067  partially_grouped_rel,
7068  path,
7069  parse->groupClause,
7070  NIL,
7071  dNumPartialGroups));
7072  }
7073  }
7074 
7075  }
7076 
7077  if (can_sort && cheapest_partial_path != NULL)
7078  {
7079  /* Similar to above logic, but for partial paths. */
7080  foreach(lc, input_rel->partial_pathlist)
7081  {
7082  Path *path = (Path *) lfirst(lc);
7083  Path *path_original = path;
7084  bool is_sorted;
7085  int presorted_keys;
7086 
7087  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7088  path->pathkeys,
7089  &presorted_keys);
7090 
7091  if (path == cheapest_partial_path || is_sorted)
7092  {
7093  /* Sort the cheapest partial path, if it isn't already */
7094  if (!is_sorted)
7095  path = (Path *) create_sort_path(root,
7096  partially_grouped_rel,
7097  path,
7098  root->group_pathkeys,
7099  -1.0);
7100 
7101  if (parse->hasAggs)
7102  add_partial_path(partially_grouped_rel, (Path *)
7103  create_agg_path(root,
7104  partially_grouped_rel,
7105  path,
7106  partially_grouped_rel->reltarget,
7107  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7109  parse->groupClause,
7110  NIL,
7111  agg_partial_costs,
7112  dNumPartialPartialGroups));
7113  else
7114  add_partial_path(partially_grouped_rel, (Path *)
7115  create_group_path(root,
7116  partially_grouped_rel,
7117  path,
7118  parse->groupClause,
7119  NIL,
7120  dNumPartialPartialGroups));
7121  }
7122 
7123  /*
7124  * Now we may consider incremental sort on this path, but only
7125  * when the path is not already sorted and when incremental sort
7126  * is enabled.
7127  */
7128  if (is_sorted || !enable_incremental_sort)
7129  continue;
7130 
7131  /* Restore the input path (we might have added Sort on top). */
7132  path = path_original;
7133 
7134  /* no shared prefix, not point in building incremental sort */
7135  if (presorted_keys == 0)
7136  continue;
7137 
7138  /*
7139  * We should have already excluded pathkeys of length 1 because
7140  * then presorted_keys > 0 would imply is_sorted was true.
7141  */
7142  Assert(list_length(root->group_pathkeys) != 1);
7143 
7144  path = (Path *) create_incremental_sort_path(root,
7145  partially_grouped_rel,
7146  path,
7147  root->group_pathkeys,
7148  presorted_keys,
7149  -1.0);
7150 
7151  if (parse->hasAggs)
7152  add_partial_path(partially_grouped_rel, (Path *)
7153  create_agg_path(root,
7154  partially_grouped_rel,
7155  path,
7156  partially_grouped_rel->reltarget,
7157  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7159  parse->groupClause,
7160  NIL,
7161  agg_partial_costs,
7162  dNumPartialPartialGroups));
7163  else
7164  add_partial_path(partially_grouped_rel, (Path *)
7165  create_group_path(root,
7166  partially_grouped_rel,
7167  path,
7168  parse->groupClause,
7169  NIL,
7170  dNumPartialPartialGroups));
7171  }
7172  }
7173 
7174  if (can_hash && cheapest_total_path != NULL)
7175  {
7176  double hashaggtablesize;
7177 
7178  /* Checked above */
7179  Assert(parse->hasAggs || parse->groupClause);
7180 
7181  hashaggtablesize =
7182  estimate_hashagg_tablesize(cheapest_total_path,
7183  agg_partial_costs,
7184  dNumPartialGroups);
7185 
7186  /*
7187  * Tentatively produce a partial HashAgg Path, depending on if it
7188  * looks as if the hash table will fit in work_mem.
7189  */
7190  if ((!hashagg_avoid_disk_plan || hashaggtablesize < work_mem * 1024L) &&
7191  cheapest_total_path != NULL)
7192  {
7193  add_path(partially_grouped_rel, (Path *)
7194  create_agg_path(root,
7195  partially_grouped_rel,
7196  cheapest_total_path,
7197  partially_grouped_rel->reltarget,
7198  AGG_HASHED,
7200  parse->groupClause,
7201  NIL,
7202  agg_partial_costs,
7203  dNumPartialGroups));
7204  }
7205  }
7206 
7207  if (can_hash && cheapest_partial_path != NULL)
7208  {
7209  double hashaggtablesize;
7210 
7211  hashaggtablesize =
7212  estimate_hashagg_tablesize(cheapest_partial_path,
7213  agg_partial_costs,
7214  dNumPartialPartialGroups);
7215 
7216  /* Do the same for partial paths. */
7217  if ((!hashagg_avoid_disk_plan ||
7218  hashaggtablesize < work_mem * 1024L) &&
7219  cheapest_partial_path != NULL)
7220  {
7221  add_partial_path(partially_grouped_rel, (Path *)
7222  create_agg_path(root,
7223  partially_grouped_rel,
7224  cheapest_partial_path,
7225  partially_grouped_rel->reltarget,
7226  AGG_HASHED,
7228  parse->groupClause,
7229  NIL,
7230  agg_partial_costs,
7231  dNumPartialPartialGroups));
7232  }
7233  }
7234 
7235  /*
7236  * If there is an FDW that's responsible for all baserels of the query,
7237  * let it consider adding partially grouped ForeignPaths.
7238  */
7239  if (partially_grouped_rel->fdwroutine &&
7240  partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
7241  {
7242  FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
7243 
7244  fdwroutine->GetForeignUpperPaths(root,
7246  input_rel, partially_grouped_rel,
7247  extra);
7248  }
7249 
7250  return partially_grouped_rel;
7251 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:205
List * group_pathkeys
Definition: pathnodes.h:300
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:131
RelOptKind reloptkind
Definition: pathnodes.h:662
SortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2769
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition: planner.c:3683
Oid userid
Definition: pathnodes.h:715
AggClauseCosts agg_partial_costs
Definition: pathnodes.h:2487
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:231
bool hasAggs
Definition: parsenodes.h:125
Definition: nodes.h:529
PartitionwiseAggregateType patype
Definition: pathnodes.h:2494
List * partial_pathlist
Definition: pathnodes.h:681
#define MemSet(start, val, len)
Definition: c.h:971
bool useridiscurrent
Definition: pathnodes.h:716
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define GROUPING_CAN_USE_SORT
Definition: pathnodes.h:2447
#define linitial(l)
Definition: pg_list.h:195
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1192
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:2973
struct Path * cheapest_total_path
Definition: pathnodes.h:683
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:718
Relids relids
Definition: pathnodes.h:665
double estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: selfuncs.c:3839
bool hashagg_avoid_disk_plan
Definition: costsize.c:133
Oid serverid
Definition: pathnodes.h:714
List * exprs
Definition: pathnodes.h:1074
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
int work_mem
Definition: globals.c:121
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2818
#define GROUPING_CAN_USE_HASH
Definition: pathnodes.h:2448
List * pathkeys
Definition: pathnodes.h:1158
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1154
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition: planner.c:5294
static int list_length(const List *l)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:673
List * groupClause
Definition: parsenodes.h:148
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
List * pathlist
Definition: pathnodes.h:679
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2862
AggClauseCosts agg_final_costs
Definition: pathnodes.h:2488
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:676
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ create_partitionwise_grouping_paths()

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

Definition at line 7629 of file planner.c.

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

Referenced by create_ordinary_grouping_paths().

7637 {
7638  int nparts = input_rel->nparts;
7639  int cnt_parts;
7640  List *grouped_live_children = NIL;
7641  List *partially_grouped_live_children = NIL;
7642  PathTarget *target = grouped_rel->reltarget;
7643  bool partial_grouping_valid = true;
7644 
7647  partially_grouped_rel != NULL);
7648 
7649  /* Add paths for partitionwise aggregation/grouping. */
7650  for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
7651  {
7652  RelOptInfo *child_input_rel = input_rel->part_rels[cnt_parts];
7653  PathTarget *child_target = copy_pathtarget(target);
7654  AppendRelInfo **appinfos;
7655  int nappinfos;
7656  GroupPathExtraData child_extra;
7657  RelOptInfo *child_grouped_rel;
7658  RelOptInfo *child_partially_grouped_rel;
7659 
7660  /* Pruned or dummy children can be ignored. */
7661  if (child_input_rel == NULL || IS_DUMMY_REL(child_input_rel))
7662  continue;
7663 
7664  /*
7665  * Copy the given "extra" structure as is and then override the
7666  * members specific to this child.
7667  */
7668  memcpy(&child_extra, extra, sizeof(child_extra));
7669 
7670  appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
7671  &nappinfos);
7672 
7673  child_target->exprs = (List *)
7675  (Node *) target->exprs,
7676  nappinfos, appinfos);
7677 
7678  /* Translate havingQual and targetList. */
7679  child_extra.havingQual = (Node *)
7681  extra->havingQual,
7682  nappinfos, appinfos);
7683  child_extra.targetList = (List *)
7685  (Node *) extra->targetList,
7686  nappinfos, appinfos);
7687 
7688  /*
7689  * extra->patype was the value computed for our parent rel; patype is
7690  * the value for this relation. For the child, our value is its
7691  * parent rel's value.
7692  */
7693  child_extra.patype = patype;
7694 
7695  /*
7696  * Create grouping relation to hold fully aggregated grouping and/or
7697  * aggregation paths for the child.
7698  */
7699  child_grouped_rel = make_grouping_rel(root, child_input_rel,
7700  child_target,
7701  extra->target_parallel_safe,
7702  child_extra.havingQual);
7703 
7704  /* Create grouping paths for this child relation. */
7705  create_ordinary_grouping_paths(root, child_input_rel,
7706  child_grouped_rel,
7707  agg_costs, gd, &child_extra,
7708  &child_partially_grouped_rel);
7709 
7710  if (child_partially_grouped_rel)
7711  {
7712  partially_grouped_live_children =
7713  lappend(partially_grouped_live_children,
7714  child_partially_grouped_rel);
7715  }
7716  else
7717  partial_grouping_valid = false;
7718 
7719  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7720  {
7721  set_cheapest(child_grouped_rel);
7722  grouped_live_children = lappend(grouped_live_children,
7723  child_grouped_rel);
7724  }
7725 
7726  pfree(appinfos);
7727  }
7728 
7729  /*
7730  * Try to create append paths for partially grouped children. For full
7731  * partitionwise aggregation, we might have paths in the partial_pathlist
7732  * if parallel aggregation is possible. For partial partitionwise
7733  * aggregation, we may have paths in both pathlist and partial_pathlist.
7734  *
7735  * NB: We must have a partially grouped path for every child in order to
7736  * generate a partially grouped path for this relation.
7737  */
7738  if (partially_grouped_rel && partial_grouping_valid)
7739  {
7740  Assert(partially_grouped_live_children != NIL);
7741 
7742  add_paths_to_append_rel(root, partially_grouped_rel,
7743  partially_grouped_live_children);
7744 
7745  /*
7746  * We need call set_cheapest, since the finalization step will use the
7747  * cheapest path from the rel.
7748  */
7749  if (partially_grouped_rel->pathlist)
7750  set_cheapest(partially_grouped_rel);
7751  }
7752 
7753  /* If possible, create append paths for fully grouped children. */
7754  if (patype == PARTITIONWISE_AGGREGATE_FULL)
7755  {
7756  Assert(grouped_live_children != NIL);
7757 
7758  add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
7759  }
7760 }
#define NIL
Definition: pg_list.h:65
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:672
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition: planner.c:3914
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1297
Definition: nodes.h:529
PartitionwiseAggregateType patype
Definition: pathnodes.h:2494
void pfree(void *pointer)
Definition: mcxt.c:1056
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1418
int nparts
Definition: pathnodes.h:743
Relids relids
Definition: pathnodes.h:665
List * lappend(List *list, void *datum)
Definition: list.c:321
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition: appendinfo.c:728
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
List * exprs
Definition: pathnodes.h:1074
#define Assert(condition)
Definition: c.h:738
struct RelOptInfo ** part_rels
Definition: pathnodes.h:750
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:4053
List * pathlist
Definition: pathnodes.h:679
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:676
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:194

◆ create_window_paths()

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

Definition at line 4550 of file planner.c.

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

Referenced by grouping_planner().

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

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 6156 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

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

6157 {
6158  Node *result;
6159 
6160  /*
6161  * Convert named-argument function calls, insert default arguments and
6162  * simplify constant subexprs
6163  */
6164  result = eval_const_expressions(NULL, (Node *) expr);
6165 
6166  /* Fill in opfuncid values if missing */
6167  fix_opfuncids(result);
6168 
6169  return (Expr *) result;
6170 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1587
Definition: nodes.h:529
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2255

◆ expression_planner_with_deps()

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

Definition at line 6183 of file planner.c.

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

Referenced by GetCachedExpression().

6186 {
6187  Node *result;
6188  PlannerGlobal glob;
6189  PlannerInfo root;
6190 
6191  /* Make up dummy planner state so we can use setrefs machinery */
6192  MemSet(&glob, 0, sizeof(glob));
6193  glob.type = T_PlannerGlobal;
6194  glob.relationOids = NIL;
6195  glob.invalItems = NIL;
6196 
6197  MemSet(&root, 0, sizeof(root));
6198  root.type = T_PlannerInfo;
6199  root.glob = &glob;
6200 
6201  /*
6202  * Convert named-argument function calls, insert default arguments and
6203  * simplify constant subexprs. Collect identities of inlined functions
6204  * and elided domains, too.
6205  */
6206  result = eval_const_expressions(&root, (Node *) expr);
6207 
6208  /* Fill in opfuncid values if missing */
6209  fix_opfuncids(result);
6210 
6211  /*
6212  * Now walk the finished expression to find anything else we ought to
6213  * record as an expression dependency.
6214  */
6215  (void) extract_query_dependencies_walker(result, &root);
6216 
6217  *relationOids = glob.relationOids;
6218  *invalItems = glob.invalItems;
6219 
6220  return (Expr *) result;
6221 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1587
Definition: nodes.h:529
#define MemSet(start, val, len)
Definition: c.h:971
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2255
PlannerGlobal * glob
Definition: pathnodes.h:181
List * invalItems
Definition: pathnodes.h:129
NodeTag type
Definition: pathnodes.h:177
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:2827
NodeTag type
Definition: pathnodes.h:107
List * relationOids
Definition: pathnodes.h:127

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

Definition at line 3335 of file planner.c.

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

Referenced by preprocess_grouping_sets().

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

◆ gather_grouping_paths()

static void gather_grouping_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 7267 of file planner.c.

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

Referenced by add_paths_to_grouping_rel(), and create_ordinary_grouping_paths().

7268 {
7269  ListCell *lc;
7270  Path *cheapest_partial_path;
7271 
7272  /* Try Gather for unordered paths and Gather Merge for ordered ones. */
7273  generate_useful_gather_paths(root, rel, true);
7274 
7275  /* Try cheapest partial path + explicit Sort + Gather Merge. */
7276  cheapest_partial_path = linitial(rel->partial_pathlist);
7278  cheapest_partial_path->pathkeys))
7279  {
7280  Path *path;
7281  double total_groups;
7282 
7283  total_groups =
7284  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
7285  path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
7286  root->group_pathkeys,
7287  -1.0);
7288  path = (Path *)
7290  rel,
7291  path,
7292  rel->reltarget,
7293  root->group_pathkeys,
7294  NULL,
7295  &total_groups);
7296 
7297  add_path(rel, path);
7298  }
7299 
7300  /*
7301  * Consider incremental sort on all partial paths, if enabled.
7302  *
7303  * We can also skip the entire loop when we only have a single-item
7304  * group_pathkeys because then we can't possibly have a presorted prefix
7305  * of the list without having the list be fully sorted.
7306  */
7308  return;
7309 
7310  /* also consider incremental sort on partial paths, if enabled */
7311  foreach(lc, rel->partial_pathlist)
7312  {
7313  Path *path = (Path *) lfirst(lc);
7314  bool is_sorted;
7315  int presorted_keys;
7316  double total_groups;
7317 
7318  is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7319  path->pathkeys,
7320  &presorted_keys);
7321 
7322  if (is_sorted)
7323  continue;
7324 
7325  if (presorted_keys == 0)
7326  continue;
7327 
7328  path = (Path *) create_incremental_sort_path(root,
7329  rel,
7330  path,
7331  root->group_pathkeys,
7332  presorted_keys,
7333  -1.0);
7334 
7335  path = (Path *)
7337  rel,
7338  path,
7339  rel->reltarget,
7340  root->group_pathkeys,
7341  NULL,
7342  &total_groups);
7343 
7344  add_path(rel, path);
7345  }
7346 }
List * group_pathkeys
Definition: pathnodes.h:300
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:131
SortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2769
int parallel_workers
Definition: pathnodes.h:1151
List * partial_pathlist
Definition: pathnodes.h:681
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define linitial(l)
Definition: pg_list.h:195
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2816
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1754
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2818
List * pathkeys
Definition: pathnodes.h:1158
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1154
static int list_length(const List *l)
Definition: pg_list.h:169
struct PathTarget * reltarget
Definition: pathnodes.h:676

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

Definition at line 5997 of file planner.c.

References RelOptInfo::cheapest_total_path, compare_fractional_path_costs(), lfirst, RelOptInfo::pathlist, and Path::rows.

Referenced by make_subplan(), recurse_set_operations(), and standard_planner().

5998 {
5999  Path *best_path = rel->cheapest_total_path;
6000  ListCell *l;
6001 
6002  /* If all tuples will be retrieved, just return the cheapest-total path */
6003  if (tuple_fraction <= 0.0)
6004  return best_path;
6005 
6006  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
6007  if (tuple_fraction >= 1.0 && best_path->rows > 0)
6008  tuple_fraction /= best_path->rows;
6009 
6010  foreach(l, rel->pathlist)
6011  {
6012  Path *path = (Path *) lfirst(l);
6013 
6014  if (path == rel->cheapest_total_path ||
6015  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
6016  continue;
6017 
6018  best_path = path;
6019  }
6020 
6021  return best_path;
6022 }
struct Path * cheapest_total_path
Definition: pathnodes.h:683
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1154
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: pathnodes.h:679

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

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

Referenced by create_ordinary_grouping_paths(), and create_partial_grouping_paths().

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

◆ group_by_has_partkey()

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

Definition at line 7769 of file planner.c.

References Assert, get_sortgrouplist_exprs(), lfirst, list_member(), RelOptInfo::part_scheme, RelOptInfo::partexprs, and PartitionSchemeData::partnatts.

Referenced by create_ordinary_grouping_paths().

7772 {
7773  List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
7774  int cnt = 0;
7775  int partnatts;
7776 
7777  /* Input relation should be partitioned. */
7778  Assert(input_rel->part_scheme);
7779 
7780  /* Rule out early, if there are no partition keys present. */
7781  if (!input_rel->partexprs)
7782  return false;
7783 
7784  partnatts = input_rel->part_scheme->partnatts;
7785 
7786  for (cnt = 0; cnt < partnatts; cnt++)
7787  {
7788  List *partexprs = input_rel->partexprs[cnt];
7789  ListCell *lc;
7790  bool found = false;
7791 
7792  foreach(lc, partexprs)
7793  {
7794  Expr *partexpr = lfirst(lc);
7795 
7796  if (list_member(groupexprs, partexpr))
7797  {
7798  found = true;
7799  break;
7800  }
7801  }
7802 
7803  /*
7804  * If none of the partition key expressions match with any of the
7805  * GROUP BY expression, return false.
7806  */
7807  if (!found)
7808  return false;
7809  }
7810 
7811  return true;
7812 }
List ** partexprs
Definition: pathnodes.h:753
bool list_member(const List *list, const void *datum)
Definition: list.c:613
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:414
PartitionScheme part_scheme
Definition: pathnodes.h:742
Definition: pg_list.h:50

◆ grouping_planner()

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

Definition at line 1833 of file planner.c.

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

Referenced by inheritance_planner(), and subquery_planner().

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

◆ inheritance_planner()

static void inheritance_planner ( PlannerInfo root)
static

Definition at line 1209 of file planner.c.

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

Referenced by subquery_planner().

1210 {
1211  Query *parse = root->parse;
1212  int top_parentRTindex = parse->resultRelation;
1213  List *select_rtable;
1214  List *select_appinfos;
1215  List *child_appinfos;
1216  List *old_child_rtis;
1217  List *new_child_rtis;
1218  Bitmapset *subqueryRTindexes;
1219  Index next_subquery_rti;
1220  int nominalRelation = -1;
1221  Index rootRelation = 0;
1222  List *final_rtable = NIL;
1223  List *final_rowmarks = NIL;
1224  List *final_appendrels = NIL;
1225  int save_rel_array_size = 0;
1226  RelOptInfo **save_rel_array = NULL;
1227  AppendRelInfo **save_append_rel_array = NULL;
1228  List *subpaths = NIL;
1229  List *subroots = NIL;
1230  List *resultRelations = NIL;
1231  List *withCheckOptionLists = NIL;
1232  List *returningLists = NIL;
1233  List *rowMarks;
1234  RelOptInfo *final_rel;
1235  ListCell *lc;
1236  ListCell *lc2;
1237  Index rti;
1238  RangeTblEntry *parent_rte;
1239  Bitmapset *parent_relids;
1240  Query **parent_parses;
1241 
1242  /* Should only get here for UPDATE or DELETE */
1243  Assert(parse->commandType == CMD_UPDATE ||
1244  parse->commandType == CMD_DELETE);
1245 
1246  /*
1247  * We generate a modified instance of the original Query for each target
1248  * relation, plan that, and put all the plans into a list that will be
1249  * controlled by a single ModifyTable node. All the instances share the
1250  * same rangetable, but each instance must have its own set of subquery
1251  * RTEs within the finished rangetable because (1) they are likely to get
1252  * scribbled on during planning, and (2) it's not inconceivable that
1253  * subqueries could get planned differently in different cases. We need
1254  * not create duplicate copies of other RTE kinds, in particular not the
1255  * target relations, because they don't have either of those issues. Not
1256  * having to duplicate the target relations is important because doing so
1257  * (1) would result in a rangetable of length O(N^2) for N targets, with
1258  * at least O(N^3) work expended here; and (2) would greatly complicate
1259  * management of the rowMarks list.
1260  *
1261  * To begin with, generate a bitmapset of the relids of the subquery RTEs.
1262  */
1263  subqueryRTindexes = NULL;
1264  rti = 1;
1265  foreach(lc, parse->rtable)
1266  {
1268 
1269  if (rte->rtekind == RTE_SUBQUERY)
1270  subqueryRTindexes = bms_add_member(subqueryRTindexes, rti);
1271  rti++;
1272  }
1273 
1274  /*
1275  * If the parent RTE is a partitioned table, we should use that as the
1276  * nominal target relation, because the RTEs added for partitioned tables
1277  * (including the root parent) as child members of the inheritance set do
1278  * not appear anywhere else in the plan, so the confusion explained below
1279  * for non-partitioning inheritance cases is not possible.
1280  */
1281  parent_rte = rt_fetch(top_parentRTindex, parse->rtable);
1282  Assert(parent_rte->inh);
1283  if (parent_rte->relkind == RELKIND_PARTITIONED_TABLE)
1284  {
1285  nominalRelation = top_parentRTindex;
1286  rootRelation = top_parentRTindex;
1287  }
1288 
1289  /*
1290  * Before generating the real per-child-relation plans, do a cycle of
1291  * planning as though the query were a SELECT. The objective here is to
1292  * find out which child relations need to be processed, using the same
1293  * expansion and pruning logic as for a SELECT. We'll then pull out the
1294  * RangeTblEntry-s generated for the child rels, and make use of the
1295  * AppendRelInfo entries for them to guide the real planning. (This is
1296  * rather inefficient; we could perhaps stop short of making a full Path
1297  * tree. But this whole function is inefficient and slated for
1298  * destruction, so let's not contort query_planner for that.)
1299  */
1300  {
1301  PlannerInfo *subroot;
1302 
1303  /*
1304  * Flat-copy the PlannerInfo to prevent modification of the original.
1305  */
1306  subroot = makeNode(PlannerInfo);
1307  memcpy(subroot, root, sizeof(PlannerInfo));
1308 
1309  /*
1310  * Make a deep copy of the parsetree for this planning cycle to mess
1311  * around with, and change it to look like a SELECT. (Hack alert: the