PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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)
 
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)
 
Listget_partitioned_child_rels (PlannerInfo *root, Index rti)
 

Variables

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

Macro Definition Documentation

#define EXPRKIND_APPINFO   7

Definition at line 80 of file planner.c.

Referenced by subquery_planner().

#define EXPRKIND_ARBITER_ELEM   10

Definition at line 83 of file planner.c.

Referenced by subquery_planner().

#define EXPRKIND_LIMIT   6

Definition at line 79 of file planner.c.

Referenced by subquery_planner().

#define EXPRKIND_PHV   8

Definition at line 81 of file planner.c.

Referenced by preprocess_phv_expression().

#define EXPRKIND_QUAL   0

Definition at line 73 of file planner.c.

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

#define EXPRKIND_RTFUNC   2

Definition at line 75 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

#define EXPRKIND_RTFUNC_LATERAL   3

Definition at line 76 of file planner.c.

Referenced by subquery_planner().

#define EXPRKIND_TABLEFUNC   11

Definition at line 84 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

#define EXPRKIND_TABLEFUNC_LATERAL   12

Definition at line 85 of file planner.c.

Referenced by subquery_planner().

#define EXPRKIND_TABLESAMPLE   9

Definition at line 82 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

#define EXPRKIND_TARGET   1

Definition at line 74 of file planner.c.

Referenced by subquery_planner().

#define EXPRKIND_VALUES   4

Definition at line 77 of file planner.c.

Referenced by preprocess_expression(), and subquery_planner().

#define EXPRKIND_VALUES_LATERAL   5

Definition at line 78 of file planner.c.

Referenced by subquery_planner().

Function Documentation

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

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

5879 {
5880  ListCell *lc;
5881 
5882  Assert(list_length(targets) == list_length(targets_contain_srfs));
5883  Assert(!linitial_int(targets_contain_srfs));
5884 
5885  /* If no SRFs appear at this plan level, nothing to do */
5886  if (list_length(targets) == 1)
5887  return;
5888 
5889  /*
5890  * Stack SRF-evaluation nodes atop each path for the rel.
5891  *
5892  * In principle we should re-run set_cheapest() here to identify the
5893  * cheapest path, but it seems unlikely that adding the same tlist eval
5894  * costs to all the paths would change that, so we don't bother. Instead,
5895  * just assume that the cheapest-startup and cheapest-total paths remain
5896  * so. (There should be no parameterized paths anymore, so we needn't
5897  * worry about updating cheapest_parameterized_paths.)
5898  */
5899  foreach(lc, rel->pathlist)
5900  {
5901  Path *subpath = (Path *) lfirst(lc);
5902  Path *newpath = subpath;
5903  ListCell *lc1,
5904  *lc2;
5905 
5906  Assert(subpath->param_info == NULL);
5907  forboth(lc1, targets, lc2, targets_contain_srfs)
5908  {
5909  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5910  bool contains_srfs = (bool) lfirst_int(lc2);
5911 
5912  /* If this level doesn't contain SRFs, do regular projection */
5913  if (contains_srfs)
5914  newpath = (Path *) create_set_projection_path(root,
5915  rel,
5916  newpath,
5917  thistarget);
5918  else
5919  newpath = (Path *) apply_projection_to_path(root,
5920  rel,
5921  newpath,
5922  thistarget);
5923  }
5924  lfirst(lc) = newpath;
5925  if (subpath == rel->cheapest_startup_path)
5926  rel->cheapest_startup_path = newpath;
5927  if (subpath == rel->cheapest_total_path)
5928  rel->cheapest_total_path = newpath;
5929  }
5930 
5931  /* Likewise for partial paths, if any */
5932  foreach(lc, rel->partial_pathlist)
5933  {
5934  Path *subpath = (Path *) lfirst(lc);
5935  Path *newpath = subpath;
5936  ListCell *lc1,
5937  *lc2;
5938 
5939  Assert(subpath->param_info == NULL);
5940  forboth(lc1, targets, lc2, targets_contain_srfs)
5941  {
5942  PathTarget *thistarget = lfirst_node(PathTarget, lc1);
5943  bool contains_srfs = (bool) lfirst_int(lc2);
5944 
5945  /* If this level doesn't contain SRFs, do regular projection */
5946  if (contains_srfs)
5947  newpath = (Path *) create_set_projection_path(root,
5948  rel,
5949  newpath,
5950  thistarget);
5951  else
5952  {
5953  /* avoid apply_projection_to_path, in case of multiple refs */
5954  newpath = (Path *) create_projection_path(root,
5955  rel,
5956  newpath,
5957  thistarget);
5958  }
5959  }
5960  lfirst(lc) = newpath;
5961  }
5962 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2370
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
struct Path * cheapest_startup_path
Definition: relation.h:588
ParamPathInfo * param_info
Definition: relation.h:1011
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2279
List * partial_pathlist
Definition: relation.h:587
char bool
Definition: c.h:202
#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:589
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2446
#define Assert(condition)
Definition: c.h:664
#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:585
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
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 4199 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 create_grouping_paths().

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

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

4727 {
4728  Query *parse = root->parse;
4729  Path *cheapest_input_path = input_rel->cheapest_total_path;
4730  RelOptInfo *distinct_rel;
4731  double numDistinctRows;
4732  bool allow_hash;
4733  Path *path;
4734  ListCell *lc;
4735 
4736  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4737  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4738 
4739  /*
4740  * We don't compute anything at this level, so distinct_rel will be
4741  * parallel-safe if the input rel is parallel-safe. In particular, if
4742  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4743  * output those expressions, and will not be parallel-safe unless those
4744  * expressions are parallel-safe.
4745  */
4746  distinct_rel->consider_parallel = input_rel->consider_parallel;
4747 
4748  /*
4749  * If the input rel belongs to a single FDW, so does the distinct_rel.
4750  */
4751  distinct_rel->serverid = input_rel->serverid;
4752  distinct_rel->userid = input_rel->userid;
4753  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4754  distinct_rel->fdwroutine = input_rel->fdwroutine;
4755 
4756  /* Estimate number of distinct rows there will be */
4757  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4758  root->hasHavingQual)
4759  {
4760  /*
4761  * If there was grouping or aggregation, use the number of input rows
4762  * as the estimated number of DISTINCT rows (ie, assume the input is
4763  * already mostly unique).
4764  */
4765  numDistinctRows = cheapest_input_path->rows;
4766  }
4767  else
4768  {
4769  /*
4770  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4771  */
4772  List *distinctExprs;
4773 
4774  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4775  parse->targetList);
4776  numDistinctRows = estimate_num_groups(root, distinctExprs,
4777  cheapest_input_path->rows,
4778  NULL);
4779  }
4780 
4781  /*
4782  * Consider sort-based implementations of DISTINCT, if possible.
4783  */
4785  {
4786  /*
4787  * First, if we have any adequately-presorted paths, just stick a
4788  * Unique node on those. Then consider doing an explicit sort of the
4789  * cheapest input path and Unique'ing that.
4790  *
4791  * When we have DISTINCT ON, we must sort by the more rigorous of
4792  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4793  * Also, if we do have to do an explicit sort, we might as well use
4794  * the more rigorous ordering to avoid a second sort later. (Note
4795  * that the parser will have ensured that one clause is a prefix of
4796  * the other.)
4797  */
4798  List *needed_pathkeys;
4799 
4800  if (parse->hasDistinctOn &&
4802  list_length(root->sort_pathkeys))
4803  needed_pathkeys = root->sort_pathkeys;
4804  else
4805  needed_pathkeys = root->distinct_pathkeys;
4806 
4807  foreach(lc, input_rel->pathlist)
4808  {
4809  Path *path = (Path *) lfirst(lc);
4810 
4811  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4812  {
4813  add_path(distinct_rel, (Path *)
4814  create_upper_unique_path(root, distinct_rel,
4815  path,
4817  numDistinctRows));
4818  }
4819  }
4820 
4821  /* For explicit-sort case, always use the more rigorous clause */
4822  if (list_length(root->distinct_pathkeys) <
4823  list_length(root->sort_pathkeys))
4824  {
4825  needed_pathkeys = root->sort_pathkeys;
4826  /* Assert checks that parser didn't mess up... */
4828  needed_pathkeys));
4829  }
4830  else
4831  needed_pathkeys = root->distinct_pathkeys;
4832 
4833  path = cheapest_input_path;
4834  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4835  path = (Path *) create_sort_path(root, distinct_rel,
4836  path,
4837  needed_pathkeys,
4838  -1.0);
4839 
4840  add_path(distinct_rel, (Path *)
4841  create_upper_unique_path(root, distinct_rel,
4842  path,
4844  numDistinctRows));
4845  }
4846 
4847  /*
4848  * Consider hash-based implementations of DISTINCT, if possible.
4849  *
4850  * If we were not able to make any other types of path, we *must* hash or
4851  * die trying. If we do have other choices, there are several things that
4852  * should prevent selection of hashing: if the query uses DISTINCT ON
4853  * (because it won't really have the expected behavior if we hash), or if
4854  * enable_hashagg is off, or if it looks like the hashtable will exceed
4855  * work_mem.
4856  *
4857  * Note: grouping_is_hashable() is much more expensive to check than the
4858  * other gating conditions, so we want to do it last.
4859  */
4860  if (distinct_rel->pathlist == NIL)
4861  allow_hash = true; /* we have no alternatives */
4862  else if (parse->hasDistinctOn || !enable_hashagg)
4863  allow_hash = false; /* policy-based decision not to hash */
4864  else
4865  {
4866  Size hashentrysize;
4867 
4868  /* Estimate per-hash-entry space at tuple width... */
4869  hashentrysize = MAXALIGN(cheapest_input_path->pathtarget->width) +
4871  /* plus the per-hash-entry overhead */
4872  hashentrysize += hash_agg_entry_size(0);
4873 
4874  /* Allow hashing only if hashtable is predicted to fit in work_mem */
4875  allow_hash = (hashentrysize * numDistinctRows <= work_mem * 1024L);
4876  }
4877 
4878  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4879  {
4880  /* Generate hashed aggregate path --- no sort needed */
4881  add_path(distinct_rel, (Path *)
4882  create_agg_path(root,
4883  distinct_rel,
4884  cheapest_input_path,
4885  cheapest_input_path->pathtarget,
4886  AGG_HASHED,
4888  parse->distinctClause,
4889  NIL,
4890  NULL,
4891  numDistinctRows));
4892  }
4893 
4894  /* Give a helpful error if we failed to find any implementation */
4895  if (distinct_rel->pathlist == NIL)
4896  ereport(ERROR,
4897  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4898  errmsg("could not implement DISTINCT"),
4899  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4900 
4901  /*
4902  * If there is an FDW that's responsible for all baserels of the query,
4903  * let it consider adding ForeignPaths.
4904  */
4905  if (distinct_rel->fdwroutine &&
4906  distinct_rel->fdwroutine->GetForeignUpperPaths)
4907  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4908  input_rel, distinct_rel);
4909 
4910  /* Let extensions possibly add some more paths */
4912  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4913  input_rel, distinct_rel);
4914 
4915  /* Now choose the best path(s) */
4916  set_cheapest(distinct_rel);
4917 
4918  return distinct_rel;
4919 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:194
#define NIL
Definition: pg_list.h:69
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3351
PathTarget * pathtarget
Definition: relation.h:1009
Query * parse
Definition: relation.h:155
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:2615
Oid userid
Definition: relation.h:619
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:69
bool useridiscurrent
Definition: relation.h:620
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:952
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:2667
struct Path * cheapest_total_path
Definition: relation.h:589
struct FdwRoutine * fdwroutine
Definition: relation.h:622
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:234
Oid serverid
Definition: relation.h:618
#define SizeofMinimalTupleHeader
Definition: htup_details.h:650
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:2513
List * pathkeys
Definition: relation.h:1022
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1018
size_t Size
Definition: c.h:350
static int list_length(const List *l)
Definition: pg_list.h:89
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:2012
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
#define MAXALIGN(LEN)
Definition: c.h:576
bool consider_parallel
Definition: relation.h:579
bool enable_hashagg
Definition: costsize.c:124
int width
Definition: relation.h:941
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:585
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
static RelOptInfo * create_grouping_paths ( PlannerInfo root,
RelOptInfo input_rel,
PathTarget target,
const AggClauseCosts agg_costs,
grouping_sets_data gd 
)
static

