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 5817 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, linitial_int, list_length(), NULL, Path::param_info, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, and subpath().

Referenced by grouping_planner().

5819 {
5820  ListCell *lc;
5821 
5822  Assert(list_length(targets) == list_length(targets_contain_srfs));
5823  Assert(!linitial_int(targets_contain_srfs));
5824 
5825  /* If no SRFs appear at this plan level, nothing to do */
5826  if (list_length(targets) == 1)
5827  return;
5828 
5829  /*
5830  * Stack SRF-evaluation nodes atop each path for the rel.
5831  *
5832  * In principle we should re-run set_cheapest() here to identify the
5833  * cheapest path, but it seems unlikely that adding the same tlist eval
5834  * costs to all the paths would change that, so we don't bother. Instead,
5835  * just assume that the cheapest-startup and cheapest-total paths remain
5836  * so. (There should be no parameterized paths anymore, so we needn't
5837  * worry about updating cheapest_parameterized_paths.)
5838  */
5839  foreach(lc, rel->pathlist)
5840  {
5841  Path *subpath = (Path *) lfirst(lc);
5842  Path *newpath = subpath;
5843  ListCell *lc1,
5844  *lc2;
5845 
5846  Assert(subpath->param_info == NULL);
5847  forboth(lc1, targets, lc2, targets_contain_srfs)
5848  {
5849  PathTarget *thistarget = (PathTarget *) lfirst(lc1);
5850  bool contains_srfs = (bool) lfirst_int(lc2);
5851 
5852  /* If this level doesn't contain SRFs, do regular projection */
5853  if (contains_srfs)
5854  newpath = (Path *) create_set_projection_path(root,
5855  rel,
5856  newpath,
5857  thistarget);
5858  else
5859  newpath = (Path *) apply_projection_to_path(root,
5860  rel,
5861  newpath,
5862  thistarget);
5863  }
5864  lfirst(lc) = newpath;
5865  if (subpath == rel->cheapest_startup_path)
5866  rel->cheapest_startup_path = newpath;
5867  if (subpath == rel->cheapest_total_path)
5868  rel->cheapest_total_path = newpath;
5869  }
5870 
5871  /* Likewise for partial paths, if any */
5872  foreach(lc, rel->partial_pathlist)
5873  {
5874  Path *subpath = (Path *) lfirst(lc);
5875  Path *newpath = subpath;
5876  ListCell *lc1,
5877  *lc2;
5878 
5879  Assert(subpath->param_info == NULL);
5880  forboth(lc1, targets, lc2, targets_contain_srfs)
5881  {
5882  PathTarget *thistarget = (PathTarget *) lfirst(lc1);
5883  bool contains_srfs = (bool) lfirst_int(lc2);
5884 
5885  /* If this level doesn't contain SRFs, do regular projection */
5886  if (contains_srfs)
5887  newpath = (Path *) create_set_projection_path(root,
5888  rel,
5889  newpath,
5890  thistarget);
5891  else
5892  {
5893  /* avoid apply_projection_to_path, in case of multiple refs */
5894  newpath = (Path *) create_projection_path(root,
5895  rel,
5896  newpath,
5897  thistarget);
5898  }
5899  }
5900  lfirst(lc) = newpath;
5901  }
5902 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2343
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
struct Path * cheapest_startup_path
Definition: relation.h:511
ParamPathInfo * param_info
Definition: relation.h:920
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2252
List * partial_pathlist
Definition: relation.h:510
char bool
Definition: c.h:202
#define linitial_int(l)
Definition: pg_list.h:111
#define lfirst_int(lc)
Definition: pg_list.h:107
struct Path * cheapest_total_path
Definition: relation.h:512
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2419
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:508
Definition: relation.h:911
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 4139 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, linitial, list_concat(), list_copy(), list_head(), list_length(), list_make1, lnext, makeNode, Max, Min, NIL, NULL, 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().

4148 {
4149  Query *parse = root->parse;
4150 
4151  /*
4152  * If we're not being offered sorted input, then only consider plans that
4153  * can be done entirely by hashing.
4154  *
4155  * We can hash everything if it looks like it'll fit in work_mem. But if
4156  * the input is actually sorted despite not being advertised as such, we
4157  * prefer to make use of that in order to use less memory.
4158  *
4159  * If none of the grouping sets are sortable, then ignore the work_mem
4160  * limit and generate a path anyway, since otherwise we'll just fail.
4161  */
4162  if (!is_sorted)
4163  {
4164  List *new_rollups = NIL;
4165  RollupData *unhashed_rollup = NULL;
4166  List *sets_data;
4167  List *empty_sets_data = NIL;
4168  List *empty_sets = NIL;
4169  ListCell *lc;
4170  ListCell *l_start = list_head(gd->rollups);
4171  AggStrategy strat = AGG_HASHED;
4172  Size hashsize;
4173  double exclude_groups = 0.0;
4174 
4175  Assert(can_hash);
4176 
4177  if (pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
4178  {
4179  unhashed_rollup = lfirst(l_start);
4180  exclude_groups = unhashed_rollup->numGroups;
4181  l_start = lnext(l_start);
4182  }
4183 
4184  hashsize = estimate_hashagg_tablesize(path,
4185  agg_costs,
4186  dNumGroups - exclude_groups);
4187 
4188  /*
4189  * gd->rollups is empty if we have only unsortable columns to work
4190  * with. Override work_mem in that case; otherwise, we'll rely on the
4191  * sorted-input case to generate usable mixed paths.
4192  */
4193  if (hashsize > work_mem * 1024L && gd->rollups)
4194  return; /* nope, won't fit */
4195 
4196  /*
4197  * We need to burst the existing rollups list into individual grouping
4198  * sets and recompute a groupClause for each set.
4199  */
4200  sets_data = list_copy(gd->unsortable_sets);
4201 
4202  for_each_cell(lc, l_start)
4203  {
4204  RollupData *rollup = lfirst(lc);
4205 
4206  /*
4207  * If we find an unhashable rollup that's not been skipped by the
4208  * "actually sorted" check above, we can't cope; we'd need sorted
4209  * input (with a different sort order) but we can't get that here.
4210  * So bail out; we'll get a valid path from the is_sorted case
4211  * instead.
4212  *
4213  * The mere presence of empty grouping sets doesn't make a rollup
4214  * unhashable (see preprocess_grouping_sets), we handle those
4215  * specially below.
4216  */
4217  if (!rollup->hashable)
4218  return;
4219  else
4220  sets_data = list_concat(sets_data, list_copy(rollup->gsets_data));
4221  }
4222  foreach(lc, sets_data)
4223  {
4224  GroupingSetData *gs = lfirst(lc);
4225  List *gset = gs->set;
4226  RollupData *rollup;
4227 
4228  if (gset == NIL)
4229  {
4230  /* Empty grouping sets can't be hashed. */
4231  empty_sets_data = lappend(empty_sets_data, gs);
4232  empty_sets = lappend(empty_sets, NIL);
4233  }
4234  else
4235  {
4236  rollup = makeNode(RollupData);
4237 
4238  rollup->groupClause = preprocess_groupclause(root, gset);
4239  rollup->gsets_data = list_make1(gs);
4240  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4241  rollup->gsets_data,
4242  gd->tleref_to_colnum_map);
4243  rollup->numGroups = gs->numGroups;
4244  rollup->hashable = true;
4245  rollup->is_hashed = true;
4246  new_rollups = lappend(new_rollups, rollup);
4247  }
4248  }
4249 
4250  /*
4251  * If we didn't find anything nonempty to hash, then bail. We'll
4252  * generate a path from the is_sorted case.
4253  */
4254  if (new_rollups == NIL)
4255  return;
4256 
4257  /*
4258  * If there were empty grouping sets they should have been in the
4259  * first rollup.
4260  */
4261  Assert(!unhashed_rollup || !empty_sets);
4262 
4263  if (unhashed_rollup)
4264  {
4265  new_rollups = lappend(new_rollups, unhashed_rollup);
4266  strat = AGG_MIXED;
4267  }
4268  else if (empty_sets)
4269  {
4270  RollupData *rollup = makeNode(RollupData);
4271 
4272  rollup->groupClause = NIL;
4273  rollup->gsets_data = empty_sets_data;
4274  rollup->gsets = empty_sets;
4275  rollup->numGroups = list_length(empty_sets);
4276  rollup->hashable = false;
4277  rollup->is_hashed = false;
4278  new_rollups = lappend(new_rollups, rollup);
4279  strat = AGG_MIXED;
4280  }
4281 
4282  add_path(grouped_rel, (Path *)
4284  grouped_rel,
4285  path,
4286  target,
4287  (List *) parse->havingQual,
4288  strat,
4289  new_rollups,
4290  agg_costs,
4291  dNumGroups));
4292  return;
4293  }
4294 
4295  /*
4296  * If we have sorted input but nothing we can do with it, bail.
4297  */
4298  if (list_length(gd->rollups) == 0)
4299  return;
4300 
4301  /*
4302  * Given sorted input, we try and make two paths: one sorted and one mixed
4303  * sort/hash. (We need to try both because hashagg might be disabled, or
4304  * some columns might not be sortable.)
4305  *
4306  * can_hash is passed in as false if some obstacle elsewhere (such as
4307  * ordered aggs) means that we shouldn't consider hashing at all.
4308  */
4309  if (can_hash && gd->any_hashable)
4310  {
4311  List *rollups = NIL;
4312  List *hash_sets = list_copy(gd->unsortable_sets);
4313  double availspace = (work_mem * 1024.0);
4314  ListCell *lc;
4315 
4316  /*
4317  * Account first for space needed for groups we can't sort at all.
4318  */
4319  availspace -= (double) estimate_hashagg_tablesize(path,
4320  agg_costs,
4321  gd->dNumHashGroups);
4322 
4323  if (availspace > 0 && list_length(gd->rollups) > 1)
4324  {
4325  double scale;
4326  int num_rollups = list_length(gd->rollups);
4327  int k_capacity;
4328  int *k_weights = palloc(num_rollups * sizeof(int));
4329  Bitmapset *hash_items = NULL;
4330  int i;
4331 
4332  /*
4333  * We treat this as a knapsack problem: the knapsack capacity
4334  * represents work_mem, the item weights are the estimated memory
4335  * usage of the hashtables needed to implement a single rollup, and
4336  * we really ought to use the cost saving as the item value;
4337  * however, currently the costs assigned to sort nodes don't
4338  * reflect the comparison costs well, and so we treat all items as
4339  * of equal value (each rollup we hash instead saves us one sort).
4340  *
4341  * To use the discrete knapsack, we need to scale the values to a
4342  * reasonably small bounded range. We choose to allow a 5% error
4343  * margin; we have no more than 4096 rollups in the worst possible
4344  * case, which with a 5% error margin will require a bit over 42MB
4345  * of workspace. (Anyone wanting to plan queries that complex had
4346  * better have the memory for it. In more reasonable cases, with
4347  * no more than a couple of dozen rollups, the memory usage will
4348  * be negligible.)
4349  *
4350  * k_capacity is naturally bounded, but we clamp the values for
4351  * scale and weight (below) to avoid overflows or underflows (or
4352  * uselessly trying to use a scale factor less than 1 byte).
4353  */
4354  scale = Max(availspace / (20.0 * num_rollups), 1.0);
4355  k_capacity = (int) floor(availspace / scale);
4356 
4357  /*
4358  * We leave the first rollup out of consideration since it's the
4359  * one that matches the input sort order. We assign indexes "i"
4360  * to only those entries considered for hashing; the second loop,
4361  * below, must use the same condition.
4362  */
4363  i = 0;
4365  {
4366  RollupData *rollup = lfirst(lc);
4367 
4368  if (rollup->hashable)
4369  {
4370  double sz = estimate_hashagg_tablesize(path,
4371  agg_costs,
4372  rollup->numGroups);
4373 
4374  /*
4375  * If sz is enormous, but work_mem (and hence scale) is
4376  * small, avoid integer overflow here.
4377  */
4378  k_weights[i] = (int) Min(floor(sz / scale),
4379  k_capacity + 1.0);
4380  ++i;
4381  }
4382  }
4383 
4384  /*
4385  * Apply knapsack algorithm; compute the set of items which
4386  * maximizes the value stored (in this case the number of sorts
4387  * saved) while keeping the total size (approximately) within
4388  * capacity.
4389  */
4390  if (i > 0)
4391  hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4392 
4393  if (!bms_is_empty(hash_items))
4394  {
4395  rollups = list_make1(linitial(gd->rollups));
4396 
4397  i = 0;
4399  {
4400  RollupData *rollup = lfirst(lc);
4401 
4402  if (rollup->hashable)
4403  {
4404  if (bms_is_member(i, hash_items))
4405  hash_sets = list_concat(hash_sets,
4406  list_copy(rollup->gsets_data));
4407  else
4408  rollups = lappend(rollups, rollup);
4409  ++i;
4410  }
4411  else
4412  rollups = lappend(rollups, rollup);
4413  }
4414  }
4415  }
4416 
4417  if (!rollups && hash_sets)
4418  rollups = list_copy(gd->rollups);
4419 
4420  foreach(lc, hash_sets)
4421  {
4422  GroupingSetData *gs = lfirst(lc);
4423  RollupData *rollup = makeNode(RollupData);
4424 
4425  Assert(gs->set != NIL);
4426 
4427  rollup->groupClause = preprocess_groupclause(root, gs->set);
4428  rollup->gsets_data = list_make1(gs);
4429  rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4430  rollup->gsets_data,
4431  gd->tleref_to_colnum_map);
4432  rollup->numGroups = gs->numGroups;
4433  rollup->hashable = true;
4434  rollup->is_hashed = true;
4435  rollups = lcons(rollup, rollups);
4436  }
4437 
4438  if (rollups)
4439  {
4440  add_path(grouped_rel, (Path *)
4442  grouped_rel,
4443  path,
4444  target,
4445  (List *) parse->havingQual,
4446  AGG_MIXED,
4447  rollups,
4448  agg_costs,
4449  dNumGroups));
4450  }
4451  }
4452 
4453  /*
4454  * Now try the simple sorted case.
4455  */
4456  if (!gd->unsortable_sets)
4457  add_path(grouped_rel, (Path *)
4459  grouped_rel,
4460  path,
4461  target,
4462  (List *) parse->havingQual,
4463  AGG_SORTED,
4464  gd->rollups,
4465  agg_costs,
4466  dNumGroups));
4467 }
List * group_pathkeys
Definition: relation.h:263
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:154
List * groupClause
Definition: relation.h:1434
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition: planner.c:2891
#define Min(x, y)
Definition: c.h:806
bool is_hashed
Definition: relation.h:1439
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:1437
#define list_make1(x1)
Definition: pg_list.h:133
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:2705
#define linitial(l)
Definition: pg_list.h:110
int * tleref_to_colnum_map
Definition: planner.c:108
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:3458
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:2246
int work_mem
Definition: globals.c:112
List * lcons(void *datum, List *list)
Definition: list.c:259
List * pathkeys
Definition: relation.h:932
#define Max(x, y)
Definition: c.h:800
#define makeNode(_type_)
Definition: nodes.h:554
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
size_t Size
Definition: c.h:356
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:163
AggStrategy
Definition: nodes.h:725
void * palloc(Size size)
Definition: mcxt.c:849
int i
double numGroups
Definition: relation.h:1428
bool hashable
Definition: relation.h:1438
Node * havingQual
Definition: parsenodes.h:141
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:1436
Definition: relation.h:911
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1435
static RelOptInfo * create_distinct_paths ( PlannerInfo root,
RelOptInfo input_rel 
)
static

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

