PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
planagg.c File Reference
Include dependency graph for planagg.c:

Go to the source code of this file.

Functions

static bool find_minmax_aggs_walker (Node *node, List **context)
 
static bool build_minmax_path (PlannerInfo *root, MinMaxAggInfo *mminfo, Oid eqop, Oid sortop, bool nulls_first)
 
static void minmax_qp_callback (PlannerInfo *root, void *extra)
 
static Oid fetch_agg_sort_op (Oid aggfnoid)
 
void preprocess_minmax_aggregates (PlannerInfo *root, List *tlist)
 

Function Documentation

static bool build_minmax_path ( PlannerInfo root,
MinMaxAggInfo mminfo,
Oid  eqop,
Oid  sortop,
bool  nulls_first 
)
static

Definition at line 342 of file planagg.c.

References PlannerInfo::append_rel_list, apply_projection_to_path(), NullTest::arg, NullTest::argisrow, Assert, assignSortGroupRef(), copyObject(), create_pathtarget, Query::distinctClause, PlannerInfo::eq_classes, SortGroupClause::eqop, get_cheapest_fractional_path_for_pathkeys(), Query::hasAggs, Query::hasDistinctOn, SortGroupClause::hashable, PlannerInfo::hasHavingQual, Query::havingQual, IncrementVarSublevelsUp(), PlannerInfo::init_plans, Int64GetDatum(), INT8OID, InvalidOid, IS_NOT_NULL, PlannerInfo::join_info_list, Query::jointree, lcons(), PlannerInfo::limit_tuples, Query::limitCount, Query::limitOffset, list_make1, list_member(), NullTest::location, makeConst(), makeNode, makeTargetEntry(), minmax_qp_callback(), NIL, NULL, SortGroupClause::nulls_first, NullTest::nulltesttype, PlannerInfo::outer_params, palloc(), PlannerInfo::parent_root, parse(), PlannerInfo::parse, MinMaxAggInfo::path, MinMaxAggInfo::pathcost, RelOptInfo::pathlist, PlannerInfo::placeholder_list, PlannerInfo::plan_params, PlannerInfo::processed_tlist, pstrdup(), FromExpr::quals, PlannerInfo::query_level, PlannerInfo::query_pathkeys, query_planner(), RelOptInfo::rows, Query::sortClause, SortGroupClause::sortop, SS_charge_for_initplans(), SS_identify_outer_params(), Path::startup_cost, MinMaxAggInfo::subroot, MinMaxAggInfo::target, Query::targetList, SortGroupClause::tleSortGroupRef, Path::total_cost, and PlannerInfo::tuple_fraction.

Referenced by preprocess_minmax_aggregates().

