1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.192 2005/08/27 22:13:43 tgl Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "executor/nodeAgg.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #ifdef OPTIMIZER_DEBUG
27 #include "nodes/print.h"
29 #include "optimizer/clauses.h"
30 #include "optimizer/cost.h"
31 #include "optimizer/pathnode.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/planmain.h"
34 #include "optimizer/planner.h"
35 #include "optimizer/prep.h"
36 #include "optimizer/subselect.h"
37 #include "optimizer/tlist.h"
38 #include "optimizer/var.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"
46 ParamListInfo PlannerBoundParamList = NULL; /* current boundParams */
49 /* Expression kind codes for preprocess_expression */
50 #define EXPRKIND_QUAL 0
51 #define EXPRKIND_TARGET 1
52 #define EXPRKIND_RTFUNC 2
53 #define EXPRKIND_LIMIT 3
54 #define EXPRKIND_ININFO 4
57 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
58 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
59 static Plan *inheritance_planner(PlannerInfo *root, List *inheritlist);
60 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
61 static double preprocess_limit(PlannerInfo *root,
62 double tuple_fraction,
63 int *offset_est, int *count_est);
64 static bool choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
65 Path *cheapest_path, Path *sorted_path,
66 double dNumGroups, AggClauseCounts *agg_counts);
67 static bool hash_safe_grouping(PlannerInfo *root);
68 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
69 AttrNumber **groupColIdx, bool *need_tlist_eval);
70 static void locate_grouping_columns(PlannerInfo *root,
73 AttrNumber *groupColIdx);
74 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
77 /*****************************************************************************
79 * Query optimizer entry point
81 *****************************************************************************/
83 planner(Query *parse, bool isCursor, int cursorOptions,
84 ParamListInfo boundParams)
86 double tuple_fraction;
88 Index save_PlannerQueryLevel;
89 List *save_PlannerParamList;
90 ParamListInfo save_PlannerBoundParamList;
93 * The planner can be called recursively (an example is when
94 * eval_const_expressions tries to pre-evaluate an SQL function). So,
95 * these global state variables must be saved and restored.
97 * Query level and the param list cannot be moved into the per-query
98 * PlannerInfo structure since their whole purpose is communication
99 * across multiple sub-queries. Also, boundParams is explicitly info
100 * from outside the query, and so is likewise better handled as a global
103 * Note we do NOT save and restore PlannerPlanId: it exists to assign
104 * unique IDs to SubPlan nodes, and we want those IDs to be unique for
105 * the life of a backend. Also, PlannerInitPlan is saved/restored in
106 * subquery_planner, not here.
108 save_PlannerQueryLevel = PlannerQueryLevel;
109 save_PlannerParamList = PlannerParamList;
110 save_PlannerBoundParamList = PlannerBoundParamList;
112 /* Initialize state for handling outer-level references and params */
113 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
114 PlannerParamList = NIL;
115 PlannerBoundParamList = boundParams;
117 /* Determine what fraction of the plan is likely to be scanned */
121 * We have no real idea how many tuples the user will ultimately
122 * FETCH from a cursor, but it seems a good bet that he doesn't
123 * want 'em all. Optimize for 10% retrieval (you gotta better
124 * number? Should this be a SETtable parameter?)
126 tuple_fraction = 0.10;
130 /* Default assumption is we need all the tuples */
131 tuple_fraction = 0.0;
134 /* primary planning entry point (may recurse for subqueries) */
135 result_plan = subquery_planner(parse, tuple_fraction, NULL);
137 /* check we popped out the right number of levels */
138 Assert(PlannerQueryLevel == 0);
141 * If creating a plan for a scrollable cursor, make sure it can run
142 * backwards on demand. Add a Material node at the top at need.
144 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
146 if (!ExecSupportsBackwardScan(result_plan))
147 result_plan = materialize_finished_plan(result_plan);
150 /* final cleanup of the plan */
151 result_plan = set_plan_references(result_plan, parse->rtable);
153 /* executor wants to know total number of Params used overall */
154 result_plan->nParamExec = list_length(PlannerParamList);
156 /* restore state for outer planner, if any */
157 PlannerQueryLevel = save_PlannerQueryLevel;
158 PlannerParamList = save_PlannerParamList;
159 PlannerBoundParamList = save_PlannerBoundParamList;
165 /*--------------------
167 * Invokes the planner on a subquery. We recurse to here for each
168 * sub-SELECT found in the query tree.
170 * parse is the querytree produced by the parser & rewriter.
171 * tuple_fraction is the fraction of tuples we expect will be retrieved.
172 * tuple_fraction is interpreted as explained for grouping_planner, below.
174 * If subquery_pathkeys isn't NULL, it receives a list of pathkeys indicating
175 * the output sort ordering of the completed plan.
177 * Basically, this routine does the stuff that should only be done once
178 * per Query object. It then calls grouping_planner. At one time,
179 * grouping_planner could be invoked recursively on the same Query object;
180 * that's not currently true, but we keep the separation between the two
181 * routines anyway, in case we need it again someday.
183 * subquery_planner will be called recursively to handle sub-Query nodes
184 * found within the query's expressions and rangetable.
186 * Returns a query plan.
187 *--------------------
190 subquery_planner(Query *parse, double tuple_fraction,
191 List **subquery_pathkeys)
193 List *saved_initplan = PlannerInitPlan;
194 int saved_planid = PlannerPlanId;
201 /* Set up for a new level of subquery */
203 PlannerInitPlan = NIL;
205 /* Create a PlannerInfo data structure for this subquery */
206 root = makeNode(PlannerInfo);
210 * Look for IN clauses at the top level of WHERE, and transform them
211 * into joins. Note that this step only handles IN clauses originally
212 * at top level of WHERE; if we pull up any subqueries in the next
213 * step, their INs are processed just before pulling them up.
215 root->in_info_list = NIL;
216 if (parse->hasSubLinks)
217 parse->jointree->quals = pull_up_IN_clauses(root,
218 parse->jointree->quals);
221 * Check to see if any subqueries in the rangetable can be merged into
224 parse->jointree = (FromExpr *)
225 pull_up_subqueries(root, (Node *) parse->jointree, false);
228 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
229 * can avoid the expense of doing flatten_join_alias_vars(). Also
230 * check for outer joins --- if none, we can skip reduce_outer_joins()
231 * and some other processing. This must be done after we have done
232 * pull_up_subqueries, of course.
234 * Note: if reduce_outer_joins manages to eliminate all outer joins,
235 * root->hasOuterJoins is not reset currently. This is OK since its
236 * purpose is merely to suppress unnecessary processing in simple cases.
238 root->hasJoinRTEs = false;
239 root->hasOuterJoins = false;
240 foreach(l, parse->rtable)
242 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
244 if (rte->rtekind == RTE_JOIN)
246 root->hasJoinRTEs = true;
247 if (IS_OUTER_JOIN(rte->jointype))
249 root->hasOuterJoins = true;
250 /* Can quit scanning once we find an outer join */
257 * Set hasHavingQual to remember if HAVING clause is present. Needed
258 * because preprocess_expression will reduce a constant-true condition
259 * to an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
261 root->hasHavingQual = (parse->havingQual != NULL);
264 * Do expression preprocessing on targetlist and quals.
266 parse->targetList = (List *)
267 preprocess_expression(root, (Node *) parse->targetList,
270 preprocess_qual_conditions(root, (Node *) parse->jointree);
272 parse->havingQual = preprocess_expression(root, parse->havingQual,
275 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
277 parse->limitCount = preprocess_expression(root, parse->limitCount,
280 root->in_info_list = (List *)
281 preprocess_expression(root, (Node *) root->in_info_list,
284 /* Also need to preprocess expressions for function RTEs */
285 foreach(l, parse->rtable)
287 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
289 if (rte->rtekind == RTE_FUNCTION)
290 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
295 * In some cases we may want to transfer a HAVING clause into WHERE.
296 * We cannot do so if the HAVING clause contains aggregates (obviously)
297 * or volatile functions (since a HAVING clause is supposed to be executed
298 * only once per group). Also, it may be that the clause is so expensive
299 * to execute that we're better off doing it only once per group, despite
300 * the loss of selectivity. This is hard to estimate short of doing the
301 * entire planning process twice, so we use a heuristic: clauses
302 * containing subplans are left in HAVING. Otherwise, we move or copy
303 * the HAVING clause into WHERE, in hopes of eliminating tuples before
304 * aggregation instead of after.
306 * If the query has explicit grouping then we can simply move such a
307 * clause into WHERE; any group that fails the clause will not be
308 * in the output because none of its tuples will reach the grouping
309 * or aggregation stage. Otherwise we must have a degenerate
310 * (variable-free) HAVING clause, which we put in WHERE so that
311 * query_planner() can use it in a gating Result node, but also keep
312 * in HAVING to ensure that we don't emit a bogus aggregated row.
313 * (This could be done better, but it seems not worth optimizing.)
315 * Note that both havingQual and parse->jointree->quals are in
316 * implicitly-ANDed-list form at this point, even though they are
317 * declared as Node *.
320 foreach(l, (List *) parse->havingQual)
322 Node *havingclause = (Node *) lfirst(l);
324 if (contain_agg_clause(havingclause) ||
325 contain_volatile_functions(havingclause) ||
326 contain_subplans(havingclause))
328 /* keep it in HAVING */
329 newHaving = lappend(newHaving, havingclause);
331 else if (parse->groupClause)
333 /* move it to WHERE */
334 parse->jointree->quals = (Node *)
335 lappend((List *) parse->jointree->quals, havingclause);
339 /* put a copy in WHERE, keep it in HAVING */
340 parse->jointree->quals = (Node *)
341 lappend((List *) parse->jointree->quals,
342 copyObject(havingclause));
343 newHaving = lappend(newHaving, havingclause);
346 parse->havingQual = (Node *) newHaving;
349 * If we have any outer joins, try to reduce them to plain inner
350 * joins. This step is most easily done after we've done expression
353 if (root->hasOuterJoins)
354 reduce_outer_joins(root);
357 * See if we can simplify the jointree; opportunities for this may
358 * come from having pulled up subqueries, or from flattening explicit
359 * JOIN syntax. We must do this after flattening JOIN alias
360 * variables, since eliminating explicit JOIN nodes from the jointree
361 * will cause get_relids_for_join() to fail. But it should happen
362 * after reduce_outer_joins, anyway.
364 parse->jointree = (FromExpr *)
365 simplify_jointree(root, (Node *) parse->jointree);
368 * Do the main planning. If we have an inherited target relation,
369 * that needs special processing, else go straight to
372 if (parse->resultRelation &&
373 (lst = expand_inherited_rtentry(root, parse->resultRelation)) != NIL)
374 plan = inheritance_planner(root, lst);
376 plan = grouping_planner(root, tuple_fraction);
379 * If any subplans were generated, or if we're inside a subplan, build
380 * initPlan list and extParam/allParam sets for plan nodes, and attach
381 * the initPlans to the top plan node.
383 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
384 SS_finalize_plan(plan, parse->rtable);
386 /* Return sort ordering info if caller wants it */
387 if (subquery_pathkeys)
388 *subquery_pathkeys = root->query_pathkeys;
390 /* Return to outer subquery context */
392 PlannerInitPlan = saved_initplan;
393 /* we do NOT restore PlannerPlanId; that's not an oversight! */
399 * preprocess_expression
400 * Do subquery_planner's preprocessing work for an expression,
401 * which can be a targetlist, a WHERE clause (including JOIN/ON
402 * conditions), or a HAVING clause.
405 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
408 * Fall out quickly if expression is empty. This occurs often enough
409 * to be worth checking. Note that null->null is the correct conversion
410 * for implicit-AND result format, too.
416 * If the query has any join RTEs, replace join alias variables with
417 * base-relation variables. We must do this before sublink processing,
418 * else sublinks expanded out from join aliases wouldn't get
421 if (root->hasJoinRTEs)
422 expr = flatten_join_alias_vars(root, expr);
425 * Simplify constant expressions.
427 * Note: this also flattens nested AND and OR expressions into N-argument
428 * form. All processing of a qual expression after this point must be
429 * careful to maintain AND/OR flatness --- that is, do not generate a tree
430 * with AND directly under AND, nor OR directly under OR.
432 * Because this is a relatively expensive process, we skip it when the
433 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()".
434 * The expression will only be evaluated once anyway, so no point in
435 * pre-simplifying; we can't execute it any faster than the executor can,
436 * and we will waste cycles copying the tree. Notice however that we
437 * still must do it for quals (to get AND/OR flatness); and if we are
438 * in a subquery we should not assume it will be done only once.
440 if (root->parse->jointree->fromlist != NIL ||
441 kind == EXPRKIND_QUAL ||
442 PlannerQueryLevel > 1)
443 expr = eval_const_expressions(expr);
446 * If it's a qual or havingQual, canonicalize it.
448 if (kind == EXPRKIND_QUAL)
450 expr = (Node *) canonicalize_qual((Expr *) expr);
452 #ifdef OPTIMIZER_DEBUG
453 printf("After canonicalize_qual()\n");
458 /* Expand SubLinks to SubPlans */
459 if (root->parse->hasSubLinks)
460 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
463 * XXX do not insert anything here unless you have grokked the
464 * comments in SS_replace_correlation_vars ...
467 /* Replace uplevel vars with Param nodes */
468 if (PlannerQueryLevel > 1)
469 expr = SS_replace_correlation_vars(expr);
472 * If it's a qual or havingQual, convert it to implicit-AND format.
473 * (We don't want to do this before eval_const_expressions, since the
474 * latter would be unable to simplify a top-level AND correctly. Also,
475 * SS_process_sublinks expects explicit-AND format.)
477 if (kind == EXPRKIND_QUAL)
478 expr = (Node *) make_ands_implicit((Expr *) expr);
484 * preprocess_qual_conditions
485 * Recursively scan the query's jointree and do subquery_planner's
486 * preprocessing work on each qual condition found therein.
489 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
493 if (IsA(jtnode, RangeTblRef))
495 /* nothing to do here */
497 else if (IsA(jtnode, FromExpr))
499 FromExpr *f = (FromExpr *) jtnode;
502 foreach(l, f->fromlist)
503 preprocess_qual_conditions(root, lfirst(l));
505 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
507 else if (IsA(jtnode, JoinExpr))
509 JoinExpr *j = (JoinExpr *) jtnode;
511 preprocess_qual_conditions(root, j->larg);
512 preprocess_qual_conditions(root, j->rarg);
514 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
517 elog(ERROR, "unrecognized node type: %d",
518 (int) nodeTag(jtnode));
521 /*--------------------
522 * inheritance_planner
523 * Generate a plan in the case where the result relation is an
526 * We have to handle this case differently from cases where a source
527 * relation is an inheritance set. Source inheritance is expanded at
528 * the bottom of the plan tree (see allpaths.c), but target inheritance
529 * has to be expanded at the top. The reason is that for UPDATE, each
530 * target relation needs a different targetlist matching its own column
531 * set. (This is not so critical for DELETE, but for simplicity we treat
532 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
533 * can never be the nullable side of an outer join, so it's OK to generate
536 * inheritlist is an integer list of RT indexes for the result relation set.
538 * Returns a query plan.
539 *--------------------
542 inheritance_planner(PlannerInfo *root, List *inheritlist)
544 Query *parse = root->parse;
545 int parentRTindex = parse->resultRelation;
546 Oid parentOID = getrelid(parentRTindex, parse->rtable);
547 int mainrtlength = list_length(parse->rtable);
548 List *subplans = NIL;
552 foreach(l, inheritlist)
554 int childRTindex = lfirst_int(l);
555 Oid childOID = getrelid(childRTindex, parse->rtable);
560 * Generate modified query with this rel as target. We have to
561 * be prepared to translate varnos in in_info_list as well as in
564 memcpy(&subroot, root, sizeof(PlannerInfo));
565 subroot.parse = (Query *)
566 adjust_inherited_attrs((Node *) parse,
567 parentRTindex, parentOID,
568 childRTindex, childOID);
569 subroot.in_info_list = (List *)
570 adjust_inherited_attrs((Node *) root->in_info_list,
571 parentRTindex, parentOID,
572 childRTindex, childOID);
575 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
577 subplans = lappend(subplans, subplan);
580 * XXX my goodness this next bit is ugly. Really need to think about
581 * ways to rein in planner's habit of scribbling on its input.
583 * Planning of the subquery might have modified the rangetable,
584 * either by addition of RTEs due to expansion of inherited source
585 * tables, or by changes of the Query structures inside subquery
586 * RTEs. We have to ensure that this gets propagated back to the
587 * master copy. However, if we aren't done planning yet, we also
588 * need to ensure that subsequent calls to grouping_planner have
589 * virgin sub-Queries to work from. So, if we are at the last
590 * list entry, just copy the subquery rangetable back to the master
591 * copy; if we are not, then extend the master copy by adding
592 * whatever the subquery added. (We assume these added entries
593 * will go untouched by the future grouping_planner calls. We are
594 * also effectively assuming that sub-Queries will get planned
595 * identically each time, or at least that the impacts on their
596 * rangetables will be the same each time. Did I say this is ugly?)
598 if (lnext(l) == NULL)
599 parse->rtable = subroot.parse->rtable;
602 int subrtlength = list_length(subroot.parse->rtable);
604 if (subrtlength > mainrtlength)
608 subrt = list_copy_tail(subroot.parse->rtable, mainrtlength);
609 parse->rtable = list_concat(parse->rtable, subrt);
610 mainrtlength = subrtlength;
614 /* Save preprocessed tlist from first rel for use in Append */
616 tlist = subplan->targetlist;
619 /* Save the target-relations list for the executor, too */
620 parse->resultRelations = inheritlist;
622 /* Mark result as unordered (probably unnecessary) */
623 root->query_pathkeys = NIL;
625 return (Plan *) make_append(subplans, true, tlist);
628 /*--------------------
630 * Perform planning steps related to grouping, aggregation, etc.
631 * This primarily means adding top-level processing to the basic
632 * query plan produced by query_planner.
634 * tuple_fraction is the fraction of tuples we expect will be retrieved
636 * tuple_fraction is interpreted as follows:
637 * 0: expect all tuples to be retrieved (normal case)
638 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
639 * from the plan to be retrieved
640 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
641 * expected to be retrieved (ie, a LIMIT specification)
643 * Returns a query plan. Also, root->query_pathkeys is returned as the
644 * actual output ordering of the plan (in pathkey format).
645 *--------------------
648 grouping_planner(PlannerInfo *root, double tuple_fraction)
650 Query *parse = root->parse;
651 List *tlist = parse->targetList;
655 List *current_pathkeys;
657 double dNumGroups = 0;
659 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
660 if (parse->limitCount || parse->limitOffset)
661 tuple_fraction = preprocess_limit(root, tuple_fraction,
662 &offset_est, &count_est);
664 if (parse->setOperations)
666 List *set_sortclauses;
669 * If there's a top-level ORDER BY, assume we have to fetch all
670 * the tuples. This might seem too simplistic given all the
671 * hackery below to possibly avoid the sort ... but a nonzero
672 * tuple_fraction is only of use to plan_set_operations() when
673 * the setop is UNION ALL, and the result of UNION ALL is always
676 if (parse->sortClause)
677 tuple_fraction = 0.0;
680 * Construct the plan for set operations. The result will not
681 * need any work except perhaps a top-level sort and/or LIMIT.
683 result_plan = plan_set_operations(root, tuple_fraction,
687 * Calculate pathkeys representing the sort order (if any) of the
688 * set operation's result. We have to do this before overwriting
689 * the sort key information...
691 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
692 result_plan->targetlist);
693 current_pathkeys = canonicalize_pathkeys(root, current_pathkeys);
696 * We should not need to call preprocess_targetlist, since we must
697 * be in a SELECT query node. Instead, use the targetlist
698 * returned by plan_set_operations (since this tells whether it
699 * returned any resjunk columns!), and transfer any sort key
700 * information from the original tlist.
702 Assert(parse->commandType == CMD_SELECT);
704 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
707 * Can't handle FOR UPDATE/SHARE here (parser should have checked
708 * already, but let's make sure).
712 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
713 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
716 * Calculate pathkeys that represent result ordering requirements
718 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
720 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
724 /* No set operations, do regular planning */
726 List *group_pathkeys;
727 AttrNumber *groupColIdx = NULL;
728 bool need_tlist_eval = true;
734 AggClauseCounts agg_counts;
735 int numGroupCols = list_length(parse->groupClause);
736 bool use_hashed_grouping = false;
738 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
740 /* Preprocess targetlist */
741 tlist = preprocess_targetlist(root, tlist);
744 * Generate appropriate target list for subplan; may be different
745 * from tlist if grouping or aggregation is needed.
747 sub_tlist = make_subplanTargetList(root, tlist,
748 &groupColIdx, &need_tlist_eval);
751 * Calculate pathkeys that represent grouping/ordering requirements.
752 * Stash them in PlannerInfo so that query_planner can canonicalize
755 root->group_pathkeys =
756 make_pathkeys_for_sortclauses(parse->groupClause, tlist);
757 root->sort_pathkeys =
758 make_pathkeys_for_sortclauses(parse->sortClause, tlist);
761 * Will need actual number of aggregates for estimating costs.
763 * Note: we do not attempt to detect duplicate aggregates here; a
764 * somewhat-overestimated count is okay for our present purposes.
766 * Note: think not that we can turn off hasAggs if we find no aggs.
767 * It is possible for constant-expression simplification to remove
768 * all explicit references to aggs, but we still have to follow
769 * the aggregate semantics (eg, producing only one output row).
773 count_agg_clauses((Node *) tlist, &agg_counts);
774 count_agg_clauses(parse->havingQual, &agg_counts);
778 * Figure out whether we need a sorted result from query_planner.
780 * If we have a GROUP BY clause, then we want a result sorted
781 * properly for grouping. Otherwise, if there is an ORDER BY
782 * clause, we want to sort by the ORDER BY clause. (Note: if we
783 * have both, and ORDER BY is a superset of GROUP BY, it would be
784 * tempting to request sort by ORDER BY --- but that might just
785 * leave us failing to exploit an available sort order at all.
786 * Needs more thought...)
788 if (parse->groupClause)
789 root->query_pathkeys = root->group_pathkeys;
790 else if (parse->sortClause)
791 root->query_pathkeys = root->sort_pathkeys;
793 root->query_pathkeys = NIL;
796 * Generate the best unsorted and presorted paths for this Query
797 * (but note there may not be any presorted path). query_planner
798 * will also estimate the number of groups in the query, and
799 * canonicalize all the pathkeys.
801 query_planner(root, sub_tlist, tuple_fraction,
802 &cheapest_path, &sorted_path, &dNumGroups);
804 group_pathkeys = root->group_pathkeys;
805 sort_pathkeys = root->sort_pathkeys;
808 * If grouping, decide whether we want to use hashed grouping.
810 if (parse->groupClause)
812 use_hashed_grouping =
813 choose_hashed_grouping(root, tuple_fraction,
814 cheapest_path, sorted_path,
815 dNumGroups, &agg_counts);
817 /* Also convert # groups to long int --- but 'ware overflow! */
818 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
822 * Select the best path. If we are doing hashed grouping, we will
823 * always read all the input tuples, so use the cheapest-total
824 * path. Otherwise, trust query_planner's decision about which to use.
826 if (use_hashed_grouping || !sorted_path)
827 best_path = cheapest_path;
829 best_path = sorted_path;
832 * Check to see if it's possible to optimize MIN/MAX aggregates.
833 * If so, we will forget all the work we did so far to choose a
834 * "regular" path ... but we had to do it anyway to be able to
835 * tell which way is cheaper.
837 result_plan = optimize_minmax_aggregates(root,
840 if (result_plan != NULL)
843 * optimize_minmax_aggregates generated the full plan, with
844 * the right tlist, and it has no sort order.
846 current_pathkeys = NIL;
851 * Normal case --- create a plan according to query_planner's
854 result_plan = create_plan(root, best_path);
855 current_pathkeys = best_path->pathkeys;
858 * create_plan() returns a plan with just a "flat" tlist of
859 * required Vars. Usually we need to insert the sub_tlist as the
860 * tlist of the top plan node. However, we can skip that if we
861 * determined that whatever query_planner chose to return will be
867 * If the top-level plan node is one that cannot do expression
868 * evaluation, we must insert a Result node to project the
871 if (!is_projection_capable_plan(result_plan))
873 result_plan = (Plan *) make_result(sub_tlist, NULL,
879 * Otherwise, just replace the subplan's flat tlist with
882 result_plan->targetlist = sub_tlist;
886 * Also, account for the cost of evaluation of the sub_tlist.
888 * Up to now, we have only been dealing with "flat" tlists,
889 * containing just Vars. So their evaluation cost is zero
890 * according to the model used by cost_qual_eval() (or if you
891 * prefer, the cost is factored into cpu_tuple_cost). Thus we
892 * can avoid accounting for tlist cost throughout
893 * query_planner() and subroutines. But now we've inserted a
894 * tlist that might contain actual operators, sub-selects, etc
895 * --- so we'd better account for its cost.
897 * Below this point, any tlist eval cost for added-on nodes
898 * should be accounted for as we create those nodes.
899 * Presently, of the node types we can add on, only Agg and
900 * Group project new tlists (the rest just copy their input
901 * tuples) --- so make_agg() and make_group() are responsible
902 * for computing the added cost.
904 cost_qual_eval(&tlist_cost, sub_tlist);
905 result_plan->startup_cost += tlist_cost.startup;
906 result_plan->total_cost += tlist_cost.startup +
907 tlist_cost.per_tuple * result_plan->plan_rows;
912 * Since we're using query_planner's tlist and not the one
913 * make_subplanTargetList calculated, we have to refigure any
914 * grouping-column indexes make_subplanTargetList computed.
916 locate_grouping_columns(root, tlist, result_plan->targetlist,
921 * Insert AGG or GROUP node if needed, plus an explicit sort step
924 * HAVING clause, if any, becomes qual of the Agg or Group node.
926 if (use_hashed_grouping)
928 /* Hashed aggregate plan --- no sort needed */
929 result_plan = (Plan *) make_agg(root,
931 (List *) parse->havingQual,
938 /* Hashed aggregation produces randomly-ordered results */
939 current_pathkeys = NIL;
941 else if (parse->hasAggs)
943 /* Plain aggregate plan --- sort if needed */
944 AggStrategy aggstrategy;
946 if (parse->groupClause)
948 if (!pathkeys_contained_in(group_pathkeys,
951 result_plan = (Plan *)
952 make_sort_from_groupcols(root,
956 current_pathkeys = group_pathkeys;
958 aggstrategy = AGG_SORTED;
961 * The AGG node will not change the sort ordering of its
962 * groups, so current_pathkeys describes the result too.
967 aggstrategy = AGG_PLAIN;
968 /* Result will be only one row anyway; no sort order */
969 current_pathkeys = NIL;
972 result_plan = (Plan *) make_agg(root,
974 (List *) parse->havingQual,
982 else if (parse->groupClause)
985 * GROUP BY without aggregation, so insert a group node (plus
986 * the appropriate sort node, if necessary).
988 * Add an explicit sort if we couldn't make the path come
989 * out the way the GROUP node needs it.
991 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
993 result_plan = (Plan *)
994 make_sort_from_groupcols(root,
998 current_pathkeys = group_pathkeys;
1001 result_plan = (Plan *) make_group(root,
1003 (List *) parse->havingQual,
1008 /* The Group node won't change sort ordering */
1010 else if (root->hasHavingQual)
1013 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1014 * This is a degenerate case in which we are supposed to emit
1015 * either 0 or 1 row depending on whether HAVING succeeds.
1016 * Furthermore, there cannot be any variables in either HAVING
1017 * or the targetlist, so we actually do not need the FROM table
1018 * at all! We can just throw away the plan-so-far and generate
1019 * a Result node. This is a sufficiently unusual corner case
1020 * that it's not worth contorting the structure of this routine
1021 * to avoid having to generate the plan in the first place.
1023 result_plan = (Plan *) make_result(tlist,
1027 } /* end of non-minmax-aggregate case */
1028 } /* end of if (setOperations) */
1031 * If we were not able to make the plan come out in the right order,
1032 * add an explicit sort step.
1034 if (parse->sortClause)
1036 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1038 result_plan = (Plan *)
1039 make_sort_from_sortclauses(root,
1042 current_pathkeys = sort_pathkeys;
1047 * If there is a DISTINCT clause, add the UNIQUE node.
1049 if (parse->distinctClause)
1051 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1054 * If there was grouping or aggregation, leave plan_rows as-is
1055 * (ie, assume the result was already mostly unique). If not,
1056 * use the number of distinct-groups calculated by query_planner.
1058 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1059 result_plan->plan_rows = dNumGroups;
1063 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1065 if (parse->limitCount || parse->limitOffset)
1067 result_plan = (Plan *) make_limit(result_plan,
1075 * Return the actual output ordering in query_pathkeys for possible
1076 * use by an outer query level.
1078 root->query_pathkeys = current_pathkeys;
1084 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1086 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1087 * results back in *count_est and *offset_est. These variables are set to
1088 * 0 if the corresponding clause is not present, and -1 if it's present
1089 * but we couldn't estimate the value for it. (The "0" convention is OK
1090 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1091 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1092 * usual practice of never estimating less than one row.) These values will
1093 * be passed to make_limit, which see if you change this code.
1095 * The return value is the suitably adjusted tuple_fraction to use for
1096 * planning the query. This adjustment is not overridable, since it reflects
1097 * plan actions that grouping_planner() will certainly take, not assumptions
1101 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1102 int *offset_est, int *count_est)
1104 Query *parse = root->parse;
1106 double limit_fraction;
1108 /* Should not be called unless LIMIT or OFFSET */
1109 Assert(parse->limitCount || parse->limitOffset);
1112 * Try to obtain the clause values. We use estimate_expression_value
1113 * primarily because it can sometimes do something useful with Params.
1115 if (parse->limitCount)
1117 est = estimate_expression_value(parse->limitCount);
1118 if (est && IsA(est, Const))
1120 if (((Const *) est)->constisnull)
1122 /* NULL indicates LIMIT ALL, ie, no limit */
1123 *count_est = 0; /* treat as not present */
1127 *count_est = DatumGetInt32(((Const *) est)->constvalue);
1128 if (*count_est <= 0)
1129 *count_est = 1; /* force to at least 1 */
1133 *count_est = -1; /* can't estimate */
1136 *count_est = 0; /* not present */
1138 if (parse->limitOffset)
1140 est = estimate_expression_value(parse->limitOffset);
1141 if (est && IsA(est, Const))
1143 if (((Const *) est)->constisnull)
1145 /* Treat NULL as no offset; the executor will too */
1146 *offset_est = 0; /* treat as not present */
1150 *offset_est = DatumGetInt32(((Const *) est)->constvalue);
1151 if (*offset_est < 0)
1152 *offset_est = 0; /* less than 0 is same as 0 */
1156 *offset_est = -1; /* can't estimate */
1159 *offset_est = 0; /* not present */
1161 if (*count_est != 0)
1164 * A LIMIT clause limits the absolute number of tuples returned.
1165 * However, if it's not a constant LIMIT then we have to guess; for
1166 * lack of a better idea, assume 10% of the plan's result is wanted.
1168 if (*count_est < 0 || *offset_est < 0)
1170 /* LIMIT or OFFSET is an expression ... punt ... */
1171 limit_fraction = 0.10;
1175 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1176 limit_fraction = (double) *count_est + (double) *offset_est;
1180 * If we have absolute limits from both caller and LIMIT, use the
1181 * smaller value; likewise if they are both fractional. If one is
1182 * fractional and the other absolute, we can't easily determine which
1183 * is smaller, but we use the heuristic that the absolute will usually
1186 if (tuple_fraction >= 1.0)
1188 if (limit_fraction >= 1.0)
1191 tuple_fraction = Min(tuple_fraction, limit_fraction);
1195 /* caller absolute, limit fractional; use caller's value */
1198 else if (tuple_fraction > 0.0)
1200 if (limit_fraction >= 1.0)
1202 /* caller fractional, limit absolute; use limit */
1203 tuple_fraction = limit_fraction;
1207 /* both fractional */
1208 tuple_fraction = Min(tuple_fraction, limit_fraction);
1213 /* no info from caller, just use limit */
1214 tuple_fraction = limit_fraction;
1217 else if (*offset_est != 0 && tuple_fraction > 0.0)
1220 * We have an OFFSET but no LIMIT. This acts entirely differently
1221 * from the LIMIT case: here, we need to increase rather than
1222 * decrease the caller's tuple_fraction, because the OFFSET acts
1223 * to cause more tuples to be fetched instead of fewer. This only
1224 * matters if we got a tuple_fraction > 0, however.
1226 * As above, use 10% if OFFSET is present but unestimatable.
1228 if (*offset_est < 0)
1229 limit_fraction = 0.10;
1231 limit_fraction = (double) *offset_est;
1234 * If we have absolute counts from both caller and OFFSET, add them
1235 * together; likewise if they are both fractional. If one is
1236 * fractional and the other absolute, we want to take the larger,
1237 * and we heuristically assume that's the fractional one.
1239 if (tuple_fraction >= 1.0)
1241 if (limit_fraction >= 1.0)
1243 /* both absolute, so add them together */
1244 tuple_fraction += limit_fraction;
1248 /* caller absolute, limit fractional; use limit */
1249 tuple_fraction = limit_fraction;
1254 if (limit_fraction >= 1.0)
1256 /* caller fractional, limit absolute; use caller's value */
1260 /* both fractional, so add them together */
1261 tuple_fraction += limit_fraction;
1262 if (tuple_fraction >= 1.0)
1263 tuple_fraction = 0.0; /* assume fetch all */
1268 return tuple_fraction;
1272 * choose_hashed_grouping - should we use hashed grouping?
1275 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1276 Path *cheapest_path, Path *sorted_path,
1277 double dNumGroups, AggClauseCounts *agg_counts)
1279 int numGroupCols = list_length(root->parse->groupClause);
1280 double cheapest_path_rows;
1281 int cheapest_path_width;
1283 List *current_pathkeys;
1288 * Check can't-do-it conditions, including whether the grouping operators
1291 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1292 * (Doing so would imply storing *all* the input values in the hash table,
1293 * which seems like a certain loser.)
1295 if (!enable_hashagg)
1297 if (agg_counts->numDistinctAggs != 0)
1299 if (!hash_safe_grouping(root))
1303 * Don't do it if it doesn't look like the hashtable will fit into
1306 * Beware here of the possibility that cheapest_path->parent is NULL.
1307 * This could happen if user does something silly like
1308 * SELECT 'foo' GROUP BY 1;
1310 if (cheapest_path->parent)
1312 cheapest_path_rows = cheapest_path->parent->rows;
1313 cheapest_path_width = cheapest_path->parent->width;
1317 cheapest_path_rows = 1; /* assume non-set result */
1318 cheapest_path_width = 100; /* arbitrary */
1321 /* Estimate per-hash-entry space at tuple width... */
1322 hashentrysize = cheapest_path_width;
1323 /* plus space for pass-by-ref transition values... */
1324 hashentrysize += agg_counts->transitionSpace;
1325 /* plus the per-hash-entry overhead */
1326 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1328 if (hashentrysize * dNumGroups > work_mem * 1024L)
1332 * See if the estimated cost is no more than doing it the other way.
1333 * While avoiding the need for sorted input is usually a win, the fact
1334 * that the output won't be sorted may be a loss; so we need to do an
1335 * actual cost comparison.
1337 * We need to consider
1338 * cheapest_path + hashagg [+ final sort]
1340 * cheapest_path [+ sort] + group or agg [+ final sort]
1342 * presorted_path + group or agg [+ final sort]
1343 * where brackets indicate a step that may not be needed. We assume
1344 * query_planner() will have returned a presorted path only if it's a
1345 * winner compared to cheapest_path for this purpose.
1347 * These path variables are dummies that just hold cost fields; we don't
1348 * make actual Paths for these steps.
1350 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1351 numGroupCols, dNumGroups,
1352 cheapest_path->startup_cost, cheapest_path->total_cost,
1353 cheapest_path_rows);
1354 /* Result of hashed agg is always unsorted */
1355 if (root->sort_pathkeys)
1356 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1357 dNumGroups, cheapest_path_width);
1361 sorted_p.startup_cost = sorted_path->startup_cost;
1362 sorted_p.total_cost = sorted_path->total_cost;
1363 current_pathkeys = sorted_path->pathkeys;
1367 sorted_p.startup_cost = cheapest_path->startup_cost;
1368 sorted_p.total_cost = cheapest_path->total_cost;
1369 current_pathkeys = cheapest_path->pathkeys;
1371 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1373 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1374 cheapest_path_rows, cheapest_path_width);
1375 current_pathkeys = root->group_pathkeys;
1378 if (root->parse->hasAggs)
1379 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1380 numGroupCols, dNumGroups,
1381 sorted_p.startup_cost, sorted_p.total_cost,
1382 cheapest_path_rows);
1384 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1385 sorted_p.startup_cost, sorted_p.total_cost,
1386 cheapest_path_rows);
1387 /* The Agg or Group node will preserve ordering */
1388 if (root->sort_pathkeys &&
1389 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1390 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1391 dNumGroups, cheapest_path_width);
1394 * Now make the decision using the top-level tuple fraction. First we
1395 * have to convert an absolute count (LIMIT) into fractional form.
1397 if (tuple_fraction >= 1.0)
1398 tuple_fraction /= dNumGroups;
1400 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1401 tuple_fraction) < 0)
1403 /* Hashed is cheaper, so use it */
1410 * hash_safe_grouping - are grouping operators hashable?
1412 * We assume hashed aggregation will work if the datatype's equality operator
1413 * is marked hashjoinable.
1416 hash_safe_grouping(PlannerInfo *root)
1420 foreach(gl, root->parse->groupClause)
1422 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1423 TargetEntry *tle = get_sortgroupclause_tle(grpcl,
1424 root->parse->targetList);
1428 optup = equality_oper(exprType((Node *) tle->expr), true);
1431 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1432 ReleaseSysCache(optup);
1440 * make_subplanTargetList
1441 * Generate appropriate target list when grouping is required.
1443 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1444 * above the result of query_planner, we typically want to pass a different
1445 * target list to query_planner than the outer plan nodes should have.
1446 * This routine generates the correct target list for the subplan.
1448 * The initial target list passed from the parser already contains entries
1449 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1450 * for variables used only in HAVING clauses; so we need to add those
1451 * variables to the subplan target list. Also, we flatten all expressions
1452 * except GROUP BY items into their component variables; the other expressions
1453 * will be computed by the inserted nodes rather than by the subplan.
1454 * For example, given a query like
1455 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1456 * we want to pass this targetlist to the subplan:
1458 * where the a+b target will be used by the Sort/Group steps, and the
1459 * other targets will be used for computing the final results. (In the
1460 * above example we could theoretically suppress the a and b targets and
1461 * pass down only c,d,a+b, but it's not really worth the trouble to
1462 * eliminate simple var references from the subplan. We will avoid doing
1463 * the extra computation to recompute a+b at the outer level; see
1464 * replace_vars_with_subplan_refs() in setrefs.c.)
1466 * If we are grouping or aggregating, *and* there are no non-Var grouping
1467 * expressions, then the returned tlist is effectively dummy; we do not
1468 * need to force it to be evaluated, because all the Vars it contains
1469 * should be present in the output of query_planner anyway.
1471 * 'tlist' is the query's target list.
1472 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1473 * expressions (if there are any) in the subplan's target list.
1474 * 'need_tlist_eval' is set true if we really need to evaluate the
1477 * The result is the targetlist to be passed to the subplan.
1481 make_subplanTargetList(PlannerInfo *root,
1483 AttrNumber **groupColIdx,
1484 bool *need_tlist_eval)
1486 Query *parse = root->parse;
1491 *groupColIdx = NULL;
1494 * If we're not grouping or aggregating, there's nothing to do here;
1495 * query_planner should receive the unmodified target list.
1497 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1499 *need_tlist_eval = true;
1504 * Otherwise, start with a "flattened" tlist (having just the vars
1505 * mentioned in the targetlist and HAVING qual --- but not upper-
1506 * level Vars; they will be replaced by Params later on).
1508 sub_tlist = flatten_tlist(tlist);
1509 extravars = pull_var_clause(parse->havingQual, false);
1510 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1511 list_free(extravars);
1512 *need_tlist_eval = false; /* only eval if not flat tlist */
1515 * If grouping, create sub_tlist entries for all GROUP BY expressions
1516 * (GROUP BY items that are simple Vars should be in the list
1517 * already), and make an array showing where the group columns are in
1520 numCols = list_length(parse->groupClause);
1524 AttrNumber *grpColIdx;
1527 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1528 *groupColIdx = grpColIdx;
1530 foreach(gl, parse->groupClause)
1532 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1533 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1534 TargetEntry *te = NULL;
1537 /* Find or make a matching sub_tlist entry */
1538 foreach(sl, sub_tlist)
1540 te = (TargetEntry *) lfirst(sl);
1541 if (equal(groupexpr, te->expr))
1546 te = makeTargetEntry((Expr *) groupexpr,
1547 list_length(sub_tlist) + 1,
1550 sub_tlist = lappend(sub_tlist, te);
1551 *need_tlist_eval = true; /* it's not flat anymore */
1554 /* and save its resno */
1555 grpColIdx[keyno++] = te->resno;
1563 * locate_grouping_columns
1564 * Locate grouping columns in the tlist chosen by query_planner.
1566 * This is only needed if we don't use the sub_tlist chosen by
1567 * make_subplanTargetList. We have to forget the column indexes found
1568 * by that routine and re-locate the grouping vars in the real sub_tlist.
1571 locate_grouping_columns(PlannerInfo *root,
1574 AttrNumber *groupColIdx)
1580 * No work unless grouping.
1582 if (!root->parse->groupClause)
1584 Assert(groupColIdx == NULL);
1587 Assert(groupColIdx != NULL);
1589 foreach(gl, root->parse->groupClause)
1591 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1592 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1593 TargetEntry *te = NULL;
1596 foreach(sl, sub_tlist)
1598 te = (TargetEntry *) lfirst(sl);
1599 if (equal(groupexpr, te->expr))
1603 elog(ERROR, "failed to locate grouping columns");
1605 groupColIdx[keyno++] = te->resno;
1610 * postprocess_setop_tlist
1611 * Fix up targetlist returned by plan_set_operations().
1613 * We need to transpose sort key info from the orig_tlist into new_tlist.
1614 * NOTE: this would not be good enough if we supported resjunk sort keys
1615 * for results of set operations --- then, we'd need to project a whole
1616 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1617 * find any resjunk columns in orig_tlist.
1620 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1623 ListCell *orig_tlist_item = list_head(orig_tlist);
1625 foreach(l, new_tlist)
1627 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1628 TargetEntry *orig_tle;
1630 /* ignore resjunk columns in setop result */
1631 if (new_tle->resjunk)
1634 Assert(orig_tlist_item != NULL);
1635 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1636 orig_tlist_item = lnext(orig_tlist_item);
1637 if (orig_tle->resjunk) /* should not happen */
1638 elog(ERROR, "resjunk output columns are not implemented");
1639 Assert(new_tle->resno == orig_tle->resno);
1640 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1642 if (orig_tlist_item != NULL)
1643 elog(ERROR, "resjunk output columns are not implemented");