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