]> granicus.if.org Git - postgresql/blobdiff - src/backend/optimizer/plan/planner.c
Account for SRFs in targetlists in planner rowcount estimates.
[postgresql] / src / backend / optimizer / plan / planner.c
index c5378eb60af7b1a6ad1ff0093799418ea627fc9d..31fe55707238de952e5eeae4736ea6d10789b0da 100644 (file)
@@ -3,7 +3,7 @@
  * planner.c
  *       The query optimizer external interface.
  *
- * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
@@ -225,6 +225,7 @@ standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
        result = makeNode(PlannedStmt);
 
        result->commandType = parse->commandType;
+       result->queryId = parse->queryId;
        result->hasReturning = (parse->returningList != NIL);
        result->hasModifyingCTE = parse->hasModifyingCTE;
        result->canSetTag = parse->canSetTag;
@@ -233,7 +234,6 @@ standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
        result->rtable = glob->finalrtable;
        result->resultRelations = glob->resultRelations;
        result->utilityStmt = parse->utilityStmt;
-       result->intoClause = parse->intoClause;
        result->subplans = glob->subplans;
        result->rewindPlanIDs = glob->rewindPlanIDs;
        result->rowMarks = glob->finalrowmarks;
@@ -529,22 +529,10 @@ subquery_planner(PlannerGlobal *glob, Query *parse,
                        List       *rowMarks;
 
                        /*
-                        * Deal with the RETURNING clause if any.  It's convenient to pass
-                        * the returningList through setrefs.c now rather than at top
-                        * level (if we waited, handling inherited UPDATE/DELETE would be
-                        * much harder).
+                        * Set up the RETURNING list-of-lists, if needed.
                         */
                        if (parse->returningList)
-                       {
-                               List       *rlist;
-
-                               Assert(parse->resultRelation);
-                               rlist = set_returning_clause_references(root,
-                                                                                                               parse->returningList,
-                                                                                                               plan,
-                                                                                                         parse->resultRelation);
-                               returningLists = list_make1(rlist);
-                       }
+                               returningLists = list_make1(parse->returningList);
                        else
                                returningLists = NIL;
 
@@ -772,14 +760,15 @@ inheritance_planner(PlannerInfo *root)
                 * then fool around with subquery RTEs.
                 */
                subroot.parse = (Query *)
-                       adjust_appendrel_attrs((Node *) parse,
+                       adjust_appendrel_attrs(root,
+                                                                  (Node *) parse,
                                                                   appinfo);
 
                /*
                 * The rowMarks list might contain references to subquery RTEs, so
-                * make a copy that we can apply ChangeVarNodes to.  (Fortunately,
-                * the executor doesn't need to see the modified copies --- we can
-                * just pass it the original rowMarks list.)
+                * make a copy that we can apply ChangeVarNodes to.  (Fortunately, the
+                * executor doesn't need to see the modified copies --- we can just
+                * pass it the original rowMarks list.)
                 */
                subroot.rowMarks = (List *) copyObject(root->rowMarks);
 
@@ -795,10 +784,11 @@ inheritance_planner(PlannerInfo *root)
 
                /*
                 * If this isn't the first child Query, generate duplicates of all
-                * subquery RTEs, and adjust Var numbering to reference the duplicates.
-                * To simplify the loop logic, we scan the original rtable not the
-                * copy just made by adjust_appendrel_attrs; that should be OK since
-                * subquery RTEs couldn't contain any references to the target rel.
+                * subquery RTEs, and adjust Var numbering to reference the
+                * duplicates. To simplify the loop logic, we scan the original rtable
+                * not the copy just made by adjust_appendrel_attrs; that should be OK
+                * since subquery RTEs couldn't contain any references to the target
+                * rel.
                 */
                if (final_rtable != NIL)
                {
@@ -811,7 +801,7 @@ inheritance_planner(PlannerInfo *root)
 
                                if (rte->rtekind == RTE_SUBQUERY)
                                {
-                                       Index   newrti;
+                                       Index           newrti;
 
                                        /*
                                         * The RTE can't contain any references to its own RT
@@ -835,8 +825,6 @@ inheritance_planner(PlannerInfo *root)
                Assert(subroot.join_info_list == NIL);
                /* and we haven't created PlaceHolderInfos, either */
                Assert(subroot.placeholder_list == NIL);
-               /* build a separate list of initplans for each child */
-               subroot.init_plans = NIL;
                /* hack to mark target relation as an inheritance partition */
                subroot.hasInheritedTarget = true;
 
@@ -862,7 +850,7 @@ inheritance_planner(PlannerInfo *root)
                else
                        final_rtable = list_concat(final_rtable,
                                                                           list_copy_tail(subroot.parse->rtable,
-                                                                                                         list_length(final_rtable)));
+                                                                                                list_length(final_rtable)));
 
                /*
                 * We need to collect all the RelOptInfos from all child plans into
@@ -883,22 +871,15 @@ inheritance_planner(PlannerInfo *root)
                save_rel_array = subroot.simple_rel_array;
 
                /* Make sure any initplans from this rel get into the outer list */
-               root->init_plans = list_concat(root->init_plans, subroot.init_plans);
+               root->init_plans = subroot.init_plans;
 
                /* Build list of target-relation RT indexes */
                resultRelations = lappend_int(resultRelations, appinfo->child_relid);
 
                /* Build list of per-relation RETURNING targetlists */
                if (parse->returningList)
-               {
-                       List       *rlist;
-
-                       rlist = set_returning_clause_references(&subroot,
-                                                                                               subroot.parse->returningList,
-                                                                                                       subplan,
-                                                                                                       appinfo->child_relid);
-                       returningLists = lappend(returningLists, rlist);
-               }
+                       returningLists = lappend(returningLists,
+                                                                        subroot.parse->returningList);
        }
 
        /* Mark result as unordered (probably unnecessary) */
@@ -1064,7 +1045,6 @@ grouping_planner(PlannerInfo *root, double tuple_fraction)
                double          sub_limit_tuples;
                AttrNumber *groupColIdx = NULL;
                bool            need_tlist_eval = true;
-               QualCost        tlist_cost;
                Path       *cheapest_path;
                Path       *sorted_path;
                Path       *best_path;
@@ -1337,18 +1317,17 @@ grouping_planner(PlannerInfo *root, double tuple_fraction)
                                need_sort_for_grouping = true;
 
                                /*
-                                * Always override create_plan's tlist, so that we don't
-                                * sort useless data from a "physical" tlist.
+                                * Always override create_plan's tlist, so that we don't sort
+                                * useless data from a "physical" tlist.
                                 */
                                need_tlist_eval = true;
                        }
 
                        /*
-                        * create_plan returns a plan with just a "flat" tlist of
-                        * required Vars.  Usually we need to insert the sub_tlist as the
-                        * tlist of the top plan node.  However, we can skip that if we
-                        * determined that whatever create_plan chose to return will be
-                        * good enough.
+                        * create_plan returns a plan with just a "flat" tlist of required
+                        * Vars.  Usually we need to insert the sub_tlist as the tlist of
+                        * the top plan node.  However, we can skip that if we determined
+                        * that whatever create_plan chose to return will be good enough.
                         */
                        if (need_tlist_eval)
                        {
@@ -1375,27 +1354,9 @@ grouping_planner(PlannerInfo *root, double tuple_fraction)
 
                                /*
                                 * Also, account for the cost of evaluation of the sub_tlist.
-                                *
-                                * Up to now, we have only been dealing with "flat" tlists,
-                                * containing just Vars.  So their evaluation cost is zero
-                                * according to the model used by cost_qual_eval() (or if you
-                                * prefer, the cost is factored into cpu_tuple_cost).  Thus we
-                                * can avoid accounting for tlist cost throughout
-                                * query_planner() and subroutines.  But now we've inserted a
-                                * tlist that might contain actual operators, sub-selects, etc
-                                * --- so we'd better account for its cost.
-                                *
-                                * Below this point, any tlist eval cost for added-on nodes
-                                * should be accounted for as we create those nodes.
-                                * Presently, of the node types we can add on, only Agg,
-                                * WindowAgg, and Group project new tlists (the rest just copy
-                                * their input tuples) --- so make_agg(), make_windowagg() and
-                                * make_group() are responsible for computing the added cost.
+                                * See comments for add_tlist_costs_to_plan() for more info.
                                 */
-                               cost_qual_eval(&tlist_cost, sub_tlist, root);
-                               result_plan->startup_cost += tlist_cost.startup;
-                               result_plan->total_cost += tlist_cost.startup +
-                                       tlist_cost.per_tuple * result_plan->plan_rows;
+                               add_tlist_costs_to_plan(root, result_plan, sub_tlist);
                        }
                        else
                        {
@@ -1566,7 +1527,7 @@ grouping_planner(PlannerInfo *root, double tuple_fraction)
                         *
                         * Note: it's essential here to use PVC_INCLUDE_AGGREGATES so that
                         * Vars mentioned only in aggregate expressions aren't pulled out
-                        * as separate targetlist entries.  Otherwise we could be putting
+                        * as separate targetlist entries.      Otherwise we could be putting
                         * ungrouped Vars directly into an Agg node's tlist, resulting in
                         * undefined behavior.
                         */
@@ -1835,6 +1796,61 @@ grouping_planner(PlannerInfo *root, double tuple_fraction)
        return result_plan;
 }
 
