PostgreSQL Source Code  git master
planner.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/htup_details.h"
#include "access/parallel.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/pg_constraint_fn.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "lib/bipartite_match.h"
#include "lib/knapsack.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.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 "optimizer/var.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/parse_agg.h"
#include "rewrite/rewriteManip.h"
#include "storage/dsm_impl.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/lsyscache.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
 

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 bool limit_needed (Query *parse)
 
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)
 
static Size estimate_hashagg_tablesize (Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
 
static RelOptInfocreate_grouping_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, const AggClauseCosts *agg_costs, grouping_sets_data *gd)
 
static void consider_groupingsets_paths (PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, PathTarget *target, 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, List *tlist, WindowFuncLists *wflists, List *activeWindows)
 
static void create_one_window_path (PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, List *tlist, WindowFuncLists *wflists, List *activeWindows)
 
static RelOptInfocreate_distinct_paths (PlannerInfo *root, RelOptInfo *input_rel)
 
static RelOptInfocreate_ordered_paths (PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, double limit_tuples)
 
static PathTargetmake_group_input_target (PlannerInfo *root, PathTarget *final_target)
 
static PathTargetmake_partial_grouping_target (PlannerInfo *root, PathTarget *grouping_target)
 
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, PathTarget *target, PathTarget *partial_grouping_target, const AggClauseCosts *agg_costs, const AggClauseCosts *agg_final_costs, grouping_sets_data *gd, bool can_sort, bool can_hash, double dNumGroups, List *havingQual)
 
static void add_partial_paths_to_grouping_rel (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, PathTarget *target, PathTarget *partial_grouping_target, AggClauseCosts *agg_partial_costs, AggClauseCosts *agg_final_costs, grouping_sets_data *gd, bool can_sort, bool can_hash, List *havingQual)
 
static bool can_parallel_agg (PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs)
 
PlannedStmtplanner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannedStmtstandard_planner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannerInfosubquery_planner (PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
 
Exprpreprocess_phv_expression (PlannerInfo *root, Expr *expr)
 
bool is_dummy_plan (Plan *plan)
 
RowMarkType select_rowmark_type (RangeTblEntry *rte, LockClauseStrength strength)
 
void mark_partial_aggref (Aggref *agg, AggSplit aggsplit)
 
Pathget_cheapest_fractional_path (RelOptInfo *rel, double tuple_fraction)
 
Exprexpression_planner (Expr *expr)
 
bool plan_cluster_use_sort (Oid tableOid, Oid indexOid)
 
int plan_create_index_workers (Oid tableOid, Oid indexOid)
 
Listget_partitioned_child_rels (PlannerInfo *root, Index rti, bool *part_cols_updated)
 
Listget_partitioned_child_rels_for_join (PlannerInfo *root, Relids join_relids)
 

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

Referenced by subquery_planner().

◆ EXPRKIND_ARBITER_ELEM

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 84 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_LIMIT

#define EXPRKIND_LIMIT   6

Definition at line 80 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_PHV

#define EXPRKIND_PHV   8

Definition at line 82 of file planner.c.

Referenced by preprocess_phv_expression().

◆ EXPRKIND_QUAL

#define EXPRKIND_QUAL   0

Definition at line 74 of file planner.c.

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

◆ EXPRKIND_RTFUNC

#define EXPRKIND_RTFUNC   2

Definition at line 76 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_RTFUNC_LATERAL

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 77 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLEFUNC

#define EXPRKIND_TABLEFUNC   11

Definition at line 85 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TABLEFUNC_LATERAL

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 86 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_TABLESAMPLE

#define EXPRKIND_TABLESAMPLE   9

Definition at line 83 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_TARGET

#define EXPRKIND_TARGET   1

Definition at line 75 of file planner.c.

Referenced by subquery_planner().

◆ EXPRKIND_VALUES

#define EXPRKIND_VALUES   4

Definition at line 78 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

◆ EXPRKIND_VALUES_LATERAL

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 79 of file planner.c.

Referenced by subquery_planner().

Function Documentation

◆ add_partial_paths_to_grouping_rel()

static void add_partial_paths_to_grouping_rel ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
PathTarget target,
PathTarget partial_grouping_target,
AggClauseCosts agg_partial_costs,
AggClauseCosts agg_final_costs,
grouping_sets_data gd,
bool  can_sort,
bool  can_hash,
List havingQual 
)
static

Definition at line 6289 of file planner.c.

References add_partial_path(), AGG_HASHED, AGG_PLAIN, AGG_SORTED, AGGSPLIT_INITIAL_SERIAL, Assert, create_agg_path(), create_group_path(), create_sort_path(), estimate_hashagg_tablesize(), get_number_of_groups(), PlannerInfo::group_pathkeys, Query::groupClause, Query::hasAggs, lfirst, linitial, NIL, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), Path::rows, and work_mem.

Referenced by create_grouping_paths().

6300 {
6301  Query *parse = root->parse;
6302  Path *cheapest_partial_path = linitial(input_rel->partial_pathlist);
6303  Size hashaggtablesize;
6304  double dNumPartialGroups = 0;
6305  ListCell *lc;
6306 
6307  /* Estimate number of partial groups. */
6308  dNumPartialGroups = get_number_of_groups(root,
6309  cheapest_partial_path->rows,
6310  gd);
6311 
6312  if (can_sort)
6313  {
6314  /* This should have been checked previously */
6315  Assert(parse->hasAggs || parse->groupClause);
6316 
6317  /*
6318  * Use any available suitably-sorted path as input, and also consider
6319  * sorting the cheapest partial path.
6320  */
6321  foreach(lc, input_rel->partial_pathlist)
6322  {
6323  Path *path = (Path *) lfirst(lc);
6324  bool is_sorted;
6325 
6326  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6327  path->pathkeys);
6328  if (path == cheapest_partial_path || is_sorted)
6329  {
6330  /* Sort the cheapest partial path, if it isn't already */
6331  if (!is_sorted)
6332  path = (Path *) create_sort_path(root,
6333  grouped_rel,
6334  path,
6335  root->group_pathkeys,
6336  -1.0);
6337 
6338  if (parse->hasAggs)
6339  add_partial_path(grouped_rel, (Path *)
6340  create_agg_path(root,
6341  grouped_rel,
6342  path,
6343  partial_grouping_target,
6344  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6346  parse->groupClause,
6347  NIL,
6348  agg_partial_costs,
6349  dNumPartialGroups));
6350  else
6351  add_partial_path(grouped_rel, (Path *)
6352  create_group_path(root,
6353  grouped_rel,
6354  path,
6355  partial_grouping_target,
6356  parse->groupClause,
6357  NIL,
6358  dNumPartialGroups));
6359  }
6360  }
6361  }
6362 
6363  if (can_hash)
6364  {
6365  /* Checked above */
6366  Assert(parse->hasAggs || parse->groupClause);
6367 
6368  hashaggtablesize =
6369  estimate_hashagg_tablesize(cheapest_partial_path,
6370  agg_partial_costs,
6371  dNumPartialGroups);
6372 
6373  /*
6374  * Tentatively produce a partial HashAgg Path, depending on if it
6375  * looks as if the hash table will fit in work_mem.
6376  */
6377  if (hashaggtablesize < work_mem * 1024L)
6378  {
6379  add_partial_path(grouped_rel, (Path *)
6380  create_agg_path(root,
6381  grouped_rel,
6382  cheapest_partial_path,
6383  partial_grouping_target,
6384  AGG_HASHED,
6386  parse->groupClause,
6387  NIL,
6388  agg_partial_costs,
6389  dNumPartialGroups));
6390  }
6391  }
6392 }
List * group_pathkeys
Definition: relation.h:264
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd)
Definition: planner.c:3465
bool hasAggs
Definition: parsenodes.h:123
List * partial_pathlist
Definition: relation.h:601
#define linitial(l)
Definition: pg_list.h:111
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:2762
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2651
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3577
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
int work_mem
Definition: globals.c:113
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2607
List * pathkeys
Definition: relation.h:1060
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
size_t Size
Definition: c.h:422
List * groupClause
Definition: parsenodes.h:146
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:762
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ add_paths_to_grouping_rel()

static void add_paths_to_grouping_rel ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
PathTarget target,
PathTarget partial_grouping_target,
const AggClauseCosts agg_costs,
const AggClauseCosts agg_final_costs,
grouping_sets_data gd,
bool  can_sort,
bool  can_hash,
double  dNumGroups,
List havingQual 
)
static

Definition at line 5998 of file planner.c.

References add_path(), AGG_HASHED, AGG_PLAIN, AGG_SORTED, AGGSPLIT_FINAL_DESERIAL, AGGSPLIT_SIMPLE, Assert, RelOptInfo::cheapest_total_path, consider_groupingsets_paths(), create_agg_path(), create_gather_merge_path(), create_gather_path(), create_group_path(), create_sort_path(), estimate_hashagg_tablesize(), PlannerInfo::group_pathkeys, Query::groupClause, Query::groupingSets, Query::hasAggs, lfirst, linitial, NIL, Path::parallel_workers, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, Path::rows, subpath(), and work_mem.

Referenced by create_grouping_paths().