Definition at line 3562 of file planner.c.

References add_partial_path(), add_path(), AGG_HASHED, AGG_PLAIN, AGG_SORTED, AGGSPLIT_FINAL_DESERIAL, AGGSPLIT_INITIAL_SERIAL, AGGSPLIT_SIMPLE, grouping_sets_data::any_hashable, Assert, RelOptInfo::cheapest_total_path, consider_groupingsets_paths(), RelOptInfo::consider_parallel, create_agg_path(), create_append_path(), create_gather_merge_path(), create_gather_path(), create_group_path(), create_result_path(), create_sort_path(), create_upper_paths_hook, ereport, errcode(), errdetail(), errmsg(), ERROR, estimate_hashagg_tablesize(), PathTarget::exprs, RelOptInfo::fdwroutine, fetch_upper_rel(), get_agg_clause_costs(), get_number_of_groups(), FdwRoutine::GetForeignUpperPaths, PlannerInfo::group_pathkeys, Query::groupClause, grouping_is_hashable(), grouping_is_sortable(), Query::groupingSets, Query::hasAggs, PlannerInfo::hasHavingQual, AggClauseCosts::hasNonPartial, AggClauseCosts::hasNonSerial, Query::havingQual, is_parallel_safe(), lappend(), lfirst, linitial, list_length(), make_partial_grouping_target(), MemSet, NIL, AggClauseCosts::numOrderedAggs, Path::parallel_workers, parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_contained_in(), RelOptInfo::pathlist, Path::pathtarget, grouping_sets_data::rollups, Path::rows, RelOptInfo::serverid, set_cheapest(), subpath(), UPPERREL_GROUP_AGG, RelOptInfo::userid, RelOptInfo::useridiscurrent, and work_mem.

Referenced by grouping_planner().

