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