4667 {
4668  Query *parse = root->parse;
4669  Path *cheapest_input_path = input_rel->cheapest_total_path;
4670  RelOptInfo *distinct_rel;
4671  double numDistinctRows;
4672  bool allow_hash;
4673  Path *path;
4674  ListCell *lc;
4675 
4676  /* For now, do all work in the (DISTINCT, NULL) upperrel */
4677  distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
4678 
4679  /*
4680  * We don't compute anything at this level, so distinct_rel will be
4681  * parallel-safe if the input rel is parallel-safe. In particular, if
4682  * there is a DISTINCT ON (...) clause, any path for the input_rel will
4683  * output those expressions, and will not be parallel-safe unless those
4684  * expressions are parallel-safe.
4685  */
4686  distinct_rel->consider_parallel = input_rel->consider_parallel;
4687 
4688  /*
4689  * If the input rel belongs to a single FDW, so does the distinct_rel.
4690  */
4691  distinct_rel->serverid = input_rel->serverid;
4692  distinct_rel->userid = input_rel->userid;
4693  distinct_rel->useridiscurrent = input_rel->useridiscurrent;
4694  distinct_rel->fdwroutine = input_rel->fdwroutine;
4695 
4696  /* Estimate number of distinct rows there will be */
4697  if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
4698  root->hasHavingQual)
4699  {
4700  /*
4701  * If there was grouping or aggregation, use the number of input rows
4702  * as the estimated number of DISTINCT rows (ie, assume the input is
4703  * already mostly unique).
4704  */
4705  numDistinctRows = cheapest_input_path->rows;
4706  }
4707  else
4708  {
4709  /*
4710  * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
4711  */
4712  List *distinctExprs;
4713 
4714  distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
4715  parse->targetList);
4716  numDistinctRows = estimate_num_groups(root, distinctExprs,
4717  cheapest_input_path->rows,
4718  NULL);
4719  }
4720 
4721  /*
4722  * Consider sort-based implementations of DISTINCT, if possible.
4723  */
4725  {
4726  /*
4727  * First, if we have any adequately-presorted paths, just stick a
4728  * Unique node on those. Then consider doing an explicit sort of the
4729  * cheapest input path and Unique'ing that.
4730  *
4731  * When we have DISTINCT ON, we must sort by the more rigorous of
4732  * DISTINCT and ORDER BY, else it won't have the desired behavior.
4733  * Also, if we do have to do an explicit sort, we might as well use
4734  * the more rigorous ordering to avoid a second sort later. (Note
4735  * that the parser will have ensured that one clause is a prefix of
4736  * the other.)
4737  */
4738  List *needed_pathkeys;
4739 
4740  if (parse->hasDistinctOn &&
4742  list_length(root->sort_pathkeys))
4743  needed_pathkeys = root->sort_pathkeys;
4744  else
4745  needed_pathkeys = root->distinct_pathkeys;
4746 
4747  foreach(lc, input_rel->pathlist)
4748  {
4749  Path *path = (Path *) lfirst(lc);
4750 
4751  if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4752  {
4753  add_path(distinct_rel, (Path *)
4754  create_upper_unique_path(root, distinct_rel,
4755  path,
4757  numDistinctRows));
4758  }
4759  }
4760 
4761  /* For explicit-sort case, always use the more rigorous clause */
4762  if (list_length(root->distinct_pathkeys) <
4763  list_length(root->sort_pathkeys))
4764  {
4765  needed_pathkeys = root->sort_pathkeys;
4766  /* Assert checks that parser didn't mess up... */
4768  needed_pathkeys));
4769  }
4770  else
4771  needed_pathkeys = root->distinct_pathkeys;
4772 
4773  path = cheapest_input_path;
4774  if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
4775  path = (Path *) create_sort_path(root, distinct_rel,
4776  path,
4777  needed_pathkeys,
4778  -1.0);
4779 
4780  add_path(distinct_rel, (Path *)
4781  create_upper_unique_path(root, distinct_rel,
4782  path,
4784  numDistinctRows));
4785  }
4786 
4787  /*
4788  * Consider hash-based implementations of DISTINCT, if possible.
4789  *
4790  * If we were not able to make any other types of path, we *must* hash or
4791  * die trying. If we do have other choices, there are several things that
4792  * should prevent selection of hashing: if the query uses DISTINCT ON
4793  * (because it won't really have the expected behavior if we hash), or if
4794  * enable_hashagg is off, or if it looks like the hashtable will exceed
4795  * work_mem.
4796  *
4797  * Note: grouping_is_hashable() is much more expensive to check than the
4798  * other gating conditions, so we want to do it last.
4799  */
4800  if (distinct_rel->pathlist == NIL)
4801  allow_hash = true; /* we have no alternatives */
4802  else if (parse->hasDistinctOn || !enable_hashagg)
4803  allow_hash = false; /* policy-based decision not to hash */
4804  else
4805  {
4806  Size hashentrysize;
4807 
4808  /* Estimate per-hash-entry space at tuple width... */
4809  hashentrysize = MAXALIGN(cheapest_input_path->pathtarget->width) +
4811  /* plus the per-hash-entry overhead */
4812  hashentrysize += hash_agg_entry_size(0);
4813 
4814  /* Allow hashing only if hashtable is predicted to fit in work_mem */
4815  allow_hash = (hashentrysize * numDistinctRows <= work_mem * 1024L);
4816  }
4817 
4818  if (allow_hash && grouping_is_hashable(parse->distinctClause))
4819  {
4820  /* Generate hashed aggregate path --- no sort needed */
4821  add_path(distinct_rel, (Path *)
4822  create_agg_path(root,
4823  distinct_rel,
4824  cheapest_input_path,
4825  cheapest_input_path->pathtarget,
4826  AGG_HASHED,
4828  parse->distinctClause,
4829  NIL,
4830  NULL,
4831  numDistinctRows));
4832  }
4833 
4834  /* Give a helpful error if we failed to find any implementation */
4835  if (distinct_rel->pathlist == NIL)
4836  ereport(ERROR,
4837  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4838  errmsg("could not implement DISTINCT"),
4839  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4840 
4841  /*
4842  * If there is an FDW that's responsible for all baserels of the query,
4843  * let it consider adding ForeignPaths.
4844  */
4845  if (distinct_rel->fdwroutine &&
4846  distinct_rel->fdwroutine->GetForeignUpperPaths)
4847  distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
4848  input_rel, distinct_rel);
4849 
4850  /* Let extensions possibly add some more paths */
4852  (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
4853  input_rel, distinct_rel);
4854 
4855  /* Now choose the best path(s) */
4856  set_cheapest(distinct_rel);
4857 
4858  return distinct_rel;
4859 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:191
#define NIL
Definition: pg_list.h:69
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3277
PathTarget * pathtarget
Definition: relation.h:918
Query * parse
Definition: relation.h:154
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:2588
Oid userid
Definition: relation.h:542
bool hasAggs
Definition: parsenodes.h:116
List * groupingSets
Definition: parsenodes.h:139
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:543
bool hasDistinctOn
Definition: parsenodes.h:120
List * targetList
Definition: parsenodes.h:131
List * distinctClause
Definition: parsenodes.h:145
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
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:2640
struct Path * cheapest_total_path
Definition: relation.h:512
struct FdwRoutine * fdwroutine
Definition: relation.h:545
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * sort_pathkeys
Definition: relation.h:266
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
Oid serverid
Definition: relation.h:541
#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:112
List * distinct_pathkeys
Definition: relation.h:265
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2486
List * pathkeys
Definition: relation.h:932
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
size_t Size
Definition: c.h:356
static int list_length(const List *l)
Definition: pg_list.h:89
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:2001
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:395
#define MAXALIGN(LEN)
Definition: c.h:588
bool consider_parallel
Definition: relation.h:502
bool enable_hashagg
Definition: costsize.c:124
int width
Definition: relation.h:850
List * groupClause
Definition: parsenodes.h:137
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
bool hasHavingQual
Definition: relation.h:301
List * pathlist
Definition: relation.h:508
Definition: pg_list.h:45
Definition: relation.h:911
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 3502 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, NULL, 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().

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