+/*
+ * add_tlist_costs_to_plan
+ *
+ * Estimate the execution costs associated with evaluating the targetlist
+ * expressions, and add them to the cost estimates for the Plan node.
+ *
+ * If the tlist contains set-returning functions, also inflate the Plan's cost
+ * and plan_rows estimates accordingly.  (Hence, this must be called *after*
+ * any logic that uses plan_rows to, eg, estimate qual evaluation costs.)
+ *
+ * Note: during initial stages of planning, we mostly consider plan nodes with
+ * "flat" tlists, containing just Vars.  So their evaluation cost is zero
+ * according to the model used by cost_qual_eval() (or if you prefer, the cost
+ * is factored into cpu_tuple_cost).  Thus we can avoid accounting for tlist
+ * cost throughout query_planner() and subroutines.  But once we apply a
+ * tlist that might contain actual operators, sub-selects, etc, we'd better
+ * account for its cost.  Any set-returning functions in the tlist must also
+ * affect the estimated rowcount.
+ *
+ * Once grouping_planner() has applied a general tlist to the topmost
+ * scan/join plan node, any tlist eval cost for added-on nodes should be
+ * accounted for as we create those nodes.  Presently, of the node types we
+ * can add on later, only Agg, WindowAgg, and Group project new tlists (the
+ * rest just copy their input tuples) --- so make_agg(), make_windowagg() and
+ * make_group() are responsible for calling this function to account for their
+ * tlist costs.
+ */
+void
+add_tlist_costs_to_plan(PlannerInfo *root, Plan *plan, List *tlist)
+{
+       QualCost        tlist_cost;
+       double          tlist_rows;
+
+       cost_qual_eval(&tlist_cost, tlist, root);
+       plan->startup_cost += tlist_cost.startup;
+       plan->total_cost += tlist_cost.startup +
+               tlist_cost.per_tuple * plan->plan_rows;
+
+       tlist_rows = tlist_returns_set_rows(tlist);
+       if (tlist_rows > 1)
+       {
+               /*
+                * We assume that execution costs of the tlist proper were all
+                * accounted for by cost_qual_eval.  However, it still seems
+                * appropriate to charge something more for the executor's general
+                * costs of processing the added tuples.  The cost is probably less
+                * than cpu_tuple_cost, though, so we arbitrarily use half of that.
+                */
+               plan->total_cost += plan->plan_rows * (tlist_rows - 1) *
+                       cpu_tuple_cost / 2;
+
+               plan->plan_rows *= tlist_rows;
+       }
+}
+
 /*
  * Detect whether a plan node is a "dummy" plan created when a relation
  * is deemed not to need scanning due to constraint exclusion.
@@ -2673,8 +2689,8 @@ make_subplanTargetList(PlannerInfo *root,
        }
 
        /*
-        * Otherwise, we must build a tlist containing all grouping columns,
-        * plus any other Vars mentioned in the targetlist and HAVING qual.
+        * Otherwise, we must build a tlist containing all grouping columns, plus
+        * any other Vars mentioned in the targetlist and HAVING qual.
         */
        sub_tlist = NIL;
        non_group_cols = NIL;