344 {
345  PlannerInfo *subroot;
346  Query *parse;
347  TargetEntry *tle;
348  List *tlist;
349  NullTest *ntest;
350  SortGroupClause *sortcl;
351  RelOptInfo *final_rel;
352  Path *sorted_path;
353  Cost path_cost;
354  double path_fraction;
355 
356  /*
357  * We are going to construct what is effectively a sub-SELECT query, so
358  * clone the current query level's state and adjust it to make it look
359  * like a subquery. Any outer references will now be one level higher
360  * than before. (This means that when we are done, there will be no Vars
361  * of level 1, which is why the subquery can become an initplan.)
362  */
363  subroot = (PlannerInfo *) palloc(sizeof(PlannerInfo));
364  memcpy(subroot, root, sizeof(PlannerInfo));
365  subroot->query_level++;
366  subroot->parent_root = root;
367  /* reset subplan-related stuff */
368  subroot->plan_params = NIL;
369  subroot->outer_params = NULL;
370  subroot->init_plans = NIL;
371 
372  subroot->parse = parse = (Query *) copyObject(root->parse);
373  IncrementVarSublevelsUp((Node *) parse, 1, 1);
374 
375  /* append_rel_list might contain outer Vars? */
376  subroot->append_rel_list = (List *) copyObject(root->append_rel_list);
377  IncrementVarSublevelsUp((Node *) subroot->append_rel_list, 1, 1);
378  /* There shouldn't be any OJ info to translate, as yet */
379  Assert(subroot->join_info_list == NIL);
380  /* and we haven't made equivalence classes, either */
381  Assert(subroot->eq_classes == NIL);
382  /* and we haven't created PlaceHolderInfos, either */
383  Assert(subroot->placeholder_list == NIL);
384 
385  /*----------
386  * Generate modified query of the form
387  * (SELECT col FROM tab
388  * WHERE col IS NOT NULL AND existing-quals
389  * ORDER BY col ASC/DESC
390  * LIMIT 1)
391  *----------
392  */
393  /* single tlist entry that is the aggregate target */
394  tle = makeTargetEntry(copyObject(mminfo->target),
395  (AttrNumber) 1,
396  pstrdup("agg_target"),
397  false);
398  tlist = list_make1(tle);
399  subroot->processed_tlist = parse->targetList = tlist;
400 
401  /* No HAVING, no DISTINCT, no aggregates anymore */
402  parse->havingQual = NULL;
403  subroot->hasHavingQual = false;
404  parse->distinctClause = NIL;
405  parse->hasDistinctOn = false;
406  parse->hasAggs = false;
407 
408  /* Build "target IS NOT NULL" expression */
409  ntest = makeNode(NullTest);
410  ntest->nulltesttype = IS_NOT_NULL;
411  ntest->arg = copyObject(mminfo->target);
412  /* we checked it wasn't a rowtype in find_minmax_aggs_walker */
413  ntest->argisrow = false;
414  ntest->location = -1;
415 
416  /* User might have had that in WHERE already */
417  if (!list_member((List *) parse->jointree->quals, ntest))
418  parse->jointree->quals = (Node *)
419  lcons(ntest, (List *) parse->jointree->quals);
420 
421  /* Build suitable ORDER BY clause */
422  sortcl = makeNode(SortGroupClause);
423  sortcl->tleSortGroupRef = assignSortGroupRef(tle, tlist);
424  sortcl->eqop = eqop;
425  sortcl->sortop = sortop;
426  sortcl->nulls_first = nulls_first;
427  sortcl->hashable = false; /* no need to make this accurate */
428  parse->sortClause = list_make1(sortcl);
429 
430  /* set up expressions for LIMIT 1 */
431  parse->limitOffset = NULL;
432  parse->limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
433  sizeof(int64),
434  Int64GetDatum(1), false,
435  FLOAT8PASSBYVAL);
436 
437  /*
438  * Generate the best paths for this query, telling query_planner that we
439  * have LIMIT 1.
440  */
441  subroot->tuple_fraction = 1.0;
442  subroot->limit_tuples = 1.0;
443 
444  final_rel = query_planner(subroot, tlist, minmax_qp_callback, NULL);
445 
446  /*
447  * Since we didn't go through subquery_planner() to handle the subquery,
448  * we have to do some of the same cleanup it would do, in particular cope
449  * with params and initplans used within this subquery. (This won't
450  * matter if we end up not using the subplan.)
451  */
452  SS_identify_outer_params(subroot);
453  SS_charge_for_initplans(subroot, final_rel);
454 
455  /*
456  * Get the best presorted path, that being the one that's cheapest for
457  * fetching just one row. If there's no such path, fail.
458  */
459  if (final_rel->rows > 1.0)
460  path_fraction = 1.0 / final_rel->rows;
461  else
462  path_fraction = 1.0;
463 
464  sorted_path =
466  subroot->query_pathkeys,
467  NULL,
468  path_fraction);
469  if (!sorted_path)
470  return false;
471 
472  /*
473  * The path might not return exactly what we want, so fix that. (We
474  * assume that this won't change any conclusions about which was the
475  * cheapest path.)
476  */
477  sorted_path = apply_projection_to_path(subroot, final_rel, sorted_path,
478  create_pathtarget(subroot, tlist));
479 
480  /*
481  * Determine cost to get just the first row of the presorted path.
482  *
483  * Note: cost calculation here should match
484  * compare_fractional_path_costs().
485  */
486  path_cost = sorted_path->startup_cost +
487  path_fraction * (sorted_path->total_cost - sorted_path->startup_cost);
488 
489  /* Save state for further processing */
490  mminfo->subroot = subroot;
491  mminfo->path = sorted_path;
492  mminfo->pathcost = path_cost;
493 
494  return true;
495 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2253
Node * limitOffset
Definition: parsenodes.h:149
#define NIL
Definition: pg_list.h:69
static void minmax_qp_callback(PlannerInfo *root, void *extra)
Definition: planagg.c:501
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
Query * parse
Definition: relation.h:152
List * plan_params
Definition: relation.h:166
List * sortClause
Definition: parsenodes.h:147
List * query_pathkeys
Definition: relation.h:257
List * join_info_list
Definition: relation.h:247
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:773
FromExpr * jointree
Definition: parsenodes.h:129
RelOptInfo * query_planner(PlannerInfo *root, List *tlist, query_pathkeys_callback qp_callback, void *qp_extra)
Definition: planmain.c:54
char * pstrdup(const char *in)
Definition: mcxt.c:1165
bool hasAggs
Definition: parsenodes.h:116
void SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
Definition: subselect.c:2153
Index tleSortGroupRef
Definition: parsenodes.h:1102
Definition: nodes.h:508
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:296
Node * quals
Definition: primnodes.h:1434
bool hasDistinctOn
Definition: parsenodes.h:120
List * targetList
Definition: parsenodes.h:131
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
#define list_make1(x1)
Definition: pg_list.h:133
double tuple_fraction
Definition: relation.h:286
List * distinctClause
Definition: parsenodes.h:145
Path * path
Definition: relation.h:1954
bool list_member(const List *list, const void *datum)
Definition: list.c:444
double limit_tuples
Definition: relation.h:287
Cost startup_cost
Definition: relation.h:906
Expr * arg
Definition: primnodes.h:1156
Node * limitCount
Definition: parsenodes.h:150
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition: pathkeys.c:383
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:2102
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
struct PlannerInfo * parent_root
Definition: relation.h:158
List * append_rel_list
Definition: relation.h:249
NullTestType nulltesttype
Definition: primnodes.h:1157
List * init_plans
Definition: relation.h:225
double rows
Definition: relation.h:493
#define InvalidOid
Definition: postgres_ext.h:36
Cost total_cost
Definition: relation.h:907
#define INT8OID
Definition: pg_type.h:304
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
Expr * target
Definition: relation.h:1952
void SS_identify_outer_params(PlannerInfo *root)
Definition: subselect.c:2091
List * eq_classes
Definition: relation.h:232
Bitmapset * outer_params
Definition: relation.h:167
int location
Definition: primnodes.h:1159
Index query_level
Definition: relation.h:156
void * palloc(Size size)
Definition: mcxt.c:891
List * placeholder_list
Definition: relation.h:253
bool hasHavingQual
Definition: relation.h:297
bool argisrow
Definition: primnodes.h:1158
List * pathlist
Definition: relation.h:504
Node * havingQual
Definition: parsenodes.h:141
List * processed_tlist
Definition: relation.h:276
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Definition: relation.h:888
double Cost
Definition: nodes.h:632
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
PlannerInfo * subroot
Definition: relation.h:1953
static Oid fetch_agg_sort_op ( Oid  aggfnoid)
static