References add_column_to_pathtarget(), add_path(), castNode, copy_pathtarget(), create_sort_path(), create_windowagg_path(), get_typavgwidth(), lfirst, lnext, make_pathkeys_for_window(), Path::pathkeys, pathkeys_contained_in(), PathTarget::width, WindowFuncLists::windowFuncs, WindowClause::winref, and WindowFunc::wintype.

Referenced by create_window_paths().

4578 {
4579  PathTarget *window_target;
4580  ListCell *l;
4581 
4582  /*
4583  * Since each window clause could require a different sort order, we stack
4584  * up a WindowAgg node for each clause, with sort steps between them as
4585  * needed. (We assume that select_active_windows chose a good order for
4586  * executing the clauses in.)
4587  *
4588  * input_target should contain all Vars and Aggs needed for the result.
4589  * (In some cases we wouldn't need to propagate all of these all the way
4590  * to the top, since they might only be needed as inputs to WindowFuncs.
4591  * It's probably not worth trying to optimize that though.) It must also
4592  * contain all window partitioning and sorting expressions, to ensure
4593  * they're computed only once at the bottom of the stack (that's critical
4594  * for volatile functions). As we climb up the stack, we'll add outputs
4595  * for the WindowFuncs computed at each level.
4596  */
4597  window_target = input_target;
4598 
4599  foreach(l, activeWindows)
4600  {
4601  WindowClause *wc = (WindowClause *) lfirst(l);
4602  List *window_pathkeys;
4603 
4604  window_pathkeys = make_pathkeys_for_window(root,
4605  wc,
4606  tlist);
4607 
4608  /* Sort if necessary */
4609  if (!pathkeys_contained_in(window_pathkeys, path->pathkeys))
4610  {
4611  path = (Path *) create_sort_path(root, window_rel,
4612  path,
4613  window_pathkeys,
4614  -1.0);
4615  }
4616 
4617  if (lnext(l))
4618  {
4619  /*
4620  * Add the current WindowFuncs to the output target for this
4621  * intermediate WindowAggPath. We must copy window_target to
4622  * avoid changing the previous path's target.
4623  *
4624  * Note: a WindowFunc adds nothing to the target's eval costs; but
4625  * we do need to account for the increase in tlist width.
4626  */
4627  ListCell *lc2;
4628 
4629  window_target = copy_pathtarget(window_target);
4630  foreach(lc2, wflists->windowFuncs[wc->winref])
4631  {
4632  WindowFunc *wfunc = castNode(WindowFunc, lfirst(lc2));
4633 
4634  add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
4635  window_target->width += get_typavgwidth(wfunc->wintype, -1);
4636  }
4637  }
4638  else
4639  {
4640  /* Install the goal target in the topmost WindowAgg */
4641  window_target = output_target;
4642  }
4643 
4644  path = (Path *)
4645  create_windowagg_path(root, window_rel, path, window_target,
4646  wflists->windowFuncs[wc->winref],
4647  wc,
4648  window_pathkeys);
4649  }
4650 
4651  add_path(window_rel, path);
4652 }
PathTarget * copy_pathtarget(PathTarget *src)
Definition: tlist.c:629
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition: planner.c:5508
#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:2918
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2296
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2486
List * pathkeys
Definition: relation.h:932
#define lfirst(lc)
Definition: pg_list.h:106
Oid wintype
Definition: primnodes.h:356
int width
Definition: relation.h:850
Definition: pg_list.h:45
List ** windowFuncs
Definition: clauses.h:27
Definition: relation.h:911
static RelOptInfo * create_ordered_paths ( PlannerInfo root,
RelOptInfo input_rel,
PathTarget target,
double  limit_tuples 
)
static

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