3567 {
3568  Query *parse = root->parse;
3569  Path *cheapest_path = input_rel->cheapest_total_path;
3570  RelOptInfo *grouped_rel;
3571  PathTarget *partial_grouping_target = NULL;
3572  AggClauseCosts agg_partial_costs; /* parallel only */
3573  AggClauseCosts agg_final_costs; /* parallel only */
3574  Size hashaggtablesize;
3575  double dNumGroups;
3576  double dNumPartialGroups = 0;
3577  bool can_hash;
3578  bool can_sort;
3579  bool try_parallel_aggregation;
3580 
3581  ListCell *lc;
3582 
3583  /* For now, do all work in the (GROUP_AGG, NULL) upperrel */
3584  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
3585 
3586  /*
3587  * If the input relation is not parallel-safe, then the grouped relation
3588  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
3589  * target list and HAVING quals are parallel-safe.
3590  */
3591  if (input_rel->consider_parallel &&
3592  is_parallel_safe(root, (Node *) target->exprs) &&
3593  is_parallel_safe(root, (Node *) parse->havingQual))
3594  grouped_rel->consider_parallel = true;
3595 
3596  /*
3597  * If the input rel belongs to a single FDW, so does the grouped rel.
3598  */
3599  grouped_rel->serverid = input_rel->serverid;
3600  grouped_rel->userid = input_rel->userid;
3601  grouped_rel->useridiscurrent = input_rel->useridiscurrent;
3602  grouped_rel->fdwroutine = input_rel->fdwroutine;
3603 
3604  /*
3605  * Check for degenerate grouping.
3606  */
3607  if ((root->hasHavingQual || parse->groupingSets) &&
3608  !parse->hasAggs && parse->groupClause == NIL)
3609  {
3610  /*
3611  * We have a HAVING qual and/or grouping sets, but no aggregates and
3612  * no GROUP BY (which implies that the grouping sets are all empty).
3613  *
3614  * This is a degenerate case in which we are supposed to emit either
3615  * zero or one row for each grouping set depending on whether HAVING
3616  * succeeds. Furthermore, there cannot be any variables in either
3617  * HAVING or the targetlist, so we actually do not need the FROM table
3618  * at all! We can just throw away the plan-so-far and generate a
3619  * Result node. This is a sufficiently unusual corner case that it's
3620  * not worth contorting the structure of this module to avoid having
3621  * to generate the earlier paths in the first place.
3622  */
3623  int nrows = list_length(parse->groupingSets);
3624  Path *path;
3625 
3626  if (nrows > 1)
3627  {
3628  /*
3629  * Doesn't seem worthwhile writing code to cons up a
3630  * generate_series or a values scan to emit multiple rows. Instead
3631  * just make N clones and append them. (With a volatile HAVING
3632  * clause, this means you might get between 0 and N output rows.
3633  * Offhand I think that's desired.)
3634  */
3635  List *paths = NIL;
3636 
3637  while (--nrows >= 0)
3638  {
3639  path = (Path *)
3640  create_result_path(root, grouped_rel,
3641  target,
3642  (List *) parse->havingQual);
3643  paths = lappend(paths, path);
3644  }
3645  path = (Path *)
3646  create_append_path(grouped_rel,
3647  paths,
3648  NULL,
3649  0,
3650  NIL);
3651  path->pathtarget = target;
3652  }
3653  else
3654  {
3655  /* No grouping sets, or just one, so one output row */
3656  path = (Path *)
3657  create_result_path(root, grouped_rel,
3658  target,
3659  (List *) parse->havingQual);
3660  }
3661 
3662  add_path(grouped_rel, path);
3663 
3664  /* No need to consider any other alternatives. */
3665  set_cheapest(grouped_rel);
3666 
3667  return grouped_rel;
3668  }
3669 
3670  /*
3671  * Estimate number of groups.
3672  */
3673  dNumGroups = get_number_of_groups(root,
3674  cheapest_path->rows,
3675  gd);
3676 
3677  /*
3678  * Determine whether it's possible to perform sort-based implementations
3679  * of grouping. (Note that if groupClause is empty,
3680  * grouping_is_sortable() is trivially true, and all the
3681  * pathkeys_contained_in() tests will succeed too, so that we'll consider
3682  * every surviving input path.)
3683  *
3684  * If we have grouping sets, we might be able to sort some but not all of
3685  * them; in this case, we need can_sort to be true as long as we must
3686  * consider any sorted-input plan.
3687  */
3688  can_sort = (gd && gd->rollups != NIL)
3689  || grouping_is_sortable(parse->groupClause);
3690 
3691  /*
3692  * Determine whether we should consider hash-based implementations of
3693  * grouping.
3694  *
3695  * Hashed aggregation only applies if we're grouping. If we have grouping
3696  * sets, some groups might be hashable but others not; in this case we set
3697  * can_hash true as long as there is nothing globally preventing us from
3698  * hashing (and we should therefore consider plans with hashes).
3699  *
3700  * Executor doesn't support hashed aggregation with DISTINCT or ORDER BY
3701  * aggregates. (Doing so would imply storing *all* the input values in
3702  * the hash table, and/or running many sorts in parallel, either of which
3703  * seems like a certain loser.) We similarly don't support ordered-set
3704  * aggregates in hashed aggregation, but that case is also included in the
3705  * numOrderedAggs count.
3706  *
3707  * Note: grouping_is_hashable() is much more expensive to check than the
3708  * other gating conditions, so we want to do it last.
3709  */
3710  can_hash = (parse->groupClause != NIL &&
3711  agg_costs->numOrderedAggs == 0 &&
3712  (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause)));
3713 
3714  /*
3715  * If grouped_rel->consider_parallel is true, then paths that we generate
3716  * for this grouping relation could be run inside of a worker, but that
3717  * doesn't mean we can actually use the PartialAggregate/FinalizeAggregate
3718  * execution strategy. Figure that out.
3719  */
3720  if (!grouped_rel->consider_parallel)
3721  {
3722  /* Not even parallel-safe. */
3723  try_parallel_aggregation = false;
3724  }
3725  else if (input_rel->partial_pathlist == NIL)
3726  {
3727  /* Nothing to use as input for partial aggregate. */
3728  try_parallel_aggregation = false;
3729  }
3730  else if (!parse->hasAggs && parse->groupClause == NIL)
3731  {
3732  /*
3733  * We don't know how to do parallel aggregation unless we have either
3734  * some aggregates or a grouping clause.
3735  */
3736  try_parallel_aggregation = false;
3737  }
3738  else if (parse->groupingSets)
3739  {
3740  /* We don't know how to do grouping sets in parallel. */
3741  try_parallel_aggregation = false;
3742  }
3743  else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
3744  {
3745  /* Insufficient support for partial mode. */
3746  try_parallel_aggregation = false;
3747  }
3748  else
3749  {
3750  /* Everything looks good. */
3751  try_parallel_aggregation = true;
3752  }
3753 
3754  /*
3755  * Before generating paths for grouped_rel, we first generate any possible
3756  * partial paths; that way, later code can easily consider both parallel
3757  * and non-parallel approaches to grouping. Note that the partial paths
3758  * we generate here are also partially aggregated, so simply pushing a
3759  * Gather node on top is insufficient to create a final path, as would be
3760  * the case for a scan/join rel.
3761  */
3762  if (try_parallel_aggregation)
3763  {
3764  Path *cheapest_partial_path = linitial(input_rel->partial_pathlist);
3765 
3766  /*
3767  * Build target list for partial aggregate paths. These paths cannot
3768  * just emit the same tlist as regular aggregate paths, because (1) we
3769  * must include Vars and Aggrefs needed in HAVING, which might not
3770  * appear in the result tlist, and (2) the Aggrefs must be set in
3771  * partial mode.
3772  */
3773  partial_grouping_target = make_partial_grouping_target(root, target);
3774 
3775  /* Estimate number of partial groups. */
3776  dNumPartialGroups = get_number_of_groups(root,
3777  cheapest_partial_path->rows,
3778  gd);
3779 
3780  /*
3781  * Collect statistics about aggregates for estimating costs of
3782  * performing aggregation in parallel.
3783  */
3784  MemSet(&agg_partial_costs, 0, sizeof(AggClauseCosts));
3785  MemSet(&agg_final_costs, 0, sizeof(AggClauseCosts));
3786  if (parse->hasAggs)
3787  {
3788  /* partial phase */
3789  get_agg_clause_costs(root, (Node *) partial_grouping_target->exprs,
3791  &agg_partial_costs);
3792 
3793  /* final phase */
3794  get_agg_clause_costs(root, (Node *) target->exprs,
3796  &agg_final_costs);
3797  get_agg_clause_costs(root, parse->havingQual,
3799  &agg_final_costs);
3800  }
3801 
3802  if (can_sort)
3803  {
3804  /* This was checked before setting try_parallel_aggregation */
3805  Assert(parse->hasAggs || parse->groupClause);
3806 
3807  /*
3808  * Use any available suitably-sorted path as input, and also
3809  * consider sorting the cheapest partial path.
3810  */
3811  foreach(lc, input_rel->partial_pathlist)
3812  {
3813  Path *path = (Path *) lfirst(lc);
3814  bool is_sorted;
3815 
3816  is_sorted = pathkeys_contained_in(root->group_pathkeys,
3817  path->pathkeys);
3818  if (path == cheapest_partial_path || is_sorted)
3819  {
3820  /* Sort the cheapest partial path, if it isn't already */
3821  if (!is_sorted)
3822  path = (Path *) create_sort_path(root,
3823  grouped_rel,
3824  path,
3825  root->group_pathkeys,
3826  -1.0);
3827 
3828  if (parse->hasAggs)
3829  add_partial_path(grouped_rel, (Path *)
3830  create_agg_path(root,
3831  grouped_rel,
3832  path,
3833  partial_grouping_target,
3834  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
3836  parse->groupClause,
3837  NIL,
3838  &agg_partial_costs,
3839  dNumPartialGroups));
3840  else
3841  add_partial_path(grouped_rel, (Path *)
3842  create_group_path(root,
3843  grouped_rel,
3844  path,
3845  partial_grouping_target,
3846  parse->groupClause,
3847  NIL,
3848  dNumPartialGroups));
3849  }
3850  }
3851  }
3852 
3853  if (can_hash)
3854  {
3855  /* Checked above */
3856  Assert(parse->hasAggs || parse->groupClause);
3857 
3858  hashaggtablesize =
3859  estimate_hashagg_tablesize(cheapest_partial_path,
3860  &agg_partial_costs,
3861  dNumPartialGroups);
3862 
3863  /*
3864  * Tentatively produce a partial HashAgg Path, depending on if it
3865  * looks as if the hash table will fit in work_mem.
3866  */
3867  if (hashaggtablesize < work_mem * 1024L)
3868  {
3869  add_partial_path(grouped_rel, (Path *)
3870  create_agg_path(root,
3871  grouped_rel,
3872  cheapest_partial_path,
3873  partial_grouping_target,
3874  AGG_HASHED,
3876  parse->groupClause,
3877  NIL,
3878  &agg_partial_costs,
3879  dNumPartialGroups));
3880  }
3881  }
3882  }
3883 
3884  /* Build final grouping paths */
3885  if (can_sort)
3886  {
3887  /*
3888  * Use any available suitably-sorted path as input, and also consider
3889  * sorting the cheapest-total path.
3890  */
3891  foreach(lc, input_rel->pathlist)
3892  {
3893  Path *path = (Path *) lfirst(lc);
3894  bool is_sorted;
3895 
3896  is_sorted = pathkeys_contained_in(root->group_pathkeys,
3897  path->pathkeys);
3898  if (path == cheapest_path || is_sorted)
3899  {
3900  /* Sort the cheapest-total path if it isn't already sorted */
3901  if (!is_sorted)
3902  path = (Path *) create_sort_path(root,
3903  grouped_rel,
3904  path,
3905  root->group_pathkeys,
3906  -1.0);
3907 
3908  /* Now decide what to stick atop it */
3909  if (parse->groupingSets)
3910  {
3911  consider_groupingsets_paths(root, grouped_rel,
3912  path, true, can_hash, target,
3913  gd, agg_costs, dNumGroups);
3914  }
3915  else if (parse->hasAggs)
3916  {
3917  /*
3918  * We have aggregation, possibly with plain GROUP BY. Make
3919  * an AggPath.
3920  */
3921  add_path(grouped_rel, (Path *)
3922  create_agg_path(root,
3923  grouped_rel,
3924  path,
3925  target,
3926  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
3928  parse->groupClause,
3929  (List *) parse->havingQual,
3930  agg_costs,
3931  dNumGroups));
3932  }
3933  else if (parse->groupClause)
3934  {
3935  /*
3936  * We have GROUP BY without aggregation or grouping sets.
3937  * Make a GroupPath.
3938  */
3939  add_path(grouped_rel, (Path *)
3940  create_group_path(root,
3941  grouped_rel,
3942  path,
3943  target,
3944  parse->groupClause,
3945  (List *) parse->havingQual,
3946  dNumGroups));
3947  }
3948  else
3949  {
3950  /* Other cases should have been handled above */
3951  Assert(false);
3952  }
3953  }
3954  }
3955 
3956  /*
3957  * Now generate a complete GroupAgg Path atop of the cheapest partial
3958  * path. We can do this using either Gather or Gather Merge.
3959  */
3960  if (grouped_rel->partial_pathlist)
3961  {
3962  Path *path = (Path *) linitial(grouped_rel->partial_pathlist);
3963  double total_groups = path->rows * path->parallel_workers;
3964 
3965  path = (Path *) create_gather_path(root,
3966  grouped_rel,
3967  path,
3968  partial_grouping_target,
3969  NULL,
3970  &total_groups);
3971 
3972  /*
3973  * Since Gather's output is always unsorted, we'll need to sort,
3974  * unless there's no GROUP BY clause or a degenerate (constant)
3975  * one, in which case there will only be a single group.
3976  */
3977  if (root->group_pathkeys)
3978  path = (Path *) create_sort_path(root,
3979  grouped_rel,
3980  path,
3981  root->group_pathkeys,
3982  -1.0);
3983 
3984  if (parse->hasAggs)
3985  add_path(grouped_rel, (Path *)
3986  create_agg_path(root,
3987  grouped_rel,
3988  path,
3989  target,
3990  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
3992  parse->groupClause,
3993  (List *) parse->havingQual,
3994  &agg_final_costs,
3995  dNumGroups));
3996  else
3997  add_path(grouped_rel, (Path *)
3998  create_group_path(root,
3999  grouped_rel,
4000  path,
4001  target,
4002  parse->groupClause,
4003  (List *) parse->havingQual,
4004  dNumGroups));
4005 
4006  /*
4007  * The point of using Gather Merge rather than Gather is that it
4008  * can preserve the ordering of the input path, so there's no
4009  * reason to try it unless (1) it's possible to produce more than
4010  * one output row and (2) we want the output path to be ordered.
4011  */
4012  if (parse->groupClause != NIL && root->group_pathkeys != NIL)
4013  {
4014  foreach(lc, grouped_rel->partial_pathlist)
4015  {
4016  Path *subpath = (Path *) lfirst(lc);
4017  Path *gmpath;
4018  double total_groups;
4019 
4020  /*
4021  * It's useful to consider paths that are already properly
4022  * ordered for Gather Merge, because those don't need a
4023  * sort. It's also useful to consider the cheapest path,
4024  * because sorting it in parallel and then doing Gather
4025  * Merge may be better than doing an unordered Gather
4026  * followed by a sort. But there's no point in
4027  * considering non-cheapest paths that aren't already
4028  * sorted correctly.
4029  */
4030  if (path != subpath &&
4032  subpath->pathkeys))
4033  continue;
4034 
4035  total_groups = subpath->rows * subpath->parallel_workers;
4036 
4037  gmpath = (Path *)
4039  grouped_rel,
4040  subpath,
4041  partial_grouping_target,
4042  root->group_pathkeys,
4043  NULL,
4044  &total_groups);
4045 
4046  if (parse->hasAggs)
4047  add_path(grouped_rel, (Path *)
4048  create_agg_path(root,
4049  grouped_rel,
4050  gmpath,
4051  target,
4052  parse->groupClause ? AGG_SORTED : AGG_PLAIN,
4054  parse->groupClause,
4055  (List *) parse->havingQual,
4056  &agg_final_costs,
4057  dNumGroups));
4058  else
4059  add_path(grouped_rel, (Path *)
4060  create_group_path(root,
4061  grouped_rel,
4062  gmpath,
4063  target,
4064  parse->groupClause,
4065  (List *) parse->havingQual,
4066  dNumGroups));
4067  }
4068  }
4069  }
4070  }
4071 
4072  if (can_hash)
4073  {
4074  if (parse->groupingSets)
4075  {
4076  /*
4077  * Try for a hash-only groupingsets path over unsorted input.
4078  */
4079  consider_groupingsets_paths(root, grouped_rel,
4080  cheapest_path, false, true, target,
4081  gd, agg_costs, dNumGroups);
4082  }
4083  else
4084  {
4085  hashaggtablesize = estimate_hashagg_tablesize(cheapest_path,
4086  agg_costs,
4087  dNumGroups);
4088 
4089  /*
4090  * Provided that the estimated size of the hashtable does not
4091  * exceed work_mem, we'll generate a HashAgg Path, although if we
4092  * were unable to sort above, then we'd better generate a Path, so
4093  * that we at least have one.
4094  */
4095  if (hashaggtablesize < work_mem * 1024L ||
4096  grouped_rel->pathlist == NIL)
4097  {
4098  /*
4099  * We just need an Agg over the cheapest-total input path,
4100  * since input order won't matter.
4101  */
4102  add_path(grouped_rel, (Path *)
4103  create_agg_path(root, grouped_rel,
4104  cheapest_path,
4105  target,
4106  AGG_HASHED,
4108  parse->groupClause,
4109  (List *) parse->havingQual,
4110  agg_costs,
4111  dNumGroups));
4112  }
4113  }
4114 
4115  /*
4116  * Generate a HashAgg Path atop of the cheapest partial path. Once
4117  * again, we'll only do this if it looks as though the hash table
4118  * won't exceed work_mem.
4119  */
4120  if (grouped_rel->partial_pathlist)
4121  {
4122  Path *path = (Path *) linitial(grouped_rel->partial_pathlist);
4123 
4124  hashaggtablesize = estimate_hashagg_tablesize(path,
4125  &agg_final_costs,
4126  dNumGroups);
4127 
4128  if (hashaggtablesize < work_mem * 1024L)
4129  {
4130  double total_groups = path->rows * path->parallel_workers;
4131 
4132  path = (Path *) create_gather_path(root,
4133  grouped_rel,
4134  path,
4135  partial_grouping_target,
4136  NULL,
4137  &total_groups);
4138 
4139  add_path(grouped_rel, (Path *)
4140  create_agg_path(root,
4141  grouped_rel,
4142  path,
4143  target,
4144  AGG_HASHED,
4146  parse->groupClause,
4147  (List *) parse->havingQual,
4148  &agg_final_costs,
4149  dNumGroups));
4150  }
4151  }
4152  }
4153 
4154  /* Give a helpful error if we failed to find any implementation */
4155  if (grouped_rel->pathlist == NIL)
4156  ereport(ERROR,
4157  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4158  errmsg("could not implement GROUP BY"),
4159  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4160 
4161  /*
4162  * If there is an FDW that's responsible for all baserels of the query,
4163  * let it consider adding ForeignPaths.
4164  */
4165  if (grouped_rel->fdwroutine &&
4166  grouped_rel->fdwroutine->GetForeignUpperPaths)
4168  input_rel, grouped_rel);
4169 
4170  /* Let extensions possibly add some more paths */
4172  (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4173  input_rel, grouped_rel);
4174 
4175  /* Now choose the best path(s) */
4176  set_cheapest(grouped_rel);
4177 
4178  /*
4179  * We've been using the partial pathlist for the grouped relation to hold
4180  * partially aggregated paths, but that's actually a little bit bogus
4181  * because it's unsafe for later planning stages -- like ordered_rel ---
4182  * to get the idea that they can use these partial paths as if they didn't
4183  * need a FinalizeAggregate step. Zap the partial pathlist at this stage
4184  * so we don't get confused.
4185  */
4186  grouped_rel->partial_pathlist = NIL;
4187 
4188  return grouped_rel;
4189 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:194
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:1730
PathTarget * pathtarget
Definition: relation.h:1009
Query * parse
Definition: relation.h:155
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
Oid userid
Definition: relation.h:619
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd)
Definition: planner.c:3406
void get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit, AggClauseCosts *costs)
Definition: clauses.c:467
bool hasAggs
Definition: parsenodes.h:123
int parallel_workers
Definition: relation.h:1015
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
List * partial_pathlist
Definition: relation.h:587
#define MemSet(start, val, len)
Definition: c.h:846
bool hasNonSerial
Definition: relation.h:61
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:69
bool hasNonPartial
Definition: relation.h:60
bool useridiscurrent
Definition: relation.h:620
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers, List *partitioned_rels)
Definition: pathnode.c:1203
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:4199
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target)
Definition: planner.c:5182
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1087
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:952
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:2667
struct Path * cheapest_total_path
Definition: relation.h:589
struct FdwRoutine * fdwroutine
Definition: relation.h:622
int errdetail(const char *fmt,...)
Definition: elog.c:873
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *groupClause, List *qual, double numGroups)
Definition: pathnode.c:2557
static Size estimate_hashagg_tablesize(Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition: planner.c:3518
#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:234
Oid serverid
Definition: relation.h:618
List * exprs
Definition: relation.h:938
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:1639
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2513
List * pathkeys
Definition: relation.h:1022
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1018
size_t Size
Definition: c.h:350
static int list_length(const List *l)
Definition: pg_list.h:89
bool consider_parallel
Definition: relation.h:579
List * groupClause
Definition: parsenodes.h:146
int errmsg(const char *fmt,...)
Definition: elog.c:797
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:752
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:1349
List * pathlist
Definition: relation.h:585
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
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
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 4630 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, WindowClause::winref, and WindowFunc::wintype.

Referenced by create_window_paths().

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

Definition at line 4936 of file planner.c.

References add_path(), apply_projection_to_path(), Assert, RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_gather_merge_path(), create_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().

4940 {
4941  Path *cheapest_input_path = input_rel->cheapest_total_path;
4942  RelOptInfo *ordered_rel;
4943  ListCell *lc;
4944 
4945  /* For now, do all work in the (ORDERED, NULL) upperrel */
4946  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4947 
4948  /*
4949  * If the input relation is not parallel-safe, then the ordered relation
4950  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4951  * target list is parallel-safe.
4952  */
4953  if (input_rel->consider_parallel &&
4954  is_parallel_safe(root, (Node *) target->exprs))
4955  ordered_rel->consider_parallel = true;
4956 
4957  /*
4958  * If the input rel belongs to a single FDW, so does the ordered_rel.
4959  */
4960  ordered_rel->serverid = input_rel->serverid;
4961  ordered_rel->userid = input_rel->userid;
4962  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4963  ordered_rel->fdwroutine = input_rel->fdwroutine;
4964 
4965  foreach(lc, input_rel->pathlist)
4966  {
4967  Path *path = (Path *) lfirst(lc);
4968  bool is_sorted;
4969 
4970  is_sorted = pathkeys_contained_in(root->sort_pathkeys,
4971  path->pathkeys);
4972  if (path == cheapest_input_path || is_sorted)
4973  {
4974  if (!is_sorted)
4975  {
4976  /* An explicit sort here can take advantage of LIMIT */
4977  path = (Path *) create_sort_path(root,
4978  ordered_rel,
4979  path,
4980  root->sort_pathkeys,
4981  limit_tuples);
4982  }
4983 
4984  /* Add projection step if needed */
4985  if (path->pathtarget != target)
4986  path = apply_projection_to_path(root, ordered_rel,
4987  path, target);
4988 
4989  add_path(ordered_rel, path);
4990  }
4991  }
4992 
4993  /*
4994  * generate_gather_paths() will have already generated a simple Gather
4995  * path for the best parallel path, if any, and the loop above will have
4996  * considered sorting it. Similarly, generate_gather_paths() will also
4997  * have generated order-preserving Gather Merge plans which can be used
4998  * without sorting if they happen to match the sort_pathkeys, and the loop
4999  * above will have handled those as well. However, there's one more
5000  * possibility: it may make sense to sort the cheapest partial path
5001  * according to the required output order and then use Gather Merge.
5002  */
5003  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5004  input_rel->partial_pathlist != NIL)
5005  {
5006  Path *cheapest_partial_path;
5007 
5008  cheapest_partial_path = linitial(input_rel->partial_pathlist);
5009 
5010  /*
5011  * If cheapest partial path doesn't need a sort, this is redundant
5012  * with what's already been tried.
5013  */
5015  cheapest_partial_path->pathkeys))
5016  {
5017  Path *path;
5018  double total_groups;
5019 
5020  path = (Path *) create_sort_path(root,
5021  ordered_rel,
5022  cheapest_partial_path,
5023  root->sort_pathkeys,
5024  -1.0);
5025 
5026  total_groups = cheapest_partial_path->rows *
5027  cheapest_partial_path->parallel_workers;
5028  path = (Path *)
5029  create_gather_merge_path(root, ordered_rel,
5030  path,
5031  target, root->sort_pathkeys, NULL,
5032  &total_groups);
5033 
5034  /* Add projection step if needed */
5035  if (path->pathtarget != target)
5036  path = apply_projection_to_path(root, ordered_rel,
5037  path, target);
5038 
5039  add_path(ordered_rel, path);
5040  }
5041  }
5042 
5043  /*
5044  * If there is an FDW that's responsible for all baserels of the query,
5045  * let it consider adding ForeignPaths.
5046  */
5047  if (ordered_rel->fdwroutine &&
5048  ordered_rel->fdwroutine->GetForeignUpperPaths)
5049  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5050  input_rel, ordered_rel);
5051 
5052  /* Let extensions possibly add some more paths */
5054  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5055  input_rel, ordered_rel);
5056 
5057  /*
5058  * No need to bother with set_cheapest here; grouping_planner does not
5059  * need us to do it.
5060  */
5061  Assert(ordered_rel->pathlist != NIL);
5062 
5063  return ordered_rel;
5064 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2370
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:194
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:1009
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
Oid userid
Definition: relation.h:619
int parallel_workers
Definition: relation.h:1015
Definition: nodes.h:509
List * partial_pathlist
Definition: relation.h:587
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:69
bool useridiscurrent
Definition: relation.h:620
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1087
#define linitial(l)
Definition: pg_list.h:111
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:952
struct Path * cheapest_total_path
Definition: relation.h:589
struct FdwRoutine * fdwroutine
Definition: relation.h:622
List * sort_pathkeys
Definition: relation.h:267
Oid serverid
Definition: relation.h:618
List * exprs
Definition: relation.h:938
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:1639
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2513
List * pathkeys
Definition: relation.h:1022
#define Assert(condition)
Definition: c.h:664
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1018
bool consider_parallel
Definition: relation.h:579
List * pathlist
Definition: relation.h:585
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 4544 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().

