LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/plan - subselect.c (source / functions) Coverage Total Hit UBC GBC CBC
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 95.7 % 1072 1026 46 1 1025
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 40 40 40
Baseline: lcov-20260827-baseline Branches: 81.1 % 790 641 149 1 640
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 89.7 % 97 87 10 87
(360..) days: 96.3 % 974 938 36 1 937
Function coverage date bins:
(30,360] days: 100.0 % 4 4 4
(360..) days: 100.0 % 36 36 36
Branch coverage date bins:
(30,360] days: 80.2 % 91 73 18 73
(360..) days: 81.3 % 699 568 131 1 567

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * subselect.c
                                  4                 :                :  *    Planning routines for subselects.
                                  5                 :                :  *
                                  6                 :                :  * This module deals with SubLinks and CTEs, but not subquery RTEs (i.e.,
                                  7                 :                :  * not sub-SELECT-in-FROM cases).
                                  8                 :                :  *
                                  9                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                 10                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 11                 :                :  *
                                 12                 :                :  * IDENTIFICATION
                                 13                 :                :  *    src/backend/optimizer/plan/subselect.c
                                 14                 :                :  *
                                 15                 :                :  *-------------------------------------------------------------------------
                                 16                 :                :  */
                                 17                 :                : #include "postgres.h"
                                 18                 :                : 
                                 19                 :                : #include "access/htup_details.h"
                                 20                 :                : #include "catalog/pg_operator.h"
                                 21                 :                : #include "catalog/pg_type.h"
                                 22                 :                : #include "executor/executor.h"
                                 23                 :                : #include "executor/nodeSubplan.h"
                                 24                 :                : #include "miscadmin.h"
                                 25                 :                : #include "nodes/makefuncs.h"
                                 26                 :                : #include "nodes/nodeFuncs.h"
                                 27                 :                : #include "optimizer/clauses.h"
                                 28                 :                : #include "optimizer/cost.h"
                                 29                 :                : #include "optimizer/optimizer.h"
                                 30                 :                : #include "optimizer/paramassign.h"
                                 31                 :                : #include "optimizer/pathnode.h"
                                 32                 :                : #include "optimizer/planmain.h"
                                 33                 :                : #include "optimizer/planner.h"
                                 34                 :                : #include "optimizer/prep.h"
                                 35                 :                : #include "optimizer/subselect.h"
                                 36                 :                : #include "parser/parse_relation.h"
                                 37                 :                : #include "rewrite/rewriteManip.h"
                                 38                 :                : #include "utils/builtins.h"
                                 39                 :                : #include "utils/lsyscache.h"
                                 40                 :                : #include "utils/syscache.h"
                                 41                 :                : 
                                 42                 :                : 
                                 43                 :                : typedef struct convert_testexpr_context
                                 44                 :                : {
                                 45                 :                :     PlannerInfo *root;
                                 46                 :                :     List       *subst_nodes;    /* Nodes to substitute for Params */
                                 47                 :                : } convert_testexpr_context;
                                 48                 :                : 
                                 49                 :                : typedef struct process_sublinks_context
                                 50                 :                : {
                                 51                 :                :     PlannerInfo *root;
                                 52                 :                :     bool        isTopQual;
                                 53                 :                : } process_sublinks_context;
                                 54                 :                : 
                                 55                 :                : typedef struct finalize_primnode_context
                                 56                 :                : {
                                 57                 :                :     PlannerInfo *root;
                                 58                 :                :     Bitmapset  *paramids;       /* Non-local PARAM_EXEC paramids found */
                                 59                 :                : } finalize_primnode_context;
                                 60                 :                : 
                                 61                 :                : typedef struct inline_cte_walker_context
                                 62                 :                : {
                                 63                 :                :     const char *ctename;        /* name and relative level of target CTE */
                                 64                 :                :     int         levelsup;
                                 65                 :                :     Query      *ctequery;       /* query to substitute */
                                 66                 :                : } inline_cte_walker_context;
                                 67                 :                : 
                                 68                 :                : 
                                 69                 :                : static Node *build_subplan(PlannerInfo *root, Plan *plan, Path *path,
                                 70                 :                :                            PlannerInfo *subroot, List *plan_params,
                                 71                 :                :                            SubLinkType subLinkType, int subLinkId,
                                 72                 :                :                            Node *testexpr, List *testexpr_paramids,
                                 73                 :                :                            bool unknownEqFalse);
                                 74                 :                : static List *generate_subquery_params(PlannerInfo *root, List *tlist,
                                 75                 :                :                                       List **paramIds);
                                 76                 :                : static List *generate_subquery_vars(PlannerInfo *root, List *tlist,
                                 77                 :                :                                     Index varno);
                                 78                 :                : static Node *convert_testexpr(PlannerInfo *root,
                                 79                 :                :                               Node *testexpr,
                                 80                 :                :                               List *subst_nodes);
                                 81                 :                : static Node *convert_testexpr_mutator(Node *node,
                                 82                 :                :                                       convert_testexpr_context *context);
                                 83                 :                : static bool subplan_is_hashable(Plan *plan, bool unknownEqFalse);
                                 84                 :                : static bool subpath_is_hashable(Path *path, bool unknownEqFalse);
                                 85                 :                : static bool testexpr_is_hashable(Node *testexpr, List *param_ids);
                                 86                 :                : static bool test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids);
                                 87                 :                : static bool hash_ok_operator(OpExpr *expr);
                                 88                 :                : static bool contain_dml(Node *node);
                                 89                 :                : static bool contain_dml_walker(Node *node, void *context);
                                 90                 :                : static bool contain_outer_selfref(Node *node);
                                 91                 :                : static bool contain_outer_selfref_walker(Node *node, Index *depth);
                                 92                 :                : static void inline_cte(PlannerInfo *root, CommonTableExpr *cte);
                                 93                 :                : static bool inline_cte_walker(Node *node, inline_cte_walker_context *context);
                                 94                 :                : static bool sublink_testexpr_is_not_nullable(PlannerInfo *root, SubLink *sublink);
                                 95                 :                : static bool simplify_EXISTS_query(PlannerInfo *root, Query *query);
                                 96                 :                : static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
                                 97                 :                :                                     Node **testexpr, List **paramIds);
                                 98                 :                : static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root);
                                 99                 :                : static Node *process_sublinks_mutator(Node *node,
                                100                 :                :                                       process_sublinks_context *context);
                                101                 :                : static Bitmapset *finalize_plan(PlannerInfo *root,
                                102                 :                :                                 Plan *plan,
                                103                 :                :                                 int gather_param,
                                104                 :                :                                 Bitmapset *valid_params,
                                105                 :                :                                 Bitmapset *scan_params);
                                106                 :                : static bool finalize_primnode(Node *node, finalize_primnode_context *context);
                                107                 :                : static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context);
                                108                 :                : static const char *sublinktype_to_string(SubLinkType subLinkType);
                                109                 :                : 
                                110                 :                : 
                                111                 :                : /*
                                112                 :                :  * Get the datatype/typmod/collation of the first column of the plan's output.
                                113                 :                :  *
                                114                 :                :  * This information is stored for ARRAY_SUBLINK execution and for
                                115                 :                :  * exprType()/exprTypmod()/exprCollation(), which have no way to get at the
                                116                 :                :  * plan associated with a SubPlan node.  We really only need the info for
                                117                 :                :  * EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency we save it
                                118                 :                :  * always.
                                119                 :                :  */
                                120                 :                : static void
 5606 tgl@sss.pgh.pa.us         121                 :CBC       32205 : get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod,
                                122                 :                :                    Oid *colcollation)
                                123                 :                : {
                                124                 :                :     /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
 6587                           125         [ +  + ]:          32205 :     if (plan->targetlist)
                                126                 :                :     {
 3426                           127                 :          30191 :         TargetEntry *tent = linitial_node(TargetEntry, plan->targetlist);
                                128                 :                : 
 6587                           129         [ +  - ]:          30191 :         if (!tent->resjunk)
                                130                 :                :         {
 6379                           131                 :          30191 :             *coltype = exprType((Node *) tent->expr);
                                132                 :          30191 :             *coltypmod = exprTypmod((Node *) tent->expr);
 5679 peter_e@gmx.net           133                 :          30191 :             *colcollation = exprCollation((Node *) tent->expr);
 6379 tgl@sss.pgh.pa.us         134                 :          30191 :             return;
                                135                 :                :         }
                                136                 :                :     }
                                137                 :           2014 :     *coltype = VOIDOID;
                                138                 :           2014 :     *coltypmod = -1;
 5679 peter_e@gmx.net           139                 :           2014 :     *colcollation = InvalidOid;
                                140                 :                : }
                                141                 :                : 
                                142                 :                : /*
                                143                 :                :  * Convert a SubLink (as created by the parser) into a SubPlan.
                                144                 :                :  *
                                145                 :                :  * We are given the SubLink's contained query, type, ID, and testexpr.  We are
                                146                 :                :  * also told if this expression appears at top level of a WHERE/HAVING qual.
                                147                 :                :  *
                                148                 :                :  * Note: we assume that the testexpr has been AND/OR flattened (actually,
                                149                 :                :  * it's been through eval_const_expressions), but not converted to
                                150                 :                :  * implicit-AND form; and any SubLinks in it should already have been
                                151                 :                :  * converted to SubPlans.  The subquery is as yet untouched, however.
                                152                 :                :  *
                                153                 :                :  * The result is whatever we need to substitute in place of the SubLink node
                                154                 :                :  * in the executable expression.  If we're going to do the subplan as a
                                155                 :                :  * regular subplan, this will be the constructed SubPlan node.  If we're going
                                156                 :                :  * to do the subplan as an InitPlan, the SubPlan node instead goes into
                                157                 :                :  * root->init_plans, and what we return here is an expression tree
                                158                 :                :  * representing the InitPlan's result: usually just a Param node representing
                                159                 :                :  * a single scalar result, but possibly a row comparison tree containing
                                160                 :                :  * multiple Param nodes, or for a MULTIEXPR subquery a simple NULL constant
                                161                 :                :  * (since the real output Params are elsewhere in the tree, and the MULTIEXPR
                                162                 :                :  * subquery itself is in a resjunk tlist entry whose value is uninteresting).
                                163                 :                :  */
                                164                 :                : static Node *
 4453 tgl@sss.pgh.pa.us         165                 :          28750 : make_subplan(PlannerInfo *root, Query *orig_subquery,
                                166                 :                :              SubLinkType subLinkType, int subLinkId,
                                167                 :                :              Node *testexpr, bool isTopQual)
                                168                 :                : {
                                169                 :                :     Query      *subquery;
 6579                           170                 :          28750 :     bool        simple_exists = false;
                                171                 :                :     double      tuple_fraction;
                                172                 :                :     PlannerInfo *subroot;
                                173                 :                :     RelOptInfo *final_rel;
                                174                 :                :     Path       *best_path;
                                175                 :                :     Plan       *plan;
                                176                 :                :     List       *plan_params;
                                177                 :                :     Node       *result;
  324 rhaas@postgresql.org      178                 :          28750 :     const char *sublinkstr = sublinktype_to_string(subLinkType);
                                179                 :                : 
                                180                 :                :     /*
                                181                 :                :      * Copy the source Query node.  This is a quick and dirty kluge to resolve
                                182                 :                :      * the fact that the parser can generate trees with multiple links to the
                                183                 :                :      * same sub-Query node, but the planner wants to scribble on the Query.
                                184                 :                :      * Try to clean this up when we do querytree redesign...
                                185                 :                :      */
 3458 peter_e@gmx.net           186                 :          28750 :     subquery = copyObject(orig_subquery);
                                187                 :                : 
                                188                 :                :     /*
                                189                 :                :      * If it's an EXISTS subplan, we might be able to simplify it.
                                190                 :                :      */
 6579 tgl@sss.pgh.pa.us         191         [ +  + ]:          28750 :     if (subLinkType == EXISTS_SUBLINK)
 4296                           192                 :           1776 :         simple_exists = simplify_EXISTS_query(root, subquery);
                                193                 :                : 
                                194                 :                :     /*
                                195                 :                :      * For an EXISTS subplan, tell lower-level planner to expect that only the
                                196                 :                :      * first tuple will be retrieved.  For ALL and ANY subplans, we will be
                                197                 :                :      * able to stop evaluating if the test condition fails or matches, so very
                                198                 :                :      * often not all the tuples will be retrieved; for lack of a better idea,
                                199                 :                :      * specify 50% retrieval.  For EXPR, MULTIEXPR, and ROWCOMPARE subplans,
                                200                 :                :      * use default behavior (we're only expecting one row out, anyway).
                                201                 :                :      *
                                202                 :                :      * NOTE: if you change these numbers, also change cost_subplan() in
                                203                 :                :      * path/costsize.c.
                                204                 :                :      *
                                205                 :                :      * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
                                206                 :                :      * its output.  In that case it would've been better to specify full
                                207                 :                :      * retrieval.  At present, however, we can only check hashability after
                                208                 :                :      * we've made the subplan :-(.  (Determining whether it'll fit in hash_mem
                                209                 :                :      * is the really hard part.)  Therefore, we don't want to be too
                                210                 :                :      * optimistic about the percentage of tuples retrieved, for fear of
                                211                 :                :      * selecting a plan that's bad for the materialization case.
                                212                 :                :      */
 6579                           213         [ +  + ]:          28750 :     if (subLinkType == EXISTS_SUBLINK)
 9690                           214                 :           1776 :         tuple_fraction = 1.0;   /* just like a LIMIT 1 */
 6579                           215   [ +  +  +  + ]:          26974 :     else if (subLinkType == ALL_SUBLINK ||
                                216                 :                :              subLinkType == ANY_SUBLINK)
 9690                           217                 :            523 :         tuple_fraction = 0.5;   /* 50% */
                                218                 :                :     else
 8571                           219                 :          26451 :         tuple_fraction = 0.0;   /* default behavior */
                                220                 :                : 
                                221                 :                :     /* plan_params should not be in use in current query level */
 5104                           222         [ -  + ]:          28750 :     Assert(root->plan_params == NIL);
                                223                 :                : 
                                224                 :                :     /* Generate Paths for the subquery */
  324 rhaas@postgresql.org      225                 :          28750 :     subroot = subquery_planner(root->glob, subquery,
                                226                 :                :                                choose_plan_name(root->glob, sublinkstr, true),
                                227                 :                :                                root, NULL, false, tuple_fraction, NULL);
                                228                 :                : 
                                229                 :                :     /* Isolate the params needed by this specific subplan */
 5104 tgl@sss.pgh.pa.us         230                 :          28750 :     plan_params = root->plan_params;
                                231                 :          28750 :     root->plan_params = NIL;
                                232                 :                : 
                                233                 :                :     /*
                                234                 :                :      * Select best Path and turn it into a Plan.  At least for now, there
                                235                 :                :      * seems no reason to postpone doing that.
                                236                 :                :      */
 3825                           237                 :          28750 :     final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
                                238                 :          28750 :     best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
                                239                 :                : 
                                240                 :          28750 :     plan = create_plan(subroot, best_path);
                                241                 :                : 
                                242                 :                :     /* And convert to SubPlan or InitPlan format. */
  884                           243                 :          28750 :     result = build_subplan(root, plan, best_path,
                                244                 :                :                            subroot, plan_params,
                                245                 :                :                            subLinkType, subLinkId,
                                246                 :                :                            testexpr, NIL, isTopQual);
                                247                 :                : 
                                248                 :                :     /*
                                249                 :                :      * If it's a correlated EXISTS with an unimportant targetlist, we might be
                                250                 :                :      * able to transform it to the equivalent of an IN and then implement it
                                251                 :                :      * by hashing.  We don't have enough information yet to tell which way is
                                252                 :                :      * likely to be better (it depends on the expected number of executions of
                                253                 :                :      * the EXISTS qual, and we are much too early in planning the outer query
                                254                 :                :      * to be able to guess that).  So we generate both plans, if possible, and
                                255                 :                :      * leave it to setrefs.c to decide which to use.
                                256                 :                :      */
 6579                           257   [ +  +  +  + ]:          28750 :     if (simple_exists && IsA(result, SubPlan))
                                258                 :                :     {
                                259                 :                :         Node       *newtestexpr;
                                260                 :                :         List       *paramIds;
                                261                 :                : 
                                262                 :                :         /* Make a second copy of the original subquery */
 3458 peter_e@gmx.net           263                 :           1532 :         subquery = copyObject(orig_subquery);
                                264                 :                :         /* and re-simplify */
 4296 tgl@sss.pgh.pa.us         265                 :           1532 :         simple_exists = simplify_EXISTS_query(root, subquery);
 6579                           266         [ -  + ]:           1532 :         Assert(simple_exists);
                                267                 :                :         /* See if it can be converted to an ANY query */
                                268                 :           1532 :         subquery = convert_EXISTS_to_ANY(root, subquery,
                                269                 :                :                                          &newtestexpr, &paramIds);
                                270         [ +  + ]:           1532 :         if (subquery)
                                271                 :                :         {
                                272                 :                :             char       *plan_name;
                                273                 :                : 
                                274                 :                :             /*
                                275                 :                :              * Generate Paths for the ANY subquery; we'll need all rows. Use a
                                276                 :                :              * distinct prefix for this user-visible name, since this is an
                                277                 :                :              * ANY implementation of the original EXISTS subplan.
                                278                 :                :              */
   12 fujii@postgresql.org      279                 :           1278 :             plan_name = choose_plan_name(root->glob, "exists_to_any", true);
  324 rhaas@postgresql.org      280                 :           1278 :             subroot = subquery_planner(root->glob, subquery, plan_name,
                                281                 :                :                                        root, subroot, false, 0.0, NULL);
                                282                 :                : 
                                283                 :                :             /* Isolate the params needed by this specific subplan */
 5104 tgl@sss.pgh.pa.us         284                 :           1278 :             plan_params = root->plan_params;
                                285                 :           1278 :             root->plan_params = NIL;
                                286                 :                : 
                                287                 :                :             /* Select best Path */
 3825                           288                 :           1278 :             final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
                                289                 :           1278 :             best_path = final_rel->cheapest_total_path;
                                290                 :                : 
                                291                 :                :             /* Now we can check if it'll fit in hash_mem */
  298                           292         [ +  + ]:           1278 :             if (subpath_is_hashable(best_path, true))
                                293                 :                :             {
                                294                 :                :                 SubPlan    *hashplan;
                                295                 :                :                 AlternativeSubPlan *asplan;
                                296                 :                : 
                                297                 :                :                 /* OK, finish planning the ANY subquery */
 2160                           298                 :           1273 :                 plan = create_plan(subroot, best_path);
                                299                 :                : 
                                300                 :                :                 /* ... and convert to SubPlan format */
 3474 peter_e@gmx.net           301                 :           1273 :                 hashplan = castNode(SubPlan,
                                302                 :                :                                     build_subplan(root, plan, best_path,
                                303                 :                :                                                   subroot, plan_params,
                                304                 :                :                                                   ANY_SUBLINK, 0,
                                305                 :                :                                                   newtestexpr,
                                306                 :                :                                                   paramIds,
                                307                 :                :                                                   true));
                                308                 :                :                 /* Check we got what we expected */
 6579 tgl@sss.pgh.pa.us         309         [ -  + ]:           1273 :                 Assert(hashplan->parParam == NIL);
                                310         [ -  + ]:           1273 :                 Assert(hashplan->useHashTable);
                                311                 :                : 
                                312                 :                :                 /* Leave it to setrefs.c to decide which plan to use */
                                313                 :           1273 :                 asplan = makeNode(AlternativeSubPlan);
                                314                 :           1273 :                 asplan->subplans = list_make2(result, hashplan);
                                315                 :           1273 :                 result = (Node *) asplan;
 2160                           316                 :           1273 :                 root->hasAlternativeSubPlans = true;
                                317                 :                :             }
                                318                 :                :         }
                                319                 :                :     }
                                320                 :                : 
 6579                           321                 :          28750 :     return result;
                                322                 :                : }
                                323                 :                : 
                                324                 :                : /*
                                325                 :                :  * Build a SubPlan node given the raw inputs --- subroutine for make_subplan
                                326                 :                :  *
                                327                 :                :  * Returns either the SubPlan, or a replacement expression if we decide to
                                328                 :                :  * make it an InitPlan, as explained in the comments for make_subplan.
                                329                 :                :  */
                                330                 :                : static Node *
  884                           331                 :          30023 : build_subplan(PlannerInfo *root, Plan *plan, Path *path,
                                332                 :                :               PlannerInfo *subroot, List *plan_params,
                                333                 :                :               SubLinkType subLinkType, int subLinkId,
                                334                 :                :               Node *testexpr, List *testexpr_paramids,
                                335                 :                :               bool unknownEqFalse)
                                336                 :                : {
                                337                 :                :     Node       *result;
                                338                 :                :     SubPlan    *splan;
                                339                 :                :     ListCell   *lc;
                                340                 :                : 
                                341                 :                :     /*
                                342                 :                :      * Initialize the SubPlan node.
                                343                 :                :      *
                                344                 :                :      * Note: plan_id and cost fields are set further down.
                                345                 :                :      */
 7121                           346                 :          30023 :     splan = makeNode(SubPlan);
 6579                           347                 :          30023 :     splan->subLinkType = subLinkType;
  324 rhaas@postgresql.org      348                 :          30023 :     splan->plan_name = subroot->plan_name;
 7121 tgl@sss.pgh.pa.us         349                 :          30023 :     splan->testexpr = NULL;
                                350                 :          30023 :     splan->paramIds = NIL;
 5606                           351                 :          30023 :     get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
                                352                 :                :                        &splan->firstColCollation);
 7121                           353                 :          30023 :     splan->useHashTable = false;
 6579                           354                 :          30023 :     splan->unknownEqFalse = unknownEqFalse;
 3424                           355                 :          30023 :     splan->parallel_safe = plan->parallel_safe;
 7121                           356                 :          30023 :     splan->setParam = NIL;
                                357                 :          30023 :     splan->parParam = NIL;
                                358                 :          30023 :     splan->args = NIL;
                                359                 :                : 
                                360                 :                :     /*
                                361                 :                :      * Make parParam and args lists of param IDs and expressions that current
                                362                 :                :      * query level will pass to this child plan.
                                363                 :                :      */
 5104                           364   [ +  +  +  +  :          64716 :     foreach(lc, plan_params)
                                              +  + ]
                                365                 :                :     {
                                366                 :          34693 :         PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
                                367                 :          34693 :         Node       *arg = pitem->item;
                                368                 :                : 
                                369                 :                :         /*
                                370                 :                :          * The Var, PlaceHolderVar, Aggref, GroupingFunc, or ReturningExpr has
                                371                 :                :          * already been adjusted to have the correct varlevelsup, phlevelsup,
                                372                 :                :          * agglevelsup, or retlevelsup.
                                373                 :                :          *
                                374                 :                :          * If it's a PlaceHolderVar, Aggref, GroupingFunc, or ReturningExpr,
                                375                 :                :          * its arguments might contain SubLinks, which have not yet been
                                376                 :                :          * processed (see the comments for SS_replace_correlation_vars).  Do
                                377                 :                :          * that now.
                                378                 :                :          */
                                379         [ +  + ]:          34693 :         if (IsA(arg, PlaceHolderVar) ||
 1620                           380         [ +  + ]:          34683 :             IsA(arg, Aggref) ||
  588 dean.a.rasheed@gmail      381         [ +  + ]:          34626 :             IsA(arg, GroupingFunc) ||
                                382         [ +  + ]:          34569 :             IsA(arg, ReturningExpr))
 5104 tgl@sss.pgh.pa.us         383                 :            139 :             arg = SS_process_sublinks(root, arg, false);
                                384                 :                : 
                                385                 :          34693 :         splan->parParam = lappend_int(splan->parParam, pitem->paramId);
                                386                 :          34693 :         splan->args = lappend(splan->args, arg);
                                387                 :                :     }
                                388                 :                : 
                                389                 :                :     /*
                                390                 :                :      * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY,
                                391                 :                :      * ROWCOMPARE, or MULTIEXPR types can be used as initPlans.  For EXISTS,
                                392                 :                :      * EXPR, or ARRAY, we return a Param referring to the result of evaluating
                                393                 :                :      * the initPlan.  For ROWCOMPARE, we must modify the testexpr tree to
                                394                 :                :      * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted
                                395                 :                :      * by the parser, and then return that tree.  For MULTIEXPR, we return a
                                396                 :                :      * null constant: the resjunk targetlist item containing the SubLink does
                                397                 :                :      * not need to return anything useful, since the referencing Params are
                                398                 :                :      * elsewhere.
                                399                 :                :      */
 6579                           400   [ +  +  +  + ]:          30023 :     if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
 9782                           401                 :            222 :     {
                                402                 :                :         Param      *prm;
                                403                 :                : 
 6579                           404         [ -  + ]:            222 :         Assert(testexpr == NULL);
 2785                           405                 :            222 :         prm = generate_new_exec_param(root, BOOLOID, -1, InvalidOid);
 7121                           406                 :            222 :         splan->setParam = list_make1_int(prm->paramid);
  324 rhaas@postgresql.org      407                 :            222 :         splan->isInitPlan = true;
 9782 tgl@sss.pgh.pa.us         408                 :            222 :         result = (Node *) prm;
                                409                 :                :     }
 6579                           410   [ +  +  +  + ]:          29801 :     else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
 9782                           411                 :           6791 :     {
 8128 neilc@samurai.com         412                 :           6791 :         TargetEntry *te = linitial(plan->targetlist);
                                413                 :                :         Param      *prm;
                                414                 :                : 
 7813 tgl@sss.pgh.pa.us         415         [ -  + ]:           6791 :         Assert(!te->resjunk);
 6579                           416         [ -  + ]:           6791 :         Assert(testexpr == NULL);
 2785                           417                 :           6791 :         prm = generate_new_exec_param(root,
                                418                 :           6791 :                                       exprType((Node *) te->expr),
                                419                 :           6791 :                                       exprTypmod((Node *) te->expr),
                                420                 :           6791 :                                       exprCollation((Node *) te->expr));
 7121                           421                 :           6791 :         splan->setParam = list_make1_int(prm->paramid);
  324 rhaas@postgresql.org      422                 :           6791 :         splan->isInitPlan = true;
 9782 tgl@sss.pgh.pa.us         423                 :           6791 :         result = (Node *) prm;
                                424                 :                :     }
 6579                           425   [ +  +  +  + ]:          23010 :     else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
 8542                           426                 :             92 :     {
 8128 neilc@samurai.com         427                 :             92 :         TargetEntry *te = linitial(plan->targetlist);
                                428                 :                :         Oid         arraytype;
                                429                 :                :         Param      *prm;
                                430                 :                : 
 7813 tgl@sss.pgh.pa.us         431         [ -  + ]:             92 :         Assert(!te->resjunk);
 6579                           432         [ -  + ]:             92 :         Assert(testexpr == NULL);
 4293                           433                 :             92 :         arraytype = get_promoted_array_type(exprType((Node *) te->expr));
 8542                           434         [ -  + ]:             92 :         if (!OidIsValid(arraytype))
 8434 tgl@sss.pgh.pa.us         435         [ #  # ]:UBC           0 :             elog(ERROR, "could not find array type for datatype %s",
                                436                 :                :                  format_type_be(exprType((Node *) te->expr)));
 2785 tgl@sss.pgh.pa.us         437                 :CBC          92 :         prm = generate_new_exec_param(root,
                                438                 :                :                                       arraytype,
                                439                 :             92 :                                       exprTypmod((Node *) te->expr),
                                440                 :             92 :                                       exprCollation((Node *) te->expr));
 7121                           441                 :             92 :         splan->setParam = list_make1_int(prm->paramid);
  324 rhaas@postgresql.org      442                 :             92 :         splan->isInitPlan = true;
 8542 tgl@sss.pgh.pa.us         443                 :             92 :         result = (Node *) prm;
                                444                 :                :     }
 6579                           445   [ +  +  +  + ]:          22918 :     else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