Definition at line 520 of file planagg.c.

References AGGFNOID, GETSTRUCT, HeapTupleIsValid, InvalidOid, ObjectIdGetDatum, ReleaseSysCache(), and SearchSysCache1.

Referenced by find_minmax_aggs_walker().

521 {
522  HeapTuple aggTuple;
523  Form_pg_aggregate aggform;
524  Oid aggsortop;
525 
526  /* fetch aggregate entry from pg_aggregate */
527  aggTuple = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(aggfnoid));
528  if (!HeapTupleIsValid(aggTuple))
529  return InvalidOid;
530  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
531  aggsortop = aggform->aggsortop;
532  ReleaseSysCache(aggTuple);
533 
534  return aggsortop;
535 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:87
static bool find_minmax_aggs_walker ( Node node,
List **  context 
)
static

Definition at line 247 of file planagg.c.

References Aggref::aggfilter, Aggref::aggfnoid, MinMaxAggInfo::aggfnoid, Aggref::agglevelsup, Aggref::aggorder, MinMaxAggInfo::aggsortop, Aggref::args, Assert, contain_mutable_functions(), equal(), TargetEntry::expr, expression_tree_walker(), exprType(), fetch_agg_sort_op(), IsA, lappend(), lfirst, linitial, list_length(), makeNode, NIL, NULL, OidIsValid, MinMaxAggInfo::param, MinMaxAggInfo::path, MinMaxAggInfo::pathcost, MinMaxAggInfo::subroot, MinMaxAggInfo::target, and type_is_rowtype().

Referenced by preprocess_minmax_aggregates().

