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