6005 {
6006  Query *parse = root->parse;
6007  Path *cheapest_path = input_rel->cheapest_total_path;
6008  ListCell *lc;
6009 
6010  if (can_sort)
6011  {
6012  /*
6013  * Use any available suitably-sorted path as input, and also consider
6014  * sorting the cheapest-total path.
6015  */
6016  foreach(lc, input_rel->pathlist)
6017  {
6018  Path *path = (Path *) lfirst(lc);
6019  bool is_sorted;
6020 
6021  is_sorted = pathkeys_contained_in(root->group_pathkeys,
6022  path->pathkeys);
6023  if (path == cheapest_path || is_sorted)
6024  {
6025  /* Sort the cheapest-total path if it isn't already sorted */
6026  if (!is_sorted)
6027  path = (Path *) create_sort_path(root,
6028  grouped_rel,
6029  path,
6030  root->group_pathkeys,
6031  -1.0);
6032 
6033  /* Now decide what to stick atop it */
6034  if (parse->groupingSets)
6035  {
6036  consider_groupingsets_paths(root, grouped_rel,
6037  path, true, can_hash, target,
6038  gd, agg_costs, dNumGroups);
6039  }
6040  else if (parse->hasAggs)
6041  {
6042  /*
6043  * We have aggregation, possibly with plain GROUP BY. Make
6044  * an AggPath.
6045  */
6046  add_path(grouped_rel, (Path *)
6047  create_agg_path(root,
6048  grouped_rel,
6049  path,
6050  target,
6051  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6053  parse->groupClause,
6054  havingQual,
6055  agg_costs,
6056  dNumGroups));
6057  }
6058  else if (parse->groupClause)
6059  {
6060  /*
6061  * We have GROUP BY without aggregation or grouping sets.
6062  * Make a GroupPath.
6063  */
6064  add_path(grouped_rel, (Path *)
6065  create_group_path(root,
6066  grouped_rel,
6067  path,
6068  target,
6069  parse->groupClause,
6070  havingQual,
6071  dNumGroups));
6072  }
6073  else
6074  {
6075  /* Other cases should have been handled above */
6076  Assert(false);
6077  }
6078  }
6079  }
6080 
6081  /*
6082  * Now generate a complete GroupAgg Path atop of the cheapest partial
6083  * path. We can do this using either Gather or Gather Merge.
6084  */
6085  if (grouped_rel->partial_pathlist)
6086  {
6087  Path *path = (Path *) linitial(grouped_rel->partial_pathlist);
6088  double total_groups = path->rows * path->parallel_workers;
6089 
6090  path = (Path *) create_gather_path(root,
6091  grouped_rel,
6092  path,
6093  partial_grouping_target,
6094  NULL,
6095  &total_groups);
6096 
6097  /*
6098  * Since Gather's output is always unsorted, we'll need to sort,
6099  * unless there's no GROUP BY clause or a degenerate (constant)
6100  * one, in which case there will only be a single group.
6101  */
6102  if (root->group_pathkeys)
6103  path = (Path *) create_sort_path(root,
6104  grouped_rel,
6105  path,
6106  root->group_pathkeys,
6107  -1.0);
6108 
6109  if (parse->hasAggs)
6110  add_path(grouped_rel, (Path *)
6111  create_agg_path(root,
6112  grouped_rel,
6113  path,
6114  target,
6115  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6117  parse->groupClause,
6118  havingQual,
6119  agg_final_costs,
6120  dNumGroups));
6121  else
6122  add_path(grouped_rel, (Path *)
6123  create_group_path(root,
6124  grouped_rel,
6125  path,
6126  target,
6127  parse->groupClause,
6128  havingQual,
6129  dNumGroups));
6130 
6131  /*
6132  * The point of using Gather Merge rather than Gather is that it
6133  * can preserve the ordering of the input path, so there's no
6134  * reason to try it unless (1) it's possible to produce more than
6135  * one output row and (2) we want the output path to be ordered.
6136  */
6137  if (parse->groupClause != NIL && root->group_pathkeys != NIL)
6138  {
6139  foreach(lc, grouped_rel->partial_pathlist)
6140  {
6141  Path *subpath = (Path *) lfirst(lc);
6142  Path *gmpath;
6143  double total_groups;
6144 
6145  /*
6146  * It's useful to consider paths that are already properly
6147  * ordered for Gather Merge, because those don't need a
6148  * sort. It's also useful to consider the cheapest path,
6149  * because sorting it in parallel and then doing Gather
6150  * Merge may be better than doing an unordered Gather
6151  * followed by a sort. But there's no point in considering
6152  * non-cheapest paths that aren't already sorted
6153  * correctly.
6154  */
6155  if (path != subpath &&
6157  subpath->pathkeys))
6158  continue;
6159 
6160  total_groups = subpath->rows * subpath->parallel_workers;
6161 
6162  gmpath = (Path *)
6164  grouped_rel,
6165  subpath,
6166  partial_grouping_target,
6167  root->group_pathkeys,
6168  NULL,
6169  &total_groups);
6170 
6171  if (parse->hasAggs)
6172  add_path(grouped_rel, (Path *)
6173  create_agg_path(root,
6174  grouped_rel,
6175  gmpath,
6176  target,
6177  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
6179  parse->groupClause,
6180  havingQual,
6181  agg_final_costs,
6182  dNumGroups));
6183  else
6184  add_path(grouped_rel, (Path *)
6185  create_group_path(root,
6186  grouped_rel,
6187  gmpath,
6188  target,
6189  parse->groupClause,
6190  havingQual,
6191  dNumGroups));
6192  }
6193  }
6194  }
6195  }
6196 
6197  if (can_hash)
6198  {
6199  Size hashaggtablesize;
6200 
6201  if (parse->groupingSets)
6202  {
6203  /*
6204  * Try for a hash-only groupingsets path over unsorted input.
6205  */
6206  consider_groupingsets_paths(root, grouped_rel,
6207  cheapest_path, false, true, target,
6208  gd, agg_costs, dNumGroups);
6209  }
6210  else
6211  {
6212  hashaggtablesize = estimate_hashagg_tablesize(cheapest_path,
6213  agg_costs,
6214  dNumGroups);
6215 
6216  /*
6217  * Provided that the estimated size of the hashtable does not
6218  * exceed work_mem, we'll generate a HashAgg Path, although if we
6219  * were unable to sort above, then we'd better generate a Path, so
6220  * that we at least have one.
6221  */
6222  if (hashaggtablesize < work_mem * 1024L ||
6223  grouped_rel->pathlist == NIL)
6224  {
6225  /*
6226  * We just need an Agg over the cheapest-total input path,
6227  * since input order won't matter.
6228  */
6229  add_path(grouped_rel, (Path *)
6230  create_agg_path(root, grouped_rel,
6231  cheapest_path,
6232  target,
6233  AGG_HASHED,
6235  parse->groupClause,
6236  havingQual,
6237  agg_costs,
6238  dNumGroups));
6239  }
6240  }
6241 
6242  /*
6243  * Generate a HashAgg Path atop of the cheapest partial path. Once
6244  * again, we'll only do this if it looks as though the hash table
6245  * won't exceed work_mem.
6246  */
6247  if (grouped_rel->partial_pathlist)
6248  {
6249  Path *path = (Path *) linitial(grouped_rel->partial_pathlist);
6250 
6251  hashaggtablesize = estimate_hashagg_tablesize(path,
6252  agg_final_costs,
6253  dNumGroups);
6254 
6255  if (hashaggtablesize < work_mem * 1024L)
6256  {
6257  double total_groups = path->rows * path->parallel_workers;
6258 
6259  path = (Path *) create_gather_path(root,
6260  grouped_rel,
6261  path,
6262  partial_grouping_target,
6263  NULL,
6264  &total_groups);
6265 
6266  add_path(grouped_rel, (Path *)
6267  create_agg_path(root,
6268  grouped_rel,
6269  path,
6270  target,
6271  AGG_HASHED,
6273  parse->groupClause,
6274  havingQual,
6275  agg_final_costs,
6276  dNumGroups));
6277  }
6278  }
6279  }
6280 }
List * group_pathkeys
Definition: relation.h:264
#define NIL
Definition: pg_list.h:69
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1808
Query * parse
Definition: relation.h:155
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool hasAggs
Definition: parsenodes.h:123
int parallel_workers
Definition: relation.h:1053
List * groupingSets
Definition: parsenodes.h:148
List * partial_pathlist
Definition: relation.h:601
static void consider_groupingsets_paths(PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, PathTarget *target, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3878
#define linitial(l)
Definition: pg_list.h:111
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:2762
struct Path * cheapest_total_path
Definition: relation.h:603
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2651
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3577
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
int work_mem
Definition: globals.c:113
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1717
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2607
List * pathkeys
Definition: relation.h:1060
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
size_t Size
Definition: c.h:422
List * groupClause
Definition: parsenodes.h:146
List * pathlist
Definition: relation.h:599
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ adjust_paths_for_srfs()

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

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

5559 {
5560  ListCell *lc;
5561 
5562  Assert(list_length(targets) == list_length(targets_contain_srfs));
5563  Assert(!linitial_int(targets_contain_srfs));
5564 
5565  /* If no SRFs appear at this plan level, nothing to do */
5566  if (list_length(targets) == 1)
5567  return;
5568 
5569  /*
5570  * Stack SRF-evaluation nodes atop each path for the rel.
5571  *
5572  * In principle we should re-run set_cheapest() here to identify the
5573  * cheapest path, but it seems unlikely that adding the same tlist eval
5574  * costs to all the paths would change that, so we don't bother. Instead,
5575  * just assume that the cheapest-startup and cheapest-total paths remain
5576  * so. (There should be no parameterized paths anymore, so we needn't
5577  * worry about updating cheapest_parameterized_paths.)
5578  */
5579  foreach(lc, rel->pathlist)
5580  {
5581  Path *subpath = (Path *) lfirst(lc);
5582  Path *newpath = subpath;
5583  ListCell *lc1,
5584  *lc2;
5585 
5586  Assert(subpath->param_info == NULL);
5587  forboth(lc1, targets, lc2, targets_contain_srfs)
5588  {
5589  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5590  bool contains_srfs = (bool) lfirst_int(lc2);
5591 
5592  /* If this level doesn't contain SRFs, do regular projection */
5593  if (contains_srfs)
5594  newpath = (Path *) create_set_projection_path(root,
5595  rel,
5596  newpath,
5597  thistarget);
5598  else
5599  newpath = (Path *) apply_projection_to_path(root,
5600  rel,
5601  newpath,
5602  thistarget);
5603  }
5604  lfirst(lc) = newpath;
5605  if (subpath == rel->cheapest_startup_path)
5606  rel->cheapest_startup_path = newpath;
5607  if (subpath == rel->cheapest_total_path)
5608  rel->cheapest_total_path = newpath;
5609  }
5610 
5611  /* Likewise for partial paths, if any */
5612  foreach(lc, rel->partial_pathlist)
5613  {
5614  Path *subpath = (Path *) lfirst(lc);
5615  Path *newpath = subpath;
5616  ListCell *lc1,
5617  *lc2;
5618 
5619  Assert(subpath->param_info == NULL);
5620  forboth(lc1, targets, lc2, targets_contain_srfs)
5621  {
5622  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5623  bool contains_srfs = (bool) lfirst_int(lc2);
5624 
5625  /* If this level doesn't contain SRFs, do regular projection */
5626  if (contains_srfs)
5627  newpath = (Path *) create_set_projection_path(root,
5628  rel,
5629  newpath,
5630  thistarget);
5631  else
5632  {
5633  /* avoid apply_projection_to_path, in case of multiple refs */
5634  newpath = (Path *) create_projection_path(root,
5635  rel,
5636  newpath,
5637  thistarget);
5638  }
5639  }
5640  lfirst(lc) = newpath;
5641  }
5642 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2451
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
struct Path * cheapest_startup_path
Definition: relation.h:602
ParamPathInfo * param_info
Definition: relation.h:1049
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2360
List * partial_pathlist
Definition: relation.h:601
char bool
Definition: c.h:265
#define linitial_int(l)
Definition: pg_list.h:112
#define lfirst_int(lc)
Definition: pg_list.h:107
#define lfirst_node(type, lc)
Definition: pg_list.h:109
struct Path * cheapest_total_path
Definition: relation.h:603
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2540
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
List * pathlist
Definition: relation.h:599
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234

◆ can_parallel_agg()

static bool can_parallel_agg ( PlannerInfo root,
RelOptInfo input_rel,
RelOptInfo grouped_rel,
const AggClauseCosts agg_costs 
)
static

Definition at line 6401 of file planner.c.

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

Referenced by create_grouping_paths().

6403 {
6404  Query *parse = root->parse;
6405 
6406  if (!grouped_rel->consider_parallel)
6407  {
6408  /* Not even parallel-safe. */
6409  return false;
6410  }
6411  else if (input_rel->partial_pathlist == NIL)
6412  {
6413  /* Nothing to use as input for partial aggregate. */
6414  return false;
6415  }
6416  else if (!parse->hasAggs && parse->groupClause == NIL)
6417  {
6418  /*
6419  * We don't know how to do parallel aggregation unless we have either
6420  * some aggregates or a grouping clause.
6421  */
6422  return false;
6423  }
6424  else if (parse->groupingSets)
6425  {
6426  /* We don't know how to do grouping sets in parallel. */
6427  return false;
6428  }
6429  else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
6430  {
6431  /* Insufficient support for partial mode. */
6432  return false;
6433  }
6434 
6435  /* Everything looks good. */
6436  return true;
6437 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
bool hasAggs
Definition: parsenodes.h:123
List * groupingSets
Definition: parsenodes.h:148
List * partial_pathlist
Definition: relation.h:601
bool hasNonSerial
Definition: relation.h:61
bool hasNonPartial
Definition: relation.h:60
bool consider_parallel
Definition: relation.h:593
List * groupClause
Definition: parsenodes.h:146
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ consider_groupingsets_paths()

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

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

3887 {
3888  Query *parse = root->parse;
3889 
3890  /*
3891  * If we're not being offered sorted input, then only consider plans that
3892  * can be done entirely by hashing.
3893  *
3894  * We can hash everything if it looks like it'll fit in work_mem. But if
3895  * the input is actually sorted despite not being advertised as such, we
3896  * prefer to make use of that in order to use less memory.
3897  *
3898  * If none of the grouping sets are sortable, then ignore the work_mem
3899  * limit and generate a path anyway, since otherwise we'll just fail.
3900  */
3901  if (!is_sorted)
3902  {
3903  List *new_rollups = NIL;
3904  RollupData *unhashed_rollup = NULL;
3905  List *sets_data;
3906  List *empty_sets_data = NIL;
3907  List *empty_sets = NIL;
3908  ListCell *lc;
3909  ListCell *l_start = list_head(gd->rollups);
3910  AggStrategy strat = AGG_HASHED;
3911  Size hashsize;
3912  double exclude_groups = 0.0;
3913 
3914  Assert(can_hash);
3915 
3916  if (pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
3917  {
3918  unhashed_rollup = lfirst_node(RollupData, l_start);
3919  exclude_groups = unhashed_rollup->numGroups;
3920  l_start = lnext(l_start);
3921  }
3922 
3923  hashsize = estimate_hashagg_tablesize(path,
3924  agg_costs,
3925  dNumGroups - exclude_groups);
3926 
3927  /*
3928  * gd->rollups is empty if we have only unsortable columns to work
3929  * with. Override work_mem in that case; otherwise, we'll rely on the
3930  * sorted-input case to generate usable mixed paths.
3931  */
3932  if (hashsize > work_mem * 1024L && gd->rollups)
3933  return; /* nope, won't fit */
3934 
3935  /*
3936  * We need to burst the existing rollups list into individual grouping
3937  * sets and recompute a groupClause for each set.
3938  */
3939  sets_data = list_copy(gd->unsortable_sets);
3940 
3941  for_each_cell(lc, l_start)
3942  {
3943  RollupData *rollup = lfirst_node(RollupData, lc);
3944 
3945  /*
3946  * If we find an unhashable rollup that's not been skipped by the
3947  * "actually sorted" check above, we can't cope; we'd need sorted
3948  * input (with a different sort order) but we can't get that here.
3949  * So bail out; we'll get a valid path from the is_sorted case
3950  * instead.
3951  *
3952  * The mere presence of empty grouping sets doesn't make a rollup
3953  * unhashable (see preprocess_grouping_sets), we handle those
3954  * specially below.
3955  */
3956  if (!rollup->hashable)
3957  return;
3958  else
3959  sets_data = list_concat(sets_data, list_copy(rollup->gsets_data));
3960  }
3961  foreach(lc, sets_data)
3962  {
3964  List *gset = gs->set;
3965  RollupData *rollup;
3966 
3967  if (gset == NIL)
3968  {
3969  /* Empty grouping sets can't be hashed. */
3970  empty_sets_data = lappend(empty_sets_data, gs);
3971  empty_sets = lappend(empty_sets, NIL);
3972  }
3973  else
3974  {
3975  rollup = makeNode(RollupData);
3976 
3977  rollup->groupClause = preprocess_groupclause(root, gset);
3978  rollup->gsets_data = list_make1(gs);
3979  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
3980  rollup->gsets_data,
3981  gd->tleref_to_colnum_map);
3982  rollup->numGroups = gs->numGroups;
3983  rollup->hashable = true;
3984  rollup->is_hashed = true;
3985  new_rollups = lappend(new_rollups, rollup);
3986  }
3987  }
3988 
3989  /*
3990  * If we didn't find anything nonempty to hash, then bail. We'll
3991  * generate a path from the is_sorted case.
3992  */
3993  if (new_rollups == NIL)
3994  return;
3995 
3996  /*
3997  * If there were empty grouping sets they should have been in the
3998  * first rollup.
3999  */
4000  Assert(!unhashed_rollup || !empty_sets);
4001 
4002  if (unhashed_rollup)
4003  {
4004  new_rollups = lappend(new_rollups, unhashed_rollup);
4005  strat = AGG_MIXED;
4006  }
4007  else if (empty_sets)
4008  {
4009  RollupData *rollup = makeNode(RollupData);
4010 
4011  rollup->groupClause = NIL;
4012  rollup->gsets_data = empty_sets_data;
4013  rollup->gsets = empty_sets;
4014  rollup->numGroups = list_length(empty_sets);
4015  rollup->hashable = false;
4016  rollup->is_hashed = false;
4017  new_rollups = lappend(new_rollups, rollup);
4018  strat = AGG_MIXED;
4019  }
4020 
4021  add_path(grouped_rel, (Path *)
4023  grouped_rel,
4024  path,
4025  target,
4026  (List *) parse->havingQual,
4027  strat,
4028  new_rollups,
4029  agg_costs,
4030  dNumGroups));
4031  return;
4032  }
4033 
4034  /*
4035  * If we have sorted input but nothing we can do with it, bail.
4036  */
4037  if (list_length(gd->rollups) == 0)
4038  return;
4039 
4040  /*
4041  * Given sorted input, we try and make two paths: one sorted and one mixed
4042  * sort/hash. (We need to try both because hashagg might be disabled, or
4043  * some columns might not be sortable.)
4044  *
4045  * can_hash is passed in as false if some obstacle elsewhere (such as
4046  * ordered aggs) means that we shouldn't consider hashing at all.
4047  */
4048  if (can_hash && gd->any_hashable)
4049  {
4050  List *rollups = NIL;
4051  List *hash_sets = list_copy(gd->unsortable_sets);
4052  double availspace = (work_mem * 1024.0);
4053  ListCell *lc;
4054 
4055  /*
4056  * Account first for space needed for groups we can't sort at all.
4057  */
4058  availspace -= (double) estimate_hashagg_tablesize(path,
4059  agg_costs,
4060  gd->dNumHashGroups);
4061 
4062  if (availspace > 0 && list_length(gd->rollups) > 1)
4063  {
4064  double scale;
4065  int num_rollups = list_length(gd->rollups);
4066  int k_capacity;
4067  int *k_weights = palloc(num_rollups * sizeof(int));
4068  Bitmapset *hash_items = NULL;
4069  int i;
4070 
4071  /*
4072  * We treat this as a knapsack problem: the knapsack capacity
4073  * represents work_mem, the item weights are the estimated memory
4074  * usage of the hashtables needed to implement a single rollup,
4075  * and we really ought to use the cost saving as the item value;
4076  * however, currently the costs assigned to sort nodes don't
4077  * reflect the comparison costs well, and so we treat all items as
4078  * of equal value (each rollup we hash instead saves us one sort).
4079  *
4080  * To use the discrete knapsack, we need to scale the values to a
4081  * reasonably small bounded range. We choose to allow a 5% error
4082  * margin; we have no more than 4096 rollups in the worst possible
4083  * case, which with a 5% error margin will require a bit over 42MB
4084  * of workspace. (Anyone wanting to plan queries that complex had
4085  * better have the memory for it. In more reasonable cases, with
4086  * no more than a couple of dozen rollups, the memory usage will
4087  * be negligible.)
4088  *
4089  * k_capacity is naturally bounded, but we clamp the values for
4090  * scale and weight (below) to avoid overflows or underflows (or
4091  * uselessly trying to use a scale factor less than 1 byte).
4092  */
4093  scale = Max(availspace / (20.0 * num_rollups), 1.0);
4094  k_capacity = (int) floor(availspace / scale);
4095 
4096  /*
4097  * We leave the first rollup out of consideration since it's the
4098  * one that matches the input sort order. We assign indexes "i"
4099  * to only those entries considered for hashing; the second loop,
4100  * below, must use the same condition.
4101  */
4102  i = 0;
4104  {
4105  RollupData *rollup = lfirst_node(RollupData, lc);
4106 
4107  if (rollup->hashable)
4108  {
4109  double sz = estimate_hashagg_tablesize(path,
4110  agg_costs,
4111  rollup->numGroups);
4112 
4113  /*
4114  * If sz is enormous, but work_mem (and hence scale) is
4115  * small, avoid integer overflow here.
4116  */
4117  k_weights[i] = (int) Min(floor(sz / scale),
4118  k_capacity + 1.0);
4119  ++i;
4120  }
4121  }
4122 
4123  /*
4124  * Apply knapsack algorithm; compute the set of items which
4125  * maximizes the value stored (in this case the number of sorts
4126  * saved) while keeping the total size (approximately) within
4127  * capacity.
4128  */
4129  if (i > 0)
4130  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4131 
4132  if (!bms_is_empty(hash_items))
4133  {
4134  rollups = list_make1(linitial(gd->rollups));
4135 
4136  i = 0;
4138  {
4139  RollupData *rollup = lfirst_node(RollupData, lc);
4140 
4141  if (rollup->hashable)
4142  {
4143  if (bms_is_member(i, hash_items))
4144  hash_sets = list_concat(hash_sets,
4145  list_copy(rollup->gsets_data));
4146  else
4147  rollups = lappend(rollups, rollup);
4148  ++i;
4149  }
4150  else
4151  rollups = lappend(rollups, rollup);
4152  }
4153  }
4154  }
4155 
4156  if (!rollups && hash_sets)
4157  rollups = list_copy(gd->rollups);
4158 
4159  foreach(lc, hash_sets)
4160  {
4162  RollupData *rollup = makeNode(RollupData);
4163 
4164  Assert(gs->set != NIL);
4165 
4166  rollup->groupClause = preprocess_groupclause(root, gs->set);
4167  rollup->gsets_data = list_make1(gs);
4168  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4169  rollup->gsets_data,
4170  gd->tleref_to_colnum_map);
4171  rollup->numGroups = gs->numGroups;
4172  rollup->hashable = true;
4173  rollup->is_hashed = true;
4174  rollups = lcons(rollup, rollups);
4175  }
4176 
4177  if (rollups)
4178  {
4179  add_path(grouped_rel, (Path *)
4181  grouped_rel,
4182  path,
4183  target,
4184  (List *) parse->havingQual,
4185  AGG_MIXED,
4186  rollups,
4187  agg_costs,
4188  dNumGroups));
4189  }
4190  }
4191 
4192  /*
4193  * Now try the simple sorted case.
4194  */
4195  if (!gd->unsortable_sets)
4196  add_path(grouped_rel, (Path *)
4198  grouped_rel,
4199  path,
4200  target,
4201  (List *) parse->havingQual,
4202  AGG_SORTED,
4203  gd->rollups,
4204  agg_costs,
4205  dNumGroups));
4206 }
List * group_pathkeys
Definition: relation.h:264
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
List * groupClause
Definition: relation.h:1581
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:3008
#define Min(x, y)
Definition: c.h:846
bool is_hashed
Definition: relation.h:1586
List * list_copy(const List *oldlist)
Definition: list.c:1160
int scale
Definition: pgbench.c:111
double dNumHashGroups
Definition: planner.c:104
List * list_concat(List *list1, List *list2)
Definition: list.c:321
double numGroups
Definition: relation.h:1584
#define list_make1(x1)
Definition: pg_list.h:139
GroupingSetsPath * create_groupingsets_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *having_qual, AggStrategy aggstrategy, List *rollups, const AggClauseCosts *agg_costs, double numGroups)
Definition: pathnode.c:2828
#define linitial(l)
Definition: pg_list.h:111
int * tleref_to_colnum_map
Definition: planner.c:109
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3577
List * lappend(List *list, void *datum)
Definition: list.c:128
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:707
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
static List * remap_to_groupclause_idx(List *groupClause, List *gsets, int *tleref_to_colnum_map)
Definition: planner.c:2363
int work_mem
Definition: globals.c:113
List * lcons(void *datum, List *list)
Definition: list.c:259
List * pathkeys
Definition: relation.h:1060
#define Max(x, y)
Definition: c.h:840
#define makeNode(_type_)
Definition: nodes.h:561
#define Assert(condition)
Definition: c.h:688
size_t Size
Definition: c.h:422
static int list_length(const List *l)
Definition: pg_list.h:89
List * unsortable_sets
Definition: planner.c:108
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
AggStrategy
Definition: nodes.h:739
void * palloc(Size size)
Definition: mcxt.c:835
int i
double numGroups
Definition: relation.h:1575
bool hashable
Definition: relation.h:1585
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
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:464
List * gsets_data
Definition: relation.h:1583
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1582

◆ create_distinct_paths()

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

Definition at line 4404 of file planner.c.

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

Referenced by grouping_planner().