4880 {
4881  Path *cheapest_input_path = input_rel->cheapest_total_path;
4882  RelOptInfo *ordered_rel;
4883  ListCell *lc;
4884 
4885  /* For now, do all work in the (ORDERED, NULL) upperrel */
4886  ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
4887 
4888  /*
4889  * If the input relation is not parallel-safe, then the ordered relation
4890  * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4891  * target list is parallel-safe.
4892  */
4893  if (input_rel->consider_parallel &&
4894  is_parallel_safe(root, (Node *) target->exprs))
4895  ordered_rel->consider_parallel = true;
4896 
4897  /*
4898  * If the input rel belongs to a single FDW, so does the ordered_rel.
4899  */
4900  ordered_rel->serverid = input_rel->serverid;
4901  ordered_rel->userid = input_rel->userid;
4902  ordered_rel->useridiscurrent = input_rel->useridiscurrent;
4903  ordered_rel->fdwroutine = input_rel->fdwroutine;
4904 
4905  foreach(lc, input_rel->pathlist)
4906  {
4907  Path *path = (Path *) lfirst(lc);
4908  bool is_sorted;
4909 
4910  is_sorted = pathkeys_contained_in(root->sort_pathkeys,
4911  path->pathkeys);
4912  if (path == cheapest_input_path || is_sorted)
4913  {
4914  if (!is_sorted)
4915  {
4916  /* An explicit sort here can take advantage of LIMIT */
4917  path = (Path *) create_sort_path(root,
4918  ordered_rel,
4919  path,
4920  root->sort_pathkeys,
4921  limit_tuples);
4922  }
4923 
4924  /* Add projection step if needed */
4925  if (path->pathtarget != target)
4926  path = apply_projection_to_path(root, ordered_rel,
4927  path, target);
4928 
4929  add_path(ordered_rel, path);
4930  }
4931  }
4932 
4933  /*
4934  * generate_gather_paths() will have already generated a simple Gather
4935  * path for the best parallel path, if any, and the loop above will have
4936  * considered sorting it. Similarly, generate_gather_paths() will also
4937  * have generated order-preserving Gather Merge plans which can be used
4938  * without sorting if they happen to match the sort_pathkeys, and the loop
4939  * above will have handled those as well. However, there's one more
4940  * possibility: it may make sense to sort the cheapest partial path
4941  * according to the required output order and then use Gather Merge.
4942  */
4943  if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
4944  input_rel->partial_pathlist != NIL)
4945  {
4946  Path *cheapest_partial_path;
4947 
4948  cheapest_partial_path = linitial(input_rel->partial_pathlist);
4949 
4950  /*
4951  * If cheapest partial path doesn't need a sort, this is redundant
4952  * with what's already been tried.
4953  */
4955  cheapest_partial_path->pathkeys))
4956  {
4957  Path *path;
4958  double total_groups;
4959 
4960  path = (Path *) create_sort_path(root,
4961  ordered_rel,
4962  cheapest_partial_path,
4963  root->sort_pathkeys,
4964  -1.0);
4965 
4966  total_groups = cheapest_partial_path->rows *
4967  cheapest_partial_path->parallel_workers;
4968  path = (Path *)
4969  create_gather_merge_path(root, ordered_rel,
4970  path,
4971  target, root->sort_pathkeys, NULL,
4972  &total_groups);
4973 
4974  /* Add projection step if needed */
4975  if (path->pathtarget != target)
4976  path = apply_projection_to_path(root, ordered_rel,
4977  path, target);
4978 
4979  add_path(ordered_rel, path);
4980  }
4981  }
4982 
4983  /*
4984  * If there is an FDW that's responsible for all baserels of the query,
4985  * let it consider adding ForeignPaths.
4986  */
4987  if (ordered_rel->fdwroutine &&
4988  ordered_rel->fdwroutine->GetForeignUpperPaths)
4989  ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
4990  input_rel, ordered_rel);
4991 
4992  /* Let extensions possibly add some more paths */
4994  (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
4995  input_rel, ordered_rel);
4996 
4997  /*
4998  * No need to bother with set_cheapest here; grouping_planner does not
4999  * need us to do it.
5000  */
5001  Assert(ordered_rel->pathlist != NIL);
5002 
5003  return ordered_rel;
5004 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2343
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:191
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:918
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
Oid userid
Definition: relation.h:542
int parallel_workers
Definition: relation.h:924
Definition: nodes.h:506
List * partial_pathlist
Definition: relation.h:510
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:69
bool useridiscurrent
Definition: relation.h:543
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1071
#define linitial(l)
Definition: pg_list.h:110
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
struct Path * cheapest_total_path
Definition: relation.h:512
struct FdwRoutine * fdwroutine
Definition: relation.h:545
List * sort_pathkeys
Definition: relation.h:266
Oid serverid
Definition: relation.h:541
List * exprs
Definition: relation.h:847
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:1640
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2486
List * pathkeys
Definition: relation.h:932
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
bool consider_parallel
Definition: relation.h:502
List * pathlist
Definition: relation.h:508
Definition: relation.h:911
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 4484 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, NULL, 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().

4491 {
4492  RelOptInfo *window_rel;
4493  ListCell *lc;
4494 
4495  /* For now, do all work in the (WINDOW, NULL) upperrel */
4496  window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4497 
4498  /*
4499  * If the input relation is not parallel-safe, then the window relation
4500  * can't be parallel-safe, either. Otherwise, we need to examine the
4501  * target list and active windows for non-parallel-safe constructs.
4502  */
4503  if (input_rel->consider_parallel &&
4504  is_parallel_safe(root, (Node *) output_target->exprs) &&
4505  is_parallel_safe(root, (Node *) activeWindows))
4506  window_rel->consider_parallel = true;
4507 
4508  /*
4509  * If the input rel belongs to a single FDW, so does the window rel.
4510  */
4511  window_rel->serverid = input_rel->serverid;
4512  window_rel->userid = input_rel->userid;
4513  window_rel->useridiscurrent = input_rel->useridiscurrent;
4514  window_rel->fdwroutine = input_rel->fdwroutine;
4515 
4516  /*
4517  * Consider computing window functions starting from the existing
4518  * cheapest-total path (which will likely require a sort) as well as any
4519  * existing paths that satisfy root->window_pathkeys (which won't).
4520  */
4521  foreach(lc, input_rel->pathlist)
4522  {
4523  Path *path = (Path *) lfirst(lc);
4524 
4525  if (path == input_rel->cheapest_total_path ||
4528  window_rel,
4529  path,
4530  input_target,
4531  output_target,
4532  tlist,
4533  wflists,
4534  activeWindows);
4535  }
4536 
4537  /*
4538  * If there is an FDW that's responsible for all baserels of the query,
4539  * let it consider adding ForeignPaths.
4540  */
4541  if (window_rel->fdwroutine &&
4542  window_rel->fdwroutine->GetForeignUpperPaths)
4543  window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4544  input_rel, window_rel);
4545 
4546  /* Let extensions possibly add some more paths */
4548  (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4549  input_rel, window_rel);
4550 
4551  /* Now choose the best path(s) */
4552  set_cheapest(window_rel);
4553 
4554  return window_rel;
4555 }
GetForeignUpperPaths_function GetForeignUpperPaths
Definition: fdwapi.h:191
Oid userid
Definition: relation.h:542
Definition: nodes.h:506
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:69
bool useridiscurrent
Definition: relation.h:543
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1071
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:4570
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
struct Path * cheapest_total_path
Definition: relation.h:512
struct FdwRoutine * fdwroutine
Definition: relation.h:545
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
Oid serverid
Definition: relation.h:541
List * exprs
Definition: relation.h:847
List * window_pathkeys
Definition: relation.h:264
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
List * pathkeys
Definition: relation.h:932
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
bool consider_parallel
Definition: relation.h:502
List * pathlist
Definition: relation.h:508
Definition: relation.h:911
static Size estimate_hashagg_tablesize ( Path path,
const AggClauseCosts agg_costs,
double  dNumGroups 
)
static

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

3460 {
3461  Size hashentrysize;
3462 
3463  /* Estimate per-hash-entry space at tuple width... */
3464  hashentrysize = MAXALIGN(path->pathtarget->width) +
3466 
3467  /* plus space for pass-by-ref transition values... */
3468  hashentrysize += agg_costs->transitionSpace;
3469  /* plus the per-hash-entry overhead */
3470  hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
3471 
3472  /*
3473  * Note that this disregards the effect of fill-factor and growth policy
3474  * of the hash-table. That's probably ok, given default the default
3475  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3476  * "double-in-size" growth policies here.
3477  */
3478  return hashentrysize * dNumGroups;
3479 }
PathTarget * pathtarget
Definition: relation.h:918
#define SizeofMinimalTupleHeader
Definition: htup_details.h:650
size_t Size
Definition: c.h:356
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:2001
#define MAXALIGN(LEN)
Definition: c.h:588
int width
Definition: relation.h:850
Size transitionSpace
Definition: relation.h:64
Expr* expression_planner ( Expr expr)

Definition at line 5927 of file planner.c.

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

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

