]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
When using extended-query protocol, postpone planning of unnamed statements
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.172 2004/06/11 01:08:52 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <limits.h>
19
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #ifdef OPTIMIZER_DEBUG
26 #include "nodes/print.h"
27 #endif
28 #include "optimizer/clauses.h"
29 #include "optimizer/cost.h"
30 #include "optimizer/pathnode.h"
31 #include "optimizer/paths.h"
32 #include "optimizer/planmain.h"
33 #include "optimizer/planner.h"
34 #include "optimizer/prep.h"
35 #include "optimizer/subselect.h"
36 #include "optimizer/tlist.h"
37 #include "optimizer/var.h"
38 #include "parser/analyze.h"
39 #include "parser/parsetree.h"
40 #include "parser/parse_expr.h"
41 #include "parser/parse_oper.h"
42 #include "utils/selfuncs.h"
43 #include "utils/syscache.h"
44
45
46 ParamListInfo PlannerBoundParamList = NULL;     /* current boundParams */
47
48
49 /* Expression kind codes for preprocess_expression */
50 #define EXPRKIND_QUAL   0
51 #define EXPRKIND_TARGET 1
52 #define EXPRKIND_RTFUNC 2
53 #define EXPRKIND_LIMIT  3
54 #define EXPRKIND_ININFO 4
55
56
57 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
58 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
59 static Plan *inheritance_planner(Query *parse, List *inheritlist);
60 static Plan *grouping_planner(Query *parse, double tuple_fraction);
61 static bool hash_safe_grouping(Query *parse);
62 static List *make_subplanTargetList(Query *parse, List *tlist,
63                                            AttrNumber **groupColIdx, bool *need_tlist_eval);
64 static void locate_grouping_columns(Query *parse,
65                                                 List *tlist,
66                                                 List *sub_tlist,
67                                                 AttrNumber *groupColIdx);
68 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
69
70
71 /*****************************************************************************
72  *
73  *         Query optimizer entry point
74  *
75  *****************************************************************************/
76 Plan *
77 planner(Query *parse, bool isCursor, int cursorOptions,
78                 ParamListInfo boundParams)
79 {
80         double          tuple_fraction;
81         Plan       *result_plan;
82         Index           save_PlannerQueryLevel;
83         List       *save_PlannerParamList;
84         ParamListInfo save_PlannerBoundParamList;
85
86         /*
87          * The planner can be called recursively (an example is when
88          * eval_const_expressions tries to pre-evaluate an SQL function). So,
89          * these global state variables must be saved and restored.
90          *
91          * Query level and the param list cannot be moved into the Query structure
92          * since their whole purpose is communication across multiple sub-Queries.
93          * Also, boundParams is explicitly info from outside the Query, and so
94          * is likewise better handled as a global variable.
95          *
96          * Note we do NOT save and restore PlannerPlanId: it exists to assign
97          * unique IDs to SubPlan nodes, and we want those IDs to be unique for
98          * the life of a backend.  Also, PlannerInitPlan is saved/restored in
99          * subquery_planner, not here.
100          */
101         save_PlannerQueryLevel = PlannerQueryLevel;
102         save_PlannerParamList = PlannerParamList;
103         save_PlannerBoundParamList = PlannerBoundParamList;
104
105         /* Initialize state for handling outer-level references and params */
106         PlannerQueryLevel = 0;          /* will be 1 in top-level subquery_planner */
107         PlannerParamList = NIL;
108         PlannerBoundParamList = boundParams;
109
110         /* Determine what fraction of the plan is likely to be scanned */
111         if (isCursor)
112         {
113                 /*
114                  * We have no real idea how many tuples the user will ultimately
115                  * FETCH from a cursor, but it seems a good bet that he doesn't
116                  * want 'em all.  Optimize for 10% retrieval (you gotta better
117                  * number?      Should this be a SETtable parameter?)
118                  */
119                 tuple_fraction = 0.10;
120         }
121         else
122         {
123                 /* Default assumption is we need all the tuples */
124                 tuple_fraction = 0.0;
125         }
126
127         /* primary planning entry point (may recurse for subqueries) */
128         result_plan = subquery_planner(parse, tuple_fraction);
129
130         Assert(PlannerQueryLevel == 0);
131
132         /*
133          * If creating a plan for a scrollable cursor, make sure it can run
134          * backwards on demand.  Add a Material node at the top at need.
135          */
136         if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
137         {
138                 if (!ExecSupportsBackwardScan(result_plan))
139                         result_plan = materialize_finished_plan(result_plan);
140         }
141
142         /* executor wants to know total number of Params used overall */
143         result_plan->nParamExec = list_length(PlannerParamList);
144
145         /* final cleanup of the plan */
146         set_plan_references(result_plan, parse->rtable);
147
148         /* restore state for outer planner, if any */
149         PlannerQueryLevel = save_PlannerQueryLevel;
150         PlannerParamList = save_PlannerParamList;
151         PlannerBoundParamList = save_PlannerBoundParamList;
152
153         return result_plan;
154 }
155
156
157 /*--------------------
158  * subquery_planner
159  *        Invokes the planner on a subquery.  We recurse to here for each
160  *        sub-SELECT found in the query tree.
161  *
162  * parse is the querytree produced by the parser & rewriter.
163  * tuple_fraction is the fraction of tuples we expect will be retrieved.
164  * tuple_fraction is interpreted as explained for grouping_planner, below.
165  *
166  * Basically, this routine does the stuff that should only be done once
167  * per Query object.  It then calls grouping_planner.  At one time,
168  * grouping_planner could be invoked recursively on the same Query object;
169  * that's not currently true, but we keep the separation between the two
170  * routines anyway, in case we need it again someday.
171  *
172  * subquery_planner will be called recursively to handle sub-Query nodes
173  * found within the query's expressions and rangetable.
174  *
175  * Returns a query plan.
176  *--------------------
177  */
178 Plan *
179 subquery_planner(Query *parse, double tuple_fraction)
180 {
181         List       *saved_initplan = PlannerInitPlan;
182         int                     saved_planid = PlannerPlanId;
183         bool            hasOuterJoins;
184         Plan       *plan;
185         List       *newHaving;
186         List       *lst;
187         ListCell   *l;
188
189         /* Set up for a new level of subquery */
190         PlannerQueryLevel++;
191         PlannerInitPlan = NIL;
192
193         /*
194          * Look for IN clauses at the top level of WHERE, and transform them
195          * into joins.  Note that this step only handles IN clauses originally
196          * at top level of WHERE; if we pull up any subqueries in the next
197          * step, their INs are processed just before pulling them up.
198          */
199         parse->in_info_list = NIL;
200         if (parse->hasSubLinks)
201                 parse->jointree->quals = pull_up_IN_clauses(parse,
202                                                                                                  parse->jointree->quals);
203
204         /*
205          * Check to see if any subqueries in the rangetable can be merged into
206          * this query.
207          */
208         parse->jointree = (FromExpr *)
209                 pull_up_subqueries(parse, (Node *) parse->jointree, false);
210
211         /*
212          * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
213          * can avoid the expense of doing flatten_join_alias_vars().  Also
214          * check for outer joins --- if none, we can skip
215          * reduce_outer_joins(). This must be done after we have done
216          * pull_up_subqueries, of course.
217          */
218         parse->hasJoinRTEs = false;
219         hasOuterJoins = false;
220         foreach(l, parse->rtable)
221         {
222                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
223
224                 if (rte->rtekind == RTE_JOIN)
225                 {
226                         parse->hasJoinRTEs = true;
227                         if (IS_OUTER_JOIN(rte->jointype))
228                         {
229                                 hasOuterJoins = true;
230                                 /* Can quit scanning once we find an outer join */
231                                 break;
232                         }
233                 }
234         }
235
236         /*
237          * Do expression preprocessing on targetlist and quals.
238          */
239         parse->targetList = (List *)
240                 preprocess_expression(parse, (Node *) parse->targetList,
241                                                           EXPRKIND_TARGET);
242
243         preprocess_qual_conditions(parse, (Node *) parse->jointree);
244
245         parse->havingQual = preprocess_expression(parse, parse->havingQual,
246                                                                                           EXPRKIND_QUAL);
247
248         parse->limitOffset = preprocess_expression(parse, parse->limitOffset,
249                                                                                            EXPRKIND_LIMIT);
250         parse->limitCount = preprocess_expression(parse, parse->limitCount,
251                                                                                           EXPRKIND_LIMIT);
252
253         parse->in_info_list = (List *)
254                 preprocess_expression(parse, (Node *) parse->in_info_list,
255                                                           EXPRKIND_ININFO);
256
257         /* Also need to preprocess expressions for function RTEs */
258         foreach(l, parse->rtable)
259         {
260                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
261
262                 if (rte->rtekind == RTE_FUNCTION)
263                         rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
264                                                                                                   EXPRKIND_RTFUNC);
265         }
266
267         /*
268          * A HAVING clause without aggregates is equivalent to a WHERE clause
269          * (except it can only refer to grouped fields).  Transfer any
270          * agg-free clauses of the HAVING qual into WHERE.      This may seem like
271          * wasting cycles to cater to stupidly-written queries, but there are
272          * other reasons for doing it.  Firstly, if the query contains no aggs
273          * at all, then we aren't going to generate an Agg plan node, and so
274          * there'll be no place to execute HAVING conditions; without this
275          * transfer, we'd lose the HAVING condition entirely, which is wrong.
276          * Secondly, when we push down a qual condition into a sub-query, it's
277          * easiest to push the qual into HAVING always, in case it contains
278          * aggs, and then let this code sort it out.
279          *
280          * Note that both havingQual and parse->jointree->quals are in
281          * implicitly-ANDed-list form at this point, even though they are
282          * declared as Node *.
283          */
284         newHaving = NIL;
285         foreach(l, (List *) parse->havingQual)
286         {
287                 Node       *havingclause = (Node *) lfirst(l);
288
289                 if (contain_agg_clause(havingclause))
290                         newHaving = lappend(newHaving, havingclause);
291                 else
292                         parse->jointree->quals = (Node *)
293                                 lappend((List *) parse->jointree->quals, havingclause);
294         }
295         parse->havingQual = (Node *) newHaving;
296
297         /*
298          * If we have any outer joins, try to reduce them to plain inner
299          * joins. This step is most easily done after we've done expression
300          * preprocessing.
301          */
302         if (hasOuterJoins)
303                 reduce_outer_joins(parse);
304
305         /*
306          * See if we can simplify the jointree; opportunities for this may
307          * come from having pulled up subqueries, or from flattening explicit
308          * JOIN syntax.  We must do this after flattening JOIN alias
309          * variables, since eliminating explicit JOIN nodes from the jointree
310          * will cause get_relids_for_join() to fail.  But it should happen
311          * after reduce_outer_joins, anyway.
312          */
313         parse->jointree = (FromExpr *)
314                 simplify_jointree(parse, (Node *) parse->jointree);
315
316         /*
317          * Do the main planning.  If we have an inherited target relation,
318          * that needs special processing, else go straight to
319          * grouping_planner.
320          */
321         if (parse->resultRelation &&
322                 (lst = expand_inherited_rtentry(parse, parse->resultRelation,
323                                                                                 false)) != NIL)
324                 plan = inheritance_planner(parse, lst);
325         else
326                 plan = grouping_planner(parse, tuple_fraction);
327
328         /*
329          * If any subplans were generated, or if we're inside a subplan, build
330          * initPlan list and extParam/allParam sets for plan nodes.
331          */
332         if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
333         {
334                 Cost            initplan_cost = 0;
335
336                 /* Prepare extParam/allParam sets for all nodes in tree */
337                 SS_finalize_plan(plan, parse->rtable);
338
339                 /*
340                  * SS_finalize_plan doesn't handle initPlans, so we have to
341                  * manually attach them to the topmost plan node, and add their
342                  * extParams to the topmost node's, too.
343                  *
344                  * We also add the total_cost of each initPlan to the startup cost of
345                  * the top node.  This is a conservative overestimate, since in
346                  * fact each initPlan might be executed later than plan startup,
347                  * or even not at all.
348                  */
349                 plan->initPlan = PlannerInitPlan;
350
351                 foreach(l, plan->initPlan)
352                 {
353                         SubPlan    *initplan = (SubPlan *) lfirst(l);
354
355                         plan->extParam = bms_add_members(plan->extParam,
356                                                                                          initplan->plan->extParam);
357                         /* allParam must include all members of extParam */
358                         plan->allParam = bms_add_members(plan->allParam,
359                                                                                          plan->extParam);
360                         initplan_cost += initplan->plan->total_cost;
361                 }
362
363                 plan->startup_cost += initplan_cost;
364                 plan->total_cost += initplan_cost;
365         }
366
367         /* Return to outer subquery context */
368         PlannerQueryLevel--;
369         PlannerInitPlan = saved_initplan;
370         /* we do NOT restore PlannerPlanId; that's not an oversight! */
371
372         return plan;
373 }
374
375 /*
376  * preprocess_expression
377  *              Do subquery_planner's preprocessing work for an expression,
378  *              which can be a targetlist, a WHERE clause (including JOIN/ON
379  *              conditions), or a HAVING clause.
380  */
381 static Node *
382 preprocess_expression(Query *parse, Node *expr, int kind)
383 {
384         /*
385          * If the query has any join RTEs, replace join alias variables with
386          * base-relation variables. We must do this before sublink processing,
387          * else sublinks expanded out from join aliases wouldn't get
388          * processed.
389          */
390         if (parse->hasJoinRTEs)
391                 expr = flatten_join_alias_vars(parse, expr);
392
393         /*
394          * If it's a qual or havingQual, canonicalize it.  It seems most useful
395          * to do this before applying eval_const_expressions, since the latter
396          * can optimize flattened AND/ORs better than unflattened ones.
397          *
398          * Note: all processing of a qual expression after this point must be
399          * careful to maintain AND/OR flatness --- that is, do not generate a
400          * tree with AND directly under AND, nor OR directly under OR.
401          */
402         if (kind == EXPRKIND_QUAL)
403         {
404                 expr = (Node *) canonicalize_qual((Expr *) expr);
405
406 #ifdef OPTIMIZER_DEBUG
407                 printf("After canonicalize_qual()\n");
408                 pprint(expr);
409 #endif
410         }
411
412         /*
413          * Simplify constant expressions.
414          */
415         expr = eval_const_expressions(expr);
416
417         /* Expand SubLinks to SubPlans */
418         if (parse->hasSubLinks)
419                 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
420
421         /*
422          * XXX do not insert anything here unless you have grokked the
423          * comments in SS_replace_correlation_vars ...
424          */
425
426         /* Replace uplevel vars with Param nodes */
427         if (PlannerQueryLevel > 1)
428                 expr = SS_replace_correlation_vars(expr);
429
430         /*
431          * If it's a qual or havingQual, convert it to implicit-AND format.
432          * (We don't want to do this before eval_const_expressions, since the
433          * latter would be unable to simplify a top-level AND correctly.  Also,
434          * SS_process_sublinks expects explicit-AND format.)
435          */
436         if (kind == EXPRKIND_QUAL)
437                 expr = (Node *) make_ands_implicit((Expr *) expr);
438
439         return expr;
440 }
441
442 /*
443  * preprocess_qual_conditions
444  *              Recursively scan the query's jointree and do subquery_planner's
445  *              preprocessing work on each qual condition found therein.
446  */
447 static void
448 preprocess_qual_conditions(Query *parse, Node *jtnode)
449 {
450         if (jtnode == NULL)
451                 return;
452         if (IsA(jtnode, RangeTblRef))
453         {
454                 /* nothing to do here */
455         }
456         else if (IsA(jtnode, FromExpr))
457         {
458                 FromExpr   *f = (FromExpr *) jtnode;
459                 ListCell   *l;
460
461                 foreach(l, f->fromlist)
462                         preprocess_qual_conditions(parse, lfirst(l));
463
464                 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
465         }
466         else if (IsA(jtnode, JoinExpr))
467         {
468                 JoinExpr   *j = (JoinExpr *) jtnode;
469
470                 preprocess_qual_conditions(parse, j->larg);
471                 preprocess_qual_conditions(parse, j->rarg);
472
473                 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
474         }
475         else
476                 elog(ERROR, "unrecognized node type: %d",
477                          (int) nodeTag(jtnode));
478 }
479
480 /*--------------------
481  * inheritance_planner
482  *        Generate a plan in the case where the result relation is an
483  *        inheritance set.
484  *
485  * We have to handle this case differently from cases where a source
486  * relation is an inheritance set.      Source inheritance is expanded at
487  * the bottom of the plan tree (see allpaths.c), but target inheritance
488  * has to be expanded at the top.  The reason is that for UPDATE, each
489  * target relation needs a different targetlist matching its own column
490  * set.  (This is not so critical for DELETE, but for simplicity we treat
491  * inherited DELETE the same way.)      Fortunately, the UPDATE/DELETE target
492  * can never be the nullable side of an outer join, so it's OK to generate
493  * the plan this way.
494  *
495  * parse is the querytree produced by the parser & rewriter.
496  * inheritlist is an integer list of RT indexes for the result relation set.
497  *
498  * Returns a query plan.
499  *--------------------
500  */
501 static Plan *
502 inheritance_planner(Query *parse, List *inheritlist)
503 {
504         int                     parentRTindex = parse->resultRelation;
505         Oid                     parentOID = getrelid(parentRTindex, parse->rtable);
506         int                     mainrtlength = list_length(parse->rtable);
507         List       *subplans = NIL;
508         List       *tlist = NIL;
509         ListCell   *l;
510
511         foreach(l, inheritlist)
512         {
513                 int                     childRTindex = lfirst_int(l);
514                 Oid                     childOID = getrelid(childRTindex, parse->rtable);
515                 int                     subrtlength;
516                 Query      *subquery;
517                 Plan       *subplan;
518
519                 /* Generate modified query with this rel as target */
520                 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
521                                                                                                 parentRTindex, parentOID,
522                                                                                                  childRTindex, childOID);
523                 /* Generate plan */
524                 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
525                 subplans = lappend(subplans, subplan);
526
527                 /*
528                  * It's possible that additional RTEs got added to the rangetable
529                  * due to expansion of inherited source tables (see allpaths.c).
530                  * If so, we must copy 'em back to the main parse tree's rtable.
531                  *
532                  * XXX my goodness this is ugly.  Really need to think about ways to
533                  * rein in planner's habit of scribbling on its input.
534                  */
535                 subrtlength = list_length(subquery->rtable);
536                 if (subrtlength > mainrtlength)
537                 {
538                         List       *subrt;
539
540                         subrt = list_copy_tail(subquery->rtable, mainrtlength);
541                         parse->rtable = list_concat(parse->rtable, subrt);
542                         mainrtlength = subrtlength;
543                 }
544                 /* Save preprocessed tlist from first rel for use in Append */
545                 if (tlist == NIL)
546                         tlist = subplan->targetlist;
547         }
548
549         /* Save the target-relations list for the executor, too */
550         parse->resultRelations = inheritlist;
551
552         /* Mark result as unordered (probably unnecessary) */
553         parse->query_pathkeys = NIL;
554
555         return (Plan *) make_append(subplans, true, tlist);
556 }
557
558 /*--------------------
559  * grouping_planner
560  *        Perform planning steps related to grouping, aggregation, etc.
561  *        This primarily means adding top-level processing to the basic
562  *        query plan produced by query_planner.
563  *
564  * parse is the querytree produced by the parser & rewriter.
565  * tuple_fraction is the fraction of tuples we expect will be retrieved
566  *
567  * tuple_fraction is interpreted as follows:
568  *        0: expect all tuples to be retrieved (normal case)
569  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
570  *              from the plan to be retrieved
571  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
572  *              expected to be retrieved (ie, a LIMIT specification)
573  *
574  * Returns a query plan.  Also, parse->query_pathkeys is returned as the
575  * actual output ordering of the plan (in pathkey format).
576  *--------------------
577  */
578 static Plan *
579 grouping_planner(Query *parse, double tuple_fraction)
580 {
581         List       *tlist = parse->targetList;
582         Plan       *result_plan;
583         List       *current_pathkeys;
584         List       *sort_pathkeys;
585
586         if (parse->setOperations)
587         {
588                 List   *set_sortclauses;
589
590                 /*
591                  * Construct the plan for set operations.  The result will not
592                  * need any work except perhaps a top-level sort and/or LIMIT.
593                  */
594                 result_plan = plan_set_operations(parse,
595                                                                                   &set_sortclauses);
596
597                 /*
598                  * Calculate pathkeys representing the sort order (if any) of the
599                  * set operation's result.  We have to do this before overwriting
600                  * the sort key information...
601                  */
602                 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
603                                                                                                         result_plan->targetlist);
604                 current_pathkeys = canonicalize_pathkeys(parse, current_pathkeys);
605
606                 /*
607                  * We should not need to call preprocess_targetlist, since we must
608                  * be in a SELECT query node.  Instead, use the targetlist
609                  * returned by plan_set_operations (since this tells whether it
610                  * returned any resjunk columns!), and transfer any sort key
611                  * information from the original tlist.
612                  */
613                 Assert(parse->commandType == CMD_SELECT);
614
615                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
616
617                 /*
618                  * Can't handle FOR UPDATE here (parser should have checked
619                  * already, but let's make sure).
620                  */
621                 if (parse->rowMarks)
622                         ereport(ERROR,
623                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
624                                          errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
625
626                 /*
627                  * Calculate pathkeys that represent result ordering requirements
628                  */
629                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
630                                                                                                           tlist);
631                 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
632         }
633         else
634         {
635                 /* No set operations, do regular planning */
636                 List       *sub_tlist;
637                 List       *group_pathkeys;
638                 AttrNumber *groupColIdx = NULL;
639                 bool            need_tlist_eval = true;
640                 QualCost        tlist_cost;
641                 double          sub_tuple_fraction;
642                 Path       *cheapest_path;
643                 Path       *sorted_path;
644                 double          dNumGroups = 0;
645                 long            numGroups = 0;
646                 int                     numAggs = 0;
647                 int                     numGroupCols = list_length(parse->groupClause);
648                 bool            use_hashed_grouping = false;
649
650                 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
651                 tlist = preprocess_targetlist(tlist,
652                                                                           parse->commandType,
653                                                                           parse->resultRelation,
654                                                                           parse->rtable);
655
656                 /*
657                  * Add TID targets for rels selected FOR UPDATE (should this be
658                  * done in preprocess_targetlist?).  The executor uses the TID to
659                  * know which rows to lock, much as for UPDATE or DELETE.
660                  */
661                 if (parse->rowMarks)
662                 {
663                         ListCell   *l;
664
665                         /*
666                          * We've got trouble if the FOR UPDATE appears inside
667                          * grouping, since grouping renders a reference to individual
668                          * tuple CTIDs invalid.  This is also checked at parse time,
669                          * but that's insufficient because of rule substitution, query
670                          * pullup, etc.
671                          */
672                         CheckSelectForUpdate(parse);
673
674                         /*
675                          * Currently the executor only supports FOR UPDATE at top
676                          * level
677                          */
678                         if (PlannerQueryLevel > 1)
679                                 ereport(ERROR,
680                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
681                                                  errmsg("SELECT FOR UPDATE is not allowed in subqueries")));
682
683                         foreach(l, parse->rowMarks)
684                         {
685                                 Index           rti = lfirst_int(l);
686                                 char       *resname;
687                                 Resdom     *resdom;
688                                 Var                *var;
689                                 TargetEntry *ctid;
690
691                                 resname = (char *) palloc(32);
692                                 snprintf(resname, 32, "ctid%u", rti);
693                                 resdom = makeResdom(list_length(tlist) + 1,
694                                                                         TIDOID,
695                                                                         -1,
696                                                                         resname,
697                                                                         true);
698
699                                 var = makeVar(rti,
700                                                           SelfItemPointerAttributeNumber,
701                                                           TIDOID,
702                                                           -1,
703                                                           0);
704
705                                 ctid = makeTargetEntry(resdom, (Expr *) var);
706                                 tlist = lappend(tlist, ctid);
707                         }
708                 }
709
710                 /*
711                  * Generate appropriate target list for subplan; may be different
712                  * from tlist if grouping or aggregation is needed.
713                  */
714                 sub_tlist = make_subplanTargetList(parse, tlist,
715                                                                                  &groupColIdx, &need_tlist_eval);
716
717                 /*
718                  * Calculate pathkeys that represent grouping/ordering
719                  * requirements
720                  */
721                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
722                                                                                                            tlist);
723                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
724                                                                                                           tlist);
725
726                 /*
727                  * Will need actual number of aggregates for estimating costs.
728                  *
729                  * Note: we do not attempt to detect duplicate aggregates here; a
730                  * somewhat-overestimated count is okay for our present purposes.
731                  *
732                  * Note: think not that we can turn off hasAggs if we find no aggs.
733                  * It is possible for constant-expression simplification to remove
734                  * all explicit references to aggs, but we still have to follow the
735                  * aggregate semantics (eg, producing only one output row).
736                  */
737                 if (parse->hasAggs)
738                         numAggs = count_agg_clause((Node *) tlist) +
739                                 count_agg_clause(parse->havingQual);
740
741                 /*
742                  * Figure out whether we need a sorted result from query_planner.
743                  *
744                  * If we have a GROUP BY clause, then we want a result sorted
745                  * properly for grouping.  Otherwise, if there is an ORDER BY
746                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
747                  * have both, and ORDER BY is a superset of GROUP BY, it would be
748                  * tempting to request sort by ORDER BY --- but that might just
749                  * leave us failing to exploit an available sort order at all.
750                  * Needs more thought...)
751                  */
752                 if (parse->groupClause)
753                         parse->query_pathkeys = group_pathkeys;
754                 else if (parse->sortClause)
755                         parse->query_pathkeys = sort_pathkeys;
756                 else
757                         parse->query_pathkeys = NIL;
758
759                 /*
760                  * Adjust tuple_fraction if we see that we are going to apply
761                  * limiting/grouping/aggregation/etc.  This is not overridable by
762                  * the caller, since it reflects plan actions that this routine
763                  * will certainly take, not assumptions about context.
764                  */
765                 if (parse->limitCount != NULL)
766                 {
767                         /*
768                          * A LIMIT clause limits the absolute number of tuples
769                          * returned. However, if it's not a constant LIMIT then we
770                          * have to punt; for lack of a better idea, assume 10% of the
771                          * plan's result is wanted.
772                          */
773                         double          limit_fraction = 0.0;
774
775                         if (IsA(parse->limitCount, Const))
776                         {
777                                 Const      *limitc = (Const *) parse->limitCount;
778                                 int32           count = DatumGetInt32(limitc->constvalue);
779
780                                 /*
781                                  * A NULL-constant LIMIT represents "LIMIT ALL", which we
782                                  * treat the same as no limit (ie, expect to retrieve all
783                                  * the tuples).
784                                  */
785                                 if (!limitc->constisnull && count > 0)
786                                 {
787                                         limit_fraction = (double) count;
788                                         /* We must also consider the OFFSET, if present */
789                                         if (parse->limitOffset != NULL)
790                                         {
791                                                 if (IsA(parse->limitOffset, Const))
792                                                 {
793                                                         int32           offset;
794
795                                                         limitc = (Const *) parse->limitOffset;
796                                                         offset = DatumGetInt32(limitc->constvalue);
797                                                         if (!limitc->constisnull && offset > 0)
798                                                                 limit_fraction += (double) offset;
799                                                 }
800                                                 else
801                                                 {
802                                                         /* OFFSET is an expression ... punt ... */
803                                                         limit_fraction = 0.10;
804                                                 }
805                                         }
806                                 }
807                         }
808                         else
809                         {
810                                 /* LIMIT is an expression ... punt ... */
811                                 limit_fraction = 0.10;
812                         }
813
814                         if (limit_fraction > 0.0)
815                         {
816                                 /*
817                                  * If we have absolute limits from both caller and LIMIT,
818                                  * use the smaller value; if one is fractional and the
819                                  * other absolute, treat the fraction as a fraction of the
820                                  * absolute value; else we can multiply the two fractions
821                                  * together.
822                                  */
823                                 if (tuple_fraction >= 1.0)
824                                 {
825                                         if (limit_fraction >= 1.0)
826                                         {
827                                                 /* both absolute */
828                                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
829                                         }
830                                         else
831                                         {
832                                                 /* caller absolute, limit fractional */
833                                                 tuple_fraction *= limit_fraction;
834                                                 if (tuple_fraction < 1.0)
835                                                         tuple_fraction = 1.0;
836                                         }
837                                 }
838                                 else if (tuple_fraction > 0.0)
839                                 {
840                                         if (limit_fraction >= 1.0)
841                                         {
842                                                 /* caller fractional, limit absolute */
843                                                 tuple_fraction *= limit_fraction;
844                                                 if (tuple_fraction < 1.0)
845                                                         tuple_fraction = 1.0;
846                                         }
847                                         else
848                                         {
849                                                 /* both fractional */
850                                                 tuple_fraction *= limit_fraction;
851                                         }
852                                 }
853                                 else
854                                 {
855                                         /* no info from caller, just use limit */
856                                         tuple_fraction = limit_fraction;
857                                 }
858                         }
859                 }
860
861                 /*
862                  * With grouping or aggregation, the tuple fraction to pass to
863                  * query_planner() may be different from what it is at top level.
864                  */
865                 sub_tuple_fraction = tuple_fraction;
866
867                 if (parse->groupClause)
868                 {
869                         /*
870                          * In GROUP BY mode, we have the little problem that we don't
871                          * really know how many input tuples will be needed to make a
872                          * group, so we can't translate an output LIMIT count into an
873                          * input count.  For lack of a better idea, assume 25% of the
874                          * input data will be processed if there is any output limit.
875                          * However, if the caller gave us a fraction rather than an
876                          * absolute count, we can keep using that fraction (which
877                          * amounts to assuming that all the groups are about the same
878                          * size).
879                          */
880                         if (sub_tuple_fraction >= 1.0)
881                                 sub_tuple_fraction = 0.25;
882
883                         /*
884                          * If both GROUP BY and ORDER BY are specified, we will need
885                          * two levels of sort --- and, therefore, certainly need to
886                          * read all the input tuples --- unless ORDER BY is a subset
887                          * of GROUP BY.  (We have not yet canonicalized the pathkeys,
888                          * so must use the slower noncanonical comparison method.)
889                          */
890                         if (parse->groupClause && parse->sortClause &&
891                                 !noncanonical_pathkeys_contained_in(sort_pathkeys,
892                                                                                                         group_pathkeys))
893                                 sub_tuple_fraction = 0.0;
894                 }
895                 else if (parse->hasAggs)
896                 {
897                         /*
898                          * Ungrouped aggregate will certainly want all the input
899                          * tuples.
900                          */
901                         sub_tuple_fraction = 0.0;
902                 }
903                 else if (parse->distinctClause)
904                 {
905                         /*
906                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
907                          * number of input tuples per output tuple.  Handle the same
908                          * way.
909                          */
910                         if (sub_tuple_fraction >= 1.0)
911                                 sub_tuple_fraction = 0.25;
912                 }
913
914                 /*
915                  * Generate the best unsorted and presorted paths for this Query
916                  * (but note there may not be any presorted path).
917                  */
918                 query_planner(parse, sub_tlist, sub_tuple_fraction,
919                                           &cheapest_path, &sorted_path);
920
921                 /*
922                  * We couldn't canonicalize group_pathkeys and sort_pathkeys
923                  * before running query_planner(), so do it now.
924                  */
925                 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
926                 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
927
928                 /*
929                  * Consider whether we might want to use hashed grouping.
930                  */
931                 if (parse->groupClause)
932                 {
933                         List       *groupExprs;
934                         double          cheapest_path_rows;
935                         int                     cheapest_path_width;
936
937                         /*
938                          * Beware in this section of the possibility that
939                          * cheapest_path->parent is NULL.  This could happen if user
940                          * does something silly like SELECT 'foo' GROUP BY 1;
941                          */
942                         if (cheapest_path->parent)
943                         {
944                                 cheapest_path_rows = cheapest_path->parent->rows;
945                                 cheapest_path_width = cheapest_path->parent->width;
946                         }
947                         else
948                         {
949                                 cheapest_path_rows = 1; /* assume non-set result */
950                                 cheapest_path_width = 100;              /* arbitrary */
951                         }
952
953                         /*
954                          * Always estimate the number of groups.  We can't do this
955                          * until after running query_planner(), either.
956                          */
957                         groupExprs = get_sortgrouplist_exprs(parse->groupClause,
958                                                                                                  parse->targetList);
959                         dNumGroups = estimate_num_groups(parse,
960                                                                                          groupExprs,
961                                                                                          cheapest_path_rows);
962                         /* Also want it as a long int --- but 'ware overflow! */
963                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
964
965                         /*
966                          * Check can't-do-it conditions, including whether the
967                          * grouping operators are hashjoinable.
968                          *
969                          * Executor doesn't support hashed aggregation with DISTINCT
970                          * aggregates.  (Doing so would imply storing *all* the input
971                          * values in the hash table, which seems like a certain
972                          * loser.)
973                          */
974                         if (!enable_hashagg || !hash_safe_grouping(parse))
975                                 use_hashed_grouping = false;
976                         else if (parse->hasAggs &&
977                                          (contain_distinct_agg_clause((Node *) tlist) ||
978                                           contain_distinct_agg_clause(parse->havingQual)))
979                                 use_hashed_grouping = false;
980                         else
981                         {
982                                 /*
983                                  * Use hashed grouping if (a) we think we can fit the
984                                  * hashtable into work_mem, *and* (b) the estimated cost is
985                                  * no more than doing it the other way.  While avoiding
986                                  * the need for sorted input is usually a win, the fact
987                                  * that the output won't be sorted may be a loss; so we
988                                  * need to do an actual cost comparison.
989                                  *
990                                  * In most cases we have no good way to estimate the size of
991                                  * the transition value needed by an aggregate;
992                                  * arbitrarily assume it is 100 bytes.  Also set the
993                                  * overhead per hashtable entry at 64 bytes.
994                                  */
995                                 int                     hashentrysize = cheapest_path_width + 64 + numAggs * 100;
996
997                                 if (hashentrysize * dNumGroups <= work_mem * 1024L)
998                                 {
999                                         /*
1000                                          * Okay, do the cost comparison.  We need to consider
1001                                          * cheapest_path + hashagg [+ final sort] versus
1002                                          * either cheapest_path [+ sort] + group or agg [+
1003                                          * final sort] or presorted_path + group or agg [+
1004                                          * final sort] where brackets indicate a step that may
1005                                          * not be needed. We assume query_planner() will have
1006                                          * returned a presorted path only if it's a winner
1007                                          * compared to cheapest_path for this purpose.
1008                                          *
1009                                          * These path variables are dummies that just hold cost
1010                                          * fields; we don't make actual Paths for these steps.
1011                                          */
1012                                         Path            hashed_p;
1013                                         Path            sorted_p;
1014
1015                                         cost_agg(&hashed_p, parse,
1016                                                          AGG_HASHED, numAggs,
1017                                                          numGroupCols, dNumGroups,
1018                                                          cheapest_path->startup_cost,
1019                                                          cheapest_path->total_cost,
1020                                                          cheapest_path_rows);
1021                                         /* Result of hashed agg is always unsorted */
1022                                         if (sort_pathkeys)
1023                                                 cost_sort(&hashed_p, parse, sort_pathkeys,
1024                                                                   hashed_p.total_cost,
1025                                                                   dNumGroups,
1026                                                                   cheapest_path_width);
1027
1028                                         if (sorted_path)
1029                                         {
1030                                                 sorted_p.startup_cost = sorted_path->startup_cost;
1031                                                 sorted_p.total_cost = sorted_path->total_cost;
1032                                                 current_pathkeys = sorted_path->pathkeys;
1033                                         }
1034                                         else
1035                                         {
1036                                                 sorted_p.startup_cost = cheapest_path->startup_cost;
1037                                                 sorted_p.total_cost = cheapest_path->total_cost;
1038                                                 current_pathkeys = cheapest_path->pathkeys;
1039                                         }
1040                                         if (!pathkeys_contained_in(group_pathkeys,
1041                                                                                            current_pathkeys))
1042                                         {
1043                                                 cost_sort(&sorted_p, parse, group_pathkeys,
1044                                                                   sorted_p.total_cost,
1045                                                                   cheapest_path_rows,
1046                                                                   cheapest_path_width);
1047                                                 current_pathkeys = group_pathkeys;
1048                                         }
1049                                         if (parse->hasAggs)
1050                                                 cost_agg(&sorted_p, parse,
1051                                                                  AGG_SORTED, numAggs,
1052                                                                  numGroupCols, dNumGroups,
1053                                                                  sorted_p.startup_cost,
1054                                                                  sorted_p.total_cost,
1055                                                                  cheapest_path_rows);
1056                                         else
1057                                                 cost_group(&sorted_p, parse,
1058                                                                    numGroupCols, dNumGroups,
1059                                                                    sorted_p.startup_cost,
1060                                                                    sorted_p.total_cost,
1061                                                                    cheapest_path_rows);
1062                                         /* The Agg or Group node will preserve ordering */
1063                                         if (sort_pathkeys &&
1064                                                 !pathkeys_contained_in(sort_pathkeys,
1065                                                                                            current_pathkeys))
1066                                         {
1067                                                 cost_sort(&sorted_p, parse, sort_pathkeys,
1068                                                                   sorted_p.total_cost,
1069                                                                   dNumGroups,
1070                                                                   cheapest_path_width);
1071                                         }
1072
1073                                         /*
1074                                          * Now make the decision using the top-level tuple
1075                                          * fraction.  First we have to convert an absolute
1076                                          * count (LIMIT) into fractional form.
1077                                          */
1078                                         if (tuple_fraction >= 1.0)
1079                                                 tuple_fraction /= dNumGroups;
1080
1081                                         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1082                                                                                                           tuple_fraction) < 0)
1083                                         {
1084                                                 /* Hashed is cheaper, so use it */
1085                                                 use_hashed_grouping = true;
1086                                         }
1087                                 }
1088                         }
1089                 }
1090
1091                 /*
1092                  * Select the best path and create a plan to execute it.
1093                  *
1094                  * If we are doing hashed grouping, we will always read all the input
1095                  * tuples, so use the cheapest-total path.      Otherwise, trust
1096                  * query_planner's decision about which to use.
1097                  */
1098                 if (sorted_path && !use_hashed_grouping)
1099                 {
1100                         result_plan = create_plan(parse, sorted_path);
1101                         current_pathkeys = sorted_path->pathkeys;
1102                 }
1103                 else
1104                 {
1105                         result_plan = create_plan(parse, cheapest_path);
1106                         current_pathkeys = cheapest_path->pathkeys;
1107                 }
1108
1109                 /*
1110                  * create_plan() returns a plan with just a "flat" tlist of
1111                  * required Vars.  Usually we need to insert the sub_tlist as the
1112                  * tlist of the top plan node.  However, we can skip that if we
1113                  * determined that whatever query_planner chose to return will be
1114                  * good enough.
1115                  */
1116                 if (need_tlist_eval)
1117                 {
1118                         /*
1119                          * If the top-level plan node is one that cannot do expression
1120                          * evaluation, we must insert a Result node to project the
1121                          * desired tlist.
1122                          */
1123                         if (!is_projection_capable_plan(result_plan))
1124                         {
1125                                 result_plan = (Plan *) make_result(sub_tlist, NULL,
1126                                                                                                    result_plan);
1127                         }
1128                         else
1129                         {
1130                                 /*
1131                                  * Otherwise, just replace the subplan's flat tlist with
1132                                  * the desired tlist.
1133                                  */
1134                                 result_plan->targetlist = sub_tlist;
1135                         }
1136
1137                         /*
1138                          * Also, account for the cost of evaluation of the sub_tlist.
1139                          *
1140                          * Up to now, we have only been dealing with "flat" tlists,
1141                          * containing just Vars.  So their evaluation cost is zero
1142                          * according to the model used by cost_qual_eval() (or if you
1143                          * prefer, the cost is factored into cpu_tuple_cost).  Thus we
1144                          * can avoid accounting for tlist cost throughout
1145                          * query_planner() and subroutines.  But now we've inserted a
1146                          * tlist that might contain actual operators, sub-selects, etc
1147                          * --- so we'd better account for its cost.
1148                          *
1149                          * Below this point, any tlist eval cost for added-on nodes
1150                          * should be accounted for as we create those nodes.
1151                          * Presently, of the node types we can add on, only Agg and
1152                          * Group project new tlists (the rest just copy their input
1153                          * tuples) --- so make_agg() and make_group() are responsible
1154                          * for computing the added cost.
1155                          */
1156                         cost_qual_eval(&tlist_cost, sub_tlist);
1157                         result_plan->startup_cost += tlist_cost.startup;
1158                         result_plan->total_cost += tlist_cost.startup +
1159                                 tlist_cost.per_tuple * result_plan->plan_rows;
1160                 }
1161                 else
1162                 {
1163                         /*
1164                          * Since we're using query_planner's tlist and not the one
1165                          * make_subplanTargetList calculated, we have to refigure any
1166                          * grouping-column indexes make_subplanTargetList computed.
1167                          */
1168                         locate_grouping_columns(parse, tlist, result_plan->targetlist,
1169                                                                         groupColIdx);
1170                 }
1171
1172                 /*
1173                  * Insert AGG or GROUP node if needed, plus an explicit sort step
1174                  * if necessary.
1175                  *
1176                  * HAVING clause, if any, becomes qual of the Agg node
1177                  */
1178                 if (use_hashed_grouping)
1179                 {
1180                         /* Hashed aggregate plan --- no sort needed */
1181                         result_plan = (Plan *) make_agg(parse,
1182                                                                                         tlist,
1183                                                                                         (List *) parse->havingQual,
1184                                                                                         AGG_HASHED,
1185                                                                                         numGroupCols,
1186                                                                                         groupColIdx,
1187                                                                                         numGroups,
1188                                                                                         numAggs,
1189                                                                                         result_plan);
1190                         /* Hashed aggregation produces randomly-ordered results */
1191                         current_pathkeys = NIL;
1192                 }
1193                 else if (parse->hasAggs)
1194                 {
1195                         /* Plain aggregate plan --- sort if needed */
1196                         AggStrategy aggstrategy;
1197
1198                         if (parse->groupClause)
1199                         {
1200                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1201                                 {
1202                                         result_plan = (Plan *)
1203                                                 make_sort_from_groupcols(parse,
1204                                                                                                  parse->groupClause,
1205                                                                                                  groupColIdx,
1206                                                                                                  result_plan);
1207                                         current_pathkeys = group_pathkeys;
1208                                 }
1209                                 aggstrategy = AGG_SORTED;
1210
1211                                 /*
1212                                  * The AGG node will not change the sort ordering of its
1213                                  * groups, so current_pathkeys describes the result too.
1214                                  */
1215                         }
1216                         else
1217                         {
1218                                 aggstrategy = AGG_PLAIN;
1219                                 /* Result will be only one row anyway; no sort order */
1220                                 current_pathkeys = NIL;
1221                         }
1222
1223                         result_plan = (Plan *) make_agg(parse,
1224                                                                                         tlist,
1225                                                                                         (List *) parse->havingQual,
1226                                                                                         aggstrategy,
1227                                                                                         numGroupCols,
1228                                                                                         groupColIdx,
1229                                                                                         numGroups,
1230                                                                                         numAggs,
1231                                                                                         result_plan);
1232                 }
1233                 else
1234                 {
1235                         /*
1236                          * If there are no Aggs, we shouldn't have any HAVING qual
1237                          * anymore
1238                          */
1239                         Assert(parse->havingQual == NULL);
1240
1241                         /*
1242                          * If we have a GROUP BY clause, insert a group node (plus the
1243                          * appropriate sort node, if necessary).
1244                          */
1245                         if (parse->groupClause)
1246                         {
1247                                 /*
1248                                  * Add an explicit sort if we couldn't make the path come
1249                                  * out the way the GROUP node needs it.
1250                                  */
1251                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1252                                 {
1253                                         result_plan = (Plan *)
1254                                                 make_sort_from_groupcols(parse,
1255                                                                                                  parse->groupClause,
1256                                                                                                  groupColIdx,
1257                                                                                                  result_plan);
1258                                         current_pathkeys = group_pathkeys;
1259                                 }
1260
1261                                 result_plan = (Plan *) make_group(parse,
1262                                                                                                   tlist,
1263                                                                                                   numGroupCols,
1264                                                                                                   groupColIdx,
1265                                                                                                   dNumGroups,
1266                                                                                                   result_plan);
1267                                 /* The Group node won't change sort ordering */
1268                         }
1269                 }
1270         }                                                       /* end of if (setOperations) */
1271
1272         /*
1273          * If we were not able to make the plan come out in the right order,
1274          * add an explicit sort step.
1275          */
1276         if (parse->sortClause)
1277         {
1278                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1279                 {
1280                         result_plan = (Plan *)
1281                                 make_sort_from_sortclauses(parse,
1282                                                                                    parse->sortClause,
1283                                                                                    result_plan);
1284                         current_pathkeys = sort_pathkeys;
1285                 }
1286         }
1287
1288         /*
1289          * If there is a DISTINCT clause, add the UNIQUE node.
1290          */
1291         if (parse->distinctClause)
1292         {
1293                 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1294
1295                 /*
1296                  * If there was grouping or aggregation, leave plan_rows as-is
1297                  * (ie, assume the result was already mostly unique).  If not,
1298                  * it's reasonable to assume the UNIQUE filter has effects
1299                  * comparable to GROUP BY.
1300                  */
1301                 if (!parse->groupClause && !parse->hasAggs)
1302                 {
1303                         List       *distinctExprs;
1304
1305                         distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1306                                                                                                         parse->targetList);
1307                         result_plan->plan_rows = estimate_num_groups(parse,
1308                                                                                                                  distinctExprs,
1309                                                                                                  result_plan->plan_rows);
1310                 }
1311         }
1312
1313         /*
1314          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1315          */
1316         if (parse->limitOffset || parse->limitCount)
1317         {
1318                 result_plan = (Plan *) make_limit(result_plan,
1319                                                                                   parse->limitOffset,
1320                                                                                   parse->limitCount);
1321         }
1322
1323         /*
1324          * Return the actual output ordering in query_pathkeys for possible
1325          * use by an outer query level.
1326          */
1327         parse->query_pathkeys = current_pathkeys;
1328
1329         return result_plan;
1330 }
1331
1332 /*
1333  * hash_safe_grouping - are grouping operators hashable?
1334  *
1335  * We assume hashed aggregation will work if the datatype's equality operator
1336  * is marked hashjoinable.
1337  */
1338 static bool
1339 hash_safe_grouping(Query *parse)
1340 {
1341         ListCell   *gl;
1342
1343         foreach(gl, parse->groupClause)
1344         {
1345                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1346                 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1347                 Operator        optup;
1348                 bool            oprcanhash;
1349
1350                 optup = equality_oper(tle->resdom->restype, true);
1351                 if (!optup)
1352                         return false;
1353                 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1354                 ReleaseSysCache(optup);
1355                 if (!oprcanhash)
1356                         return false;
1357         }
1358         return true;
1359 }
1360
1361 /*---------------
1362  * make_subplanTargetList
1363  *        Generate appropriate target list when grouping is required.
1364  *
1365  * When grouping_planner inserts Aggregate or Group plan nodes above
1366  * the result of query_planner, we typically want to pass a different
1367  * target list to query_planner than the outer plan nodes should have.
1368  * This routine generates the correct target list for the subplan.
1369  *
1370  * The initial target list passed from the parser already contains entries
1371  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1372  * for variables used only in HAVING clauses; so we need to add those
1373  * variables to the subplan target list.  Also, if we are doing either
1374  * grouping or aggregation, we flatten all expressions except GROUP BY items
1375  * into their component variables; the other expressions will be computed by
1376  * the inserted nodes rather than by the subplan.  For example,
1377  * given a query like
1378  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1379  * we want to pass this targetlist to the subplan:
1380  *              a,b,c,d,a+b
1381  * where the a+b target will be used by the Sort/Group steps, and the
1382  * other targets will be used for computing the final results.  (In the
1383  * above example we could theoretically suppress the a and b targets and
1384  * pass down only c,d,a+b, but it's not really worth the trouble to
1385  * eliminate simple var references from the subplan.  We will avoid doing
1386  * the extra computation to recompute a+b at the outer level; see
1387  * replace_vars_with_subplan_refs() in setrefs.c.)
1388  *
1389  * If we are grouping or aggregating, *and* there are no non-Var grouping
1390  * expressions, then the returned tlist is effectively dummy; we do not
1391  * need to force it to be evaluated, because all the Vars it contains
1392  * should be present in the output of query_planner anyway.
1393  *
1394  * 'parse' is the query being processed.
1395  * 'tlist' is the query's target list.
1396  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1397  *                      expressions (if there are any) in the subplan's target list.
1398  * 'need_tlist_eval' is set true if we really need to evaluate the
1399  *                      result tlist.
1400  *
1401  * The result is the targetlist to be passed to the subplan.
1402  *---------------
1403  */
1404 static List *
1405 make_subplanTargetList(Query *parse,
1406                                            List *tlist,
1407                                            AttrNumber **groupColIdx,
1408                                            bool *need_tlist_eval)
1409 {
1410         List       *sub_tlist;
1411         List       *extravars;
1412         int                     numCols;
1413
1414         *groupColIdx = NULL;
1415
1416         /*
1417          * If we're not grouping or aggregating, nothing to do here;
1418          * query_planner should receive the unmodified target list.
1419          */
1420         if (!parse->hasAggs && !parse->groupClause)
1421         {
1422                 *need_tlist_eval = true;
1423                 return tlist;
1424         }
1425
1426         /*
1427          * Otherwise, start with a "flattened" tlist (having just the vars
1428          * mentioned in the targetlist and HAVING qual --- but not upper-
1429          * level Vars; they will be replaced by Params later on).
1430          */
1431         sub_tlist = flatten_tlist(tlist);
1432         extravars = pull_var_clause(parse->havingQual, false);
1433         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1434         list_free(extravars);
1435         *need_tlist_eval = false;       /* only eval if not flat tlist */
1436
1437         /*
1438          * If grouping, create sub_tlist entries for all GROUP BY expressions
1439          * (GROUP BY items that are simple Vars should be in the list
1440          * already), and make an array showing where the group columns are in
1441          * the sub_tlist.
1442          */
1443         numCols = list_length(parse->groupClause);
1444         if (numCols > 0)
1445         {
1446                 int                     keyno = 0;
1447                 AttrNumber *grpColIdx;
1448                 ListCell   *gl;
1449
1450                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1451                 *groupColIdx = grpColIdx;
1452
1453                 foreach(gl, parse->groupClause)
1454                 {
1455                         GroupClause             *grpcl = (GroupClause *) lfirst(gl);
1456                         Node                    *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1457                         TargetEntry             *te = NULL;
1458                         ListCell                *sl;
1459
1460                         /* Find or make a matching sub_tlist entry */
1461                         foreach(sl, sub_tlist)
1462                         {
1463                                 te = (TargetEntry *) lfirst(sl);
1464                                 if (equal(groupexpr, te->expr))
1465                                         break;
1466                         }
1467                         if (!sl)
1468                         {
1469                                 te = makeTargetEntry(makeResdom(list_length(sub_tlist) + 1,
1470                                                                                                 exprType(groupexpr),
1471                                                                                                 exprTypmod(groupexpr),
1472                                                                                                 NULL,
1473                                                                                                 false),
1474                                                                          (Expr *) groupexpr);
1475                                 sub_tlist = lappend(sub_tlist, te);
1476                                 *need_tlist_eval = true;                /* it's not flat anymore */
1477                         }
1478
1479                         /* and save its resno */
1480                         grpColIdx[keyno++] = te->resdom->resno;
1481                 }
1482         }
1483
1484         return sub_tlist;
1485 }
1486
1487 /*
1488  * locate_grouping_columns
1489  *              Locate grouping columns in the tlist chosen by query_planner.
1490  *
1491  * This is only needed if we don't use the sub_tlist chosen by
1492  * make_subplanTargetList.      We have to forget the column indexes found
1493  * by that routine and re-locate the grouping vars in the real sub_tlist.
1494  */
1495 static void
1496 locate_grouping_columns(Query *parse,
1497                                                 List *tlist,
1498                                                 List *sub_tlist,
1499                                                 AttrNumber *groupColIdx)
1500 {
1501         int                     keyno = 0;
1502         ListCell   *gl;
1503
1504         /*
1505          * No work unless grouping.
1506          */
1507         if (!parse->groupClause)
1508         {
1509                 Assert(groupColIdx == NULL);
1510                 return;
1511         }
1512         Assert(groupColIdx != NULL);
1513
1514         foreach(gl, parse->groupClause)
1515         {
1516                 GroupClause             *grpcl = (GroupClause *) lfirst(gl);
1517                 Node                    *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1518                 TargetEntry             *te = NULL;
1519                 ListCell                *sl;
1520
1521                 foreach(sl, sub_tlist)
1522                 {
1523                         te = (TargetEntry *) lfirst(sl);
1524                         if (equal(groupexpr, te->expr))
1525                                 break;
1526                 }
1527                 if (!sl)
1528                         elog(ERROR, "failed to locate grouping columns");
1529
1530                 groupColIdx[keyno++] = te->resdom->resno;
1531         }
1532 }
1533
1534 /*
1535  * postprocess_setop_tlist
1536  *        Fix up targetlist returned by plan_set_operations().
1537  *
1538  * We need to transpose sort key info from the orig_tlist into new_tlist.
1539  * NOTE: this would not be good enough if we supported resjunk sort keys
1540  * for results of set operations --- then, we'd need to project a whole
1541  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
1542  * find any resjunk columns in orig_tlist.
1543  */
1544 static List *
1545 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1546 {
1547         ListCell   *l;
1548         ListCell   *orig_tlist_item = list_head(orig_tlist);
1549
1550         foreach(l, new_tlist)
1551         {
1552                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1553                 TargetEntry *orig_tle;
1554
1555                 /* ignore resjunk columns in setop result */
1556                 if (new_tle->resdom->resjunk)
1557                         continue;
1558
1559                 Assert(orig_tlist_item != NULL);
1560                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1561                 orig_tlist_item = lnext(orig_tlist_item);
1562                 if (orig_tle->resdom->resjunk)  /* should not happen */
1563                         elog(ERROR, "resjunk output columns are not implemented");
1564                 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1565                 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1566                 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1567         }
1568         if (orig_tlist_item != NULL)
1569                 elog(ERROR, "resjunk output columns are not implemented");
1570         return new_tlist;
1571 }