4406 {
4407  Query *parse = root->parse;
4408  Path *cheapest_input_path = input_rel->cheapest_total_path;
4409  RelOptInfo *distinct_rel;
4410  double numDistinctRows;
4411  bool allow_hash;
4412  Path *path;
4413  ListCell *lc;
4414 
4415  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4416  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4417 
4418  /*
4419  * We don't compute anything at this level, so distinct_rel will be
4420  * parallel-safe if the input rel is parallel-safe. In particular, if
4421  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4422  * output those expressions, and will not be parallel-safe unless those
4423  * expressions are parallel-safe.
4424  */
4425  distinct_rel->consider_parallel = input_rel->consider_parallel;
4426 
4427  /*
4428  * If the input rel belongs to a single FDW, so does the distinct_rel.
4429  */
4430  distinct_rel->serverid = input_rel->serverid;
4431  distinct_rel->userid = input_rel->userid;
4432  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4433  distinct_rel->fdwroutine = input_rel->fdwroutine;
4434 
4435  /* Estimate number of distinct rows there will be */
4436  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4437  root->hasHavingQual)
4438  {
4439  /*
4440  * If there was grouping or aggregation, use the number of input rows
4441  * as the estimated number of DISTINCT rows (ie, assume the input is
4442  * already mostly unique).
4443  */
4444  numDistinctRows = cheapest_input_path->rows;
4445  }
4446  else
4447  {
4448  /*
4449  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4450  */
4451  List *distinctExprs;
4452 
4453  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4454  parse->targetList);
4455  numDistinctRows = estimate_num_groups(root, distinctExprs,
4456  cheapest_input_path->rows,
4457  NULL);
4458  }
4459 
4460  /*
4461  * Consider sort-based implementations of DISTINCT, if possible.
4462  */
4464  {
4465  /*
4466  * First, if we have any adequately-presorted paths, just stick a
4467  * Unique node on those. Then consider doing an explicit sort of the
4468  * cheapest input path and Unique'ing that.
4469  *
4470  * When we have DISTINCT ON, we must sort by the more rigorous of
4471  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4472  * Also, if we do have to do an explicit sort, we might as well use
4473  * the more rigorous ordering to avoid a second sort later. (Note
4474  * that the parser will have ensured that one clause is a prefix of
4475  * the other.)
4476  */
4477  List *needed_pathkeys;
4478 
4479  if (parse->hasDistinctOn &&
4481  list_length(root->sort_pathkeys))
4482  needed_pathkeys = root->sort_pathkeys;
4483  else
4484  needed_pathkeys = root->distinct_pathkeys;
4485 
4486  foreach(lc, input_rel->pathlist)
4487  {
4488  Path *path = (Path *) lfirst(lc);
4489 
4490  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4491  {
4492  add_path(distinct_rel, (Path *)
4493  create_upper_unique_path(root, distinct_rel,
4494  path,
4496  numDistinctRows));
4497  }
4498  }
4499 
4500  /* For explicit-sort case, always use the more rigorous clause */
4501  if (list_length(root->distinct_pathkeys) <
4502  list_length(root->sort_pathkeys))
4503  {
4504  needed_pathkeys = root->sort_pathkeys;
4505  /* Assert checks that parser didn't mess up... */
4507  needed_pathkeys));
4508  }
4509  else
4510  needed_pathkeys = root->distinct_pathkeys;
4511 
4512  path = cheapest_input_path;
4513  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4514  path = (Path *) create_sort_path(root, distinct_rel,
4515  path,
4516  needed_pathkeys,
4517  -1.0);
4518 
4519  add_path(distinct_rel, (Path *)
4520  create_upper_unique_path(root, distinct_rel,
4521  path,
4523  numDistinctRows));
4524  }
4525 
4526  /*
4527  * Consider hash-based implementations of DISTINCT, if possible.
4528  *
4529  * If we were not able to make any other types of path, we *must* hash or
4530  * die trying. If we do have other choices, there are several things that
4531  * should prevent selection of hashing: if the query uses DISTINCT ON
4532  * (because it won't really have the expected behavior if we hash), or if
4533  * enable_hashagg is off, or if it looks like the hashtable will exceed
4534  * work_mem.
4535  *
4536  * Note: grouping_is_hashable() is much more expensive to check than the
4537  * other gating conditions, so we want to do it last.
4538  */
4539  if (distinct_rel->pathlist == NIL)
4540  allow_hash = true; /* we have no alternatives */
4541  else if (parse->hasDistinctOn || !enable_hashagg)
4542  allow_hash = false; /* policy-based decision not to hash */
4543  else
4544  {
4545  Size hashentrysize;
4546 
4547  /* Estimate per-hash-entry space at tuple width... */
4548  hashentrysize = MAXALIGN(cheapest_input_path->pathtarget->width) +
4550  /* plus the per-hash-entry overhead */
4551  hashentrysize += hash_agg_entry_size(0);
4552 
4553  /* Allow hashing only if hashtable is predicted to fit in work_mem */
4554  allow_hash = (hashentrysize * numDistinctRows <= work_mem * 1024L);
4555  }
4556 
4557  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4558  {
4559  /* Generate hashed aggregate path --- no sort needed */
4560  add_path(distinct_rel, (Path *)
4561  create_agg_path(root,
4562  distinct_rel,
4563  cheapest_input_path,
4564  cheapest_input_path->pathtarget,
4565  AGG_HASHED,
4567  parse->distinctClause,
4568  NIL,
4569  NULL,
4570  numDistinctRows));
4571  }
4572 
4573  /* Give a helpful error if we failed to find any implementation */
4574  if (distinct_rel->pathlist == NIL)
4575  ereport(ERROR,
4576  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4577  errmsg("could not implement DISTINCT"),
4578  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4579 
4580  /*
4581  * If there is an FDW that's responsible for all baserels of the query,
4582  * let it consider adding ForeignPaths.
4583  */
4584  if (distinct_rel->fdwroutine &&
4585  distinct_rel->fdwroutine->GetForeignUpperPaths)
4586  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4587  input_rel, distinct_rel);
4588 
4589  /* Let extensions possibly add some more paths */
4591  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4592  input_rel, distinct_rel);
4593 
4594  /* Now choose the best path(s) */
4595  set_cheapest(distinct_rel);
4596 
4597  return distinct_rel;
4598 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:197
#define NIL
Definition: pg_list.h:69
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3398
PathTarget * pathtarget
Definition: relation.h:1047
Query * parse
Definition: relation.h:155
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:2710
Oid userid
Definition: relation.h:633
bool hasAggs
Definition: parsenodes.h:123
List * groupingSets
Definition: parsenodes.h:148
int errcode(int sqlerrcode)
Definition: elog.c:575
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:70
bool useridiscurrent
Definition: relation.h:634
bool hasDistinctOn
Definition: parsenodes.h:127
List * targetList
Definition: parsenodes.h:138
List * distinctClause
Definition: parsenodes.h:154
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
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:2762
struct Path * cheapest_total_path
Definition: relation.h:603
struct FdwRoutine * fdwroutine
Definition: relation.h:636
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * sort_pathkeys
Definition: relation.h:267
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: relation.h:632
#define SizeofMinimalTupleHeader
Definition: htup_details.h:655
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
int work_mem
Definition: globals.c:113
List * distinct_pathkeys
Definition: relation.h:266
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2607
List * pathkeys
Definition: relation.h:1060
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
size_t Size
Definition: c.h:422
static int list_length(const List *l)
Definition: pg_list.h:89
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:1424
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
#define MAXALIGN(LEN)
Definition: c.h:641
bool consider_parallel
Definition: relation.h:593
bool enable_hashagg
Definition: costsize.c:124
int width
Definition: relation.h:979
List * groupClause
Definition: parsenodes.h:146
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
bool hasHavingQual
Definition: relation.h:305
List * pathlist
Definition: relation.h:599
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ create_grouping_paths()

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

Definition at line 3621 of file planner.c.

References add_partial_paths_to_grouping_rel(), add_path(), add_paths_to_grouping_rel(), AGGSPLIT_FINAL_DESERIAL, AGGSPLIT_INITIAL_SERIAL, grouping_sets_data::any_hashable, can_parallel_agg(), RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_append_path(), create_result_path(), create_upper_paths_hook, ereport, errcode(), errdetail(), errmsg(), ERROR, PathTarget::exprs, RelOptInfo::fdwroutine, fetch_upper_rel(), get_agg_clause_costs(), get_number_of_groups(), FdwRoutine::GetForeignUpperPaths, Query::groupClause, grouping_is_hashable(), grouping_is_sortable(), Query::groupingSets, Query::hasAggs, PlannerInfo::hasHavingQual, Query::havingQual, is_parallel_safe(), lappend(), list_length(), make_partial_grouping_target(), MemSet, NIL, AggClauseCosts::numOrderedAggs, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, Path::pathtarget, grouping_sets_data::rollups, Path::rows, RelOptInfo::serverid, set_cheapest(), UPPERREL_GROUP_AGG, RelOptInfo::userid, and RelOptInfo::useridiscurrent.

Referenced by grouping_planner().

3626 {
3627  Query *parse = root->parse;
3628  Path *cheapest_path = input_rel->cheapest_total_path;
3629  RelOptInfo *grouped_rel;
3630  PathTarget *partial_grouping_target = NULL;
3631  AggClauseCosts agg_partial_costs; /* parallel only */
3632  AggClauseCosts agg_final_costs; /* parallel only */
3633  double dNumGroups;
3634  bool can_hash;
3635  bool can_sort;
3636  bool try_parallel_aggregation;
3637 
3638  /* For now, do all work in the (GROUP_AGG, NULL) upperrel */
3639  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
3640 
3641  /*
3642  * If the input relation is not parallel-safe, then the grouped relation
3643  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
3644  * target list and HAVING quals are parallel-safe.
3645  */
3646  if (input_rel->consider_parallel &&
3647  is_parallel_safe(root, (Node *) target->exprs) &&
3648  is_parallel_safe(root, (Node *) parse->havingQual))
3649  grouped_rel->consider_parallel = true;
3650 
3651  /*
3652  * If the input rel belongs to a single FDW, so does the grouped rel.
3653  */
3654  grouped_rel->serverid = input_rel->serverid;
3655  grouped_rel->userid = input_rel->userid;
3656  grouped_rel->useridiscurrent = input_rel->useridiscurrent;
3657  grouped_rel->fdwroutine = input_rel->fdwroutine;
3658 
3659  /*
3660  * Check for degenerate grouping.
3661  */
3662  if ((root->hasHavingQual || parse->groupingSets) &&
3663  !parse->hasAggs && parse->groupClause == NIL)
3664  {
3665  /*
3666  * We have a HAVING qual and/or grouping sets, but no aggregates and
3667  * no GROUP BY (which implies that the grouping sets are all empty).
3668  *
3669  * This is a degenerate case in which we are supposed to emit either
3670  * zero or one row for each grouping set depending on whether HAVING
3671  * succeeds. Furthermore, there cannot be any variables in either
3672  * HAVING or the targetlist, so we actually do not need the FROM table
3673  * at all! We can just throw away the plan-so-far and generate a
3674  * Result node. This is a sufficiently unusual corner case that it's
3675  * not worth contorting the structure of this module to avoid having
3676  * to generate the earlier paths in the first place.
3677  */
3678  int nrows = list_length(parse->groupingSets);
3679  Path *path;
3680 
3681  if (nrows > 1)
3682  {
3683  /*
3684  * Doesn't seem worthwhile writing code to cons up a
3685  * generate_series or a values scan to emit multiple rows. Instead
3686  * just make N clones and append them. (With a volatile HAVING
3687  * clause, this means you might get between 0 and N output rows.
3688  * Offhand I think that's desired.)
3689  */
3690  List *paths = NIL;
3691 
3692  while (--nrows >= 0)
3693  {
3694  path = (Path *)
3695  create_result_path(root, grouped_rel,
3696  target,
3697  (List *) parse->havingQual);
3698  paths = lappend(paths, path);
3699  }
3700  path = (Path *)
3701  create_append_path(grouped_rel,
3702  paths,
3703  NIL,
3704  NULL,
3705  0,
3706  false,
3707  NIL,
3708  -1);
3709  path->pathtarget = target;
3710  }
3711  else
3712  {
3713  /* No grouping sets, or just one, so one output row */
3714  path = (Path *)
3715  create_result_path(root, grouped_rel,
3716  target,
3717  (List *) parse->havingQual);
3718  }
3719 
3720  add_path(grouped_rel, path);
3721 
3722  /* No need to consider any other alternatives. */
3723  set_cheapest(grouped_rel);
3724 
3725  return grouped_rel;
3726  }
3727 
3728  /*
3729  * Estimate number of groups.
3730  */
3731  dNumGroups = get_number_of_groups(root,
3732  cheapest_path->rows,
3733  gd);
3734 
3735  /*
3736  * Determine whether it's possible to perform sort-based implementations
3737  * of grouping. (Note that if groupClause is empty,
3738  * grouping_is_sortable() is trivially true, and all the
3739  * pathkeys_contained_in() tests will succeed too, so that we'll consider
3740  * every surviving input path.)
3741  *
3742  * If we have grouping sets, we might be able to sort some but not all of
3743  * them; in this case, we need can_sort to be true as long as we must
3744  * consider any sorted-input plan.
3745  */
3746  can_sort = (gd && gd->rollups != NIL)
3747  || grouping_is_sortable(parse->groupClause);
3748 
3749  /*
3750  * Determine whether we should consider hash-based implementations of
3751  * grouping.
3752  *
3753  * Hashed aggregation only applies if we're grouping. If we have grouping
3754  * sets, some groups might be hashable but others not; in this case we set
3755  * can_hash true as long as there is nothing globally preventing us from
3756  * hashing (and we should therefore consider plans with hashes).
3757  *
3758  * Executor doesn't support hashed aggregation with DISTINCT or ORDER BY
3759  * aggregates. (Doing so would imply storing *all* the input values in
3760  * the hash table, and/or running many sorts in parallel, either of which
3761  * seems like a certain loser.) We similarly don't support ordered-set
3762  * aggregates in hashed aggregation, but that case is also included in the
3763  * numOrderedAggs count.
3764  *
3765  * Note: grouping_is_hashable() is much more expensive to check than the
3766  * other gating conditions, so we want to do it last.
3767  */
3768  can_hash = (parse->groupClause != NIL &&
3769  agg_costs->numOrderedAggs == 0 &&
3770  (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause)));
3771 
3772  /*
3773  * Figure out whether a PartialAggregate/Finalize Aggregate execution
3774  * strategy is viable.
3775  */
3776  try_parallel_aggregation = can_parallel_agg(root, input_rel, grouped_rel,
3777  agg_costs);
3778 
3779  /*
3780  * Before generating paths for grouped_rel, we first generate any possible
3781  * partial paths; that way, later code can easily consider both parallel
3782  * and non-parallel approaches to grouping. Note that the partial paths
3783  * we generate here are also partially aggregated, so simply pushing a
3784  * Gather node on top is insufficient to create a final path, as would be
3785  * the case for a scan/join rel.
3786  */
3787  if (try_parallel_aggregation)
3788  {
3789  /*
3790  * Build target list for partial aggregate paths. These paths cannot
3791  * just emit the same tlist as regular aggregate paths, because (1) we
3792  * must include Vars and Aggrefs needed in HAVING, which might not
3793  * appear in the result tlist, and (2) the Aggrefs must be set in
3794  * partial mode.
3795  */
3796  partial_grouping_target = make_partial_grouping_target(root, target);
3797 
3798  /*
3799  * Collect statistics about aggregates for estimating costs of
3800  * performing aggregation in parallel.
3801  */
3802  MemSet(&agg_partial_costs, 0, sizeof(AggClauseCosts));
3803  MemSet(&agg_final_costs, 0, sizeof(AggClauseCosts));
3804  if (parse->hasAggs)
3805  {
3806  /* partial phase */
3807  get_agg_clause_costs(root, (Node *) partial_grouping_target->exprs,
3809  &agg_partial_costs);
3810 
3811  /* final phase */
3812  get_agg_clause_costs(root, (Node *) target->exprs,
3814  &agg_final_costs);
3815  get_agg_clause_costs(root, parse->havingQual,
3817  &agg_final_costs);
3818  }
3819 
3820  add_partial_paths_to_grouping_rel(root, input_rel, grouped_rel, target,
3821  partial_grouping_target,
3822  &agg_partial_costs, &agg_final_costs,
3823  gd, can_sort, can_hash,
3824  (List *) parse->havingQual);
3825  }
3826 
3827  /* Build final grouping paths */
3828  add_paths_to_grouping_rel(root, input_rel, grouped_rel, target,
3829  partial_grouping_target, agg_costs,
3830  &agg_final_costs, gd, can_sort, can_hash,
3831  dNumGroups, (List *) parse->havingQual);
3832 
3833  /* Give a helpful error if we failed to find any implementation */
3834  if (grouped_rel->pathlist == NIL)
3835  ereport(ERROR,
3836  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3837  errmsg("could not implement GROUP BY"),
3838  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
3839 
3840  /*
3841  * If there is an FDW that's responsible for all baserels of the query,
3842  * let it consider adding ForeignPaths.
3843  */
3844  if (grouped_rel->fdwroutine &&
3845  grouped_rel->fdwroutine->GetForeignUpperPaths)
3847  input_rel, grouped_rel);
3848 
3849  /* Let extensions possibly add some more paths */
3851  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
3852  input_rel, grouped_rel);
3853 
3854  /* Now choose the best path(s) */
3855  set_cheapest(grouped_rel);
3856 
3857  /*
3858  * We've been using the partial pathlist for the grouped relation to hold
3859  * partially aggregated paths, but that's actually a little bit bogus
3860  * because it's unsafe for later planning stages -- like ordered_rel ---
3861  * to get the idea that they can use these partial paths as if they didn't
3862  * need a FinalizeAggregate step. Zap the partial pathlist at this stage
3863  * so we don't get confused.
3864  */
3865  grouped_rel->partial_pathlist = NIL;
3866 
3867  return grouped_rel;
3868 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:197
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:1047
Query * parse
Definition: relation.h:155
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Oid userid
Definition: relation.h:633
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd)
Definition: planner.c:3465
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:470
bool hasAggs
Definition: parsenodes.h:123
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:513
int errcode(int sqlerrcode)
Definition: elog.c:575
List * partial_pathlist
Definition: relation.h:601
#define MemSet(start, val, len)
Definition: c.h:897
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:70
bool useridiscurrent
Definition: relation.h:634
static bool can_parallel_agg(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs)
Definition: planner.c:6401
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target)
Definition: planner.c:4862
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1090
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
struct Path * cheapest_total_path
Definition: relation.h:603
struct FdwRoutine * fdwroutine
Definition: relation.h:636
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
int numOrderedAggs
Definition: relation.h:59
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: relation.h:632
List * exprs
Definition: relation.h:976
double rows
Definition: relation.h:1056
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, List *partial_subpaths, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1213
static int list_length(const List *l)
Definition: pg_list.h:89
static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, PathTarget *target, PathTarget *partial_grouping_target, const AggClauseCosts *agg_costs, const AggClauseCosts *agg_final_costs, grouping_sets_data *gd, bool can_sort, bool can_hash, double dNumGroups, List *havingQual)
Definition: planner.c:5998
bool consider_parallel
Definition: relation.h:593
List * groupClause
Definition: parsenodes.h:146
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
bool hasHavingQual
Definition: relation.h:305
ResultPath * create_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *resconstantqual)
Definition: pathnode.c:1415
List * pathlist
Definition: relation.h:599
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
static void add_partial_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, PathTarget *target, PathTarget *partial_grouping_target, AggClauseCosts *agg_partial_costs, AggClauseCosts *agg_final_costs, grouping_sets_data *gd, bool can_sort, bool can_hash, List *havingQual)
Definition: planner.c:6289
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ create_one_window_path()

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

Definition at line 4309 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(), PathTarget::width, WindowFuncLists::windowFuncs, and WindowClause::winref.

Referenced by create_window_paths().

4317 {
4318  PathTarget *window_target;
4319  ListCell *l;
4320 
4321  /*
4322  * Since each window clause could require a different sort order, we stack
4323  * up a WindowAgg node for each clause, with sort steps between them as
4324  * needed. (We assume that select_active_windows chose a good order for
4325  * executing the clauses in.)
4326  *
4327  * input_target should contain all Vars and Aggs needed for the result.
4328  * (In some cases we wouldn't need to propagate all of these all the way
4329  * to the top, since they might only be needed as inputs to WindowFuncs.
4330  * It's probably not worth trying to optimize that though.) It must also
4331  * contain all window partitioning and sorting expressions, to ensure
4332  * they're computed only once at the bottom of the stack (that's critical
4333  * for volatile functions). As we climb up the stack, we'll add outputs
4334  * for the WindowFuncs computed at each level.
4335  */
4336  window_target = input_target;
4337 
4338  foreach(l, activeWindows)
4339  {
4341  List *window_pathkeys;
4342 
4343  window_pathkeys = make_pathkeys_for_window(root,
4344  wc,
4345  tlist);
4346 
4347  /* Sort if necessary */
4348  if (!pathkeys_contained_in(window_pathkeys, path->pathkeys))
4349  {
4350  path = (Path *) create_sort_path(root, window_rel,
4351  path,
4352  window_pathkeys,
4353  -1.0);
4354  }
4355 
4356  if (lnext(l))
4357  {
4358  /*
4359  * Add the current WindowFuncs to the output target for this
4360  * intermediate WindowAggPath. We must copy window_target to
4361  * avoid changing the previous path's target.
4362  *
4363  * Note: a WindowFunc adds nothing to the target's eval costs; but
4364  * we do need to account for the increase in tlist width.
4365  */
4366  ListCell *lc2;
4367 
4368  window_target = copy_pathtarget(window_target);
4369  foreach(lc2, wflists->windowFuncs[wc->winref])
4370  {
4371  WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
4372 
4373  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4374  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4375  }
4376  }
4377  else
4378  {
4379  /* Install the goal target in the topmost WindowAgg */
4380  window_target = output_target;
4381  }
4382 
4383  path = (Path *)
4384  create_windowagg_path(root, window_rel, path, window_target,
4385  wflists->windowFuncs[wc->winref],
4386  wc,
4387  window_pathkeys);
4388  }
4389 
4390  add_path(window_rel, path);
4391 }
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:629
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5248
#define lnext(lc)
Definition: pg_list.h:105
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, WindowClause *winclause, List *winpathkeys)
Definition: pathnode.c:3057
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2332
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2607
List * pathkeys
Definition: relation.h:1060
Oid wintype
Definition: primnodes.h:356
int width
Definition: relation.h:979
Definition: pg_list.h:45
List ** windowFuncs
Definition: clauses.h:27