10422 vadim4o@yahoo.com         446                 :             15 :     {
                                447                 :                :         /* Adjust the Params */
                                448                 :                :         List       *params;
                                449                 :                : 
 6579 tgl@sss.pgh.pa.us         450         [ -  + ]:             15 :         Assert(testexpr != NULL);
 6797                           451                 :             15 :         params = generate_subquery_params(root,
                                452                 :                :                                           plan->targetlist,
                                453                 :                :                                           &splan->paramIds);
 7129                           454                 :             15 :         result = convert_testexpr(root,
                                455                 :                :                                   testexpr,
                                456                 :                :                                   params);
 7121                           457                 :             15 :         splan->setParam = list_copy(splan->paramIds);
  324 rhaas@postgresql.org      458                 :             15 :         splan->isInitPlan = true;
                                459                 :                : 
                                460                 :                :         /*
                                461                 :                :          * The executable expression is returned to become part of the outer
                                462                 :                :          * plan's expression tree; it is not kept in the initplan node.
                                463                 :                :          */
                                464                 :                :     }
 4453 tgl@sss.pgh.pa.us         465         [ +  + ]:          22903 :     else if (subLinkType == MULTIEXPR_SUBLINK)
                                466                 :                :     {
                                467                 :                :         /*
                                468                 :                :          * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param
                                469                 :                :          * for each output column.
                                470                 :                :          */
                                471                 :                :         List       *params;
                                472                 :                : 
                                473         [ -  + ]:            108 :         Assert(testexpr == NULL);
                                474                 :            108 :         params = generate_subquery_params(root,
                                475                 :                :                                           plan->targetlist,
                                476                 :                :                                           &splan->setParam);
                                477                 :                : 
                                478                 :                :         /*
                                479                 :                :          * Save the list of replacement Params in the n'th cell of
                                480                 :                :          * root->multiexpr_params; setrefs.c will use it to replace
                                481                 :                :          * PARAM_MULTIEXPR Params.
                                482                 :                :          */
                                483         [ +  + ]:            216 :         while (list_length(root->multiexpr_params) < subLinkId)
                                484                 :            108 :             root->multiexpr_params = lappend(root->multiexpr_params, NIL);
                                485                 :            108 :         lc = list_nth_cell(root->multiexpr_params, subLinkId - 1);
                                486         [ -  + ]:            108 :         Assert(lfirst(lc) == NIL);
                                487                 :            108 :         lfirst(lc) = params;
                                488                 :                : 
                                489                 :                :         /* It can be an initplan if there are no parParams. */
                                490         [ +  + ]:            108 :         if (splan->parParam == NIL)
                                491                 :                :         {
  324 rhaas@postgresql.org      492                 :             25 :             splan->isInitPlan = true;
 4453 tgl@sss.pgh.pa.us         493                 :             25 :             result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid);
                                494                 :                :         }
                                495                 :                :         else
                                496                 :                :         {
  324 rhaas@postgresql.org      497                 :             83 :             splan->isInitPlan = false;
 4453 tgl@sss.pgh.pa.us         498                 :             83 :             result = (Node *) splan;
                                499                 :                :         }
                                500                 :                :     }
                                501                 :                :     else
                                502                 :                :     {
                                503                 :                :         /*
                                504                 :                :          * Adjust the Params in the testexpr, unless caller already took care
                                505                 :                :          * of it (as indicated by passing a list of Param IDs).
                                506                 :                :          */
 2204                           507   [ +  +  +  + ]:          22795 :         if (testexpr && testexpr_paramids == NIL)
 6622                           508                 :            533 :         {
                                509                 :                :             List       *params;
                                510                 :                : 
                                511                 :            533 :             params = generate_subquery_params(root,
                                512                 :                :                                               plan->targetlist,
                                513                 :                :                                               &splan->paramIds);
                                514                 :            533 :             splan->testexpr = convert_testexpr(root,
                                515                 :                :                                                testexpr,
                                516                 :                :                                                params);
                                517                 :                :         }
                                518                 :                :         else
                                519                 :                :         {
 6579                           520                 :          22262 :             splan->testexpr = testexpr;
 2204                           521                 :          22262 :             splan->paramIds = testexpr_paramids;
                                522                 :                :         }
                                523                 :                : 
                                524                 :                :         /*
                                525                 :                :          * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
                                526                 :                :          * initPlans, even when they are uncorrelated or undirect correlated,
                                527                 :                :          * because we need to scan the output of the subplan for each outer
                                528                 :                :          * tuple.  But if it's a not-direct-correlated IN (= ANY) test, we
                                529                 :                :          * might be able to use a hashtable to avoid comparing all the tuples.
                                530                 :                :          */
 6579                           531         [ +  + ]:          22795 :         if (subLinkType == ANY_SUBLINK &&
                                532   [ +  +  +  + ]:           3476 :             splan->parParam == NIL &&
  298                           533         [ +  + ]:           3385 :             subplan_is_hashable(plan, unknownEqFalse) &&
 2204                           534                 :           1690 :             testexpr_is_hashable(splan->testexpr, splan->paramIds))
 7121                           535                 :           1665 :             splan->useHashTable = true;
                                536                 :                : 
                                537                 :                :         /*
                                538                 :                :          * Otherwise, we have the option to tack a Material node onto the top
                                539                 :                :          * of the subplan, to reduce the cost of reading it repeatedly.  This
                                540                 :                :          * is pointless for a direct-correlated subplan, since we'd have to
                                541                 :                :          * recompute its results each time anyway.  For uncorrelated/undirect
                                542                 :                :          * correlated subplans, we add Material unless the subplan's top plan
                                543                 :                :          * node would materialize its output anyway.  Also, if enable_material
                                544                 :                :          * is false, then the user does not want us to materialize anything
                                545                 :                :          * unnecessarily, so we don't.
                                546                 :                :          */
 5974 rhaas@postgresql.org      547   [ +  +  +  - ]:          21130 :         else if (splan->parParam == NIL && enable_material &&
 6193 tgl@sss.pgh.pa.us         548         [ +  - ]:             45 :                  !ExecMaterializesOutput(nodeTag(plan)))
                                549                 :             45 :             plan = materialize_finished_plan(plan);
                                550                 :                : 
 7121                           551                 :          22795 :         result = (Node *) splan;
  324 rhaas@postgresql.org      552                 :          22795 :         splan->isInitPlan = false;
                                553                 :                :     }
                                554                 :                : 
                                555                 :                :     /*
                                556                 :                :      * Add the subplan, its path, and its PlannerInfo to the global lists.
                                557                 :                :      */
 6579 tgl@sss.pgh.pa.us         558                 :          30023 :     root->glob->subplans = lappend(root->glob->subplans, plan);
  884                           559                 :          30023 :     root->glob->subpaths = lappend(root->glob->subpaths, path);
 5472                           560                 :          30023 :     root->glob->subroots = lappend(root->glob->subroots, subroot);
 7121                           561                 :          30023 :     splan->plan_id = list_length(root->glob->subplans);
                                562                 :                : 
  324 rhaas@postgresql.org      563         [ +  + ]:          30023 :     if (splan->isInitPlan)
 7121 tgl@sss.pgh.pa.us         564                 :           7145 :         root->init_plans = lappend(root->init_plans, splan);
                                565                 :                : 
                                566                 :                :     /*
                                567                 :                :      * A parameterless subplan (not initplan) should be prepared to handle
                                568                 :                :      * REWIND efficiently.  If it has direct parameters then there's no point
                                569                 :                :      * since it'll be reset on each scan anyway; and if it's an initplan then
                                570                 :                :      * there's no point since it won't get re-run without parameter changes
                                571                 :                :      * anyway.  The input of a hashed subplan doesn't need REWIND either.
                                572                 :                :      */
  324 rhaas@postgresql.org      573   [ +  +  +  +  :          30023 :     if (splan->parParam == NIL && !splan->isInitPlan && !splan->useHashTable)
                                              +  + ]
 7121 tgl@sss.pgh.pa.us         574                 :             45 :         root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
                                575                 :                :                                                    splan->plan_id);
                                576                 :                : 
                                577                 :                :     /* Lastly, fill in the cost estimates for use later */
 6579                           578                 :          30023 :     cost_subplan(root, splan, plan);
                                579                 :                : 
 8675                           580                 :          30023 :     return result;
                                581                 :                : }
                                582                 :                : 
                                583                 :                : /*
                                584                 :                :  * generate_subquery_params: build a list of Params representing the output
                                585                 :                :  * columns of a sublink's sub-select, given the sub-select's targetlist.
                                586                 :                :  *
                                587                 :                :  * We also return an integer list of the paramids of the Params.
                                588                 :                :  */
                                589                 :                : static List *
 6797                           590                 :            656 : generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
                                591                 :                : {
                                592                 :                :     List       *result;
                                593                 :                :     List       *ids;
                                594                 :                :     ListCell   *lc;
                                595                 :                : 
                                596                 :            656 :     result = ids = NIL;
                                597   [ +  -  +  +  :           1531 :     foreach(lc, tlist)
                                              +  + ]
                                598                 :                :     {
                                599                 :            875 :         TargetEntry *tent = (TargetEntry *) lfirst(lc);
                                600                 :                :         Param      *param;
                                601                 :                : 
                                602         [ +  + ]:            875 :         if (tent->resjunk)
                                603                 :             10 :             continue;
                                604                 :                : 
 2785                           605                 :            865 :         param = generate_new_exec_param(root,
                                606                 :            865 :                                         exprType((Node *) tent->expr),
                                607                 :            865 :                                         exprTypmod((Node *) tent->expr),
                                608                 :            865 :                                         exprCollation((Node *) tent->expr));
 6797                           609                 :            865 :         result = lappend(result, param);
                                610                 :            865 :         ids = lappend_int(ids, param->paramid);
                                611                 :                :     }
                                612                 :                : 
                                613                 :            656 :     *paramIds = ids;
                                614                 :            656 :     return result;
                                615                 :                : }
                                616                 :                : 
                                617                 :                : /*
                                618                 :                :  * generate_subquery_vars: build a list of Vars representing the output
                                619                 :                :  * columns of a sublink's sub-select, given the sub-select's targetlist.
                                620                 :                :  * The Vars have the specified varno (RTE index).
                                621                 :                :  */
                                622                 :                : static List *
                                623                 :           3684 : generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
                                624                 :                : {
                                625                 :                :     List       *result;
                                626                 :                :     ListCell   *lc;
                                627                 :                : 
                                628                 :           3684 :     result = NIL;
                                629   [ +  -  +  +  :           7449 :     foreach(lc, tlist)
                                              +  + ]
                                630                 :                :     {
                                631                 :           3765 :         TargetEntry *tent = (TargetEntry *) lfirst(lc);
                                632                 :                :         Var        *var;
                                633                 :                : 
                                634         [ -  + ]:           3765 :         if (tent->resjunk)
 6797 tgl@sss.pgh.pa.us         635                 :UBC           0 :             continue;
                                636                 :                : 
 5844 peter_e@gmx.net           637                 :CBC        3765 :         var = makeVarFromTargetEntry(varno, tent);
 6797 tgl@sss.pgh.pa.us         638                 :           3765 :         result = lappend(result, var);
                                639                 :                :     }
                                640                 :                : 
                                641                 :           3684 :     return result;
                                642                 :                : }
                                643                 :                : 
                                644                 :                : /*
                                645                 :                :  * convert_testexpr: convert the testexpr given by the parser into
                                646                 :                :  * actually executable form.  This entails replacing PARAM_SUBLINK Params
                                647                 :                :  * with Params or Vars representing the results of the sub-select.  The
                                648                 :                :  * nodes to be substituted are passed in as the List result from
                                649                 :                :  * generate_subquery_params or generate_subquery_vars.
                                650                 :                :  */
                                651                 :                : static Node *
 7129                           652                 :           4462 : convert_testexpr(PlannerInfo *root,
                                653                 :                :                  Node *testexpr,
                                654                 :                :                  List *subst_nodes)
                                655                 :                : {
                                656                 :                :     convert_testexpr_context context;
                                657                 :                : 
                                658                 :           4462 :     context.root = root;
 6797                           659                 :           4462 :     context.subst_nodes = subst_nodes;
                                660                 :           4462 :     return convert_testexpr_mutator(testexpr, &context);
                                661                 :                : }
                                662                 :                : 
                                663                 :                : static Node *
 7547                           664                 :          21555 : convert_testexpr_mutator(Node *node,
                                665                 :                :                          convert_testexpr_context *context)
                                666                 :                : {
                                667         [ +  + ]:          21555 :     if (node == NULL)
                                668                 :             77 :         return NULL;
                                669         [ +  + ]:          21478 :     if (IsA(node, Param))
                                670                 :                :     {
 7267 bruce@momjian.us          671                 :           4660 :         Param      *param = (Param *) node;
                                672                 :                : 
 7547 tgl@sss.pgh.pa.us         673         [ +  + ]:           4660 :         if (param->paramkind == PARAM_SUBLINK)
                                674                 :                :         {
 6797                           675   [ +  -  -  + ]:           9310 :             if (param->paramid <= 0 ||
                                676                 :           4655 :                 param->paramid > list_length(context->subst_nodes))
 7547 tgl@sss.pgh.pa.us         677         [ #  # ]:UBC           0 :                 elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
                                678                 :                : 
                                679                 :                :             /*
                                680                 :                :              * We copy the list item to avoid having doubly-linked
                                681                 :                :              * substructure in the modified parse tree.  This is probably
                                682                 :                :              * unnecessary when it's a Param, but be safe.
                                683                 :                :              */
 6797 tgl@sss.pgh.pa.us         684                 :CBC        4655 :             return (Node *) copyObject(list_nth(context->subst_nodes,
                                685                 :                :                                                 param->paramid - 1));
                                686                 :                :         }
                                687                 :                :     }
 4643                           688         [ +  + ]:          16823 :     if (IsA(node, SubLink))
                                689                 :                :     {
                                690                 :                :         /*
                                691                 :                :          * If we come across a nested SubLink, it is neither necessary nor
                                692                 :                :          * correct to recurse into it: any PARAM_SUBLINKs we might find inside
                                693                 :                :          * belong to the inner SubLink not the outer. So just return it as-is.
                                694                 :                :          *
                                695                 :                :          * This reasoning depends on the assumption that nothing will pull
                                696                 :                :          * subexpressions into or out of the testexpr field of a SubLink, at
                                697                 :                :          * least not without replacing PARAM_SUBLINKs first.  If we did want
                                698                 :                :          * to do that we'd need to rethink the parser-output representation
                                699                 :                :          * altogether, since currently PARAM_SUBLINKs are only unique per
                                700                 :                :          * SubLink not globally across the query.  The whole point of
                                701                 :                :          * replacing them with Vars or PARAM_EXEC nodes is to make them
                                702                 :                :          * globally unique before they escape from the SubLink's testexpr.
                                703                 :                :          *
                                704                 :                :          * Note: this can't happen when called during SS_process_sublinks,
                                705                 :                :          * because that recursively processes inner SubLinks first.  It can
                                706                 :                :          * happen when called from convert_ANY_sublink_to_join, though.
                                707                 :                :          */
                                708                 :             10 :         return node;
                                709                 :                :     }
  637 peter@eisentraut.org      710                 :          16813 :     return expression_tree_mutator(node, convert_testexpr_mutator, context);
                                711                 :                : }
                                712                 :                : 
                                713                 :                : /*
                                714                 :                :  * subplan_is_hashable: can we implement an ANY subplan by hashing?
                                715                 :                :  *
                                716                 :                :  * This is not responsible for checking whether the combining testexpr
                                717                 :                :  * is suitable for hashing.  We only look at the subquery itself.
                                718                 :                :  */
                                719                 :                : static bool
  298 tgl@sss.pgh.pa.us         720                 :           1695 : subplan_is_hashable(Plan *plan, bool unknownEqFalse)
                                721                 :                : {
                                722                 :                :     Size        hashtablesize;
                                723                 :                : 
                                724                 :                :     /*
                                725                 :                :      * The estimated size of the hashtable holding the subquery result must
                                726                 :                :      * fit in hash_mem.  (Note: reject on equality, to ensure that an estimate
                                727                 :                :      * of SIZE_MAX disables hashing regardless of the hash_mem limit.)
                                728                 :                :      */
                                729                 :           1695 :     hashtablesize = EstimateSubplanHashTableSpace(plan->plan_rows,
                                730                 :           1695 :                                                   plan->plan_width,
                                731                 :                :                                                   unknownEqFalse);
                                732         [ +  + ]:           1695 :     if (hashtablesize >= get_hash_memory_limit())
 2160                           733                 :              5 :         return false;
                                734                 :                : 
                                735                 :           1690 :     return true;
                                736                 :                : }
                                737                 :                : 
                                738                 :                : /*
                                739                 :                :  * subpath_is_hashable: can we implement an ANY subplan by hashing?
                                740                 :                :  *
                                741                 :                :  * Identical to subplan_is_hashable, but work from a Path for the subplan.
                                742                 :                :  */
                                743                 :                : static bool
  298                           744                 :           1278 : subpath_is_hashable(Path *path, bool unknownEqFalse)
                                745                 :                : {
                                746                 :                :     Size        hashtablesize;
                                747                 :                : 
                                748                 :                :     /*
                                749                 :                :      * The estimated size of the hashtable holding the subquery result must
                                750                 :                :      * fit in hash_mem.  (Note: reject on equality, to ensure that an estimate
                                751                 :                :      * of SIZE_MAX disables hashing regardless of the hash_mem limit.)
                                752                 :                :      */
                                753                 :           1278 :     hashtablesize = EstimateSubplanHashTableSpace(path->rows,
                                754                 :           1278 :                                                   path->pathtarget->width,
                                755                 :                :                                                   unknownEqFalse);
                                756         [ +  + ]:           1278 :     if (hashtablesize >= get_hash_memory_limit())
 8630                           757                 :              5 :         return false;
                                758                 :                : 
 6579                           759                 :           1273 :     return true;
                                760                 :                : }
                                761                 :                : 
                                762                 :                : /*
                                763                 :                :  * testexpr_is_hashable: is an ANY SubLink's test expression hashable?
                                764                 :                :  *
                                765                 :                :  * To identify LHS vs RHS of the hash expression, we must be given the
                                766                 :                :  * list of output Param IDs of the SubLink's subquery.
                                767                 :                :  */
                                768                 :                : static bool
 2204                           769                 :           1690 : testexpr_is_hashable(Node *testexpr, List *param_ids)
                                770                 :                : {
                                771                 :                :     /*
                                772                 :                :      * The testexpr must be a single OpExpr, or an AND-clause containing only
                                773                 :                :      * OpExprs, each of which satisfy test_opexpr_is_hashable().
                                774                 :                :      */
 6579                           775   [ +  -  +  + ]:           1690 :     if (testexpr && IsA(testexpr, OpExpr))
                                776                 :                :     {
 2204                           777         [ +  + ]:            956 :         if (test_opexpr_is_hashable((OpExpr *) testexpr, param_ids))
 6579                           778                 :            931 :             return true;
                                779                 :                :     }
 2767                           780         [ +  - ]:            734 :     else if (is_andclause(testexpr))
                                781                 :                :     {
                                782                 :                :         ListCell   *l;
                                783                 :                : 
 6579                           784   [ +  -  +  +  :           2202 :         foreach(l, ((BoolExpr *) testexpr)->args)
                                              +  + ]
                                785                 :                :         {
 7267 bruce@momjian.us          786                 :           1468 :             Node       *andarg = (Node *) lfirst(l);
                                787                 :                : 
 7547 tgl@sss.pgh.pa.us         788         [ -  + ]:           1468 :             if (!IsA(andarg, OpExpr))
 6579 tgl@sss.pgh.pa.us         789                 :UBC           0 :                 return false;
 2204 tgl@sss.pgh.pa.us         790         [ -  + ]:CBC        1468 :             if (!test_opexpr_is_hashable((OpExpr *) andarg, param_ids))
 7547 tgl@sss.pgh.pa.us         791                 :UBC           0 :                 return false;
                                792                 :                :         }
 6579 tgl@sss.pgh.pa.us         793                 :CBC         734 :         return true;
                                794                 :                :     }
                                795                 :                : 
                                796                 :             25 :     return false;
                                797                 :                : }
                                798                 :                : 
                                799                 :                : static bool
 2204                           800                 :           2424 : test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids)
                                801                 :                : {
                                802                 :                :     /*
                                803                 :                :      * The combining operator must be hashable and strict.  The need for
                                804                 :                :      * hashability is obvious, since we want to use hashing.  Without
                                805                 :                :      * strictness, behavior in the presence of nulls is too unpredictable.  We
                                806                 :                :      * actually must assume even more than plain strictness: it can't yield
                                807                 :                :      * NULL for non-null inputs, either (see nodeSubplan.c).  However, hash
                                808                 :                :      * indexes and hash joins assume that too.
                                809                 :                :      */
                                810         [ +  + ]:           2424 :     if (!hash_ok_operator(testexpr))
                                811                 :             15 :         return false;
                                812                 :                : 
                                813                 :                :     /*
                                814                 :                :      * The left and right inputs must belong to the outer and inner queries
                                815                 :                :      * respectively; hence Params that will be supplied by the subquery must
                                816                 :                :      * not appear in the LHS, and Vars of the outer query must not appear in
                                817                 :                :      * the RHS.  (Ordinarily, this must be true because of the way that the
                                818                 :                :      * parser builds an ANY SubLink's testexpr ... but inlining of functions
                                819                 :                :      * could have changed the expression's structure, so we have to check.
                                820                 :                :      * Such cases do not occur often enough to be worth trying to optimize, so
                                821                 :                :      * we don't worry about trying to commute the clause or anything like
                                822                 :                :      * that; we just need to be sure not to build an invalid plan.)
                                823                 :                :      */
                                824         [ -  + ]:           2409 :     if (list_length(testexpr->args) != 2)
 2204 tgl@sss.pgh.pa.us         825                 :UBC           0 :         return false;
 2204 tgl@sss.pgh.pa.us         826         [ +  + ]:CBC        2409 :     if (contain_exec_param((Node *) linitial(testexpr->args), param_ids))
                                827                 :             10 :         return false;
                                828         [ -  + ]:           2399 :     if (contain_var_clause((Node *) lsecond(testexpr->args)))
 2204 tgl@sss.pgh.pa.us         829                 :UBC           0 :         return false;
 2204 tgl@sss.pgh.pa.us         830                 :CBC        2399 :     return true;
                                831                 :                : }
                                832                 :                : 
                                833                 :                : /*
                                834                 :                :  * Check expression is hashable + strict
                                835                 :                :  *
                                836                 :                :  * We could use op_hashjoinable() and op_strict(), but do it like this to
                                837                 :                :  * avoid a redundant cache lookup.
                                838                 :                :  */
                                839                 :                : static bool
 7547                           840                 :           7063 : hash_ok_operator(OpExpr *expr)
                                841                 :                : {
                                842                 :           7063 :     Oid         opid = expr->opno;
                                843                 :                : 
                                844                 :                :     /* quick out if not a binary operator */
 6579                           845         [ -  + ]:           7063 :     if (list_length(expr->args) != 2)
 6579 tgl@sss.pgh.pa.us         846                 :UBC           0 :         return false;
 1684 tgl@sss.pgh.pa.us         847   [ +  -  +  + ]:CBC        7063 :     if (opid == ARRAY_EQ_OP ||
   80                           848         [ +  - ]:           7053 :         opid == RECORD_EQ_OP ||
                                849         [ -  + ]:           7053 :         opid == RANGE_EQ_OP ||
                                850                 :                :         opid == MULTIRANGE_EQ_OP)
                                851                 :                :     {
                                852                 :                :         /* these are strict, but must check input type to ensure hashable */
 5780                           853                 :             10 :         Node       *leftarg = linitial(expr->args);
                                854                 :                : 
                                855                 :             10 :         return op_hashjoinable(opid, exprType(leftarg));
                                856                 :                :     }
                                857                 :                :     else
                                858                 :                :     {
                                859                 :                :         /* else must look up the operator properties */
                                860                 :                :         HeapTuple   tup;
                                861                 :                :         Form_pg_operator optup;
                                862                 :                : 
                                863                 :           7053 :         tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid));
                                864         [ -  + ]:           7053 :         if (!HeapTupleIsValid(tup))
 5780 tgl@sss.pgh.pa.us         865         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for operator %u", opid);
 5780 tgl@sss.pgh.pa.us         866                 :CBC        7053 :         optup = (Form_pg_operator) GETSTRUCT(tup);
                                867   [ +  +  -  + ]:           7053 :         if (!optup->oprcanhash || !func_strict(optup->oprcode))
                                868                 :                :         {
                                869                 :            449 :             ReleaseSysCache(tup);
                                870                 :            449 :             return false;
                                871                 :                :         }
 8630                           872                 :           6604 :         ReleaseSysCache(tup);
 5780                           873                 :           6604 :         return true;
                                874                 :                :     }
                                875                 :                : }
                                876                 :                : 
                                877                 :                : 
                                878                 :                : /*
                                879                 :                :  * SS_process_ctes: process a query's WITH list
                                880                 :                :  *
                                881                 :                :  * Consider each CTE in the WITH list and either ignore it (if it's an
                                882                 :                :  * unreferenced SELECT), "inline" it to create a regular sub-SELECT-in-FROM,
                                883                 :                :  * or convert it to an initplan.
                                884                 :                :  *
                                885                 :                :  * A side effect is to fill in root->cte_plan_ids with a list that
                                886                 :                :  * parallels root->parse->cteList and provides the subplan ID for
                                887                 :                :  * each CTE's initplan, or a dummy ID (-1) if we didn't make an initplan.
                                888                 :                :  */
                                889                 :                : void
 6536                           890                 :           2215 : SS_process_ctes(PlannerInfo *root)
                                891                 :                : {
                                892                 :                :     ListCell   *lc;
                                893                 :                : 
                                894         [ -  + ]:           2215 :     Assert(root->cte_plan_ids == NIL);
                                895                 :                : 
                                896   [ +  -  +  +  :           5193 :     foreach(lc, root->parse->cteList)
                                              +  + ]
                                897                 :                :     {
                                898                 :           2982 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
 5662                           899                 :           2982 :         CmdType     cmdType = ((Query *) cte->ctequery)->commandType;
                                900                 :                :         Query      *subquery;
                                901                 :                :         PlannerInfo *subroot;
                                902                 :                :         RelOptInfo *final_rel;
                                903                 :                :         Path       *best_path;
                                904                 :                :         Plan       *plan;
                                905                 :                :         SubPlan    *splan;
                                906                 :                :         int         paramid;
                                907                 :                : 
                                908                 :                :         /*
                                909                 :                :          * Ignore SELECT CTEs that are not actually referenced anywhere.
                                910                 :                :          */
                                911   [ +  +  +  + ]:           2982 :         if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
                                912                 :                :         {
                                913                 :                :             /* Make a dummy entry in cte_plan_ids */
 6536                           914                 :             34 :             root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
                                915                 :             34 :             continue;
                                916                 :                :         }
                                917                 :                : 
                                918                 :                :         /*
                                919                 :                :          * Consider inlining the CTE (creating RTE_SUBQUERY RTE(s)) instead of
                                920                 :                :          * implementing it as a separately-planned CTE.
                                921                 :                :          *
                                922                 :                :          * We cannot inline if any of these conditions hold:
                                923                 :                :          *
                                924                 :                :          * 1. The user said not to (the CTEMaterializeAlways option).
                                925                 :                :          *
                                926                 :                :          * 2. The CTE is recursive.
                                927                 :                :          *
                                928                 :                :          * 3. The CTE has side-effects; this includes either not being a plain
                                929                 :                :          * SELECT, or containing volatile functions.  Inlining might change
                                930                 :                :          * the side-effects, which would be bad.
                                931                 :                :          *
                                932                 :                :          * 4. The CTE is multiply-referenced and contains a self-reference to
                                933                 :                :          * a recursive CTE outside itself.  Inlining would result in multiple
                                934                 :                :          * recursive self-references, which we don't support.
                                935                 :                :          *
                                936                 :                :          * Otherwise, we have an option whether to inline or not.  That should
                                937                 :                :          * always be a win if there's just a single reference, but if the CTE
                                938                 :                :          * is multiply-referenced then it's unclear: inlining adds duplicate
                                939                 :                :          * computations, but the ability to absorb restrictions from the outer
                                940                 :                :          * query level could outweigh that.  We do not have nearly enough
                                941                 :                :          * information at this point to tell whether that's true, so we let
                                942                 :                :          * the user express a preference.  Our default behavior is to inline
                                943                 :                :          * only singly-referenced CTEs, but a CTE marked CTEMaterializeNever
                                944                 :                :          * will be inlined even if multiply referenced.
                                945                 :                :          *
                                946                 :                :          * Note: we check for volatile functions last, because that's more
                                947                 :                :          * expensive than the other tests needed.
                                948                 :                :          */
 2749                           949         [ +  + ]:           2948 :         if ((cte->ctematerialized == CTEMaterializeNever ||
                                950         [ +  + ]:           2908 :              (cte->ctematerialized == CTEMaterializeDefault &&
                                951         [ +  + ]:           2740 :               cte->cterefcount == 1)) &&
                                952   [ +  +  +  + ]:           2035 :             !cte->cterecursive &&
                                953                 :           1221 :             cmdType == CMD_SELECT &&
                                954         [ +  + ]:           1221 :             !contain_dml(cte->ctequery) &&
 2697                           955         [ +  + ]:           1215 :             (cte->cterefcount <= 1 ||
                                956         [ +  + ]:             30 :              !contain_outer_selfref(cte->ctequery)) &&
 2749                           957         [ +  + ]:           1205 :             !contain_volatile_functions(cte->ctequery))
                                958                 :                :         {
                                959                 :           1092 :             inline_cte(root, cte);
                                960                 :                :             /* Make a dummy entry in cte_plan_ids */
                                961                 :           1092 :             root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
                                962                 :           1092 :             continue;
                                963                 :                :         }
                                964                 :                : 
                                965                 :                :         /*
                                966                 :                :          * Copy the source Query node.  Probably not necessary, but let's keep
                                967                 :                :          * this similar to make_subplan.
                                968                 :                :          */
 6536                           969                 :           1856 :         subquery = (Query *) copyObject(cte->ctequery);
                                970                 :                : 
                                971                 :                :         /* plan_params should not be in use in current query level */
 5104                           972         [ -  + ]:           1856 :         Assert(root->plan_params == NIL);
                                973                 :                : 
                                974                 :                :         /*
                                975                 :                :          * Generate Paths for the CTE query.  Always plan for full retrieval
                                976                 :                :          * --- we don't have enough info to predict otherwise.
                                977                 :                :          */
  324 rhaas@postgresql.org      978                 :           1856 :         subroot = subquery_planner(root->glob, subquery,
                                979                 :           1856 :                                    choose_plan_name(root->glob, cte->ctename, false),
  154                           980                 :           1856 :                                    root, NULL, cte->cterecursive, 0.0, NULL);
                                981                 :                : 
                                982                 :                :         /*
                                983                 :                :          * Since the current query level doesn't yet contain any RTEs, it
                                984                 :                :          * should not be possible for the CTE to have requested parameters of
                                985                 :                :          * this level.
                                986                 :                :          */
 5104 tgl@sss.pgh.pa.us         987         [ -  + ]:           1852 :         if (root->plan_params)
 5104 tgl@sss.pgh.pa.us         988         [ #  # ]:UBC           0 :             elog(ERROR, "unexpected outer reference in CTE query");
                                989                 :                : 
                                990                 :                :         /*
                                991                 :                :          * Select best Path and turn it into a Plan.  At least for now, there
                                992                 :                :          * seems no reason to postpone doing that.
                                993                 :                :          */
 3825 tgl@sss.pgh.pa.us         994                 :CBC        1852 :         final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
                                995                 :           1852 :         best_path = final_rel->cheapest_total_path;
                                996                 :                : 
                                997                 :           1852 :         plan = create_plan(subroot, best_path);
                                998                 :                : 
                                999                 :                :         /*
                               1000                 :                :          * Make a SubPlan node for it.  This is just enough unlike
                               1001                 :                :          * build_subplan that we can't share code.
                               1002                 :                :          *
                               1003                 :                :          * Note: plan_id and cost fields are set further down.
                               1004                 :                :          */
 6536                          1005                 :           1852 :         splan = makeNode(SubPlan);
                               1006                 :           1852 :         splan->subLinkType = CTE_SUBLINK;
  324 rhaas@postgresql.org     1007                 :           1852 :         splan->plan_name = subroot->plan_name;
 6536 tgl@sss.pgh.pa.us        1008                 :           1852 :         splan->testexpr = NULL;
                               1009                 :           1852 :         splan->paramIds = NIL;
 5606                          1010                 :           1852 :         get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
                               1011                 :                :                            &splan->firstColCollation);
 6536                          1012                 :           1852 :         splan->useHashTable = false;
                               1013                 :           1852 :         splan->unknownEqFalse = false;
                               1014                 :                : 
                               1015                 :                :         /*
                               1016                 :                :          * CTE scans are not considered for parallelism (cf
                               1017                 :                :          * set_rel_consider_parallel).
                               1018                 :                :          */
 3481 rhaas@postgresql.org     1019                 :           1852 :         splan->parallel_safe = false;
 6536 tgl@sss.pgh.pa.us        1020                 :           1852 :         splan->setParam = NIL;
                               1021                 :           1852 :         splan->parParam = NIL;
                               1022                 :           1852 :         splan->args = NIL;
                               1023                 :                : 
                               1024                 :                :         /*
                               1025                 :                :          * The node can't have any inputs (since it's an initplan), so the
                               1026                 :                :          * parParam and args lists remain empty.  (It could contain references
                               1027                 :                :          * to earlier CTEs' output param IDs, but CTE outputs are not
                               1028                 :                :          * propagated via the args list.)
                               1029                 :                :          */
                               1030                 :                : 
                               1031                 :                :         /*
                               1032                 :                :          * Assign a param ID to represent the CTE's output.  No ordinary
                               1033                 :                :          * "evaluation" of this param slot ever happens, but we use the param
                               1034                 :                :          * ID for setParam/chgParam signaling just as if the CTE plan were
                               1035                 :                :          * returning a simple scalar output.  (Also, the executor abuses the
                               1036                 :                :          * ParamExecData slot for this param ID for communication among
                               1037                 :                :          * multiple CteScan nodes that might be scanning this CTE.)
                               1038                 :                :          */
 2785                          1039                 :           1852 :         paramid = assign_special_exec_param(root);
 5104                          1040                 :           1852 :         splan->setParam = list_make1_int(paramid);
                               1041                 :                : 
                               1042                 :                :         /*
                               1043                 :                :          * Add the subplan, its path, and its PlannerInfo to the global lists.
                               1044                 :                :          */
 6536                          1045                 :           1852 :         root->glob->subplans = lappend(root->glob->subplans, plan);
  884                          1046                 :           1852 :         root->glob->subpaths = lappend(root->glob->subpaths, best_path);
 5472                          1047                 :           1852 :         root->glob->subroots = lappend(root->glob->subroots, subroot);
 6536                          1048                 :           1852 :         splan->plan_id = list_length(root->glob->subplans);
                               1049                 :                : 
                               1050                 :           1852 :         root->init_plans = lappend(root->init_plans, splan);
                               1051                 :                : 
                               1052                 :           1852 :         root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
                               1053                 :                : 
                               1054                 :                :         /* Lastly, fill in the cost estimates for use later */
                               1055                 :           1852 :         cost_subplan(root, splan, plan);
                               1056                 :                :     }
                               1057                 :           2211 : }
                               1058                 :                : 
                               1059                 :                : /*
                               1060                 :                :  * contain_dml: is any subquery not a plain SELECT?
                               1061                 :                :  *
                               1062                 :                :  * We reject SELECT FOR UPDATE/SHARE as well as INSERT etc.
                               1063                 :                :  */
                               1064                 :                : static bool
 2749                          1065                 :           1221 : contain_dml(Node *node)
                               1066                 :                : {
                               1067                 :           1221 :     return contain_dml_walker(node, NULL);
                               1068                 :                : }
                               1069                 :                : 
                               1070                 :                : static bool
                               1071                 :          84429 : contain_dml_walker(Node *node, void *context)
                               1072                 :                : {
                               1073         [ +  + ]:          84429 :     if (node == NULL)
                               1074                 :          31321 :         return false;
                               1075         [ +  + ]:          53108 :     if (IsA(node, Query))
                               1076                 :                :     {
                               1077                 :           2286 :         Query      *query = (Query *) node;
                               1078                 :                : 
                               1079         [ +  - ]:           2286 :         if (query->commandType != CMD_SELECT ||
                               1080         [ +  + ]:           2286 :             query->rowMarks != NIL)
                               1081                 :              6 :             return true;
                               1082                 :                : 
                               1083                 :           2280 :         return query_tree_walker(query, contain_dml_walker, context, 0);
                               1084                 :                :     }
                               1085                 :          50822 :     return expression_tree_walker(node, contain_dml_walker, context);
                               1086                 :                : }
                               1087                 :                : 
                               1088                 :                : /*
                               1089                 :                :  * contain_outer_selfref: is there an external recursive self-reference?
                               1090                 :                :  */
                               1091                 :                : static bool
 2697                          1092                 :             30 : contain_outer_selfref(Node *node)
                               1093                 :                : {
                               1094                 :             30 :     Index       depth = 0;
                               1095                 :                : 
                               1096                 :                :     /*
                               1097                 :                :      * We should be starting with a Query, so that depth will be 1 while
                               1098                 :                :      * examining its immediate contents.
                               1099                 :                :      */
                               1100         [ -  + ]:             30 :     Assert(IsA(node, Query));
                               1101                 :                : 
                               1102                 :             30 :     return contain_outer_selfref_walker(node, &depth);
                               1103                 :                : }
                               1104                 :                : 
                               1105                 :                : static bool
                               1106                 :            710 : contain_outer_selfref_walker(Node *node, Index *depth)
                               1107                 :                : {
                               1108         [ +  + ]:            710 :     if (node == NULL)
                               1109                 :            440 :         return false;
                               1110         [ +  + ]:            270 :     if (IsA(node, RangeTblEntry))
                               1111                 :                :     {
                               1112                 :             25 :         RangeTblEntry *rte = (RangeTblEntry *) node;
                               1113                 :                : 
                               1114                 :                :         /*
                               1115                 :                :          * Check for a self-reference to a CTE that's above the Query that our
                               1116                 :                :          * search started at.
                               1117                 :                :          */
                               1118         [ +  + ]:             25 :         if (rte->rtekind == RTE_CTE &&
                               1119         [ +  - ]:             10 :             rte->self_reference &&
                               1120         [ +  - ]:             10 :             rte->ctelevelsup >= *depth)
                               1121                 :             10 :             return true;
                               1122                 :             15 :         return false;           /* allow range_table_walker to continue */
                               1123                 :                :     }
                               1124         [ +  + ]:            245 :     if (IsA(node, Query))
                               1125                 :                :     {
                               1126                 :                :         /* Recurse into subquery, tracking nesting depth properly */
                               1127                 :             35 :         Query      *query = (Query *) node;
                               1128                 :                :         bool        result;
                               1129                 :                : 
                               1130                 :             35 :         (*depth)++;
                               1131                 :                : 
                               1132                 :             35 :         result = query_tree_walker(query, contain_outer_selfref_walker,
                               1133                 :                :                                    depth, QTW_EXAMINE_RTES_BEFORE);
                               1134                 :                : 
                               1135                 :             35 :         (*depth)--;
                               1136                 :                : 
                               1137                 :             35 :         return result;
                               1138                 :                :     }
  637 peter@eisentraut.org     1139                 :            210 :     return expression_tree_walker(node, contain_outer_selfref_walker, depth);
                               1140                 :                : }
                               1141                 :                : 
                               1142                 :                : /*
                               1143                 :                :  * inline_cte: convert RTE_CTE references to given CTE into RTE_SUBQUERYs
                               1144                 :                :  */
                               1145                 :                : static void
 2749 tgl@sss.pgh.pa.us        1146                 :           1092 : inline_cte(PlannerInfo *root, CommonTableExpr *cte)
                               1147                 :                : {
                               1148                 :                :     struct inline_cte_walker_context context;
                               1149                 :                : 
                               1150                 :           1092 :     context.ctename = cte->ctename;
                               1151                 :                :     /* Start at levelsup = -1 because we'll immediately increment it */
                               1152                 :           1092 :     context.levelsup = -1;
                               1153                 :           1092 :     context.ctequery = castNode(Query, cte->ctequery);
                               1154                 :                : 
                               1155                 :           1092 :     (void) inline_cte_walker((Node *) root->parse, &context);
                               1156                 :           1092 : }
                               1157                 :                : 
                               1158                 :                : static bool
                               1159                 :         337724 : inline_cte_walker(Node *node, inline_cte_walker_context *context)
                               1160                 :                : {
                               1161         [ +  + ]:         337724 :     if (node == NULL)
                               1162                 :         101487 :         return false;
                               1163         [ +  + ]:         236237 :     if (IsA(node, Query))
                               1164                 :                :     {
                               1165                 :           6973 :         Query      *query = (Query *) node;
                               1166                 :                : 
                               1167                 :           6973 :         context->levelsup++;
                               1168                 :                : 
                               1169                 :                :         /*
                               1170                 :                :          * Visit the query's RTE nodes after their contents; otherwise
                               1171                 :                :          * query_tree_walker would descend into the newly inlined CTE query,
                               1172                 :                :          * which we don't want.
                               1173                 :                :          */
                               1174                 :           6973 :         (void) query_tree_walker(query, inline_cte_walker, context,
                               1175                 :                :                                  QTW_EXAMINE_RTES_AFTER);
                               1176                 :                : 
                               1177                 :           6973 :         context->levelsup--;
                               1178                 :                : 
                               1179                 :           6973 :         return false;
                               1180                 :                :     }
                               1181         [ +  + ]:         229264 :     else if (IsA(node, RangeTblEntry))
                               1182                 :                :     {
                               1183                 :          12299 :         RangeTblEntry *rte = (RangeTblEntry *) node;
                               1184                 :                : 
                               1185         [ +  + ]:          12299 :         if (rte->rtekind == RTE_CTE &&
                               1186         [ +  + ]:           3763 :             strcmp(rte->ctename, context->ctename) == 0 &&
                               1187         [ +  + ]:           1117 :             rte->ctelevelsup == context->levelsup)
                               1188                 :                :         {
                               1189                 :                :             /*
                               1190                 :                :              * Found a reference to replace.  Generate a copy of the CTE query
                               1191                 :                :              * with appropriate level adjustment for outer references (e.g.,
                               1192                 :                :              * to other CTEs).
                               1193                 :                :              */
                               1194                 :           1112 :             Query      *newquery = copyObject(context->ctequery);
                               1195                 :                : 
                               1196         [ +  + ]:           1112 :             if (context->levelsup > 0)
                               1197                 :            610 :                 IncrementVarSublevelsUp((Node *) newquery, context->levelsup, 1);
                               1198                 :                : 
                               1199                 :                :             /*
                               1200                 :                :              * Convert the RTE_CTE RTE into a RTE_SUBQUERY.
                               1201                 :                :              *
                               1202                 :                :              * Historically, a FOR UPDATE clause has been treated as extending
                               1203                 :                :              * into views and subqueries, but not into CTEs.  We preserve this
                               1204                 :                :              * distinction by not trying to push rowmarks into the new
                               1205                 :                :              * subquery.
                               1206                 :                :              */
                               1207                 :           1112 :             rte->rtekind = RTE_SUBQUERY;
                               1208                 :           1112 :             rte->subquery = newquery;
                               1209                 :           1112 :             rte->security_barrier = false;
                               1210                 :                : 
                               1211                 :                :             /* Zero out CTE-specific fields */
                               1212                 :           1112 :             rte->ctename = NULL;
                               1213                 :           1112 :             rte->ctelevelsup = 0;
                               1214                 :           1112 :             rte->self_reference = false;
                               1215                 :           1112 :             rte->coltypes = NIL;
                               1216                 :           1112 :             rte->coltypmods = NIL;
                               1217                 :           1112 :             rte->colcollations = NIL;
                               1218                 :                :         }
                               1219                 :                : 
                               1220                 :          12299 :         return false;
                               1221                 :                :     }
                               1222                 :                : 
                               1223                 :         216965 :     return expression_tree_walker(node, inline_cte_walker, context);
                               1224                 :                : }
                               1225                 :                : 
                               1226                 :                : /*
                               1227                 :                :  * Attempt to transform 'testexpr' over the VALUES subquery into
                               1228                 :                :  * a ScalarArrayOpExpr.  We currently support the transformation only when
                               1229                 :                :  * it ends up with a constant array.  Otherwise, the evaluation of non-hashed
                               1230                 :                :  * SAOP might be slower than the corresponding Hash Join with VALUES.
                               1231                 :                :  *
                               1232                 :                :  * Return transformed ScalarArrayOpExpr or NULL if transformation isn't
                               1233                 :                :  * allowed.
                               1234                 :                :  */
                               1235                 :                : ScalarArrayOpExpr *
  510 akorotkov@postgresql     1236                 :           3766 : convert_VALUES_to_ANY(PlannerInfo *root, Node *testexpr, Query *values)
                               1237                 :                : {
                               1238                 :                :     RangeTblEntry *rte;
                               1239                 :                :     Node       *leftop;
                               1240                 :                :     Node       *rightop;
                               1241                 :                :     Oid         opno;
                               1242                 :                :     ListCell   *lc;
                               1243                 :                :     Oid         inputcollid;
                               1244                 :           3766 :     List       *exprs = NIL;
                               1245                 :                : 
                               1246                 :                :     /*
                               1247                 :                :      * Check we have a binary operator over a single-column subquery with no
                               1248                 :                :      * joins and no LIMIT/OFFSET/ORDER BY clauses.
                               1249                 :                :      */
                               1250   [ +  +  +  - ]:           7439 :     if (!IsA(testexpr, OpExpr) ||
                               1251         [ +  - ]:           7346 :         list_length(((OpExpr *) testexpr)->args) != 2 ||
                               1252                 :           3673 :         list_length(values->targetList) > 1 ||
                               1253         [ +  + ]:           3673 :         values->limitCount != NULL ||
                               1254         [ +  + ]:           3663 :         values->limitOffset != NULL ||
                               1255   [ +  +  +  + ]:           7281 :         values->sortClause != NIL ||
                               1256                 :           3638 :         list_length(values->rtable) != 1)
                               1257                 :           3064 :         return NULL;
                               1258                 :                : 
                               1259                 :            702 :     rte = linitial_node(RangeTblEntry, values->rtable);
                               1260                 :            702 :     leftop = linitial(((OpExpr *) testexpr)->args);
                               1261                 :            702 :     rightop = lsecond(((OpExpr *) testexpr)->args);
                               1262                 :            702 :     opno = ((OpExpr *) testexpr)->opno;
                               1263                 :            702 :     inputcollid = ((OpExpr *) testexpr)->inputcollid;
                               1264                 :                : 
                               1265                 :                :     /*
                               1266                 :                :      * Also, check that only RTE corresponds to VALUES; the list of values has
                               1267                 :                :      * at least two items and no volatile functions.
                               1268                 :                :      */
                               1269   [ +  +  +  + ]:            812 :     if (rte->rtekind != RTE_VALUES ||
                               1270         [ -  + ]:            210 :         list_length(rte->values_lists) < 2 ||
                               1271                 :            100 :         contain_volatile_functions((Node *) rte->values_lists))
                               1272                 :            602 :         return NULL;
                               1273                 :                : 
                               1274   [ +  -  +  +  :            300 :     foreach(lc, rte->values_lists)
                                              +  + ]
                               1275                 :                :     {
                               1276                 :            230 :         List       *elem = lfirst(lc);
                               1277                 :            230 :         Node       *value = linitial(elem);
                               1278                 :                : 
                               1279                 :                :         /*
                               1280                 :                :          * Prepare an evaluation of the right side of the operator with
                               1281                 :                :          * substitution of the given value.
                               1282                 :                :          */
                               1283                 :            230 :         value = convert_testexpr(root, rightop, list_make1(value));
                               1284                 :                : 
                               1285                 :                :         /*
                               1286                 :                :          * Try to evaluate constant expressions.  We could get Const as a
                               1287                 :                :          * result.
                               1288                 :                :          */
                               1289                 :            230 :         value = eval_const_expressions(root, value);
                               1290                 :                : 
                               1291                 :                :         /*
                               1292                 :                :          * As we only support constant output arrays, all the items must also
                               1293                 :                :          * be constant.
                               1294                 :                :          */
                               1295         [ +  + ]:            230 :         if (!IsA(value, Const))
                               1296                 :             30 :             return NULL;
                               1297                 :                : 
                               1298                 :            200 :         exprs = lappend(exprs, value);
                               1299                 :                :     }
                               1300                 :                : 
                               1301                 :                :     /* Finally, build ScalarArrayOpExpr at the top of the 'exprs' list. */
                               1302                 :             70 :     return make_SAOP_expr(opno, leftop, exprType(rightop),
                               1303                 :             70 :                           linitial_oid(rte->colcollations), inputcollid,
                               1304                 :                :                           exprs, false);
                               1305                 :                : }
                               1306                 :                : 
                               1307                 :                : /*
                               1308                 :                :  * convert_ANY_sublink_to_join: try to convert an ANY SubLink to a join
                               1309                 :                :  *
                               1310                 :                :  * The caller has found an ANY SubLink at the top level of one of the query's
                               1311                 :                :  * qual clauses, but has not checked the properties of the SubLink further.
                               1312                 :                :  * Decide whether it is appropriate to process this SubLink in join style.
                               1313                 :                :  * If so, form a JoinExpr and return it.  Return NULL if the SubLink cannot
                               1314                 :                :  * be converted to a join.
                               1315                 :                :  *
                               1316                 :                :  * If under_not is true, the caller actually found NOT (ANY SubLink), so
                               1317                 :                :  * that what we must try to build is an ANTI not SEMI join.
                               1318                 :                :  *
                               1319                 :                :  * available_rels is the set of query rels that can safely be referenced
                               1320                 :                :  * in the sublink expression.  (We must restrict this to avoid changing
                               1321                 :                :  * the semantics when a sublink is present in an outer join's ON qual.)
                               1322                 :                :  * The conversion must fail if the converted qual would reference any but
                               1323                 :                :  * these parent-query relids.
                               1324                 :                :  *
                               1325                 :                :  * On success, the returned JoinExpr has larg = NULL and rarg = the jointree
                               1326                 :                :  * item representing the pulled-up subquery.  The caller must set larg to
                               1327                 :                :  * represent the relation(s) on the lefthand side of the new join, and insert
                               1328                 :                :  * the JoinExpr into the upper query's jointree at an appropriate place
                               1329                 :                :  * (typically, where the lefthand relation(s) had been).  Note that the
                               1330                 :                :  * passed-in SubLink must also be removed from its original position in the
                               1331                 :                :  * query quals, since the quals of the returned JoinExpr replace it.
                               1332                 :                :  * (Notionally, we replace the SubLink with a constant TRUE, then elide the
                               1333                 :                :  * redundant constant from the qual.)
                               1334                 :                :  *
                               1335                 :                :  * On success, the caller is also responsible for recursively applying
                               1336                 :                :  * pull_up_sublinks processing to the rarg and quals of the returned JoinExpr.
                               1337                 :                :  * (On failure, there is no need to do anything, since pull_up_sublinks will
                               1338                 :                :  * be applied when we recursively plan the sub-select.)
                               1339                 :                :  *
                               1340                 :                :  * Side effects of a successful conversion include adding the SubLink's
                               1341                 :                :  * subselect to the query's rangetable, so that it can be referenced in
                               1342                 :                :  * the JoinExpr's rarg.
                               1343                 :                :  */
                               1344                 :                : JoinExpr *
 6584 tgl@sss.pgh.pa.us        1345                 :           3921 : convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink,
                               1346                 :                :                             bool under_not, Relids available_rels)
                               1347                 :                : {
                               1348                 :                :     JoinExpr   *result;
 7753                          1349                 :           3921 :     Query      *parse = root->parse;
 8620                          1350                 :           3921 :     Query      *subselect = (Query *) sublink->subselect;
                               1351                 :                :     Relids      upper_varnos;
                               1352                 :                :     int         rtindex;
                               1353                 :                :     ParseNamespaceItem *nsitem;
                               1354                 :                :     RangeTblEntry *rte;
                               1355                 :                :     RangeTblRef *rtr;
                               1356                 :                :     List       *subquery_vars;
                               1357                 :                :     Node       *quals;
                               1358                 :                :     ParseState *pstate;
                               1359                 :                :     Relids      sub_ref_outer_relids;
                               1360                 :                :     bool        use_lateral;
                               1361                 :                : 
 6587                          1362         [ -  + ]:           3921 :     Assert(sublink->subLinkType == ANY_SUBLINK);
                               1363                 :                : 
                               1364                 :                :     /*
                               1365                 :                :      * Per SQL spec, NOT IN is not ordinarily equivalent to an anti-join, so
                               1366                 :                :      * that by default we have to fail when under_not.  However, if we can
                               1367                 :                :      * prove that neither the outer query's expressions nor the sub-select's
                               1368                 :                :      * output columns can be NULL, and further that the operator itself cannot
                               1369                 :                :      * return NULL for non-null inputs, then the logic is identical and it's
                               1370                 :                :      * safe to convert NOT IN to an anti-join.
                               1371                 :                :      */
  168 rguo@postgresql.org      1372         [ +  + ]:           3921 :     if (under_not &&
                               1373         [ +  + ]:            220 :         (!sublink_testexpr_is_not_nullable(root, sublink) ||
                               1374         [ +  + ]:            130 :          !query_outputs_are_not_nullable(subselect)))
                               1375                 :            135 :         return NULL;
                               1376                 :                : 
                               1377                 :                :     /*
                               1378                 :                :      * If the sub-select contains any Vars of the parent query, we treat it as
                               1379                 :                :      * LATERAL.  (Vars from higher levels don't matter here.)
                               1380                 :                :      */
  924 akorotkov@postgresql     1381                 :           3786 :     sub_ref_outer_relids = pull_varnos_of_level(NULL, (Node *) subselect, 1);
                               1382                 :           3786 :     use_lateral = !bms_is_empty(sub_ref_outer_relids);
                               1383                 :                : 
                               1384                 :                :     /*
                               1385                 :                :      * Can't convert if the sub-select contains parent-level Vars of relations
                               1386                 :                :      * not in available_rels.
                               1387                 :                :      */
                               1388         [ +  + ]:           3786 :     if (!bms_is_subset(sub_ref_outer_relids, available_rels))
 6392 tgl@sss.pgh.pa.us        1389                 :             10 :         return NULL;
                               1390                 :                : 
                               1391                 :                :     /*
                               1392                 :                :      * The test expression must contain some Vars of the parent query, else
                               1393                 :                :      * it's not gonna be a join.  (Note that it won't have Vars referring to
                               1394                 :                :      * the subquery, rather Params.)
                               1395                 :                :      */
 2044                          1396                 :           3776 :     upper_varnos = pull_varnos(root, sublink->testexpr);
 6392                          1397         [ +  + ]:           3776 :     if (bms_is_empty(upper_varnos))
                               1398                 :             15 :         return NULL;
                               1399                 :                : 
                               1400                 :                :     /*
                               1401                 :                :      * However, it can't refer to anything outside available_rels.
                               1402                 :                :      */
                               1403         [ +  + ]:           3761 :     if (!bms_is_subset(upper_varnos, available_rels))
                               1404                 :             25 :         return NULL;
                               1405                 :                : 
                               1406                 :                :     /*
                               1407                 :                :      * The combining operators and left-hand expressions mustn't be volatile.
                               1408                 :                :      */
 7547                          1409         [ +  + ]:           3736 :     if (contain_volatile_functions(sublink->testexpr))
 6392                          1410                 :             52 :         return NULL;
                               1411                 :                : 
                               1412                 :                :     /* Create a dummy ParseState for addRangeTableEntryForSubquery */
 4187 rhaas@postgresql.org     1413                 :           3684 :     pstate = make_parsestate(NULL);
                               1414                 :                : 
                               1415                 :                :     /*
                               1416                 :                :      * Okay, pull up the sub-select into upper range table.
                               1417                 :                :      *
                               1418                 :                :      * We rely here on the assumption that the outer query has no references
                               1419                 :                :      * to the inner (necessarily true, other than the Vars that we build
                               1420                 :                :      * below). Therefore this is a lot easier than what pull_up_subqueries has
                               1421                 :                :      * to go through.
                               1422                 :                :      */
 2429 tgl@sss.pgh.pa.us        1423                 :           3684 :     nsitem = addRangeTableEntryForSubquery(pstate,
                               1424                 :                :                                            subselect,
                               1425                 :                :                                            NULL,
                               1426                 :                :                                            use_lateral,
                               1427                 :                :                                            false);
                               1428                 :           3684 :     rte = nsitem->p_rte;
 8620                          1429                 :           3684 :     parse->rtable = lappend(parse->rtable, rte);
 8124 neilc@samurai.com        1430                 :           3684 :     rtindex = list_length(parse->rtable);
                               1431                 :                : 
                               1432                 :                :     /*
                               1433                 :                :      * Form a RangeTblRef for the pulled-up sub-select.
                               1434                 :                :      */
 6584 tgl@sss.pgh.pa.us        1435                 :           3684 :     rtr = makeNode(RangeTblRef);
                               1436                 :           3684 :     rtr->rtindex = rtindex;
                               1437                 :                : 
                               1438                 :                :     /*
                               1439                 :                :      * Build a list of Vars representing the subselect outputs.
                               1440                 :                :      */
 6702                          1441                 :           3684 :     subquery_vars = generate_subquery_vars(root,
                               1442                 :                :                                            subselect->targetList,
                               1443                 :                :                                            rtindex);
                               1444                 :                : 
                               1445                 :                :     /*
                               1446                 :                :      * Build the new join's qual expression, replacing Params with these Vars.
                               1447                 :                :      */
 6392                          1448                 :           3684 :     quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
                               1449                 :                : 
                               1450                 :                :     /*
                               1451                 :                :      * And finally, build the JoinExpr node.
                               1452                 :                :      */
                               1453                 :           3684 :     result = makeNode(JoinExpr);
  168 rguo@postgresql.org      1454         [ +  + ]:           3684 :     result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
 6392 tgl@sss.pgh.pa.us        1455                 :           3684 :     result->isNatural = false;
                               1456                 :           3684 :     result->larg = NULL;     /* caller must fill this in */
                               1457                 :           3684 :     result->rarg = (Node *) rtr;
 6251 peter_e@gmx.net          1458                 :           3684 :     result->usingClause = NIL;
 1975 peter@eisentraut.org     1459                 :           3684 :     result->join_using_alias = NULL;
 6392 tgl@sss.pgh.pa.us        1460                 :           3684 :     result->quals = quals;
                               1461                 :           3684 :     result->alias = NULL;
                               1462                 :           3684 :     result->rtindex = 0;     /* we don't need an RTE for it */
                               1463                 :                : 
                               1464                 :           3684 :     return result;
                               1465                 :                : }
                               1466                 :                : 
                               1467                 :                : /*
                               1468                 :                :  * sublink_testexpr_is_not_nullable: verify that testexpr of an ANY_SUBLINK
                               1469                 :                :  * guarantees a non-null result, assuming the inner side is also non-null.
                               1470                 :                :  *
                               1471                 :                :  * To ensure the expression never returns NULL, we require both that the outer
                               1472                 :                :  * expressions are provably non-nullable and that the operator itself is safe.
                               1473                 :                :  * We validate operator safety by checking for membership in a standard index
                               1474                 :                :  * operator family (B-tree or Hash); this acts as a proxy for standard boolean
                               1475                 :                :  * behavior, ensuring the operator does not produce NULL results from non-null
                               1476                 :                :  * inputs.
                               1477                 :                :  *
                               1478                 :                :  * We handle the three standard parser representations for ANY sublinks: a
                               1479                 :                :  * single OpExpr for single-column comparisons, a BoolExpr containing a list of
                               1480                 :                :  * OpExprs for multi-column equality or inequality checks (where equality
                               1481                 :                :  * becomes an AND and inequality becomes an OR), and a RowCompareExpr for
                               1482                 :                :  * multi-column ordering checks.  In all cases, we validate the operators and
                               1483                 :                :  * the outer expressions.
                               1484                 :                :  *
                               1485                 :                :  * It is acceptable for this check not to be exhaustive.  We can err on the
                               1486                 :                :  * side of conservatism: if we're not sure, it's okay to return FALSE.
                               1487                 :                :  */
                               1488                 :                : static bool
  168 rguo@postgresql.org      1489                 :            220 : sublink_testexpr_is_not_nullable(PlannerInfo *root, SubLink *sublink)
                               1490                 :                : {
                               1491                 :            220 :     Node       *testexpr = sublink->testexpr;
                               1492                 :            220 :     List       *outer_exprs = NIL;
                               1493                 :                : 
                               1494                 :                :     /* Punt if sublink is not in the expected format */
                               1495   [ +  -  -  + ]:            220 :     if (sublink->subLinkType != ANY_SUBLINK || testexpr == NULL)
  168 rguo@postgresql.org      1496                 :UBC           0 :         return false;
                               1497                 :                : 
  168 rguo@postgresql.org      1498         [ +  + ]:CBC         220 :     if (IsA(testexpr, OpExpr))
                               1499                 :                :     {
                               1500                 :                :         /* single-column comparison */
                               1501                 :            155 :         OpExpr     *opexpr = (OpExpr *) testexpr;
                               1502                 :                : 
                               1503                 :                :         /* standard ANY structure should be op(outer_var, param) */
                               1504         [ -  + ]:            155 :         if (list_length(opexpr->args) != 2)
  168 rguo@postgresql.org      1505                 :UBC           0 :             return false;
                               1506                 :                : 
                               1507                 :                :         /*
                               1508                 :                :          * We rely on membership in a B-tree or Hash operator family as a
                               1509                 :                :          * guarantee that the operator acts as a proper boolean comparison and
                               1510                 :                :          * does not yield NULL for valid non-null inputs.
                               1511                 :                :          */
  168 rguo@postgresql.org      1512         [ +  + ]:CBC         155 :         if (!op_is_safe_index_member(opexpr->opno))
                               1513                 :              5 :             return false;
                               1514                 :                : 
                               1515                 :            150 :         outer_exprs = lappend(outer_exprs, linitial(opexpr->args));
                               1516                 :                :     }
                               1517   [ +  +  -  + ]:             65 :     else if (is_andclause(testexpr) || is_orclause(testexpr))
                               1518                 :             60 :     {
                               1519                 :                :         /* multi-column equality or inequality checks */
                               1520                 :             60 :         BoolExpr   *bexpr = (BoolExpr *) testexpr;
                               1521                 :                : 
                               1522   [ +  -  +  +  :            240 :         foreach_ptr(OpExpr, opexpr, bexpr->args)
                                              +  + ]
                               1523                 :                :         {
                               1524         [ -  + ]:            120 :             if (!IsA(opexpr, OpExpr))
  168 rguo@postgresql.org      1525                 :UBC           0 :                 return false;
                               1526                 :                : 
                               1527                 :                :             /* standard ANY structure should be op(outer_var, param) */
  168 rguo@postgresql.org      1528         [ -  + ]:CBC         120 :             if (list_length(opexpr->args) != 2)
  168 rguo@postgresql.org      1529                 :UBC           0 :                 return false;
                               1530                 :                : 
                               1531                 :                :             /* verify operator safety; see comment above */
  168 rguo@postgresql.org      1532         [ -  + ]:CBC         120 :             if (!op_is_safe_index_member(opexpr->opno))
  168 rguo@postgresql.org      1533                 :UBC           0 :                 return false;
                               1534                 :                : 
  168 rguo@postgresql.org      1535                 :CBC         120 :             outer_exprs = lappend(outer_exprs, linitial(opexpr->args));
                               1536                 :                :         }
                               1537                 :                :     }
                               1538         [ +  - ]:              5 :     else if (IsA(testexpr, RowCompareExpr))
                               1539                 :                :     {
                               1540                 :                :         /* multi-column ordering checks */
                               1541                 :              5 :         RowCompareExpr *rcexpr = (RowCompareExpr *) testexpr;
                               1542                 :                : 
                               1543   [ +  -  +  +  :             20 :         foreach_oid(opno, rcexpr->opnos)
                                              +  + ]
                               1544                 :                :         {
                               1545                 :                :             /* verify operator safety; see comment above */
                               1546         [ -  + ]:             10 :             if (!op_is_safe_index_member(opno))
  168 rguo@postgresql.org      1547                 :UBC           0 :                 return false;
                               1548                 :                :         }
                               1549                 :                : 
  168 rguo@postgresql.org      1550                 :CBC           5 :         outer_exprs = list_concat(outer_exprs, rcexpr->largs);
                               1551                 :                :     }
                               1552                 :                :     else
                               1553                 :                :     {
                               1554                 :                :         /* Punt if other node types */
  168 rguo@postgresql.org      1555                 :UBC           0 :         return false;
                               1556                 :                :     }
                               1557                 :                : 
                               1558                 :                :     /*
                               1559                 :                :      * Since the query hasn't yet been through expression preprocessing, we
                               1560                 :                :      * must apply flatten_join_alias_vars to the outer expressions to avoid
                               1561                 :                :      * being fooled by join aliases.
                               1562                 :                :      *
                               1563                 :                :      * We do not need to apply flatten_group_exprs though, since grouping Vars
                               1564                 :                :      * cannot appear in jointree quals.
                               1565                 :                :      */
                               1566                 :                :     outer_exprs = (List *)
  168 rguo@postgresql.org      1567                 :CBC         215 :         flatten_join_alias_vars(root, root->parse, (Node *) outer_exprs);
                               1568                 :                : 
                               1569                 :                :     /* Check that every outer expression is non-nullable */
                               1570   [ +  -  +  +  :            495 :     foreach_ptr(Expr, expr, outer_exprs)
                                              +  + ]
                               1571                 :                :     {
                               1572                 :                :         /*
                               1573                 :                :          * We have already collected relation-level not-null constraints for
                               1574                 :                :          * the outer query, so we can consult the global hash table for
                               1575                 :                :          * nullability information.
                               1576                 :                :          */
                               1577         [ +  + ]:            235 :         if (!expr_is_nonnullable(root, expr, NOTNULL_SOURCE_HASHTABLE))
                               1578                 :             85 :             return false;
                               1579                 :                : 
                               1580                 :                :         /*
                               1581                 :                :          * Note: It is possible to further prove non-nullability by examining
                               1582                 :                :          * the qual clauses available at or below the jointree node where this
                               1583                 :                :          * NOT IN clause is evaluated, but for the moment it doesn't seem
                               1584                 :                :          * worth the extra complication.
                               1585                 :                :          */
                               1586                 :                :     }
                               1587                 :                : 
                               1588                 :            130 :     return true;
                               1589                 :                : }
                               1590                 :                : 
                               1591                 :                : /*
                               1592                 :                :  * convert_EXISTS_sublink_to_join: try to convert an EXISTS SubLink to a join
                               1593                 :                :  *
                               1594                 :                :  * The API of this function is identical to convert_ANY_sublink_to_join's.
                               1595                 :                :  */
                               1596                 :                : JoinExpr *
 6587 tgl@sss.pgh.pa.us        1597                 :           8181 : convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink,
                               1598                 :                :                                bool under_not, Relids available_rels)
                               1599                 :                : {
                               1600                 :                :     JoinExpr   *result;
                               1601                 :           8181 :     Query      *parse = root->parse;
                               1602                 :           8181 :     Query      *subselect = (Query *) sublink->subselect;
                               1603                 :                :     Node       *whereClause;
                               1604                 :                :     PlannerInfo subroot;
                               1605                 :                :     int         rtoffset;
                               1606                 :                :     int         varno;
                               1607                 :                :     Relids      clause_varnos;
                               1608                 :                :     Relids      upper_varnos;
                               1609                 :                : 
                               1610         [ -  + ]:           8181 :     Assert(sublink->subLinkType == EXISTS_SUBLINK);
                               1611                 :                : 
                               1612                 :                :     /*
                               1613                 :                :      * Can't flatten if it contains WITH.  (We could arrange to pull up the
                               1614                 :                :      * WITH into the parent query's cteList, but that risks changing the
                               1615                 :                :      * semantics, since a WITH ought to be executed once per associated query
                               1616                 :                :      * call.)  Note that convert_ANY_sublink_to_join doesn't have to reject
                               1617                 :                :      * this case, since it just produces a subquery RTE that doesn't have to
                               1618                 :                :      * get flattened into the parent query.
                               1619                 :                :      */
 6065                          1620         [ -  + ]:           8181 :     if (subselect->cteList)
 6065 tgl@sss.pgh.pa.us        1621                 :UBC           0 :         return NULL;
                               1622                 :                : 
                               1623                 :                :     /*
                               1624                 :                :      * Copy the subquery so we can modify it safely (see comments in
                               1625                 :                :      * make_subplan).
                               1626                 :                :      */
 3458 peter_e@gmx.net          1627                 :CBC        8181 :     subselect = copyObject(subselect);
                               1628                 :                : 
                               1629                 :                :     /*
                               1630                 :                :      * See if the subquery can be simplified based on the knowledge that it's
                               1631                 :                :      * being used in EXISTS().  If we aren't able to get rid of its
                               1632                 :                :      * targetlist, we have to fail, because the pullup operation leaves us
                               1633                 :                :      * with noplace to evaluate the targetlist.
                               1634                 :                :      */
 4296 tgl@sss.pgh.pa.us        1635         [ +  + ]:           8181 :     if (!simplify_EXISTS_query(root, subselect))
 6392                          1636                 :             22 :         return NULL;
                               1637                 :                : 
                               1638                 :                :     /*
                               1639                 :                :      * Separate out the WHERE clause.  (We could theoretically also remove
                               1640                 :                :      * top-level plain JOIN/ON clauses, but it's probably not worth the
                               1641                 :                :      * trouble.)
                               1642                 :                :      */
 6587                          1643                 :           8159 :     whereClause = subselect->jointree->quals;
                               1644                 :           8159 :     subselect->jointree->quals = NULL;
                               1645                 :                : 
                               1646                 :                :     /*
                               1647                 :                :      * The rest of the sub-select must not refer to any Vars of the parent
                               1648                 :                :      * query.  (Vars of higher levels should be okay, though.)
                               1649                 :                :      */
                               1650         [ +  + ]:           8159 :     if (contain_vars_of_level((Node *) subselect, 1))
 6392 tgl@sss.pgh.pa.us        1651                 :GBC           2 :         return NULL;
                               1652                 :                : 
                               1653                 :                :     /*
                               1654                 :                :      * On the other hand, the WHERE clause must contain some Vars of the
                               1655                 :                :      * parent query, else it's not gonna be a join.
                               1656                 :                :      */
 6587 tgl@sss.pgh.pa.us        1657         [ +  + ]:CBC        8157 :     if (!contain_vars_of_level(whereClause, 1))
 6392                          1658                 :             71 :         return NULL;
                               1659                 :                : 
                               1660                 :                :     /*
                               1661                 :                :      * We don't risk optimizing if the WHERE clause is volatile, either.
                               1662                 :                :      */
 6587                          1663         [ -  + ]:           8086 :     if (contain_volatile_functions(whereClause))
 6392 tgl@sss.pgh.pa.us        1664                 :UBC           0 :         return NULL;
                               1665                 :                : 
                               1666                 :                :     /*
                               1667                 :                :      * Scan the rangetable for relation RTEs and retrieve the necessary
                               1668                 :                :      * catalog information for each relation.  Using this information, clear
                               1669                 :                :      * the inh flag for any relation that has no children, collect not-null
                               1670                 :                :      * attribute numbers for any relation that has column not-null
                               1671                 :                :      * constraints, and expand virtual generated columns for any relation that
                               1672                 :                :      * contains them.
                               1673                 :                :      *
                               1674                 :                :      * Note: we construct up an entirely dummy PlannerInfo for use here.  This
                               1675                 :                :      * is fine because only the "glob" and "parse" links will be used in this
                               1676                 :                :      * case.
                               1677                 :                :      *
                               1678                 :                :      * Note: we temporarily assign back the WHERE clause so that any virtual
                               1679                 :                :      * generated column references within it can be expanded.  It should be
                               1680                 :                :      * separated out again afterward.
                               1681                 :                :      */
  401 rguo@postgresql.org      1682   [ +  -  +  -  :CBC      760084 :     MemSet(&subroot, 0, sizeof(subroot));
                                     +  -  +  -  +  
                                                 + ]
                               1683                 :           8086 :     subroot.type = T_PlannerInfo;
                               1684                 :           8086 :     subroot.glob = root->glob;
                               1685                 :           8086 :     subroot.parse = subselect;
                               1686                 :           8086 :     subselect->jointree->quals = whereClause;
                               1687                 :           8086 :     subselect = preprocess_relation_rtes(&subroot);
                               1688                 :                : 
                               1689                 :                :     /*
                               1690                 :                :      * Now separate out the WHERE clause again.
                               1691                 :                :      */
                               1692                 :           8086 :     whereClause = subselect->jointree->quals;
                               1693                 :           8086 :     subselect->jointree->quals = NULL;
                               1694                 :                : 
                               1695                 :                :     /*
                               1696                 :                :      * The subquery must have a nonempty jointree, but we can make it so.
                               1697                 :                :      */
 2768 tgl@sss.pgh.pa.us        1698                 :           8086 :     replace_empty_jointree(subselect);
                               1699                 :                : 
                               1700                 :                :     /*
                               1701                 :                :      * Prepare to pull up the sub-select into top range table.
                               1702                 :                :      *
                               1703                 :                :      * We rely here on the assumption that the outer query has no references
                               1704                 :                :      * to the inner (necessarily true). Therefore this is a lot easier than
                               1705                 :                :      * what pull_up_subqueries has to go through.
                               1706                 :                :      *
                               1707                 :                :      * In fact, it's even easier than what convert_ANY_sublink_to_join has to
                               1708                 :                :      * do.  The machinations of simplify_EXISTS_query ensured that there is
                               1709                 :                :      * nothing interesting in the subquery except an rtable and jointree, and
                               1710                 :                :      * even the jointree FromExpr no longer has quals.  So we can just append
                               1711                 :                :      * the rtable to our own and use the FromExpr in our jointree. But first,
                               1712                 :                :      * adjust all level-zero varnos in the subquery to account for the rtable
                               1713                 :                :      * merger.
                               1714                 :                :      */
 6587                          1715                 :           8086 :     rtoffset = list_length(parse->rtable);
                               1716                 :           8086 :     OffsetVarNodes((Node *) subselect, rtoffset, 0);
                               1717                 :           8086 :     OffsetVarNodes(whereClause, rtoffset, 0);
                               1718                 :                : 
                               1719                 :                :     /*
                               1720                 :                :      * Upper-level vars in subquery will now be one level closer to their
                               1721                 :                :      * parent than before; in particular, anything that had been level 1
                               1722                 :                :      * becomes level zero.
                               1723                 :                :      */
                               1724                 :           8086 :     IncrementVarSublevelsUp((Node *) subselect, -1, 1);
                               1725                 :           8086 :     IncrementVarSublevelsUp(whereClause, -1, 1);
                               1726                 :                : 
                               1727                 :                :     /*
                               1728                 :                :      * Now that the WHERE clause is adjusted to match the parent query
                               1729                 :                :      * environment, we can easily identify all the level-zero rels it uses.
                               1730                 :                :      * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
                               1731                 :                :      * not.
                               1732                 :                :      */
 2044                          1733                 :           8086 :     clause_varnos = pull_varnos(root, whereClause);
 6392                          1734                 :           8086 :     upper_varnos = NULL;
 1274                          1735                 :           8086 :     varno = -1;
                               1736         [ +  + ]:          27155 :     while ((varno = bms_next_member(clause_varnos, varno)) >= 0)
                               1737                 :                :     {
 6587                          1738         [ +  + ]:          19069 :         if (varno <= rtoffset)
 6392                          1739                 :          10963 :             upper_varnos = bms_add_member(upper_varnos, varno);
                               1740                 :                :     }
 6587                          1741                 :           8086 :     bms_free(clause_varnos);
 6392                          1742         [ -  + ]:           8086 :     Assert(!bms_is_empty(upper_varnos));
                               1743                 :                : 
                               1744                 :                :     /*
                               1745                 :                :      * Now that we've got the set of upper-level varnos, we can make the last
                               1746                 :                :      * check: only available_rels can be referenced.
                               1747                 :                :      */
                               1748         [ +  + ]:           8086 :     if (!bms_is_subset(upper_varnos, available_rels))
                               1749                 :             26 :         return NULL;
                               1750                 :                : 
                               1751                 :                :     /*
                               1752                 :                :      * Now we can attach the modified subquery rtable to the parent. This also
                               1753                 :                :      * adds subquery's RTEPermissionInfos into the upper query.
                               1754                 :                :      */
 1360 alvherre@alvh.no-ip.     1755                 :           8060 :     CombineRangeTables(&parse->rtable, &parse->rteperminfos,
                               1756                 :                :                        subselect->rtable, subselect->rteperminfos);
                               1757                 :                : 
                               1758                 :                :     /*
                               1759                 :                :      * And finally, build the JoinExpr node.
                               1760                 :                :      */
 6392 tgl@sss.pgh.pa.us        1761                 :           8060 :     result = makeNode(JoinExpr);
                               1762         [ +  + ]:           8060 :     result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
                               1763                 :           8060 :     result->isNatural = false;
                               1764                 :           8060 :     result->larg = NULL;     /* caller must fill this in */
                               1765                 :                :     /* flatten out the FromExpr node if it's useless */
                               1766         [ +  + ]:           8060 :     if (list_length(subselect->jointree->fromlist) == 1)
                               1767                 :           8044 :         result->rarg = (Node *) linitial(subselect->jointree->fromlist);
                               1768                 :                :     else
                               1769                 :             16 :         result->rarg = (Node *) subselect->jointree;
 6251 peter_e@gmx.net          1770                 :           8060 :     result->usingClause = NIL;
 1975 peter@eisentraut.org     1771                 :           8060 :     result->join_using_alias = NULL;
 6392 tgl@sss.pgh.pa.us        1772                 :           8060 :     result->quals = whereClause;
                               1773                 :           8060 :     result->alias = NULL;
                               1774                 :           8060 :     result->rtindex = 0;     /* we don't need an RTE for it */
                               1775                 :                : 
                               1776                 :           8060 :     return result;
                               1777                 :                : }
                               1778                 :                : 
                               1779                 :                : /*
                               1780                 :                :  * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery
                               1781                 :                :  *
                               1782                 :                :  * The only thing that matters about an EXISTS query is whether it returns
                               1783                 :                :  * zero or more than zero rows.  Therefore, we can remove certain SQL features
                               1784                 :                :  * that won't affect that.  The only part that is really likely to matter in
                               1785                 :                :  * typical usage is simplifying the targetlist: it's a common habit to write
                               1786                 :                :  * "SELECT * FROM" even though there is no need to evaluate any columns.
                               1787                 :                :  *
                               1788                 :                :  * Note: by suppressing the targetlist we could cause an observable behavioral
                               1789                 :                :  * change, namely that any errors that might occur in evaluating the tlist
                               1790                 :                :  * won't occur, nor will other side-effects of volatile functions.  This seems
                               1791                 :                :  * unlikely to bother anyone in practice.  Note that any column privileges are
                               1792                 :                :  * still checked even if the reference is removed here.
                               1793                 :                :  *
                               1794                 :                :  * The SQL standard specifies that a SELECT * immediately inside EXISTS
                               1795                 :                :  * expands to not all columns but an arbitrary literal.  That is kind of the
                               1796                 :                :  * same idea, but our optimization goes further in that it throws away the
                               1797                 :                :  * entire targetlist, and not only if it was written as *.
                               1798                 :                :  *
                               1799                 :                :  * Returns true if was able to discard the targetlist, else false.
                               1800                 :                :  */
                               1801                 :                : static bool
 4296                          1802                 :          11489 : simplify_EXISTS_query(PlannerInfo *root, Query *query)
                               1803                 :                : {
                               1804                 :                :     /*
                               1805                 :                :      * We don't try to simplify at all if the query uses set operations,
                               1806                 :                :      * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
                               1807                 :                :      * UPDATE/SHARE; none of these seem likely in normal usage and their
                               1808                 :                :      * possible effects are complex.  (Note: we could ignore an "OFFSET 0"
                               1809                 :                :      * clause, but that traditionally is used as an optimization fence, so we
                               1810                 :                :      * don't.)
                               1811                 :                :      */
 6579                          1812         [ +  - ]:          11489 :     if (query->commandType != CMD_SELECT ||
                               1813         [ +  - ]:          11489 :         query->setOperations ||
                               1814         [ +  - ]:          11489 :         query->hasAggs ||
 4121 andres@anarazel.de       1815         [ +  - ]:          11489 :         query->groupingSets ||
 6451 tgl@sss.pgh.pa.us        1816         [ +  - ]:          11489 :         query->hasWindowFuncs ||
 3635                          1817         [ +  - ]:          11489 :         query->hasTargetSRFs ||
 5662                          1818         [ +  - ]:          11489 :         query->hasModifyingCTE ||
 6579                          1819         [ +  - ]:          11489 :         query->havingQual ||
                               1820         [ +  + ]:          11489 :         query->limitOffset ||
                               1821         [ +  + ]:          11469 :         query->rowMarks)
                               1822                 :             34 :         return false;
                               1823                 :                : 
                               1824                 :                :     /*
                               1825                 :                :      * LIMIT with a constant positive (or NULL) value doesn't affect the
                               1826                 :                :      * semantics of EXISTS, so let's ignore such clauses.  This is worth doing
                               1827                 :                :      * because people accustomed to certain other DBMSes may be in the habit
                               1828                 :                :      * of writing EXISTS(SELECT ... LIMIT 1) as an optimization.  If there's a
                               1829                 :                :      * LIMIT with anything else as argument, though, we can't simplify.
                               1830                 :                :      */
 4296                          1831         [ +  + ]:          11455 :     if (query->limitCount)
                               1832                 :                :     {
                               1833                 :                :         /*
                               1834                 :                :          * The LIMIT clause has not yet been through eval_const_expressions,
                               1835                 :                :          * so we have to apply that here.  It might seem like this is a waste
                               1836                 :                :          * of cycles, since the only case plausibly worth worrying about is
                               1837                 :                :          * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
                               1838                 :                :          * so we have to fold constants or we're not going to recognize it.
                               1839                 :                :          */
                               1840                 :             20 :         Node       *node = eval_const_expressions(root, query->limitCount);
                               1841                 :                :         Const      *limit;
                               1842                 :                : 
                               1843                 :                :         /* Might as well update the query if we simplified the clause. */
                               1844                 :             20 :         query->limitCount = node;
                               1845                 :                : 
                               1846         [ -  + ]:             20 :         if (!IsA(node, Const))
 4296 tgl@sss.pgh.pa.us        1847                 :UBC           0 :             return false;
                               1848                 :                : 
 4296 tgl@sss.pgh.pa.us        1849                 :CBC          20 :         limit = (Const *) node;
                               1850         [ -  + ]:             20 :         Assert(limit->consttype == INT8OID);
                               1851   [ +  +  +  + ]:             20 :         if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
                               1852                 :             10 :             return false;
                               1853                 :                : 
                               1854                 :                :         /* Whether or not the targetlist is safe, we can drop the LIMIT. */
                               1855                 :             10 :         query->limitCount = NULL;
                               1856                 :                :     }
                               1857                 :                : 
                               1858                 :                :     /*
                               1859                 :                :      * Otherwise, we can throw away the targetlist, as well as any GROUP,
                               1860                 :                :      * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
                               1861                 :                :      * change a nonzero-rows result to zero rows or vice versa.  (Furthermore,
                               1862                 :                :      * since our parsetree representation of these clauses depends on the
                               1863                 :                :      * targetlist, we'd better throw them away if we drop the targetlist.)
                               1864                 :                :      */
 6579                          1865                 :          11445 :     query->targetList = NIL;
                               1866                 :          11445 :     query->groupClause = NIL;
 6451                          1867                 :          11445 :     query->windowClause = NIL;
 6579                          1868                 :          11445 :     query->distinctClause = NIL;
                               1869                 :          11445 :     query->sortClause = NIL;
                               1870                 :          11445 :     query->hasDistinctOn = false;
                               1871                 :                : 
                               1872                 :                :     /*
                               1873                 :                :      * Since we have thrown away the GROUP BY clauses, we'd better get rid of
                               1874                 :                :      * the RTE_GROUP RTE and clear the hasGroupRTE flag.  To safely get rid of
                               1875                 :                :      * the RTE_GROUP RTE without shifting the index of any subsequent RTE in
                               1876                 :                :      * the rtable, we convert the RTE to be RTE_RESULT type in-place, and zero
                               1877                 :                :      * out RTE_GROUP-specific fields.
                               1878                 :                :      */
  183 rguo@postgresql.org      1879         [ +  + ]:          11445 :     if (query->hasGroupRTE)
                               1880                 :                :     {
                               1881   [ +  -  +  -  :             15 :         foreach_node(RangeTblEntry, rte, query->rtable)
                                              +  + ]
                               1882                 :                :         {
                               1883         [ +  + ]:             10 :             if (rte->rtekind == RTE_GROUP)
                               1884                 :                :             {
                               1885                 :              5 :                 rte->rtekind = RTE_RESULT;
                               1886                 :              5 :                 rte->groupexprs = NIL;
                               1887                 :                : 
                               1888                 :                :                 /* A query should only have one RTE_GROUP, so we can stop. */
                               1889                 :              5 :                 break;
                               1890                 :                :             }
                               1891                 :                :         }
                               1892                 :                : 
                               1893                 :              5 :         query->hasGroupRTE = false;
                               1894                 :                :     }
                               1895                 :                : 
 6579 tgl@sss.pgh.pa.us        1896                 :          11445 :     return true;
                               1897                 :                : }
                               1898                 :                : 
                               1899                 :                : /*
                               1900                 :                :  * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink
                               1901                 :                :  *
                               1902                 :                :  * The subselect is expected to be a fresh copy that we can munge up,
                               1903                 :                :  * and to have been successfully passed through simplify_EXISTS_query.
                               1904                 :                :  *
                               1905                 :                :  * On success, the modified subselect is returned, and we store a suitable
                               1906                 :                :  * upper-level test expression at *testexpr, plus a list of the subselect's
                               1907                 :                :  * output Params at *paramIds.  (The test expression is already Param-ified
                               1908                 :                :  * and hence need not go through convert_testexpr, which is why we have to
                               1909                 :                :  * deal with the Param IDs specially.)
                               1910                 :                :  *
                               1911                 :                :  * On failure, returns NULL.
                               1912                 :                :  */
                               1913                 :                : static Query *
                               1914                 :           1532 : convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect,
                               1915                 :                :                       Node **testexpr, List **paramIds)
                               1916                 :                : {
                               1917                 :                :     Node       *whereClause;
                               1918                 :                :     PlannerInfo subroot;
                               1919                 :                :     List       *leftargs,
                               1920                 :                :                *rightargs,
                               1921                 :                :                *opids,
                               1922                 :                :                *opcollations,
                               1923                 :                :                *newWhere,
                               1924                 :                :                *tlist,
                               1925                 :                :                *testlist,
                               1926                 :                :                *paramids;
                               1927                 :                :     ListCell   *lc,
                               1928                 :                :                *rc,
                               1929                 :                :                *oc,
                               1930                 :                :                *cc;
                               1931                 :                :     AttrNumber  resno;
                               1932                 :                : 
                               1933                 :                :     /*
                               1934                 :                :      * Query must not require a targetlist, since we have to insert a new one.
                               1935                 :                :      * Caller should have dealt with the case already.
                               1936                 :                :      */
                               1937         [ -  + ]:           1532 :     Assert(subselect->targetList == NIL);
                               1938                 :                : 
                               1939                 :                :     /*
                               1940                 :                :      * Separate out the WHERE clause.  (We could theoretically also remove
                               1941                 :                :      * top-level plain JOIN/ON clauses, but it's probably not worth the
                               1942                 :                :      * trouble.)
                               1943                 :                :      */
                               1944                 :           1532 :     whereClause = subselect->jointree->quals;
                               1945                 :           1532 :     subselect->jointree->quals = NULL;
                               1946                 :                : 
                               1947                 :                :     /*
                               1948                 :                :      * The rest of the sub-select must not refer to any Vars of the parent
                               1949                 :                :      * query.  (Vars of higher levels should be okay, though.)
                               1950                 :                :      *
                               1951                 :                :      * Note: we need not check for Aggrefs separately because we know the
                               1952                 :                :      * sub-select is as yet unoptimized; any uplevel Aggref must therefore
                               1953                 :                :      * contain an uplevel Var reference.  This is not the case below ...
                               1954                 :                :      */
                               1955         [ +  + ]:           1532 :     if (contain_vars_of_level((Node *) subselect, 1))
                               1956                 :              7 :         return NULL;
                               1957                 :                : 
                               1958                 :                :     /*
                               1959                 :                :      * We don't risk optimizing if the WHERE clause is volatile, either.
                               1960                 :                :      */
                               1961         [ -  + ]:           1525 :     if (contain_volatile_functions(whereClause))
 6579 tgl@sss.pgh.pa.us        1962                 :UBC           0 :         return NULL;
                               1963                 :                : 
                               1964                 :                :     /*
                               1965                 :                :      * Clean up the WHERE clause by doing const-simplification etc on it.
                               1966                 :                :      * Aside from simplifying the processing we're about to do, this is
                               1967                 :                :      * important for being able to pull chunks of the WHERE clause up into the
                               1968                 :                :      * parent query.  Since we are invoked partway through the parent's
                               1969                 :                :      * preprocess_expression() work, earlier steps of preprocess_expression()
                               1970                 :                :      * wouldn't get applied to the pulled-up stuff unless we do them here. For
                               1971                 :                :      * the parts of the WHERE clause that get put back into the child query,
                               1972                 :                :      * this work is partially duplicative, but it shouldn't hurt.
                               1973                 :                :      *
                               1974                 :                :      * Note: we do not run flatten_join_alias_vars.  This is OK because any
                               1975                 :                :      * parent aliases were flattened already, and we're not going to pull any
                               1976                 :                :      * child Vars (of any description) into the parent.
                               1977                 :                :      *
                               1978                 :                :      * Note: we construct up an entirely dummy PlannerInfo to pass to
                               1979                 :                :      * eval_const_expressions.  This is fine because only the "glob" and
                               1980                 :                :      * "parse" links are used by eval_const_expressions.
                               1981                 :                :      */
  401 rguo@postgresql.org      1982   [ +  -  +  -  :CBC      143350 :     MemSet(&subroot, 0, sizeof(subroot));
                                     +  -  +  -  +  
                                                 + ]
                               1983                 :           1525 :     subroot.type = T_PlannerInfo;
                               1984                 :           1525 :     subroot.glob = root->glob;
                               1985                 :           1525 :     subroot.parse = subselect;
                               1986                 :           1525 :     whereClause = eval_const_expressions(&subroot, whereClause);
 3091 tgl@sss.pgh.pa.us        1987                 :           1525 :     whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
 6579                          1988                 :           1525 :     whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
                               1989                 :                : 
                               1990                 :                :     /*
                               1991                 :                :      * We now have a flattened implicit-AND list of clauses, which we try to
                               1992                 :                :      * break apart into "outervar = innervar" hash clauses. Anything that
                               1993                 :                :      * can't be broken apart just goes back into the newWhere list.  Note that
                               1994                 :                :      * we aren't trying hard yet to ensure that we have only outer or only
                               1995                 :                :      * inner on each side; we'll check that if we get to the end.
                               1996                 :                :      */
 5640                          1997                 :           1525 :     leftargs = rightargs = opids = opcollations = newWhere = NIL;
 6579                          1998   [ +  -  +  +  :           6149 :     foreach(lc, (List *) whereClause)
                                              +  + ]
                               1999                 :                :     {
                               2000                 :           4624 :         OpExpr     *expr = (OpExpr *) lfirst(lc);
                               2001                 :                : 
                               2002   [ +  +  +  + ]:           7483 :         if (IsA(expr, OpExpr) &&
                               2003                 :           2859 :             hash_ok_operator(expr))
                               2004                 :                :         {
 6286 bruce@momjian.us         2005                 :           2415 :             Node       *leftarg = (Node *) linitial(expr->args);
                               2006                 :           2415 :             Node       *rightarg = (Node *) lsecond(expr->args);
                               2007                 :                : 
 6579 tgl@sss.pgh.pa.us        2008         [ +  + ]:           2415 :             if (contain_vars_of_level(leftarg, 1))
                               2009                 :                :             {
                               2010                 :            227 :                 leftargs = lappend(leftargs, leftarg);
                               2011                 :            227 :                 rightargs = lappend(rightargs, rightarg);
                               2012                 :            227 :                 opids = lappend_oid(opids, expr->opno);
 5640                          2013                 :            227 :                 opcollations = lappend_oid(opcollations, expr->inputcollid);
 6579                          2014                 :            227 :                 continue;
                               2015                 :                :             }
                               2016         [ +  + ]:           2188 :             if (contain_vars_of_level(rightarg, 1))
                               2017                 :                :             {
                               2018                 :                :                 /*
                               2019                 :                :                  * We must commute the clause to put the outer var on the
                               2020                 :                :                  * left, because the hashing code in nodeSubplan.c expects
                               2021                 :                :                  * that.  This probably shouldn't ever fail, since hashable
                               2022                 :                :                  * operators ought to have commutators, but be paranoid.
                               2023                 :                :                  */
                               2024                 :           1780 :                 expr->opno = get_commutator(expr->opno);
                               2025   [ +  -  +  - ]:           1780 :                 if (OidIsValid(expr->opno) && hash_ok_operator(expr))
                               2026                 :                :                 {
                               2027                 :           1780 :                     leftargs = lappend(leftargs, rightarg);
                               2028                 :           1780 :                     rightargs = lappend(rightargs, leftarg);
                               2029                 :           1780 :                     opids = lappend_oid(opids, expr->opno);
 5640                          2030                 :           1780 :                     opcollations = lappend_oid(opcollations, expr->inputcollid);
 6579                          2031                 :           1780 :                     continue;
                               2032                 :                :                 }
                               2033                 :                :                 /* If no commutator, no chance to optimize the WHERE clause */
 6579 tgl@sss.pgh.pa.us        2034                 :UBC           0 :                 return NULL;
                               2035                 :                :             }
                               2036                 :                :         }
                               2037                 :                :         /* Couldn't handle it as a hash clause */
 6579 tgl@sss.pgh.pa.us        2038                 :CBC        2617 :         newWhere = lappend(newWhere, expr);
                               2039                 :                :     }
                               2040                 :                : 
                               2041                 :                :     /*
                               2042                 :                :      * If we didn't find anything we could convert, fail.
                               2043                 :                :      */
                               2044         [ +  + ]:           1525 :     if (leftargs == NIL)
                               2045                 :            192 :         return NULL;
                               2046                 :                : 
                               2047                 :                :     /*
                               2048                 :                :      * There mustn't be any parent Vars or Aggs in the stuff that we intend to
                               2049                 :                :      * put back into the child query.  Note: you might think we don't need to
                               2050                 :                :      * check for Aggs separately, because an uplevel Agg must contain an
                               2051                 :                :      * uplevel Var in its argument.  But it is possible that the uplevel Var
                               2052                 :                :      * got optimized away by eval_const_expressions.  Consider
                               2053                 :                :      *
                               2054                 :                :      * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
                               2055                 :                :      */
                               2056   [ +  +  -  + ]:           2611 :     if (contain_vars_of_level((Node *) newWhere, 1) ||
                               2057                 :           1278 :         contain_vars_of_level((Node *) rightargs, 1))
                               2058                 :             55 :         return NULL;
                               2059   [ +  +  +  - ]:           1318 :     if (root->parse->hasAggs &&
                               2060         [ -  + ]:             80 :         (contain_aggs_of_level((Node *) newWhere, 1) ||
                               2061                 :             40 :          contain_aggs_of_level((Node *) rightargs, 1)))
 6579 tgl@sss.pgh.pa.us        2062                 :UBC           0 :         return NULL;
                               2063                 :                : 
                               2064                 :                :     /*
                               2065                 :                :      * And there can't be any child Vars in the stuff we intend to pull up.
                               2066                 :                :      * (Note: we'd need to check for child Aggs too, except we know the child
                               2067                 :                :      * has no aggs at all because of simplify_EXISTS_query's check. The same
                               2068                 :                :      * goes for window functions.)
                               2069                 :                :      */
 6579 tgl@sss.pgh.pa.us        2070         [ -  + ]:CBC        1278 :     if (contain_vars_of_level((Node *) leftargs, 0))
 6579 tgl@sss.pgh.pa.us        2071                 :UBC           0 :         return NULL;
                               2072                 :                : 
                               2073                 :                :     /*
                               2074                 :                :      * Also reject sublinks in the stuff we intend to pull up.  (It might be
                               2075                 :                :      * possible to support this, but doesn't seem worth the complication.)
                               2076                 :                :      */
 6579 tgl@sss.pgh.pa.us        2077         [ -  + ]:CBC        1278 :     if (contain_subplans((Node *) leftargs))
 6579 tgl@sss.pgh.pa.us        2078                 :UBC           0 :         return NULL;
                               2079                 :                : 
                               2080                 :                :     /*
                               2081                 :                :      * Okay, adjust the sublevelsup in the stuff we're pulling up.
                               2082                 :                :      */
 6579 tgl@sss.pgh.pa.us        2083                 :CBC        1278 :     IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
                               2084                 :                : 
                               2085                 :                :     /*
                               2086                 :                :      * Put back any child-level-only WHERE clauses.
                               2087                 :                :      */
                               2088         [ +  + ]:           1278 :     if (newWhere)
                               2089                 :           1100 :         subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
                               2090                 :                : 
                               2091                 :                :     /*
                               2092                 :                :      * Build a new targetlist for the child that emits the expressions we
                               2093                 :                :      * need.  Concurrently, build a testexpr for the parent using Params to
                               2094                 :                :      * reference the child outputs.  (Since we generate Params directly here,
                               2095                 :                :      * there will be no need to convert the testexpr in build_subplan.)
                               2096                 :                :      */
                               2097                 :           1278 :     tlist = testlist = paramids = NIL;
                               2098                 :           1278 :     resno = 1;
 2737                          2099   [ +  -  +  +  :           3230 :     forfour(lc, leftargs, rc, rightargs, oc, opids, cc, opcollations)
                                     +  -  +  +  +  
                                     -  +  +  +  -  
                                     +  +  +  +  +  
                                     -  +  -  +  -  
                                              +  + ]
                               2100                 :                :     {
 6579                          2101                 :           1952 :         Node       *leftarg = (Node *) lfirst(lc);
                               2102                 :           1952 :         Node       *rightarg = (Node *) lfirst(rc);
                               2103                 :           1952 :         Oid         opid = lfirst_oid(oc);
 5640                          2104                 :           1952 :         Oid         opcollation = lfirst_oid(cc);
                               2105                 :                :         Param      *param;
                               2106                 :                : 
 2785                          2107                 :           1952 :         param = generate_new_exec_param(root,
                               2108                 :                :                                         exprType(rightarg),
                               2109                 :                :                                         exprTypmod(rightarg),
                               2110                 :                :                                         exprCollation(rightarg));
 6579                          2111                 :           1952 :         tlist = lappend(tlist,
                               2112                 :           1952 :                         makeTargetEntry((Expr *) rightarg,
                               2113                 :           1952 :                                         resno++,
                               2114                 :                :                                         NULL,
                               2115                 :                :                                         false));
                               2116                 :           1952 :         testlist = lappend(testlist,
                               2117                 :           1952 :                            make_opclause(opid, BOOLOID, false,
                               2118                 :                :                                          (Expr *) leftarg, (Expr *) param,
                               2119                 :                :                                          InvalidOid, opcollation));
                               2120                 :           1952 :         paramids = lappend_int(paramids, param->paramid);
                               2121                 :                :     }
                               2122                 :                : 
                               2123                 :                :     /* Put everything where it should go, and we're done */
                               2124                 :           1278 :     subselect->targetList = tlist;
                               2125                 :           1278 :     *testexpr = (Node *) make_ands_explicit(testlist);
                               2126                 :           1278 :     *paramIds = paramids;
                               2127                 :                : 
                               2128                 :           1278 :     return subselect;
                               2129                 :                : }
                               2130                 :                : 
                               2131                 :                : 
                               2132                 :                : /*
                               2133                 :                :  * Replace correlation vars (uplevel vars) with Params.
                               2134                 :                :  *
                               2135                 :                :  * Uplevel PlaceHolderVars, aggregates, GROUPING() expressions,
                               2136                 :                :  * MergeSupportFuncs, and ReturningExprs are replaced, too.
                               2137                 :                :  *
                               2138                 :                :  * Note: it is critical that this runs immediately after SS_process_sublinks.
                               2139                 :                :  * Since we do not recurse into the arguments of uplevel PHVs and aggregates,
                               2140                 :                :  * they will get copied to the appropriate subplan args list in the parent
                               2141                 :                :  * query with uplevel vars not replaced by Params, but only adjusted in level
                               2142                 :                :  * (see replace_outer_placeholdervar and replace_outer_agg).  That's exactly
                               2143                 :                :  * what we want for the vars of the parent level --- but if a PHV's or
                               2144                 :                :  * aggregate's argument contains any further-up variables, they have to be
                               2145                 :                :  * replaced with Params in their turn. That will happen when the parent level
                               2146                 :                :  * runs SS_replace_correlation_vars.  Therefore it must do so after expanding
                               2147                 :                :  * its sublinks to subplans.  And we don't want any steps in between, else
                               2148                 :                :  * those steps would never get applied to the argument expressions, either in
                               2149                 :                :  * the parent or the child level.
                               2150                 :                :  *
                               2151                 :                :  * Another fairly tricky thing going on here is the handling of SubLinks in
                               2152                 :                :  * the arguments of uplevel PHVs/aggregates.  Those are not touched inside the
                               2153                 :                :  * intermediate query level, either.  Instead, SS_process_sublinks recurses on
                               2154                 :                :  * them after copying the PHV or Aggref expression into the parent plan level
                               2155                 :                :  * (this is actually taken care of in build_subplan).
                               2156                 :                :  */
                               2157                 :                : Node *
 7129                          2158                 :         145609 : SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
                               2159                 :                : {
                               2160                 :                :     /* No setup needed for tree walk, so away we go */
                               2161                 :         145609 :     return replace_correlation_vars_mutator(expr, root);
                               2162                 :                : }
                               2163                 :                : 
                               2164                 :                : static Node *
                               2165                 :        1419067 : replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
                               2166                 :                : {
 9864                          2167         [ +  + ]:        1419067 :     if (node == NULL)
                               2168                 :          57779 :         return NULL;
                               2169         [ +  + ]:        1361288 :     if (IsA(node, Var))
                               2170                 :                :     {
                               2171         [ +  + ]:         366629 :         if (((Var *) node)->varlevelsup > 0)
 7129                          2172                 :          42293 :             return (Node *) replace_outer_var(root, (Var *) node);
                               2173                 :                :     }
 5269                          2174         [ +  + ]:        1318995 :     if (IsA(node, PlaceHolderVar))
                               2175                 :                :     {
                               2176         [ +  + ]:             71 :         if (((PlaceHolderVar *) node)->phlevelsup > 0)
                               2177                 :             50 :             return (Node *) replace_outer_placeholdervar(root,
                               2178                 :                :                                                          (PlaceHolderVar *) node);
                               2179                 :                :     }
 8483                          2180         [ +  + ]:        1318945 :     if (IsA(node, Aggref))
                               2181                 :                :     {
                               2182         [ +  + ]:           7281 :         if (((Aggref *) node)->agglevelsup > 0)
 7129                          2183                 :             57 :             return (Node *) replace_outer_agg(root, (Aggref *) node);
                               2184                 :                :     }
 4121 andres@anarazel.de       2185         [ +  + ]:        1318888 :     if (IsA(node, GroupingFunc))
                               2186                 :                :     {
                               2187         [ +  + ]:             78 :         if (((GroupingFunc *) node)->agglevelsup > 0)
                               2188                 :             57 :             return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
                               2189                 :                :     }
  893 dean.a.rasheed@gmail     2190         [ +  + ]:        1318831 :     if (IsA(node, MergeSupportFunc))
                               2191                 :                :     {
                               2192         [ +  + ]:             30 :         if (root->parse->commandType != CMD_MERGE)
                               2193                 :              5 :             return (Node *) replace_outer_merge_support(root,
                               2194                 :                :                                                         (MergeSupportFunc *) node);
                               2195                 :                :     }
  588                          2196         [ +  + ]:        1318826 :     if (IsA(node, ReturningExpr))
                               2197                 :                :     {
                               2198         [ +  - ]:             15 :         if (((ReturningExpr *) node)->retlevelsup > 0)
                               2199                 :             15 :             return (Node *) replace_outer_returning(root,
                               2200                 :                :                                                     (ReturningExpr *) node);
                               2201                 :                :     }
  637 peter@eisentraut.org     2202                 :        1318811 :     return expression_tree_mutator(node, replace_correlation_vars_mutator, root);
                               2203                 :                : }
                               2204                 :                : 
                               2205                 :                : /*
                               2206                 :                :  * Expand SubLinks to SubPlans in the given expression.
                               2207                 :                :  *
                               2208                 :                :  * The isQual argument tells whether or not this expression is a WHERE/HAVING
                               2209                 :                :  * qualifier expression.  If it is, any sublinks appearing at top level need
                               2210                 :                :  * not distinguish FALSE from UNKNOWN return values.
                               2211                 :                :  */
                               2212                 :                : Node *
 7129 tgl@sss.pgh.pa.us        2213                 :          91277 : SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
                               2214                 :                : {
                               2215                 :                :     process_sublinks_context context;
                               2216                 :                : 
                               2217                 :          91277 :     context.root = root;
                               2218                 :          91277 :     context.isTopQual = isQual;
                               2219                 :          91277 :     return process_sublinks_mutator(expr, &context);
                               2220                 :                : }
                               2221                 :                : 
                               2222                 :                : static Node *
 6860 bruce@momjian.us         2223                 :        1133305 : process_sublinks_mutator(Node *node, process_sublinks_context *context)
                               2224                 :                : {
                               2225                 :                :     process_sublinks_context locContext;
                               2226                 :                : 
 7129 tgl@sss.pgh.pa.us        2227                 :        1133305 :     locContext.root = context->root;
                               2228                 :                : 
 9864                          2229         [ +  + ]:        1133305 :     if (node == NULL)
10222 bruce@momjian.us         2230                 :          44132 :         return NULL;
 9864 tgl@sss.pgh.pa.us        2231         [ +  + ]:        1089173 :     if (IsA(node, SubLink))
                               2232                 :                :     {
 9633 bruce@momjian.us         2233                 :          28750 :         SubLink    *sublink = (SubLink *) node;
                               2234                 :                :         Node       *testexpr;
                               2235                 :                : 
                               2236                 :                :         /*
                               2237                 :                :          * First, recursively process the lefthand-side expressions, if any.
                               2238                 :                :          * They're not top-level anymore.
                               2239                 :                :          */
 7129 tgl@sss.pgh.pa.us        2240                 :          28750 :         locContext.isTopQual = false;
                               2241                 :          28750 :         testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
                               2242                 :                : 
                               2243                 :                :         /*
                               2244                 :                :          * Now build the SubPlan node and make the expr to return.
                               2245                 :                :          */
                               2246                 :          28750 :         return make_subplan(context->root,
 6579                          2247                 :          28750 :                             (Query *) sublink->subselect,
                               2248                 :                :                             sublink->subLinkType,
                               2249                 :                :                             sublink->subLinkId,
                               2250                 :                :                             testexpr,
 7129                          2251                 :          28750 :                             context->isTopQual);
                               2252                 :                :     }
                               2253                 :                : 
                               2254                 :                :     /*
                               2255                 :                :      * Don't recurse into the arguments of an outer PHV, Aggref, GroupingFunc,
                               2256                 :                :      * or ReturningExpr here.  Any SubLinks in the arguments have to be dealt
                               2257                 :                :      * with at the outer query level; they'll be handled when build_subplan
                               2258                 :                :      * collects the PHV, Aggref, GroupingFunc, or ReturningExpr into the
                               2259                 :                :      * arguments to be passed down to the current subplan.
                               2260                 :                :      */
 5269                          2261         [ +  + ]:        1060423 :     if (IsA(node, PlaceHolderVar))
                               2262                 :                :     {
                               2263         [ +  + ]:            216 :         if (((PlaceHolderVar *) node)->phlevelsup > 0)
                               2264                 :             10 :             return node;
                               2265                 :                :     }
                               2266         [ +  + ]:        1060207 :     else if (IsA(node, Aggref))
                               2267                 :                :     {
 6333                          2268         [ +  + ]:            568 :         if (((Aggref *) node)->agglevelsup > 0)
                               2269                 :             15 :             return node;
                               2270                 :                :     }
 1620                          2271         [ +  + ]:        1059639 :     else if (IsA(node, GroupingFunc))
                               2272                 :                :     {
                               2273         [ +  + ]:            137 :         if (((GroupingFunc *) node)->agglevelsup > 0)
                               2274                 :             30 :             return node;
                               2275                 :                :     }
  588 dean.a.rasheed@gmail     2276         [ +  + ]:        1059502 :     else if (IsA(node, ReturningExpr))
                               2277                 :                :     {
                               2278         [ +  + ]:            165 :         if (((ReturningExpr *) node)->retlevelsup > 0)
                               2279                 :              5 :             return node;
                               2280                 :                :     }
                               2281                 :                : 
                               2282                 :                :     /*
                               2283                 :                :      * We should never see a SubPlan expression in the input (since this is
                               2284                 :                :      * the very routine that creates 'em to begin with).  We shouldn't find
                               2285                 :                :      * ourselves invoked directly on a Query, either.
                               2286                 :                :      */
 6579 tgl@sss.pgh.pa.us        2287         [ -  + ]:        1060363 :     Assert(!IsA(node, SubPlan));
                               2288         [ -  + ]:        1060363 :     Assert(!IsA(node, AlternativeSubPlan));
 8623                          2289         [ -  + ]:        1060363 :     Assert(!IsA(node, Query));
                               2290                 :                : 
                               2291                 :                :     /*
                               2292                 :                :      * Because make_subplan() could return an AND or OR clause, we have to
                               2293                 :                :      * take steps to preserve AND/OR flatness of a qual.  We assume the input
                               2294                 :                :      * has been AND/OR flattened and so we need no recursion here.
                               2295                 :                :      *
                               2296                 :                :      * (Due to the coding here, we will not get called on the List subnodes of
                               2297                 :                :      * an AND; and the input is *not* yet in implicit-AND format.  So no check
                               2298                 :                :      * is needed for a bare List.)
                               2299                 :                :      *
                               2300                 :                :      * Anywhere within the top-level AND/OR clause structure, we can tell
                               2301                 :                :      * make_subplan() that NULL and FALSE are interchangeable.  So isTopQual
                               2302                 :                :      * propagates down in both cases.  (Note that this is unlike the meaning
                               2303                 :                :      * of "top level qual" used in most other places in Postgres.)
                               2304                 :                :      */
 2767                          2305         [ +  + ]:        1060363 :     if (is_andclause(node))
                               2306                 :                :     {
 8033 bruce@momjian.us         2307                 :          25502 :         List       *newargs = NIL;
                               2308                 :                :         ListCell   *l;
                               2309                 :                : 
                               2310                 :                :         /* Still at qual top-level */
 7129 tgl@sss.pgh.pa.us        2311                 :          25502 :         locContext.isTopQual = context->isTopQual;
                               2312                 :                : 
 8263                          2313   [ +  -  +  +  :          86569 :         foreach(l, ((BoolExpr *) node)->args)
                                              +  + ]
                               2314                 :                :         {
                               2315                 :                :             Node       *newarg;
                               2316                 :                : 
 7129                          2317                 :          61067 :             newarg = process_sublinks_mutator(lfirst(l), &locContext);
 2767                          2318         [ -  + ]:          61067 :             if (is_andclause(newarg))
 8124 neilc@samurai.com        2319                 :UBC           0 :                 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
                               2320                 :                :             else
 8263 tgl@sss.pgh.pa.us        2321                 :CBC       61067 :                 newargs = lappend(newargs, newarg);
                               2322                 :                :         }
                               2323                 :          25502 :         return (Node *) make_andclause(newargs);
                               2324                 :                :     }
                               2325                 :                : 
 2767                          2326         [ +  + ]:        1034861 :     if (is_orclause(node))
                               2327                 :                :     {
 8033 bruce@momjian.us         2328                 :           2158 :         List       *newargs = NIL;
                               2329                 :                :         ListCell   *l;
                               2330                 :                : 
                               2331                 :                :         /* Still at qual top-level */
 6581 tgl@sss.pgh.pa.us        2332                 :           2158 :         locContext.isTopQual = context->isTopQual;
                               2333                 :                : 
 8263                          2334   [ +  -  +  +  :           7241 :         foreach(l, ((BoolExpr *) node)->args)
                                              +  + ]
                               2335                 :                :         {
                               2336                 :                :             Node       *newarg;
                               2337                 :                : 
 7129                          2338                 :           5083 :             newarg = process_sublinks_mutator(lfirst(l), &locContext);
 2767                          2339         [ -  + ]:           5083 :             if (is_orclause(newarg))
 8124 neilc@samurai.com        2340                 :UBC           0 :                 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
                               2341                 :                :             else
 8263 tgl@sss.pgh.pa.us        2342                 :CBC        5083 :                 newargs = lappend(newargs, newarg);
                               2343                 :                :         }
                               2344                 :           2158 :         return (Node *) make_orclause(newargs);
                               2345                 :                :     }
                               2346                 :                : 
                               2347                 :                :     /*
                               2348                 :                :      * If we recurse down through anything other than an AND or OR node, we
                               2349                 :                :      * are definitely not at top qual level anymore.
                               2350                 :                :      */
 6581                          2351                 :        1032703 :     locContext.isTopQual = false;
                               2352                 :                : 
 9864                          2353                 :        1032703 :     return expression_tree_mutator(node,
                               2354                 :                :                                    process_sublinks_mutator,
                               2355                 :                :                                    &locContext);
                               2356                 :                : }
                               2357                 :                : 
                               2358                 :                : /*
                               2359                 :                :  * SS_identify_outer_params - identify the Params available from outer levels
                               2360                 :                :  *
                               2361                 :                :  * This must be run after SS_replace_correlation_vars and SS_process_sublinks
                               2362                 :                :  * processing is complete in a given query level as well as all of its
                               2363                 :                :  * descendant levels (which means it's most practical to do it at the end of
                               2364                 :                :  * processing the query level).  We compute the set of paramIds that outer
                               2365                 :                :  * levels will make available to this level+descendants, and record it in
                               2366                 :                :  * root->outer_params for use while computing extParam/allParam sets in final
                               2367                 :                :  * plan cleanup.  (We can't just compute it then, because the upper levels'
                               2368                 :                :  * plan_params lists are transient and will be gone by then.)
                               2369                 :                :  */
                               2370                 :                : void
 4034                          2371                 :         390663 : SS_identify_outer_params(PlannerInfo *root)
                               2372                 :                : {
                               2373                 :                :     Bitmapset  *outer_params;
                               2374                 :                :     PlannerInfo *proot;
                               2375                 :                :     ListCell   *l;
                               2376                 :                : 
                               2377                 :                :     /*
                               2378                 :                :      * If no parameters have been assigned anywhere in the tree, we certainly
                               2379                 :                :      * don't need to do anything here.
                               2380                 :                :      */
 3209 rhaas@postgresql.org     2381         [ +  + ]:         390663 :     if (root->glob->paramExecTypes == NIL)
 4034 tgl@sss.pgh.pa.us        2382                 :         262782 :         return;
                               2383                 :                : 
                               2384                 :                :     /*
                               2385                 :                :      * Scan all query levels above this one to see which parameters are due to
                               2386                 :                :      * be available from them, either because lower query levels have
                               2387                 :                :      * requested them (via plan_params) or because they will be available from
                               2388                 :                :      * initPlans of those levels.
                               2389                 :                :      */
                               2390                 :         127881 :     outer_params = NULL;
 5104                          2391         [ +  + ]:         175225 :     for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
                               2392                 :                :     {
                               2393                 :                :         /*
                               2394                 :                :          * Include ordinary Var/PHV/Aggref/GroupingFunc/ReturningExpr params.
                               2395                 :                :          */
                               2396   [ +  +  +  +  :          84165 :         foreach(l, proot->plan_params)
                                              +  + ]
                               2397                 :                :         {
                               2398                 :          36821 :             PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
                               2399                 :                : 
 4034                          2400                 :          36821 :             outer_params = bms_add_member(outer_params, pitem->paramId);
                               2401                 :                :         }
                               2402                 :                :         /* Include any outputs of outer-level initPlans */
 5104                          2403   [ +  +  +  +  :          51652 :         foreach(l, proot->init_plans)
                                              +  + ]
                               2404                 :                :         {
                               2405                 :           4308 :             SubPlan    *initsubplan = (SubPlan *) lfirst(l);
                               2406                 :                :             ListCell   *l2;
                               2407                 :                : 
                               2408   [ +  -  +  +  :           8616 :             foreach(l2, initsubplan->setParam)
                                              +  + ]
                               2409                 :                :             {
 4034                          2410                 :           4308 :                 outer_params = bms_add_member(outer_params, lfirst_int(l2));
                               2411                 :                :             }
                               2412                 :                :         }
                               2413                 :                :         /* Include worktable ID, if a recursive query is being planned */
 5104                          2414         [ +  + ]:          47344 :         if (proot->wt_param_id >= 0)
 4034                          2415                 :           2118 :             outer_params = bms_add_member(outer_params, proot->wt_param_id);
                               2416                 :                :     }
                               2417                 :         127881 :     root->outer_params = outer_params;
                               2418                 :                : }
                               2419                 :                : 
                               2420                 :                : /*
                               2421                 :                :  * SS_charge_for_initplans - account for initplans in Path costs & parallelism
                               2422                 :                :  *
                               2423                 :                :  * If any initPlans have been created in the current query level, they will
                               2424                 :                :  * get attached to the Plan tree created from whichever Path we select from
                               2425                 :                :  * the given rel.  Increment all that rel's Paths' costs to account for them,
                               2426                 :                :  * and if any of the initPlans are parallel-unsafe, mark all the rel's Paths
                               2427                 :                :  * parallel-unsafe as well.
                               2428                 :                :  *
                               2429                 :                :  * This is separate from SS_attach_initplans because we might conditionally
                               2430                 :                :  * create more initPlans during create_plan(), depending on which Path we
                               2431                 :                :  * select.  However, Paths that would generate such initPlans are expected
                               2432                 :                :  * to have included their cost and parallel-safety effects already.
                               2433                 :                :  */
                               2434                 :                : void
 3825                          2435                 :         390663 : SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
                               2436                 :                : {
                               2437                 :                :     Cost        initplan_cost;
                               2438                 :                :     bool        unsafe_initplans;
                               2439                 :                :     ListCell   *lc;
                               2440                 :                : 
                               2441                 :                :     /* Nothing to do if no initPlans */
                               2442         [ +  + ]:         390663 :     if (root->init_plans == NIL)
                               2443                 :         382665 :         return;
                               2444                 :                : 
                               2445                 :                :     /*
                               2446                 :                :      * Compute the cost increment just once, since it will be the same for all
                               2447                 :                :      * Paths.  Also check for parallel-unsafe initPlans.
                               2448                 :                :      */
 1141                          2449                 :           7998 :     SS_compute_initplan_cost(root->init_plans,
                               2450                 :                :                              &initplan_cost, &unsafe_initplans);
                               2451                 :                : 
                               2452                 :                :     /*
                               2453                 :                :      * Now adjust the costs and parallel_safe flags.
                               2454                 :                :      */
 3825                          2455   [ +  -  +  +  :          16135 :     foreach(lc, final_rel->pathlist)
                                              +  + ]
                               2456                 :                :     {
                               2457                 :           8137 :         Path       *path = (Path *) lfirst(lc);
                               2458                 :                : 
                               2459                 :           8137 :         path->startup_cost += initplan_cost;
                               2460                 :           8137 :         path->total_cost += initplan_cost;
 1141                          2461         [ +  + ]:           8137 :         if (unsafe_initplans)
                               2462                 :           4683 :             path->parallel_safe = false;
                               2463                 :                :     }
                               2464                 :                : 
                               2465                 :                :     /*
                               2466                 :                :      * Adjust partial paths' costs too, or forget them entirely if we must
                               2467                 :                :      * consider the rel parallel-unsafe.
                               2468                 :                :      */
                               2469         [ +  + ]:           7998 :     if (unsafe_initplans)
                               2470                 :                :     {
                               2471                 :           4611 :         final_rel->partial_pathlist = NIL;
                               2472                 :           4611 :         final_rel->consider_parallel = false;
                               2473                 :                :     }
                               2474                 :                :     else
                               2475                 :                :     {
                               2476   [ +  +  +  +  :           3397 :         foreach(lc, final_rel->partial_pathlist)
                                              +  + ]
                               2477                 :                :         {
                               2478                 :             10 :             Path       *path = (Path *) lfirst(lc);
                               2479                 :                : 
                               2480                 :             10 :             path->startup_cost += initplan_cost;
                               2481                 :             10 :             path->total_cost += initplan_cost;
                               2482                 :                :         }
                               2483                 :                :     }
                               2484                 :                : 
                               2485                 :                :     /* We needn't do set_cheapest() here, caller will do it */
                               2486                 :                : }
                               2487                 :                : 
                               2488                 :                : /*
                               2489                 :                :  * SS_compute_initplan_cost - count up the cost delta for some initplans
                               2490                 :                :  *
                               2491                 :                :  * The total cost returned in *initplan_cost_p should be added to both the
                               2492                 :                :  * startup and total costs of the plan node the initplans get attached to.
                               2493                 :                :  * We also report whether any of the initplans are not parallel-safe.
                               2494                 :                :  *
                               2495                 :                :  * The primary user of this is SS_charge_for_initplans, but it's also
                               2496                 :                :  * used in adjusting costs when we move initplans to another plan node.
                               2497                 :                :  */
                               2498                 :                : void
                               2499                 :           8208 : SS_compute_initplan_cost(List *init_plans,
                               2500                 :                :                          Cost *initplan_cost_p,
                               2501                 :                :                          bool *unsafe_initplans_p)
                               2502                 :                : {
                               2503                 :                :     Cost        initplan_cost;
                               2504                 :                :     bool        unsafe_initplans;
                               2505                 :                :     ListCell   *lc;
                               2506                 :                : 
                               2507                 :                :     /*
                               2508                 :                :      * We assume each initPlan gets run once during top plan startup.  This is
                               2509                 :                :      * a conservative overestimate, since in fact an initPlan might be
                               2510                 :                :      * executed later than plan startup, or even not at all.
                               2511                 :                :      */
                               2512                 :           8208 :     initplan_cost = 0;
                               2513                 :           8208 :     unsafe_initplans = false;
                               2514   [ +  +  +  +  :          17260 :     foreach(lc, init_plans)
                                              +  + ]
                               2515                 :                :     {
                               2516                 :           9052 :         SubPlan    *initsubplan = lfirst_node(SubPlan, lc);
                               2517                 :                : 
                               2518                 :           9052 :         initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
                               2519         [ +  + ]:           9052 :         if (!initsubplan->parallel_safe)
                               2520                 :           5447 :             unsafe_initplans = true;
                               2521                 :                :     }
                               2522                 :           8208 :     *initplan_cost_p = initplan_cost;
                               2523                 :           8208 :     *unsafe_initplans_p = unsafe_initplans;
                               2524                 :           8208 : }
                               2525                 :                : 
                               2526                 :                : /*
                               2527                 :                :  * SS_attach_initplans - attach initplans to topmost plan node
                               2528                 :                :  *
                               2529                 :                :  * Attach any initplans created in the current query level to the specified
                               2530                 :                :  * plan node, which should normally be the topmost node for the query level.
                               2531                 :                :  * (In principle the initPlans could go in any node at or above where they're
                               2532                 :                :  * referenced; but there seems no reason to put them any lower than the
                               2533                 :                :  * topmost node, so we don't bother to track exactly where they came from.)
                               2534                 :                :  *
                               2535                 :                :  * We do not touch the plan node's cost or parallel_safe flag.  The initplans
                               2536                 :                :  * must have been accounted for in SS_charge_for_initplans, or by any later
                               2537                 :                :  * code that adds initplans via SS_make_initplan_from_plan.
                               2538                 :                :  */
                               2539                 :                : void
 3825                          2540                 :         389526 : SS_attach_initplans(PlannerInfo *root, Plan *plan)
                               2541                 :                : {
                               2542                 :         389526 :     plan->initPlan = root->init_plans;
 8600                          2543                 :         389526 : }
                               2544                 :                : 
                               2545                 :                : /*
                               2546                 :                :  * SS_finalize_plan - do final parameter processing for a completed Plan.
                               2547                 :                :  *
                               2548                 :                :  * This recursively computes the extParam and allParam sets for every Plan
                               2549                 :                :  * node in the given plan tree.  (Oh, and RangeTblFunction.funcparams too.)
                               2550                 :                :  *
                               2551                 :                :  * We assume that SS_finalize_plan has already been run on any initplans or
                               2552                 :                :  * subplans the plan tree could reference.
                               2553                 :                :  */
                               2554                 :                : void
 4034                          2555                 :         141587 : SS_finalize_plan(PlannerInfo *root, Plan *plan)
                               2556                 :                : {
                               2557                 :                :     /* No setup needed, just recurse through plan tree. */
 3284                          2558                 :         141587 :     (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
 4034                          2559                 :         141587 : }
                               2560                 :                : 
                               2561                 :                : /*
                               2562                 :                :  * Recursive processing of all nodes in the plan tree
                               2563                 :                :  *
                               2564                 :                :  * gather_param is the rescan_param of an ancestral Gather/GatherMerge,
                               2565                 :                :  * or -1 if there is none.
                               2566                 :                :  *
                               2567                 :                :  * valid_params is the set of param IDs supplied by outer plan levels
                               2568                 :                :  * that are valid to reference in this plan node or its children.
                               2569                 :                :  *
                               2570                 :                :  * scan_params is a set of param IDs to force scan plan nodes to reference.
                               2571                 :                :  * This is for EvalPlanQual support, and is always NULL at the top of the
                               2572                 :                :  * recursion.
                               2573                 :                :  *
                               2574                 :                :  * The return value is the computed allParam set for the given Plan node.
                               2575                 :                :  * This is just an internal notational convenience: we can add a child
                               2576                 :                :  * plan's allParams to the set of param IDs of interest to this level
                               2577                 :                :  * in the same statement that recurses to that child.
                               2578                 :                :  *
                               2579                 :                :  * Do not scribble on caller's values of valid_params or scan_params!
                               2580                 :                :  *
                               2581                 :                :  * Note: although we attempt to deal with initPlans anywhere in the tree, the
                               2582                 :                :  * logic is not really right.  The problem is that a plan node might return an
                               2583                 :                :  * output Param of its initPlan as a targetlist item, in which case it's valid
                               2584                 :                :  * for the parent plan level to reference that same Param; the parent's usage
                               2585                 :                :  * will be converted into a Var referencing the child plan node by setrefs.c.
                               2586                 :                :  * But this function would see the parent's reference as out of scope and
                               2587                 :                :  * complain about it.  For now, this does not matter because the planner only
                               2588                 :                :  * attaches initPlans to the topmost plan node in a query level, so the case
                               2589                 :                :  * doesn't arise.  If we ever merge this processing into setrefs.c, maybe it
                               2590                 :                :  * can be handled more cleanly.
                               2591                 :                :  */
                               2592                 :                : static Bitmapset *
 3284                          2593                 :        1186763 : finalize_plan(PlannerInfo *root, Plan *plan,
                               2594                 :                :               int gather_param,
                               2595                 :                :               Bitmapset *valid_params,
                               2596                 :                :               Bitmapset *scan_params)
                               2597                 :                : {
                               2598                 :                :     finalize_primnode_context context;
                               2599                 :                :     int         locally_added_param;
                               2600                 :                :     Bitmapset  *nestloop_params;
                               2601                 :                :     Bitmapset  *initExtParam;
                               2602                 :                :     Bitmapset  *initSetParam;
                               2603                 :                :     Bitmapset  *child_params;
                               2604                 :                :     ListCell   *l;
                               2605                 :                : 
10409 bruce@momjian.us         2606         [ +  + ]:        1186763 :     if (plan == NULL)
 8600 tgl@sss.pgh.pa.us        2607                 :         688006 :         return NULL;
                               2608                 :                : 
 7126                          2609                 :         498757 :     context.root = root;
 8600                          2610                 :         498757 :     context.paramids = NULL;    /* initialize set to empty */
 6149                          2611                 :         498757 :     locally_added_param = -1;   /* there isn't one */
 5890                          2612                 :         498757 :     nestloop_params = NULL;     /* there aren't any */
                               2613                 :                : 
                               2614                 :                :     /*
                               2615                 :                :      * Examine any initPlans to determine the set of external params they
                               2616                 :                :      * reference and the set of output params they supply.  (We assume
                               2617                 :                :      * SS_finalize_plan was run on them already.)
                               2618                 :                :      */
 4034                          2619                 :         498757 :     initExtParam = initSetParam = NULL;
                               2620   [ +  +  +  +  :         508084 :     foreach(l, plan->initPlan)
                                              +  + ]
                               2621                 :                :     {
                               2622                 :           9327 :         SubPlan    *initsubplan = (SubPlan *) lfirst(l);
                               2623                 :           9327 :         Plan       *initplan = planner_subplan_get_plan(root, initsubplan);
                               2624                 :                :         ListCell   *l2;
                               2625                 :                : 
                               2626                 :           9327 :         initExtParam = bms_add_members(initExtParam, initplan->extParam);
                               2627   [ +  -  +  +  :          18694 :         foreach(l2, initsubplan->setParam)
                                              +  + ]
                               2628                 :                :         {
                               2629                 :           9367 :             initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
                               2630                 :                :         }
                               2631                 :                :     }
                               2632                 :                : 
                               2633                 :                :     /* Any setParams are validly referenceable in this node and children */
                               2634         [ +  + ]:         498757 :     if (initSetParam)
                               2635                 :           8286 :         valid_params = bms_union(valid_params, initSetParam);
                               2636                 :                : 
                               2637                 :                :     /*
                               2638                 :                :      * When we call finalize_primnode, context.paramids sets are automatically
                               2639                 :                :      * merged together.  But when recursing to self, we have to do it the hard
                               2640                 :                :      * way.  We want the paramids set to include params in subplans as well as
                               2641                 :                :      * at this level.
                               2642                 :                :      */
                               2643                 :                : 
                               2644                 :                :     /* Find params in targetlist and qual */
 8600                          2645                 :         498757 :     finalize_primnode((Node *) plan->targetlist, &context);
                               2646                 :         498757 :     finalize_primnode((Node *) plan->qual, &context);
                               2647                 :                : 
                               2648                 :                :     /*
                               2649                 :                :      * If it's a parallel-aware scan node, mark it as dependent on the parent
                               2650                 :                :      * Gather/GatherMerge's rescan Param.
                               2651                 :                :      */
 3284                          2652         [ +  + ]:         498757 :     if (plan->parallel_aware)
                               2653                 :                :     {
                               2654         [ -  + ]:           2985 :         if (gather_param < 0)
 3284 tgl@sss.pgh.pa.us        2655         [ #  # ]:UBC           0 :             elog(ERROR, "parallel-aware plan node is not below a Gather");
 3284 tgl@sss.pgh.pa.us        2656                 :CBC        2985 :         context.paramids =
                               2657                 :           2985 :             bms_add_member(context.paramids, gather_param);
                               2658                 :                :     }
                               2659                 :                : 
                               2660                 :                :     /* Check additional node-type-specific fields */
10422 vadim4o@yahoo.com        2661   [ +  +  +  +  :         498757 :     switch (nodeTag(plan))
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  -  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                           +  +  - ]
                               2662                 :                :     {
                               2663                 :          51079 :         case T_Result:
 9782 tgl@sss.pgh.pa.us        2664                 :          51079 :             finalize_primnode(((Result *) plan)->resconstantqual,
                               2665                 :                :                               &context);
10422 vadim4o@yahoo.com        2666                 :          51079 :             break;
                               2667                 :                : 
 6149 tgl@sss.pgh.pa.us        2668                 :          80385 :         case T_SeqScan:
 4051                          2669                 :          80385 :             context.paramids = bms_add_members(context.paramids, scan_params);
                               2670                 :          80385 :             break;
                               2671                 :                : 
 4122 simon@2ndQuadrant.co     2672                 :             84 :         case T_SampleScan:
 4051 tgl@sss.pgh.pa.us        2673                 :             84 :             finalize_primnode((Node *) ((SampleScan *) plan)->tablesample,
                               2674                 :                :                               &context);
 6149                          2675                 :             84 :             context.paramids = bms_add_members(context.paramids, scan_params);
                               2676                 :             84 :             break;
                               2677                 :                : 
 8867                          2678                 :          73936 :         case T_IndexScan:
 7794                          2679                 :          73936 :             finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
                               2680                 :                :                               &context);
 5747                          2681                 :          73936 :             finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
                               2682                 :                :                               &context);
                               2683                 :                : 
                               2684                 :                :             /*
                               2685                 :                :              * we need not look at indexqualorig, since it will have the same
                               2686                 :                :              * param references as indexqual.  Likewise, we can ignore
                               2687                 :                :              * indexorderbyorig.
                               2688                 :                :              */
 6149                          2689                 :          73936 :             context.paramids = bms_add_members(context.paramids, scan_params);
 8867                          2690                 :          73936 :             break;
                               2691                 :                : 
 5434                          2692                 :           6451 :         case T_IndexOnlyScan:
                               2693                 :           6451 :             finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
                               2694                 :                :                               &context);
 1697                          2695                 :           6451 :             finalize_primnode((Node *) ((IndexOnlyScan *) plan)->recheckqual,
                               2696                 :                :                               &context);
 5434                          2697                 :           6451 :             finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
                               2698                 :                :                               &context);
                               2699                 :                : 
                               2700                 :                :             /*
                               2701                 :                :              * we need not look at indextlist, since it cannot contain Params.
                               2702                 :                :              */
                               2703                 :           6451 :             context.paramids = bms_add_members(context.paramids, scan_params);
                               2704                 :           6451 :             break;
                               2705                 :                : 
 7800                          2706                 :           7964 :         case T_BitmapIndexScan:
 7794                          2707                 :           7964 :             finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
                               2708                 :                :                               &context);
                               2709                 :                : 
                               2710                 :                :             /*
                               2711                 :                :              * we need not look at indexqualorig, since it will have the same
                               2712                 :                :              * param references as indexqual.
                               2713                 :                :              */
 7800                          2714                 :           7964 :             break;
                               2715                 :                : 
                               2716                 :           7720 :         case T_BitmapHeapScan:
                               2717                 :           7720 :             finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
                               2718                 :                :                               &context);
 6149                          2719                 :           7720 :             context.paramids = bms_add_members(context.paramids, scan_params);
 7800                          2720                 :           7720 :             break;
                               2721                 :                : 
 8867                          2722                 :            466 :         case T_TidScan:
 7579                          2723                 :            466 :             finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
                               2724                 :                :                               &context);
 6149                          2725                 :            466 :             context.paramids = bms_add_members(context.paramids, scan_params);