@@ -2725,8 +2741,8 @@ make_subplanTargetList(PlannerInfo *root,
                        else
                        {
                                /*
-                                * Non-grouping column, so just remember the expression
-                                * for later call to pull_var_clause.  There's no need for
+                                * Non-grouping column, so just remember the expression for
+                                * later call to pull_var_clause.  There's no need for
                                 * pull_var_clause to examine the TargetEntry node itself.
                                 */
                                non_group_cols = lappend(non_group_cols, tle->expr);
@@ -2753,7 +2769,7 @@ make_subplanTargetList(PlannerInfo *root,
         * add them to the result tlist if not already present.  (A Var used
         * directly as a GROUP BY item will be present already.)  Note this
         * includes Vars used in resjunk items, so we are covering the needs of
-        * ORDER BY and window specifications.  Vars used within Aggrefs will be
+        * ORDER BY and window specifications.  Vars used within Aggrefs will be
         * pulled out here, too.
         */
        non_group_vars = pull_var_clause((Node *) non_group_cols,
@@ -3289,7 +3305,7 @@ plan_cluster_use_sort(Oid tableOid, Oid indexOid)
        comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
 
        /* Estimate the cost of seq scan + sort */
-       seqScanPath = create_seqscan_path(root, rel);
+       seqScanPath = create_seqscan_path(root, rel, NULL);
        cost_sort(&seqScanAndSortPath, root, NIL,
                          seqScanPath->total_cost, rel->tuples, rel->width,
                          comparisonCost, maintenance_work_mem, -1.0);
@@ -3297,7 +3313,8 @@ plan_cluster_use_sort(Oid tableOid, Oid indexOid)
        /* Estimate the cost of index scan */
        indexScanPath = create_index_path(root, indexInfo,
                                                                          NIL, NIL, NIL, NIL, NIL,
-                                                                         ForwardScanDirection, false, NULL);
+                                                                         ForwardScanDirection, false,
+                                                                         NULL, 1.0);
 
        return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
 }