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