10422 vadim4o@yahoo.com        2726                 :            466 :             break;
                               2727                 :                : 
 2007 drowley@postgresql.o     2728                 :             79 :         case T_TidRangeScan:
                               2729                 :             79 :             finalize_primnode((Node *) ((TidRangeScan *) plan)->tidrangequals,
                               2730                 :                :                               &context);
                               2731                 :             79 :             context.paramids = bms_add_members(context.paramids, scan_params);
                               2732                 :             79 :             break;
                               2733                 :                : 
 9457 tgl@sss.pgh.pa.us        2734                 :          22073 :         case T_SubqueryScan:
                               2735                 :                :             {
 4034                          2736                 :          22073 :                 SubqueryScan *sscan = (SubqueryScan *) plan;
                               2737                 :                :                 RelOptInfo *rel;
                               2738                 :                :                 Bitmapset  *subquery_params;
                               2739                 :                : 
                               2740                 :                :                 /* We must run finalize_plan on the subquery */
                               2741                 :          22073 :                 rel = find_base_rel(root, sscan->scan.scanrelid);
 3089 rhaas@postgresql.org     2742                 :          22073 :                 subquery_params = rel->subroot->outer_params;
                               2743         [ +  + ]:          22073 :                 if (gather_param >= 0)
                               2744                 :             85 :                     subquery_params = bms_add_member(bms_copy(subquery_params),
                               2745                 :                :                                                      gather_param);
                               2746                 :          22073 :                 finalize_plan(rel->subroot, sscan->subplan, gather_param,
                               2747                 :                :                               subquery_params, NULL);
                               2748                 :                : 
                               2749                 :                :                 /* Now we can add its extParams to the parent's params */
 4034 tgl@sss.pgh.pa.us        2750                 :          44146 :                 context.paramids = bms_add_members(context.paramids,
                               2751                 :          22073 :                                                    sscan->subplan->extParam);
                               2752                 :                :                 /* We need scan_params too, though */
                               2753                 :          22073 :                 context.paramids = bms_add_members(context.paramids,
                               2754                 :                :                                                    scan_params);
                               2755                 :                :             }
 9457                          2756                 :          22073 :             break;
                               2757                 :                : 
 8867                          2758                 :          15905 :         case T_FunctionScan:
                               2759                 :                :             {
 4662                          2760                 :          15905 :                 FunctionScan *fscan = (FunctionScan *) plan;
                               2761                 :                :                 ListCell   *lc;
                               2762                 :                : 
                               2763                 :                :                 /*
                               2764                 :                :                  * Call finalize_primnode independently on each function
                               2765                 :                :                  * expression, so that we can record which params are
                               2766                 :                :                  * referenced in each, in order to decide which need
                               2767                 :                :                  * re-evaluating during rescan.
                               2768                 :                :                  */
                               2769   [ +  -  +  +  :          31832 :                 foreach(lc, fscan->functions)
                                              +  + ]
                               2770                 :                :                 {
                               2771                 :          15927 :                     RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
                               2772                 :                :                     finalize_primnode_context funccontext;
                               2773                 :                : 
                               2774                 :          15927 :                     funccontext = context;
                               2775                 :          15927 :                     funccontext.paramids = NULL;
                               2776                 :                : 
                               2777                 :          15927 :                     finalize_primnode(rtfunc->funcexpr, &funccontext);
                               2778                 :                : 
                               2779                 :                :                     /* remember results for execution */
                               2780                 :          15927 :                     rtfunc->funcparams = funccontext.paramids;
                               2781                 :                : 
                               2782                 :                :                     /* add the function's params to the overall set */
                               2783                 :          15927 :                     context.paramids = bms_add_members(context.paramids,
                               2784                 :          15927 :                                                        funccontext.paramids);
                               2785                 :                :                 }
                               2786                 :                : 
                               2787                 :          15905 :                 context.paramids = bms_add_members(context.paramids,
                               2788                 :                :                                                    scan_params);
                               2789                 :                :             }
 8867                          2790                 :          15905 :             break;
                               2791                 :                : 
 3459 alvherre@alvh.no-ip.     2792                 :            240 :         case T_TableFuncScan:
                               2793                 :            240 :             finalize_primnode((Node *) ((TableFuncScan *) plan)->tablefunc,
                               2794                 :                :                               &context);
                               2795                 :            240 :             context.paramids = bms_add_members(context.paramids, scan_params);
                               2796                 :            240 :             break;
                               2797                 :                : 
 7330 mail@joeconway.com       2798                 :           4737 :         case T_ValuesScan:
 7129 tgl@sss.pgh.pa.us        2799                 :           4737 :             finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
                               2800                 :                :                               &context);
 6149                          2801                 :           4737 :             context.paramids = bms_add_members(context.paramids, scan_params);
 7330 mail@joeconway.com       2802                 :           4737 :             break;
                               2803                 :                : 
 6536 tgl@sss.pgh.pa.us        2804                 :           2928 :         case T_CteScan:
                               2805                 :                :             {
                               2806                 :                :                 /*
                               2807                 :                :                  * You might think we should add the node's cteParam to
                               2808                 :                :                  * paramids, but we shouldn't because that param is just a
                               2809                 :                :                  * linkage mechanism for multiple CteScan nodes for the same
                               2810                 :                :                  * CTE; it is never used for changed-param signaling.  What we
                               2811                 :                :                  * have to do instead is to find the referenced CTE plan and
                               2812                 :                :                  * incorporate its external paramids, so that the correct
                               2813                 :                :                  * things will happen if the CTE references outer-level
                               2814                 :                :                  * variables.  See test cases for bug #4902.  (We assume
                               2815                 :                :                  * SS_finalize_plan was run on the CTE plan already.)
                               2816                 :                :                  */
 6026 bruce@momjian.us         2817                 :           2928 :                 int         plan_id = ((CteScan *) plan)->ctePlanId;
                               2818                 :                :                 Plan       *cteplan;
                               2819                 :                : 
                               2820                 :                :                 /* so, do this ... */
 6261 tgl@sss.pgh.pa.us        2821   [ +  -  -  + ]:           2928 :                 if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
 6261 tgl@sss.pgh.pa.us        2822         [ #  # ]:UBC           0 :                     elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
                               2823                 :                :                          plan_id);
 6261 tgl@sss.pgh.pa.us        2824                 :CBC        2928 :                 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
                               2825                 :           2928 :                 context.paramids =
                               2826                 :           2928 :                     bms_add_members(context.paramids, cteplan->extParam);
                               2827                 :                : 
                               2828                 :                : #ifdef NOT_USED
                               2829                 :                :                 /* ... but not this */
                               2830                 :                :                 context.paramids =
                               2831                 :                :                     bms_add_member(context.paramids,
                               2832                 :                :                                    ((CteScan *) plan)->cteParam);
                               2833                 :                : #endif
                               2834                 :                : 
 6149                          2835                 :           2928 :                 context.paramids = bms_add_members(context.paramids,
                               2836                 :                :                                                    scan_params);
                               2837                 :                :             }
 6536                          2838                 :           2928 :             break;
                               2839                 :                : 
                               2840                 :            637 :         case T_WorkTableScan:
                               2841                 :            637 :             context.paramids =
                               2842                 :            637 :                 bms_add_member(context.paramids,
                               2843                 :                :                                ((WorkTableScan *) plan)->wtParam);
 6149                          2844                 :            637 :             context.paramids = bms_add_members(context.paramids, scan_params);
 6536                          2845                 :            637 :             break;
                               2846                 :                : 
 3436 kgrittn@postgresql.o     2847                 :            389 :         case T_NamedTuplestoreScan:
                               2848                 :            389 :             context.paramids = bms_add_members(context.paramids, scan_params);
                               2849                 :            389 :             break;
                               2850                 :                : 
 5667 tgl@sss.pgh.pa.us        2851                 :            449 :         case T_ForeignScan:
                               2852                 :                :             {
 3969 rhaas@postgresql.org     2853                 :            449 :                 ForeignScan *fscan = (ForeignScan *) plan;
                               2854                 :                : 
                               2855                 :            449 :                 finalize_primnode((Node *) fscan->fdw_exprs,
                               2856                 :                :                                   &context);
                               2857                 :            449 :                 finalize_primnode((Node *) fscan->fdw_recheck_quals,
                               2858                 :                :                                   &context);
                               2859                 :                : 
                               2860                 :                :                 /* We assume fdw_scan_tlist cannot contain Params */
                               2861                 :            449 :                 context.paramids = bms_add_members(context.paramids,
                               2862                 :                :                                                    scan_params);
                               2863                 :                :             }
 5667 tgl@sss.pgh.pa.us        2864                 :            449 :             break;
                               2865                 :                : 
 4311 rhaas@postgresql.org     2866                 :UBC           0 :         case T_CustomScan:
                               2867                 :                :             {
 4080                          2868                 :              0 :                 CustomScan *cscan = (CustomScan *) plan;
                               2869                 :                :                 ListCell   *lc;
                               2870                 :                : 
                               2871                 :              0 :                 finalize_primnode((Node *) cscan->custom_exprs,
                               2872                 :                :                                   &context);
                               2873                 :                :                 /* We assume custom_scan_tlist cannot contain Params */
                               2874                 :              0 :                 context.paramids =
                               2875                 :              0 :                     bms_add_members(context.paramids, scan_params);
                               2876                 :                : 
                               2877                 :                :                 /* child nodes if any */
 4051 tgl@sss.pgh.pa.us        2878   [ #  #  #  #  :              0 :                 foreach(lc, cscan->custom_plans)
                                              #  # ]
                               2879                 :                :                 {
 4080 rhaas@postgresql.org     2880                 :              0 :                     context.paramids =
                               2881                 :              0 :                         bms_add_members(context.paramids,
                               2882                 :              0 :                                         finalize_plan(root,
                               2883                 :              0 :                                                       (Plan *) lfirst(lc),
                               2884                 :                :                                                       gather_param,
                               2885                 :                :                                                       valid_params,
                               2886                 :                :                                                       scan_params));
                               2887                 :                :                 }
                               2888                 :                :             }
 4311                          2889                 :              0 :             break;
                               2890                 :                : 
 6165 tgl@sss.pgh.pa.us        2891                 :CBC       61657 :         case T_ModifyTable:
                               2892                 :                :             {
 6149                          2893                 :          61657 :                 ModifyTable *mtplan = (ModifyTable *) plan;
                               2894                 :                : 
                               2895                 :                :                 /* Force descendant scan nodes to reference epqParam */
                               2896                 :          61657 :                 locally_added_param = mtplan->epqParam;
                               2897                 :          61657 :                 valid_params = bms_add_member(bms_copy(valid_params),
                               2898                 :                :                                               locally_added_param);
                               2899                 :          61657 :                 scan_params = bms_add_member(bms_copy(scan_params),
                               2900                 :                :                                              locally_added_param);
                               2901                 :          61657 :                 finalize_primnode((Node *) mtplan->returningLists,
                               2902                 :                :                                   &context);
 4129 andres@anarazel.de       2903                 :          61657 :                 finalize_primnode((Node *) mtplan->onConflictSet,
                               2904                 :                :                                   &context);
                               2905                 :          61657 :                 finalize_primnode((Node *) mtplan->onConflictWhere,
                               2906                 :                :                                   &context);
                               2907                 :                :                 /* exclRelTlist contains only Vars, doesn't need examination */
                               2908                 :                :             }
 6165 tgl@sss.pgh.pa.us        2909                 :          61657 :             break;
                               2910                 :                : 
 8867                          2911                 :           8820 :         case T_Append:
                               2912                 :                :             {
 8128 neilc@samurai.com        2913   [ +  -  +  +  :          33536 :                 foreach(l, ((Append *) plan)->appendplans)
                                              +  + ]
                               2914                 :                :                 {
                               2915                 :          24716 :                     context.paramids =
                               2916                 :          24716 :                         bms_add_members(context.paramids,
 7126 tgl@sss.pgh.pa.us        2917                 :          24716 :                                         finalize_plan(root,
                               2918                 :          24716 :                                                       (Plan *) lfirst(l),
                               2919                 :                :                                                       gather_param,
                               2920                 :                :                                                       valid_params,
                               2921                 :                :                                                       scan_params));
                               2922                 :                :                 }
                               2923                 :                :             }
10422 vadim4o@yahoo.com        2924                 :           8820 :             break;
                               2925                 :                : 
 5796 tgl@sss.pgh.pa.us        2926                 :            125 :         case T_MergeAppend:
                               2927                 :                :             {
                               2928   [ +  -  +  +  :            510 :                 foreach(l, ((MergeAppend *) plan)->mergeplans)
                                              +  + ]
                               2929                 :                :                 {
                               2930                 :            385 :                     context.paramids =
                               2931                 :            385 :                         bms_add_members(context.paramids,
                               2932                 :            385 :                                         finalize_plan(root,
                               2933                 :            385 :                                                       (Plan *) lfirst(l),
                               2934                 :                :                                                       gather_param,
                               2935                 :                :                                                       valid_params,
                               2936                 :                :                                                       scan_params));
                               2937                 :                :                 }
                               2938                 :                :             }
                               2939                 :            125 :             break;
                               2940                 :                : 
 7800                          2941                 :            107 :         case T_BitmapAnd:
                               2942                 :                :             {
                               2943   [ +  -  +  +  :            321 :                 foreach(l, ((BitmapAnd *) plan)->bitmapplans)
                                              +  + ]
                               2944                 :                :                 {
                               2945                 :            214 :                     context.paramids =
                               2946                 :            214 :                         bms_add_members(context.paramids,
 7126                          2947                 :            214 :                                         finalize_plan(root,
                               2948                 :            214 :                                                       (Plan *) lfirst(l),
                               2949                 :                :                                                       gather_param,
                               2950                 :                :                                                       valid_params,
                               2951                 :                :                                                       scan_params));
                               2952                 :                :                 }
                               2953                 :                :             }
 7800                          2954                 :            107 :             break;
                               2955                 :                : 
                               2956                 :            137 :         case T_BitmapOr:
                               2957                 :                :             {
                               2958   [ +  -  +  +  :            411 :                 foreach(l, ((BitmapOr *) plan)->bitmapplans)
                                              +  + ]
                               2959                 :                :                 {
                               2960                 :            274 :                     context.paramids =
                               2961                 :            274 :                         bms_add_members(context.paramids,
 7126                          2962                 :            274 :                                         finalize_plan(root,
                               2963                 :            274 :                                                       (Plan *) lfirst(l),
                               2964                 :                :                                                       gather_param,
                               2965                 :                :                                                       valid_params,
                               2966                 :                :                                                       scan_params));
                               2967                 :                :                 }
                               2968                 :                :             }
 7800                          2969                 :            137 :             break;
                               2970                 :                : 
 9480                          2971                 :          57495 :         case T_NestLoop:
                               2972                 :                :             {
 5890                          2973                 :          57495 :                 finalize_primnode((Node *) ((Join *) plan)->joinqual,
                               2974                 :                :                                   &context);
                               2975                 :                :                 /* collect set of params that will be passed to right child */
                               2976   [ +  +  +  +  :          99310 :                 foreach(l, ((NestLoop *) plan)->nestParams)
                                              +  + ]
                               2977                 :                :                 {
                               2978                 :          41815 :                     NestLoopParam *nlp = (NestLoopParam *) lfirst(l);
                               2979                 :                : 
                               2980                 :          41815 :                     nestloop_params = bms_add_member(nestloop_params,
                               2981                 :                :                                                      nlp->paramno);
                               2982                 :                :                 }
                               2983                 :                :             }
 9480                          2984                 :          57495 :             break;
                               2985                 :                : 
10422 vadim4o@yahoo.com        2986                 :           2916 :         case T_MergeJoin:
 9480 tgl@sss.pgh.pa.us        2987                 :           2916 :             finalize_primnode((Node *) ((Join *) plan)->joinqual,
                               2988                 :                :                               &context);
 9782                          2989                 :           2916 :             finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
                               2990                 :                :                               &context);