4551 {
4552  RelOptInfo *window_rel;
4553  ListCell *lc;
4554 
4555  /* For now, do all work in the (WINDOW, NULL) upperrel */
4556  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4557 
4558  /*
4559  * If the input relation is not parallel-safe, then the window relation
4560  * can't be parallel-safe, either. Otherwise, we need to examine the
4561  * target list and active windows for non-parallel-safe constructs.
4562  */
4563  if (input_rel->consider_parallel &&
4564  is_parallel_safe(root, (Node *) output_target->exprs) &&
4565  is_parallel_safe(root, (Node *) activeWindows))
4566  window_rel->consider_parallel = true;
4567 
4568  /*
4569  * If the input rel belongs to a single FDW, so does the window rel.
4570  */
4571  window_rel->serverid = input_rel->serverid;
4572  window_rel->userid = input_rel->userid;
4573  window_rel->useridiscurrent = input_rel->useridiscurrent;
4574  window_rel->fdwroutine = input_rel->fdwroutine;
4575 
4576  /*
4577  * Consider computing window functions starting from the existing
4578  * cheapest-total path (which will likely require a sort) as well as any
4579  * existing paths that satisfy root->window_pathkeys (which won't).
4580  */
4581  foreach(lc, input_rel->pathlist)
4582  {
4583  Path *path = (Path *) lfirst(lc);
4584 
4585  if (path == input_rel->cheapest_total_path ||
4588  window_rel,
4589  path,
4590  input_target,
4591  output_target,
4592  tlist,
4593  wflists,
4594  activeWindows);
4595  }
4596 
4597  /*
4598  * If there is an FDW that's responsible for all baserels of the query,
4599  * let it consider adding ForeignPaths.
4600  */
4601  if (window_rel->fdwroutine &&
4602  window_rel->fdwroutine->GetForeignUpperPaths)
4603  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4604  input_rel, window_rel);
4605 
4606  /* Let extensions possibly add some more paths */
4608  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4609  input_rel, window_rel);
4610 
4611  /* Now choose the best path(s) */
4612  set_cheapest(window_rel);
4613 
4614  return window_rel;
4615 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:194
Oid userid
Definition: relation.h:619
Definition: nodes.h:509
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:69
bool useridiscurrent
Definition: relation.h:620
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1087
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:4630
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:952
struct Path * cheapest_total_path
Definition: relation.h:589
struct FdwRoutine * fdwroutine
Definition: relation.h:622
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
Oid serverid
Definition: relation.h:618
List * exprs
Definition: relation.h:938
List * window_pathkeys
Definition: relation.h:265
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
List * pathkeys
Definition: relation.h:1022
#define lfirst(lc)
Definition: pg_list.h:106
bool consider_parallel
Definition: relation.h:579
List * pathlist
Definition: relation.h:585
static Size estimate_hashagg_tablesize ( Path path,
const AggClauseCosts agg_costs,
double  dNumGroups 
)
static

