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 5821 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().

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

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

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

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

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

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

Referenced by create_window_paths().

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

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

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

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

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

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

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

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

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

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

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

Definition at line 3350 of file planner.c.

References Assert, grouping_sets_data::dNumHashGroups, estimate_num_groups(), forboth, get_sortgrouplist_exprs(), Query::groupClause, RollupData::groupClause, Query::groupingSets, RollupData::gsets, RollupData::gsets_data, Query::hasAggs, grouping_sets_data::hash_sets_idx, PlannerInfo::hasHavingQual, lfirst, 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().

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

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

6069 {
6070  List *result = NIL;
6071  ListCell *l;
6072 
6073  foreach(l, root->pcinfo_list)
6074  {
6076 
6077  if (pc->parent_relid == rti)
6078  {
6079  result = pc->child_rels;
6080  break;
6081  }
6082  }
6083 
6084  /* The root partitioned table is included as a child rel */
6085  Assert(list_length(result) >= 1);
6086 
6087  return result;
6088 }
#define NIL
Definition: pg_list.h:69
return result
Definition: formatting.c:1632
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:254
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 1457 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().

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

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

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

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

2293 {
2294  if (IsA(plan, Result))
2295  {
2296  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2297 
2298  if (list_length(rcqual) == 1)
2299  {
2300  Const *constqual = (Const *) linitial(rcqual);
2301 
2302  if (constqual && IsA(constqual, Const))
2303  {
2304  if (!constqual->constisnull &&
2305  !DatumGetBool(constqual->constvalue))
2306  return true;
2307  }
2308  }
2309  }
2310  return false;
2311 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define linitial(l)
Definition: pg_list.h:111
#define DatumGetBool(X)
Definition: postgres.h:399
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
bool constisnull
Definition: primnodes.h:197
static bool limit_needed ( Query parse)
static

Definition at line 2679 of file planner.c.

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

Referenced by grouping_planner().

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

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

5040 {
5041  Query *parse = root->parse;
5042  PathTarget *input_target;
5043  List *non_group_cols;
5044  List *non_group_vars;
5045  int i;
5046  ListCell *lc;
5047 
5048  /*
5049  * We must build a target containing all grouping columns, plus any other
5050  * Vars mentioned in the query's targetlist and HAVING qual.
5051  */
5052  input_target = create_empty_pathtarget();
5053  non_group_cols = NIL;
5054 
5055  i = 0;
5056  foreach(lc, final_target->exprs)
5057  {
5058  Expr *expr = (Expr *) lfirst(lc);
5059  Index sgref = get_pathtarget_sortgroupref(final_target, i);
5060 
5061  if (sgref && parse->groupClause &&
5063  {
5064  /*
5065  * It's a grouping column, so add it to the input target as-is.
5066  */
5067  add_column_to_pathtarget(input_target, expr, sgref);
5068  }
5069  else
5070  {
5071  /*
5072  * Non-grouping column, so just remember the expression for later
5073  * call to pull_var_clause.
5074  */
5075  non_group_cols = lappend(non_group_cols, expr);
5076  }
5077 
5078  i++;
5079  }
5080 
5081  /*
5082  * If there's a HAVING clause, we'll need the Vars it uses, too.
5083  */
5084  if (parse->havingQual)
5085  non_group_cols = lappend(non_group_cols, parse->havingQual);
5086 
5087  /*
5088  * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5089  * add them to the input target if not already present. (A Var used
5090  * directly as a GROUP BY item will be present already.) Note this
5091  * includes Vars used in resjunk items, so we are covering the needs of
5092  * ORDER BY and window specifications. Vars used within Aggrefs and
5093  * WindowFuncs will be pulled out here, too.
5094  */
5095  non_group_vars = pull_var_clause((Node *) non_group_cols,
5099  add_new_columns_to_pathtarget(input_target, non_group_vars);
5100 
5101  /* clean up cruft */
5102  list_free(non_group_vars);
5103  list_free(non_group_cols);
5104 
5105  /* XXX this causes some redundant cost calculation ... */
5106  return set_pathtarget_cost_width(root, input_target);
5107 }
PathTarget * create_empty_pathtarget(void)
Definition: tlist.c:653
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition: costsize.c:4992
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition: tlist.c:667
Definition: nodes.h:509
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
#define get_pathtarget_sortgroupref(target, colno)
Definition: relation.h:890
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:883
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:146
void list_free(List *list)
Definition: list.c:1133
int i
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition: tlist.c:714
static PathTarget * make_partial_grouping_target ( PlannerInfo root,
PathTarget grouping_target 
)
static

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

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

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

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

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

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

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

5228 {
5229  /* aggtranstype should be computed by this point */
5231  /* ... but aggsplit should still be as the parser left it */
5232  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5233 
5234  /* Mark the Aggref with the intended partial-aggregation mode */
5235  agg->aggsplit = aggsplit;
5236 
5237  /*
5238  * Adjust result type if needed. Normally, a partial aggregate returns
5239  * the aggregate's transition type; but if that's INTERNAL and we're
5240  * serializing, it returns BYTEA instead.
5241  */
5242  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5243  {
5244  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5245  agg->aggtype = BYTEAOID;
5246  else
5247  agg->aggtype = agg->aggtranstype;
5248  }
5249 }
#define OidIsValid(objectId)
Definition: c.h:538
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:769
#define INTERNALOID
Definition: pg_type.h:698
#define Assert(condition)
Definition: c.h:675
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:768
#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 5960 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, 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().

5961 {
5962  PlannerInfo *root;
5963  Query *query;
5964  PlannerGlobal *glob;
5965  RangeTblEntry *rte;
5966  RelOptInfo *rel;
5967  IndexOptInfo *indexInfo;
5968  QualCost indexExprCost;
5969  Cost comparisonCost;
5970  Path *seqScanPath;
5971  Path seqScanAndSortPath;
5972  IndexPath *indexScanPath;
5973  ListCell *lc;
5974 
5975  /* We can short-circuit the cost comparison if indexscans are disabled */
5976  if (!enable_indexscan)
5977  return true; /* use sort */
5978 
5979  /* Set up mostly-dummy planner state */
5980  query = makeNode(Query);
5981  query->commandType = CMD_SELECT;
5982 
5983  glob = makeNode(PlannerGlobal);
5984 
5985  root = makeNode(PlannerInfo);
5986  root->parse = query;
5987  root->glob = glob;
5988  root->query_level = 1;
5990  root->wt_param_id = -1;
5991 
5992  /* Build a minimal RTE for the rel */
5993  rte = makeNode(RangeTblEntry);
5994  rte->rtekind = RTE_RELATION;
5995  rte->relid = tableOid;
5996  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
5997  rte->lateral = false;
5998  rte->inh = false;
5999  rte->inFromCl = true;
6000  query->rtable = list_make1(rte);
6001 
6002  /* Set up RTE/RelOptInfo arrays */
6004 
6005  /* Build RelOptInfo */
6006  rel = build_simple_rel(root, 1, NULL);
6007 
6008  /* Locate IndexOptInfo for the target index */
6009  indexInfo = NULL;
6010  foreach(lc, rel->indexlist)
6011  {
6012  indexInfo = (IndexOptInfo *) lfirst(lc);
6013  if (indexInfo->indexoid == indexOid)
6014  break;
6015  }
6016 
6017  /*
6018  * It's possible that get_relation_info did not generate an IndexOptInfo
6019  * for the desired index; this could happen if it's not yet reached its
6020  * indcheckxmin usability horizon, or if it's a system index and we're
6021  * ignoring system indexes. In such cases we should tell CLUSTER to not
6022  * trust the index contents but use seqscan-and-sort.
6023  */
6024  if (lc == NULL) /* not in the list? */
6025  return true; /* use sort */
6026 
6027  /*
6028  * Rather than doing all the pushups that would be needed to use
6029  * set_baserel_size_estimates, just do a quick hack for rows and width.
6030  */
6031  rel->rows = rel->tuples;
6032  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6033 
6034  root->total_table_pages = rel->pages;
6035 
6036  /*
6037  * Determine eval cost of the index expressions, if any. We need to
6038  * charge twice that amount for each tuple comparison that happens during
6039  * the sort, since tuplesort.c will have to re-evaluate the index
6040  * expressions each time. (XXX that's pretty inefficient...)
6041  */
6042  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6043  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6044 
6045  /* Estimate the cost of seq scan + sort */
6046  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6047  cost_sort(&seqScanAndSortPath, root, NIL,
6048  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6049  comparisonCost, maintenance_work_mem, -1.0);
6050 
6051  /* Estimate the cost of index scan */
6052  indexScanPath = create_index_path(root, indexInfo,
6053  NIL, NIL, NIL, NIL, NIL,
6054  ForwardScanDirection, false,
6055  NULL, 1.0, false);
6056 
6057  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6058 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
Path path
Definition: relation.h:1030
double tuples
Definition: relation.h:565
IndexPath * create_index_path(PlannerInfo *root, IndexOptInfo *index, List *indexclauses, List *indexclausecols, List *indexorderbys, List *indexorderbycols, List *pathkeys, ScanDirection indexscandir, bool indexonly, Relids required_outer, double loop_count, bool partial_path)
Definition: pathnode.c:1008
Cost startup
Definition: relation.h:45
#define list_make1(x1)
Definition: pg_list.h:139
Cost per_tuple
Definition: relation.h:46
int wt_param_id
Definition: relation.h:308
List * rtable
Definition: parsenodes.h:135
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3428
PlannerGlobal * glob
Definition: relation.h:157
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
double total_table_pages
Definition: relation.h:289
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1110
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1644
List * indexlist
Definition: relation.h:562
double rows
Definition: relation.h:528
int maintenance_work_mem
Definition: globals.c:113
Cost total_cost
Definition: relation.h:966
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
BlockNumber pages
Definition: relation.h:564
#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:159
RTEKind rtekind
Definition: parsenodes.h:929
int width
Definition: relation.h:886
MemoryContext planner_cxt
Definition: relation.h:287
Oid indexoid
Definition: relation.h:631
#define RELKIND_RELATION
Definition: pg_class.h:160
struct PathTarget * reltarget
Definition: relation.h:536
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:947
double Cost
Definition: nodes.h:639
List * indexprs
Definition: relation.h:653
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:1632
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 5262 of file planner.c.

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

Referenced by grouping_planner().

5263 {
5264  ListCell *l;
5265  ListCell *orig_tlist_item = list_head(orig_tlist);
5266 
5267  foreach(l, new_tlist)
5268  {
5269  TargetEntry *new_tle = (TargetEntry *) lfirst(l);
5270  TargetEntry *orig_tle;
5271 
5272  /* ignore resjunk columns in setop result */
5273  if (new_tle->resjunk)
5274  continue;
5275 
5276  Assert(orig_tlist_item != NULL);
5277  orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
5278  orig_tlist_item = lnext(orig_tlist_item);
5279  if (orig_tle->resjunk) /* should not happen */
5280  elog(ERROR, "resjunk output columns are not implemented");
5281  Assert(new_tle->resno == orig_tle->resno);
5282  new_tle->ressortgroupref = orig_tle->ressortgroupref;
5283  }
5284  if (orig_tlist_item != NULL)
5285  elog(ERROR, "resjunk output columns are not implemented");
5286  return new_tlist;
5287 }
bool resjunk
Definition: primnodes.h:1374
#define ERROR
Definition: elog.h:43
AttrNumber resno
Definition: primnodes.h:1368
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:1370
#define elog
Definition: elog.h:219