10422 vadim4o@yahoo.com        2991                 :           2916 :             break;
                               2992                 :                : 
                               2993                 :          17517 :         case T_HashJoin:
 9480 tgl@sss.pgh.pa.us        2994                 :          17517 :             finalize_primnode((Node *) ((Join *) plan)->joinqual,
                               2995                 :                :                               &context);
 9782                          2996                 :          17517 :             finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
                               2997                 :                :                               &context);
10422 vadim4o@yahoo.com        2998                 :          17517 :             break;
                               2999                 :                : 
 1164 tgl@sss.pgh.pa.us        3000                 :          17517 :         case T_Hash:
                               3001                 :          17517 :             finalize_primnode((Node *) ((Hash *) plan)->hashkeys,
                               3002                 :                :                               &context);
                               3003                 :          17517 :             break;
                               3004                 :                : 
 8143                          3005                 :           1751 :         case T_Limit:
                               3006                 :           1751 :             finalize_primnode(((Limit *) plan)->limitOffset,
                               3007                 :                :                               &context);
                               3008                 :           1751 :             finalize_primnode(((Limit *) plan)->limitCount,
                               3009                 :                :                               &context);
                               3010                 :           1751 :             break;
                               3011                 :                : 
 6536                          3012                 :            637 :         case T_RecursiveUnion:
                               3013                 :                :             /* child nodes are allowed to reference wtParam */
 6149                          3014                 :            637 :             locally_added_param = ((RecursiveUnion *) plan)->wtParam;
                               3015                 :            637 :             valid_params = bms_add_member(bms_copy(valid_params),
                               3016                 :                :                                           locally_added_param);
                               3017                 :                :             /* wtParam does *not* get added to scan_params */
                               3018                 :            637 :             break;
                               3019                 :                : 
                               3020                 :           6539 :         case T_LockRows:
                               3021                 :                :             /* Force descendant scan nodes to reference epqParam */
                               3022                 :           6539 :             locally_added_param = ((LockRows *) plan)->epqParam;
                               3023                 :           6539 :             valid_params = bms_add_member(bms_copy(valid_params),
                               3024                 :                :                                           locally_added_param);
                               3025                 :           6539 :             scan_params = bms_add_member(bms_copy(scan_params),
                               3026                 :                :                                          locally_added_param);
                               3027                 :           6539 :             break;
                               3028                 :                : 
 3655                          3029                 :          11914 :         case T_Agg:
                               3030                 :                :             {
                               3031                 :          11914 :                 Agg        *agg = (Agg *) plan;
                               3032                 :                : 
                               3033                 :                :                 /*
                               3034                 :                :                  * AGG_HASHED plans need to know which Params are referenced
                               3035                 :                :                  * in aggregate calls.  Do a separate scan to identify them.
                               3036                 :                :                  */
                               3037         [ +  + ]:          11914 :                 if (agg->aggstrategy == AGG_HASHED)
                               3038                 :                :                 {
                               3039                 :                :                     finalize_primnode_context aggcontext;
                               3040                 :                : 
                               3041                 :           1300 :                     aggcontext.root = root;
                               3042                 :           1300 :                     aggcontext.paramids = NULL;
                               3043                 :           1300 :                     finalize_agg_primnode((Node *) agg->plan.targetlist,
                               3044                 :                :                                           &aggcontext);
                               3045                 :           1300 :                     finalize_agg_primnode((Node *) agg->plan.qual,
                               3046                 :                :                                           &aggcontext);
                               3047                 :           1300 :                     agg->aggParams = aggcontext.paramids;
                               3048                 :                :                 }
                               3049                 :                :             }
                               3050                 :          11914 :             break;
                               3051                 :                : 
 6040                          3052                 :            160 :         case T_WindowAgg:
                               3053                 :            160 :             finalize_primnode(((WindowAgg *) plan)->startOffset,
                               3054                 :                :                               &context);
                               3055                 :            160 :             finalize_primnode(((WindowAgg *) plan)->endOffset,
                               3056                 :                :                               &context);
                               3057                 :            160 :             break;
                               3058                 :                : 
 3284                          3059                 :            856 :         case T_Gather:
                               3060                 :                :             /* child nodes are allowed to reference rescan_param, if any */
                               3061                 :            856 :             locally_added_param = ((Gather *) plan)->rescan_param;
                               3062         [ +  + ]:            856 :             if (locally_added_param >= 0)
                               3063                 :                :             {
                               3064                 :            851 :                 valid_params = bms_add_member(bms_copy(valid_params),
                               3065                 :                :                                               locally_added_param);
                               3066                 :                : 
                               3067                 :                :                 /*
                               3068                 :                :                  * We currently don't support nested Gathers.  The issue so
                               3069                 :                :                  * far as this function is concerned would be how to identify
                               3070                 :                :                  * which child nodes depend on which Gather.
                               3071                 :                :                  */
                               3072         [ -  + ]:            851 :                 Assert(gather_param < 0);
                               3073                 :                :                 /* Pass down rescan_param to child parallel-aware nodes */
                               3074                 :            851 :                 gather_param = locally_added_param;
                               3075                 :                :             }
                               3076                 :                :             /* rescan_param does *not* get added to scan_params */
                               3077                 :            856 :             break;
                               3078                 :                : 
                               3079                 :            323 :         case T_GatherMerge:
                               3080                 :                :             /* child nodes are allowed to reference rescan_param, if any */
                               3081                 :            323 :             locally_added_param = ((GatherMerge *) plan)->rescan_param;
                               3082         [ +  - ]:            323 :             if (locally_added_param >= 0)
                               3083                 :                :             {
                               3084                 :            323 :                 valid_params = bms_add_member(bms_copy(valid_params),
                               3085                 :                :                                               locally_added_param);
                               3086                 :                : 
                               3087                 :                :                 /*
                               3088                 :                :                  * We currently don't support nested Gathers.  The issue so
                               3089                 :                :                  * far as this function is concerned would be how to identify
                               3090                 :                :                  * which child nodes depend on which Gather.
                               3091                 :                :                  */
                               3092         [ -  + ]:            323 :                 Assert(gather_param < 0);
                               3093                 :                :                 /* Pass down rescan_param to child parallel-aware nodes */
                               3094                 :            323 :                 gather_param = locally_added_param;
                               3095                 :                :             }
                               3096                 :                :             /* rescan_param does *not* get added to scan_params */
                               3097                 :            323 :             break;
                               3098                 :                : 
 1870 drowley@postgresql.o     3099                 :           1570 :         case T_Memoize:
                               3100                 :           1570 :             finalize_primnode((Node *) ((Memoize *) plan)->param_exprs,
                               3101                 :                :                               &context);
 1973                          3102                 :           1570 :             break;
                               3103                 :                : 
 3508 andres@anarazel.de       3104                 :          33194 :         case T_ProjectSet:
                               3105                 :                :         case T_Material:
                               3106                 :                :         case T_Sort:
                               3107                 :                :         case T_IncrementalSort:
                               3108                 :                :         case T_Unique:
                               3109                 :                :         case T_SetOp:
                               3110                 :                :         case T_Group:
                               3111                 :                :             /* no node-type-specific fields need fixing */