5928 {
5929  Node *result;
5930 
5931  /*
5932  * Convert named-argument function calls, insert default arguments and
5933  * simplify constant subexprs
5934  */
5935  result = eval_const_expressions(NULL, (Node *) expr);
5936 
5937  /* Fill in opfuncid values if missing */
5938  fix_opfuncids(result);
5939 
5940  return (Expr *) result;
5941 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1594
Definition: nodes.h:506
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2366
return result
Definition: formatting.c:1618
#define NULL
Definition: c.h:229
static List * extract_rollup_sets ( List groupingSets)
static

Definition at line 2994 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, NULL, BipartiteMatchState::pair_uv, BipartiteMatchState::pair_vu, palloc(), palloc0(), pfree(), and result.

Referenced by preprocess_grouping_sets().

2995 {
2996  int num_sets_raw = list_length(groupingSets);
2997  int num_empty = 0;
2998  int num_sets = 0; /* distinct sets */
2999  int num_chains = 0;
3000  List *result = NIL;
3001  List **results;
3002  List **orig_sets;
3003  Bitmapset **set_masks;
3004  int *chains;
3005  short **adjacency;
3006  short *adjacency_buf;
3008  int i;
3009  int j;
3010  int j_size;
3011  ListCell *lc1 = list_head(groupingSets);
3012  ListCell *lc;
3013 
3014  /*
3015  * Start by stripping out empty sets. The algorithm doesn't require this,
3016  * but the planner currently needs all empty sets to be returned in the
3017  * first list, so we strip them here and add them back after.
3018  */
3019  while (lc1 && lfirst(lc1) == NIL)
3020  {
3021  ++num_empty;
3022  lc1 = lnext(lc1);
3023  }
3024 
3025  /* bail out now if it turns out that all we had were empty sets. */
3026  if (!lc1)
3027  return list_make1(groupingSets);
3028 
3029  /*----------
3030  * We don't strictly need to remove duplicate sets here, but if we don't,
3031  * they tend to become scattered through the result, which is a bit
3032  * confusing (and irritating if we ever decide to optimize them out).
3033  * So we remove them here and add them back after.
3034  *
3035  * For each non-duplicate set, we fill in the following:
3036  *
3037  * orig_sets[i] = list of the original set lists
3038  * set_masks[i] = bitmapset for testing inclusion
3039  * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3040  *
3041  * chains[i] will be the result group this set is assigned to.
3042  *
3043  * We index all of these from 1 rather than 0 because it is convenient
3044  * to leave 0 free for the NIL node in the graph algorithm.
3045  *----------
3046  */
3047  orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3048  set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3049  adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3050  adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3051 
3052  j_size = 0;
3053  j = 0;
3054  i = 1;
3055 
3056  for_each_cell(lc, lc1)
3057  {
3058  List *candidate = lfirst(lc);
3059  Bitmapset *candidate_set = NULL;
3060  ListCell *lc2;
3061  int dup_of = 0;
3062 
3063  foreach(lc2, candidate)
3064  {
3065  candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3066  }
3067 
3068  /* we can only be a dup if we're the same length as a previous set */
3069  if (j_size == list_length(candidate))
3070  {
3071  int k;
3072 
3073  for (k = j; k < i; ++k)
3074  {
3075  if (bms_equal(set_masks[k], candidate_set))
3076  {
3077  dup_of = k;
3078  break;
3079  }
3080  }
3081  }
3082  else if (j_size < list_length(candidate))
3083  {
3084  j_size = list_length(candidate);
3085  j = i;
3086  }
3087 
3088  if (dup_of > 0)
3089  {
3090  orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3091  bms_free(candidate_set);
3092  }
3093  else
3094  {
3095  int k;
3096  int n_adj = 0;
3097 
3098  orig_sets[i] = list_make1(candidate);
3099  set_masks[i] = candidate_set;
3100 
3101  /* fill in adjacency list; no need to compare equal-size sets */
3102 
3103  for (k = j - 1; k > 0; --k)
3104  {
3105  if (bms_is_subset(set_masks[k], candidate_set))
3106  adjacency_buf[++n_adj] = k;
3107  }
3108 
3109  if (n_adj > 0)
3110  {
3111  adjacency_buf[0] = n_adj;
3112  adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3113  memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3114  }
3115  else
3116  adjacency[i] = NULL;
3117 
3118  ++i;
3119  }
3120  }
3121 
3122  num_sets = i - 1;
3123 
3124  /*
3125  * Apply the graph matching algorithm to do the work.
3126  */
3127  state = BipartiteMatch(num_sets, num_sets, adjacency);
3128 
3129  /*
3130  * Now, the state->pair* fields have the info we need to assign sets to
3131  * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3132  * pair_vu[v] = u (both will be true, but we check both so that we can do
3133  * it in one pass)
3134  */
3135  chains = palloc0((num_sets + 1) * sizeof(int));
3136 
3137  for (i = 1; i <= num_sets; ++i)
3138  {
3139  int u = state->pair_vu[i];
3140  int v = state->pair_uv[i];
3141 
3142  if (u > 0 && u < i)
3143  chains[i] = chains[u];
3144  else if (v > 0 && v < i)
3145  chains[i] = chains[v];
3146  else
3147  chains[i] = ++num_chains;
3148  }
3149 
3150  /* build result lists. */
3151  results = palloc0((num_chains + 1) * sizeof(List *));
3152 
3153  for (i = 1; i <= num_sets; ++i)
3154  {
3155  int c = chains[i];
3156 
3157  Assert(c > 0);
3158 
3159  results[c] = list_concat(results[c], orig_sets[i]);
3160  }
3161 
3162  /* push any empty sets back on the first list. */
3163  while (num_empty-- > 0)
3164  results[1] = lcons(NIL, results[1]);
3165 
3166  /* make result list */
3167  for (i = 1; i <= num_chains; ++i)
3168  result = lappend(result, results[i]);
3169 
3170  /*
3171  * Free all the things.
3172  *
3173  * (This is over-fussy for small sets but for large sets we could have
3174  * tied up a nontrivial amount of memory.)
3175  */
3176  BipartiteMatchFree(state);
3177  pfree(results);
3178  pfree(chains);
3179  for (i = 1; i <= num_sets; ++i)
3180  if (adjacency[i])
3181  pfree(adjacency[i]);
3182  pfree(adjacency);
3183  pfree(adjacency_buf);
3184  pfree(orig_sets);
3185  for (i = 1; i <= num_sets; ++i)
3186  bms_free(set_masks[i]);
3187  pfree(set_masks);
3188 
3189  return result;
3190 }
#define NIL
Definition: pg_list.h:69
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
void BipartiteMatchFree(BipartiteMatchState *state)
#define list_make1(x1)
Definition: pg_list.h:133
void pfree(void *pointer)
Definition: mcxt.c:950
#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:878
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 NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:163
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
void * palloc(Size size)
Definition: mcxt.c:849
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 5774 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().

5775 {
5776  Path *best_path = rel->cheapest_total_path;
5777  ListCell *l;
5778 
5779  /* If all tuples will be retrieved, just return the cheapest-total path */
5780  if (tuple_fraction <= 0.0)
5781  return best_path;
5782 
5783  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5784  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5785  tuple_fraction /= best_path->rows;
5786 
5787  foreach(l, rel->pathlist)
5788  {
5789  Path *path = (Path *) lfirst(l);
5790 
5791  if (path == rel->cheapest_total_path ||
5792  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5793  continue;
5794 
5795  best_path = path;
5796  }
5797 
5798  return best_path;
5799 }
struct Path * cheapest_total_path
Definition: relation.h:512
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:107
List * pathlist
Definition: relation.h:508
Definition: relation.h:911
static double get_number_of_groups ( PlannerInfo root,
double  path_rows,
grouping_sets_data gd 
)
static

Definition at line 3348 of file planner.c.

References 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, list_length(), NULL, GroupingSetData::numGroups, RollupData::numGroups, parse(), PlannerInfo::parse, grouping_sets_data::rollups, Query::targetList, and grouping_sets_data::unsortable_sets.

Referenced by create_grouping_paths().

3351 {
3352  Query *parse = root->parse;
3353  double dNumGroups;
3354 
3355  if (parse->groupClause)
3356  {
3357  List *groupExprs;
3358 
3359  if (parse->groupingSets)
3360  {
3361  /* Add up the estimates for each grouping set */
3362  ListCell *lc;
3363  ListCell *lc2;
3364 
3365  dNumGroups = 0;
3366 
3367  foreach(lc, gd->rollups)
3368  {
3369  RollupData *rollup = lfirst(lc);
3370  ListCell *lc;
3371 
3372  groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
3373  parse->targetList);
3374 
3375  rollup->numGroups = 0.0;
3376 
3377  forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
3378  {
3379  List *gset = (List *) lfirst(lc);
3380  GroupingSetData *gs = lfirst(lc2);
3381  double numGroups = estimate_num_groups(root,
3382  groupExprs,
3383  path_rows,
3384  &gset);
3385 
3386  gs->numGroups = numGroups;
3387  rollup->numGroups += numGroups;
3388  }
3389 
3390  dNumGroups += rollup->numGroups;
3391  }
3392 
3393  if (gd->hash_sets_idx)
3394  {
3395  ListCell *lc;
3396 
3397  gd->dNumHashGroups = 0;
3398 
3399  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3400  parse->targetList);
3401 
3402  forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
3403  {
3404  List *gset = (List *) lfirst(lc);
3405  GroupingSetData *gs = lfirst(lc2);
3406  double numGroups = estimate_num_groups(root,
3407  groupExprs,
3408  path_rows,
3409  &gset);
3410 
3411  gs->numGroups = numGroups;
3412  gd->dNumHashGroups += numGroups;
3413  }
3414 
3415  dNumGroups += gd->dNumHashGroups;
3416  }
3417  }
3418  else
3419  {
3420  /* Plain GROUP BY */
3421  groupExprs = get_sortgrouplist_exprs(parse->groupClause,
3422  parse->targetList);
3423 
3424  dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
3425  NULL);
3426  }
3427  }
3428  else if (parse->groupingSets)
3429  {
3430  /* Empty grouping sets ... one result row for each one */
3431  dNumGroups = list_length(parse->groupingSets);
3432  }
3433  else if (parse->hasAggs || root->hasHavingQual)
3434  {
3435  /* Plain aggregation, one result row */
3436  dNumGroups = 1;
3437  }
3438  else
3439  {
3440  /* Not grouping */
3441  dNumGroups = 1;
3442  }
3443 
3444  return dNumGroups;
3445 }
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3277
Query * parse
Definition: relation.h:154
List * groupClause
Definition: relation.h:1434
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
bool hasAggs
Definition: parsenodes.h:116
List * hash_sets_idx
Definition: planner.c:102
List * groupingSets
Definition: parsenodes.h:139
double dNumHashGroups
Definition: planner.c:103
double numGroups
Definition: relation.h:1437
List * targetList
Definition: parsenodes.h:131
#define NULL
Definition: c.h:229
#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:137
double numGroups
Definition: relation.h:1428
bool hasHavingQual
Definition: relation.h:301
Definition: pg_list.h:45
List * gsets_data
Definition: relation.h:1436
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
List * gsets
Definition: relation.h:1435
List* get_partitioned_child_rels ( PlannerInfo root,
Index  rti 
)