◆ create_ordered_paths()

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

Definition at line 4615 of file planner.c.

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

Referenced by grouping_planner().

4619 {
4620  Path *cheapest_input_path = input_rel->cheapest_total_path;
4621  RelOptInfo *ordered_rel;
4622  ListCell *lc;
4623 
4624  /* For now, do all work in the (ORDERED, NULL) upperrel */
4625  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4626 
4627  /*
4628  * If the input relation is not parallel-safe, then the ordered relation
4629  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4630  * target list is parallel-safe.
4631  */
4632  if (input_rel->consider_parallel &&
4633  is_parallel_safe(root, (Node *) target->exprs))
4634  ordered_rel->consider_parallel = true;
4635 
4636  /*
4637  * If the input rel belongs to a single FDW, so does the ordered_rel.
4638  */
4639  ordered_rel->serverid = input_rel->serverid;
4640  ordered_rel->userid = input_rel->userid;
4641  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4642  ordered_rel->fdwroutine = input_rel->fdwroutine;
4643 
4644  foreach(lc, input_rel->pathlist)
4645  {
4646  Path *path = (Path *) lfirst(lc);
4647  bool is_sorted;
4648 
4649  is_sorted = pathkeys_contained_in(root->sort_pathkeys,
4650  path->pathkeys);
4651  if (path == cheapest_input_path || is_sorted)
4652  {
4653  if (!is_sorted)
4654  {
4655  /* An explicit sort here can take advantage of LIMIT */
4656  path = (Path *) create_sort_path(root,
4657  ordered_rel,
4658  path,
4659  root->sort_pathkeys,
4660  limit_tuples);
4661  }
4662 
4663  /* Add projection step if needed */
4664  if (path->pathtarget != target)
4665  path = apply_projection_to_path(root, ordered_rel,
4666  path, target);
4667 
4668  add_path(ordered_rel, path);
4669  }
4670  }
4671 
4672  /*
4673  * generate_gather_paths() will have already generated a simple Gather
4674  * path for the best parallel path, if any, and the loop above will have
4675  * considered sorting it. Similarly, generate_gather_paths() will also
4676  * have generated order-preserving Gather Merge plans which can be used
4677  * without sorting if they happen to match the sort_pathkeys, and the loop
4678  * above will have handled those as well. However, there's one more
4679  * possibility: it may make sense to sort the cheapest partial path
4680  * according to the required output order and then use Gather Merge.
4681  */
4682  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
4683  input_rel->partial_pathlist != NIL)
4684  {
4685  Path *cheapest_partial_path;
4686 
4687  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4688 
4689  /*
4690  * If cheapest partial path doesn't need a sort, this is redundant
4691  * with what's already been tried.
4692  */
4694  cheapest_partial_path->pathkeys))
4695  {
4696  Path *path;
4697  double total_groups;
4698 
4699  path = (Path *) create_sort_path(root,
4700  ordered_rel,
4701  cheapest_partial_path,
4702  root->sort_pathkeys,
4703  limit_tuples);
4704 
4705  total_groups = cheapest_partial_path->rows *
4706  cheapest_partial_path->parallel_workers;
4707  path = (Path *)
4708  create_gather_merge_path(root, ordered_rel,
4709  path,
4710  path->pathtarget,
4711  root->sort_pathkeys, NULL,
4712  &total_groups);
4713 
4714  /* Add projection step if needed */
4715  if (path->pathtarget != target)
4716  path = apply_projection_to_path(root, ordered_rel,
4717  path, target);
4718 
4719  add_path(ordered_rel, path);
4720  }
4721  }
4722 
4723  /*
4724  * If there is an FDW that's responsible for all baserels of the query,
4725  * let it consider adding ForeignPaths.
4726  */
4727  if (ordered_rel->fdwroutine &&
4728  ordered_rel->fdwroutine->GetForeignUpperPaths)
4729  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
4730  input_rel, ordered_rel);
4731 
4732  /* Let extensions possibly add some more paths */
4734  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
4735  input_rel, ordered_rel);
4736 
4737  /*
4738  * No need to bother with set_cheapest here; grouping_planner does not
4739  * need us to do it.
4740  */
4741  Assert(ordered_rel->pathlist != NIL);
4742 
4743  return ordered_rel;
4744 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2451
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:197
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:1047
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Oid userid
Definition: relation.h:633
int parallel_workers
Definition: relation.h:1053
Definition: nodes.h:513
List * partial_pathlist
Definition: relation.h:601
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:70
bool useridiscurrent
Definition: relation.h:634
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1090
#define linitial(l)
Definition: pg_list.h:111
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
struct Path * cheapest_total_path
Definition: relation.h:603
struct FdwRoutine * fdwroutine
Definition: relation.h:636
List * sort_pathkeys
Definition: relation.h:267
Oid serverid
Definition: relation.h:632
List * exprs
Definition: relation.h:976
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1717
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2607
List * pathkeys
Definition: relation.h:1060
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
bool consider_parallel
Definition: relation.h:593
List * pathlist
Definition: relation.h:599

◆ create_window_paths()

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

Definition at line 4223 of file planner.c.

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

4230 {
4231  RelOptInfo *window_rel;
4232  ListCell *lc;
4233 
4234  /* For now, do all work in the (WINDOW, NULL) upperrel */
4235  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4236 
4237  /*
4238  * If the input relation is not parallel-safe, then the window relation
4239  * can't be parallel-safe, either. Otherwise, we need to examine the
4240  * target list and active windows for non-parallel-safe constructs.
4241  */
4242  if (input_rel->consider_parallel &&
4243  is_parallel_safe(root, (Node *) output_target->exprs) &&
4244  is_parallel_safe(root, (Node *) activeWindows))
4245  window_rel->consider_parallel = true;
4246 
4247  /*
4248  * If the input rel belongs to a single FDW, so does the window rel.
4249  */
4250  window_rel->serverid = input_rel->serverid;
4251  window_rel->userid = input_rel->userid;
4252  window_rel->useridiscurrent = input_rel->useridiscurrent;
4253  window_rel->fdwroutine = input_rel->fdwroutine;
4254 
4255  /*
4256  * Consider computing window functions starting from the existing
4257  * cheapest-total path (which will likely require a sort) as well as any
4258  * existing paths that satisfy root->window_pathkeys (which won't).
4259  */
4260  foreach(lc, input_rel->pathlist)
4261  {
4262  Path *path = (Path *) lfirst(lc);
4263 
4264  if (path == input_rel->cheapest_total_path ||
4267  window_rel,
4268  path,
4269  input_target,
4270  output_target,
4271  tlist,
4272  wflists,
4273  activeWindows);
4274  }
4275 
4276  /*
4277  * If there is an FDW that's responsible for all baserels of the query,
4278  * let it consider adding ForeignPaths.
4279  */
4280  if (window_rel->fdwroutine &&
4281  window_rel->fdwroutine->GetForeignUpperPaths)
4282  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4283  input_rel, window_rel);
4284 
4285  /* Let extensions possibly add some more paths */
4287  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4288  input_rel, window_rel);
4289 
4290  /* Now choose the best path(s) */
4291  set_cheapest(window_rel);
4292 
4293  return window_rel;
4294 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:197
Oid userid
Definition: relation.h:633
Definition: nodes.h:513
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:70
bool useridiscurrent
Definition: relation.h:634
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1090
static void create_one_window_path(PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, List *tlist, WindowFuncLists *wflists, List *activeWindows)
Definition: planner.c:4309
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
struct Path * cheapest_total_path
Definition: relation.h:603
struct FdwRoutine * fdwroutine
Definition: relation.h:636
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
Oid serverid
Definition: relation.h:632
List * exprs
Definition: relation.h:976
List * window_pathkeys
Definition: relation.h:265
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
List * pathkeys
Definition: relation.h:1060
#define lfirst(lc)
Definition: pg_list.h:106
bool consider_parallel
Definition: relation.h:593
List * pathlist
Definition: relation.h:599

◆ estimate_hashagg_tablesize()

static Size estimate_hashagg_tablesize ( Path path,
const AggClauseCosts agg_costs,
double  dNumGroups 
)
static

Definition at line 3577 of file planner.c.

References hash_agg_entry_size(), MAXALIGN, AggClauseCosts::numAggs, Path::pathtarget, SizeofMinimalTupleHeader, AggClauseCosts::transitionSpace, and PathTarget::width.

Referenced by add_partial_paths_to_grouping_rel(), add_paths_to_grouping_rel(), and consider_groupingsets_paths().

3579 {
3580  Size hashentrysize;
3581 
3582  /* Estimate per-hash-entry space at tuple width... */
3583  hashentrysize = MAXALIGN(path->pathtarget->width) +
3585 
3586  /* plus space for pass-by-ref transition values... */
3587  hashentrysize += agg_costs->transitionSpace;
3588  /* plus the per-hash-entry overhead */
3589  hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
3590 
3591  /*
3592  * Note that this disregards the effect of fill-factor and growth policy
3593  * of the hash-table. That's probably ok, given default the default
3594  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3595  * "double-in-size" growth policies here.
3596  */
3597  return hashentrysize * dNumGroups;
3598 }
PathTarget * pathtarget
Definition: relation.h:1047
#define SizeofMinimalTupleHeader
Definition: htup_details.h:655
size_t Size
Definition: c.h:422
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:1424
#define MAXALIGN(LEN)
Definition: c.h:641
int width
Definition: relation.h:979
Size transitionSpace
Definition: relation.h:64

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 5667 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

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

5668 {
5669  Node *result;
5670 
5671  /*
5672  * Convert named-argument function calls, insert default arguments and
5673  * simplify constant subexprs
5674  */
5675  result = eval_const_expressions(NULL, (Node *) expr);
5676 
5677  /* Fill in opfuncid values if missing */
5678  fix_opfuncids(result);
5679 
5680  return (Expr *) result;
5681 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
Definition: nodes.h:513
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2462

◆ extract_rollup_sets()

static List * extract_rollup_sets ( List groupingSets)
static

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

3112 {
3113  int num_sets_raw = list_length(groupingSets);
3114  int num_empty = 0;
3115  int num_sets = 0; /* distinct sets */
3116  int num_chains = 0;
3117  List *result = NIL;
3118  List **results;
3119  List **orig_sets;
3120  Bitmapset **set_masks;
3121  int *chains;
3122  short **adjacency;
3123  short *adjacency_buf;
3125  int i;
3126  int j;
3127  int j_size;
3128  ListCell *lc1 = list_head(groupingSets);
3129  ListCell *lc;
3130 
3131  /*
3132  * Start by stripping out empty sets. The algorithm doesn't require this,
3133  * but the planner currently needs all empty sets to be returned in the
3134  * first list, so we strip them here and add them back after.
3135  */
3136  while (lc1 && lfirst(lc1) == NIL)
3137  {
3138  ++num_empty;
3139  lc1 = lnext(lc1);
3140  }
3141 
3142  /* bail out now if it turns out that all we had were empty sets. */
3143  if (!lc1)
3144  return list_make1(groupingSets);
3145 
3146  /*----------
3147  * We don't strictly need to remove duplicate sets here, but if we don't,
3148  * they tend to become scattered through the result, which is a bit
3149  * confusing (and irritating if we ever decide to optimize them out).
3150  * So we remove them here and add them back after.
3151  *
3152  * For each non-duplicate set, we fill in the following:
3153  *
3154  * orig_sets[i] = list of the original set lists
3155  * set_masks[i] = bitmapset for testing inclusion
3156  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3157  *
3158  * chains[i] will be the result group this set is assigned to.
3159  *
3160  * We index all of these from 1 rather than 0 because it is convenient
3161  * to leave 0 free for the NIL node in the graph algorithm.
3162  *----------
3163  */
3164  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3165  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3166  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3167  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3168 
3169  j_size = 0;
3170  j = 0;
3171  i = 1;
3172 
3173  for_each_cell(lc, lc1)
3174  {
3175  List *candidate = (List *) lfirst(lc);
3176  Bitmapset *candidate_set = NULL;
3177  ListCell *lc2;
3178  int dup_of = 0;
3179 
3180  foreach(lc2, candidate)
3181  {
3182  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3183  }
3184 
3185  /* we can only be a dup if we're the same length as a previous set */
3186  if (j_size == list_length(candidate))
3187  {
3188  int k;
3189 
3190  for (k = j; k < i; ++k)
3191  {
3192  if (bms_equal(set_masks[k], candidate_set))
3193  {
3194  dup_of = k;
3195  break;
3196  }
3197  }
3198  }
3199  else if (j_size < list_length(candidate))
3200  {
3201  j_size = list_length(candidate);
3202  j = i;
3203  }
3204 
3205  if (dup_of > 0)
3206  {
3207  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3208  bms_free(candidate_set);
3209  }
3210  else
3211  {
3212  int k;
3213  int n_adj = 0;
3214 
3215  orig_sets[i] = list_make1(candidate);
3216  set_masks[i] = candidate_set;
3217 
3218  /* fill in adjacency list; no need to compare equal-size sets */
3219 
3220  for (k = j - 1; k > 0; --k)
3221  {
3222  if (bms_is_subset(set_masks[k], candidate_set))
3223  adjacency_buf[++n_adj] = k;
3224  }
3225 
3226  if (n_adj > 0)
3227  {
3228  adjacency_buf[0] = n_adj;
3229  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3230  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3231  }
3232  else
3233  adjacency[i] = NULL;
3234 
3235  ++i;
3236  }
3237  }
3238 
3239  num_sets = i - 1;
3240 
3241  /*
3242  * Apply the graph matching algorithm to do the work.
3243  */
3244  state = BipartiteMatch(num_sets, num_sets, adjacency);
3245 
3246  /*
3247  * Now, the state->pair* fields have the info we need to assign sets to
3248  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3249  * pair_vu[v] = u (both will be true, but we check both so that we can do
3250  * it in one pass)
3251  */
3252  chains = palloc0((num_sets + 1) * sizeof(int));
3253 
3254  for (i = 1; i <= num_sets; ++i)
3255  {
3256  int u = state->pair_vu[i];
3257  int v = state->pair_uv[i];
3258 
3259  if (u > 0 && u < i)
3260  chains[i] = chains[u];
3261  else if (v > 0 && v < i)
3262  chains[i] = chains[v];
3263  else
3264  chains[i] = ++num_chains;
3265  }
3266 
3267  /* build result lists. */
3268  results = palloc0((num_chains + 1) * sizeof(List *));
3269 
3270  for (i = 1; i <= num_sets; ++i)
3271  {
3272  int c = chains[i];
3273 
3274  Assert(c > 0);
3275 
3276  results[c] = list_concat(results[c], orig_sets[i]);
3277  }
3278 
3279  /* push any empty sets back on the first list. */
3280  while (num_empty-- > 0)
3281  results[1] = lcons(NIL, results[1]);
3282 
3283  /* make result list */
3284  for (i = 1; i <= num_chains; ++i)
3285  result = lappend(result, results[i]);
3286 
3287  /*
3288  * Free all the things.
3289  *
3290  * (This is over-fussy for small sets but for large sets we could have
3291  * tied up a nontrivial amount of memory.)
3292  */
3293  BipartiteMatchFree(state);
3294  pfree(results);
3295  pfree(chains);
3296  for (i = 1; i <= num_sets; ++i)
3297  if (adjacency[i])
3298  pfree(adjacency[i]);
3299  pfree(adjacency);
3300  pfree(adjacency_buf);
3301  pfree(orig_sets);
3302  for (i = 1; i <= num_sets; ++i)
3303  bms_free(set_masks[i]);
3304  pfree(set_masks);
3305 
3306  return result;
3307 }
#define NIL
Definition: pg_list.h:69
List * list_concat(List *list1, List *list2)
Definition: list.c:321
void BipartiteMatchFree(BipartiteMatchState *state)
#define list_make1(x1)
Definition: pg_list.h:139
void pfree(void *pointer)
Definition: mcxt.c:936
#define lfirst_int(lc)
Definition: pg_list.h:107
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:352
char * c
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc0(Size size)
Definition: mcxt.c:864
BipartiteMatchState * BipartiteMatch(int u_size, int v_size, short **adjacency)
List * lcons(void *datum, List *list)
Definition: list.c:259
void bms_free(Bitmapset *a)
Definition: bitmapset.c:245
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
Definition: regguts.h:298
static int list_length(const List *l)
Definition: pg_list.h:89
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:742
void * palloc(Size size)
Definition: mcxt.c:835
int i
Definition: pg_list.h:45
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:131

◆ get_cheapest_fractional_path()

Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

5515 {
5516  Path *best_path = rel->cheapest_total_path;
5517  ListCell *l;
5518 
5519  /* If all tuples will be retrieved, just return the cheapest-total path */
5520  if (tuple_fraction <= 0.0)
5521  return best_path;
5522 
5523  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5524  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5525  tuple_fraction /= best_path->rows;
5526 
5527  foreach(l, rel->pathlist)
5528  {
5529  Path *path = (Path *) lfirst(l);
5530 
5531  if (path == rel->cheapest_total_path ||
5532  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5533  continue;
5534 
5535  best_path = path;
5536  }
5537 
5538  return best_path;
5539 }
struct Path * cheapest_total_path
Definition: relation.h:603
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:117
List * pathlist
Definition: relation.h:599

◆ get_number_of_groups()

static double get_number_of_groups ( PlannerInfo root,
double  path_rows,
grouping_sets_data gd 
)
static

Definition at line 3465 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, Query::targetList, and grouping_sets_data::unsortable_sets.

Referenced by add_partial_paths_to_grouping_rel(), and create_grouping_paths().

3468 {
3469  Query *parse = root->parse;
3470  double dNumGroups;
3471 
3472  if (parse->groupClause)
3473  {
3474  List *groupExprs;
3475 
3476  if (parse->groupingSets)
3477  {
3478  /* Add up the estimates for each grouping set */
3479  ListCell *lc;
3480  ListCell *lc2;
3481 
3482  Assert(gd); /* keep Coverity happy */
3483 
3484  dNumGroups = 0;
3485 
3486  foreach(lc, gd->rollups)
3487  {
3488  RollupData *rollup = lfirst_node(RollupData, lc);
3489  ListCell *lc;
3490 
3491  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3492  parse->targetList);
3493 
3494  rollup->numGroups = 0.0;
3495 
3496  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3497  {
3498  List *gset = (List *) lfirst(lc);
3500  double numGroups = estimate_num_groups(root,
3501  groupExprs,
3502  path_rows,
3503  &gset);
3504 
3505  gs->numGroups = numGroups;
3506  rollup->numGroups += numGroups;
3507  }
3508 
3509  dNumGroups += rollup->numGroups;
3510  }
3511 
3512  if (gd->hash_sets_idx)
3513  {
3514  ListCell *lc;
3515 
3516  gd->dNumHashGroups = 0;
3517 
3518  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3519  parse->targetList);
3520 
3521  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3522  {
3523  List *gset = (List *) lfirst(lc);
3525  double numGroups = estimate_num_groups(root,
3526  groupExprs,
3527  path_rows,
3528  &gset);
3529 
3530  gs->numGroups = numGroups;
3531  gd->dNumHashGroups += numGroups;
3532  }
3533 
3534  dNumGroups += gd->dNumHashGroups;
3535  }
3536  }
3537  else
3538  {
3539  /* Plain GROUP BY */
3540  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3541  parse->targetList);
3542 
3543  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3544  NULL);
3545  }
3546  }
3547  else if (parse->groupingSets)
3548  {
3549  /* Empty grouping sets ... one result row for each one */
3550  dNumGroups = list_length(parse->groupingSets);
3551  }
3552  else if (parse->hasAggs || root->hasHavingQual)
3553  {
3554  /* Plain aggregation, one result row */
3555  dNumGroups = 1;
3556  }
3557  else
3558  {
3559  /* Not grouping */
3560  dNumGroups = 1;
3561  }
3562 
3563  return dNumGroups;
3564 }
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3398
Query * parse
Definition: relation.h:155
List * groupClause
Definition: relation.h:1581
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
bool hasAggs
Definition: parsenodes.h:123
List * hash_sets_idx
Definition: planner.c:103
List * groupingSets
Definition: parsenodes.h:148
double dNumHashGroups
Definition: planner.c:104
double numGroups
Definition: relation.h:1584
List * targetList
Definition: parsenodes.h:138
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
List * unsortable_sets
Definition: planner.c:108
List * groupClause
Definition: parsenodes.h:146
double numGroups
Definition: relation.h:1575
bool hasHavingQual
Definition: relation.h:305
Definition: pg_list.h:45
List * gsets_data
Definition: relation.h:1583
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1582