10422 vadim4o@yahoo.com        3112                 :          33194 :             break;
                               3113                 :                : 
10422 vadim4o@yahoo.com        3114                 :UBC           0 :         default:
 8434 tgl@sss.pgh.pa.us        3115         [ #  # ]:              0 :             elog(ERROR, "unrecognized node type: %d",
                               3116                 :                :                  (int) nodeTag(plan));
                               3117                 :                :     }
                               3118                 :                : 
                               3119                 :                :     /* Process left and right child plans, if any */
 5890 tgl@sss.pgh.pa.us        3120                 :CBC      498757 :     child_params = finalize_plan(root,
                               3121                 :         498757 :                                  plan->lefttree,
                               3122                 :                :                                  gather_param,
                               3123                 :                :                                  valid_params,
                               3124                 :                :                                  scan_params);
                               3125                 :         498757 :     context.paramids = bms_add_members(context.paramids, child_params);
                               3126                 :                : 
                               3127         [ +  + ]:         498757 :     if (nestloop_params)
                               3128                 :                :     {
                               3129                 :                :         /* right child can reference nestloop_params as well as valid_params */
                               3130                 :          35951 :         child_params = finalize_plan(root,
                               3131                 :          35951 :                                      plan->righttree,
                               3132                 :                :                                      gather_param,
                               3133                 :                :                                      bms_union(nestloop_params, valid_params),
                               3134                 :                :                                      scan_params);
                               3135                 :                :         /* ... and they don't count as parameters used at my level */
                               3136                 :          35951 :         child_params = bms_difference(child_params, nestloop_params);
                               3137                 :          35951 :         bms_free(nestloop_params);
                               3138                 :                :     }
                               3139                 :                :     else
                               3140                 :                :     {
                               3141                 :                :         /* easy case */
                               3142                 :         462806 :         child_params = finalize_plan(root,
                               3143                 :         462806 :                                      plan->righttree,
                               3144                 :                :                                      gather_param,
                               3145                 :                :                                      valid_params,
                               3146                 :                :                                      scan_params);
                               3147                 :                :     }
                               3148                 :         498757 :     context.paramids = bms_add_members(context.paramids, child_params);
                               3149                 :                : 
                               3150                 :                :     /*
                               3151                 :                :      * Any locally generated parameter doesn't count towards its generating
                               3152                 :                :      * plan node's external dependencies.  (Note: if we changed valid_params
                               3153                 :                :      * and/or scan_params, we leak those bitmapsets; not worth the notational
                               3154                 :                :      * trouble to clean them up.)
                               3155                 :                :      */
 6149                          3156         [ +  + ]:         498757 :     if (locally_added_param >= 0)
                               3157                 :                :     {
 6536                          3158                 :          70007 :         context.paramids = bms_del_member(context.paramids,
                               3159                 :                :                                           locally_added_param);
                               3160                 :                :     }
                               3161                 :                : 
                               3162                 :                :     /* Now we have all the paramids referenced in this node and children */
                               3163                 :                : 
 8600                          3164         [ -  + ]:         498757 :     if (!bms_is_subset(context.paramids, valid_params))
 8434 tgl@sss.pgh.pa.us        3165         [ #  # ]:UBC           0 :         elog(ERROR, "plan should not reference subplan's variable");
                               3166                 :                : 
                               3167                 :                :     /*
                               3168                 :                :      * The plan node's allParam and extParam fields should include all its
                               3169                 :                :      * referenced paramids, plus contributions from any child initPlans.
                               3170                 :                :      * However, any setParams of the initPlans should not be present in the
                               3171                 :                :      * parent node's extParams, only in its allParams.  (It's possible that
                               3172                 :                :      * some initPlans have extParams that are setParams of other initPlans.)
                               3173                 :                :      */
                               3174                 :                : 
                               3175                 :                :     /* allParam must include initplans' extParams and setParams */
 4034 tgl@sss.pgh.pa.us        3176                 :CBC      498757 :     plan->allParam = bms_union(context.paramids, initExtParam);
                               3177                 :         498757 :     plan->allParam = bms_add_members(plan->allParam, initSetParam);
                               3178                 :                :     /* extParam must include any initplan extParams */
                               3179                 :         498757 :     plan->extParam = bms_union(context.paramids, initExtParam);
                               3180                 :                :     /* but not any initplan setParams */
                               3181                 :         498757 :     plan->extParam = bms_del_members(plan->extParam, initSetParam);
                               3182                 :                : 
 8600                          3183                 :         498757 :     return plan->allParam;
                               3184                 :                : }
                               3185                 :                : 
                               3186                 :                : /*
                               3187                 :                :  * finalize_primnode: add IDs of all PARAM_EXEC params that appear (or will
                               3188                 :                :  * appear) in the given expression tree to the result set.
                               3189                 :                :  */
                               3190                 :                : static bool
 8420 bruce@momjian.us         3191                 :        8431734 : finalize_primnode(Node *node, finalize_primnode_context *context)
                               3192                 :                : {
 8657 tgl@sss.pgh.pa.us        3193         [ +  + ]:        8431734 :     if (node == NULL)
                               3194                 :         950789 :         return false;
                               3195         [ +  + ]:        7480945 :     if (IsA(node, Param))
                               3196                 :                :     {
                               3197         [ +  + ]:         105250 :         if (((Param *) node)->paramkind == PARAM_EXEC)
                               3198                 :                :         {
 7432                          3199                 :         103212 :             int         paramid = ((Param *) node)->paramid;
                               3200                 :                : 
 8600                          3201                 :         103212 :             context->paramids = bms_add_member(context->paramids, paramid);
                               3202                 :                :         }
 8657                          3203                 :         105250 :         return false;           /* no more to do here */
                               3204                 :                :     }
 1141                          3205         [ +  + ]:        7375695 :     else if (IsA(node, Aggref))
                               3206                 :                :     {
                               3207                 :                :         /*
                               3208                 :                :          * Check to see if the aggregate will be replaced by a Param
                               3209                 :                :          * referencing a subquery output during setrefs.c.  If so, we must
                               3210                 :                :          * account for that Param here.  (For various reasons, it's not
                               3211                 :                :          * convenient to perform that substitution earlier than setrefs.c, nor
                               3212                 :                :          * to perform this processing after setrefs.c.  Thus we need a wart
                               3213                 :                :          * here.)
                               3214                 :                :          */
                               3215                 :          15719 :         Aggref     *aggref = (Aggref *) node;
                               3216                 :                :         Param      *aggparam;
                               3217                 :                : 
                               3218                 :          15719 :         aggparam = find_minmax_agg_replacement_param(context->root, aggref);
                               3219         [ +  + ]:          15719 :         if (aggparam != NULL)
                               3220                 :            460 :             context->paramids = bms_add_member(context->paramids,
                               3221                 :                :                                                aggparam->paramid);
                               3222                 :                :         /* Fall through to examine the agg's arguments */
                               3223                 :                :     }
                               3224         [ +  + ]:        7359976 :     else if (IsA(node, SubPlan))
                               3225                 :                :     {
 8424 bruce@momjian.us         3226                 :          26950 :         SubPlan    *subplan = (SubPlan *) node;
 7126 tgl@sss.pgh.pa.us        3227                 :          26950 :         Plan       *plan = planner_subplan_get_plan(context->root, subplan);
                               3228                 :                :         ListCell   *lc;
                               3229                 :                :         Bitmapset  *subparamids;
                               3230                 :                : 
                               3231                 :                :         /* Recurse into the testexpr, but not into the Plan */
 6622                          3232                 :          26950 :         finalize_primnode(subplan->testexpr, context);
                               3233                 :                : 
                               3234                 :                :         /*
                               3235                 :                :          * Remove any param IDs of output parameters of the subplan that were
                               3236                 :                :          * referenced in the testexpr.  These are not interesting for
                               3237                 :                :          * parameter change signaling since we always re-evaluate the subplan.
                               3238                 :                :          * Note that this wouldn't work too well if there might be uses of the
                               3239                 :                :          * same param IDs elsewhere in the plan, but that can't happen because
                               3240                 :                :          * generate_new_exec_param never tries to merge params.
                               3241                 :                :          */
                               3242   [ +  +  +  +  :          29573 :         foreach(lc, subplan->paramIds)
                                              +  + ]
                               3243                 :                :         {
                               3244                 :           2623 :             context->paramids = bms_del_member(context->paramids,
                               3245                 :                :                                                lfirst_int(lc));
                               3246                 :                :         }
                               3247                 :                : 
                               3248                 :                :         /* Also examine args list */
                               3249                 :          26950 :         finalize_primnode((Node *) subplan->args, context);
                               3250                 :                : 
                               3251                 :                :         /*
                               3252                 :                :          * Add params needed by the subplan to paramids, but excluding those
                               3253                 :                :          * we will pass down to it.  (We assume SS_finalize_plan was run on
                               3254                 :                :          * the subplan already.)
                               3255                 :                :          */
                               3256                 :          26950 :         subparamids = bms_copy(plan->extParam);
                               3257   [ +  +  +  +  :          66574 :         foreach(lc, subplan->parParam)
                                              +  + ]
                               3258                 :                :         {
                               3259                 :          39624 :             subparamids = bms_del_member(subparamids, lfirst_int(lc));
                               3260                 :                :         }
                               3261                 :          26950 :         context->paramids = bms_join(context->paramids, subparamids);
                               3262                 :                : 
                               3263                 :          26950 :         return false;           /* no more to do here */
                               3264                 :                :     }
  637 peter@eisentraut.org     3265                 :        7348745 :     return expression_tree_walker(node, finalize_primnode, context);
                               3266                 :                : }
                               3267                 :                : 
                               3268                 :                : /*
                               3269                 :                :  * finalize_agg_primnode: find all Aggref nodes in the given expression tree,
                               3270                 :                :  * and add IDs of all PARAM_EXEC params appearing within their aggregated
                               3271                 :                :  * arguments to the result set.
                               3272                 :                :  */
                               3273                 :                : static bool
 3655 tgl@sss.pgh.pa.us        3274                 :          10993 : finalize_agg_primnode(Node *node, finalize_primnode_context *context)
                               3275                 :                : {
                               3276         [ +  + ]:          10993 :     if (node == NULL)
                               3277                 :           1358 :         return false;
                               3278         [ +  + ]:           9635 :     if (IsA(node, Aggref))
                               3279                 :                :     {
                               3280                 :            981 :         Aggref     *agg = (Aggref *) node;
                               3281                 :                : 
                               3282                 :                :         /* we should not consider the direct arguments, if any */
                               3283                 :            981 :         finalize_primnode((Node *) agg->args, context);
                               3284                 :            981 :         finalize_primnode((Node *) agg->aggfilter, context);
                               3285                 :            981 :         return false;           /* there can't be any Aggrefs below here */
                               3286                 :                :     }
  637 peter@eisentraut.org     3287                 :           8654 :     return expression_tree_walker(node, finalize_agg_primnode, context);
                               3288                 :                : }
                               3289                 :                : 
                               3290                 :                : /*
                               3291                 :                :  * SS_make_initplan_output_param - make a Param for an initPlan's output
                               3292                 :                :  *
                               3293                 :                :  * The plan is expected to return a scalar value of the given type/collation.
                               3294                 :                :  *
                               3295                 :                :  * Note that in some cases the initplan may not ever appear in the finished
                               3296                 :                :  * plan tree.  If that happens, we'll have wasted a PARAM_EXEC slot, which
                               3297                 :                :  * is no big deal.
                               3298                 :                :  */
                               3299                 :                : Param *
 3825 tgl@sss.pgh.pa.us        3300                 :            365 : SS_make_initplan_output_param(PlannerInfo *root,
                               3301                 :                :                               Oid resulttype, int32 resulttypmod,
                               3302                 :                :                               Oid resultcollation)
                               3303                 :                : {
 2785                          3304                 :            365 :     return generate_new_exec_param(root, resulttype,
                               3305                 :                :                                    resulttypmod, resultcollation);
                               3306                 :                : }
                               3307                 :                : 
                               3308                 :                : /*
                               3309                 :                :  * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan
                               3310                 :                :  *
                               3311                 :                :  * We build an EXPR_SUBLINK SubPlan node and put it into the initplan
                               3312                 :                :  * list for the outer query level.  A Param that represents the initplan's
                               3313                 :                :  * output has already been assigned using SS_make_initplan_output_param.
                               3314                 :                :  */
                               3315                 :                : void
 4034                          3316                 :            330 : SS_make_initplan_from_plan(PlannerInfo *root,
                               3317                 :                :                            PlannerInfo *subroot, Plan *plan,
                               3318                 :                :                            Param *prm)
                               3319                 :                : {
                               3320                 :                :     SubPlan    *node;
                               3321                 :                : 
                               3322                 :                :     /*
                               3323                 :                :      * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
                               3324                 :                :      * the global lists.  Ideally we'd save a real path, but right now our
                               3325                 :                :      * sole caller doesn't build a path that exactly matches the plan.  Since
                               3326                 :                :      * we're not currently going to need the path for an initplan, it's not
                               3327                 :                :      * worth requiring construction of such a path.
                               3328                 :                :      */
 5472                          3329                 :            330 :     root->glob->subplans = lappend(root->glob->subplans, plan);
  884                          3330                 :            330 :     root->glob->subpaths = lappend(root->glob->subpaths, NULL);
 4034                          3331                 :            330 :     root->glob->subroots = lappend(root->glob->subroots, subroot);
                               3332                 :                : 
                               3333                 :                :     /*
                               3334                 :                :      * Create a SubPlan node and add it to the outer list of InitPlans. Note
                               3335                 :                :      * it has to appear after any other InitPlans it might depend on (see
                               3336                 :                :      * comments in ExecReScan).
                               3337                 :                :      */
 7808                          3338                 :            330 :     node = makeNode(SubPlan);
                               3339                 :            330 :     node->subLinkType = EXPR_SUBLINK;
 3825                          3340                 :            330 :     node->plan_id = list_length(root->glob->subplans);
  324 rhaas@postgresql.org     3341                 :            330 :     node->plan_name = subroot->plan_name;
                               3342                 :            330 :     node->isInitPlan = true;
 5640 tgl@sss.pgh.pa.us        3343                 :            330 :     get_first_col_type(plan, &node->firstColType, &node->firstColTypmod,
                               3344                 :                :                        &node->firstColCollation);
 1141                          3345                 :            330 :     node->parallel_safe = plan->parallel_safe;
 3825                          3346                 :            330 :     node->setParam = list_make1_int(prm->paramid);
                               3347                 :                : 
 7129                          3348                 :            330 :     root->init_plans = lappend(root->init_plans, node);
                               3349                 :                : 
                               3350                 :                :     /*
                               3351                 :                :      * The node can't have any inputs (since it's an initplan), so the
                               3352                 :                :      * parParam and args lists remain empty.
                               3353                 :                :      */
                               3354                 :                : 
                               3355                 :                :     /* Set costs of SubPlan using info from the plan tree */
 4034                          3356                 :            330 :     cost_subplan(subroot, node, plan);
 7808                          3357                 :            330 : }
                               3358                 :                : 
                               3359                 :                : /*
                               3360                 :                :  * Get a string equivalent of a given subLinkType.
                               3361                 :                :  */
                               3362                 :                : static const char *
  324 rhaas@postgresql.org     3363                 :          28750 : sublinktype_to_string(SubLinkType subLinkType)
                               3364                 :                : {
                               3365   [ +  +  +  +  :          28750 :     switch (subLinkType)
                                        +  +  +  -  
                                                 - ]
                               3366                 :                :     {
                               3367                 :           1776 :         case EXISTS_SUBLINK:
                               3368                 :           1776 :             return "exists";
                               3369                 :             15 :         case ALL_SUBLINK:
                               3370                 :             15 :             return "all";
                               3371                 :            508 :         case ANY_SUBLINK:
                               3372                 :            508 :             return "any";
                               3373                 :             25 :         case ROWCOMPARE_SUBLINK:
                               3374                 :             25 :             return "rowcompare";
                               3375                 :          20076 :         case EXPR_SUBLINK:
                               3376                 :          20076 :             return "expr";
                               3377                 :            108 :         case MULTIEXPR_SUBLINK:
                               3378                 :            108 :             return "multiexpr";
                               3379                 :           6242 :         case ARRAY_SUBLINK:
                               3380                 :           6242 :             return "array";
  324 rhaas@postgresql.org     3381                 :UBC           0 :         case CTE_SUBLINK:
                               3382                 :              0 :             return "cte";
                               3383                 :                :     }
                               3384                 :              0 :     Assert(false);
                               3385                 :                :     return "???";
                               3386                 :                : }
        

Generated by: LCOV version 2.0-1