Definition at line 6064 of file planner.c.

References Assert, PartitionedChildRelInfo::child_rels, lfirst, list_length(), NIL, PartitionedChildRelInfo::parent_relid, PlannerInfo::pcinfo_list, and result.

Referenced by add_paths_to_append_rel(), and inheritance_planner().

6065 {
6066  List *result = NIL;
6067  ListCell *l;
6068 
6069  foreach(l, root->pcinfo_list)
6070  {
6072 
6073  if (pc->parent_relid == rti)
6074  {
6075  result = pc->child_rels;
6076  break;
6077  }
6078  }
6079 
6080  /* The root partitioned table is included as a child rel */
6081  Assert(list_length(result) >= 1);
6082 
6083  return result;
6084 }
#define NIL
Definition: pg_list.h:69
return result
Definition: formatting.c:1618
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:253
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
static void grouping_planner ( PlannerInfo root,
bool  inheritance_update,
double  tuple_fraction 
)
static

Definition at line 1455 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, linitial_int, 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, NULL, 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().

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

Definition at line 1022 of file planner.c.

References add_path(), adjust_appendrel_attrs(), PlannerInfo::append_rel_list, Assert, bms_add_member(), bms_is_member(), 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, PlannerInfo::init_plans, IS_DUMMY_PATH, PlannerInfo::join_info_list, lappend(), lappend_int(), lfirst, list_concat(), list_copy_tail(), list_length(), makeNode, NIL, NULL, 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().

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

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