248 {
249  if (node == NULL)
250  return false;
251  if (IsA(node, Aggref))
252  {
253  Aggref *aggref = (Aggref *) node;
254  Oid aggsortop;
255  TargetEntry *curTarget;
256  MinMaxAggInfo *mminfo;
257  ListCell *l;
258 
259  Assert(aggref->agglevelsup == 0);
260  if (list_length(aggref->args) != 1)
261  return true; /* it couldn't be MIN/MAX */
262 
263  /*
264  * ORDER BY is usually irrelevant for MIN/MAX, but it can change the
265  * outcome if the aggsortop's operator class recognizes non-identical
266  * values as equal. For example, 4.0 and 4.00 are equal according to
267  * numeric_ops, yet distinguishable. If MIN() receives more than one
268  * value equal to 4.0 and no value less than 4.0, it is unspecified
269  * which of those equal values MIN() returns. An ORDER BY expression
270  * that differs for each of those equal values of the argument
271  * expression makes the result predictable once again. This is a
272  * niche requirement, and we do not implement it with subquery paths.
273  * In any case, this test lets us reject ordered-set aggregates
274  * quickly.
275  */
276  if (aggref->aggorder != NIL)
277  return true;
278  /* note: we do not care if DISTINCT is mentioned ... */
279 
280  /*
281  * We might implement the optimization when a FILTER clause is present
282  * by adding the filter to the quals of the generated subquery. For
283  * now, just punt.
284  */
285  if (aggref->aggfilter != NULL)
286  return true;
287 
288  aggsortop = fetch_agg_sort_op(aggref->aggfnoid);
289  if (!OidIsValid(aggsortop))
290  return true; /* not a MIN/MAX aggregate */
291 
292  curTarget = (TargetEntry *) linitial(aggref->args);
293 
294  if (contain_mutable_functions((Node *) curTarget->expr))
295  return true; /* not potentially indexable */
296 
297  if (type_is_rowtype(exprType((Node *) curTarget->expr)))
298  return true; /* IS NOT NULL would have weird semantics */
299 
300  /*
301  * Check whether it's already in the list, and add it if not.
302  */
303  foreach(l, *context)
304  {
305  mminfo = (MinMaxAggInfo *) lfirst(l);
306  if (mminfo->aggfnoid == aggref->aggfnoid &&
307  equal(mminfo->target, curTarget->expr))
308  return false;
309  }
310 
311  mminfo = makeNode(MinMaxAggInfo);
312  mminfo->aggfnoid = aggref->aggfnoid;
313  mminfo->aggsortop = aggsortop;
314  mminfo->target = curTarget->expr;
315  mminfo->subroot = NULL; /* don't compute path yet */
316  mminfo->path = NULL;
317  mminfo->pathcost = 0;
318  mminfo->param = NULL;
319 
320  *context = lappend(*context, mminfo);
321 
322  /*
323  * We need not recurse into the argument, since it can't contain any
324  * aggregates.
325  */
326  return false;
327  }
328  Assert(!IsA(node, SubLink));
330  (void *) context);
331 }
#define NIL
Definition: pg_list.h:69
static bool find_minmax_aggs_walker(Node *node, List **context)
Definition: planagg.c:247
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2870
Param * param
Definition: relation.h:1956
Definition: nodes.h:508
List * args
Definition: primnodes.h:279
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
#define linitial(l)
Definition: pg_list.h:110
Path * path
Definition: relation.h:1954
List * aggorder
Definition: primnodes.h:280
Index agglevelsup
Definition: primnodes.h:287
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2372
List * lappend(List *list, void *datum)
Definition: list.c:128
Oid aggfnoid
Definition: primnodes.h:272
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Expr * target
Definition: relation.h:1952
Expr * expr
Definition: primnodes.h:1330
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1852
static int list_length(const List *l)
Definition: pg_list.h:89
Expr * aggfilter
Definition: primnodes.h:282
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:877
static Oid fetch_agg_sort_op(Oid aggfnoid)
Definition: planagg.c:520
PlannerInfo * subroot
Definition: relation.h:1953
static void minmax_qp_callback ( PlannerInfo root,
void *  extra 
)
static

Definition at line 501 of file planagg.c.

References PlannerInfo::distinct_pathkeys, PlannerInfo::group_pathkeys, make_pathkeys_for_sortclauses(), NIL, PlannerInfo::parse, PlannerInfo::query_pathkeys, PlannerInfo::sort_pathkeys, Query::sortClause, Query::targetList, and PlannerInfo::window_pathkeys.

Referenced by build_minmax_path().