◆ get_partitioned_child_rels()

List* get_partitioned_child_rels ( PlannerInfo root,
Index  rti,
bool part_cols_updated 
)

Definition at line 5945 of file planner.c.

References PartitionedChildRelInfo::child_rels, lfirst_node, NIL, PartitionedChildRelInfo::parent_relid, PartitionedChildRelInfo::part_cols_updated, and PlannerInfo::pcinfo_list.

Referenced by add_paths_to_append_rel(), and inheritance_planner().

5947 {
5948  List *result = NIL;
5949  ListCell *l;
5950 
5951  if (part_cols_updated)
5952  *part_cols_updated = false;
5953 
5954  foreach(l, root->pcinfo_list)
5955  {
5957 
5958  if (pc->parent_relid == rti)
5959  {
5960  result = pc->child_rels;
5961  if (part_cols_updated)
5962  *part_cols_updated = pc->part_cols_updated;
5963  break;
5964  }
5965  }
5966 
5967  return result;
5968 }
#define NIL
Definition: pg_list.h:69
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * pcinfo_list
Definition: relation.h:254
Definition: pg_list.h:45

◆ get_partitioned_child_rels_for_join()

List* get_partitioned_child_rels_for_join ( PlannerInfo root,
Relids  join_relids 
)

Definition at line 5976 of file planner.c.

References bms_is_member(), PartitionedChildRelInfo::child_rels, lfirst, list_concat(), list_copy(), NIL, PartitionedChildRelInfo::parent_relid, and PlannerInfo::pcinfo_list.

Referenced by add_paths_to_append_rel().

5977 {
5978  List *result = NIL;
5979  ListCell *l;
5980 
5981  foreach(l, root->pcinfo_list)
5982  {
5984 
5985  if (bms_is_member(pc->parent_relid, join_relids))
5986  result = list_concat(result, list_copy(pc->child_rels));
5987  }
5988 
5989  return result;
5990 }
#define NIL
Definition: pg_list.h:69
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:254
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464

◆ grouping_planner()

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

Definition at line 1577 of file planner.c.

References standard_qp_extra::activeWindows, add_path(), adjust_paths_for_srfs(), AGGSPLIT_SIMPLE, apply_projection_to_path(), Assert, Query::canSetTag, RelOptInfo::cheapest_startup_path, RelOptInfo::cheapest_total_path, CMD_SELECT, Query::commandType, RelOptInfo::consider_parallel, copyObject, create_distinct_paths(), create_grouping_paths(), create_limit_path(), create_lockrows_path(), create_modifytable_path(), create_ordered_paths(), create_pathtarget, create_projection_path(), create_upper_paths_hook, create_window_paths(), Query::distinctClause, 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, limit_needed(), PlannerInfo::limit_tuples, Query::limitCount, Query::limitOffset, linitial_int, linitial_node, list_length(), list_make1, list_make1_int, make_group_input_target(), make_pathkeys_for_sortclauses(), make_sort_input_target(), make_window_input_target(), MemSet, NIL, WindowFuncLists::numWindowFuncs, Query::onConflict, Path::param_info, 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, query_planner(), Query::resultRelation, Query::returningList, grouping_sets_data::rollups, Query::rowMarks, PlannerInfo::rowMarks, select_active_windows(), RelOptInfo::serverid, Query::setOperations, PlannerInfo::sort_pathkeys, Query::sortClause, split_pathtarget_at_srfs(), SS_assign_special_param(), standard_qp_callback(), subpath(), Query::targetList, standard_qp_extra::tlist, PlannerInfo::tuple_fraction, PlannerInfo::upper_targets, UPPERREL_FINAL, UPPERREL_GROUP_AGG, UPPERREL_WINDOW, RelOptInfo::userid, RelOptInfo::useridiscurrent, Query::windowClause, and Query::withCheckOptions.

Referenced by inheritance_planner(), and subquery_planner().