2291 {
2292  if (IsA(plan, Result))
2293  {
2294  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2295 
2296  if (list_length(rcqual) == 1)
2297  {
2298  Const *constqual = (Const *) linitial(rcqual);
2299 
2300  if (constqual && IsA(constqual, Const))
2301  {
2302  if (!constqual->constisnull &&
2303  !DatumGetBool(constqual->constvalue))
2304  return true;
2305  }
2306  }
2307  }
2308  return false;
2309 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define linitial(l)
Definition: pg_list.h:110
#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 2677 of file planner.c.

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

Referenced by grouping_planner().

2678 {
2679  Node *node;
2680 
2681  node = parse->limitCount;
2682  if (node)
2683  {
2684  if (IsA(node, Const))
2685  {
2686  /* NULL indicates LIMIT ALL, ie, no limit */
2687  if (!((Const *) node)->constisnull)
2688  return true; /* LIMIT with a constant value */
2689  }
2690  else
2691  return true; /* non-constant LIMIT */
2692  }
2693 
2694  node = parse->limitOffset;
2695  if (node)
2696  {
2697  if (IsA(node, Const))
2698  {
2699  /* Treat NULL as no offset; the executor would too */
2700  if (!((Const *) node)->constisnull)
2701  {
2702  int64 offset = DatumGetInt64(((Const *) node)->constvalue);
2703 
2704  if (offset != 0)
2705  return true; /* OFFSET with a nonzero value */
2706  }
2707  }
2708  else
2709  return true; /* non-constant OFFSET */
2710  }
2711 
2712  return false; /* don't need a Limit plan node */
2713 }
Node * limitOffset
Definition: parsenodes.h:149
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Definition: nodes.h:506
#define DatumGetInt64(X)
Definition: postgres.h:613
Node * limitCount
Definition: parsenodes.h:150
static PathTarget * make_group_input_target ( PlannerInfo root,
PathTarget final_target 
)
static

Definition at line 5035 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, NULL, parse(), PlannerInfo::parse, pull_var_clause(), PVC_INCLUDE_PLACEHOLDERS, PVC_RECURSE_AGGREGATES, PVC_RECURSE_WINDOWFUNCS, and set_pathtarget_cost_width().

Referenced by grouping_planner().

5036 {
5037  Query *parse = root->parse;
5038  PathTarget *input_target;
5039  List *non_group_cols;
5040  List *non_group_vars;
5041  int i;
5042  ListCell *lc;
5043 
5044  /*
5045  * We must build a target containing all grouping columns, plus any other
5046  * Vars mentioned in the query's targetlist and HAVING qual.
5047  */
5048  input_target = create_empty_pathtarget();
5049  non_group_cols = NIL;
5050 
5051  i = 0;
5052  foreach(lc, final_target->exprs)
5053  {
5054  Expr *expr = (Expr *) lfirst(lc);
5055  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5056 
5057  if (sgref && parse->groupClause &&
5059  {
5060  /*
5061  * It's a grouping column, so add it to the input target as-is.
5062  */
5063  add_column_to_pathtarget(input_target, expr, sgref);
5064  }
5065  else
5066  {
5067  /*
5068  * Non-grouping column, so just remember the expression for later
5069  * call to pull_var_clause.
5070  */
5071  non_group_cols = lappend(non_group_cols, expr);
5072  }
5073 
5074  i++;
5075  }
5076 
5077  /*
5078  * If there's a HAVING clause, we'll need the Vars it uses, too.
5079  */
5080  if (parse->havingQual)
5081  non_group_cols = lappend(non_group_cols, parse->havingQual);
5082 
5083  /*
5084  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5085  * add them to the input target if not already present. (A Var used
5086  * directly as a GROUP BY item will be present already.) Note this
5087  * includes Vars used in resjunk items, so we are covering the needs of
5088  * ORDER BY and window specifications. Vars used within Aggrefs and
5089  * WindowFuncs will be pulled out here, too.
5090  */
5091  non_group_vars = pull_var_clause((Node *) non_group_cols,
5095  add_new_columns_to_pathtarget(input_target, non_group_vars);
5096 
5097  /* clean up cruft */
5098  list_free(non_group_vars);
5099  list_free(non_group_cols);
5100 
5101  /* XXX this causes some redundant cost calculation ... */
5102  return set_pathtarget_cost_width(root, input_target);
5103 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:154
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:4896
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Definition: nodes.h:506
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:854
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:847
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:446
unsigned int Index
Definition: c.h:365
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * groupClause
Definition: parsenodes.h:137
void list_free(List *list)
Definition: list.c:1133
int i
Node * havingQual
Definition: parsenodes.h:141
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 5122 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, NULL, 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().

5123 {
5124  Query *parse = root->parse;
5125  PathTarget *partial_target;
5126  List *non_group_cols;
5127  List *non_group_exprs;
5128  int i;
5129  ListCell *lc;
5130 
5131  partial_target = create_empty_pathtarget();
5132  non_group_cols = NIL;
5133 
5134  i = 0;
5135  foreach(lc, grouping_target->exprs)
5136  {
5137  Expr *expr = (Expr *) lfirst(lc);
5138  Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
5139 
5140  if (sgref && parse->groupClause &&
5142  {
5143  /*
5144  * It's a grouping column, so add it to the partial_target as-is.
5145  * (This allows the upper agg step to repeat the grouping calcs.)
5146  */
5147  add_column_to_pathtarget(partial_target, expr, sgref);
5148  }
5149  else
5150  {
5151  /*
5152  * Non-grouping column, so just remember the expression for later
5153  * call to pull_var_clause.
5154  */
5155  non_group_cols = lappend(non_group_cols, expr);
5156  }
5157 
5158  i++;
5159  }
5160 
5161  /*
5162  * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
5163  */
5164  if (parse->havingQual)
5165  non_group_cols = lappend(non_group_cols, parse->havingQual);
5166 
5167  /*
5168  * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
5169  * non-group cols (plus HAVING), and add them to the partial_target if not
5170  * already present. (An expression used directly as a GROUP BY item will
5171  * be present already.) Note this includes Vars used in resjunk items, so
5172  * we are covering the needs of ORDER BY and window specifications.
5173  */
5174  non_group_exprs = pull_var_clause((Node *) non_group_cols,
5178 
5179  add_new_columns_to_pathtarget(partial_target, non_group_exprs);
5180 
5181  /*
5182  * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5183  * are at the top level of the target list, so we can just scan the list
5184  * rather than recursing through the expression trees.
5185  */
5186  foreach(lc, partial_target->exprs)
5187  {
5188  Aggref *aggref = (Aggref *) lfirst(lc);
5189 
5190  if (IsA(aggref, Aggref))
5191  {
5192  Aggref *newaggref;
5193 
5194  /*
5195  * We shouldn't need to copy the substructure of the Aggref node,
5196  * but flat-copy the node itself to avoid damaging other trees.
5197  */
5198  newaggref = makeNode(Aggref);
5199  memcpy(newaggref, aggref, sizeof(Aggref));
5200 
5201  /* For now, assume serialization is required */
5203 
5204  lfirst(lc) = newaggref;
5205  }
5206  }
5207 
5208  /* clean up cruft */
5209  list_free(non_group_exprs);
5210  list_free(non_group_cols);
5211 
5212  /* XXX this causes some redundant cost calculation ... */
5213  return set_pathtarget_cost_width(root, partial_target);
5214 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Query * parse
Definition: relation.h:154
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:4896
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:5223
Definition: nodes.h:506
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:854
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:847
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition: tlist.c:446
unsigned int Index
Definition: c.h:365
#define makeNode(_type_)
Definition: nodes.h:554
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * groupClause
Definition: parsenodes.h:137
void list_free(List *list)
Definition: list.c:1133
int i
Node * havingQual
Definition: parsenodes.h:141
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 5508 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().

5510 {
5511  List *window_pathkeys;
5512  List *window_sortclauses;
5513 
5514  /* Throw error if can't sort */
5516  ereport(ERROR,
5517  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5518  errmsg("could not implement window PARTITION BY"),
5519  errdetail("Window partitioning columns must be of sortable datatypes.")));
5521  ereport(ERROR,
5522  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5523  errmsg("could not implement window ORDER BY"),
5524  errdetail("Window ordering columns must be of sortable datatypes.")));
5525 
5526  /* Okay, make the combined pathkeys */
5527  window_sortclauses = list_concat(list_copy(wc->partitionClause),
5528  list_copy(wc->orderClause));
5529  window_pathkeys = make_pathkeys_for_sortclauses(root,
5530  window_sortclauses,
5531  tlist);
5532  list_free(window_sortclauses);
5533  return window_pathkeys;
5534 }
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:1234
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
List * orderClause
Definition: parsenodes.h:1235
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 5603 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().

5606 {
5607  Query *parse = root->parse;
5608  PathTarget *input_target;
5609  int ncols;
5610  bool *col_is_srf;
5611  bool *postpone_col;
5612  bool have_srf;
5613  bool have_volatile;
5614  bool have_expensive;
5615  bool have_srf_sortcols;
5616  bool postpone_srfs;
5617  List *postponable_cols;
5618  List *postponable_vars;
5619  int i;
5620  ListCell *lc;
5621 
5622  /* Shouldn't get here unless query has ORDER BY */
5623  Assert(parse->sortClause);
5624 
5625  *have_postponed_srfs = false; /* default result */
5626 
5627  /* Inspect tlist and collect per-column information */
5628  ncols = list_length(final_target->exprs);
5629  col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
5630  postpone_col = (bool *) palloc0(ncols * sizeof(bool));
5631  have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
5632 
5633  i = 0;
5634  foreach(lc, final_target->exprs)
5635  {
5636  Expr *expr = (Expr *) lfirst(lc);
5637 
5638  /*
5639  * If the column has a sortgroupref, assume it has to be evaluated
5640  * before sorting. Generally such columns would be ORDER BY, GROUP
5641  * BY, etc targets. One exception is columns that were removed from
5642  * GROUP BY by remove_useless_groupby_columns() ... but those would
5643  * only be Vars anyway. There don't seem to be any cases where it
5644  * would be worth the trouble to double-check.
5645  */
5646  if (get_pathtarget_sortgroupref(final_target, i) == 0)
5647  {
5648  /*
5649  * Check for SRF or volatile functions. Check the SRF case first
5650  * because we must know whether we have any postponed SRFs.
5651  */
5652  if (parse->hasTargetSRFs &&
5653  expression_returns_set((Node *) expr))
5654  {
5655  /* We'll decide below whether these are postponable */
5656  col_is_srf[i] = true;
5657  have_srf = true;
5658  }
5659  else if (contain_volatile_functions((Node *) expr))
5660  {
5661  /* Unconditionally postpone */
5662  postpone_col[i] = true;
5663  have_volatile = true;
5664  }
5665  else
5666  {
5667  /*
5668  * Else check the cost. XXX it's annoying to have to do this
5669  * when set_pathtarget_cost_width() just did it. Refactor to
5670  * allow sharing the work?
5671  */
5672  QualCost cost;
5673 
5674  cost_qual_eval_node(&cost, (Node *) expr, root);
5675 
5676  /*
5677  * We arbitrarily define "expensive" as "more than 10X
5678  * cpu_operator_cost". Note this will take in any PL function
5679  * with default cost.
5680  */
5681  if (cost.per_tuple > 10 * cpu_operator_cost)
5682  {
5683  postpone_col[i] = true;
5684  have_expensive = true;
5685  }
5686  }
5687  }
5688  else
5689  {
5690  /* For sortgroupref cols, just check if any contain SRFs */
5691  if (!have_srf_sortcols &&
5692  parse->hasTargetSRFs &&
5693  expression_returns_set((Node *) expr))
5694  have_srf_sortcols = true;
5695  }
5696 
5697  i++;
5698  }
5699 
5700  /*
5701  * We can postpone SRFs if we have some but none are in sortgroupref cols.
5702  */
5703  postpone_srfs = (have_srf && !have_srf_sortcols);
5704 
5705  /*
5706  * If we don't need a post-sort projection, just return final_target.
5707  */
5708  if (!(postpone_srfs || have_volatile ||
5709  (have_expensive &&
5710  (parse->limitCount || root->tuple_fraction > 0))))
5711  return final_target;
5712 
5713  /*
5714  * Report whether the post-sort projection will contain set-returning
5715  * functions. This is important because it affects whether the Sort can
5716  * rely on the query's LIMIT (if any) to bound the number of rows it needs
5717  * to return.
5718  */
5719  *have_postponed_srfs = postpone_srfs;
5720 
5721  /*
5722  * Construct the sort-input target, taking all non-postponable columns and
5723  * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
5724  * the postponable ones.
5725  */
5726  input_target = create_empty_pathtarget();
5727  postponable_cols = NIL;
5728 
5729  i = 0;
5730  foreach(lc, final_target->exprs)
5731  {
5732  Expr *expr = (Expr *) lfirst(lc);
5733 
5734  if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
5735  postponable_cols = lappend(postponable_cols, expr);
5736  else
5737  add_column_to_pathtarget(input_target, expr,
5738  get_pathtarget_sortgroupref(final_target, i));
5739 
5740  i++;
5741  }
5742 
5743  /*
5744  * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
5745  * postponable columns, and add them to the sort-input target if not
5746  * already present. (Some might be there already.) We mustn't
5747  * deconstruct Aggrefs or WindowFuncs here, since the projection node
5748  * would be unable to recompute them.
5749  */
5750  postponable_vars = pull_var_clause((Node *) postponable_cols,
5754  add_new_columns_to_pathtarget(input_target, postponable_vars);
5755 
5756  /* clean up cruft */
5757  list_free(postponable_vars);
5758  list_free(postponable_cols);
5759 
5760  /* XXX this represents even more redundant cost calculation ... */
5761  return set_pathtarget_cost_width(root, input_target);
5762 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3390
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:154
List * sortClause
Definition: parsenodes.h:147
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:4896
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:667
Definition: nodes.h:506
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:950
#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:290
Node * limitCount
Definition: parsenodes.h:150
double cpu_operator_cost
Definition: costsize.c:108
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:854
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:847
void * palloc0(Size size)
Definition: mcxt.c:878
#define PVC_INCLUDE_WINDOWFUNCS
Definition: var.h:22
bool hasTargetSRFs
Definition: parsenodes.h:118
#define Assert(condition)
Definition: c.h:675
#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 5388 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, list_free(), NIL, NULL, 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().

5391 {
5392  Query *parse = root->parse;
5393  PathTarget *input_target;
5394  Bitmapset *sgrefs;
5395  List *flattenable_cols;
5396  List *flattenable_vars;
5397  int i;
5398  ListCell *lc;
5399 
5400  Assert(parse->hasWindowFuncs);
5401 
5402  /*
5403  * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
5404  * into a bitmapset for convenient reference below.
5405  */
5406  sgrefs = NULL;
5407  foreach(lc, activeWindows)
5408  {
5409  WindowClause *wc = (WindowClause *) lfirst(lc);
5410  ListCell *lc2;
5411 
5412  foreach(lc2, wc->partitionClause)
5413  {
5414  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);
5415 
5416  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5417  }
5418  foreach(lc2, wc->orderClause)
5419  {
5420  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);
5421 
5422  sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
5423  }
5424  }
5425 
5426  /* Add in sortgroupref numbers of GROUP BY clauses, too */
5427  foreach(lc, parse->groupClause)
5428  {
5429  SortGroupClause *grpcl = (SortGroupClause *) lfirst(lc);
5430 
5431  sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
5432  }
5433 
5434  /*
5435  * Construct a target containing all the non-flattenable targetlist items,
5436  * and save aside the others for a moment.
5437  */
5438  input_target = create_empty_pathtarget();
5439  flattenable_cols = NIL;
5440 
5441  i = 0;
5442  foreach(lc, final_target->exprs)
5443  {
5444  Expr *expr = (Expr *) lfirst(lc);
5445  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5446 
5447  /*
5448  * Don't want to deconstruct window clauses or GROUP BY items. (Note
5449  * that such items can't contain window functions, so it's okay to
5450  * compute them below the WindowAgg nodes.)
5451  */
5452  if (sgref != 0 && bms_is_member(sgref, sgrefs))
5453  {
5454  /*
5455  * Don't want to deconstruct this value, so add it to the input
5456  * target as-is.
5457  */
5458  add_column_to_pathtarget(input_target, expr, sgref);
5459  }
5460  else
5461  {
5462  /*
5463  * Column is to be flattened, so just remember the expression for
5464  * later call to pull_var_clause.
5465  */
5466  flattenable_cols = lappend(flattenable_cols, expr);
5467  }
5468 
5469  i++;
5470  }
5471 
5472  /*
5473  * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
5474  * add them to the input target if not already present. (Some might be
5475  * there already because they're used directly as window/group clauses.)
5476  *
5477  * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
5478  * Aggrefs are placed in the Agg node's tlist and not left to be computed
5479  * at higher levels. On the other hand, we should recurse into
5480  * WindowFuncs to make sure their input expressions are available.
5481  */
5482  flattenable_vars = pull_var_clause((Node *) flattenable_cols,
5486  add_new_columns_to_pathtarget(input_target, flattenable_vars);
5487 
5488  /* clean up cruft */
5489  list_free(flattenable_vars);
5490  list_free(flattenable_cols);
5491 
5492  /* XXX this causes some redundant cost calculation ... */
5493  return set_pathtarget_cost_width(root, input_target);
5494 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:154
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:4896
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Index tleSortGroupRef
Definition: parsenodes.h:1141
Definition: nodes.h:506
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:1234
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:854
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:847
unsigned int Index
Definition: c.h:365
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:117
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
List * orderClause
Definition: parsenodes.h:1235
List * groupClause
Definition: parsenodes.h:137
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 5223 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().

5224 {
5225  /* aggtranstype should be computed by this point */
5227  /* ... but aggsplit should still be as the parser left it */
5228  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5229 
5230  /* Mark the Aggref with the intended partial-aggregation mode */
5231  agg->aggsplit = aggsplit;
5232 
5233  /*
5234  * Adjust result type if needed. Normally, a partial aggregate returns
5235  * the aggregate's transition type; but if that's INTERNAL and we're
5236  * serializing, it returns BYTEA instead.
5237  */
5238  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5239  {
5240  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5241  agg->aggtype = BYTEAOID;
5242  else
5243  agg->aggtype = agg->aggtranstype;
5244  }
5245 }
#define OidIsValid(objectId)
Definition: c.h:538
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:760
#define INTERNALOID
Definition: pg_type.h:694
#define Assert(condition)
Definition: c.h:675
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:759
#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 5956 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, list_make1, maintenance_work_mem, makeNode, NIL, NULL, RelOptInfo::pages, PlannerInfo::parse, IndexPath::path, QualCost::per_tuple, PlannerInfo::planner_cxt, PlannerInfo::query_level, RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_RELATION, RELOPT_BASEREL, 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().

5957 {
5958  PlannerInfo *root;
5959  Query *query;
5960  PlannerGlobal *glob;
5961  RangeTblEntry *rte;
5962  RelOptInfo *rel;
5963  IndexOptInfo *indexInfo;
5964  QualCost indexExprCost;
5965  Cost comparisonCost;
5966  Path *seqScanPath;
5967  Path seqScanAndSortPath;
5968  IndexPath *indexScanPath;
5969  ListCell *lc;
5970 
5971  /* We can short-circuit the cost comparison if indexscans are disabled */
5972  if (!enable_indexscan)
5973  return true; /* use sort */
5974 
5975  /* Set up mostly-dummy planner state */
5976  query = makeNode(Query);
5977  query->commandType = CMD_SELECT;
5978 
5979  glob = makeNode(PlannerGlobal);
5980 
5981  root = makeNode(PlannerInfo);
5982  root->parse = query;
5983  root->glob = glob;
5984  root->query_level = 1;
5986  root->wt_param_id = -1;
5987 
5988  /* Build a minimal RTE for the rel */
5989  rte = makeNode(RangeTblEntry);
5990  rte->rtekind = RTE_RELATION;
5991  rte->relid = tableOid;
5992  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
5993  rte->lateral = false;
5994  rte->inh = false;
5995  rte->inFromCl = true;
5996  query->rtable = list_make1(rte);
5997 
5998  /* Set up RTE/RelOptInfo arrays */
6000 
6001  /* Build RelOptInfo */
6002  rel = build_simple_rel(root, 1, RELOPT_BASEREL);
6003 
6004  /* Locate IndexOptInfo for the target index */
6005  indexInfo = NULL;
6006  foreach(lc, rel->indexlist)
6007  {
6008  indexInfo = (IndexOptInfo *) lfirst(lc);
6009  if (indexInfo->indexoid == indexOid)
6010  break;
6011  }
6012 
6013  /*
6014  * It's possible that get_relation_info did not generate an IndexOptInfo
6015  * for the desired index; this could happen if it's not yet reached its
6016  * indcheckxmin usability horizon, or if it's a system index and we're
6017  * ignoring system indexes. In such cases we should tell CLUSTER to not
6018  * trust the index contents but use seqscan-and-sort.
6019  */
6020  if (lc == NULL) /* not in the list? */
6021  return true; /* use sort */
6022 
6023  /*
6024  * Rather than doing all the pushups that would be needed to use
6025  * set_baserel_size_estimates, just do a quick hack for rows and width.
6026  */
6027  rel->rows = rel->tuples;
6028  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6029 
6030  root->total_table_pages = rel->pages;
6031 
6032  /*
6033  * Determine eval cost of the index expressions, if any. We need to
6034  * charge twice that amount for each tuple comparison that happens during
6035  * the sort, since tuplesort.c will have to re-evaluate the index
6036  * expressions each time. (XXX that's pretty inefficient...)
6037  */
6038  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6039  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6040 
6041  /* Estimate the cost of seq scan + sort */
6042  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6043  cost_sort(&seqScanAndSortPath, root, NIL,
6044  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6045  comparisonCost, maintenance_work_mem, -1.0);
6046 
6047  /* Estimate the cost of index scan */
6048  indexScanPath = create_index_path(root, indexInfo,
6049  NIL, NIL, NIL, NIL, NIL,
6050  ForwardScanDirection, false,
6051  NULL, 1.0, false);
6052 
6053  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6054 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:154
Path path
Definition: relation.h:994
double tuples
Definition: relation.h:534
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:133
Cost per_tuple
Definition: relation.h:46
int wt_param_id
Definition: relation.h:307
List * rtable
Definition: parsenodes.h:128
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3364
PlannerGlobal * glob
Definition: relation.h:156
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
double total_table_pages
Definition: relation.h:288
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1109
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:1607
List * indexlist
Definition: relation.h:531
double rows
Definition: relation.h:497
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
Definition: relnode.c:91
int maintenance_work_mem
Definition: globals.c:113
Cost total_cost
Definition: relation.h:930
CmdType commandType
Definition: parsenodes.h:103
#define makeNode(_type_)
Definition: nodes.h:554
BlockNumber pages
Definition: relation.h:533
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:62
Index query_level
Definition: relation.h:158
RTEKind rtekind
Definition: parsenodes.h:916
int width
Definition: relation.h:850
MemoryContext planner_cxt
Definition: relation.h:286
Oid indexoid
Definition: relation.h:593
#define RELKIND_RELATION
Definition: pg_class.h:160
struct PathTarget * reltarget
Definition: relation.h:505
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
Definition: relation.h:911
double Cost
Definition: nodes.h:630
List * indexprs
Definition: relation.h:615
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:1618
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 5258 of file planner.c.

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

Referenced by grouping_planner().

5259 {
5260  ListCell *l;
5261  ListCell *orig_tlist_item = list_head(orig_tlist);
5262 
5263  foreach(l, new_tlist)
5264  {
5265  TargetEntry *new_tle = (TargetEntry *) lfirst(l);
5266  TargetEntry *orig_tle;
5267 
5268  /* ignore resjunk columns in setop result */
5269  if (new_tle->resjunk)
5270  continue;
5271 
5272  Assert(orig_tlist_item != NULL);
5273  orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
5274  orig_tlist_item = lnext(orig_tlist_item);
5275  if (orig_tle->resjunk) /* should not happen */
5276  elog(ERROR, "resjunk output columns are not implemented");
5277  Assert(new_tle->resno == orig_tle->resno);
5278  new_tle->ressortgroupref = orig_tle->ressortgroupref;
5279  }
5280  if (orig_tlist_item != NULL)
5281  elog(ERROR, "resjunk output columns are not implemented");
5282  return new_tlist;
5283 }
bool resjunk
Definition: primnodes.h:1359
#define ERROR
Definition: elog.h:43
AttrNumber resno
Definition: primnodes.h:1353
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1355
#define elog
Definition: elog.h:219