502 {
503  root->group_pathkeys = NIL;
504  root->window_pathkeys = NIL;
505  root->distinct_pathkeys = NIL;
506 
507  root->sort_pathkeys =
509  root->parse->sortClause,
510  root->parse->targetList);
511 
512  root->query_pathkeys = root->sort_pathkeys;
513 }
List * group_pathkeys
Definition: relation.h:259
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:152
List * sortClause
Definition: parsenodes.h:147
List * query_pathkeys
Definition: relation.h:257
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:838
List * targetList
Definition: parsenodes.h:131
List * sort_pathkeys
Definition: relation.h:262
List * window_pathkeys
Definition: relation.h:260
List * distinct_pathkeys
Definition: relation.h:261
void preprocess_minmax_aggregates ( PlannerInfo root,
List tlist 
)

Definition at line 75 of file planagg.c.

References add_path(), MinMaxAggInfo::aggsortop, Assert, build_minmax_path(), create_minmaxagg_path(), create_pathtarget, Query::cteList, elog, ERROR, exprCollation(), exprType(), fetch_upper_rel(), find_minmax_aggs_walker(), FromExpr::fromlist, get_equality_op_for_ordering_op(), Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasWindowFuncs, Query::havingQual, RangeTblEntry::inh, IsA, Query::jointree, lfirst, linitial, list_length(), PlannerInfo::minmax_aggs, NIL, NULL, OidIsValid, MinMaxAggInfo::param, parse(), PlannerInfo::parse, planner_rt_fetch, Query::rowMarks, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblRef::rtindex, Query::setOperations, SS_make_initplan_output_param(), MinMaxAggInfo::target, and UPPERREL_GROUP_AGG.

Referenced by grouping_planner().