1579 {
1580  Query *parse = root->parse;
1581  List *tlist;
1582  int64 offset_est = 0;
1583  int64 count_est = 0;
1584  double limit_tuples = -1.0;
1585  bool have_postponed_srfs = false;
1586  PathTarget *final_target;
1587  List *final_targets;
1588  List *final_targets_contain_srfs;
1589  RelOptInfo *current_rel;
1590  RelOptInfo *final_rel;
1591  ListCell *lc;
1592 
1593  /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1594  if (parse->limitCount || parse->limitOffset)
1595  {
1596  tuple_fraction = preprocess_limit(root, tuple_fraction,
1597  &offset_est, &count_est);
1598 
1599  /*
1600  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1601  * estimate the effects of using a bounded sort.
1602  */
1603  if (count_est > 0 && offset_est >= 0)
1604  limit_tuples = (double) count_est + (double) offset_est;
1605  }
1606 
1607  /* Make tuple_fraction accessible to lower-level routines */
1608  root->tuple_fraction = tuple_fraction;
1609 
1610  if (parse->setOperations)
1611  {
1612  /*
1613  * If there's a top-level ORDER BY, assume we have to fetch all the
1614  * tuples. This might be too simplistic given all the hackery below
1615  * to possibly avoid the sort; but the odds of accurate estimates here
1616  * are pretty low anyway. XXX try to get rid of this in favor of
1617  * letting plan_set_operations generate both fast-start and
1618  * cheapest-total paths.
1619  */
1620  if (parse->sortClause)
1621  root->tuple_fraction = 0.0;
1622 
1623  /*
1624  * Construct Paths for set operations. The results will not need any
1625  * work except perhaps a top-level sort and/or LIMIT. Note that any
1626  * special work for recursive unions is the responsibility of
1627  * plan_set_operations.
1628  */
1629  current_rel = plan_set_operations(root);
1630 
1631  /*
1632  * We should not need to call preprocess_targetlist, since we must be
1633  * in a SELECT query node. Instead, use the targetlist returned by
1634  * plan_set_operations (since this tells whether it returned any
1635  * resjunk columns!), and transfer any sort key information from the
1636  * original tlist.
1637  */
1638  Assert(parse->commandType == CMD_SELECT);
1639 
1640  tlist = root->processed_tlist; /* from plan_set_operations */
1641 
1642  /* for safety, copy processed_tlist instead of modifying in-place */
1643  tlist = postprocess_setop_tlist(copyObject(tlist), parse->targetList);
1644 
1645  /* Save aside the final decorated tlist */
1646  root->processed_tlist = tlist;
1647 
1648  /* Also extract the PathTarget form of the setop result tlist */
1649  final_target = current_rel->cheapest_total_path->pathtarget;
1650 
1651  /* The setop result tlist couldn't contain any SRFs */
1652  Assert(!parse->hasTargetSRFs);
1653  final_targets = final_targets_contain_srfs = NIL;
1654 
1655  /*
1656  * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1657  * checked already, but let's make sure).
1658  */
1659  if (parse->rowMarks)
1660  ereport(ERROR,
1661  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1662  /*------
1663  translator: %s is a SQL row locking clause such as FOR UPDATE */
1664  errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1666  parse->rowMarks)->strength))));
1667 
1668  /*
1669  * Calculate pathkeys that represent result ordering requirements
1670  */
1671  Assert(parse->distinctClause == NIL);
1673  parse->sortClause,
1674  tlist);
1675  }
1676  else
1677  {
1678  /* No set operations, do regular planning */
1679  PathTarget *sort_input_target;
1680  List *sort_input_targets;
1681  List *sort_input_targets_contain_srfs;
1682  PathTarget *grouping_target;
1683  List *grouping_targets;
1684  List *grouping_targets_contain_srfs;
1685  PathTarget *scanjoin_target;
1686  List *scanjoin_targets;
1687  List *scanjoin_targets_contain_srfs;
1688  bool have_grouping;
1689  AggClauseCosts agg_costs;
1690  WindowFuncLists *wflists = NULL;
1691  List *activeWindows = NIL;
1692  grouping_sets_data *gset_data = NULL;
1693  standard_qp_extra qp_extra;
1694 
1695  /* A recursive query should always have setOperations */
1696  Assert(!root->hasRecursion);
1697 
1698  /* Preprocess grouping sets and GROUP BY clause, if any */
1699  if (parse->groupingSets)
1700  {
1701  gset_data = preprocess_grouping_sets(root);
1702  }
1703  else
1704  {
1705  /* Preprocess regular GROUP BY clause, if any */
1706  if (parse->groupClause)
1707  parse->groupClause = preprocess_groupclause(root, NIL);
1708  }
1709 
1710  /* Preprocess targetlist */
1711  tlist = preprocess_targetlist(root);
1712 
1713  /*
1714  * We are now done hacking up the query's targetlist. Most of the
1715  * remaining planning work will be done with the PathTarget
1716  * representation of tlists, but save aside the full representation so
1717  * that we can transfer its decoration (resnames etc) to the topmost
1718  * tlist of the finished Plan.
1719  */
1720  root->processed_tlist = tlist;
1721 
1722  /*
1723  * Collect statistics about aggregates for estimating costs, and mark
1724  * all the aggregates with resolved aggtranstypes. We must do this
1725  * before slicing and dicing the tlist into various pathtargets, else
1726  * some copies of the Aggref nodes might escape being marked with the
1727  * correct transtypes.
1728  *
1729  * Note: currently, we do not detect duplicate aggregates here. This
1730  * may result in somewhat-overestimated cost, which is fine for our
1731  * purposes since all Paths will get charged the same. But at some
1732  * point we might wish to do that detection in the planner, rather
1733  * than during executor startup.
1734  */
1735  MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
1736  if (parse->hasAggs)
1737  {
1738  get_agg_clause_costs(root, (Node *) tlist, AGGSPLIT_SIMPLE,
1739  &agg_costs);
1741  &agg_costs);
1742  }
1743 
1744  /*
1745  * Locate any window functions in the tlist. (We don't need to look
1746  * anywhere else, since expressions used in ORDER BY will be in there
1747  * too.) Note that they could all have been eliminated by constant
1748  * folding, in which case we don't need to do any more work.
1749  */
1750  if (parse->hasWindowFuncs)
1751  {
1752  wflists = find_window_functions((Node *) tlist,
1753  list_length(parse->windowClause));
1754  if (wflists->numWindowFuncs > 0)
1755  activeWindows = select_active_windows(root, wflists);
1756  else
1757  parse->hasWindowFuncs = false;
1758  }
1759 
1760  /*
1761  * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1762  * adding logic between here and the query_planner() call. Anything
1763  * that is needed in MIN/MAX-optimizable cases will have to be
1764  * duplicated in planagg.c.
1765  */
1766  if (parse->hasAggs)
1767  preprocess_minmax_aggregates(root, tlist);
1768 
1769  /*
1770  * Figure out whether there's a hard limit on the number of rows that
1771  * query_planner's result subplan needs to return. Even if we know a
1772  * hard limit overall, it doesn't apply if the query has any
1773  * grouping/aggregation operations, or SRFs in the tlist.
1774  */
1775  if (parse->groupClause ||
1776  parse->groupingSets ||
1777  parse->distinctClause ||
1778  parse->hasAggs ||
1779  parse->hasWindowFuncs ||
1780  parse->hasTargetSRFs ||
1781  root->hasHavingQual)
1782  root->limit_tuples = -1.0;
1783  else
1784  root->limit_tuples = limit_tuples;
1785 
1786  /* Set up data needed by standard_qp_callback */
1787  qp_extra.tlist = tlist;
1788  qp_extra.activeWindows = activeWindows;
1789  qp_extra.groupClause = (gset_data
1790  ? (gset_data->rollups ? linitial_node(RollupData, gset_data->rollups)->groupClause : NIL)
1791  : parse->groupClause);
1792 
1793  /*
1794  * Generate the best unsorted and presorted paths for the scan/join
1795  * portion of this Query, ie the processing represented by the
1796  * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1797  * We also generate (in standard_qp_callback) pathkey representations
1798  * of the query's sort clause, distinct clause, etc.
1799  */
1800  current_rel = query_planner(root, tlist,
1801  standard_qp_callback, &qp_extra);
1802 
1803  /*
1804  * Convert the query's result tlist into PathTarget format.
1805  *
1806  * Note: it's desirable to not do this till after query_planner(),
1807  * because the target width estimates can use per-Var width numbers
1808  * that were obtained within query_planner().
1809  */
1810  final_target = create_pathtarget(root, tlist);
1811 
1812  /*
1813  * If ORDER BY was given, consider whether we should use a post-sort
1814  * projection, and compute the adjusted target for preceding steps if
1815  * so.
1816  */
1817  if (parse->sortClause)
1818  sort_input_target = make_sort_input_target(root,
1819  final_target,
1820  &have_postponed_srfs);
1821  else
1822  sort_input_target = final_target;
1823 
1824  /*
1825  * If we have window functions to deal with, the output from any
1826  * grouping step needs to be what the window functions want;
1827  * otherwise, it should be sort_input_target.
1828  */
1829  if (activeWindows)
1830  grouping_target = make_window_input_target(root,
1831  final_target,
1832  activeWindows);
1833  else
1834  grouping_target = sort_input_target;
1835 
1836  /*
1837  * If we have grouping or aggregation to do, the topmost scan/join
1838  * plan node must emit what the grouping step wants; otherwise, it
1839  * should emit grouping_target.
1840  */
1841  have_grouping = (parse->groupClause || parse->groupingSets ||
1842  parse->hasAggs || root->hasHavingQual);
1843  if (have_grouping)
1844  scanjoin_target = make_group_input_target(root, final_target);
1845  else
1846  scanjoin_target = grouping_target;
1847 
1848  /*
1849  * If there are any SRFs in the targetlist, we must separate each of
1850  * these PathTargets into SRF-computing and SRF-free targets. Replace
1851  * each of the named targets with a SRF-free version, and remember the
1852  * list of additional projection steps we need to add afterwards.
1853  */
1854  if (parse->hasTargetSRFs)
1855  {
1856  /* final_target doesn't recompute any SRFs in sort_input_target */
1857  split_pathtarget_at_srfs(root, final_target, sort_input_target,
1858  &final_targets,
1859  &final_targets_contain_srfs);
1860  final_target = linitial_node(PathTarget, final_targets);
1861  Assert(!linitial_int(final_targets_contain_srfs));
1862  /* likewise for sort_input_target vs. grouping_target */
1863  split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
1864  &sort_input_targets,
1865  &sort_input_targets_contain_srfs);
1866  sort_input_target = linitial_node(PathTarget, sort_input_targets);
1867  Assert(!linitial_int(sort_input_targets_contain_srfs));
1868  /* likewise for grouping_target vs. scanjoin_target */
1869  split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
1870  &grouping_targets,
1871  &grouping_targets_contain_srfs);
1872  grouping_target = linitial_node(PathTarget, grouping_targets);
1873  Assert(!linitial_int(grouping_targets_contain_srfs));
1874  /* scanjoin_target will not have any SRFs precomputed for it */
1875  split_pathtarget_at_srfs(root, scanjoin_target, NULL,
1876  &scanjoin_targets,
1877  &scanjoin_targets_contain_srfs);
1878  scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
1879  Assert(!linitial_int(scanjoin_targets_contain_srfs));
1880  }
1881  else
1882  {
1883  /* initialize lists, just to keep compiler quiet */
1884  final_targets = final_targets_contain_srfs = NIL;
1885  sort_input_targets = sort_input_targets_contain_srfs = NIL;
1886  grouping_targets = grouping_targets_contain_srfs = NIL;
1887  scanjoin_targets = scanjoin_targets_contain_srfs = NIL;
1888  }
1889 
1890  /*
1891  * Forcibly apply SRF-free scan/join target to all the Paths for the
1892  * scan/join rel.
1893  *
1894  * In principle we should re-run set_cheapest() here to identify the
1895  * cheapest path, but it seems unlikely that adding the same tlist
1896  * eval costs to all the paths would change that, so we don't bother.
1897  * Instead, just assume that the cheapest-startup and cheapest-total
1898  * paths remain so. (There should be no parameterized paths anymore,
1899  * so we needn't worry about updating cheapest_parameterized_paths.)
1900  */
1901  foreach(lc, current_rel->pathlist)
1902  {
1903  Path *subpath = (Path *) lfirst(lc);
1904  Path *path;
1905 
1906  Assert(subpath->param_info == NULL);
1907  path = apply_projection_to_path(root, current_rel,
1908  subpath, scanjoin_target);
1909  /* If we had to add a Result, path is different from subpath */
1910  if (path != subpath)
1911  {
1912  lfirst(lc) = path;
1913  if (subpath == current_rel->cheapest_startup_path)
1914  current_rel->cheapest_startup_path = path;
1915  if (subpath == current_rel->cheapest_total_path)
1916  current_rel->cheapest_total_path = path;
1917  }
1918  }
1919 
1920  /*
1921  * Upper planning steps which make use of the top scan/join rel's
1922  * partial pathlist will expect partial paths for that rel to produce
1923  * the same output as complete paths ... and we just changed the
1924  * output for the complete paths, so we'll need to do the same thing
1925  * for partial paths. But only parallel-safe expressions can be
1926  * computed by partial paths.
1927  */
1928  if (current_rel->partial_pathlist &&
1929  is_parallel_safe(root, (Node *) scanjoin_target->exprs))
1930  {
1931  /* Apply the scan/join target to each partial path */
1932  foreach(lc, current_rel->partial_pathlist)
1933  {
1934  Path *subpath = (Path *) lfirst(lc);
1935  Path *newpath;
1936 
1937  /* Shouldn't have any parameterized paths anymore */
1938  Assert(subpath->param_info == NULL);
1939 
1940  /*
1941  * Don't use apply_projection_to_path() here, because there
1942  * could be other pointers to these paths, and therefore we
1943  * mustn't modify them in place.
1944  */
1945  newpath = (Path *) create_projection_path(root,
1946  current_rel,
1947  subpath,
1948  scanjoin_target);
1949  lfirst(lc) = newpath;
1950  }
1951  }
1952  else
1953  {
1954  /*
1955  * In the unfortunate event that scanjoin_target is not
1956  * parallel-safe, we can't apply it to the partial paths; in that
1957  * case, we'll need to forget about the partial paths, which
1958  * aren't valid input for upper planning steps.
1959  */
1960  current_rel->partial_pathlist = NIL;
1961  }
1962 
1963  /* Now fix things up if scan/join target contains SRFs */
1964  if (parse->hasTargetSRFs)
1965  adjust_paths_for_srfs(root, current_rel,
1966  scanjoin_targets,
1967  scanjoin_targets_contain_srfs);
1968 
1969  /*
1970  * Save the various upper-rel PathTargets we just computed into
1971  * root->upper_targets[]. The core code doesn't use this, but it
1972  * provides a convenient place for extensions to get at the info. For
1973  * consistency, we save all the intermediate targets, even though some
1974  * of the corresponding upperrels might not be needed for this query.
1975  */
1976  root->upper_targets[UPPERREL_FINAL] = final_target;
1977  root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
1978  root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
1979 
1980  /*
1981  * If we have grouping and/or aggregation, consider ways to implement
1982  * that. We build a new upperrel representing the output of this
1983  * phase.
1984  */
1985  if (have_grouping)
1986  {
1987  current_rel = create_grouping_paths(root,
1988  current_rel,
1989  grouping_target,
1990  &agg_costs,
1991  gset_data);
1992  /* Fix things up if grouping_target contains SRFs */
1993  if (parse->hasTargetSRFs)
1994  adjust_paths_for_srfs(root, current_rel,
1995  grouping_targets,
1996  grouping_targets_contain_srfs);
1997  }
1998 
1999  /*
2000  * If we have window functions, consider ways to implement those. We
2001  * build a new upperrel representing the output of this phase.
2002  */
2003  if (activeWindows)
2004  {
2005  current_rel = create_window_paths(root,
2006  current_rel,
2007  grouping_target,
2008  sort_input_target,
2009  tlist,
2010  wflists,
2011  activeWindows);
2012  /* Fix things up if sort_input_target contains SRFs */
2013  if (parse->hasTargetSRFs)
2014  adjust_paths_for_srfs(root, current_rel,
2015  sort_input_targets,
2016  sort_input_targets_contain_srfs);
2017  }
2018 
2019  /*
2020  * If there is a DISTINCT clause, consider ways to implement that. We
2021  * build a new upperrel representing the output of this phase.
2022  */
2023  if (parse->distinctClause)
2024  {
2025  current_rel = create_distinct_paths(root,
2026  current_rel);
2027  }
2028  } /* end of if (setOperations) */
2029 
2030  /*
2031  * If ORDER BY was given, consider ways to implement that, and generate a
2032  * new upperrel containing only paths that emit the correct ordering and
2033  * project the correct final_target. We can apply the original
2034  * limit_tuples limit in sort costing here, but only if there are no
2035  * postponed SRFs.
2036  */
2037  if (parse->sortClause)
2038  {
2039  current_rel = create_ordered_paths(root,
2040  current_rel,
2041  final_target,
2042  have_postponed_srfs ? -1.0 :
2043  limit_tuples);
2044  /* Fix things up if final_target contains SRFs */
2045  if (parse->hasTargetSRFs)
2046  adjust_paths_for_srfs(root, current_rel,
2047  final_targets,
2048  final_targets_contain_srfs);
2049  }
2050 
2051  /*
2052  * Now we are prepared to build the final-output upperrel.
2053  */
2054  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
2055 
2056  /*
2057  * If the input rel is marked consider_parallel and there's nothing that's
2058  * not parallel-safe in the LIMIT clause, then the final_rel can be marked
2059  * consider_parallel as well. Note that if the query has rowMarks or is
2060  * not a SELECT, consider_parallel will be false for every relation in the
2061  * query.
2062  */
2063  if (current_rel->consider_parallel &&
2064  is_parallel_safe(root, parse->limitOffset) &&
2065  is_parallel_safe(root, parse->limitCount))
2066  final_rel->consider_parallel = true;
2067 
2068  /*
2069  * If the current_rel belongs to a single FDW, so does the final_rel.
2070  */
2071  final_rel->serverid = current_rel->serverid;
2072  final_rel->userid = current_rel->userid;
2073  final_rel->useridiscurrent = current_rel->useridiscurrent;
2074  final_rel->fdwroutine = current_rel->fdwroutine;
2075 
2076  /*
2077  * Generate paths for the final_rel. Insert all surviving paths, with
2078  * LockRows, Limit, and/or ModifyTable steps added if needed.
2079  */
2080  foreach(lc, current_rel->pathlist)
2081  {
2082  Path *path = (Path *) lfirst(lc);
2083 
2084  /*
2085  * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
2086  * (Note: we intentionally test parse->rowMarks not root->rowMarks
2087  * here. If there are only non-locking rowmarks, they should be
2088  * handled by the ModifyTable node instead. However, root->rowMarks
2089  * is what goes into the LockRows node.)
2090  */
2091  if (parse->rowMarks)
2092  {
2093  path = (Path *) create_lockrows_path(root, final_rel, path,
2094  root->rowMarks,
2095  SS_assign_special_param(root));
2096  }
2097 
2098  /*
2099  * If there is a LIMIT/OFFSET clause, add the LIMIT node.
2100  */
2101  if (limit_needed(parse))
2102  {
2103  path = (Path *) create_limit_path(root, final_rel, path,
2104  parse->limitOffset,
2105  parse->limitCount,
2106  offset_est, count_est);
2107  }
2108 
2109  /*
2110  * If this is an INSERT/UPDATE/DELETE, and we're not being called from
2111  * inheritance_planner, add the ModifyTable node.
2112  */
2113  if (parse->commandType != CMD_SELECT && !inheritance_update)
2114  {
2115  List *withCheckOptionLists;
2116  List *returningLists;
2117  List *rowMarks;
2118 
2119  /*
2120  * Set up the WITH CHECK OPTION and RETURNING lists-of-lists, if
2121  * needed.
2122  */
2123  if (parse->withCheckOptions)
2124  withCheckOptionLists = list_make1(parse->withCheckOptions);
2125  else
2126  withCheckOptionLists = NIL;
2127 
2128  if (parse->returningList)
2129  returningLists = list_make1(parse->returningList);
2130  else
2131  returningLists = NIL;
2132 
2133  /*
2134  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
2135  * will have dealt with fetching non-locked marked rows, else we
2136  * need to have ModifyTable do that.
2137  */
2138  if (parse->rowMarks)
2139  rowMarks = NIL;
2140  else
2141  rowMarks = root->rowMarks;
2142 
2143  path = (Path *)
2144  create_modifytable_path(root, final_rel,
2145  parse->commandType,
2146  parse->canSetTag,
2147  parse->resultRelation,
2148  NIL,
2149  false,
2151  list_make1(path),
2152  list_make1(root),
2153  withCheckOptionLists,
2154  returningLists,
2155  rowMarks,
2156  parse->onConflict,
2157  SS_assign_special_param(root));
2158  }
2159 
2160  /* And shove it into final_rel */
2161  add_path(final_rel, path);
2162  }
2163 
2164  /*
2165  * If there is an FDW that's responsible for all baserels of the query,
2166  * let it consider adding ForeignPaths.
2167  */
2168  if (final_rel->fdwroutine &&
2169  final_rel->fdwroutine->GetForeignUpperPaths)
2171  current_rel, final_rel);
2172 
2173  /* Let extensions possibly add some more paths */
2175  (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2176  current_rel, final_rel);
2177 
2178  /* Note: currently, we leave it to callers to do set_cheapest() */
2179 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2451
RelOptInfo * plan_set_operations(PlannerInfo *root)
Definition: prepunion.c:144
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:197
Node * limitOffset
Definition: parsenodes.h:158
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:256
static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
Definition: planner.c:2609
PathTarget * pathtarget
Definition: relation.h:1047
Query * parse
Definition: relation.h:155
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:2580
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * sortClause
Definition: parsenodes.h:156
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition: pathnode.c:3228
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
OnConflictExpr * onConflict
Definition: parsenodes.h:142
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:865
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:3008
RelOptInfo * query_planner(PlannerInfo *root, List *tlist, query_pathkeys_callback qp_callback, void *qp_extra)
Definition: planmain.c:54
struct Path * cheapest_startup_path
Definition: relation.h:602
Oid userid
Definition: relation.h:633
List * withCheckOptions
Definition: parsenodes.h:169
void split_pathtarget_at_srfs(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition: tlist.c:840
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:470
bool hasAggs
Definition: parsenodes.h:123
int resultRelation
Definition: parsenodes.h:120
int numWindowFuncs
Definition: clauses.h:25
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition: clauses.c:743
ParamPathInfo * param_info
Definition: relation.h:1049
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:513
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2360
int errcode(int sqlerrcode)
Definition: elog.c:575
List * partial_pathlist
Definition: relation.h:601
static RelOptInfo * create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel)
Definition: planner.c:4404
#define MemSet(start, val, len)
Definition: c.h:897
List * tlist
Definition: planner.c:91
static PathTarget * make_group_input_target(PlannerInfo *root, PathTarget *final_target)
Definition: planner.c:4775
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:70
bool useridiscurrent
Definition: relation.h:634
void preprocess_minmax_aggregates(PlannerInfo *root, List *tlist)
Definition: planagg.c:75
List * rowMarks
Definition: parsenodes.h:161
#define linitial_node(type, l)
Definition: pg_list.h:114
LimitPath * create_limit_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, Node *limitOffset, Node *limitCount, int64 offset_est, int64 count_est)
Definition: pathnode.c:3391
bool hasRecursion
Definition: relation.h:308
List * windowClause
Definition: parsenodes.h:152
List * targetList
Definition: parsenodes.h:138
static List * postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
Definition: planner.c:4998
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition: planner.c:5557
#define list_make1(x1)
Definition: pg_list.h:139
#define linitial_int(l)
Definition: pg_list.h:112
static RelOptInfo * create_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, const AggClauseCosts *agg_costs, grouping_sets_data *gd)
Definition: planner.c:3621
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, bool partColsUpdated, List *resultRelations, List *subpaths, List *subroots, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: pathnode.c:3289
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1090
double tuple_fraction
Definition: relation.h:294
List * distinctClause
Definition: parsenodes.h:154
#define ERROR
Definition: elog.h:43
static bool limit_needed(Query *parse)
Definition: planner.c:2794
List * preprocess_targetlist(PlannerInfo *root)
Definition: preptlist.c:70
double limit_tuples
Definition: relation.h:295
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
struct Path * cheapest_total_path
Definition: relation.h:603
Node * limitCount
Definition: parsenodes.h:159
static PathTarget * make_window_input_target(PlannerInfo *root, PathTarget *final_target, List *activeWindows)
Definition: planner.c:5128
struct FdwRoutine * fdwroutine
Definition: relation.h:636
static void standard_qp_callback(PlannerInfo *root, void *extra)
Definition: planner.c:3376
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
static grouping_sets_data * preprocess_grouping_sets(PlannerInfo *root)
Definition: planner.c:2188
List * returningList
Definition: parsenodes.h:144
#define list_make1_int(x1)
Definition: pg_list.h:145
#define ereport(elevel, rest)
Definition: elog.h:122
List * sort_pathkeys
Definition: relation.h:267
static RelOptInfo * create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, double limit_tuples)
Definition: planner.c:4615
Oid serverid
Definition: relation.h:632
List * exprs
Definition: relation.h:976
CmdType commandType
Definition: parsenodes.h:110
bool hasTargetSRFs
Definition: parsenodes.h:125
List * groupClause
Definition: planner.c:93
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:124
bool canSetTag
Definition: parsenodes.h:116
static int list_length(const List *l)
Definition: pg_list.h:89
static RelOptInfo * create_window_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, List *tlist, WindowFuncLists *wflists, List *activeWindows)
Definition: planner.c:4223
bool consider_parallel
Definition: relation.h:593
List * activeWindows
Definition: planner.c:92
Node * setOperations
Definition: parsenodes.h:163
List * groupClause
Definition: parsenodes.h:146
int errmsg(const char *fmt,...)
Definition: elog.c:797
static List * select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
Definition: planner.c:5031
bool hasHavingQual
Definition: relation.h:305
List * pathlist
Definition: relation.h:599
#define copyObject(obj)
Definition: nodes.h:626
Node * havingQual
Definition: parsenodes.h:150
List * processed_tlist
Definition: relation.h:284
Definition: pg_list.h:45
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
static PathTarget * make_sort_input_target(PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
Definition: planner.c:5343
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: relation.h:278

◆ inheritance_planner()

static void inheritance_planner ( PlannerInfo root)
static

Definition at line 1099 of file planner.c.

References add_path(), adjust_appendrel_attrs(), PlannerInfo::append_rel_list, Assert, bms_add_member(), bms_is_member(), bms_make_singleton(), bms_overlap(), Query::canSetTag, ChangeVarNodes(), RelOptInfo::cheapest_total_path, AppendRelInfo::child_relid, CMD_INSERT, Query::commandType, copyObject, create_modifytable_path(), fetch_upper_rel(), get_partitioned_child_rels(), grouping_planner(), PlannerInfo::hasInheritedTarget, RangeTblEntry::inh, PlannerInfo::init_plans, IS_DUMMY_PATH, PlannerInfo::join_info_list, lappend(), lappend_int(), lfirst_node, list_concat(), list_copy_tail(), list_length(), makeNode, NIL, Query::onConflict, palloc0(), AppendRelInfo::parent_relid, parse(), PlannerInfo::parse, PlannerInfo::placeholder_list, pull_varnos(), RangeTblEntry::relkind, RELKIND_PARTITIONED_TABLE, Query::resultRelation, Query::returningList, Query::rowMarks, PlannerInfo::rowMarks, rt_fetch, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblEntry::securityQuals, set_cheapest(), set_dummy_rel_pathlist(), PlannerInfo::simple_rel_array, PlannerInfo::simple_rel_array_size, PlannerInfo::simple_rte_array, SS_assign_special_param(), subpath(), AppendRelInfo::translated_vars, UPPERREL_FINAL, and Query::withCheckOptions.

Referenced by subquery_planner().

1100 {
1101  Query *parse = root->parse;
1102  int top_parentRTindex = parse->resultRelation;
1103  Bitmapset *subqueryRTindexes;
1104  Bitmapset *modifiableARIindexes;
1105  int nominalRelation = -1;
1106  List *final_rtable = NIL;
1107  int save_rel_array_size = 0;
1108  RelOptInfo **save_rel_array = NULL;
1109  List *subpaths = NIL;
1110  List *subroots = NIL;
1111  List *resultRelations = NIL;
1112  List *withCheckOptionLists = NIL;
1113  List *returningLists = NIL;
1114  List *rowMarks;
1115  RelOptInfo *final_rel;
1116  ListCell *lc;
1117  Index rti;
1118  RangeTblEntry *parent_rte;
1119  List *partitioned_rels = NIL;
1120  PlannerInfo *parent_root;
1121  Query *parent_parse;
1122  Bitmapset *parent_relids = bms_make_singleton(top_parentRTindex);
1123  PlannerInfo **parent_roots = NULL;
1124  bool partColsUpdated = false;
1125 
1126  Assert(parse->commandType != CMD_INSERT);
1127 
1128  /*
1129  * We generate a modified instance of the original Query for each target
1130  * relation, plan that, and put all the plans into a list that will be
1131  * controlled by a single ModifyTable node. All the instances share the
1132  * same rangetable, but each instance must have its own set of subquery
1133  * RTEs within the finished rangetable because (1) they are likely to get
1134  * scribbled on during planning, and (2) it's not inconceivable that
1135  * subqueries could get planned differently in different cases. We need
1136  * not create duplicate copies of other RTE kinds, in particular not the
1137  * target relations, because they don't have either of those issues. Not
1138  * having to duplicate the target relations is important because doing so
1139  * (1) would result in a rangetable of length O(N^2) for N targets, with
1140  * at least O(N^3) work expended here; and (2) would greatly complicate
1141  * management of the rowMarks list.
1142  *
1143  * To begin with, generate a bitmapset of the relids of the subquery RTEs.
1144  */
1145  subqueryRTindexes = NULL;
1146  rti = 1;
1147  foreach(lc, parse->rtable)
1148  {
1150 
1151  if (rte->rtekind == RTE_SUBQUERY)
1152  subqueryRTindexes = bms_add_member(subqueryRTindexes, rti);
1153  rti++;
1154  }
1155 
1156  /*
1157  * Next, we want to identify which AppendRelInfo items contain references
1158  * to any of the aforesaid subquery RTEs. These items will need to be
1159  * copied and modified to adjust their subquery references; whereas the
1160  * other ones need not be touched. It's worth being tense over this
1161  * because we can usually avoid processing most of the AppendRelInfo
1162  * items, thereby saving O(N^2) space and time when the target is a large
1163  * inheritance tree. We can identify AppendRelInfo items by their
1164  * child_relid, since that should be unique within the list.
1165  */
1166  modifiableARIindexes = NULL;
1167  if (subqueryRTindexes != NULL)
1168  {
1169  foreach(lc, root->append_rel_list)
1170  {
1171  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
1172 
1173  if (bms_is_member(appinfo->parent_relid, subqueryRTindexes) ||
1174  bms_is_member(appinfo->child_relid, subqueryRTindexes) ||
1176  subqueryRTindexes))
1177  modifiableARIindexes = bms_add_member(modifiableARIindexes,
1178  appinfo->child_relid);
1179  }
1180  }
1181 
1182  /*
1183  * If the parent RTE is a partitioned table, we should use that as the
1184  * nominal relation, because the RTEs added for partitioned tables
1185  * (including the root parent) as child members of the inheritance set do
1186  * not appear anywhere else in the plan. The situation is exactly the
1187  * opposite in the case of non-partitioned inheritance parent as described
1188  * below. For the same reason, collect the list of descendant partitioned
1189  * tables to be saved in ModifyTable node, so that executor can lock those
1190  * as well.
1191  */
1192  parent_rte = rt_fetch(top_parentRTindex, root->parse->rtable);
1193  if (parent_rte->relkind == RELKIND_PARTITIONED_TABLE)
1194  {
1195  nominalRelation = top_parentRTindex;
1196  partitioned_rels = get_partitioned_child_rels(root, top_parentRTindex,
1197  &partColsUpdated);
1198  /* The root partitioned table is included as a child rel */
1199  Assert(list_length(partitioned_rels) >= 1);
1200  }
1201 
1202  /*
1203  * The PlannerInfo for each child is obtained by translating the relevant
1204  * members of the PlannerInfo for its immediate parent, which we find
1205  * using the parent_relid in its AppendRelInfo. We save the PlannerInfo
1206  * for each parent in an array indexed by relid for fast retrieval. Since
1207  * the maximum number of parents is limited by the number of RTEs in the
1208  * query, we use that number to allocate the array. An extra entry is
1209  * needed since relids start from 1.
1210  */
1211  parent_roots = (PlannerInfo **) palloc0((list_length(parse->rtable) + 1) *
1212  sizeof(PlannerInfo *));
1213  parent_roots[top_parentRTindex] = root;
1214 
1215  /*
1216  * And now we can get on with generating a plan for each child table.
1217  */
1218  foreach(lc, root->append_rel_list)
1219  {
1220  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
1221  PlannerInfo *subroot;
1222  RangeTblEntry *child_rte;
1223  RelOptInfo *sub_final_rel;
1224  Path *subpath;
1225 
1226  /* append_rel_list contains all append rels; ignore others */
1227  if (!bms_is_member(appinfo->parent_relid, parent_relids))
1228  continue;
1229 
1230  /*
1231  * expand_inherited_rtentry() always processes a parent before any of
1232  * that parent's children, so the parent_root for this relation should
1233  * already be available.
1234  */
1235  parent_root = parent_roots[appinfo->parent_relid];
1236  Assert(parent_root != NULL);
1237  parent_parse = parent_root->parse;
1238 
1239  /*
1240  * We need a working copy of the PlannerInfo so that we can control
1241  * propagation of information back to the main copy.
1242  */
1243  subroot = makeNode(PlannerInfo);
1244  memcpy(subroot, parent_root, sizeof(PlannerInfo));
1245 
1246  /*
1247  * Generate modified query with this rel as target. We first apply
1248  * adjust_appendrel_attrs, which copies the Query and changes
1249  * references to the parent RTE to refer to the current child RTE,
1250  * then fool around with subquery RTEs.
1251  */
1252  subroot->parse = (Query *)
1253  adjust_appendrel_attrs(parent_root,
1254  (Node *) parent_parse,
1255  1, &appinfo);
1256 
1257  /*
1258  * If there are securityQuals attached to the parent, move them to the
1259  * child rel (they've already been transformed properly for that).
1260  */
1261  parent_rte = rt_fetch(appinfo->parent_relid, subroot->parse->rtable);
1262  child_rte = rt_fetch(appinfo->child_relid, subroot->parse->rtable);
1263  child_rte->securityQuals = parent_rte->securityQuals;
1264  parent_rte->securityQuals = NIL;
1265 
1266  /*
1267  * The rowMarks list might contain references to subquery RTEs, so
1268  * make a copy that we can apply ChangeVarNodes to. (Fortunately, the
1269  * executor doesn't need to see the modified copies --- we can just
1270  * pass it the original rowMarks list.)
1271  */
1272  subroot->rowMarks = copyObject(parent_root->rowMarks);
1273 
1274  /*
1275  * The append_rel_list likewise might contain references to subquery
1276  * RTEs (if any subqueries were flattenable UNION ALLs). So prepare
1277  * to apply ChangeVarNodes to that, too. As explained above, we only
1278  * want to copy items that actually contain such references; the rest
1279  * can just get linked into the subroot's append_rel_list.
1280  *
1281  * If we know there are no such references, we can just use the outer
1282  * append_rel_list unmodified.
1283  */
1284  if (modifiableARIindexes != NULL)
1285  {
1286  ListCell *lc2;
1287 
1288  subroot->append_rel_list = NIL;
1289  foreach(lc2, parent_root->append_rel_list)
1290  {
1291  AppendRelInfo *appinfo2 = lfirst_node(AppendRelInfo, lc2);
1292 
1293  if (bms_is_member(appinfo2->child_relid, modifiableARIindexes))
1294  appinfo2 = copyObject(appinfo2);
1295 
1296  subroot->append_rel_list = lappend(subroot->append_rel_list,
1297  appinfo2);
1298  }
1299  }
1300 
1301  /*
1302  * Add placeholders to the child Query's rangetable list to fill the
1303  * RT indexes already reserved for subqueries in previous children.
1304  * These won't be referenced, so there's no need to make them very
1305  * valid-looking.
1306  */
1307  while (list_length(subroot->parse->rtable) < list_length(final_rtable))
1308  subroot->parse->rtable = lappend(subroot->parse->rtable,
1310 
1311  /*
1312  * If this isn't the first child Query, generate duplicates of all
1313  * subquery RTEs, and adjust Var numbering to reference the
1314  * duplicates. To simplify the loop logic, we scan the original rtable
1315  * not the copy just made by adjust_appendrel_attrs; that should be OK
1316  * since subquery RTEs couldn't contain any references to the target
1317  * rel.
1318  */
1319  if (final_rtable != NIL && subqueryRTindexes != NULL)
1320  {
1321  ListCell *lr;
1322 
1323  rti = 1;
1324  foreach(lr, parent_parse->rtable)
1325  {
1327 
1328  if (bms_is_member(rti, subqueryRTindexes))
1329  {
1330  Index newrti;
1331 
1332  /*
1333  * The RTE can't contain any references to its own RT
1334  * index, except in its securityQuals, so we can save a
1335  * few cycles by applying ChangeVarNodes to the rest of
1336  * the rangetable before we append the RTE to it.
1337  */
1338  newrti = list_length(subroot->parse->rtable) + 1;
1339  ChangeVarNodes((Node *) subroot->parse, rti, newrti, 0);
1340  ChangeVarNodes((Node *) subroot->rowMarks, rti, newrti, 0);
1341  /* Skip processing unchanging parts of append_rel_list */
1342  if (modifiableARIindexes != NULL)
1343  {
1344  ListCell *lc2;
1345 
1346  foreach(lc2, subroot->append_rel_list)
1347  {
1348  AppendRelInfo *appinfo2 = lfirst_node(AppendRelInfo, lc2);
1349 
1350  if (bms_is_member(appinfo2->child_relid,
1351  modifiableARIindexes))
1352  ChangeVarNodes((Node *) appinfo2, rti, newrti, 0);
1353  }
1354  }
1355  rte = copyObject(rte);
1356  ChangeVarNodes((Node *) rte->securityQuals, rti, newrti, 0);
1357  subroot->parse->rtable = lappend(subroot->parse->rtable,
1358  rte);
1359  }
1360  rti++;
1361  }
1362  }
1363 
1364  /* There shouldn't be any OJ info to translate, as yet */
1365  Assert(subroot->join_info_list == NIL);
1366  /* and we haven't created PlaceHolderInfos, either */
1367  Assert(subroot->placeholder_list == NIL);
1368  /* hack to mark target relation as an inheritance partition */
1369  subroot->hasInheritedTarget = true;
1370 
1371  /*
1372  * If the child is further partitioned, remember it as a parent. Since
1373  * a partitioned table does not have any data, we don't need to create
1374  * a plan for it. We do, however, need to remember the PlannerInfo for
1375  * use when processing its children.
1376  */
1377  if (child_rte->inh)
1378  {
1379  Assert(child_rte->relkind == RELKIND_PARTITIONED_TABLE);
1380  parent_relids =
1381  bms_add_member(parent_relids, appinfo->child_relid);
1382  parent_roots[appinfo->child_relid] = subroot;
1383 
1384  continue;
1385  }
1386 
1387  /* Generate Path(s) for accessing this result relation */
1388  grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
1389 
1390  /*
1391  * Set the nomimal target relation of the ModifyTable node if not
1392  * already done. We use the inheritance parent RTE as the nominal
1393  * target relation if it's a partitioned table (see just above this
1394  * loop). In the non-partitioned parent case, we'll use the first
1395  * child relation (even if it's excluded) as the nominal target
1396  * relation. Because of the way expand_inherited_rtentry works, the
1397  * latter should be the RTE representing the parent table in its role
1398  * as a simple member of the inheritance set.
1399  *
1400  * It would be logically cleaner to *always* use the inheritance
1401  * parent RTE as the nominal relation; but that RTE is not otherwise
1402  * referenced in the plan in the non-partitioned inheritance case.
1403  * Instead the duplicate child RTE created by expand_inherited_rtentry
1404  * is used elsewhere in the plan, so using the original parent RTE
1405  * would give rise to confusing use of multiple aliases in EXPLAIN
1406  * output for what the user will think is the "same" table. OTOH,
1407  * it's not a problem in the partitioned inheritance case, because the
1408  * duplicate child RTE added for the parent does not appear anywhere
1409  * else in the plan tree.
1410  */
1411  if (nominalRelation < 0)
1412  nominalRelation = appinfo->child_relid;
1413 
1414  /*
1415  * Select cheapest path in case there's more than one. We always run
1416  * modification queries to conclusion, so we care only for the
1417  * cheapest-total path.
1418  */
1419  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
1420  set_cheapest(sub_final_rel);
1421  subpath = sub_final_rel->cheapest_total_path;
1422 
1423  /*
1424  * If this child rel was excluded by constraint exclusion, exclude it
1425  * from the result plan.
1426  */
1427  if (IS_DUMMY_PATH(subpath))
1428  continue;
1429 
1430  /*
1431  * If this is the first non-excluded child, its post-planning rtable
1432  * becomes the initial contents of final_rtable; otherwise, append
1433  * just its modified subquery RTEs to final_rtable.
1434  */
1435  if (final_rtable == NIL)
1436  final_rtable = subroot->parse->rtable;
1437  else
1438  final_rtable = list_concat(final_rtable,
1439  list_copy_tail(subroot->parse->rtable,
1440  list_length(final_rtable)));
1441 
1442  /*
1443  * We need to collect all the RelOptInfos from all child plans into
1444  * the main PlannerInfo, since setrefs.c will need them. We use the
1445  * last child's simple_rel_array (previous ones are too short), so we
1446  * have to propagate forward the RelOptInfos that were already built
1447  * in previous children.
1448  */
1449  Assert(subroot->simple_rel_array_size >= save_rel_array_size);
1450  for (rti = 1; rti < save_rel_array_size; rti++)
1451  {
1452  RelOptInfo *brel = save_rel_array[rti];
1453 
1454  if (brel)
1455  subroot->simple_rel_array[rti] = brel;
1456  }
1457  save_rel_array_size = subroot->simple_rel_array_size;
1458  save_rel_array = subroot->simple_rel_array;
1459 
1460  /* Make sure any initplans from this rel get into the outer list */
1461  root->init_plans = subroot->init_plans;
1462 
1463  /* Build list of sub-paths */
1464  subpaths = lappend(subpaths, subpath);
1465 
1466  /* Build list of modified subroots, too */
1467  subroots = lappend(subroots, subroot);
1468 
1469  /* Build list of target-relation RT indexes */
1470  resultRelations = lappend_int(resultRelations, appinfo->child_relid);
1471 
1472  /* Build lists of per-relation WCO and RETURNING targetlists */
1473  if (parse->withCheckOptions)
1474  withCheckOptionLists = lappend(withCheckOptionLists,
1475  subroot->parse->withCheckOptions);
1476  if (parse->returningList)
1477  returningLists = lappend(returningLists,
1478  subroot->parse->returningList);
1479 
1480  Assert(!parse->onConflict);
1481  }
1482 
1483  /* Result path must go into outer query's FINAL upperrel */
1484  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1485 
1486  /*
1487  * We don't currently worry about setting final_rel's consider_parallel
1488  * flag in this case, nor about allowing FDWs or create_upper_paths_hook
1489  * to get control here.
1490  */
1491 
1492  /*
1493  * If we managed to exclude every child rel, return a dummy plan; it
1494  * doesn't even need a ModifyTable node.
1495  */
1496  if (subpaths == NIL)
1497  {
1498  set_dummy_rel_pathlist(final_rel);
1499  return;
1500  }
1501 
1502  /*
1503  * Put back the final adjusted rtable into the master copy of the Query.
1504  * (We mustn't do this if we found no non-excluded children.)
1505  */
1506  parse->rtable = final_rtable;
1507  root->simple_rel_array_size = save_rel_array_size;
1508  root->simple_rel_array = save_rel_array;
1509  /* Must reconstruct master's simple_rte_array, too */
1510  root->simple_rte_array = (RangeTblEntry **)
1511  palloc0((list_length(final_rtable) + 1) * sizeof(RangeTblEntry *));
1512  rti = 1;
1513  foreach(lc, final_rtable)
1514  {
1516 
1517  root->simple_rte_array[rti++] = rte;
1518  }
1519 
1520  /*
1521  * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node will
1522  * have dealt with fetching non-locked marked rows, else we need to have
1523  * ModifyTable do that.
1524  */
1525  if (parse->rowMarks)
1526  rowMarks = NIL;
1527  else
1528  rowMarks = root->rowMarks;
1529 
1530  /* Create Path representing a ModifyTable to do the UPDATE/DELETE work */
1531  add_path(final_rel, (Path *)
1532  create_modifytable_path(root, final_rel,
1533  parse->commandType,
1534  parse->canSetTag,
1535  nominalRelation,
1536  partitioned_rels,
1537  partColsUpdated,
1538  resultRelations,
1539  subpaths,
1540  subroots,
1541  withCheckOptionLists,
1542  returningLists,
1543  rowMarks,
1544  NULL,
1545  SS_assign_special_param(root)));
1546 }
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:256
Query * parse
Definition: relation.h:155
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * join_info_list
Definition: relation.h:250
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
OnConflictExpr * onConflict
Definition: parsenodes.h:142
List * withCheckOptions
Definition: parsenodes.h:169
List * securityQuals
Definition: parsenodes.h:1072
int resultRelation
Definition: parsenodes.h:120
List * get_partitioned_child_rels(PlannerInfo *root, Index rti, bool *part_cols_updated)
Definition: planner.c:5945
Definition: nodes.h:513
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
List * rowMarks
Definition: parsenodes.h:161
List * translated_vars
Definition: relation.h:2105
struct RelOptInfo ** simple_rel_array
Definition: relation.h:179
#define IS_DUMMY_PATH(p)
Definition: relation.h:1281
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, bool partColsUpdated, List *resultRelations, List *subpaths, List *subroots, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: pathnode.c:3289
void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:1955
List * rtable
Definition: parsenodes.h:135
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1137
#define lfirst_node(type, lc)
Definition: pg_list.h:109
struct Path * cheapest_total_path
Definition: relation.h:603
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:223
List * returningList
Definition: parsenodes.h:144
int simple_rel_array_size
Definition: relation.h:180
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Relids pull_varnos(Node *node)
Definition: var.c:95
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: prepunion.c:1958
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void * palloc0(Size size)
Definition: mcxt.c:864
List * append_rel_list
Definition: relation.h:252
unsigned int Index
Definition: c.h:431
List * init_plans
Definition: relation.h:228
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:561
#define Assert(condition)
Definition: c.h:688
bool hasInheritedTarget
Definition: relation.h:300
bool canSetTag
Definition: parsenodes.h:116
static int list_length(const List *l)
Definition: pg_list.h:89
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:742
RTEKind rtekind
Definition: parsenodes.h:959
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:487
static void grouping_planner(PlannerInfo *root, bool inheritance_update, double tuple_fraction)
Definition: planner.c:1577
List * placeholder_list
Definition: relation.h:258
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
Index child_relid
Definition: relation.h:2078
#define copyObject(obj)
Definition: nodes.h:626
Index parent_relid
Definition: relation.h:2077
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649

◆ is_dummy_plan()

bool is_dummy_plan ( Plan plan)

Definition at line 2407 of file planner.c.

References Const::constisnull, Const::constvalue, DatumGetBool, IsA, linitial, and list_length().

2408 {
2409  if (IsA(plan, Result))
2410  {
2411  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2412 
2413  if (list_length(rcqual) == 1)
2414  {
2415  Const *constqual = (Const *) linitial(rcqual);
2416 
2417  if (constqual && IsA(constqual, Const))
2418  {
2419  if (!constqual->constisnull &&
2420  !DatumGetBool(constqual->constvalue))
2421  return true;
2422  }
2423  }
2424  }
2425  return false;
2426 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
#define linitial(l)
Definition: pg_list.h:111
#define DatumGetBool(X)
Definition: postgres.h:376
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
bool constisnull
Definition: primnodes.h:197

◆ limit_needed()

static bool limit_needed ( Query parse)
static

Definition at line 2794 of file planner.c.

References DatumGetInt64, IsA, Query::limitCount, and Query::limitOffset.

Referenced by grouping_planner().

2795 {
2796  Node *node;
2797 
2798  node = parse->limitCount;
2799  if (node)
2800  {
2801  if (IsA(node, Const))
2802  {
2803  /* NULL indicates LIMIT ALL, ie, no limit */
2804  if (!((Const *) node)->constisnull)
2805  return true; /* LIMIT with a constant value */
2806  }
2807  else
2808  return true; /* non-constant LIMIT */
2809  }
2810 
2811  node = parse->limitOffset;
2812  if (node)
2813  {
2814  if (IsA(node, Const))
2815  {
2816  /* Treat NULL as no offset; the executor would too */
2817  if (!((Const *) node)->constisnull)
2818  {
2819  int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2820 
2821  if (offset != 0)
2822  return true; /* OFFSET with a nonzero value */
2823  }
2824  }
2825  else
2826  return true; /* non-constant OFFSET */
2827  }
2828 
2829  return false; /* don't need a Limit plan node */
2830 }
Node * limitOffset
Definition: parsenodes.h:158
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
Definition: nodes.h:513
#define DatumGetInt64(X)
Definition: postgres.h:590
Node * limitCount
Definition: parsenodes.h:159

◆ make_group_input_target()

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

Definition at line 4775 of file planner.c.

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

Referenced by grouping_planner().

4776 {
4777  Query *parse = root->parse;
4778  PathTarget *input_target;
4779  List *non_group_cols;
4780  List *non_group_vars;
4781  int i;
4782  ListCell *lc;
4783 
4784  /*
4785  * We must build a target containing all grouping columns, plus any other
4786  * Vars mentioned in the query's targetlist and HAVING qual.
4787  */
4788  input_target = create_empty_pathtarget();
4789  non_group_cols = NIL;
4790 
4791  i = 0;
4792  foreach(lc, final_target->exprs)
4793  {
4794  Expr *expr = (Expr *) lfirst(lc);
4795  Index sgref = get_pathtarget_sortgroupref(final_target, i);
4796 
4797  if (sgref && parse->groupClause &&
4798  get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
4799  {
4800  /*
4801  * It's a grouping column, so add it to the input target as-is.
4802  */
4803  add_column_to_pathtarget(input_target, expr, sgref);
4804  }
4805  else
4806  {
4807  /*
4808  * Non-grouping column, so just remember the expression for later
4809  * call to pull_var_clause.
4810  */
4811  non_group_cols = lappend(non_group_cols, expr);
4812  }
4813 
4814  i++;
4815  }
4816 
4817  /*
4818  * If there's a HAVING clause, we'll need the Vars it uses, too.
4819  */
4820  if (parse->havingQual)
4821  non_group_cols = lappend(non_group_cols, parse->havingQual);
4822 
4823  /*
4824  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
4825  * add them to the input target if not already present. (A Var used
4826  * directly as a GROUP BY item will be present already.) Note this
4827  * includes Vars used in resjunk items, so we are covering the needs of
4828  * ORDER BY and window specifications. Vars used within Aggrefs and
4829  * WindowFuncs will be pulled out here, too.
4830  */
4831  non_group_vars = pull_var_clause((Node *) non_group_cols,
4835  add_new_columns_to_pathtarget(input_target, non_group_vars);
4836 
4837  /* clean up cruft */
4838  list_free(non_group_vars);
4839  list_free(non_group_cols);
4840 
4841  /* XXX this causes some redundant cost calculation ... */
4842  return set_pathtarget_cost_width(root, input_target);
4843 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:5233
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Definition: nodes.h:513
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:983
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:976
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:446
unsigned int Index
Definition: c.h:431
#define lfirst(lc)
Definition: pg_list.h:106
List * groupClause
Definition: parsenodes.h:146
void list_free(List *list)
Definition: list.c:1133
int i
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:714

◆ make_partial_grouping_target()

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

Definition at line 4862 of file planner.c.

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

Referenced by create_grouping_paths().

4863 {
4864  Query *parse = root->parse;
4865  PathTarget *partial_target;
4866  List *non_group_cols;
4867  List *non_group_exprs;
4868  int i;
4869  ListCell *lc;
4870 
4871  partial_target = create_empty_pathtarget();
4872  non_group_cols = NIL;
4873 
4874  i = 0;
4875  foreach(lc, grouping_target->exprs)
4876  {
4877  Expr *expr = (Expr *) lfirst(lc);
4878  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
4879 
4880  if (sgref && parse->groupClause &&
4881  get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
4882  {
4883  /*
4884  * It's a grouping column, so add it to the partial_target as-is.
4885  * (This allows the upper agg step to repeat the grouping calcs.)
4886  */
4887  add_column_to_pathtarget(partial_target, expr, sgref);
4888  }
4889  else
4890  {
4891  /*
4892  * Non-grouping column, so just remember the expression for later
4893  * call to pull_var_clause.
4894  */
4895  non_group_cols = lappend(non_group_cols, expr);
4896  }
4897 
4898  i++;
4899  }
4900 
4901  /*
4902  * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
4903  */
4904  if (parse->havingQual)
4905  non_group_cols = lappend(non_group_cols, parse->havingQual);
4906 
4907  /*
4908  * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
4909  * non-group cols (plus HAVING), and add them to the partial_target if not
4910  * already present. (An expression used directly as a GROUP BY item will
4911  * be present already.) Note this includes Vars used in resjunk items, so
4912  * we are covering the needs of ORDER BY and window specifications.
4913  */
4914  non_group_exprs = pull_var_clause((Node *) non_group_cols,
4918 
4919  add_new_columns_to_pathtarget(partial_target, non_group_exprs);
4920 
4921  /*
4922  * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
4923  * are at the top level of the target list, so we can just scan the list
4924  * rather than recursing through the expression trees.
4925  */
4926  foreach(lc, partial_target->exprs)
4927  {
4928  Aggref *aggref = (Aggref *) lfirst(lc);
4929 
4930  if (IsA(aggref, Aggref))
4931  {
4932  Aggref *newaggref;
4933 
4934  /*
4935  * We shouldn't need to copy the substructure of the Aggref node,
4936  * but flat-copy the node itself to avoid damaging other trees.
4937  */
4938  newaggref = makeNode(Aggref);
4939  memcpy(newaggref, aggref, sizeof(Aggref));
4940 
4941  /* For now, assume serialization is required */
4943 
4944  lfirst(lc) = newaggref;
4945  }
4946  }
4947 
4948  /* clean up cruft */
4949  list_free(non_group_exprs);
4950  list_free(non_group_cols);
4951 
4952  /* XXX this causes some redundant cost calculation ... */
4953  return set_pathtarget_cost_width(root, partial_target);
4954 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
Query * parse
Definition: relation.h:155
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:5233
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition: planner.c:4963
Definition: nodes.h:513
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
#define PVC_INCLUDE_AGGREGATES
Definition: var.h:20
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:983
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:976
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:446
unsigned int Index
Definition: c.h:431
#define makeNode(_type_)
Definition: nodes.h:561
#define lfirst(lc)
Definition: pg_list.h:106
List * groupClause
Definition: parsenodes.h:146
void list_free(List *list)
Definition: list.c:1133
int i
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:714

◆ make_pathkeys_for_window()

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

Definition at line 5248 of file planner.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, grouping_is_sortable(), list_concat(), list_copy(), list_free(), make_pathkeys_for_sortclauses(), WindowClause::orderClause, and WindowClause::partitionClause.

Referenced by create_one_window_path(), and standard_qp_callback().

5250 {
5251  List *window_pathkeys;
5252  List *window_sortclauses;
5253 
5254  /* Throw error if can't sort */
5256  ereport(ERROR,
5257  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5258  errmsg("could not implement window PARTITION BY"),
5259  errdetail("Window partitioning columns must be of sortable datatypes.")));
5261  ereport(ERROR,
5262  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5263  errmsg("could not implement window ORDER BY"),
5264  errdetail("Window ordering columns must be of sortable datatypes.")));
5265 
5266  /* Okay, make the combined pathkeys */
5267  window_sortclauses = list_concat(list_copy(wc->partitionClause),
5268  list_copy(wc->orderClause));
5269  window_pathkeys = make_pathkeys_for_sortclauses(root,
5270  window_sortclauses,
5271  tlist);
5272  list_free(window_sortclauses);
5273  return window_pathkeys;
5274 }
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:865
List * list_copy(const List *oldlist)
Definition: list.c:1160
int errcode(int sqlerrcode)
Definition: elog.c:575
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define ERROR
Definition: elog.h:43
List * partitionClause
Definition: parsenodes.h:1300
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * orderClause
Definition: parsenodes.h:1301
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
Definition: pg_list.h:45

◆ make_sort_input_target()

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

Definition at line 5343 of file planner.c.

References add_column_to_pathtarget(), add_new_columns_to_pathtarget(), Assert, contain_volatile_functions(), cost_qual_eval_node(), cpu_operator_cost, create_empty_pathtarget(), expression_returns_set(), PathTarget::exprs, get_pathtarget_sortgroupref, Query::hasTargetSRFs, i, lappend(), lfirst, Query::limitCount, list_free(), list_length(), NIL, palloc0(), parse(), PlannerInfo::parse, QualCost::per_tuple, pull_var_clause(), PVC_INCLUDE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS, PVC_INCLUDE_WINDOWFUNCS, set_pathtarget_cost_width(), Query::sortClause, and PlannerInfo::tuple_fraction.

Referenced by grouping_planner().

5346 {
5347  Query *parse = root->parse;
5348  PathTarget *input_target;
5349  int ncols;
5350  bool *col_is_srf;
5351  bool *postpone_col;
5352  bool have_srf;
5353  bool have_volatile;
5354  bool have_expensive;
5355  bool have_srf_sortcols;
5356  bool postpone_srfs;
5357  List *postponable_cols;
5358  List *postponable_vars;
5359  int i;
5360  ListCell *lc;
5361 
5362  /* Shouldn't get here unless query has ORDER BY */
5363  Assert(parse->sortClause);
5364 
5365  *have_postponed_srfs = false; /* default result */
5366 
5367  /* Inspect tlist and collect per-column information */
5368  ncols = list_length(final_target->exprs);
5369  col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
5370  postpone_col = (bool *) palloc0(ncols * sizeof(bool));
5371  have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
5372 
5373  i = 0;
5374  foreach(lc, final_target->exprs)
5375  {
5376  Expr *expr = (Expr *) lfirst(lc);
5377 
5378  /*
5379  * If the column has a sortgroupref, assume it has to be evaluated
5380  * before sorting. Generally such columns would be ORDER BY, GROUP
5381  * BY, etc targets. One exception is columns that were removed from
5382  * GROUP BY by remove_useless_groupby_columns() ... but those would
5383  * only be Vars anyway. There don't seem to be any cases where it
5384  * would be worth the trouble to double-check.
5385  */
5386  if (get_pathtarget_sortgroupref(final_target, i) == 0)
5387  {
5388  /*
5389  * Check for SRF or volatile functions. Check the SRF case first
5390  * because we must know whether we have any postponed SRFs.
5391  */
5392  if (parse->hasTargetSRFs &&
5393  expression_returns_set((Node *) expr))
5394  {
5395  /* We'll decide below whether these are postponable */
5396  col_is_srf[i] = true;
5397  have_srf = true;
5398  }
5399  else if (contain_volatile_functions((Node *) expr))
5400  {
5401  /* Unconditionally postpone */
5402  postpone_col[i] = true;
5403  have_volatile = true;
5404  }
5405  else
5406  {
5407  /*
5408  * Else check the cost. XXX it's annoying to have to do this
5409  * when set_pathtarget_cost_width() just did it. Refactor to
5410  * allow sharing the work?
5411  */
5412  QualCost cost;
5413 
5414  cost_qual_eval_node(&cost, (Node *) expr, root);
5415 
5416  /*
5417  * We arbitrarily define "expensive" as "more than 10X
5418  * cpu_operator_cost". Note this will take in any PL function
5419  * with default cost.
5420  */
5421  if (cost.per_tuple > 10 * cpu_operator_cost)
5422  {
5423  postpone_col[i] = true;
5424  have_expensive = true;
5425  }
5426  }
5427  }
5428  else
5429  {
5430  /* For sortgroupref cols, just check if any contain SRFs */
5431  if (!have_srf_sortcols &&
5432  parse->hasTargetSRFs &&
5433  expression_returns_set((Node *) expr))
5434  have_srf_sortcols = true;
5435  }
5436 
5437  i++;
5438  }
5439 
5440  /*
5441  * We can postpone SRFs if we have some but none are in sortgroupref cols.
5442  */
5443  postpone_srfs = (have_srf && !have_srf_sortcols);
5444 
5445  /*
5446  * If we don't need a post-sort projection, just return final_target.
5447  */
5448  if (!(postpone_srfs || have_volatile ||
5449  (have_expensive &&
5450  (parse->limitCount || root->tuple_fraction > 0))))
5451  return final_target;
5452 
5453  /*
5454  * Report whether the post-sort projection will contain set-returning
5455  * functions. This is important because it affects whether the Sort can
5456  * rely on the query's LIMIT (if any) to bound the number of rows it needs
5457  * to return.
5458  */
5459  *have_postponed_srfs = postpone_srfs;
5460 
5461  /*
5462  * Construct the sort-input target, taking all non-postponable columns and
5463  * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
5464  * the postponable ones.
5465  */
5466  input_target = create_empty_pathtarget();
5467  postponable_cols = NIL;
5468 
5469  i = 0;
5470  foreach(lc, final_target->exprs)
5471  {
5472  Expr *expr = (Expr *) lfirst(lc);
5473 
5474  if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
5475  postponable_cols = lappend(postponable_cols, expr);
5476  else
5477  add_column_to_pathtarget(input_target, expr,
5478  get_pathtarget_sortgroupref(final_target, i));
5479 
5480  i++;
5481  }
5482 
5483  /*
5484  * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
5485  * postponable columns, and add them to the sort-input target if not
5486  * already present. (Some might be there already.) We mustn't
5487  * deconstruct Aggrefs or WindowFuncs here, since the projection node
5488  * would be unable to recompute them.
5489  */
5490  postponable_vars = pull_var_clause((Node *) postponable_cols,
5494  add_new_columns_to_pathtarget(input_target, postponable_vars);
5495 
5496  /* clean up cruft */
5497  list_free(postponable_vars);
5498  list_free(postponable_cols);
5499 
5500  /* XXX this represents even more redundant cost calculation ... */
5501  return set_pathtarget_cost_width(root, input_target);
5502 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3729
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
List * sortClause
Definition: parsenodes.h:156
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:5233
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:670
Definition: nodes.h:513
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:960
#define PVC_INCLUDE_AGGREGATES
Definition: var.h:20
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
Cost per_tuple
Definition: relation.h:46
double tuple_fraction
Definition: relation.h:294
Node * limitCount
Definition: parsenodes.h:159
double cpu_operator_cost
Definition: costsize.c:108
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:983
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:976
void * palloc0(Size size)
Definition: mcxt.c:864
#define PVC_INCLUDE_WINDOWFUNCS
Definition: var.h:22
bool hasTargetSRFs
Definition: parsenodes.h:125
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
void list_free(List *list)
Definition: list.c:1133
int i
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:714

◆ make_window_input_target()

static PathTarget * make_window_input_target ( PlannerInfo root,
PathTarget final_target,
List activeWindows 
)
static

Definition at line 5128 of file planner.c.

References add_column_to_pathtarget(), add_new_columns_to_pathtarget(), Assert, bms_add_member(), bms_is_member(), create_empty_pathtarget(), PathTarget::exprs, get_pathtarget_sortgroupref, Query::groupClause, Query::hasWindowFuncs, i, lappend(), lfirst, lfirst_node, list_free(), NIL, WindowClause::orderClause, parse(), PlannerInfo::parse, WindowClause::partitionClause, pull_var_clause(), PVC_INCLUDE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, set_pathtarget_cost_width(), and SortGroupClause::tleSortGroupRef.

Referenced by grouping_planner().

5131 {
5132  Query *parse = root->parse;
5133  PathTarget *input_target;
5134  Bitmapset *sgrefs;
5135  List *flattenable_cols;
5136  List *flattenable_vars;
5137  int i;
5138  ListCell *lc;
5139 
5140  Assert(parse->hasWindowFuncs);
5141 
5142  /*
5143  * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
5144  * into a bitmapset for convenient reference below.
5145  */
5146  sgrefs = NULL;
5147  foreach(lc, activeWindows)
5148  {
5150  ListCell *lc2;
5151 
5152  foreach(lc2, wc->partitionClause)
5153  {
5155 
5156  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5157  }
5158  foreach(lc2, wc->orderClause)
5159  {
5161 
5162  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5163  }
5164  }
5165 
5166  /* Add in sortgroupref numbers of GROUP BY clauses, too */
5167  foreach(lc, parse->groupClause)
5168  {
5170 
5171  sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
5172  }
5173 
5174  /*
5175  * Construct a target containing all the non-flattenable targetlist items,
5176  * and save aside the others for a moment.
5177  */
5178  input_target = create_empty_pathtarget();
5179  flattenable_cols = NIL;
5180 
5181  i = 0;
5182  foreach(lc, final_target->exprs)
5183  {
5184  Expr *expr = (Expr *) lfirst(lc);
5185  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5186 
5187  /*
5188  * Don't want to deconstruct window clauses or GROUP BY items. (Note
5189  * that such items can't contain window functions, so it's okay to
5190  * compute them below the WindowAgg nodes.)
5191  */
5192  if (sgref != 0 && bms_is_member(sgref, sgrefs))
5193  {
5194  /*
5195  * Don't want to deconstruct this value, so add it to the input
5196  * target as-is.
5197  */
5198  add_column_to_pathtarget(input_target, expr, sgref);
5199  }
5200  else
5201  {
5202  /*
5203  * Column is to be flattened, so just remember the expression for
5204  * later call to pull_var_clause.
5205  */
5206  flattenable_cols = lappend(flattenable_cols, expr);
5207  }
5208 
5209  i++;
5210  }
5211 
5212  /*
5213  * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
5214  * add them to the input target if not already present. (Some might be
5215  * there already because they're used directly as window/group clauses.)
5216  *
5217  * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
5218  * Aggrefs are placed in the Agg node's tlist and not left to be computed
5219  * at higher levels. On the other hand, we should recurse into
5220  * WindowFuncs to make sure their input expressions are available.
5221  */
5222  flattenable_vars = pull_var_clause((Node *) flattenable_cols,
5226  add_new_columns_to_pathtarget(input_target, flattenable_vars);
5227 
5228  /* clean up cruft */
5229  list_free(flattenable_vars);
5230  list_free(flattenable_cols);
5231 
5232  /* XXX this causes some redundant cost calculation ... */
5233  return set_pathtarget_cost_width(root, input_target);
5234 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:5233
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Index tleSortGroupRef
Definition: parsenodes.h:1204
Definition: nodes.h:513
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
#define PVC_INCLUDE_AGGREGATES
Definition: var.h:20
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
List * partitionClause
Definition: parsenodes.h:1300
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:983
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:976
unsigned int Index
Definition: c.h:431
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:124
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:742
List * orderClause
Definition: parsenodes.h:1301
List * groupClause
Definition: parsenodes.h:146
void list_free(List *list)
Definition: list.c:1133
int i
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:714

◆ mark_partial_aggref()

void mark_partial_aggref ( Aggref agg,
AggSplit  aggsplit 
)

Definition at line 4963 of file planner.c.

References Aggref::aggsplit, AGGSPLIT_SIMPLE, Aggref::aggtranstype, Aggref::aggtype, Assert, BYTEAOID, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, INTERNALOID, and OidIsValid.

Referenced by convert_combining_aggrefs(), and make_partial_grouping_target().

4964 {
4965  /* aggtranstype should be computed by this point */
4967  /* ... but aggsplit should still be as the parser left it */
4968  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
4969 
4970  /* Mark the Aggref with the intended partial-aggregation mode */
4971  agg->aggsplit = aggsplit;
4972 
4973  /*
4974  * Adjust result type if needed. Normally, a partial aggregate returns
4975  * the aggregate's transition type; but if that's INTERNAL and we're
4976  * serializing, it returns BYTEA instead.
4977  */
4978  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
4979  {
4980  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
4981  agg->aggtype = BYTEAOID;
4982  else
4983  agg->aggtype = agg->aggtranstype;
4984  }
4985 }
#define OidIsValid(objectId)
Definition: c.h:594
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:774
#define INTERNALOID
Definition: pg_type.h:698
#define Assert(condition)
Definition: c.h:688
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:773
#define BYTEAOID
Definition: pg_type.h:292
Oid aggtranstype
Definition: primnodes.h:298
Oid aggtype
Definition: primnodes.h:295

◆ plan_cluster_use_sort()

bool plan_cluster_use_sort ( Oid  tableOid,
Oid  indexOid 
)

Definition at line 5696 of file planner.c.

References build_simple_rel(), CMD_SELECT, Query::commandType, cost_qual_eval(), cost_sort(), create_index_path(), create_seqscan_path(), CurrentMemoryContext, enable_indexscan, ForwardScanDirection, get_relation_data_width(), PlannerInfo::glob, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, RangeTblEntry::inFromCl, RangeTblEntry::inh, RangeTblEntry::lateral, lfirst_node, list_make1, maintenance_work_mem, makeNode, NIL, RelOptInfo::pages, PlannerInfo::parse, IndexPath::path, QualCost::per_tuple, PlannerInfo::planner_cxt, PlannerInfo::query_level, RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_RELATION, RelOptInfo::reltarget, RelOptInfo::rows, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, setup_simple_rel_arrays(), QualCost::startup, Path::total_cost, PlannerInfo::total_table_pages, RelOptInfo::tuples, PathTarget::width, and PlannerInfo::wt_param_id.

Referenced by copy_heap_data().

5697 {
5698  PlannerInfo *root;
5699  Query *query;
5700  PlannerGlobal *glob;
5701  RangeTblEntry *rte;
5702  RelOptInfo *rel;
5703  IndexOptInfo *indexInfo;
5704  QualCost indexExprCost;
5705  Cost comparisonCost;
5706  Path *seqScanPath;
5707  Path seqScanAndSortPath;
5708  IndexPath *indexScanPath;
5709  ListCell *lc;
5710 
5711  /* We can short-circuit the cost comparison if indexscans are disabled */
5712  if (!enable_indexscan)
5713  return true; /* use sort */
5714 
5715  /* Set up mostly-dummy planner state */
5716  query = makeNode(Query);
5717  query->commandType = CMD_SELECT;
5718 
5719  glob = makeNode(PlannerGlobal);
5720 
5721  root = makeNode(PlannerInfo);
5722  root->parse = query;
5723  root->glob = glob;
5724  root->query_level = 1;
5726  root->wt_param_id = -1;
5727 
5728  /* Build a minimal RTE for the rel */
5729  rte = makeNode(RangeTblEntry);
5730  rte->rtekind = RTE_RELATION;
5731  rte->relid = tableOid;
5732  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
5733  rte->lateral = false;
5734  rte->inh = false;
5735  rte->inFromCl = true;
5736  query->