Definition at line 3518 of file planner.c.

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

Referenced by consider_groupingsets_paths(), and create_grouping_paths().

3520 {
3521  Size hashentrysize;
3522 
3523  /* Estimate per-hash-entry space at tuple width... */
3524  hashentrysize = MAXALIGN(path->pathtarget->width) +
3526 
3527  /* plus space for pass-by-ref transition values... */
3528  hashentrysize += agg_costs->transitionSpace;
3529  /* plus the per-hash-entry overhead */
3530  hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
3531 
3532  /*
3533  * Note that this disregards the effect of fill-factor and growth policy
3534  * of the hash-table. That's probably ok, given default the default
3535  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3536  * "double-in-size" growth policies here.
3537  */
3538  return hashentrysize * dNumGroups;
3539 }
PathTarget * pathtarget
Definition: relation.h:1009
#define SizeofMinimalTupleHeader
Definition: htup_details.h:650
size_t Size
Definition: c.h:350
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:2012
#define MAXALIGN(LEN)
Definition: c.h:576
int width
Definition: relation.h:941
Size transitionSpace
Definition: relation.h:64
Expr* expression_planner ( Expr expr)

Definition at line 5987 of file planner.c.

References eval_const_expressions(), fix_opfuncids(), and result.

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

5988 {
5989  Node *result;
5990 
5991  /*
5992  * Convert named-argument function calls, insert default arguments and
5993  * simplify constant subexprs
5994  */
5995  result = eval_const_expressions(NULL, (Node *) expr);
5996 
5997  /* Fill in opfuncid values if missing */
5998  fix_opfuncids(result);
5999 
6000  return (Expr *) result;
6001 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
Definition: nodes.h:509
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2421
return result
Definition: formatting.c:1633
static List * extract_rollup_sets ( List groupingSets)
static

Definition at line 3052 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(), pfree(), and result.

Referenced by preprocess_grouping_sets().

3053 {
3054  int num_sets_raw = list_length(groupingSets);
3055  int num_empty = 0;
3056  int num_sets = 0; /* distinct sets */
3057  int num_chains = 0;
3058  List *result = NIL;
3059  List **results;
3060  List **orig_sets;
3061  Bitmapset **set_masks;
3062  int *chains;
3063  short **adjacency;
3064  short *adjacency_buf;
3066  int i;
3067  int j;
3068  int j_size;
3069  ListCell *lc1 = list_head(groupingSets);
3070  ListCell *lc;
3071 
3072  /*
3073  * Start by stripping out empty sets. The algorithm doesn't require this,
3074  * but the planner currently needs all empty sets to be returned in the
3075  * first list, so we strip them here and add them back after.
3076  */
3077  while (lc1 && lfirst(lc1) == NIL)
3078  {
3079  ++num_empty;
3080  lc1 = lnext(lc1);
3081  }
3082 
3083  /* bail out now if it turns out that all we had were empty sets. */
3084  if (!lc1)
3085  return list_make1(groupingSets);
3086 
3087  /*----------
3088  * We don't strictly need to remove duplicate sets here, but if we don't,
3089  * they tend to become scattered through the result, which is a bit
3090  * confusing (and irritating if we ever decide to optimize them out).
3091  * So we remove them here and add them back after.
3092  *
3093  * For each non-duplicate set, we fill in the following:
3094  *
3095  * orig_sets[i] = list of the original set lists
3096  * set_masks[i] = bitmapset for testing inclusion
3097  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3098  *
3099  * chains[i] will be the result group this set is assigned to.
3100  *
3101  * We index all of these from 1 rather than 0 because it is convenient
3102  * to leave 0 free for the NIL node in the graph algorithm.
3103  *----------
3104  */
3105  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3106  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3107  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3108  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3109 
3110  j_size = 0;
3111  j = 0;
3112  i = 1;
3113 
3114  for_each_cell(lc, lc1)
3115  {
3116  List *candidate = (List *) lfirst(lc);
3117  Bitmapset *candidate_set = NULL;
3118  ListCell *lc2;
3119  int dup_of = 0;
3120 
3121  foreach(lc2, candidate)
3122  {
3123  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3124  }
3125 
3126  /* we can only be a dup if we're the same length as a previous set */
3127  if (j_size == list_length(candidate))
3128  {
3129  int k;
3130 
3131  for (k = j; k < i; ++k)
3132  {
3133  if (bms_equal(set_masks[k], candidate_set))
3134  {
3135  dup_of = k;
3136  break;
3137  }
3138  }
3139  }
3140  else if (j_size < list_length(candidate))
3141  {
3142  j_size = list_length(candidate);
3143  j = i;
3144  }
3145 
3146  if (dup_of > 0)
3147  {
3148  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3149  bms_free(candidate_set);
3150  }
3151  else
3152  {
3153  int k;
3154  int n_adj = 0;
3155 
3156  orig_sets[i] = list_make1(candidate);
3157  set_masks[i] = candidate_set;
3158 
3159  /* fill in adjacency list; no need to compare equal-size sets */
3160 
3161  for (k = j - 1; k > 0; --k)
3162  {
3163  if (bms_is_subset(set_masks[k], candidate_set))
3164  adjacency_buf[++n_adj] = k;
3165  }
3166 
3167  if (n_adj > 0)
3168  {
3169  adjacency_buf[0] = n_adj;
3170  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3171  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3172  }
3173  else
3174  adjacency[i] = NULL;
3175 
3176  ++i;
3177  }
3178  }
3179 
3180  num_sets = i - 1;
3181 
3182  /*
3183  * Apply the graph matching algorithm to do the work.
3184  */
3185  state = BipartiteMatch(num_sets, num_sets, adjacency);
3186 
3187  /*
3188  * Now, the state->pair* fields have the info we need to assign sets to
3189  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3190  * pair_vu[v] = u (both will be true, but we check both so that we can do
3191  * it in one pass)
3192  */
3193  chains = palloc0((num_sets + 1) * sizeof(int));
3194 
3195  for (i = 1; i <= num_sets; ++i)
3196  {
3197  int u = state->pair_vu[i];
3198  int v = state->pair_uv[i];
3199 
3200  if (u > 0 && u < i)
3201  chains[i] = chains[u];
3202  else if (v > 0 && v < i)
3203  chains[i] = chains[v];
3204  else
3205  chains[i] = ++num_chains;
3206  }
3207 
3208  /* build result lists. */
3209  results = palloc0((num_chains + 1) * sizeof(List *));
3210 
3211  for (i = 1; i <= num_sets; ++i)
3212  {
3213  int c = chains[i];
3214 
3215  Assert(c > 0);
3216 
3217  results[c] = list_concat(results[c], orig_sets[i]);
3218  }
3219 
3220  /* push any empty sets back on the first list. */
3221  while (num_empty-- > 0)
3222  results[1] = lcons(NIL, results[1]);
3223 
3224  /* make result list */
3225  for (i = 1; i <= num_chains; ++i)
3226  result = lappend(result, results[i]);
3227 
3228  /*
3229  * Free all the things.
3230  *
3231  * (This is over-fussy for small sets but for large sets we could have
3232  * tied up a nontrivial amount of memory.)
3233  */
3234  BipartiteMatchFree(state);
3235  pfree(results);
3236  pfree(chains);
3237  for (i = 1; i <= num_sets; ++i)
3238  if (adjacency[i])
3239  pfree(adjacency[i]);
3240  pfree(adjacency);
3241  pfree(adjacency_buf);
3242  pfree(orig_sets);
3243  for (i = 1; i <= num_sets; ++i)
3244  bms_free(set_masks[i]);
3245  pfree(set_masks);
3246 
3247  return result;
3248 }
#define NIL
Definition: pg_list.h:69
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1633
void BipartiteMatchFree(BipartiteMatchState *state)
#define list_make1(x1)
Definition: pg_list.h:139
void pfree(void *pointer)
Definition: mcxt.c:949
#define lfirst_int(lc)
Definition: pg_list.h:107
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
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:877
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:201
#define Assert(condition)
Definition: c.h:664
#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:698
void * palloc(Size size)
Definition: mcxt.c:848
int i
Definition: pg_list.h:45
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:131
Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

5835 {
5836  Path *best_path = rel->cheapest_total_path;
5837  ListCell *l;
5838 
5839  /* If all tuples will be retrieved, just return the cheapest-total path */
5840  if (tuple_fraction <= 0.0)
5841  return best_path;
5842 
5843  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5844  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5845  tuple_fraction /= best_path->rows;
5846 
5847  foreach(l, rel->pathlist)
5848  {
5849  Path *path = (Path *) lfirst(l);
5850 
5851  if (path == rel->cheapest_total_path ||
5852  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5853  continue;
5854 
5855  best_path = path;
5856  }
5857 
5858  return best_path;
5859 }
struct Path * cheapest_total_path
Definition: relation.h:589
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1018
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:107
List * pathlist
Definition: relation.h:585
static double get_number_of_groups ( PlannerInfo root,
double  path_rows,
grouping_sets_data gd 
)
static

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

3409 {
3410  Query *parse = root->parse;
3411  double dNumGroups;
3412 
3413  if (parse->groupClause)
3414  {
3415  List *groupExprs;
3416 
3417  if (parse->groupingSets)
3418  {
3419  /* Add up the estimates for each grouping set */
3420  ListCell *lc;
3421  ListCell *lc2;
3422 
3423  Assert(gd); /* keep Coverity happy */
3424 
3425  dNumGroups = 0;
3426 
3427  foreach(lc, gd->rollups)
3428  {
3429  RollupData *rollup = lfirst_node(RollupData, lc);
3430  ListCell *lc;
3431 
3432  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3433  parse->targetList);
3434 
3435  rollup->numGroups = 0.0;
3436 
3437  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3438  {
3439  List *gset = (List *) lfirst(lc);
3441  double numGroups = estimate_num_groups(root,
3442  groupExprs,
3443  path_rows,
3444  &gset);
3445 
3446  gs->numGroups = numGroups;
3447  rollup->numGroups += numGroups;
3448  }
3449 
3450  dNumGroups += rollup->numGroups;
3451  }
3452 
3453  if (gd->hash_sets_idx)
3454  {
3455  ListCell *lc;
3456 
3457  gd->dNumHashGroups = 0;
3458 
3459  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3460  parse->targetList);
3461 
3462  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3463  {
3464  List *gset = (List *) lfirst(lc);
3466  double numGroups = estimate_num_groups(root,
3467  groupExprs,
3468  path_rows,
3469  &gset);
3470 
3471  gs->numGroups = numGroups;
3472  gd->dNumHashGroups += numGroups;
3473  }
3474 
3475  dNumGroups += gd->dNumHashGroups;
3476  }
3477  }
3478  else
3479  {
3480  /* Plain GROUP BY */
3481  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3482  parse->targetList);
3483 
3484  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3485  NULL);
3486  }
3487  }
3488  else if (parse->groupingSets)
3489  {
3490  /* Empty grouping sets ... one result row for each one */
3491  dNumGroups = list_length(parse->groupingSets);
3492  }
3493  else if (parse->hasAggs || root->hasHavingQual)
3494  {
3495  /* Plain aggregation, one result row */
3496  dNumGroups = 1;
3497  }
3498  else
3499  {
3500  /* Not grouping */
3501  dNumGroups = 1;
3502  }
3503 
3504  return dNumGroups;
3505 }
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3351
Query * parse
Definition: relation.h:155
List * groupClause
Definition: relation.h:1536
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
bool hasAggs
Definition: parsenodes.h:123
List * hash_sets_idx
Definition: planner.c:102
List * groupingSets
Definition: parsenodes.h:148
double dNumHashGroups
Definition: planner.c:103
double numGroups
Definition: relation.h:1539
List * targetList
Definition: parsenodes.h:138
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define Assert(condition)
Definition: c.h:664
#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:107
List * groupClause
Definition: parsenodes.h:146
double numGroups
Definition: relation.h:1530
bool hasHavingQual
Definition: relation.h:305
Definition: pg_list.h:45
List * gsets_data
Definition: relation.h:1538
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1537
List* get_partitioned_child_rels ( PlannerInfo root,
Index  rti 
)