76 {
77  Query *parse = root->parse;
78  FromExpr *jtnode;
79  RangeTblRef *rtr;
80  RangeTblEntry *rte;
81  List *aggs_list;
82  RelOptInfo *grouped_rel;
83  ListCell *lc;
84 
85  /* minmax_aggs list should be empty at this point */
86  Assert(root->minmax_aggs == NIL);
87 
88  /* Nothing to do if query has no aggregates */
89  if (!parse->hasAggs)
90  return;
91 
92  Assert(!parse->setOperations); /* shouldn't get here if a setop */
93  Assert(parse->rowMarks == NIL); /* nor if FOR UPDATE */
94 
95  /*
96  * Reject unoptimizable cases.
97  *
98  * We don't handle GROUP BY or windowing, because our current
99  * implementations of grouping require looking at all the rows anyway, and
100  * so there's not much point in optimizing MIN/MAX.
101  */
102  if (parse->groupClause || list_length(parse->groupingSets) > 1 ||
103  parse->hasWindowFuncs)
104  return;
105 
106  /*
107  * Reject if query contains any CTEs; there's no way to build an indexscan
108  * on one so we couldn't succeed here. (If the CTEs are unreferenced,
109  * that's not true, but it doesn't seem worth expending cycles to check.)
110  */
111  if (parse->cteList)
112  return;
113 
114  /*
115  * We also restrict the query to reference exactly one table, since join
116  * conditions can't be handled reasonably. (We could perhaps handle a
117  * query containing cartesian-product joins, but it hardly seems worth the
118  * trouble.) However, the single table could be buried in several levels
119  * of FromExpr due to subqueries. Note the "single" table could be an
120  * inheritance parent, too, including the case of a UNION ALL subquery
121  * that's been flattened to an appendrel.
122  */
123  jtnode = parse->jointree;
124  while (IsA(jtnode, FromExpr))
125  {
126  if (list_length(jtnode->fromlist) != 1)
127  return;
128  jtnode = linitial(jtnode->fromlist);
129  }
130  if (!IsA(jtnode, RangeTblRef))
131  return;
132  rtr = (RangeTblRef *) jtnode;
133  rte = planner_rt_fetch(rtr->rtindex, root);
134  if (rte->rtekind == RTE_RELATION)
135  /* ordinary relation, ok */ ;
136  else if (rte->rtekind == RTE_SUBQUERY && rte->inh)
137  /* flattened UNION ALL subquery, ok */ ;
138  else
139  return;
140 
141  /*
142  * Scan the tlist and HAVING qual to find all the aggregates and verify
143  * all are MIN/MAX aggregates. Stop as soon as we find one that isn't.
144  */
145  aggs_list = NIL;
146  if (find_minmax_aggs_walker((Node *) tlist, &aggs_list))
147  return;
148  if (find_minmax_aggs_walker(parse->havingQual, &aggs_list))
149  return;
150 
151  /*
152  * OK, there is at least the possibility of performing the optimization.
153  * Build an access path for each aggregate. If any of the aggregates
154  * prove to be non-indexable, give up; there is no point in optimizing
155  * just some of them.
156  */
157  foreach(lc, aggs_list)
158  {
159  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
160  Oid eqop;
161  bool reverse;
162 
163  /*
164  * We'll need the equality operator that goes with the aggregate's
165  * ordering operator.
166  */
167  eqop = get_equality_op_for_ordering_op(mminfo->aggsortop, &reverse);
168  if (!OidIsValid(eqop)) /* shouldn't happen */
169  elog(ERROR, "could not find equality operator for ordering operator %u",
170  mminfo->aggsortop);
171 
172  /*
173  * We can use either an ordering that gives NULLS FIRST or one that
174  * gives NULLS LAST; furthermore there's unlikely to be much
175  * performance difference between them, so it doesn't seem worth
176  * costing out both ways if we get a hit on the first one. NULLS
177  * FIRST is more likely to be available if the operator is a
178  * reverse-sort operator, so try that first if reverse.
179  */
180  if (build_minmax_path(root, mminfo, eqop, mminfo->aggsortop, reverse))
181  continue;
182  if (build_minmax_path(root, mminfo, eqop, mminfo->aggsortop, !reverse))
183  continue;
184 
185  /* No indexable path for this aggregate, so fail */
186  return;
187  }
188 
189  /*
190  * OK, we can do the query this way. Prepare to create a MinMaxAggPath
191  * node.
192  *
193  * First, create an output Param node for each agg. (If we end up not
194  * using the MinMaxAggPath, we'll waste a PARAM_EXEC slot for each agg,
195  * which is not worth worrying about. We can't wait till create_plan time
196  * to decide whether to make the Param, unfortunately.)
197  */
198  foreach(lc, aggs_list)
199  {
200  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
201 
202  mminfo->param =
204  exprType((Node *) mminfo->target),
205  -1,
206  exprCollation((Node *) mminfo->target));
207  }
208 
209  /*
210  * Create a MinMaxAggPath node with the appropriate estimated costs and
211  * other needed data, and add it to the UPPERREL_GROUP_AGG upperrel, where
212  * it will compete against the standard aggregate implementation. (It
213  * will likely always win, but we need not assume that here.)
214  *
215  * Note: grouping_planner won't have created this upperrel yet, but it's
216  * fine for us to create it first. We will not have inserted the correct
217  * consider_parallel value in it, but MinMaxAggPath paths are currently
218  * never parallel-safe anyway, so that doesn't matter. Likewise, it
219  * doesn't matter that we haven't filled FDW-related fields in the rel.
220  */
221  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
222  add_path(grouped_rel, (Path *)
223  create_minmaxagg_path(root, grouped_rel,
224  create_pathtarget(root, tlist),
225  aggs_list,
226  (List *) parse->havingQual));
227 }
#define NIL
Definition: pg_list.h:69
static bool find_minmax_aggs_walker(Node *node, List **context)
Definition: planagg.c:247
MinMaxAggPath * create_minmaxagg_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *mmaggregates, List *quals)
Definition: pathnode.c:2733
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Query * parse
Definition: relation.h:152
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
FromExpr * jointree
Definition: parsenodes.h:129
bool hasAggs
Definition: parsenodes.h:116
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
Param * param
Definition: relation.h:1956
List * groupingSets
Definition: parsenodes.h:139
Definition: nodes.h:508
List * minmax_aggs
Definition: relation.h:280
List * fromlist
Definition: primnodes.h:1433
unsigned int Oid
Definition: postgres_ext.h:31
List * rowMarks
Definition: parsenodes.h:152
#define OidIsValid(objectId)
Definition: c.h:534
#define linitial(l)
Definition: pg_list.h:110
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Expr * target
Definition: relation.h:1952
bool hasWindowFuncs
Definition: parsenodes.h:117
Param * SS_make_initplan_output_param(PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
Definition: subselect.c:2877
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:745
static bool build_minmax_path(PlannerInfo *root, MinMaxAggInfo *mminfo, Oid eqop, Oid sortop, bool nulls_first)
Definition: planagg.c:342
RTEKind rtekind
Definition: parsenodes.h:882
List * cteList
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
#define elog
Definition: elog.h:219
Node * havingQual
Definition: parsenodes.h:141
Definition: pg_list.h:45
Definition: relation.h:888
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651