Definition at line 6125 of file planner.c.

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

Referenced by add_paths_to_append_rel(), and inheritance_planner().

6126 {
6127  List *result = NIL;
6128  ListCell *l;
6129 
6130  foreach(l, root->pcinfo_list)
6131  {
6133 
6134  if (pc->parent_relid == rti)
6135  {
6136  result = pc->child_rels;
6137  break;
6138  }
6139  }
6140 
6141  return result;
6142 }
#define NIL
Definition: pg_list.h:69
return result
Definition: formatting.c:1633
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * pcinfo_list
Definition: relation.h:254
Definition: pg_list.h:45
static void grouping_planner ( PlannerInfo root,
bool  inheritance_update,
double  tuple_fraction 
)
static

Definition at line 1513 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, OnConflictExpr::onConflictSet, 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_onconflict_targetlist(), preprocess_targetlist(), PlannerInfo::processed_tlist, query_planner(), Query::resultRelation, Query::returningList, grouping_sets_data::rollups, Query::rowMarks, PlannerInfo::rowMarks, Query::rtable, 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().

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

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

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

Definition at line 2348 of file planner.c.

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

2349 {
2350  if (IsA(plan, Result))
2351  {
2352  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2353 
2354  if (list_length(rcqual) == 1)
2355  {
2356  Const *constqual = (Const *) linitial(rcqual);
2357 
2358  if (constqual && IsA(constqual, Const))
2359  {
2360  if (!constqual->constisnull &&
2361  !DatumGetBool(constqual->constvalue))
2362  return true;
2363  }
2364  }
2365  }
2366  return false;
2367 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define linitial(l)
Definition: pg_list.h:111
#define DatumGetBool(X)
Definition: postgres.h:399
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
bool constisnull
Definition: primnodes.h:197
static bool limit_needed ( Query parse)
static

Definition at line 2735 of file planner.c.

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

Referenced by grouping_planner().

2736 {
2737  Node *node;
2738 
2739  node = parse->limitCount;
2740  if (node)
2741  {
2742  if (IsA(node, Const))
2743  {
2744  /* NULL indicates LIMIT ALL, ie, no limit */
2745  if (!((Const *) node)->constisnull)
2746  return true; /* LIMIT with a constant value */
2747  }
2748  else
2749  return true; /* non-constant LIMIT */
2750  }
2751 
2752  node = parse->limitOffset;
2753  if (node)
2754  {
2755  if (IsA(node, Const))
2756  {
2757  /* Treat NULL as no offset; the executor would too */
2758  if (!((Const *) node)->constisnull)
2759  {
2760  int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2761 
2762  if (offset != 0)
2763  return true; /* OFFSET with a nonzero value */
2764  }
2765  }
2766  else
2767  return true; /* non-constant OFFSET */
2768  }
2769 
2770  return false; /* don't need a Limit plan node */
2771 }
Node * limitOffset
Definition: parsenodes.h:158
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Definition: nodes.h:509
#define DatumGetInt64(X)
Definition: postgres.h:613
Node * limitCount
Definition: parsenodes.h:159
static PathTarget * make_group_input_target ( PlannerInfo root,
PathTarget final_target 
)
static

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

5096 {
5097  Query *parse = root->parse;
5098  PathTarget *input_target;
5099  List *non_group_cols;
5100  List *non_group_vars;
5101  int i;
5102  ListCell *lc;
5103 
5104  /*
5105  * We must build a target containing all grouping columns, plus any other
5106  * Vars mentioned in the query's targetlist and HAVING qual.
5107  */
5108  input_target = create_empty_pathtarget();
5109  non_group_cols = NIL;
5110 
5111  i = 0;
5112  foreach(lc, final_target->exprs)
5113  {
5114  Expr *expr = (Expr *) lfirst(lc);
5115  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5116 
5117  if (sgref && parse->groupClause &&
5118  get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
5119  {
5120  /*
5121  * It's a grouping column, so add it to the input target as-is.
5122  */
5123  add_column_to_pathtarget(input_target, expr, sgref);
5124  }
5125  else
5126  {
5127  /*
5128  * Non-grouping column, so just remember the expression for later
5129  * call to pull_var_clause.
5130  */
5131  non_group_cols = lappend(non_group_cols, expr);
5132  }
5133 
5134  i++;
5135  }
5136 
5137  /*
5138  * If there's a HAVING clause, we'll need the Vars it uses, too.
5139  */
5140  if (parse->havingQual)
5141  non_group_cols = lappend(non_group_cols, parse->havingQual);
5142 
5143  /*
5144  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5145  * add them to the input target if not already present. (A Var used
5146  * directly as a GROUP BY item will be present already.) Note this
5147  * includes Vars used in resjunk items, so we are covering the needs of
5148  * ORDER BY and window specifications. Vars used within Aggrefs and
5149  * WindowFuncs will be pulled out here, too.
5150  */
5151  non_group_vars = pull_var_clause((Node *) non_group_cols,
5155  add_new_columns_to_pathtarget(input_target, non_group_vars);
5156 
5157  /* clean up cruft */
5158  list_free(non_group_vars);
5159  list_free(non_group_cols);
5160 
5161  /* XXX this causes some redundant cost calculation ... */
5162  return set_pathtarget_cost_width(root, input_target);
5163 }
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:4990
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Definition: nodes.h:509
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:945
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:938
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:446
unsigned int Index
Definition: c.h:359
#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
static PathTarget * make_partial_grouping_target ( PlannerInfo root,
PathTarget grouping_target 
)
static

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

5183 {
5184  Query *parse = root->parse;
5185  PathTarget *partial_target;
5186  List *non_group_cols;
5187  List *non_group_exprs;
5188  int i;
5189  ListCell *lc;
5190 
5191  partial_target = create_empty_pathtarget();
5192  non_group_cols = NIL;
5193 
5194  i = 0;
5195  foreach(lc, grouping_target->exprs)
5196  {
5197  Expr *expr = (Expr *) lfirst(lc);
5198  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
5199 
5200  if (sgref && parse->groupClause &&
5201  get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
5202  {
5203  /*
5204  * It's a grouping column, so add it to the partial_target as-is.
5205  * (This allows the upper agg step to repeat the grouping calcs.)
5206  */
5207  add_column_to_pathtarget(partial_target, expr, sgref);
5208  }
5209  else
5210  {
5211  /*
5212  * Non-grouping column, so just remember the expression for later
5213  * call to pull_var_clause.
5214  */
5215  non_group_cols = lappend(non_group_cols, expr);
5216  }
5217 
5218  i++;
5219  }
5220 
5221  /*
5222  * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
5223  */
5224  if (parse->havingQual)
5225  non_group_cols = lappend(non_group_cols, parse->havingQual);
5226 
5227  /*
5228  * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
5229  * non-group cols (plus HAVING), and add them to the partial_target if not
5230  * already present. (An expression used directly as a GROUP BY item will
5231  * be present already.) Note this includes Vars used in resjunk items, so
5232  * we are covering the needs of ORDER BY and window specifications.
5233  */
5234  non_group_exprs = pull_var_clause((Node *) non_group_cols,
5238 
5239  add_new_columns_to_pathtarget(partial_target, non_group_exprs);
5240 
5241  /*
5242  * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5243  * are at the top level of the target list, so we can just scan the list
5244  * rather than recursing through the expression trees.
5245  */
5246  foreach(lc, partial_target->exprs)
5247  {
5248  Aggref *aggref = (Aggref *) lfirst(lc);
5249 
5250  if (IsA(aggref, Aggref))
5251  {
5252  Aggref *newaggref;
5253 
5254  /*
5255  * We shouldn't need to copy the substructure of the Aggref node,
5256  * but flat-copy the node itself to avoid damaging other trees.
5257  */
5258  newaggref = makeNode(Aggref);
5259  memcpy(newaggref, aggref, sizeof(Aggref));
5260 
5261  /* For now, assume serialization is required */
5263 
5264  lfirst(lc) = newaggref;
5265  }
5266  }
5267 
5268  /* clean up cruft */
5269  list_free(non_group_exprs);
5270  list_free(non_group_cols);
5271 
5272  /* XXX this causes some redundant cost calculation ... */
5273  return set_pathtarget_cost_width(root, partial_target);
5274 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:155
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:4990
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:5283
Definition: nodes.h:509
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:945
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:938
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:446
unsigned int Index
Definition: c.h:359
#define makeNode(_type_)
Definition: nodes.h:557
#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
static List * make_pathkeys_for_window ( PlannerInfo root,
WindowClause wc,
List tlist 
)
static

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

5570 {
5571  List *window_pathkeys;
5572  List *window_sortclauses;
5573 
5574  /* Throw error if can't sort */
5576  ereport(ERROR,
5577  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5578  errmsg("could not implement window PARTITION BY"),
5579  errdetail("Window partitioning columns must be of sortable datatypes.")));
5581  ereport(ERROR,
5582  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5583  errmsg("could not implement window ORDER BY"),
5584  errdetail("Window ordering columns must be of sortable datatypes.")));
5585 
5586  /* Okay, make the combined pathkeys */
5587  window_sortclauses = list_concat(list_copy(wc->partitionClause),
5588  list_copy(wc->orderClause));
5589  window_pathkeys = make_pathkeys_for_sortclauses(root,
5590  window_sortclauses,
5591  tlist);
5592  list_free(window_sortclauses);
5593  return window_pathkeys;
5594 }
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:1283
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * orderClause
Definition: parsenodes.h:1284
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
static PathTarget * make_sort_input_target ( PlannerInfo root,
PathTarget final_target,
bool have_postponed_srfs 
)
static

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

5666 {
5667  Query *parse = root->parse;
5668  PathTarget *input_target;
5669  int ncols;
5670  bool *col_is_srf;
5671  bool *postpone_col;
5672  bool have_srf;
5673  bool have_volatile;
5674  bool have_expensive;
5675  bool have_srf_sortcols;
5676  bool postpone_srfs;
5677  List *postponable_cols;
5678  List *postponable_vars;
5679  int i;
5680  ListCell *lc;
5681 
5682  /* Shouldn't get here unless query has ORDER BY */
5683  Assert(parse->sortClause);
5684 
5685  *have_postponed_srfs = false; /* default result */
5686 
5687  /* Inspect tlist and collect per-column information */
5688  ncols = list_length(final_target->exprs);
5689  col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
5690  postpone_col = (bool *) palloc0(ncols * sizeof(bool));
5691  have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
5692 
5693  i = 0;
5694  foreach(lc, final_target->exprs)
5695  {
5696  Expr *expr = (Expr *) lfirst(lc);
5697 
5698  /*
5699  * If the column has a sortgroupref, assume it has to be evaluated
5700  * before sorting. Generally such columns would be ORDER BY, GROUP
5701  * BY, etc targets. One exception is columns that were removed from
5702  * GROUP BY by remove_useless_groupby_columns() ... but those would
5703  * only be Vars anyway. There don't seem to be any cases where it
5704  * would be worth the trouble to double-check.
5705  */
5706  if (get_pathtarget_sortgroupref(final_target, i) == 0)
5707  {
5708  /*
5709  * Check for SRF or volatile functions. Check the SRF case first
5710  * because we must know whether we have any postponed SRFs.
5711  */
5712  if (parse->hasTargetSRFs &&
5713  expression_returns_set((Node *) expr))
5714  {
5715  /* We'll decide below whether these are postponable */
5716  col_is_srf[i] = true;
5717  have_srf = true;
5718  }
5719  else if (contain_volatile_functions((Node *) expr))
5720  {
5721  /* Unconditionally postpone */
5722  postpone_col[i] = true;
5723  have_volatile = true;
5724  }
5725  else
5726  {
5727  /*
5728  * Else check the cost. XXX it's annoying to have to do this
5729  * when set_pathtarget_cost_width() just did it. Refactor to
5730  * allow sharing the work?
5731  */
5732  QualCost cost;
5733 
5734  cost_qual_eval_node(&cost, (Node *) expr, root);
5735 
5736  /*
5737  * We arbitrarily define "expensive" as "more than 10X
5738  * cpu_operator_cost". Note this will take in any PL function
5739  * with default cost.
5740  */
5741  if (cost.per_tuple > 10 * cpu_operator_cost)
5742  {
5743  postpone_col[i] = true;
5744  have_expensive = true;
5745  }
5746  }
5747  }
5748  else
5749  {
5750  /* For sortgroupref cols, just check if any contain SRFs */
5751  if (!have_srf_sortcols &&
5752  parse->hasTargetSRFs &&
5753  expression_returns_set((Node *) expr))
5754  have_srf_sortcols = true;
5755  }
5756 
5757  i++;
5758  }
5759 
5760  /*
5761  * We can postpone SRFs if we have some but none are in sortgroupref cols.
5762  */
5763  postpone_srfs = (have_srf && !have_srf_sortcols);
5764 
5765  /*
5766  * If we don't need a post-sort projection, just return final_target.
5767  */
5768  if (!(postpone_srfs || have_volatile ||
5769  (have_expensive &&
5770  (parse->limitCount || root->tuple_fraction > 0))))
5771  return final_target;
5772 
5773  /*
5774  * Report whether the post-sort projection will contain set-returning
5775  * functions. This is important because it affects whether the Sort can
5776  * rely on the query's LIMIT (if any) to bound the number of rows it needs
5777  * to return.
5778  */
5779  *have_postponed_srfs = postpone_srfs;
5780 
5781  /*
5782  * Construct the sort-input target, taking all non-postponable columns and
5783  * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
5784  * the postponable ones.
5785  */
5786  input_target = create_empty_pathtarget();
5787  postponable_cols = NIL;
5788 
5789  i = 0;
5790  foreach(lc, final_target->exprs)
5791  {
5792  Expr *expr = (Expr *) lfirst(lc);
5793 
5794  if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
5795  postponable_cols = lappend(postponable_cols, expr);
5796  else
5797  add_column_to_pathtarget(input_target, expr,
5798  get_pathtarget_sortgroupref(final_target, i));
5799 
5800  i++;
5801  }
5802 
5803  /*
5804  * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
5805  * postponable columns, and add them to the sort-input target if not
5806  * already present. (Some might be there already.) We mustn't
5807  * deconstruct Aggrefs or WindowFuncs here, since the projection node
5808  * would be unable to recompute them.
5809  */
5810  postponable_vars = pull_var_clause((Node *) postponable_cols,
5814  add_new_columns_to_pathtarget(input_target, postponable_vars);
5815 
5816  /* clean up cruft */
5817  list_free(postponable_vars);
5818  list_free(postponable_cols);
5819 
5820  /* XXX this represents even more redundant cost calculation ... */
5821  return set_pathtarget_cost_width(root, input_target);
5822 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3489
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:4990
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:509
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
#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:945
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:938
void * palloc0(Size size)
Definition: mcxt.c:877
#define PVC_INCLUDE_WINDOWFUNCS
Definition: var.h:22
bool hasTargetSRFs
Definition: parsenodes.h:125
#define Assert(condition)
Definition: c.h:664
#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
static PathTarget * make_window_input_target ( PlannerInfo root,
PathTarget final_target,
List activeWindows 
)
static

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

5451 {
5452  Query *parse = root->parse;
5453  PathTarget *input_target;
5454  Bitmapset *sgrefs;
5455  List *flattenable_cols;
5456  List *flattenable_vars;
5457  int i;
5458  ListCell *lc;
5459 
5460  Assert(parse->hasWindowFuncs);
5461 
5462  /*
5463  * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
5464  * into a bitmapset for convenient reference below.
5465  */
5466  sgrefs = NULL;
5467  foreach(lc, activeWindows)
5468  {
5470  ListCell *lc2;
5471 
5472  foreach(lc2, wc->partitionClause)
5473  {
5475 
5476  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5477  }
5478  foreach(lc2, wc->orderClause)
5479  {
5481 
5482  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5483  }
5484  }
5485 
5486  /* Add in sortgroupref numbers of GROUP BY clauses, too */
5487  foreach(lc, parse->groupClause)
5488  {
5490 
5491  sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
5492  }
5493 
5494  /*
5495  * Construct a target containing all the non-flattenable targetlist items,
5496  * and save aside the others for a moment.
5497  */
5498  input_target = create_empty_pathtarget();
5499  flattenable_cols = NIL;
5500 
5501  i = 0;
5502  foreach(lc, final_target->exprs)
5503  {
5504  Expr *expr = (Expr *) lfirst(lc);
5505  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5506 
5507  /*
5508  * Don't want to deconstruct window clauses or GROUP BY items. (Note
5509  * that such items can't contain window functions, so it's okay to
5510  * compute them below the WindowAgg nodes.)
5511  */
5512  if (sgref != 0 && bms_is_member(sgref, sgrefs))
5513  {
5514  /*
5515  * Don't want to deconstruct this value, so add it to the input
5516  * target as-is.
5517  */
5518  add_column_to_pathtarget(input_target, expr, sgref);
5519  }
5520  else
5521  {
5522  /*
5523  * Column is to be flattened, so just remember the expression for
5524  * later call to pull_var_clause.
5525  */
5526  flattenable_cols = lappend(flattenable_cols, expr);
5527  }
5528 
5529  i++;
5530  }
5531 
5532  /*
5533  * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
5534  * add them to the input target if not already present. (Some might be
5535  * there already because they're used directly as window/group clauses.)
5536  *
5537  * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
5538  * Aggrefs are placed in the Agg node's tlist and not left to be computed
5539  * at higher levels. On the other hand, we should recurse into
5540  * WindowFuncs to make sure their input expressions are available.
5541  */
5542  flattenable_vars = pull_var_clause((Node *) flattenable_cols,
5546  add_new_columns_to_pathtarget(input_target, flattenable_vars);
5547 
5548  /* clean up cruft */
5549  list_free(flattenable_vars);
5550  list_free(flattenable_cols);
5551 
5552  /* XXX this causes some redundant cost calculation ... */
5553  return set_pathtarget_cost_width(root, input_target);
5554 }
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:4990
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Index tleSortGroupRef
Definition: parsenodes.h:1190
Definition: nodes.h:509
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:1283
#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:945
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:938
unsigned int Index
Definition: c.h:359
#define Assert(condition)
Definition: c.h:664
#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:698
List * orderClause
Definition: parsenodes.h:1284
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:420
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
void mark_partial_aggref ( Aggref agg,
AggSplit  aggsplit 
)

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

5284 {
5285  /* aggtranstype should be computed by this point */
5287  /* ... but aggsplit should still be as the parser left it */
5288  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5289 
5290  /* Mark the Aggref with the intended partial-aggregation mode */
5291  agg->aggsplit = aggsplit;
5292 
5293  /*
5294  * Adjust result type if needed. Normally, a partial aggregate returns
5295  * the aggregate's transition type; but if that's INTERNAL and we're
5296  * serializing, it returns BYTEA instead.
5297  */
5298  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5299  {
5300  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5301  agg->aggtype = BYTEAOID;
5302  else
5303  agg->aggtype = agg->aggtranstype;
5304  }
5305 }
#define OidIsValid(objectId)
Definition: c.h:532
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:770
#define INTERNALOID
Definition: pg_type.h:698
#define Assert(condition)
Definition: c.h:664
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:769
#define BYTEAOID
Definition: pg_type.h:292
Oid aggtranstype
Definition: primnodes.h:298
Oid aggtype
Definition: primnodes.h:295
bool plan_cluster_use_sort ( Oid  tableOid,
Oid  indexOid 
)

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

6017 {
6018  PlannerInfo *root;
6019  Query *query;
6020  PlannerGlobal *glob;
6021  RangeTblEntry *rte;
6022  RelOptInfo *rel;
6023  IndexOptInfo *indexInfo;
6024  QualCost indexExprCost;
6025  Cost comparisonCost;
6026  Path *seqScanPath;
6027  Path seqScanAndSortPath;
6028  IndexPath *indexScanPath;
6029  ListCell *lc;
6030 
6031  /* We can short-circuit the cost comparison if indexscans are disabled */
6032  if (!enable_indexscan)
6033  return true; /* use sort */
6034 
6035  /* Set up mostly-dummy planner state */
6036  query = makeNode(Query);
6037  query->commandType = CMD_SELECT;
6038 
6039  glob = makeNode(PlannerGlobal);
6040 
6041  root = makeNode(PlannerInfo);
6042  root->parse = query;
6043  root->glob = glob;
6044  root->query_level = 1;
6046  root->wt_param_id = -1;
6047 
6048  /* Build a minimal RTE for the rel */
6049  rte = makeNode(RangeTblEntry);
6050  rte->rtekind = RTE_RELATION;
6051  rte->relid = tableOid;
6052  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6053  rte->lateral = false;
6054  rte->inh = false;
6055  rte->inFromCl = true;
6056  query->rtable = list_make1(rte);
6057 
6058  /* Set up RTE/RelOptInfo arrays */
6060 
6061  /* Build RelOptInfo */
6062  rel = build_simple_rel(root, 1, NULL);
6063 
6064  /* Locate IndexOptInfo for the target index */
6065  indexInfo = NULL;
6066  foreach(lc, rel->indexlist)
6067  {
6068  indexInfo = lfirst_node(IndexOptInfo, lc);
6069  if (indexInfo->indexoid == indexOid)
6070  break;
6071  }
6072 
6073  /*
6074  * It's possible that get_relation_info did not generate an IndexOptInfo
6075  * for the desired index; this could happen if it's not yet reached its
6076  * indcheckxmin usability horizon, or if it's a system index and we're
6077  * ignoring system indexes. In such cases we should tell CLUSTER to not
6078  * trust the index contents but use seqscan-and-sort.
6079  */
6080  if (lc == NULL) /* not in the list? */
6081  return true; /* use sort */
6082 
6083  /*
6084  * Rather than doing all the pushups that would be needed to use
6085  * set_baserel_size_estimates, just do a quick hack for rows and width.
6086  */
6087  rel->rows = rel->tuples;
6088  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6089 
6090  root->total_table_pages = rel->pages;
6091 
6092  /*
6093  * Determine eval cost of the index expressions, if any. We need to
6094  * charge twice that amount for each tuple comparison that happens during
6095  * the sort, since tuplesort.c will have to re-evaluate the index
6096  * expressions each time. (XXX that's pretty inefficient...)
6097  */
6098  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6099  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6100 
6101  /* Estimate the cost of seq scan + sort */
6102  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6103  cost_sort(&seqScanAndSortPath, root, NIL,
6104  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6105  comparisonCost, maintenance_work_mem, -1.0);
6106 
6107  /* Estimate the cost of index scan */
6108  indexScanPath = create_index_path(root, indexInfo,
6109  NIL, NIL, NIL, NIL, NIL,
6110  ForwardScanDirection, false,
6111  NULL, 1.0, false);
6112 
6113  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6114 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
Path path
Definition: relation.h:1084
double tuples
Definition: relation.h:611
IndexPath * create_index_path(PlannerInfo *root, IndexOptInfo *index, List *indexclauses, List *indexclausecols, List *indexorderbys, List *indexorderbycols, List *pathkeys, ScanDirection indexscandir, bool indexonly, Relids required_outer, double loop_count, bool partial_path)
Definition: pathnode.c:1008
Cost startup
Definition: relation.h:45
#define list_make1(x1)
Definition: pg_list.h:139
Cost per_tuple
Definition: relation.h:46
int wt_param_id
Definition: relation.h:311
List * rtable
Definition: parsenodes.h:135
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3463
#define lfirst_node(type, lc)
Definition: pg_list.h:109
PlannerGlobal * glob
Definition: relation.h:157
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
double total_table_pages
Definition: relation.h:292
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1121
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1644
List * indexlist
Definition: relation.h:608
double rows
Definition: relation.h:574
int maintenance_work_mem
Definition: globals.c:114
Cost total_cost
Definition: relation.h:1020
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
BlockNumber pages
Definition: relation.h:610
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:62
Index query_level
Definition: relation.h:159
RTEKind rtekind
Definition: parsenodes.h:945
int width
Definition: relation.h:941
MemoryContext planner_cxt
Definition: relation.h:290
Oid indexoid
Definition: relation.h:685
#define RELKIND_RELATION
Definition: pg_class.h:160
struct PathTarget * reltarget
Definition: relation.h:582
bool enable_indexscan
Definition: costsize.c:119
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:938
double Cost
Definition: nodes.h:640
List * indexprs
Definition: relation.h:707
PlannedStmt* planner ( Query parse,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 203 of file planner.c.

References parse(), planner_hook, result, and standard_planner().

Referenced by pg_plan_query().

204 {
206 
207  if (planner_hook)
208  result = (*planner_hook) (parse, cursorOptions, boundParams);
209  else
210  result = standard_planner(parse, cursorOptions, boundParams);
211  return result;
212 }
PlannedStmt * standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:215
return result
Definition: formatting.c:1633
planner_hook_type planner_hook
Definition: planner.c:66
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
static List * postprocess_setop_tlist ( List new_tlist,
List orig_tlist 
)
static

Definition at line 5318 of file planner.c.

References Assert, elog, ERROR, lfirst_node, list_head(), lnext, TargetEntry::resjunk, TargetEntry::resno, and TargetEntry::ressortgroupref.

Referenced by grouping_planner().

5319 {
5320  ListCell *l;
5321  ListCell *orig_tlist_item = list_head(orig_tlist);
5322 
5323  foreach(l, new_tlist)
5324  {
5325  TargetEntry *new_tle = lfirst_node(TargetEntry, l);
5326  TargetEntry *orig_tle;
5327 
5328  /* ignore resjunk columns in setop result */
5329  if (new_tle->resjunk)
5330  continue;
5331 
5332  Assert(orig_tlist_item != NULL);
5333  orig_tle = lfirst_node(TargetEntry, orig_tlist_item);
5334  orig_tlist_item = lnext(orig_tlist_item);
5335  if (orig_tle->resjunk) /* should not happen */
5336  elog(ERROR, "resjunk output columns are not implemented");
5337  Assert(new_tle->resno == orig_tle->resno);
5338  new_tle->ressortgroupref = orig_tle->ressortgroupref;
5339  }
5340  if (orig_tlist_item != NULL)
5341  elog(ERROR, "resjunk output columns are not implemented");
5342  return new_tlist;
5343 }
bool resjunk
Definition: primnodes.h:1375
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
AttrNumber resno
Definition: primnodes.h:1369
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
#define Assert(condition)
Definition: c.h:664
Index ressortgroupref
Definition: primnodes.h:1371
#define elog
Definition: elog.h:219