LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/path - costsize.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 603a3335f2b60b2c798da5c627b3bb288b92a7bd vs e395fbd32a07557de4ac98088928c1749d4845d8 Lines: 98.0 % 1936 1897 39 8 1889 5
Current Date: 2026-07-25 17:13:00 -0400 Functions: 100.0 % 74 74 2 72
Baseline: lcov-20260726-baseline Branches: 82.8 % 1083 897 186 10 887
Baseline Date: 2026-07-25 19:16:42 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 8 8 8
(30,360] days: 100.0 % 123 123 123
(360..) days: 97.8 % 1805 1766 39 1766
Function coverage date bins:
(360..) days: 100.0 % 74 74 2 72
Branch coverage date bins:
(7,30] days: 100.0 % 10 10 10
(30,360] days: 80.6 % 72 58 14 58
(360..) days: 82.8 % 1001 829 172 829

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * costsize.c
                                  4                 :                :  *    Routines to compute (and set) relation sizes and path costs
                                  5                 :                :  *
                                  6                 :                :  * Path costs are measured in arbitrary units established by these basic
                                  7                 :                :  * parameters:
                                  8                 :                :  *
                                  9                 :                :  *  seq_page_cost       Cost of a sequential page fetch
                                 10                 :                :  *  random_page_cost    Cost of a non-sequential page fetch
                                 11                 :                :  *  cpu_tuple_cost      Cost of typical CPU time to process a tuple
                                 12                 :                :  *  cpu_index_tuple_cost  Cost of typical CPU time to process an index tuple
                                 13                 :                :  *  cpu_operator_cost   Cost of CPU time to execute an operator or function
                                 14                 :                :  *  parallel_tuple_cost Cost of CPU time to pass a tuple from worker to leader backend
                                 15                 :                :  *  parallel_setup_cost Cost of setting up shared memory for parallelism
                                 16                 :                :  *
                                 17                 :                :  * We expect that the kernel will typically do some amount of read-ahead
                                 18                 :                :  * optimization; this in conjunction with seek costs means that seq_page_cost
                                 19                 :                :  * is normally considerably less than random_page_cost.  (However, if the
                                 20                 :                :  * database is fully cached in RAM, it is reasonable to set them equal.)
                                 21                 :                :  *
                                 22                 :                :  * We also use a rough estimate "effective_cache_size" of the number of
                                 23                 :                :  * disk pages in Postgres + OS-level disk cache.  (We can't simply use
                                 24                 :                :  * NBuffers for this purpose because that would ignore the effects of
                                 25                 :                :  * the kernel's disk cache.)
                                 26                 :                :  *
                                 27                 :                :  * Obviously, taking constants for these values is an oversimplification,
                                 28                 :                :  * but it's tough enough to get any useful estimates even at this level of
                                 29                 :                :  * detail.  Note that all of these parameters are user-settable, in case
                                 30                 :                :  * the default values are drastically off for a particular platform.
                                 31                 :                :  *
                                 32                 :                :  * seq_page_cost and random_page_cost can also be overridden for an individual
                                 33                 :                :  * tablespace, in case some data is on a fast disk and other data is on a slow
                                 34                 :                :  * disk.  Per-tablespace overrides never apply to temporary work files such as
                                 35                 :                :  * an external sort or a materialize node that overflows work_mem.
                                 36                 :                :  *
                                 37                 :                :  * We compute two separate costs for each path:
                                 38                 :                :  *      total_cost: total estimated cost to fetch all tuples
                                 39                 :                :  *      startup_cost: cost that is expended before first tuple is fetched
                                 40                 :                :  * In some scenarios, such as when there is a LIMIT or we are implementing
                                 41                 :                :  * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
                                 42                 :                :  * path's result.  A caller can estimate the cost of fetching a partial
                                 43                 :                :  * result by interpolating between startup_cost and total_cost.  In detail:
                                 44                 :                :  *      actual_cost = startup_cost +
                                 45                 :                :  *          (total_cost - startup_cost) * tuples_to_fetch / path->rows;
                                 46                 :                :  * Note that a base relation's rows count (and, by extension, plan_rows for
                                 47                 :                :  * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
                                 48                 :                :  * that this equation works properly.  (Note: while path->rows is never zero
                                 49                 :                :  * for ordinary relations, it is zero for paths for provably-empty relations,
                                 50                 :                :  * so beware of division-by-zero.)  The LIMIT is applied as a top-level
                                 51                 :                :  * plan node.
                                 52                 :                :  *
                                 53                 :                :  * Each path stores the total number of disabled nodes that exist at or
                                 54                 :                :  * below that point in the plan tree. This is regarded as a component of
                                 55                 :                :  * the cost, and paths with fewer disabled nodes should be regarded as
                                 56                 :                :  * cheaper than those with more. Disabled nodes occur when the user sets
                                 57                 :                :  * a GUC like enable_seqscan=false. We can't necessarily respect such a
                                 58                 :                :  * setting in every part of the plan tree, but we want to respect in as many
                                 59                 :                :  * parts of the plan tree as possible. Simpler schemes like storing a Boolean
                                 60                 :                :  * here rather than a count fail to do that. We used to disable nodes by
                                 61                 :                :  * adding a large constant to the startup cost, but that distorted planning
                                 62                 :                :  * in other ways.
                                 63                 :                :  *
                                 64                 :                :  * For largely historical reasons, most of the routines in this module use
                                 65                 :                :  * the passed result Path only to store their results (rows, startup_cost and
                                 66                 :                :  * total_cost) into.  All the input data they need is passed as separate
                                 67                 :                :  * parameters, even though much of it could be extracted from the Path.
                                 68                 :                :  * An exception is made for the cost_XXXjoin() routines, which expect all
                                 69                 :                :  * the other fields of the passed XXXPath to be filled in, and similarly
                                 70                 :                :  * cost_index() assumes the passed IndexPath is valid except for its output
                                 71                 :                :  * values.
                                 72                 :                :  *
                                 73                 :                :  *
                                 74                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                 75                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 76                 :                :  *
                                 77                 :                :  * IDENTIFICATION
                                 78                 :                :  *    src/backend/optimizer/path/costsize.c
                                 79                 :                :  *
                                 80                 :                :  *-------------------------------------------------------------------------
                                 81                 :                :  */
                                 82                 :                : 
                                 83                 :                : #include "postgres.h"
                                 84                 :                : 
                                 85                 :                : #include <limits.h>
                                 86                 :                : #include <math.h>
                                 87                 :                : 
                                 88                 :                : #include "access/amapi.h"
                                 89                 :                : #include "access/htup_details.h"
                                 90                 :                : #include "access/tsmapi.h"
                                 91                 :                : #include "executor/executor.h"
                                 92                 :                : #include "executor/nodeAgg.h"
                                 93                 :                : #include "executor/nodeHash.h"
                                 94                 :                : #include "executor/nodeMemoize.h"
                                 95                 :                : #include "miscadmin.h"
                                 96                 :                : #include "nodes/makefuncs.h"
                                 97                 :                : #include "nodes/nodeFuncs.h"
                                 98                 :                : #include "nodes/tidbitmap.h"
                                 99                 :                : #include "optimizer/clauses.h"
                                100                 :                : #include "optimizer/cost.h"
                                101                 :                : #include "optimizer/optimizer.h"
                                102                 :                : #include "optimizer/pathnode.h"
                                103                 :                : #include "optimizer/paths.h"
                                104                 :                : #include "optimizer/placeholder.h"
                                105                 :                : #include "optimizer/plancat.h"
                                106                 :                : #include "optimizer/restrictinfo.h"
                                107                 :                : #include "parser/parsetree.h"
                                108                 :                : #include "utils/lsyscache.h"
                                109                 :                : #include "utils/selfuncs.h"
                                110                 :                : #include "utils/spccache.h"
                                111                 :                : #include "utils/tuplesort.h"
                                112                 :                : 
                                113                 :                : 
                                114                 :                : #define LOG2(x)  (log(x) / 0.693147180559945)
                                115                 :                : 
                                116                 :                : /*
                                117                 :                :  * Append and MergeAppend nodes are less expensive than some other operations
                                118                 :                :  * which use cpu_tuple_cost; instead of adding a separate GUC, estimate the
                                119                 :                :  * per-tuple cost as cpu_tuple_cost multiplied by this value.
                                120                 :                :  */
                                121                 :                : #define APPEND_CPU_COST_MULTIPLIER 0.5
                                122                 :                : 
                                123                 :                : /*
                                124                 :                :  * Maximum value for row estimates.  We cap row estimates to this to help
                                125                 :                :  * ensure that costs based on these estimates remain within the range of what
                                126                 :                :  * double can represent.  add_path() wouldn't act sanely given infinite or NaN
                                127                 :                :  * cost values.
                                128                 :                :  */
                                129                 :                : #define MAXIMUM_ROWCOUNT 1e100
                                130                 :                : 
                                131                 :                : double      seq_page_cost = DEFAULT_SEQ_PAGE_COST;
                                132                 :                : double      random_page_cost = DEFAULT_RANDOM_PAGE_COST;
                                133                 :                : double      cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
                                134                 :                : double      cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
                                135                 :                : double      cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
                                136                 :                : double      parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST;
                                137                 :                : double      parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST;
                                138                 :                : double      recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR;
                                139                 :                : 
                                140                 :                : int         effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
                                141                 :                : 
                                142                 :                : Cost        disable_cost = 1.0e10;
                                143                 :                : 
                                144                 :                : int         max_parallel_workers_per_gather = 2;
                                145                 :                : 
                                146                 :                : bool        enable_seqscan = true;
                                147                 :                : bool        enable_indexscan = true;
                                148                 :                : bool        enable_indexonlyscan = true;
                                149                 :                : bool        enable_bitmapscan = true;
                                150                 :                : bool        enable_tidscan = true;
                                151                 :                : bool        enable_sort = true;
                                152                 :                : bool        enable_incremental_sort = true;
                                153                 :                : bool        enable_hashagg = true;
                                154                 :                : bool        enable_groupagg = true;
                                155                 :                : bool        enable_nestloop = true;
                                156                 :                : bool        enable_material = true;
                                157                 :                : bool        enable_memoize = true;
                                158                 :                : bool        enable_mergejoin = true;
                                159                 :                : bool        enable_hashjoin = true;
                                160                 :                : bool        enable_gathermerge = true;
                                161                 :                : bool        enable_partitionwise_join = false;
                                162                 :                : bool        enable_partitionwise_aggregate = false;
                                163                 :                : bool        enable_parallel_append = true;
                                164                 :                : bool        enable_parallel_hash = true;
                                165                 :                : bool        enable_partition_pruning = true;
                                166                 :                : bool        enable_presorted_aggregate = true;
                                167                 :                : bool        enable_async_append = true;
                                168                 :                : 
                                169                 :                : typedef struct
                                170                 :                : {
                                171                 :                :     PlannerInfo *root;
                                172                 :                :     QualCost    total;
                                173                 :                : } cost_qual_eval_context;
                                174                 :                : 
                                175                 :                : static List *extract_nonindex_conditions(List *qual_clauses, List *indexclauses);
                                176                 :                : static MergeScanSelCache *cached_scansel(PlannerInfo *root,
                                177                 :                :                                          RestrictInfo *rinfo,
                                178                 :                :                                          PathKey *pathkey);
                                179                 :                : static void cost_rescan(PlannerInfo *root, Path *path,
                                180                 :                :                         Cost *rescan_startup_cost, Cost *rescan_total_cost);
                                181                 :                : static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
                                182                 :                : static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
                                183                 :                :                                       ParamPathInfo *param_info,
                                184                 :                :                                       QualCost *qpqual_cost);
                                185                 :                : static bool has_indexed_join_quals(NestPath *path);
                                186                 :                : static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
                                187                 :                :                                  List *quals);
                                188                 :                : static double calc_joinrel_size_estimate(PlannerInfo *root,
                                189                 :                :                                          RelOptInfo *joinrel,
                                190                 :                :                                          RelOptInfo *outer_rel,
                                191                 :                :                                          RelOptInfo *inner_rel,
                                192                 :                :                                          double outer_rows,
                                193                 :                :                                          double inner_rows,
                                194                 :                :                                          SpecialJoinInfo *sjinfo,
                                195                 :                :                                          List *restrictlist);
                                196                 :                : static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root,
                                197                 :                :                                                     Relids outer_relids,
                                198                 :                :                                                     Relids inner_relids,
                                199                 :                :                                                     SpecialJoinInfo *sjinfo,
                                200                 :                :                                                     List **restrictlist);
                                201                 :                : static Cost append_nonpartial_cost(List *subpaths, int numpaths,
                                202                 :                :                                    int parallel_workers);
                                203                 :                : static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
                                204                 :                : static int32 get_expr_width(PlannerInfo *root, const Node *expr);
                                205                 :                : static double relation_byte_size(double tuples, int width);
                                206                 :                : static double page_size(double tuples, int width);
                                207                 :                : static double get_parallel_divisor(Path *path);
                                208                 :                : 
                                209                 :                : 
                                210                 :                : /*
                                211                 :                :  * clamp_row_est
                                212                 :                :  *      Force a row-count estimate to a sane value.
                                213                 :                :  */
                                214                 :                : double
 8238 tgl@sss.pgh.pa.us         215                 :CBC     8007295 : clamp_row_est(double nrows)
                                216                 :                : {
                                217                 :                :     /*
                                218                 :                :      * Avoid infinite and NaN row estimates.  Costs derived from such values
                                219                 :                :      * are going to be useless.  Also force the estimate to be at least one
                                220                 :                :      * row, to make explain output look better and to avoid possible
                                221                 :                :      * divide-by-zero when interpolating costs.  Make it an integer, too.
                                222                 :                :      */
 2106 drowley@postgresql.o      223   [ +  -  -  + ]:        8007295 :     if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
 2106 drowley@postgresql.o      224                 :UBC           0 :         nrows = MAXIMUM_ROWCOUNT;
 2106 drowley@postgresql.o      225         [ +  + ]:CBC     8007295 :     else if (nrows <= 1.0)
 8238 tgl@sss.pgh.pa.us         226                 :        2559610 :         nrows = 1.0;
                                227                 :                :     else
 7766                           228                 :        5447685 :         nrows = rint(nrows);
                                229                 :                : 
 8238                           230                 :        8007295 :     return nrows;
                                231                 :                : }
                                232                 :                : 
                                233                 :                : /*
                                234                 :                :  * clamp_width_est
                                235                 :                :  *      Force a tuple-width estimate to a sane value.
                                236                 :                :  *
                                237                 :                :  * The planner represents datatype width and tuple width estimates as int32.
                                238                 :                :  * When summing column width estimates to create a tuple width estimate,
                                239                 :                :  * it's possible to reach integer overflow in edge cases.  To ensure sane
                                240                 :                :  * behavior, we form such sums in int64 arithmetic and then apply this routine
                                241                 :                :  * to clamp to int32 range.
                                242                 :                :  */
                                243                 :                : int32
  950                           244                 :        1532804 : clamp_width_est(int64 tuple_width)
                                245                 :                : {
                                246                 :                :     /*
                                247                 :                :      * Anything more than MaxAllocSize is clearly bogus, since we could not
                                248                 :                :      * create a tuple that large.
                                249                 :                :      */
                                250         [ -  + ]:        1532804 :     if (tuple_width > MaxAllocSize)
  950 tgl@sss.pgh.pa.us         251                 :UBC           0 :         return (int32) MaxAllocSize;
                                252                 :                : 
                                253                 :                :     /*
                                254                 :                :      * Unlike clamp_row_est, we just Assert that the value isn't negative,
                                255                 :                :      * rather than masking such errors.
                                256                 :                :      */
  950 tgl@sss.pgh.pa.us         257         [ -  + ]:CBC     1532804 :     Assert(tuple_width >= 0);
                                258                 :                : 
                                259                 :        1532804 :     return (int32) tuple_width;
                                260                 :                : }
                                261                 :                : 
                                262                 :                : 
                                263                 :                : /*
                                264                 :                :  * cost_seqscan
                                265                 :                :  *    Determines and returns the cost of scanning a relation sequentially.
                                266                 :                :  *
                                267                 :                :  * 'baserel' is the relation to be scanned
                                268                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                                269                 :                :  */
                                270                 :                : void
 7721                           271                 :         341292 : cost_seqscan(Path *path, PlannerInfo *root,
                                272                 :                :              RelOptInfo *baserel, ParamPathInfo *param_info)
                                273                 :                : {
 9658                           274                 :         341292 :     Cost        startup_cost = 0;
                                275                 :                :     Cost        cpu_run_cost;
                                276                 :                :     Cost        disk_run_cost;
                                277                 :                :     double      spc_seq_page_cost;
                                278                 :                :     QualCost    qpqual_cost;
                                279                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org      280                 :         341292 :     uint64      enable_mask = PGS_SEQSCAN;
                                281                 :                : 
                                282                 :                :     /* Should only be applied to base relations */
 8569 tgl@sss.pgh.pa.us         283         [ -  + ]:         341292 :     Assert(baserel->relid > 0);
 8841                           284         [ -  + ]:         341292 :     Assert(baserel->rtekind == RTE_RELATION);
                                285                 :                : 
                                286                 :                :     /* Mark the path with the correct row estimate */
 5211                           287         [ +  + ]:         341292 :     if (param_info)
                                288                 :           1206 :         path->rows = param_info->ppi_rows;
                                289                 :                :     else
                                290                 :         340086 :         path->rows = baserel->rows;
                                291                 :                : 
                                292                 :                :     /* fetch estimated page cost for tablespace containing table */
 6046 rhaas@postgresql.org      293                 :         341292 :     get_tablespace_page_costs(baserel->reltablespace,
                                294                 :                :                               NULL,
                                295                 :                :                               &spc_seq_page_cost);
                                296                 :                : 
                                297                 :                :     /*
                                298                 :                :      * disk costs
                                299                 :                :      */
 3840                           300                 :         341292 :     disk_run_cost = spc_seq_page_cost * baserel->pages;
                                301                 :                : 
                                302                 :                :     /* CPU costs */
 5211 tgl@sss.pgh.pa.us         303                 :         341292 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                                304                 :                : 
                                305                 :         341292 :     startup_cost += qpqual_cost.startup;
                                306                 :         341292 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
 3840 rhaas@postgresql.org      307                 :         341292 :     cpu_run_cost = cpu_per_tuple * baserel->tuples;
                                308                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811 tgl@sss.pgh.pa.us         309                 :         341292 :     startup_cost += path->pathtarget->cost.startup;
                                310                 :         341292 :     cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
                                311                 :                : 
                                312                 :                :     /* Adjust costing for parallelism, if used. */
 3699 rhaas@postgresql.org      313         [ +  + ]:         341292 :     if (path->parallel_workers > 0)
                                314                 :                :     {
 3481                           315                 :          24390 :         double      parallel_divisor = get_parallel_divisor(path);
                                316                 :                : 
                                317                 :                :         /* The CPU cost is divided among all the workers. */
 3840                           318                 :          24390 :         cpu_run_cost /= parallel_divisor;
                                319                 :                : 
                                320                 :                :         /*
                                321                 :                :          * It may be possible to amortize some of the I/O cost, but probably
                                322                 :                :          * not very much, because most operating systems already do aggressive
                                323                 :                :          * prefetching.  For now, we assume that the disk run cost can't be
                                324                 :                :          * amortized at all.
                                325                 :                :          */
                                326                 :                : 
                                327                 :                :         /*
                                328                 :                :          * In the case of a parallel plan, the row count needs to represent
                                329                 :                :          * the number of tuples processed per worker.
                                330                 :                :          */
 3481                           331                 :          24390 :         path->rows = clamp_row_est(path->rows / parallel_divisor);
                                332                 :                :     }
                                333                 :                :     else
  179                           334                 :         316902 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                                335                 :                : 
                                336                 :         341292 :     path->disabled_nodes =
                                337                 :         341292 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 4090 simon@2ndQuadrant.co      338                 :         341292 :     path->startup_cost = startup_cost;
 3840 rhaas@postgresql.org      339                 :         341292 :     path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
 4090 simon@2ndQuadrant.co      340                 :         341292 : }
                                341                 :                : 
                                342                 :                : /*
                                343                 :                :  * cost_samplescan
                                344                 :                :  *    Determines and returns the cost of scanning a relation using sampling.
                                345                 :                :  *
                                346                 :                :  * 'baserel' is the relation to be scanned
                                347                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                                348                 :                :  */
                                349                 :                : void
 4019 tgl@sss.pgh.pa.us         350                 :            245 : cost_samplescan(Path *path, PlannerInfo *root,
                                351                 :                :                 RelOptInfo *baserel, ParamPathInfo *param_info)
                                352                 :                : {
 4090 simon@2ndQuadrant.co      353                 :            245 :     Cost        startup_cost = 0;
                                354                 :            245 :     Cost        run_cost = 0;
                                355                 :                :     RangeTblEntry *rte;
                                356                 :                :     TableSampleClause *tsc;
                                357                 :                :     TsmRoutine *tsm;
                                358                 :                :     double      spc_seq_page_cost,
                                359                 :                :                 spc_random_page_cost,
                                360                 :                :                 spc_page_cost;
                                361                 :                :     QualCost    qpqual_cost;
                                362                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org      363                 :            245 :     uint64      enable_mask = 0;
                                364                 :                : 
                                365                 :                :     /* Should only be applied to base relations with tablesample clauses */
 4090 simon@2ndQuadrant.co      366         [ -  + ]:            245 :     Assert(baserel->relid > 0);
 4019 tgl@sss.pgh.pa.us         367         [ +  - ]:            245 :     rte = planner_rt_fetch(baserel->relid, root);
                                368         [ -  + ]:            245 :     Assert(rte->rtekind == RTE_RELATION);
                                369                 :            245 :     tsc = rte->tablesample;
                                370         [ -  + ]:            245 :     Assert(tsc != NULL);
                                371                 :            245 :     tsm = GetTsmRoutine(tsc->tsmhandler);
                                372                 :                : 
                                373                 :                :     /* Mark the path with the correct row estimate */
                                374         [ +  + ]:            245 :     if (param_info)
                                375                 :             60 :         path->rows = param_info->ppi_rows;
                                376                 :                :     else
 4090 simon@2ndQuadrant.co      377                 :            185 :         path->rows = baserel->rows;
                                378                 :                : 
                                379                 :                :     /* fetch estimated page cost for tablespace containing table */
                                380                 :            245 :     get_tablespace_page_costs(baserel->reltablespace,
                                381                 :                :                               &spc_random_page_cost,
                                382                 :                :                               &spc_seq_page_cost);
                                383                 :                : 
                                384                 :                :     /* if NextSampleBlock is used, assume random access, else sequential */
 4019 tgl@sss.pgh.pa.us         385                 :            490 :     spc_page_cost = (tsm->NextSampleBlock != NULL) ?
                                386         [ +  + ]:            245 :         spc_random_page_cost : spc_seq_page_cost;
                                387                 :                : 
                                388                 :                :     /*
                                389                 :                :      * disk costs (recall that baserel->pages has already been set to the
                                390                 :                :      * number of pages the sampling method will visit)
                                391                 :                :      */
                                392                 :            245 :     run_cost += spc_page_cost * baserel->pages;
                                393                 :                : 
                                394                 :                :     /*
                                395                 :                :      * CPU costs (recall that baserel->tuples has already been set to the
                                396                 :                :      * number of tuples the sampling method will select).  Note that we ignore
                                397                 :                :      * execution cost of the TABLESAMPLE parameter expressions; they will be
                                398                 :                :      * evaluated only once per scan, and in most usages they'll likely be
                                399                 :                :      * simple constants anyway.  We also don't charge anything for the
                                400                 :                :      * calculations the sampling method might do internally.
                                401                 :                :      */
                                402                 :            245 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                                403                 :                : 
 4090 simon@2ndQuadrant.co      404                 :            245 :     startup_cost += qpqual_cost.startup;
                                405                 :            245 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
 4019 tgl@sss.pgh.pa.us         406                 :            245 :     run_cost += cpu_per_tuple * baserel->tuples;
                                407                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811                           408                 :            245 :     startup_cost += path->pathtarget->cost.startup;
                                409                 :            245 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                                410                 :                : 
  179 rhaas@postgresql.org      411         [ +  - ]:            245 :     if (path->parallel_workers == 0)
                                412                 :            245 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                                413                 :                : 
                                414                 :            245 :     path->disabled_nodes =
                                415                 :            245 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 9658 tgl@sss.pgh.pa.us         416                 :            245 :     path->startup_cost = startup_cost;
                                417                 :            245 :     path->total_cost = startup_cost + run_cost;
10974 scrappy@hub.org           418                 :            245 : }
                                419                 :                : 
                                420                 :                : /*
                                421                 :                :  * cost_gather
                                422                 :                :  *    Determines and returns the cost of gather path.
                                423                 :                :  *
                                424                 :                :  * 'rel' is the relation to be operated upon
                                425                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                                426                 :                :  * 'rows' may be used to point to a row estimate; if non-NULL, it overrides
                                427                 :                :  * both 'rel' and 'param_info'.  This is useful when the path doesn't exactly
                                428                 :                :  * correspond to any particular RelOptInfo.
                                429                 :                :  */
                                430                 :                : void
 3952 rhaas@postgresql.org      431                 :          21971 : cost_gather(GatherPath *path, PlannerInfo *root,
                                432                 :                :             RelOptInfo *rel, ParamPathInfo *param_info,
                                433                 :                :             double *rows)
                                434                 :                : {
                                435                 :          21971 :     Cost        startup_cost = 0;
                                436                 :          21971 :     Cost        run_cost = 0;
                                437                 :                : 
                                438                 :                :     /* Mark the path with the correct row estimate */
 3779                           439         [ +  + ]:          21971 :     if (rows)
                                440                 :           5822 :         path->path.rows = *rows;
                                441         [ -  + ]:          16149 :     else if (param_info)
 3952 rhaas@postgresql.org      442                 :UBC           0 :         path->path.rows = param_info->ppi_rows;
                                443                 :                :     else
 3952 rhaas@postgresql.org      444                 :CBC       16149 :         path->path.rows = rel->rows;
                                445                 :                : 
                                446                 :          21971 :     startup_cost = path->subpath->startup_cost;
                                447                 :                : 
                                448                 :          21971 :     run_cost = path->subpath->total_cost - path->subpath->startup_cost;
                                449                 :                : 
                                450                 :                :     /* Parallel setup and communication cost. */
                                451                 :          21971 :     startup_cost += parallel_setup_cost;
 3910                           452                 :          21971 :     run_cost += parallel_tuple_cost * path->path.rows;
                                453                 :                : 
  179                           454                 :          21971 :     path->path.disabled_nodes = path->subpath->disabled_nodes
                                455                 :          21971 :         + ((rel->pgs_mask & PGS_GATHER) != 0 ? 0 : 1);
 3952                           456                 :          21971 :     path->path.startup_cost = startup_cost;
                                457                 :          21971 :     path->path.total_cost = (startup_cost + run_cost);
                                458                 :          21971 : }
                                459                 :                : 
                                460                 :                : /*
                                461                 :                :  * cost_gather_merge
                                462                 :                :  *    Determines and returns the cost of gather merge path.
                                463                 :                :  *
                                464                 :                :  * GatherMerge merges several pre-sorted input streams, using a heap that at
                                465                 :                :  * any given instant holds the next tuple from each stream. If there are N
                                466                 :                :  * streams, we need about N*log2(N) tuple comparisons to construct the heap at
                                467                 :                :  * startup, and then for each output tuple, about log2(N) comparisons to
                                468                 :                :  * replace the top heap entry with the next tuple from the same stream.
                                469                 :                :  */
                                470                 :                : void
 3426                           471                 :          15813 : cost_gather_merge(GatherMergePath *path, PlannerInfo *root,
                                472                 :                :                   RelOptInfo *rel, ParamPathInfo *param_info,
                                473                 :                :                   int input_disabled_nodes,
                                474                 :                :                   Cost input_startup_cost, Cost input_total_cost,
                                475                 :                :                   double *rows)
                                476                 :                : {
                                477                 :          15813 :     Cost        startup_cost = 0;
                                478                 :          15813 :     Cost        run_cost = 0;
                                479                 :                :     Cost        comparison_cost;
                                480                 :                :     double      N;
                                481                 :                :     double      logN;
                                482                 :                : 
                                483                 :                :     /* Mark the path with the correct row estimate */
                                484         [ +  + ]:          15813 :     if (rows)
                                485                 :           9457 :         path->path.rows = *rows;
                                486         [ -  + ]:           6356 :     else if (param_info)
 3426 rhaas@postgresql.org      487                 :UBC           0 :         path->path.rows = param_info->ppi_rows;
                                488                 :                :     else
 3426 rhaas@postgresql.org      489                 :CBC        6356 :         path->path.rows = rel->rows;
                                490                 :                : 
                                491                 :                :     /*
                                492                 :                :      * Add one to the number of workers to account for the leader.  This might
                                493                 :                :      * be overgenerous since the leader will do less work than other workers
                                494                 :                :      * in typical cases, but we'll go with it for now.
                                495                 :                :      */
                                496         [ -  + ]:          15813 :     Assert(path->num_workers > 0);
                                497                 :          15813 :     N = (double) path->num_workers + 1;
                                498                 :          15813 :     logN = LOG2(N);
                                499                 :                : 
                                500                 :                :     /* Assumed cost per tuple comparison */
                                501                 :          15813 :     comparison_cost = 2.0 * cpu_operator_cost;
                                502                 :                : 
                                503                 :                :     /* Heap creation cost */
                                504                 :          15813 :     startup_cost += comparison_cost * N * logN;
                                505                 :                : 
                                506                 :                :     /* Per-tuple heap maintenance cost */
                                507                 :          15813 :     run_cost += path->path.rows * comparison_cost * logN;
                                508                 :                : 
                                509                 :                :     /* small cost for heap management, like cost_merge_append */
                                510                 :          15813 :     run_cost += cpu_operator_cost * path->path.rows;
                                511                 :                : 
                                512                 :                :     /*
                                513                 :                :      * Parallel setup and communication cost.  Since Gather Merge, unlike
                                514                 :                :      * Gather, requires us to block until a tuple is available from every
                                515                 :                :      * worker, we bump the IPC cost up a little bit as compared with Gather.
                                516                 :                :      * For lack of a better idea, charge an extra 5%.
                                517                 :                :      */
                                518                 :          15813 :     startup_cost += parallel_setup_cost;
                                519                 :          15813 :     run_cost += parallel_tuple_cost * path->path.rows * 1.05;
                                520                 :                : 
  179                           521                 :          15813 :     path->path.disabled_nodes = path->subpath->disabled_nodes
                                522                 :          15813 :         + ((rel->pgs_mask & PGS_GATHER_MERGE) != 0 ? 0 : 1);
 3426                           523                 :          15813 :     path->path.startup_cost = startup_cost + input_startup_cost;
                                524                 :          15813 :     path->path.total_cost = (startup_cost + run_cost + input_total_cost);
                                525                 :          15813 : }
                                526                 :                : 
                                527                 :                : /*
                                528                 :                :  * cost_index
                                529                 :                :  *    Determines and returns the cost of scanning a relation using an index.
                                530                 :                :  *
                                531                 :                :  * 'path' describes the indexscan under consideration, and is complete
                                532                 :                :  *      except for the fields to be set by this routine
                                533                 :                :  * 'loop_count' is the number of repetitions of the indexscan to factor into
                                534                 :                :  *      estimates of caching behavior
                                535                 :                :  *
                                536                 :                :  * In addition to rows, startup_cost and total_cost, cost_index() sets the
                                537                 :                :  * path's indextotalcost and indexselectivity fields.  These values will be
                                538                 :                :  * needed if the IndexPath is used in a BitmapIndexScan.
                                539                 :                :  *
                                540                 :                :  * NOTE: path->indexquals must contain only clauses usable as index
                                541                 :                :  * restrictions.  Any additional quals evaluated as qpquals may reduce the
                                542                 :                :  * number of returned tuples, but they won't reduce the number of tuples
                                543                 :                :  * we have to fetch from the table, so they don't reduce the scan cost.
                                544                 :                :  */
                                545                 :                : void
 3448                           546                 :         665791 : cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
                                547                 :                :            bool partial_path)
                                548                 :                : {
 5328 tgl@sss.pgh.pa.us         549                 :         665791 :     IndexOptInfo *index = path->indexinfo;
 7791                           550                 :         665791 :     RelOptInfo *baserel = index->rel;
 5328                           551                 :         665791 :     bool        indexonly = (path->path.pathtype == T_IndexOnlyScan);
                                552                 :                :     amcostestimate_function amcostestimate;
                                553                 :                :     List       *qpquals;
 9658                           554                 :         665791 :     Cost        startup_cost = 0;
                                555                 :         665791 :     Cost        run_cost = 0;
 3448 rhaas@postgresql.org      556                 :         665791 :     Cost        cpu_run_cost = 0;
                                557                 :                :     Cost        indexStartupCost;
                                558                 :                :     Cost        indexTotalCost;
                                559                 :                :     Selectivity indexSelectivity;
                                560                 :                :     double      indexCorrelation,
                                561                 :                :                 csquared;
                                562                 :                :     double      spc_seq_page_cost,
                                563                 :                :                 spc_random_page_cost;
                                564                 :                :     Cost        min_IO_cost,
                                565                 :                :                 max_IO_cost;
                                566                 :                :     QualCost    qpqual_cost;
                                567                 :                :     Cost        cpu_per_tuple;
                                568                 :                :     double      tuples_fetched;
                                569                 :                :     double      pages_fetched;
                                570                 :                :     double      rand_heap_pages;
                                571                 :                :     double      index_pages;
                                572                 :                :     uint64      enable_mask;
                                573                 :                : 
                                574                 :                :     /* Should only be applied to base relations */
 8841 tgl@sss.pgh.pa.us         575   [ +  -  -  + ]:         665791 :     Assert(IsA(baserel, RelOptInfo) &&
                                576                 :                :            IsA(index, IndexOptInfo));
 8569                           577         [ -  + ]:         665791 :     Assert(baserel->relid > 0);
 8841                           578         [ -  + ]:         665791 :     Assert(baserel->rtekind == RTE_RELATION);
                                579                 :                : 
                                580                 :                :     /*
                                581                 :                :      * Mark the path with the correct row estimate, and identify which quals
                                582                 :                :      * will need to be enforced as qpquals.  We need not check any quals that
                                583                 :                :      * are implied by the index's predicate, so we can use indrestrictinfo not
                                584                 :                :      * baserestrictinfo as the list of relevant restriction clauses for the
                                585                 :                :      * rel.
                                586                 :                :      */
 5211                           587         [ +  + ]:         665791 :     if (path->path.param_info)
                                588                 :                :     {
                                589                 :         138046 :         path->path.rows = path->path.param_info->ppi_rows;
                                590                 :                :         /* qpquals come from the rel's restriction clauses and ppi_clauses */
 2724                           591                 :         138046 :         qpquals = list_concat(extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
                                592                 :                :                                                           path->indexclauses),
 3322                           593                 :         138046 :                               extract_nonindex_conditions(path->path.param_info->ppi_clauses,
                                594                 :                :                                                           path->indexclauses));
                                595                 :                :     }
                                596                 :                :     else
                                597                 :                :     {
 5211                           598                 :         527745 :         path->path.rows = baserel->rows;
                                599                 :                :         /* qpquals come from just the rel's restriction clauses */
 3769                           600                 :         527745 :         qpquals = extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
                                601                 :                :                                               path->indexclauses);
                                602                 :                :     }
                                603                 :                : 
                                604                 :                :     /* is this scan type disabled? */
  179 rhaas@postgresql.org      605         [ +  + ]:         665791 :     enable_mask = (indexonly ? PGS_INDEXONLYSCAN : PGS_INDEXSCAN)
                                606         [ +  + ]:         665791 :         | (partial_path ? 0 : PGS_CONSIDER_NONPARTIAL);
                                607                 :         665791 :     path->path.disabled_nodes =
                                608                 :         665791 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
                                609                 :                : 
                                610                 :                :     /*
                                611                 :                :      * Call index-access-method-specific code to estimate the processing cost
                                612                 :                :      * for scanning the index, as well as the selectivity of the index (ie,
                                613                 :                :      * the fraction of main-table tuples we will have to retrieve) and its
                                614                 :                :      * correlation to the main-table tuple order.  We need a cast here because
                                615                 :                :      * pathnodes.h uses a weak function type to avoid including amapi.h.
                                616                 :                :      */
 3843 tgl@sss.pgh.pa.us         617                 :         665791 :     amcostestimate = (amcostestimate_function) index->amcostestimate;
                                618                 :         665791 :     amcostestimate(root, path, loop_count,
                                619                 :                :                    &indexStartupCost, &indexTotalCost,
                                620                 :                :                    &indexSelectivity, &indexCorrelation,
                                621                 :                :                    &index_pages);
                                622                 :                : 
                                623                 :                :     /*
                                624                 :                :      * Save amcostestimate's results for possible use in bitmap scan planning.
                                625                 :                :      * We don't bother to save indexStartupCost or indexCorrelation, because a
                                626                 :                :      * bitmap scan doesn't care about either.
                                627                 :                :      */
 7766                           628                 :         665791 :     path->indextotalcost = indexTotalCost;
                                629                 :         665791 :     path->indexselectivity = indexSelectivity;
                                630                 :                : 
                                631                 :                :     /* all costs for touching index itself included here */
 9658                           632                 :         665791 :     startup_cost += indexStartupCost;
                                633                 :         665791 :     run_cost += indexTotalCost - indexStartupCost;
                                634                 :                : 
                                635                 :                :     /* estimate number of main-table tuples fetched */
 7355                           636                 :         665791 :     tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
                                637                 :                : 
                                638                 :                :     /* fetch estimated page costs for tablespace containing table */
 6046 rhaas@postgresql.org      639                 :         665791 :     get_tablespace_page_costs(baserel->reltablespace,
                                640                 :                :                               &spc_random_page_cost,
                                641                 :                :                               &spc_seq_page_cost);
                                642                 :                : 
                                643                 :                :     /*----------
                                644                 :                :      * Estimate number of main-table pages fetched, and compute I/O cost.
                                645                 :                :      *
                                646                 :                :      * When the index ordering is uncorrelated with the table ordering,
                                647                 :                :      * we use an approximation proposed by Mackert and Lohman (see
                                648                 :                :      * index_pages_fetched() for details) to compute the number of pages
                                649                 :                :      * fetched, and then charge spc_random_page_cost per page fetched.
                                650                 :                :      *
                                651                 :                :      * When the index ordering is exactly correlated with the table ordering
                                652                 :                :      * (just after a CLUSTER, for example), the number of pages fetched should
                                653                 :                :      * be exactly selectivity * table_size.  What's more, all but the first
                                654                 :                :      * will be sequential fetches, not the random fetches that occur in the
                                655                 :                :      * uncorrelated case.  So if the number of pages is more than 1, we
                                656                 :                :      * ought to charge
                                657                 :                :      *      spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
                                658                 :                :      * For partially-correlated indexes, we ought to charge somewhere between
                                659                 :                :      * these two estimates.  We currently interpolate linearly between the
                                660                 :                :      * estimates based on the correlation squared (XXX is that appropriate?).
                                661                 :                :      *
                                662                 :                :      * If it's an index-only scan, then we will not need to fetch any heap
                                663                 :                :      * pages for which the visibility map shows all tuples are visible.
                                664                 :                :      * Hence, reduce the estimated number of heap fetches accordingly.
                                665                 :                :      * We use the measured fraction of the entire heap that is all-visible,
                                666                 :                :      * which might not be particularly relevant to the subset of the heap
                                667                 :                :      * that this query will fetch; but it's not clear how to do better.
                                668                 :                :      *----------
                                669                 :                :      */
 5294 tgl@sss.pgh.pa.us         670         [ +  + ]:         665791 :     if (loop_count > 1)
                                671                 :                :     {
                                672                 :                :         /*
                                673                 :                :          * For repeated indexscans, the appropriate estimate for the
                                674                 :                :          * uncorrelated case is to scale up the number of tuples fetched in
                                675                 :                :          * the Mackert and Lohman formula by the number of scans, so that we
                                676                 :                :          * estimate the number of pages fetched by all the scans; then
                                677                 :                :          * pro-rate the costs for one scan.  In this case we assume all the
                                678                 :                :          * fetches are random accesses.
                                679                 :                :          */
                                680                 :          74555 :         pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
                                681                 :                :                                             baserel->pages,
 7250                           682                 :          74555 :                                             (double) index->pages,
                                683                 :                :                                             root);
                                684                 :                : 
 5405                           685         [ +  + ]:          74555 :         if (indexonly)
 5399                           686                 :          11131 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
                                687                 :                : 
 3448 rhaas@postgresql.org      688                 :          74555 :         rand_heap_pages = pages_fetched;
                                689                 :                : 
 5294 tgl@sss.pgh.pa.us         690                 :          74555 :         max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
                                691                 :                : 
                                692                 :                :         /*
                                693                 :                :          * In the perfectly correlated case, the number of pages touched by
                                694                 :                :          * each scan is selectivity * table_size, and we can use the Mackert
                                695                 :                :          * and Lohman formula at the page level to estimate how much work is
                                696                 :                :          * saved by caching across scans.  We still assume all the fetches are
                                697                 :                :          * random, though, which is an overestimate that's hard to correct for
                                698                 :                :          * without double-counting the cache effects.  (But in most cases
                                699                 :                :          * where such a plan is actually interesting, only one page would get
                                700                 :                :          * fetched per scan anyway, so it shouldn't matter much.)
                                701                 :                :          */
 7163                           702                 :          74555 :         pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
                                703                 :                : 
 5294                           704                 :          74555 :         pages_fetched = index_pages_fetched(pages_fetched * loop_count,
                                705                 :                :                                             baserel->pages,
 7163                           706                 :          74555 :                                             (double) index->pages,
                                707                 :                :                                             root);
                                708                 :                : 
 5405                           709         [ +  + ]:          74555 :         if (indexonly)
 5399                           710                 :          11131 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
                                711                 :                : 
 5294                           712                 :          74555 :         min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
                                713                 :                :     }
                                714                 :                :     else
                                715                 :                :     {
                                716                 :                :         /*
                                717                 :                :          * Normal case: apply the Mackert and Lohman formula, and then
                                718                 :                :          * interpolate between that and the correlation-derived result.
                                719                 :                :          */
 7355                           720                 :         591236 :         pages_fetched = index_pages_fetched(tuples_fetched,
                                721                 :                :                                             baserel->pages,
 7250                           722                 :         591236 :                                             (double) index->pages,
                                723                 :                :                                             root);
                                724                 :                : 
 5405                           725         [ +  + ]:         591236 :         if (indexonly)
 5399                           726                 :          57299 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
                                727                 :                : 
 3448 rhaas@postgresql.org      728                 :         591236 :         rand_heap_pages = pages_fetched;
                                729                 :                : 
                                730                 :                :         /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
 6046                           731                 :         591236 :         max_IO_cost = pages_fetched * spc_random_page_cost;
                                732                 :                : 
                                733                 :                :         /* min_IO_cost is for the perfectly correlated case (csquared=1) */
 7355 tgl@sss.pgh.pa.us         734                 :         591236 :         pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
                                735                 :                : 
 5405                           736         [ +  + ]:         591236 :         if (indexonly)
 5399                           737                 :          57299 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
                                738                 :                : 
 5397                           739         [ +  + ]:         591236 :         if (pages_fetched > 0)
                                740                 :                :         {
                                741                 :         516826 :             min_IO_cost = spc_random_page_cost;
                                742         [ +  + ]:         516826 :             if (pages_fetched > 1)
                                743                 :         146949 :                 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
                                744                 :                :         }
                                745                 :                :         else
                                746                 :          74410 :             min_IO_cost = 0;
                                747                 :                :     }
                                748                 :                : 
 3448 rhaas@postgresql.org      749         [ +  + ]:         665791 :     if (partial_path)
                                750                 :                :     {
                                751                 :                :         /*
                                752                 :                :          * For index only scans compute workers based on number of index pages
                                753                 :                :          * fetched; the number of heap pages we fetch might be so small as to
                                754                 :                :          * effectively rule out parallelism, which we don't want to do.
                                755                 :                :          */
 3421                           756         [ +  + ]:         227036 :         if (indexonly)
                                757                 :          18996 :             rand_heap_pages = -1;
                                758                 :                : 
                                759                 :                :         /*
                                760                 :                :          * Estimate the number of parallel workers required to scan index. Use
                                761                 :                :          * the number of heap pages computed considering heap fetches won't be
                                762                 :                :          * sequential as for parallel scans the pages are accessed in random
                                763                 :                :          * order.
                                764                 :                :          */
 3448                           765                 :         227036 :         path->path.parallel_workers = compute_parallel_worker(baserel,
                                766                 :                :                                                               rand_heap_pages,
                                767                 :                :                                                               index_pages,
                                768                 :                :                                                               max_parallel_workers_per_gather);
                                769                 :                : 
                                770                 :                :         /*
                                771                 :                :          * Fall out if workers can't be assigned for parallel scan, because in
                                772                 :                :          * such a case this path will be rejected.  So there is no benefit in
                                773                 :                :          * doing extra computation.
                                774                 :                :          */
                                775         [ +  + ]:         227036 :         if (path->path.parallel_workers <= 0)
                                776                 :         219368 :             return;
                                777                 :                : 
                                778                 :           7668 :         path->path.parallel_aware = true;
                                779                 :                :     }
                                780                 :                : 
                                781                 :                :     /*
                                782                 :                :      * Now interpolate based on estimated index order correlation to get total
                                783                 :                :      * disk I/O cost for main table accesses.
                                784                 :                :      */
 7163 tgl@sss.pgh.pa.us         785                 :         446423 :     csquared = indexCorrelation * indexCorrelation;
                                786                 :                : 
                                787                 :         446423 :     run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
                                788                 :                : 
                                789                 :                :     /*
                                790                 :                :      * Estimate CPU costs per tuple.
                                791                 :                :      *
                                792                 :                :      * What we want here is cpu_tuple_cost plus the evaluation costs of any
                                793                 :                :      * qual clauses that we have to evaluate as qpquals.
                                794                 :                :      */
 4163                           795                 :         446423 :     cost_qual_eval(&qpqual_cost, qpquals, root);
                                796                 :                : 
 5219                           797                 :         446423 :     startup_cost += qpqual_cost.startup;
                                798                 :         446423 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
                                799                 :                : 
 3448 rhaas@postgresql.org      800                 :         446423 :     cpu_run_cost += cpu_per_tuple * tuples_fetched;
                                801                 :                : 
                                802                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811 tgl@sss.pgh.pa.us         803                 :         446423 :     startup_cost += path->path.pathtarget->cost.startup;
 3448 rhaas@postgresql.org      804                 :         446423 :     cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
                                805                 :                : 
                                806                 :                :     /* Adjust costing for parallelism, if used. */
                                807         [ +  + ]:         446423 :     if (path->path.parallel_workers > 0)
                                808                 :                :     {
                                809                 :           7668 :         double      parallel_divisor = get_parallel_divisor(&path->path);
                                810                 :                : 
                                811                 :           7668 :         path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
                                812                 :                : 
                                813                 :                :         /* The CPU cost is divided among all the workers. */
                                814                 :           7668 :         cpu_run_cost /= parallel_divisor;
                                815                 :                :     }
                                816                 :                : 
                                817                 :         446423 :     run_cost += cpu_run_cost;
                                818                 :                : 
 7766 tgl@sss.pgh.pa.us         819                 :         446423 :     path->path.startup_cost = startup_cost;
                                820                 :         446423 :     path->path.total_cost = startup_cost + run_cost;
                                821                 :                : }
                                822                 :                : 
                                823                 :                : /*
                                824                 :                :  * extract_nonindex_conditions
                                825                 :                :  *
                                826                 :                :  * Given a list of quals to be enforced in an indexscan, extract the ones that
                                827                 :                :  * will have to be applied as qpquals (ie, the index machinery won't handle
                                828                 :                :  * them).  Here we detect only whether a qual clause is directly redundant
                                829                 :                :  * with some indexclause.  If the index path is chosen for use, createplan.c
                                830                 :                :  * will try a bit harder to get rid of redundant qual conditions; specifically
                                831                 :                :  * it will see if quals can be proven to be implied by the indexquals.  But
                                832                 :                :  * it does not seem worth the cycles to try to factor that in at this stage,
                                833                 :                :  * since we're only trying to estimate qual eval costs.  Otherwise this must
                                834                 :                :  * match the logic in create_indexscan_plan().
                                835                 :                :  *
                                836                 :                :  * qual_clauses, and the result, are lists of RestrictInfos.
                                837                 :                :  * indexclauses is a list of IndexClauses.
                                838                 :                :  */
                                839                 :                : static List *
 2724                           840                 :         803837 : extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
                                841                 :                : {
 4163                           842                 :         803837 :     List       *result = NIL;
                                843                 :                :     ListCell   *lc;
                                844                 :                : 
                                845   [ +  +  +  +  :        1656750 :     foreach(lc, qual_clauses)
                                              +  + ]
                                846                 :                :     {
 3394                           847                 :         852913 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
                                848                 :                : 
 4163                           849         [ +  + ]:         852913 :         if (rinfo->pseudoconstant)
                                850                 :           3434 :             continue;           /* we may drop pseudoconstants here */
 2724                           851         [ +  + ]:         849479 :         if (is_redundant_with_indexclauses(rinfo, indexclauses))
                                852                 :         475306 :             continue;           /* dup or derived from same EquivalenceClass */
                                853                 :                :         /* ... skip the predicate proof attempt createplan.c will try ... */
 4163                           854                 :         374173 :         result = lappend(result, rinfo);
                                855                 :                :     }
                                856                 :         803837 :     return result;
                                857                 :                : }
                                858                 :                : 
                                859                 :                : /*
                                860                 :                :  * index_pages_fetched
                                861                 :                :  *    Estimate the number of pages actually fetched after accounting for
                                862                 :                :  *    cache effects.
                                863                 :                :  *
                                864                 :                :  * We use an approximation proposed by Mackert and Lohman, "Index Scans
                                865                 :                :  * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
                                866                 :                :  * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
                                867                 :                :  * The Mackert and Lohman approximation is that the number of pages
                                868                 :                :  * fetched is
                                869                 :                :  *  PF =
                                870                 :                :  *      min(2TNs/(2T+Ns), T)            when T <= b
                                871                 :                :  *      2TNs/(2T+Ns)                    when T > b and Ns <= 2Tb/(2T-b)
                                872                 :                :  *      b + (Ns - 2Tb/(2T-b))*(T-b)/T   when T > b and Ns > 2Tb/(2T-b)
                                873                 :                :  * where
                                874                 :                :  *      T = # pages in table
                                875                 :                :  *      N = # tuples in table
                                876                 :                :  *      s = selectivity = fraction of table to be scanned
                                877                 :                :  *      b = # buffer pages available (we include kernel space here)
                                878                 :                :  *
                                879                 :                :  * We assume that effective_cache_size is the total number of buffer pages
                                880                 :                :  * available for the whole query, and pro-rate that space across all the
                                881                 :                :  * tables in the query and the index currently under consideration.  (This
                                882                 :                :  * ignores space needed for other indexes used by the query, but since we
                                883                 :                :  * don't know which indexes will get used, we can't estimate that very well;
                                884                 :                :  * and in any case counting all the tables may well be an overestimate, since
                                885                 :                :  * depending on the join plan not all the tables may be scanned concurrently.)
                                886                 :                :  *
                                887                 :                :  * The product Ns is the number of tuples fetched; we pass in that
                                888                 :                :  * product rather than calculating it here.  "pages" is the number of pages
                                889                 :                :  * in the object under consideration (either an index or a table).
                                890                 :                :  * "index_pages" is the amount to add to the total table space, which was
                                891                 :                :  * computed for us by make_one_rel.
                                892                 :                :  *
                                893                 :                :  * Caller is expected to have ensured that tuples_fetched is greater than zero
                                894                 :                :  * and rounded to integer (see clamp_row_est).  The result will likewise be
                                895                 :                :  * greater than zero and integral.
                                896                 :                :  */
                                897                 :                : double
 7355                           898                 :         948130 : index_pages_fetched(double tuples_fetched, BlockNumber pages,
                                899                 :                :                     double index_pages, PlannerInfo *root)
                                900                 :                : {
                                901                 :                :     double      pages_fetched;
                                902                 :                :     double      total_pages;
                                903                 :                :     double      T,
                                904                 :                :                 b;
                                905                 :                : 
                                906                 :                :     /* T is # pages in table, but don't allow it to be zero */
                                907         [ +  + ]:         948130 :     T = (pages > 1) ? (double) pages : 1.0;
                                908                 :                : 
                                909                 :                :     /* Compute number of pages assumed to be competing for cache space */
 7250                           910                 :         948130 :     total_pages = root->total_table_pages + index_pages;
                                911         [ +  + ]:         948130 :     total_pages = Max(total_pages, 1.0);
                                912         [ -  + ]:         948130 :     Assert(T <= total_pages);
                                913                 :                : 
                                914                 :                :     /* b is pro-rated share of effective_cache_size */
 3322                           915                 :         948130 :     b = (double) effective_cache_size * T / total_pages;
                                916                 :                : 
                                917                 :                :     /* force it positive and integral */
 7355                           918         [ -  + ]:         948130 :     if (b <= 1.0)
 7355 tgl@sss.pgh.pa.us         919                 :UBC           0 :         b = 1.0;
                                920                 :                :     else
 7355 tgl@sss.pgh.pa.us         921                 :CBC      948130 :         b = ceil(b);
                                922                 :                : 
                                923                 :                :     /* This part is the Mackert and Lohman formula */
                                924         [ +  - ]:         948130 :     if (T <= b)
                                925                 :                :     {
                                926                 :         948130 :         pages_fetched =
                                927                 :         948130 :             (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
                                928         [ +  + ]:         948130 :         if (pages_fetched >= T)
                                929                 :         568003 :             pages_fetched = T;
                                930                 :                :         else
                                931                 :         380127 :             pages_fetched = ceil(pages_fetched);
                                932                 :                :     }
                                933                 :                :     else
                                934                 :                :     {
                                935                 :                :         double      lim;
                                936                 :                : 
 7355 tgl@sss.pgh.pa.us         937                 :UBC           0 :         lim = (2.0 * T * b) / (2.0 * T - b);
                                938         [ #  # ]:              0 :         if (tuples_fetched <= lim)
                                939                 :                :         {
                                940                 :              0 :             pages_fetched =
                                941                 :              0 :                 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
                                942                 :                :         }
                                943                 :                :         else
                                944                 :                :         {
                                945                 :              0 :             pages_fetched =
                                946                 :              0 :                 b + (tuples_fetched - lim) * (T - b) / T;
                                947                 :                :         }
                                948                 :              0 :         pages_fetched = ceil(pages_fetched);
                                949                 :                :     }
 7355 tgl@sss.pgh.pa.us         950                 :CBC      948130 :     return pages_fetched;
                                951                 :                : }
                                952                 :                : 
                                953                 :                : /*
                                954                 :                :  * get_indexpath_pages
                                955                 :                :  *      Determine the total size of the indexes used in a bitmap index path.
                                956                 :                :  *
                                957                 :                :  * Note: if the same index is used more than once in a bitmap tree, we will
                                958                 :                :  * count it multiple times, which perhaps is the wrong thing ... but it's
                                959                 :                :  * not completely clear, and detecting duplicates is difficult, so ignore it
                                960                 :                :  * for now.
                                961                 :                :  */
                                962                 :                : static double
 7250                           963                 :         172451 : get_indexpath_pages(Path *bitmapqual)
                                964                 :                : {
                                965                 :         172451 :     double      result = 0;
                                966                 :                :     ListCell   *l;
                                967                 :                : 
                                968         [ +  + ]:         172451 :     if (IsA(bitmapqual, BitmapAndPath))
                                969                 :                :     {
                                970                 :          21370 :         BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
                                971                 :                : 
                                972   [ +  -  +  +  :          64110 :         foreach(l, apath->bitmapquals)
                                              +  + ]
                                973                 :                :         {
                                974                 :          42740 :             result += get_indexpath_pages((Path *) lfirst(l));
                                975                 :                :         }
                                976                 :                :     }
                                977         [ +  + ]:         151081 :     else if (IsA(bitmapqual, BitmapOrPath))
                                978                 :                :     {
                                979                 :            209 :         BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
                                980                 :                : 
                                981   [ +  -  +  +  :            637 :         foreach(l, opath->bitmapquals)
                                              +  + ]
                                982                 :                :         {
                                983                 :            428 :             result += get_indexpath_pages((Path *) lfirst(l));
                                984                 :                :         }
                                985                 :                :     }
                                986         [ +  - ]:         150872 :     else if (IsA(bitmapqual, IndexPath))
                                987                 :                :     {
                                988                 :         150872 :         IndexPath  *ipath = (IndexPath *) bitmapqual;
                                989                 :                : 
                                990                 :         150872 :         result = (double) ipath->indexinfo->pages;
                                991                 :                :     }
                                992                 :                :     else
 7250 tgl@sss.pgh.pa.us         993         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
                                994                 :                : 
 7250 tgl@sss.pgh.pa.us         995                 :CBC      172451 :     return result;
                                996                 :                : }
                                997                 :                : 
                                998                 :                : /*
                                999                 :                :  * cost_bitmap_heap_scan
                               1000                 :                :  *    Determines and returns the cost of scanning a relation using a bitmap
                               1001                 :                :  *    index-then-heap plan.
                               1002                 :                :  *
                               1003                 :                :  * 'baserel' is the relation to be scanned
                               1004                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1005                 :                :  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
                               1006                 :                :  * 'loop_count' is the number of repetitions of the indexscan to factor into
                               1007                 :                :  *      estimates of caching behavior
                               1008                 :                :  *
                               1009                 :                :  * Note: the component IndexPaths in bitmapqual should have been costed
                               1010                 :                :  * using the same loop_count.
                               1011                 :                :  */
                               1012                 :                : void
 7721                          1013                 :         463050 : cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
                               1014                 :                :                       ParamPathInfo *param_info,
                               1015                 :                :                       Path *bitmapqual, double loop_count)
                               1016                 :                : {
 7768                          1017                 :         463050 :     Cost        startup_cost = 0;
                               1018                 :         463050 :     Cost        run_cost = 0;
                               1019                 :                :     Cost        indexTotalCost;
                               1020                 :                :     QualCost    qpqual_cost;
                               1021                 :                :     Cost        cpu_per_tuple;
                               1022                 :                :     Cost        cost_per_page;
                               1023                 :                :     Cost        cpu_run_cost;
                               1024                 :                :     double      tuples_fetched;
                               1025                 :                :     double      pages_fetched;
                               1026                 :                :     double      spc_seq_page_cost,
                               1027                 :                :                 spc_random_page_cost;
                               1028                 :                :     double      T;
  179 rhaas@postgresql.org     1029                 :         463050 :     uint64      enable_mask = PGS_BITMAPSCAN;
                               1030                 :                : 
                               1031                 :                :     /* Should only be applied to base relations */
 7768 tgl@sss.pgh.pa.us        1032         [ -  + ]:         463050 :     Assert(IsA(baserel, RelOptInfo));
                               1033         [ -  + ]:         463050 :     Assert(baserel->relid > 0);
                               1034         [ -  + ]:         463050 :     Assert(baserel->rtekind == RTE_RELATION);
                               1035                 :                : 
                               1036                 :                :     /* Mark the path with the correct row estimate */
 5211                          1037         [ +  + ]:         463050 :     if (param_info)
                               1038                 :         219346 :         path->rows = param_info->ppi_rows;
                               1039                 :                :     else
 5294                          1040                 :         243704 :         path->rows = baserel->rows;
                               1041                 :                : 
 3467 rhaas@postgresql.org     1042                 :         463050 :     pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
                               1043                 :                :                                          loop_count, &indexTotalCost,
                               1044                 :                :                                          &tuples_fetched);
                               1045                 :                : 
 7766 tgl@sss.pgh.pa.us        1046                 :         463050 :     startup_cost += indexTotalCost;
 3467 rhaas@postgresql.org     1047         [ +  + ]:         463050 :     T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
                               1048                 :                : 
                               1049                 :                :     /* Fetch estimated page costs for tablespace containing table. */
 6046                          1050                 :         463050 :     get_tablespace_page_costs(baserel->reltablespace,
                               1051                 :                :                               &spc_random_page_cost,
                               1052                 :                :                               &spc_seq_page_cost);
                               1053                 :                : 
                               1054                 :                :     /*
                               1055                 :                :      * For small numbers of pages we should charge spc_random_page_cost
                               1056                 :                :      * apiece, while if nearly all the table's pages are being read, it's more
                               1057                 :                :      * appropriate to charge spc_seq_page_cost apiece.  The effect is
                               1058                 :                :      * nonlinear, too. For lack of a better idea, interpolate like this to
                               1059                 :                :      * determine the cost per page.
                               1060                 :                :      */
 7765 tgl@sss.pgh.pa.us        1061         [ +  + ]:         463050 :     if (pages_fetched >= 2.0)
 6046 rhaas@postgresql.org     1062                 :          84704 :         cost_per_page = spc_random_page_cost -
                               1063                 :          84704 :             (spc_random_page_cost - spc_seq_page_cost)
                               1064                 :          84704 :             * sqrt(pages_fetched / T);
                               1065                 :                :     else
                               1066                 :         378346 :         cost_per_page = spc_random_page_cost;
                               1067                 :                : 
 7766 tgl@sss.pgh.pa.us        1068                 :         463050 :     run_cost += pages_fetched * cost_per_page;
                               1069                 :                : 
                               1070                 :                :     /*
                               1071                 :                :      * Estimate CPU costs per tuple.
                               1072                 :                :      *
                               1073                 :                :      * Often the indexquals don't need to be rechecked at each tuple ... but
                               1074                 :                :      * not always, especially not if there are enough tuples involved that the
                               1075                 :                :      * bitmaps become lossy.  For the moment, just assume they will be
                               1076                 :                :      * rechecked always.  This means we charge the full freight for all the
                               1077                 :                :      * scan clauses.
                               1078                 :                :      */
 5211                          1079                 :         463050 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1080                 :                : 
                               1081                 :         463050 :     startup_cost += qpqual_cost.startup;
                               1082                 :         463050 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
 3427 rhaas@postgresql.org     1083                 :         463050 :     cpu_run_cost = cpu_per_tuple * tuples_fetched;
                               1084                 :                : 
                               1085                 :                :     /* Adjust costing for parallelism, if used. */
                               1086         [ +  + ]:         463050 :     if (path->parallel_workers > 0)
                               1087                 :                :     {
                               1088                 :           3248 :         double      parallel_divisor = get_parallel_divisor(path);
                               1089                 :                : 
                               1090                 :                :         /* The CPU cost is divided among all the workers. */
                               1091                 :           3248 :         cpu_run_cost /= parallel_divisor;
                               1092                 :                : 
                               1093                 :           3248 :         path->rows = clamp_row_est(path->rows / parallel_divisor);
                               1094                 :                :     }
                               1095                 :                :     else
  179                          1096                 :         459802 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1097                 :                : 
                               1098                 :                : 
 3427                          1099                 :         463050 :     run_cost += cpu_run_cost;
                               1100                 :                : 
                               1101                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811 tgl@sss.pgh.pa.us        1102                 :         463050 :     startup_cost += path->pathtarget->cost.startup;
                               1103                 :         463050 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1104                 :                : 
  179 rhaas@postgresql.org     1105                 :         463050 :     path->disabled_nodes =
                               1106                 :         463050 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 7768 tgl@sss.pgh.pa.us        1107                 :         463050 :     path->startup_cost = startup_cost;
                               1108                 :         463050 :     path->total_cost = startup_cost + run_cost;
                               1109                 :         463050 : }
                               1110                 :                : 
                               1111                 :                : /*
                               1112                 :                :  * cost_bitmap_tree_node
                               1113                 :                :  *      Extract cost and selectivity from a bitmap tree node (index/and/or)
                               1114                 :                :  */
                               1115                 :                : void
 7766                          1116                 :         877392 : cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
                               1117                 :                : {
                               1118         [ +  + ]:         877392 :     if (IsA(path, IndexPath))
                               1119                 :                :     {
                               1120                 :         828196 :         *cost = ((IndexPath *) path)->indextotalcost;
                               1121                 :         828196 :         *selec = ((IndexPath *) path)->indexselectivity;
                               1122                 :                : 
                               1123                 :                :         /*
                               1124                 :                :          * Charge a small amount per retrieved tuple to reflect the costs of
                               1125                 :                :          * manipulating the bitmap.  This is mostly to make sure that a bitmap
                               1126                 :                :          * scan doesn't look to be the same cost as an indexscan to retrieve a
                               1127                 :                :          * single tuple.
                               1128                 :                :          */
 5294                          1129                 :         828196 :         *cost += 0.1 * cpu_operator_cost * path->rows;
                               1130                 :                :     }
 7766                          1131         [ +  + ]:          49196 :     else if (IsA(path, BitmapAndPath))
                               1132                 :                :     {
                               1133                 :          44802 :         *cost = path->total_cost;
                               1134                 :          44802 :         *selec = ((BitmapAndPath *) path)->bitmapselectivity;
                               1135                 :                :     }
                               1136         [ +  - ]:           4394 :     else if (IsA(path, BitmapOrPath))
                               1137                 :                :     {
                               1138                 :           4394 :         *cost = path->total_cost;
                               1139                 :           4394 :         *selec = ((BitmapOrPath *) path)->bitmapselectivity;
                               1140                 :                :     }
                               1141                 :                :     else
                               1142                 :                :     {
 7766 tgl@sss.pgh.pa.us        1143         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(path));
                               1144                 :                :         *cost = *selec = 0;     /* keep compiler quiet */
                               1145                 :                :     }
 7766 tgl@sss.pgh.pa.us        1146                 :CBC      877392 : }
                               1147                 :                : 
                               1148                 :                : /*
                               1149                 :                :  * cost_bitmap_and_node
                               1150                 :                :  *      Estimate the cost of a BitmapAnd node
                               1151                 :                :  *
                               1152                 :                :  * Note that this considers only the costs of index scanning and bitmap
                               1153                 :                :  * creation, not the eventual heap access.  In that sense the object isn't
                               1154                 :                :  * truly a Path, but it has enough path-like properties (costs in particular)
                               1155                 :                :  * to warrant treating it as one.  We don't bother to set the path rows field,
                               1156                 :                :  * however.
                               1157                 :                :  */
                               1158                 :                : void
 7721                          1159                 :          44669 : cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
                               1160                 :                : {
                               1161                 :                :     Cost        totalCost;
                               1162                 :                :     Selectivity selec;
                               1163                 :                :     ListCell   *l;
                               1164                 :                : 
                               1165                 :                :     /*
                               1166                 :                :      * We estimate AND selectivity on the assumption that the inputs are
                               1167                 :                :      * independent.  This is probably often wrong, but we don't have the info
                               1168                 :                :      * to do better.
                               1169                 :                :      *
                               1170                 :                :      * The runtime cost of the BitmapAnd itself is estimated at 100x
                               1171                 :                :      * cpu_operator_cost for each tbm_intersect needed.  Probably too small,
                               1172                 :                :      * definitely too simplistic?
                               1173                 :                :      */
 7766                          1174                 :          44669 :     totalCost = 0.0;
                               1175                 :          44669 :     selec = 1.0;
                               1176   [ +  -  +  +  :         134007 :     foreach(l, path->bitmapquals)
                                              +  + ]
                               1177                 :                :     {
 7589 bruce@momjian.us         1178                 :          89338 :         Path       *subpath = (Path *) lfirst(l);
                               1179                 :                :         Cost        subCost;
                               1180                 :                :         Selectivity subselec;
                               1181                 :                : 
 7766 tgl@sss.pgh.pa.us        1182                 :          89338 :         cost_bitmap_tree_node(subpath, &subCost, &subselec);
                               1183                 :                : 
                               1184                 :          89338 :         selec *= subselec;
                               1185                 :                : 
                               1186                 :          89338 :         totalCost += subCost;
                               1187         [ +  + ]:          89338 :         if (l != list_head(path->bitmapquals))
                               1188                 :          44669 :             totalCost += 100.0 * cpu_operator_cost;
                               1189                 :                :     }
                               1190                 :          44669 :     path->bitmapselectivity = selec;
 5294                          1191                 :          44669 :     path->path.rows = 0;     /* per above, not used */
  704 rhaas@postgresql.org     1192                 :          44669 :     path->path.disabled_nodes = 0;
 7766 tgl@sss.pgh.pa.us        1193                 :          44669 :     path->path.startup_cost = totalCost;
                               1194                 :          44669 :     path->path.total_cost = totalCost;
                               1195                 :          44669 : }
                               1196                 :                : 
                               1197                 :                : /*
                               1198                 :                :  * cost_bitmap_or_node
                               1199                 :                :  *      Estimate the cost of a BitmapOr node
                               1200                 :                :  *
                               1201                 :                :  * See comments for cost_bitmap_and_node.
                               1202                 :                :  */
                               1203                 :                : void
 7721                          1204                 :           1772 : cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
                               1205                 :                : {
                               1206                 :                :     Cost        totalCost;
                               1207                 :                :     Selectivity selec;
                               1208                 :                :     ListCell   *l;
                               1209                 :                : 
                               1210                 :                :     /*
                               1211                 :                :      * We estimate OR selectivity on the assumption that the inputs are
                               1212                 :                :      * non-overlapping, since that's often the case in "x IN (list)" type
                               1213                 :                :      * situations.  Of course, we clamp to 1.0 at the end.
                               1214                 :                :      *
                               1215                 :                :      * The runtime cost of the BitmapOr itself is estimated at 100x
                               1216                 :                :      * cpu_operator_cost for each tbm_union needed.  Probably too small,
                               1217                 :                :      * definitely too simplistic?  We are aware that the tbm_unions are
                               1218                 :                :      * optimized out when the inputs are BitmapIndexScans.
                               1219                 :                :      */
 7766                          1220                 :           1772 :     totalCost = 0.0;
                               1221                 :           1772 :     selec = 0.0;
                               1222   [ +  -  +  +  :           4147 :     foreach(l, path->bitmapquals)
                                              +  + ]
                               1223                 :                :     {
 7589 bruce@momjian.us         1224                 :           2375 :         Path       *subpath = (Path *) lfirst(l);
                               1225                 :                :         Cost        subCost;
                               1226                 :                :         Selectivity subselec;
                               1227                 :                : 
 7766 tgl@sss.pgh.pa.us        1228                 :           2375 :         cost_bitmap_tree_node(subpath, &subCost, &subselec);
                               1229                 :                : 
                               1230                 :           2375 :         selec += subselec;
                               1231                 :                : 
                               1232                 :           2375 :         totalCost += subCost;
                               1233         [ +  + ]:           2375 :         if (l != list_head(path->bitmapquals) &&
                               1234         [ -  + ]:            603 :             !IsA(subpath, IndexPath))
 7766 tgl@sss.pgh.pa.us        1235                 :UBC           0 :             totalCost += 100.0 * cpu_operator_cost;
                               1236                 :                :     }
 7766 tgl@sss.pgh.pa.us        1237         [ +  - ]:CBC        1772 :     path->bitmapselectivity = Min(selec, 1.0);
 5294                          1238                 :           1772 :     path->path.rows = 0;     /* per above, not used */
 7766                          1239                 :           1772 :     path->path.startup_cost = totalCost;
                               1240                 :           1772 :     path->path.total_cost = totalCost;
                               1241                 :           1772 : }
                               1242                 :                : 
                               1243                 :                : /*
                               1244                 :                :  * cost_tidscan
                               1245                 :                :  *    Determines and returns the cost of scanning a relation using TIDs.
                               1246                 :                :  *
                               1247                 :                :  * 'baserel' is the relation to be scanned
                               1248                 :                :  * 'tidquals' is the list of TID-checkable quals
                               1249                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1250                 :                :  */
                               1251                 :                : void
 7721                          1252                 :            636 : cost_tidscan(Path *path, PlannerInfo *root,
                               1253                 :                :              RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
                               1254                 :                : {
 9658                          1255                 :            636 :     Cost        startup_cost = 0;
                               1256                 :            636 :     Cost        run_cost = 0;
                               1257                 :                :     QualCost    qpqual_cost;
                               1258                 :                :     Cost        cpu_per_tuple;
                               1259                 :                :     QualCost    tid_qual_cost;
                               1260                 :                :     double      ntuples;
                               1261                 :                :     ListCell   *l;
                               1262                 :                :     double      spc_random_page_cost;
  179 rhaas@postgresql.org     1263                 :            636 :     uint64      enable_mask = 0;
                               1264                 :                : 
                               1265                 :                :     /* Should only be applied to base relations */
 8569 tgl@sss.pgh.pa.us        1266         [ -  + ]:            636 :     Assert(baserel->relid > 0);
 8841                          1267         [ -  + ]:            636 :     Assert(baserel->rtekind == RTE_RELATION);
  704 rhaas@postgresql.org     1268         [ -  + ]:            636 :     Assert(tidquals != NIL);
                               1269                 :                : 
                               1270                 :                :     /* Mark the path with the correct row estimate */
 5082 tgl@sss.pgh.pa.us        1271         [ +  + ]:            636 :     if (param_info)
                               1272                 :             97 :         path->rows = param_info->ppi_rows;
                               1273                 :                :     else
                               1274                 :            539 :         path->rows = baserel->rows;
                               1275                 :                : 
                               1276                 :                :     /* Count how many tuples we expect to retrieve */
 7547                          1277                 :            636 :     ntuples = 0;
                               1278   [ +  -  +  +  :           1293 :     foreach(l, tidquals)
                                              +  + ]
                               1279                 :                :     {
 2765                          1280                 :            657 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
                               1281                 :            657 :         Expr       *qual = rinfo->clause;
                               1282                 :                : 
                               1283                 :                :         /*
                               1284                 :                :          * We must use a TID scan for CurrentOfExpr; in any other case, we
                               1285                 :                :          * should be generating a TID scan only if TID scans are allowed.
                               1286                 :                :          * Also, if CurrentOfExpr is the qual, there should be only one.
                               1287                 :                :          */
  179 rhaas@postgresql.org     1288   [ -  +  -  - ]:            657 :         Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0 || IsA(qual, CurrentOfExpr));
  704                          1289   [ +  +  -  + ]:            657 :         Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
                               1290                 :                : 
 2765 tgl@sss.pgh.pa.us        1291         [ +  + ]:            657 :         if (IsA(qual, ScalarArrayOpExpr))
                               1292                 :                :         {
                               1293                 :                :             /* Each element of the array yields 1 tuple */
                               1294                 :             41 :             ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
 7235 bruce@momjian.us         1295                 :             41 :             Node       *arraynode = (Node *) lsecond(saop->args);
                               1296                 :                : 
  934 tgl@sss.pgh.pa.us        1297                 :             41 :             ntuples += estimate_array_length(root, arraynode);
                               1298                 :                :         }
 2765                          1299         [ +  + ]:            616 :         else if (IsA(qual, CurrentOfExpr))
                               1300                 :                :         {
                               1301                 :                :             /* CURRENT OF yields 1 tuple */
 6850                          1302                 :            344 :             ntuples++;
                               1303                 :                :         }
                               1304                 :                :         else
                               1305                 :                :         {
                               1306                 :                :             /* It's just CTID = something, count 1 tuple */
 7547                          1307                 :            272 :             ntuples++;
                               1308                 :                :         }
                               1309                 :                :     }
                               1310                 :                : 
                               1311                 :                :     /*
                               1312                 :                :      * The TID qual expressions will be computed once, any other baserestrict
                               1313                 :                :      * quals once per retrieved tuple.
                               1314                 :                :      */
 6985                          1315                 :            636 :     cost_qual_eval(&tid_qual_cost, tidquals, root);
                               1316                 :                : 
                               1317                 :                :     /* fetch estimated page cost for tablespace containing table */
 6046 rhaas@postgresql.org     1318                 :            636 :     get_tablespace_page_costs(baserel->reltablespace,
                               1319                 :                :                               &spc_random_page_cost,
                               1320                 :                :                               NULL);
                               1321                 :                : 
                               1322                 :                :     /* disk costs --- assume each tuple on a different page */
                               1323                 :            636 :     run_cost += spc_random_page_cost * ntuples;
                               1324                 :                : 
                               1325                 :                :     /* Add scanning CPU costs */
 5082 tgl@sss.pgh.pa.us        1326                 :            636 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1327                 :                : 
                               1328                 :                :     /* XXX currently we assume TID quals are a subset of qpquals */
                               1329                 :            636 :     startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
                               1330                 :            636 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
 6985                          1331                 :            636 :         tid_qual_cost.per_tuple;
 9658                          1332                 :            636 :     run_cost += cpu_per_tuple * ntuples;
                               1333                 :                : 
                               1334                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811                          1335                 :            636 :     startup_cost += path->pathtarget->cost.startup;
                               1336                 :            636 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1337                 :                : 
                               1338                 :                :     /*
                               1339                 :                :      * There are assertions above verifying that we only reach this function
                               1340                 :                :      * either when baserel->pgs_mask includes PGS_TIDSCAN or when the TID scan
                               1341                 :                :      * is the only legal path, so we only need to consider the effects of
                               1342                 :                :      * PGS_CONSIDER_NONPARTIAL here.
                               1343                 :                :      */
  179 rhaas@postgresql.org     1344         [ +  - ]:            636 :     if (path->parallel_workers == 0)
                               1345                 :            636 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1346                 :            636 :     path->disabled_nodes =
                               1347                 :            636 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 9658 tgl@sss.pgh.pa.us        1348                 :            636 :     path->startup_cost = startup_cost;
                               1349                 :            636 :     path->total_cost = startup_cost + run_cost;
 9742 bruce@momjian.us         1350                 :            636 : }
                               1351                 :                : 
                               1352                 :                : /*
                               1353                 :                :  * cost_tidrangescan
                               1354                 :                :  *    Determines and sets the costs of scanning a relation using a range of
                               1355                 :                :  *    TIDs for 'path'
                               1356                 :                :  *
                               1357                 :                :  * 'baserel' is the relation to be scanned
                               1358                 :                :  * 'tidrangequals' is the list of TID-checkable range quals
                               1359                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1360                 :                :  */
                               1361                 :                : void
 1975 drowley@postgresql.o     1362                 :           1703 : cost_tidrangescan(Path *path, PlannerInfo *root,
                               1363                 :                :                   RelOptInfo *baserel, List *tidrangequals,
                               1364                 :                :                   ParamPathInfo *param_info)
                               1365                 :                : {
                               1366                 :                :     Selectivity selectivity;
                               1367                 :                :     double      pages;
                               1368                 :                :     Cost        startup_cost;
                               1369                 :                :     Cost        cpu_run_cost;
                               1370                 :                :     Cost        disk_run_cost;
                               1371                 :                :     QualCost    qpqual_cost;
                               1372                 :                :     Cost        cpu_per_tuple;
                               1373                 :                :     QualCost    tid_qual_cost;
                               1374                 :                :     double      ntuples;
                               1375                 :                :     double      nseqpages;
                               1376                 :                :     double      spc_random_page_cost;
                               1377                 :                :     double      spc_seq_page_cost;
  179 rhaas@postgresql.org     1378                 :           1703 :     uint64      enable_mask = PGS_TIDSCAN;
                               1379                 :                : 
                               1380                 :                :     /* Should only be applied to base relations */
 1975 drowley@postgresql.o     1381         [ -  + ]:           1703 :     Assert(baserel->relid > 0);
                               1382         [ -  + ]:           1703 :     Assert(baserel->rtekind == RTE_RELATION);
                               1383                 :                : 
                               1384                 :                :     /* Mark the path with the correct row estimate */
                               1385         [ -  + ]:           1703 :     if (param_info)
 1975 drowley@postgresql.o     1386                 :UBC           0 :         path->rows = param_info->ppi_rows;
                               1387                 :                :     else
 1975 drowley@postgresql.o     1388                 :CBC        1703 :         path->rows = baserel->rows;
                               1389                 :                : 
                               1390                 :                :     /* Count how many tuples and pages we expect to scan */
                               1391                 :           1703 :     selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
                               1392                 :                :                                          JOIN_INNER, NULL);
                               1393                 :           1703 :     pages = ceil(selectivity * baserel->pages);
                               1394                 :                : 
                               1395         [ +  + ]:           1703 :     if (pages <= 0.0)
                               1396                 :             35 :         pages = 1.0;
                               1397                 :                : 
                               1398                 :                :     /*
                               1399                 :                :      * The first page in a range requires a random seek, but each subsequent
                               1400                 :                :      * page is just a normal sequential page read. NOTE: it's desirable for
                               1401                 :                :      * TID Range Scans to cost more than the equivalent Sequential Scans,
                               1402                 :                :      * because Seq Scans have some performance advantages such as scan
                               1403                 :                :      * synchronization, and we'd prefer one of them to be picked unless a TID
                               1404                 :                :      * Range Scan really is better.
                               1405                 :                :      */
                               1406                 :           1703 :     ntuples = selectivity * baserel->tuples;
                               1407                 :           1703 :     nseqpages = pages - 1.0;
                               1408                 :                : 
                               1409                 :                :     /*
                               1410                 :                :      * The TID qual expressions will be computed once, any other baserestrict
                               1411                 :                :      * quals once per retrieved tuple.
                               1412                 :                :      */
                               1413                 :           1703 :     cost_qual_eval(&tid_qual_cost, tidrangequals, root);
                               1414                 :                : 
                               1415                 :                :     /* fetch estimated page cost for tablespace containing table */
                               1416                 :           1703 :     get_tablespace_page_costs(baserel->reltablespace,
                               1417                 :                :                               &spc_random_page_cost,
                               1418                 :                :                               &spc_seq_page_cost);
                               1419                 :                : 
                               1420                 :                :     /* disk costs; 1 random page and the remainder as seq pages */
  241                          1421                 :           1703 :     disk_run_cost = spc_random_page_cost + spc_seq_page_cost * nseqpages;
                               1422                 :                : 
                               1423                 :                :     /* Add scanning CPU costs */
 1975                          1424                 :           1703 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1425                 :                : 
                               1426                 :                :     /*
                               1427                 :                :      * XXX currently we assume TID quals are a subset of qpquals at this
                               1428                 :                :      * point; they will be removed (if possible) when we create the plan, so
                               1429                 :                :      * we subtract their cost from the total qpqual cost.  (If the TID quals
                               1430                 :                :      * can't be removed, this is a mistake and we're going to underestimate
                               1431                 :                :      * the CPU cost a bit.)
                               1432                 :                :      */
  241                          1433                 :           1703 :     startup_cost = qpqual_cost.startup + tid_qual_cost.per_tuple;
 1975                          1434                 :           1703 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
                               1435                 :           1703 :         tid_qual_cost.per_tuple;
  241                          1436                 :           1703 :     cpu_run_cost = cpu_per_tuple * ntuples;
                               1437                 :                : 
                               1438                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 1975                          1439                 :           1703 :     startup_cost += path->pathtarget->cost.startup;
  241                          1440                 :           1703 :     cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1441                 :                : 
                               1442                 :                :     /* Adjust costing for parallelism, if used. */
                               1443         [ +  + ]:           1703 :     if (path->parallel_workers > 0)
                               1444                 :                :     {
                               1445                 :             40 :         double      parallel_divisor = get_parallel_divisor(path);
                               1446                 :                : 
                               1447                 :                :         /* The CPU cost is divided among all the workers. */
                               1448                 :             40 :         cpu_run_cost /= parallel_divisor;
                               1449                 :                : 
                               1450                 :                :         /*
                               1451                 :                :          * In the case of a parallel plan, the row count needs to represent
                               1452                 :                :          * the number of tuples processed per worker.
                               1453                 :                :          */
                               1454                 :             40 :         path->rows = clamp_row_est(path->rows / parallel_divisor);
                               1455                 :                :     }
                               1456                 :                : 
                               1457                 :                :     /*
                               1458                 :                :      * We should not generate this path type when PGS_TIDSCAN is unset, but we
                               1459                 :                :      * might need to disable this path due to PGS_CONSIDER_NONPARTIAL.
                               1460                 :                :      */
  179 rhaas@postgresql.org     1461         [ -  + ]:           1703 :     Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0);
                               1462         [ +  + ]:           1703 :     if (path->parallel_workers == 0)
                               1463                 :           1663 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1464                 :           1703 :     path->disabled_nodes =
                               1465                 :           1703 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 1975 drowley@postgresql.o     1466                 :           1703 :     path->startup_cost = startup_cost;
  241                          1467                 :           1703 :     path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
 1975                          1468                 :           1703 : }
                               1469                 :                : 
                               1470                 :                : /*
                               1471                 :                :  * cost_subqueryscan
                               1472                 :                :  *    Determines and returns the cost of scanning a subquery RTE.
                               1473                 :                :  *
                               1474                 :                :  * 'baserel' is the relation to be scanned
                               1475                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1476                 :                :  * 'trivial_pathtarget' is true if the pathtarget is believed to be trivial.
                               1477                 :                :  */
                               1478                 :                : void
 3793 tgl@sss.pgh.pa.us        1479                 :          49142 : cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root,
                               1480                 :                :                   RelOptInfo *baserel, ParamPathInfo *param_info,
                               1481                 :                :                   bool trivial_pathtarget)
                               1482                 :                : {
                               1483                 :                :     Cost        startup_cost;
                               1484                 :                :     Cost        run_cost;
                               1485                 :                :     List       *qpquals;
                               1486                 :                :     QualCost    qpqual_cost;
                               1487                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org     1488                 :          49142 :     uint64      enable_mask = 0;
                               1489                 :                : 
                               1490                 :                :     /* Should only be applied to base relations that are subqueries */
 8413 tgl@sss.pgh.pa.us        1491         [ -  + ]:          49142 :     Assert(baserel->relid > 0);
                               1492         [ -  + ]:          49142 :     Assert(baserel->rtekind == RTE_SUBQUERY);
                               1493                 :                : 
                               1494                 :                :     /*
                               1495                 :                :      * We compute the rowcount estimate as the subplan's estimate times the
                               1496                 :                :      * selectivity of relevant restriction clauses.  In simple cases this will
                               1497                 :                :      * come out the same as baserel->rows; but when dealing with parallelized
                               1498                 :                :      * paths we must do it like this to get the right answer.
                               1499                 :                :      */
 5211                          1500         [ +  + ]:          49142 :     if (param_info)
 1544                          1501                 :            956 :         qpquals = list_concat_copy(param_info->ppi_clauses,
                               1502                 :            956 :                                    baserel->baserestrictinfo);
                               1503                 :                :     else
                               1504                 :          48186 :         qpquals = baserel->baserestrictinfo;
                               1505                 :                : 
                               1506                 :          49142 :     path->path.rows = clamp_row_est(path->subpath->rows *
                               1507                 :          49142 :                                     clauselist_selectivity(root,
                               1508                 :                :                                                            qpquals,
                               1509                 :                :                                                            0,
                               1510                 :                :                                                            JOIN_INNER,
                               1511                 :                :                                                            NULL));
                               1512                 :                : 
                               1513                 :                :     /*
                               1514                 :                :      * Cost of path is cost of evaluating the subplan, plus cost of evaluating
                               1515                 :                :      * any restriction clauses and tlist that will be attached to the
                               1516                 :                :      * SubqueryScan node, plus cpu_tuple_cost to account for selection and
                               1517                 :                :      * projection overhead.
                               1518                 :                :      */
  179 rhaas@postgresql.org     1519         [ +  + ]:          49142 :     if (path->path.parallel_workers == 0)
                               1520                 :          49082 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1521                 :          49142 :     path->path.disabled_nodes = path->subpath->disabled_nodes
                               1522                 :          49142 :         + (((baserel->pgs_mask & enable_mask) != enable_mask) ? 1 : 0);
 3793 tgl@sss.pgh.pa.us        1523                 :          49142 :     path->path.startup_cost = path->subpath->startup_cost;
                               1524                 :          49142 :     path->path.total_cost = path->subpath->total_cost;
                               1525                 :                : 
                               1526                 :                :     /*
                               1527                 :                :      * However, if there are no relevant restriction clauses and the
                               1528                 :                :      * pathtarget is trivial, then we expect that setrefs.c will optimize away
                               1529                 :                :      * the SubqueryScan plan node altogether, so we should just make its cost
                               1530                 :                :      * and rowcount equal to the input path's.
                               1531                 :                :      *
                               1532                 :                :      * Note: there are some edge cases where createplan.c will apply a
                               1533                 :                :      * different targetlist to the SubqueryScan node, thus falsifying our
                               1534                 :                :      * current estimate of whether the target is trivial, and making the cost
                               1535                 :                :      * estimate (though not the rowcount) wrong.  It does not seem worth the
                               1536                 :                :      * extra complication to try to account for that exactly, especially since
                               1537                 :                :      * that behavior falsifies other cost estimates as well.
                               1538                 :                :      */
 1468                          1539   [ +  +  +  + ]:          49142 :     if (qpquals == NIL && trivial_pathtarget)
                               1540                 :          22160 :         return;
                               1541                 :                : 
 5211                          1542                 :          26982 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1543                 :                : 
                               1544                 :          26982 :     startup_cost = qpqual_cost.startup;
                               1545                 :          26982 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
 1544                          1546                 :          26982 :     run_cost = cpu_per_tuple * path->subpath->rows;
                               1547                 :                : 
                               1548                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3793                          1549                 :          26982 :     startup_cost += path->path.pathtarget->cost.startup;
                               1550                 :          26982 :     run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
                               1551                 :                : 
                               1552                 :          26982 :     path->path.startup_cost += startup_cost;
                               1553                 :          26982 :     path->path.total_cost += startup_cost + run_cost;
                               1554                 :                : }
                               1555                 :                : 
                               1556                 :                : /*
                               1557                 :                :  * cost_functionscan
                               1558                 :                :  *    Determines and returns the cost of scanning a function RTE.
                               1559                 :                :  *
                               1560                 :                :  * 'baserel' is the relation to be scanned
                               1561                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1562                 :                :  */
                               1563                 :                : void
 5101                          1564                 :          35061 : cost_functionscan(Path *path, PlannerInfo *root,
                               1565                 :                :                   RelOptInfo *baserel, ParamPathInfo *param_info)
                               1566                 :                : {
 8841                          1567                 :          35061 :     Cost        startup_cost = 0;
                               1568                 :          35061 :     Cost        run_cost = 0;
                               1569                 :                :     QualCost    qpqual_cost;
                               1570                 :                :     Cost        cpu_per_tuple;
                               1571                 :                :     RangeTblEntry *rte;
                               1572                 :                :     QualCost    exprcost;
  179 rhaas@postgresql.org     1573                 :          35061 :     uint64      enable_mask = 0;
                               1574                 :                : 
                               1575                 :                :     /* Should only be applied to base relations that are functions */
 8569 tgl@sss.pgh.pa.us        1576         [ -  + ]:          35061 :     Assert(baserel->relid > 0);
 7036                          1577         [ +  - ]:          35061 :     rte = planner_rt_fetch(baserel->relid, root);
 7125                          1578         [ -  + ]:          35061 :     Assert(rte->rtekind == RTE_FUNCTION);
                               1579                 :                : 
                               1580                 :                :     /* Mark the path with the correct row estimate */
 5101                          1581         [ +  + ]:          35061 :     if (param_info)
                               1582                 :           4419 :         path->rows = param_info->ppi_rows;
                               1583                 :                :     else
                               1584                 :          30642 :         path->rows = baserel->rows;
                               1585                 :                : 
                               1586                 :                :     /*
                               1587                 :                :      * Estimate costs of executing the function expression(s).
                               1588                 :                :      *
                               1589                 :                :      * Currently, nodeFunctionscan.c always executes the functions to
                               1590                 :                :      * completion before returning any rows, and caches the results in a
                               1591                 :                :      * tuplestore.  So the function eval cost is all startup cost, and per-row
                               1592                 :                :      * costs are minimal.
                               1593                 :                :      *
                               1594                 :                :      * XXX in principle we ought to charge tuplestore spill costs if the
                               1595                 :                :      * number of rows is large.  However, given how phony our rowcount
                               1596                 :                :      * estimates for functions tend to be, there's not a lot of point in that
                               1597                 :                :      * refinement right now.
                               1598                 :                :      */
 4630                          1599                 :          35061 :     cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
                               1600                 :                : 
 6161                          1601                 :          35061 :     startup_cost += exprcost.startup + exprcost.per_tuple;
                               1602                 :                : 
                               1603                 :                :     /* Add scanning CPU costs */
 5101                          1604                 :          35061 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1605                 :                : 
                               1606                 :          35061 :     startup_cost += qpqual_cost.startup;
                               1607                 :          35061 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
 8841                          1608                 :          35061 :     run_cost += cpu_per_tuple * baserel->tuples;
                               1609                 :                : 
                               1610                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811                          1611                 :          35061 :     startup_cost += path->pathtarget->cost.startup;
                               1612                 :          35061 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1613                 :                : 
  179 rhaas@postgresql.org     1614         [ +  - ]:          35061 :     if (path->parallel_workers == 0)
                               1615                 :          35061 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1616                 :          35061 :     path->disabled_nodes =
                               1617                 :          35061 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 8841 tgl@sss.pgh.pa.us        1618                 :          35061 :     path->startup_cost = startup_cost;
                               1619                 :          35061 :     path->total_cost = startup_cost + run_cost;
                               1620                 :          35061 : }
                               1621                 :                : 
                               1622                 :                : /*
                               1623                 :                :  * cost_tablefuncscan
                               1624                 :                :  *    Determines and returns the cost of scanning a table function.
                               1625                 :                :  *
                               1626                 :                :  * 'baserel' is the relation to be scanned
                               1627                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1628                 :                :  */
                               1629                 :                : void
 3427 alvherre@alvh.no-ip.     1630                 :            602 : cost_tablefuncscan(Path *path, PlannerInfo *root,
                               1631                 :                :                    RelOptInfo *baserel, ParamPathInfo *param_info)
                               1632                 :                : {
                               1633                 :            602 :     Cost        startup_cost = 0;
                               1634                 :            602 :     Cost        run_cost = 0;
                               1635                 :                :     QualCost    qpqual_cost;
                               1636                 :                :     Cost        cpu_per_tuple;
                               1637                 :                :     RangeTblEntry *rte;
                               1638                 :                :     QualCost    exprcost;
  179 rhaas@postgresql.org     1639                 :            602 :     uint64      enable_mask = 0;
                               1640                 :                : 
                               1641                 :                :     /* Should only be applied to base relations that are functions */
 3427 alvherre@alvh.no-ip.     1642         [ -  + ]:            602 :     Assert(baserel->relid > 0);
                               1643         [ +  - ]:            602 :     rte = planner_rt_fetch(baserel->relid, root);
                               1644         [ -  + ]:            602 :     Assert(rte->rtekind == RTE_TABLEFUNC);
                               1645                 :                : 
                               1646                 :                :     /* Mark the path with the correct row estimate */
                               1647         [ +  + ]:            602 :     if (param_info)
                               1648                 :            240 :         path->rows = param_info->ppi_rows;
                               1649                 :                :     else
                               1650                 :            362 :         path->rows = baserel->rows;
                               1651                 :                : 
                               1652                 :                :     /*
                               1653                 :                :      * Estimate costs of executing the table func expression(s).
                               1654                 :                :      *
                               1655                 :                :      * XXX in principle we ought to charge tuplestore spill costs if the
                               1656                 :                :      * number of rows is large.  However, given how phony our rowcount
                               1657                 :                :      * estimates for tablefuncs tend to be, there's not a lot of point in that
                               1658                 :                :      * refinement right now.
                               1659                 :                :      */
                               1660                 :            602 :     cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
                               1661                 :                : 
                               1662                 :            602 :     startup_cost += exprcost.startup + exprcost.per_tuple;
                               1663                 :                : 
                               1664                 :                :     /* Add scanning CPU costs */
                               1665                 :            602 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1666                 :                : 
                               1667                 :            602 :     startup_cost += qpqual_cost.startup;
                               1668                 :            602 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
                               1669                 :            602 :     run_cost += cpu_per_tuple * baserel->tuples;
                               1670                 :                : 
                               1671                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
                               1672                 :            602 :     startup_cost += path->pathtarget->cost.startup;
                               1673                 :            602 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1674                 :                : 
  179 rhaas@postgresql.org     1675         [ +  - ]:            602 :     if (path->parallel_workers == 0)
                               1676                 :            602 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1677                 :            602 :     path->disabled_nodes =
                               1678                 :            602 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 3427 alvherre@alvh.no-ip.     1679                 :            602 :     path->startup_cost = startup_cost;
                               1680                 :            602 :     path->total_cost = startup_cost + run_cost;
                               1681                 :            602 : }
                               1682                 :                : 
                               1683                 :                : /*
                               1684                 :                :  * cost_valuesscan
                               1685                 :                :  *    Determines and returns the cost of scanning a VALUES RTE.
                               1686                 :                :  *
                               1687                 :                :  * 'baserel' is the relation to be scanned
                               1688                 :                :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
                               1689                 :                :  */
                               1690                 :                : void
 5096 tgl@sss.pgh.pa.us        1691                 :           6996 : cost_valuesscan(Path *path, PlannerInfo *root,
                               1692                 :                :                 RelOptInfo *baserel, ParamPathInfo *param_info)
                               1693                 :                : {
 7298 mail@joeconway.com       1694                 :           6996 :     Cost        startup_cost = 0;
                               1695                 :           6996 :     Cost        run_cost = 0;
                               1696                 :                :     QualCost    qpqual_cost;
                               1697                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org     1698                 :           6996 :     uint64      enable_mask = 0;
                               1699                 :                : 
                               1700                 :                :     /* Should only be applied to base relations that are values lists */
 7298 mail@joeconway.com       1701         [ -  + ]:           6996 :     Assert(baserel->relid > 0);
                               1702         [ -  + ]:           6996 :     Assert(baserel->rtekind == RTE_VALUES);
                               1703                 :                : 
                               1704                 :                :     /* Mark the path with the correct row estimate */
 5096 tgl@sss.pgh.pa.us        1705         [ +  + ]:           6996 :     if (param_info)
                               1706                 :             55 :         path->rows = param_info->ppi_rows;
                               1707                 :                :     else
                               1708                 :           6941 :         path->rows = baserel->rows;
                               1709                 :                : 
                               1710                 :                :     /*
                               1711                 :                :      * For now, estimate list evaluation cost at one operator eval per list
                               1712                 :                :      * (probably pretty bogus, but is it worth being smarter?)
                               1713                 :                :      */
 7298 mail@joeconway.com       1714                 :           6996 :     cpu_per_tuple = cpu_operator_cost;
                               1715                 :                : 
                               1716                 :                :     /* Add scanning CPU costs */
 5096 tgl@sss.pgh.pa.us        1717                 :           6996 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1718                 :                : 
                               1719                 :           6996 :     startup_cost += qpqual_cost.startup;
                               1720                 :           6996 :     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
 7298 mail@joeconway.com       1721                 :           6996 :     run_cost += cpu_per_tuple * baserel->tuples;
                               1722                 :                : 
                               1723                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811 tgl@sss.pgh.pa.us        1724                 :           6996 :     startup_cost += path->pathtarget->cost.startup;
                               1725                 :           6996 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1726                 :                : 
  179 rhaas@postgresql.org     1727         [ +  - ]:           6996 :     if (path->parallel_workers == 0)
                               1728                 :           6996 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1729                 :           6996 :     path->disabled_nodes =
                               1730                 :           6996 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 7298 mail@joeconway.com       1731                 :           6996 :     path->startup_cost = startup_cost;
                               1732                 :           6996 :     path->total_cost = startup_cost + run_cost;
                               1733                 :           6996 : }
                               1734                 :                : 
                               1735                 :                : /*
                               1736                 :                :  * cost_ctescan
                               1737                 :                :  *    Determines and returns the cost of scanning a CTE RTE.
                               1738                 :                :  *
                               1739                 :                :  * Note: this is used for both self-reference and regular CTEs; the
                               1740                 :                :  * possible cost differences are below the threshold of what we could
                               1741                 :                :  * estimate accurately anyway.  Note that the costs of evaluating the
                               1742                 :                :  * referenced CTE query are added into the final plan as initplan costs,
                               1743                 :                :  * and should NOT be counted here.
                               1744                 :                :  */
                               1745                 :                : void
 5082 tgl@sss.pgh.pa.us        1746                 :           3518 : cost_ctescan(Path *path, PlannerInfo *root,
                               1747                 :                :              RelOptInfo *baserel, ParamPathInfo *param_info)
                               1748                 :                : {
 6504                          1749                 :           3518 :     Cost        startup_cost = 0;
                               1750                 :           3518 :     Cost        run_cost = 0;
                               1751                 :                :     QualCost    qpqual_cost;
                               1752                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org     1753                 :           3518 :     uint64      enable_mask = 0;
                               1754                 :                : 
                               1755                 :                :     /* Should only be applied to base relations that are CTEs */
 6504 tgl@sss.pgh.pa.us        1756         [ -  + ]:           3518 :     Assert(baserel->relid > 0);
                               1757         [ -  + ]:           3518 :     Assert(baserel->rtekind == RTE_CTE);
                               1758                 :                : 
                               1759                 :                :     /* Mark the path with the correct row estimate */
 5082                          1760         [ -  + ]:           3518 :     if (param_info)
 5082 tgl@sss.pgh.pa.us        1761                 :UBC           0 :         path->rows = param_info->ppi_rows;
                               1762                 :                :     else
 5082 tgl@sss.pgh.pa.us        1763                 :CBC        3518 :         path->rows = baserel->rows;
                               1764                 :                : 
                               1765                 :                :     /* Charge one CPU tuple cost per row for tuplestore manipulation */
 6504                          1766                 :           3518 :     cpu_per_tuple = cpu_tuple_cost;
                               1767                 :                : 
                               1768                 :                :     /* Add scanning CPU costs */
 5082                          1769                 :           3518 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1770                 :                : 
                               1771                 :           3518 :     startup_cost += qpqual_cost.startup;
                               1772                 :           3518 :     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
 6504                          1773                 :           3518 :     run_cost += cpu_per_tuple * baserel->tuples;
                               1774                 :                : 
                               1775                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811                          1776                 :           3518 :     startup_cost += path->pathtarget->cost.startup;
                               1777                 :           3518 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
                               1778                 :                : 
  179 rhaas@postgresql.org     1779         [ +  - ]:           3518 :     if (path->parallel_workers == 0)
                               1780                 :           3518 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1781                 :           3518 :     path->disabled_nodes =
                               1782                 :           3518 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 6504 tgl@sss.pgh.pa.us        1783                 :           3518 :     path->startup_cost = startup_cost;
                               1784                 :           3518 :     path->total_cost = startup_cost + run_cost;
                               1785                 :           3518 : }
                               1786                 :                : 
                               1787                 :                : /*
                               1788                 :                :  * cost_namedtuplestorescan
                               1789                 :                :  *    Determines and returns the cost of scanning a named tuplestore.
                               1790                 :                :  */
                               1791                 :                : void
 3404 kgrittn@postgresql.o     1792                 :            437 : cost_namedtuplestorescan(Path *path, PlannerInfo *root,
                               1793                 :                :                          RelOptInfo *baserel, ParamPathInfo *param_info)
                               1794                 :                : {
                               1795                 :            437 :     Cost        startup_cost = 0;
                               1796                 :            437 :     Cost        run_cost = 0;
                               1797                 :                :     QualCost    qpqual_cost;
                               1798                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org     1799                 :            437 :     uint64      enable_mask = 0;
                               1800                 :                : 
                               1801                 :                :     /* Should only be applied to base relations that are Tuplestores */
 3404 kgrittn@postgresql.o     1802         [ -  + ]:            437 :     Assert(baserel->relid > 0);
                               1803         [ -  + ]:            437 :     Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
                               1804                 :                : 
                               1805                 :                :     /* Mark the path with the correct row estimate */
                               1806         [ -  + ]:            437 :     if (param_info)
 3404 kgrittn@postgresql.o     1807                 :UBC           0 :         path->rows = param_info->ppi_rows;
                               1808                 :                :     else
 3404 kgrittn@postgresql.o     1809                 :CBC         437 :         path->rows = baserel->rows;
                               1810                 :                : 
                               1811                 :                :     /* Charge one CPU tuple cost per row for tuplestore manipulation */
                               1812                 :            437 :     cpu_per_tuple = cpu_tuple_cost;
                               1813                 :                : 
                               1814                 :                :     /* Add scanning CPU costs */
                               1815                 :            437 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1816                 :                : 
                               1817                 :            437 :     startup_cost += qpqual_cost.startup;
                               1818                 :            437 :     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
                               1819                 :            437 :     run_cost += cpu_per_tuple * baserel->tuples;
                               1820                 :                : 
  179 rhaas@postgresql.org     1821         [ +  - ]:            437 :     if (path->parallel_workers == 0)
                               1822                 :            437 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1823                 :            437 :     path->disabled_nodes =
                               1824                 :            437 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 3404 kgrittn@postgresql.o     1825                 :            437 :     path->startup_cost = startup_cost;
                               1826                 :            437 :     path->total_cost = startup_cost + run_cost;
                               1827                 :            437 : }
                               1828                 :                : 
                               1829                 :                : /*
                               1830                 :                :  * cost_resultscan
                               1831                 :                :  *    Determines and returns the cost of scanning an RTE_RESULT relation.
                               1832                 :                :  */
                               1833                 :                : void
 2736 tgl@sss.pgh.pa.us        1834                 :           3701 : cost_resultscan(Path *path, PlannerInfo *root,
                               1835                 :                :                 RelOptInfo *baserel, ParamPathInfo *param_info)
                               1836                 :                : {
                               1837                 :           3701 :     Cost        startup_cost = 0;
                               1838                 :           3701 :     Cost        run_cost = 0;
                               1839                 :                :     QualCost    qpqual_cost;
                               1840                 :                :     Cost        cpu_per_tuple;
  179 rhaas@postgresql.org     1841                 :           3701 :     uint64      enable_mask = 0;
                               1842                 :                : 
                               1843                 :                :     /* Should only be applied to RTE_RESULT base relations */
 2736 tgl@sss.pgh.pa.us        1844         [ -  + ]:           3701 :     Assert(baserel->relid > 0);
                               1845         [ -  + ]:           3701 :     Assert(baserel->rtekind == RTE_RESULT);
                               1846                 :                : 
                               1847                 :                :     /* Mark the path with the correct row estimate */
                               1848         [ +  + ]:           3701 :     if (param_info)
                               1849                 :            165 :         path->rows = param_info->ppi_rows;
                               1850                 :                :     else
                               1851                 :           3536 :         path->rows = baserel->rows;
                               1852                 :                : 
                               1853                 :                :     /* We charge qual cost plus cpu_tuple_cost */
                               1854                 :           3701 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
                               1855                 :                : 
                               1856                 :           3701 :     startup_cost += qpqual_cost.startup;
                               1857                 :           3701 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
                               1858                 :           3701 :     run_cost += cpu_per_tuple * baserel->tuples;
                               1859                 :                : 
  179 rhaas@postgresql.org     1860         [ +  - ]:           3701 :     if (path->parallel_workers == 0)
                               1861                 :           3701 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1862                 :           3701 :     path->disabled_nodes =
                               1863                 :           3701 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 2736 tgl@sss.pgh.pa.us        1864                 :           3701 :     path->startup_cost = startup_cost;
                               1865                 :           3701 :     path->total_cost = startup_cost + run_cost;
                               1866                 :           3701 : }
                               1867                 :                : 
                               1868                 :                : /*
                               1869                 :                :  * cost_recursive_union
                               1870                 :                :  *    Determines and returns the cost of performing a recursive union,
                               1871                 :                :  *    and also the estimated output size.
                               1872                 :                :  *
                               1873                 :                :  * We are given Paths for the nonrecursive and recursive terms.
                               1874                 :                :  */
                               1875                 :                : void
 3793                          1876                 :            633 : cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
                               1877                 :                : {
                               1878                 :                :     Cost        startup_cost;
                               1879                 :                :     Cost        total_cost;
                               1880                 :                :     double      total_rows;
  179 rhaas@postgresql.org     1881                 :            633 :     uint64      enable_mask = 0;
                               1882                 :                : 
                               1883                 :                :     /* We probably have decent estimates for the non-recursive term */
 6504 tgl@sss.pgh.pa.us        1884                 :            633 :     startup_cost = nrterm->startup_cost;
                               1885                 :            633 :     total_cost = nrterm->total_cost;
 3793                          1886                 :            633 :     total_rows = nrterm->rows;
                               1887                 :                : 
                               1888                 :                :     /*
                               1889                 :                :      * We arbitrarily assume that about 10 recursive iterations will be
                               1890                 :                :      * needed, and that we've managed to get a good fix on the cost and output
                               1891                 :                :      * size of each one of them.  These are mighty shaky assumptions but it's
                               1892                 :                :      * hard to see how to do better.
                               1893                 :                :      */
 6504                          1894                 :            633 :     total_cost += 10 * rterm->total_cost;
 3793                          1895                 :            633 :     total_rows += 10 * rterm->rows;
                               1896                 :                : 
                               1897                 :                :     /*
                               1898                 :                :      * Also charge cpu_tuple_cost per row to account for the costs of
                               1899                 :                :      * manipulating the tuplestores.  (We don't worry about possible
                               1900                 :                :      * spill-to-disk costs.)
                               1901                 :                :      */
 6504                          1902                 :            633 :     total_cost += cpu_tuple_cost * total_rows;
                               1903                 :                : 
  179 rhaas@postgresql.org     1904         [ +  - ]:            633 :     if (runion->parallel_workers == 0)
                               1905                 :            633 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               1906                 :            633 :     runion->disabled_nodes =
                               1907                 :            633 :         (runion->parent->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 6504 tgl@sss.pgh.pa.us        1908                 :            633 :     runion->startup_cost = startup_cost;
                               1909                 :            633 :     runion->total_cost = total_cost;
 3793                          1910                 :            633 :     runion->rows = total_rows;
                               1911                 :            633 :     runion->pathtarget->width = Max(nrterm->pathtarget->width,
                               1912                 :                :                                     rterm->pathtarget->width);
 6504                          1913                 :            633 : }
                               1914                 :                : 
                               1915                 :                : /*
                               1916                 :                :  * cost_tuplesort
                               1917                 :                :  *    Determines and returns the cost of sorting a relation using tuplesort,
                               1918                 :                :  *    not including the cost of reading the input data.
                               1919                 :                :  *
                               1920                 :                :  * If the total volume of data to sort is less than sort_mem, we will do
                               1921                 :                :  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
                               1922                 :                :  * comparisons for t tuples.
                               1923                 :                :  *
                               1924                 :                :  * If the total volume exceeds sort_mem, we switch to a tape-style merge
                               1925                 :                :  * algorithm.  There will still be about t*log2(t) tuple comparisons in
                               1926                 :                :  * total, but we will also need to write and read each tuple once per
                               1927                 :                :  * merge pass.  We expect about ceil(logM(r)) merge passes where r is the
                               1928                 :                :  * number of initial runs formed and M is the merge order used by tuplesort.c.
                               1929                 :                :  * Since the average initial run should be about sort_mem, we have
                               1930                 :                :  *      disk traffic = 2 * relsize * ceil(logM(p / sort_mem))
                               1931                 :                :  *      cpu = comparison_cost * t * log2(t)
                               1932                 :                :  *
                               1933                 :                :  * If the sort is bounded (i.e., only the first k result tuples are needed)
                               1934                 :                :  * and k tuples can fit into sort_mem, we use a heap method that keeps only
                               1935                 :                :  * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
                               1936                 :                :  *
                               1937                 :                :  * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
                               1938                 :                :  * accesses (XXX can't we refine that guess?)
                               1939                 :                :  *
                               1940                 :                :  * By default, we charge two operator evals per tuple comparison, which should
                               1941                 :                :  * be in the right ballpark in most cases.  The caller can tweak this by
                               1942                 :                :  * specifying nonzero comparison_cost; typically that's used for any extra
                               1943                 :                :  * work that has to be done to prepare the inputs to the comparison operators.
                               1944                 :                :  *
                               1945                 :                :  * 'tuples' is the number of tuples in the relation
                               1946                 :                :  * 'width' is the average tuple width in bytes
                               1947                 :                :  * 'comparison_cost' is the extra cost per comparison, if any
                               1948                 :                :  * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
                               1949                 :                :  * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
                               1950                 :                :  */
                               1951                 :                : static void
 1392                          1952                 :        1555520 : cost_tuplesort(Cost *startup_cost, Cost *run_cost,
                               1953                 :                :                double tuples, int width,
                               1954                 :                :                Cost comparison_cost, int sort_mem,
                               1955                 :                :                double limit_tuples)
                               1956                 :                : {
 7023                          1957                 :        1555520 :     double      input_bytes = relation_byte_size(tuples, width);
                               1958                 :                :     double      output_bytes;
                               1959                 :                :     double      output_tuples;
  541                          1960                 :        1555520 :     int64       sort_mem_bytes = sort_mem * (int64) 1024;
                               1961                 :                : 
                               1962                 :                :     /*
                               1963                 :                :      * We want to be sure the cost of a sort is never estimated as zero, even
                               1964                 :                :      * if passed-in tuple count is zero.  Besides, mustn't do log(0)...
                               1965                 :                :      */
 9695                          1966         [ +  + ]:        1555520 :     if (tuples < 2.0)
                               1967                 :         434342 :         tuples = 2.0;
                               1968                 :                : 
                               1969                 :                :     /* Include the default cost-per-comparison */
 1392                          1970                 :        1555520 :     comparison_cost += 2.0 * cpu_operator_cost;
                               1971                 :                : 
                               1972                 :                :     /* Do we have a useful LIMIT? */
 7023                          1973   [ +  +  +  + ]:        1555520 :     if (limit_tuples > 0 && limit_tuples < tuples)
                               1974                 :                :     {
                               1975                 :           1324 :         output_tuples = limit_tuples;
                               1976                 :           1324 :         output_bytes = relation_byte_size(output_tuples, width);
                               1977                 :                :     }
                               1978                 :                :     else
                               1979                 :                :     {
                               1980                 :        1554196 :         output_tuples = tuples;
                               1981                 :        1554196 :         output_bytes = input_bytes;
                               1982                 :                :     }
                               1983                 :                : 
 5771                          1984         [ +  + ]:        1555520 :     if (output_bytes > sort_mem_bytes)
                               1985                 :                :     {
                               1986                 :                :         /*
                               1987                 :                :          * We'll have to use a disk-based sort of all the tuples
                               1988                 :                :          */
 7023                          1989                 :          10576 :         double      npages = ceil(input_bytes / BLCKSZ);
 3761 rhaas@postgresql.org     1990                 :          10576 :         double      nruns = input_bytes / sort_mem_bytes;
 5771 tgl@sss.pgh.pa.us        1991                 :          10576 :         double      mergeorder = tuplesort_merge_order(sort_mem_bytes);
                               1992                 :                :         double      log_runs;
                               1993                 :                :         double      npageaccesses;
                               1994                 :                : 
                               1995                 :                :         /*
                               1996                 :                :          * CPU costs
                               1997                 :                :          *
                               1998                 :                :          * Assume about N log2 N comparisons
                               1999                 :                :          */
 1392                          2000                 :          10576 :         *startup_cost = comparison_cost * tuples * LOG2(tuples);
                               2001                 :                : 
                               2002                 :                :         /* Disk costs */
                               2003                 :                : 
                               2004                 :                :         /* Compute logM(r) as log(r) / log(M) */
 7462                          2005         [ +  + ]:          10576 :         if (nruns > mergeorder)
                               2006                 :           3269 :             log_runs = ceil(log(nruns) / log(mergeorder));
                               2007                 :                :         else
 9695                          2008                 :           7307 :             log_runs = 1.0;
 9658                          2009                 :          10576 :         npageaccesses = 2.0 * npages * log_runs;
                               2010                 :                :         /* Assume 3/4ths of accesses are sequential, 1/4th are not */
 2302 tomas.vondra@postgre     2011                 :          10576 :         *startup_cost += npageaccesses *
 7356 tgl@sss.pgh.pa.us        2012                 :          10576 :             (seq_page_cost * 0.75 + random_page_cost * 0.25);
                               2013                 :                :     }
 5771                          2014   [ +  +  -  + ]:        1544944 :     else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
                               2015                 :                :     {
                               2016                 :                :         /*
                               2017                 :                :          * We'll use a bounded heap-sort keeping just K tuples in memory, for
                               2018                 :                :          * a total number of tuple comparisons of N log2 K; but the constant
                               2019                 :                :          * factor is a bit higher than for quicksort.  Tweak it so that the
                               2020                 :                :          * cost curve is continuous at the crossover point.
                               2021                 :                :          */
 1392                          2022                 :            898 :         *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
                               2023                 :                :     }
                               2024                 :                :     else
                               2025                 :                :     {
                               2026                 :                :         /* We'll use plain quicksort on all the input tuples */
                               2027                 :        1544046 :         *startup_cost = comparison_cost * tuples * LOG2(tuples);
                               2028                 :                :     }
                               2029                 :                : 
                               2030                 :                :     /*
                               2031                 :                :      * Also charge a small amount (arbitrarily set equal to operator cost) per
                               2032                 :                :      * extracted tuple.  We don't charge cpu_tuple_cost because a Sort node
                               2033                 :                :      * doesn't do qual-checking or projection, so it has less overhead than
                               2034                 :                :      * most plan nodes.  Note it's correct to use tuples not output_tuples
                               2035                 :                :      * here --- the upper LIMIT will pro-rate the run cost so we'd be double
                               2036                 :                :      * counting the LIMIT otherwise.
                               2037                 :                :      */
 2302 tomas.vondra@postgre     2038                 :        1555520 :     *run_cost = cpu_operator_cost * tuples;
                               2039                 :        1555520 : }
                               2040                 :                : 
                               2041                 :                : /*
                               2042                 :                :  * cost_incremental_sort
                               2043                 :                :  *  Determines and returns the cost of sorting a relation incrementally, when
                               2044                 :                :  *  the input path is presorted by a prefix of the pathkeys.
                               2045                 :                :  *
                               2046                 :                :  * 'presorted_keys' is the number of leading pathkeys by which the input path
                               2047                 :                :  * is sorted.
                               2048                 :                :  *
                               2049                 :                :  * We estimate the number of groups into which the relation is divided by the
                               2050                 :                :  * leading pathkeys, and then calculate the cost of sorting a single group
                               2051                 :                :  * with tuplesort using cost_tuplesort().
                               2052                 :                :  */
                               2053                 :                : void
                               2054                 :           9713 : cost_incremental_sort(Path *path,
                               2055                 :                :                       PlannerInfo *root, List *pathkeys, int presorted_keys,
                               2056                 :                :                       int input_disabled_nodes,
                               2057                 :                :                       Cost input_startup_cost, Cost input_total_cost,
                               2058                 :                :                       double input_tuples, int width, Cost comparison_cost, int sort_mem,
                               2059                 :                :                       double limit_tuples)
                               2060                 :                : {
                               2061                 :                :     Cost        startup_cost,
                               2062                 :                :                 run_cost,
                               2063                 :           9713 :                 input_run_cost = input_total_cost - input_startup_cost;
                               2064                 :                :     double      group_tuples,
                               2065                 :                :                 input_groups;
                               2066                 :                :     Cost        group_startup_cost,
                               2067                 :                :                 group_run_cost,
                               2068                 :                :                 group_input_run_cost;
                               2069                 :           9713 :     List       *presortedExprs = NIL;
                               2070                 :                :     ListCell   *l;
 2285                          2071                 :           9713 :     bool        unknown_varno = false;
                               2072                 :                : 
 1318 drowley@postgresql.o     2073   [ +  -  -  + ]:           9713 :     Assert(presorted_keys > 0 && presorted_keys < list_length(pathkeys));
                               2074                 :                : 
                               2075                 :                :     /*
                               2076                 :                :      * We want to be sure the cost of a sort is never estimated as zero, even
                               2077                 :                :      * if passed-in tuple count is zero.  Besides, mustn't do log(0)...
                               2078                 :                :      */
 2302 tomas.vondra@postgre     2079         [ +  + ]:           9713 :     if (input_tuples < 2.0)
                               2080                 :           4992 :         input_tuples = 2.0;
                               2081                 :                : 
                               2082                 :                :     /* Default estimate of number of groups, capped to one group per row. */
 2285                          2083         [ +  + ]:           9713 :     input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
                               2084                 :                : 
                               2085                 :                :     /*
                               2086                 :                :      * Extract presorted keys as list of expressions.
                               2087                 :                :      *
                               2088                 :                :      * We need to be careful about Vars containing "varno 0" which might have
                               2089                 :                :      * been introduced by generate_append_tlist, which would confuse
                               2090                 :                :      * estimate_num_groups (in fact it'd fail for such expressions). See
                               2091                 :                :      * recurse_set_operations which has to deal with the same issue.
                               2092                 :                :      *
                               2093                 :                :      * Unlike recurse_set_operations we can't access the original target list
                               2094                 :                :      * here, and even if we could it's not very clear how useful would that be
                               2095                 :                :      * for a set operation combining multiple tables. So we simply detect if
                               2096                 :                :      * there are any expressions with "varno 0" and use the default
                               2097                 :                :      * DEFAULT_NUM_DISTINCT in that case.
                               2098                 :                :      *
                               2099                 :                :      * We might also use either 1.0 (a single group) or input_tuples (each row
                               2100                 :                :      * being a separate group), pretty much the worst and best case for
                               2101                 :                :      * incremental sort. But those are extreme cases and using something in
                               2102                 :                :      * between seems reasonable. Furthermore, generate_append_tlist is used
                               2103                 :                :      * for set operations, which are likely to produce mostly unique output
                               2104                 :                :      * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
                               2105                 :                :      * while maintaining lower startup cost.
                               2106                 :                :      */
 2302                          2107   [ +  -  +  -  :          10068 :     foreach(l, pathkeys)
                                              +  - ]
                               2108                 :                :     {
                               2109                 :          10068 :         PathKey    *key = (PathKey *) lfirst(l);
                               2110                 :          10068 :         EquivalenceMember *member = (EquivalenceMember *)
 1164 tgl@sss.pgh.pa.us        2111                 :          10068 :             linitial(key->pk_eclass->ec_members);
                               2112                 :                : 
                               2113                 :                :         /*
                               2114                 :                :          * Check if the expression contains Var with "varno 0" so that we
                               2115                 :                :          * don't call estimate_num_groups in that case.
                               2116                 :                :          */
 2012                          2117         [ +  + ]:          10068 :         if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
                               2118                 :                :         {
 2285 tomas.vondra@postgre     2119                 :              7 :             unknown_varno = true;
                               2120                 :              7 :             break;
                               2121                 :                :         }
                               2122                 :                : 
                               2123                 :                :         /* expression not containing any Vars with "varno 0" */
 2302                          2124                 :          10061 :         presortedExprs = lappend(presortedExprs, member->em_expr);
                               2125                 :                : 
 1318 drowley@postgresql.o     2126         [ +  + ]:          10061 :         if (foreach_current_index(l) + 1 >= presorted_keys)
 2302 tomas.vondra@postgre     2127                 :           9706 :             break;
                               2128                 :                :     }
                               2129                 :                : 
                               2130                 :                :     /* Estimate the number of groups with equal presorted keys. */
 2285                          2131         [ +  + ]:           9713 :     if (!unknown_varno)
 1944 drowley@postgresql.o     2132                 :           9706 :         input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
                               2133                 :                :                                            NULL, NULL);
                               2134                 :                : 
 2302 tomas.vondra@postgre     2135                 :           9713 :     group_tuples = input_tuples / input_groups;
                               2136                 :           9713 :     group_input_run_cost = input_run_cost / input_groups;
                               2137                 :                : 
                               2138                 :                :     /*
                               2139                 :                :      * Estimate the average cost of sorting of one group where presorted keys
                               2140                 :                :      * are equal.
                               2141                 :                :      */
 1392 tgl@sss.pgh.pa.us        2142                 :           9713 :     cost_tuplesort(&group_startup_cost, &group_run_cost,
                               2143                 :                :                    group_tuples, width, comparison_cost, sort_mem,
                               2144                 :                :                    limit_tuples);
                               2145                 :                : 
                               2146                 :                :     /*
                               2147                 :                :      * Startup cost of incremental sort is the startup cost of its first group
                               2148                 :                :      * plus the cost of its input.
                               2149                 :                :      */
 1318 drowley@postgresql.o     2150                 :           9713 :     startup_cost = group_startup_cost + input_startup_cost +
                               2151                 :                :         group_input_run_cost;
                               2152                 :                : 
                               2153                 :                :     /*
                               2154                 :                :      * After we started producing tuples from the first group, the cost of
                               2155                 :                :      * producing all the tuples is given by the cost to finish processing this
                               2156                 :                :      * group, plus the total cost to process the remaining groups, plus the
                               2157                 :                :      * remaining cost of input.
                               2158                 :                :      */
                               2159                 :           9713 :     run_cost = group_run_cost + (group_run_cost + group_startup_cost) *
                               2160                 :           9713 :         (input_groups - 1) + group_input_run_cost * (input_groups - 1);
                               2161                 :                : 
                               2162                 :                :     /*
                               2163                 :                :      * Incremental sort adds some overhead by itself. Firstly, it has to
                               2164                 :                :      * detect the sort groups. This is roughly equal to one extra copy and
                               2165                 :                :      * comparison per tuple.
                               2166                 :                :      */
 2302 tomas.vondra@postgre     2167                 :           9713 :     run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
                               2168                 :                : 
                               2169                 :                :     /*
                               2170                 :                :      * Additionally, we charge double cpu_tuple_cost for each input group to
                               2171                 :                :      * account for the tuplesort_reset that's performed after each group.
                               2172                 :                :      */
                               2173                 :           9713 :     run_cost += 2.0 * cpu_tuple_cost * input_groups;
                               2174                 :                : 
                               2175                 :           9713 :     path->rows = input_tuples;
                               2176                 :                : 
                               2177                 :                :     /*
                               2178                 :                :      * We should not generate these paths when enable_incremental_sort=false.
                               2179                 :                :      * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
                               2180                 :                :      * it will have already affected the input path.
                               2181                 :                :      */
  704 rhaas@postgresql.org     2182         [ -  + ]:           9713 :     Assert(enable_incremental_sort);
                               2183                 :           9713 :     path->disabled_nodes = input_disabled_nodes;
                               2184                 :                : 
 2302 tomas.vondra@postgre     2185                 :           9713 :     path->startup_cost = startup_cost;
                               2186                 :           9713 :     path->total_cost = startup_cost + run_cost;
                               2187                 :           9713 : }
                               2188                 :                : 
                               2189                 :                : /*
                               2190                 :                :  * cost_sort
                               2191                 :                :  *    Determines and returns the cost of sorting a relation, including
                               2192                 :                :  *    the cost of reading the input data.
                               2193                 :                :  *
                               2194                 :                :  * NOTE: some callers currently pass NIL for pathkeys because they
                               2195                 :                :  * can't conveniently supply the sort keys.  Since this routine doesn't
                               2196                 :                :  * currently do anything with pathkeys anyway, that doesn't matter...
                               2197                 :                :  * but if it ever does, it should react gracefully to lack of key data.
                               2198                 :                :  * (Actually, the thing we'd most likely be interested in is just the number
                               2199                 :                :  * of sort keys, which all callers *could* supply.)
                               2200                 :                :  */
                               2201                 :                : void
                               2202                 :        1545807 : cost_sort(Path *path, PlannerInfo *root,
                               2203                 :                :           List *pathkeys, int input_disabled_nodes,
                               2204                 :                :           Cost input_cost, double tuples, int width,
                               2205                 :                :           Cost comparison_cost, int sort_mem,
                               2206                 :                :           double limit_tuples)
                               2207                 :                : 
                               2208                 :                : {
                               2209                 :                :     Cost        startup_cost;
                               2210                 :                :     Cost        run_cost;
                               2211                 :                : 
 1392 tgl@sss.pgh.pa.us        2212                 :        1545807 :     cost_tuplesort(&startup_cost, &run_cost,
                               2213                 :                :                    tuples, width,
                               2214                 :                :                    comparison_cost, sort_mem,
                               2215                 :                :                    limit_tuples);
                               2216                 :                : 
 2302 tomas.vondra@postgre     2217                 :        1545807 :     startup_cost += input_cost;
                               2218                 :                : 
                               2219                 :                :     /*
                               2220                 :                :      * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
                               2221                 :                :      * it will have already affected the input path.
                               2222                 :                :      */
                               2223                 :        1545807 :     path->rows = tuples;
  704 rhaas@postgresql.org     2224                 :        1545807 :     path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
 9658 tgl@sss.pgh.pa.us        2225                 :        1545807 :     path->startup_cost = startup_cost;
                               2226                 :        1545807 :     path->total_cost = startup_cost + run_cost;
10974 scrappy@hub.org          2227                 :        1545807 : }
                               2228                 :                : 
                               2229                 :                : /*
                               2230                 :                :  * append_nonpartial_cost
                               2231                 :                :  *    Estimate the cost of the non-partial paths in a Parallel Append.
                               2232                 :                :  *    The non-partial paths are assumed to be the first "numpaths" paths
                               2233                 :                :  *    from the subpaths list, and to be in order of decreasing cost.
                               2234                 :                :  */
                               2235                 :                : static Cost
 3155 rhaas@postgresql.org     2236                 :          21761 : append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
                               2237                 :                : {
                               2238                 :                :     Cost       *costarr;
                               2239                 :                :     int         arrlen;
                               2240                 :                :     ListCell   *l;
                               2241                 :                :     ListCell   *cell;
                               2242                 :                :     int         path_index;
                               2243                 :                :     int         min_index;
                               2244                 :                :     int         max_index;
                               2245                 :                : 
                               2246         [ +  + ]:          21761 :     if (numpaths == 0)
                               2247                 :          17543 :         return 0;
                               2248                 :                : 
                               2249                 :                :     /*
                               2250                 :                :      * Array length is number of workers or number of relevant paths,
                               2251                 :                :      * whichever is less.
                               2252                 :                :      */
                               2253                 :           4218 :     arrlen = Min(parallel_workers, numpaths);
  228 michael@paquier.xyz      2254                 :           4218 :     costarr = palloc_array(Cost, arrlen);
                               2255                 :                : 
                               2256                 :                :     /* The first few paths will each be claimed by a different worker. */
 3155 rhaas@postgresql.org     2257                 :           4218 :     path_index = 0;
                               2258   [ +  -  +  +  :          12235 :     foreach(cell, subpaths)
                                              +  + ]
                               2259                 :                :     {
                               2260                 :           9141 :         Path       *subpath = (Path *) lfirst(cell);
                               2261                 :                : 
                               2262         [ +  + ]:           9141 :         if (path_index == arrlen)
                               2263                 :           1124 :             break;
                               2264                 :           8017 :         costarr[path_index++] = subpath->total_cost;
                               2265                 :                :     }
                               2266                 :                : 
                               2267                 :                :     /*
                               2268                 :                :      * Since subpaths are sorted by decreasing cost, the last one will have
                               2269                 :                :      * the minimum cost.
                               2270                 :                :      */
                               2271                 :           4218 :     min_index = arrlen - 1;
                               2272                 :                : 
                               2273                 :                :     /*
                               2274                 :                :      * For each of the remaining subpaths, add its cost to the array element
                               2275                 :                :      * with minimum cost.
                               2276                 :                :      */
 2568 tgl@sss.pgh.pa.us        2277   [ +  -  +  +  :           7213 :     for_each_cell(l, subpaths, cell)
                                              +  + ]
                               2278                 :                :     {
 3155 rhaas@postgresql.org     2279                 :           3470 :         Path       *subpath = (Path *) lfirst(l);
                               2280                 :                : 
                               2281                 :                :         /* Consider only the non-partial paths */
                               2282         [ +  + ]:           3470 :         if (path_index++ == numpaths)
                               2283                 :            475 :             break;
                               2284                 :                : 
                               2285                 :           2995 :         costarr[min_index] += subpath->total_cost;
                               2286                 :                : 
                               2287                 :                :         /* Update the new min cost array index */
 1432 drowley@postgresql.o     2288                 :           2995 :         min_index = 0;
                               2289         [ +  + ]:           9015 :         for (int i = 0; i < arrlen; i++)
                               2290                 :                :         {
 3155 rhaas@postgresql.org     2291         [ +  + ]:           6020 :             if (costarr[i] < costarr[min_index])
                               2292                 :           1041 :                 min_index = i;
                               2293                 :                :         }
                               2294                 :                :     }
                               2295                 :                : 
                               2296                 :                :     /* Return the highest cost from the array */
 1432 drowley@postgresql.o     2297                 :           4218 :     max_index = 0;
                               2298         [ +  + ]:          12235 :     for (int i = 0; i < arrlen; i++)
                               2299                 :                :     {
 3155 rhaas@postgresql.org     2300         [ +  + ]:           8017 :         if (costarr[i] > costarr[max_index])
                               2301                 :            391 :             max_index = i;
                               2302                 :                :     }
                               2303                 :                : 
                               2304                 :           4218 :     return costarr[max_index];
                               2305                 :                : }
                               2306                 :                : 
                               2307                 :                : /*
                               2308                 :                :  * cost_append
                               2309                 :                :  *    Determines and returns the cost of an Append node.
                               2310                 :                :  */
                               2311                 :                : void
  383 rguo@postgresql.org      2312                 :          58917 : cost_append(AppendPath *apath, PlannerInfo *root)
                               2313                 :                : {
  179 rhaas@postgresql.org     2314                 :          58917 :     RelOptInfo *rel = apath->path.parent;
                               2315                 :                :     ListCell   *l;
                               2316                 :          58917 :     uint64      enable_mask = PGS_APPEND;
                               2317                 :                : 
                               2318         [ +  + ]:          58917 :     if (apath->path.parallel_workers == 0)
                               2319                 :          37116 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               2320                 :                : 
                               2321                 :          58917 :     apath->path.disabled_nodes =
                               2322                 :          58917 :         (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 3155                          2323                 :          58917 :     apath->path.startup_cost = 0;
                               2324                 :          58917 :     apath->path.total_cost = 0;
 2669 tgl@sss.pgh.pa.us        2325                 :          58917 :     apath->path.rows = 0;
                               2326                 :                : 
 3155 rhaas@postgresql.org     2327         [ +  + ]:          58917 :     if (apath->subpaths == NIL)
                               2328                 :           1795 :         return;
                               2329                 :                : 
                               2330         [ +  + ]:          57122 :     if (!apath->path.parallel_aware)
                               2331                 :                :     {
 2669 tgl@sss.pgh.pa.us        2332                 :          35361 :         List       *pathkeys = apath->path.pathkeys;
                               2333                 :                : 
                               2334         [ +  + ]:          35361 :         if (pathkeys == NIL)
                               2335                 :                :         {
 1390 drowley@postgresql.o     2336                 :          33552 :             Path       *firstsubpath = (Path *) linitial(apath->subpaths);
                               2337                 :                : 
                               2338                 :                :             /*
                               2339                 :                :              * For an unordered, non-parallel-aware Append we take the startup
                               2340                 :                :              * cost as the startup cost of the first subpath.
                               2341                 :                :              */
                               2342                 :          33552 :             apath->path.startup_cost = firstsubpath->startup_cost;
                               2343                 :                : 
                               2344                 :                :             /*
                               2345                 :                :              * Compute rows, number of disabled nodes, and total cost as sums
                               2346                 :                :              * of underlying subplan values.
                               2347                 :                :              */
 2669 tgl@sss.pgh.pa.us        2348   [ +  -  +  +  :         131685 :             foreach(l, apath->subpaths)
                                              +  + ]
                               2349                 :                :             {
                               2350                 :          98133 :                 Path       *subpath = (Path *) lfirst(l);
                               2351                 :                : 
                               2352                 :          98133 :                 apath->path.rows += subpath->rows;
  704 rhaas@postgresql.org     2353                 :          98133 :                 apath->path.disabled_nodes += subpath->disabled_nodes;
 2669 tgl@sss.pgh.pa.us        2354                 :          98133 :                 apath->path.total_cost += subpath->total_cost;
                               2355                 :                :             }
                               2356                 :                :         }
                               2357                 :                :         else
                               2358                 :                :         {
                               2359                 :                :             /*
                               2360                 :                :              * For an ordered, non-parallel-aware Append we take the startup
                               2361                 :                :              * cost as the sum of the subpath startup costs.  This ensures
                               2362                 :                :              * that we don't underestimate the startup cost when a query's
                               2363                 :                :              * LIMIT is such that several of the children have to be run to
                               2364                 :                :              * satisfy it.  This might be overkill --- another plausible hack
                               2365                 :                :              * would be to take the Append's startup cost as the maximum of
                               2366                 :                :              * the child startup costs.  But we don't want to risk believing
                               2367                 :                :              * that an ORDER BY LIMIT query can be satisfied at small cost
                               2368                 :                :              * when the first child has small startup cost but later ones
                               2369                 :                :              * don't.  (If we had the ability to deal with nonlinear cost
                               2370                 :                :              * interpolation for partial retrievals, we would not need to be
                               2371                 :                :              * so conservative about this.)
                               2372                 :                :              *
                               2373                 :                :              * This case is also different from the above in that we have to
                               2374                 :                :              * account for possibly injecting sorts into subpaths that aren't
                               2375                 :                :              * natively ordered.
                               2376                 :                :              */
                               2377   [ +  -  +  +  :           7041 :             foreach(l, apath->subpaths)
                                              +  + ]
                               2378                 :                :             {
                               2379                 :           5232 :                 Path       *subpath = (Path *) lfirst(l);
                               2380                 :                :                 int         presorted_keys;
                               2381                 :                :                 Path        sort_path;  /* dummy for result of
                               2382                 :                :                                          * cost_sort/cost_incremental_sort */
                               2383                 :                : 
  383 rguo@postgresql.org      2384         [ +  + ]:           5232 :                 if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
                               2385                 :                :                                                  &presorted_keys))
                               2386                 :                :                 {
                               2387                 :                :                     /*
                               2388                 :                :                      * We'll need to insert a Sort node, so include costs for
                               2389                 :                :                      * that.  We choose to use incremental sort if it is
                               2390                 :                :                      * enabled and there are presorted keys; otherwise we use
                               2391                 :                :                      * full sort.
                               2392                 :                :                      *
                               2393                 :                :                      * We can use the parent's LIMIT if any, since we
                               2394                 :                :                      * certainly won't pull more than that many tuples from
                               2395                 :                :                      * any child.
                               2396                 :                :                      */
                               2397   [ +  -  +  + ]:             46 :                     if (enable_incremental_sort && presorted_keys > 0)
                               2398                 :                :                     {
                               2399                 :             10 :                         cost_incremental_sort(&sort_path,
                               2400                 :                :                                               root,
                               2401                 :                :                                               pathkeys,
                               2402                 :                :                                               presorted_keys,
                               2403                 :                :                                               subpath->disabled_nodes,
                               2404                 :                :                                               subpath->startup_cost,
                               2405                 :                :                                               subpath->total_cost,
                               2406                 :                :                                               subpath->rows,
                               2407                 :             10 :                                               subpath->pathtarget->width,
                               2408                 :                :                                               0.0,
                               2409                 :                :                                               work_mem,
                               2410                 :                :                                               apath->limit_tuples);
                               2411                 :                :                     }
                               2412                 :                :                     else
                               2413                 :                :                     {
                               2414                 :             36 :                         cost_sort(&sort_path,
                               2415                 :                :                                   root,
                               2416                 :                :                                   pathkeys,
                               2417                 :                :                                   subpath->disabled_nodes,
                               2418                 :                :                                   subpath->total_cost,
                               2419                 :                :                                   subpath->rows,
                               2420                 :             36 :                                   subpath->pathtarget->width,
                               2421                 :                :                                   0.0,
                               2422                 :                :                                   work_mem,
                               2423                 :                :                                   apath->limit_tuples);
                               2424                 :                :                     }
                               2425                 :                : 
 2669 tgl@sss.pgh.pa.us        2426                 :             46 :                     subpath = &sort_path;
                               2427                 :                :                 }
                               2428                 :                : 
                               2429                 :           5232 :                 apath->path.rows += subpath->rows;
  704 rhaas@postgresql.org     2430                 :           5232 :                 apath->path.disabled_nodes += subpath->disabled_nodes;
 2669 tgl@sss.pgh.pa.us        2431                 :           5232 :                 apath->path.startup_cost += subpath->startup_cost;
                               2432                 :           5232 :                 apath->path.total_cost += subpath->total_cost;
                               2433                 :                :             }
                               2434                 :                :         }
                               2435                 :                :     }
                               2436                 :                :     else                        /* parallel-aware */
                               2437                 :                :     {
 3155 rhaas@postgresql.org     2438                 :          21761 :         int         i = 0;
                               2439                 :          21761 :         double      parallel_divisor = get_parallel_divisor(&apath->path);
                               2440                 :                : 
                               2441                 :                :         /* Parallel-aware Append never produces ordered output. */
 2669 tgl@sss.pgh.pa.us        2442         [ -  + ]:          21761 :         Assert(apath->path.pathkeys == NIL);
                               2443                 :                : 
                               2444                 :                :         /* Calculate startup cost. */
 3155 rhaas@postgresql.org     2445   [ +  -  +  +  :          86685 :         foreach(l, apath->subpaths)
                                              +  + ]
                               2446                 :                :         {
                               2447                 :          64924 :             Path       *subpath = (Path *) lfirst(l);
                               2448                 :                : 
                               2449                 :                :             /*
                               2450                 :                :              * Append will start returning tuples when the child node having
                               2451                 :                :              * lowest startup cost is done setting up. We consider only the
                               2452                 :                :              * first few subplans that immediately get a worker assigned.
                               2453                 :                :              */
                               2454         [ +  + ]:          64924 :             if (i == 0)
                               2455                 :          21761 :                 apath->path.startup_cost = subpath->startup_cost;
                               2456         [ +  + ]:          43163 :             else if (i < apath->path.parallel_workers)
                               2457         [ +  + ]:          21291 :                 apath->path.startup_cost = Min(apath->path.startup_cost,
                               2458                 :                :                                                subpath->startup_cost);
                               2459                 :                : 
                               2460                 :                :             /*
                               2461                 :                :              * Apply parallel divisor to subpaths.  Scale the number of rows
                               2462                 :                :              * for each partial subpath based on the ratio of the parallel
                               2463                 :                :              * divisor originally used for the subpath to the one we adopted.
                               2464                 :                :              * Also add the cost of partial paths to the total cost, but
                               2465                 :                :              * ignore non-partial paths for now.
                               2466                 :                :              */
                               2467         [ +  + ]:          64924 :             if (i < apath->first_partial_path)
                               2468                 :          11012 :                 apath->path.rows += subpath->rows / parallel_divisor;
                               2469                 :                :             else
                               2470                 :                :             {
                               2471                 :                :                 double      subpath_parallel_divisor;
                               2472                 :                : 
 3125                          2473                 :          53912 :                 subpath_parallel_divisor = get_parallel_divisor(subpath);
                               2474                 :          53912 :                 apath->path.rows += subpath->rows * (subpath_parallel_divisor /
                               2475                 :                :                                                      parallel_divisor);
 3155                          2476                 :          53912 :                 apath->path.total_cost += subpath->total_cost;
                               2477                 :                :             }
                               2478                 :                : 
  704                          2479                 :          64924 :             apath->path.disabled_nodes += subpath->disabled_nodes;
 3125                          2480                 :          64924 :             apath->path.rows = clamp_row_est(apath->path.rows);
                               2481                 :                : 
 3155                          2482                 :          64924 :             i++;
                               2483                 :                :         }
                               2484                 :                : 
                               2485                 :                :         /* Add cost for non-partial subpaths. */
                               2486                 :          21761 :         apath->path.total_cost +=
                               2487                 :          21761 :             append_nonpartial_cost(apath->subpaths,
                               2488                 :                :                                    apath->first_partial_path,
                               2489                 :                :                                    apath->path.parallel_workers);
                               2490                 :                :     }
                               2491                 :                : 
                               2492                 :                :     /*
                               2493                 :                :      * Although Append does not do any selection or projection, it's not free;
                               2494                 :                :      * add a small per-tuple overhead.
                               2495                 :                :      */
 3077                          2496                 :          57122 :     apath->path.total_cost +=
                               2497                 :          57122 :         cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
                               2498                 :                : }
                               2499                 :                : 
                               2500                 :                : /*
                               2501                 :                :  * cost_merge_append
                               2502                 :                :  *    Determines and returns the cost of a MergeAppend node.
                               2503                 :                :  *
                               2504                 :                :  * MergeAppend merges several pre-sorted input streams, using a heap that
                               2505                 :                :  * at any given instant holds the next tuple from each stream.  If there
                               2506                 :                :  * are N streams, we need about N*log2(N) tuple comparisons to construct
                               2507                 :                :  * the heap at startup, and then for each output tuple, about log2(N)
                               2508                 :                :  * comparisons to replace the top entry.
                               2509                 :                :  *
                               2510                 :                :  * (The effective value of N will drop once some of the input streams are
                               2511                 :                :  * exhausted, but it seems unlikely to be worth trying to account for that.)
                               2512                 :                :  *
                               2513                 :                :  * The heap is never spilled to disk, since we assume N is not very large.
                               2514                 :                :  * So this is much simpler than cost_sort.
                               2515                 :                :  *
                               2516                 :                :  * As in cost_sort, we charge two operator evals per tuple comparison.
                               2517                 :                :  *
                               2518                 :                :  * 'pathkeys' is a list of sort keys
                               2519                 :                :  * 'n_streams' is the number of input streams
                               2520                 :                :  * 'input_disabled_nodes' is the sum of the input streams' disabled node counts
                               2521                 :                :  * 'input_startup_cost' is the sum of the input streams' startup costs
                               2522                 :                :  * 'input_total_cost' is the sum of the input streams' total costs
                               2523                 :                :  * 'tuples' is the number of tuples in all the streams
                               2524                 :                :  */
                               2525                 :                : void
 5764 tgl@sss.pgh.pa.us        2526                 :           7390 : cost_merge_append(Path *path, PlannerInfo *root,
                               2527                 :                :                   List *pathkeys, int n_streams,
                               2528                 :                :                   int input_disabled_nodes,
                               2529                 :                :                   Cost input_startup_cost, Cost input_total_cost,
                               2530                 :                :                   double tuples)
                               2531                 :                : {
  179 rhaas@postgresql.org     2532                 :           7390 :     RelOptInfo *rel = path->parent;
 5764 tgl@sss.pgh.pa.us        2533                 :           7390 :     Cost        startup_cost = 0;
                               2534                 :           7390 :     Cost        run_cost = 0;
                               2535                 :                :     Cost        comparison_cost;
                               2536                 :                :     double      N;
                               2537                 :                :     double      logN;
  179 rhaas@postgresql.org     2538                 :           7390 :     uint64      enable_mask = PGS_MERGE_APPEND;
                               2539                 :                : 
                               2540         [ +  - ]:           7390 :     if (path->parallel_workers == 0)
                               2541                 :           7390 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               2542                 :                : 
                               2543                 :                :     /*
                               2544                 :                :      * Avoid log(0)...
                               2545                 :                :      */
 5764 tgl@sss.pgh.pa.us        2546         [ +  - ]:           7390 :     N = (n_streams < 2) ? 2.0 : (double) n_streams;
                               2547                 :           7390 :     logN = LOG2(N);
                               2548                 :                : 
                               2549                 :                :     /* Assumed cost per tuple comparison */
                               2550                 :           7390 :     comparison_cost = 2.0 * cpu_operator_cost;
                               2551                 :                : 
                               2552                 :                :     /* Heap creation cost */
                               2553                 :           7390 :     startup_cost += comparison_cost * N * logN;
                               2554                 :                : 
                               2555                 :                :     /* Per-tuple heap maintenance cost */
 3550                          2556                 :           7390 :     run_cost += tuples * comparison_cost * logN;
                               2557                 :                : 
                               2558                 :                :     /*
                               2559                 :                :      * Although MergeAppend does not do any selection or projection, it's not
                               2560                 :                :      * free; add a small per-tuple overhead.
                               2561                 :                :      */
 3077 rhaas@postgresql.org     2562                 :           7390 :     run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
                               2563                 :                : 
  179                          2564                 :           7390 :     path->disabled_nodes =
                               2565                 :           7390 :         (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
                               2566                 :           7390 :     path->disabled_nodes += input_disabled_nodes;
 5764 tgl@sss.pgh.pa.us        2567                 :           7390 :     path->startup_cost = startup_cost + input_startup_cost;
                               2568                 :           7390 :     path->total_cost = startup_cost + run_cost + input_total_cost;
                               2569                 :           7390 : }
                               2570                 :                : 
                               2571                 :                : /*
                               2572                 :                :  * cost_material
                               2573                 :                :  *    Determines and returns the cost of materializing a relation, including
                               2574                 :                :  *    the cost of reading the input data.
                               2575                 :                :  *
                               2576                 :                :  * If the total volume of data to materialize exceeds work_mem, we will need
                               2577                 :                :  * to write it to disk, so the cost is much higher in that case.
                               2578                 :                :  *
                               2579                 :                :  * Note that here we are estimating the costs for the first scan of the
                               2580                 :                :  * relation, so the materialization is all overhead --- any savings will
                               2581                 :                :  * occur only on rescan, which is estimated in cost_rescan.
                               2582                 :                :  */
                               2583                 :                : void
 8639                          2584                 :         496634 : cost_material(Path *path,
                               2585                 :                :               bool enabled, int input_disabled_nodes,
                               2586                 :                :               Cost input_startup_cost, Cost input_total_cost,
                               2587                 :                :               double tuples, int width)
                               2588                 :                : {
 6161                          2589                 :         496634 :     Cost        startup_cost = input_startup_cost;
                               2590                 :         496634 :     Cost        run_cost = input_total_cost - input_startup_cost;
 8639                          2591                 :         496634 :     double      nbytes = relation_byte_size(tuples, width);
  541                          2592                 :         496634 :     double      work_mem_bytes = work_mem * (Size) 1024;
                               2593                 :                : 
 5294                          2594                 :         496634 :     path->rows = tuples;
                               2595                 :                : 
                               2596                 :                :     /*
                               2597                 :                :      * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
                               2598                 :                :      * reflect bookkeeping overhead.  (This rate must be more than what
                               2599                 :                :      * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
                               2600                 :                :      * if it is exactly the same then there will be a cost tie between
                               2601                 :                :      * nestloop with A outer, materialized B inner and nestloop with B outer,
                               2602                 :                :      * materialized A inner.  The extra cost ensures we'll prefer
                               2603                 :                :      * materializing the smaller rel.)  Note that this is normally a good deal
                               2604                 :                :      * less than cpu_tuple_cost; which is OK because a Material plan node
                               2605                 :                :      * doesn't do qual-checking or projection, so it's got less overhead than
                               2606                 :                :      * most plan nodes.
                               2607                 :                :      */
 6001                          2608                 :         496634 :     run_cost += 2 * cpu_operator_cost * tuples;
                               2609                 :                : 
                               2610                 :                :     /*
                               2611                 :                :      * If we will spill to disk, charge at the rate of seq_page_cost per page.
                               2612                 :                :      * This cost is assumed to be evenly spread through the plan run phase,
                               2613                 :                :      * which isn't exactly accurate but our cost model doesn't allow for
                               2614                 :                :      * nonuniform costs within the run phase.
                               2615                 :                :      */
 8209                          2616         [ +  + ]:         496634 :     if (nbytes > work_mem_bytes)
                               2617                 :                :     {
 8639                          2618                 :           3185 :         double      npages = ceil(nbytes / BLCKSZ);
                               2619                 :                : 
 7356                          2620                 :           3185 :         run_cost += seq_page_cost * npages;
                               2621                 :                :     }
                               2622                 :                : 
  179 rhaas@postgresql.org     2623                 :         496634 :     path->disabled_nodes = input_disabled_nodes + (enabled ? 0 : 1);
 8639 tgl@sss.pgh.pa.us        2624                 :         496634 :     path->startup_cost = startup_cost;
                               2625                 :         496634 :     path->total_cost = startup_cost + run_cost;
                               2626                 :         496634 : }
                               2627                 :                : 
                               2628                 :                : /*
                               2629                 :                :  * cost_memoize_rescan
                               2630                 :                :  *    Determines the estimated cost of rescanning a Memoize node.
                               2631                 :                :  *
                               2632                 :                :  * In order to estimate this, we must gain knowledge of how often we expect to
                               2633                 :                :  * be called and how many distinct sets of parameters we are likely to be
                               2634                 :                :  * called with. If we expect a good cache hit ratio, then we can set our
                               2635                 :                :  * costs to account for that hit ratio, plus a little bit of cost for the
                               2636                 :                :  * caching itself.  Caching will not work out well if we expect to be called
                               2637                 :                :  * with too many distinct parameter values.  The worst-case here is that we
                               2638                 :                :  * never see any parameter value twice, in which case we'd never get a cache
                               2639                 :                :  * hit and caching would be a complete waste of effort.
                               2640                 :                :  */
                               2641                 :                : static void
 1838 drowley@postgresql.o     2642                 :         191620 : cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath,
                               2643                 :                :                     Cost *rescan_startup_cost, Cost *rescan_total_cost)
                               2644                 :                : {
                               2645                 :                :     EstimationInfo estinfo;
                               2646                 :                :     ListCell   *lc;
                               2647                 :         191620 :     Cost        input_startup_cost = mpath->subpath->startup_cost;
                               2648                 :         191620 :     Cost        input_total_cost = mpath->subpath->total_cost;
                               2649                 :         191620 :     double      tuples = mpath->subpath->rows;
  362                          2650                 :         191620 :     Cardinality est_calls = mpath->est_calls;
 1838                          2651                 :         191620 :     int         width = mpath->subpath->pathtarget->width;
                               2652                 :                : 
                               2653                 :                :     double      hash_mem_bytes;
                               2654                 :                :     double      est_entry_bytes;
                               2655                 :                :     Cardinality est_cache_entries;
                               2656                 :                :     Cardinality ndistinct;
                               2657                 :                :     double      evict_ratio;
                               2658                 :                :     double      hit_ratio;
                               2659                 :                :     Cost        startup_cost;
                               2660                 :                :     Cost        total_cost;
                               2661                 :                : 
                               2662                 :                :     /* available cache space */
 1827 tgl@sss.pgh.pa.us        2663                 :         191620 :     hash_mem_bytes = get_hash_memory_limit();
                               2664                 :                : 
                               2665                 :                :     /*
                               2666                 :                :      * Set the number of bytes each cache entry should consume in the cache.
                               2667                 :                :      * To provide us with better estimations on how many cache entries we can
                               2668                 :                :      * store at once, we make a call to the executor here to ask it what
                               2669                 :                :      * memory overheads there are for a single cache entry.
                               2670                 :                :      */
 1941 drowley@postgresql.o     2671                 :         191620 :     est_entry_bytes = relation_byte_size(tuples, width) +
                               2672                 :         191620 :         ExecEstimateCacheEntryOverheadBytes(tuples);
                               2673                 :                : 
                               2674                 :                :     /* include the estimated width for the cache keys */
 1224                          2675   [ +  -  +  +  :         406079 :     foreach(lc, mpath->param_exprs)
                                              +  + ]
                               2676                 :         214459 :         est_entry_bytes += get_expr_width(root, (Node *) lfirst(lc));
                               2677                 :                : 
                               2678                 :                :     /* estimate on the upper limit of cache entries we can hold at once */
 1941                          2679                 :         191620 :     est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
                               2680                 :                : 
                               2681                 :                :     /* estimate on the distinct number of parameter values */
  362                          2682                 :         191620 :     ndistinct = estimate_num_groups(root, mpath->param_exprs, est_calls, NULL,
                               2683                 :                :                                     &estinfo);
                               2684                 :                : 
                               2685                 :                :     /*
                               2686                 :                :      * When the estimation fell back on using a default value, it's a bit too
                               2687                 :                :      * risky to assume that it's ok to use a Memoize node.  The use of a
                               2688                 :                :      * default could cause us to use a Memoize node when it's really
                               2689                 :                :      * inappropriate to do so.  If we see that this has been done, then we'll
                               2690                 :                :      * assume that every call will have unique parameters, which will almost
                               2691                 :                :      * certainly mean a MemoizePath will never survive add_path().
                               2692                 :                :      */
 1941                          2693         [ +  + ]:         191620 :     if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
  362                          2694                 :          16098 :         ndistinct = est_calls;
                               2695                 :                : 
                               2696                 :                :     /* Remember the ndistinct estimate for EXPLAIN */
                               2697                 :         191620 :     mpath->est_unique_keys = ndistinct;
                               2698                 :                : 
                               2699                 :                :     /*
                               2700                 :                :      * Since we've already estimated the maximum number of entries we can
                               2701                 :                :      * store at once and know the estimated number of distinct values we'll be
                               2702                 :                :      * called with, we'll take this opportunity to set the path's est_entries.
                               2703                 :                :      * This will ultimately determine the hash table size that the executor
                               2704                 :                :      * will use.  If we leave this at zero, the executor will just choose the
                               2705                 :                :      * size itself.  Really this is not the right place to do this, but it's
                               2706                 :                :      * convenient since everything is already calculated.
                               2707                 :                :      */
 1838                          2708   [ +  +  +  -  :         191620 :     mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
                                              +  + ]
                               2709                 :                :                              PG_UINT32_MAX);
                               2710                 :                : 
                               2711                 :                :     /*
                               2712                 :                :      * When the number of distinct parameter values is above the amount we can
                               2713                 :                :      * store in the cache, then we'll have to evict some entries from the
                               2714                 :                :      * cache.  This is not free. Here we estimate how often we'll incur the
                               2715                 :                :      * cost of that eviction.
                               2716                 :                :      */
 1941                          2717         [ +  + ]:         191620 :     evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
                               2718                 :                : 
                               2719                 :                :     /*
                               2720                 :                :      * In order to estimate how costly a single scan will be, we need to
                               2721                 :                :      * attempt to estimate what the cache hit ratio will be.  To do that we
                               2722                 :                :      * must look at how many scans are estimated in total for this node and
                               2723                 :                :      * how many of those scans we expect to get a cache hit.
                               2724                 :                :      */
  362                          2725                 :         383240 :     hit_ratio = ((est_calls - ndistinct) / est_calls) *
 1222                          2726         [ +  + ]:         191620 :         (est_cache_entries / Max(ndistinct, est_cache_entries));
                               2727                 :                : 
                               2728                 :                :     /* Remember the hit ratio estimate for EXPLAIN */
  362                          2729                 :         191620 :     mpath->est_hit_ratio = hit_ratio;
                               2730                 :                : 
 1222                          2731   [ +  -  -  + ]:         191620 :     Assert(hit_ratio >= 0 && hit_ratio <= 1.0);
                               2732                 :                : 
                               2733                 :                :     /*
                               2734                 :                :      * Set the total_cost accounting for the expected cache hit ratio.  We
                               2735                 :                :      * also add on a cpu_operator_cost to account for a cache lookup. This
                               2736                 :                :      * will happen regardless of whether it's a cache hit or not.
                               2737                 :                :      */
 1941                          2738                 :         191620 :     total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
                               2739                 :                : 
                               2740                 :                :     /* Now adjust the total cost to account for cache evictions */
                               2741                 :                : 
                               2742                 :                :     /* Charge a cpu_tuple_cost for evicting the actual cache entry */
                               2743                 :         191620 :     total_cost += cpu_tuple_cost * evict_ratio;
                               2744                 :                : 
                               2745                 :                :     /*
                               2746                 :                :      * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
                               2747                 :                :      * The per-tuple eviction is really just a pfree, so charging a whole
                               2748                 :                :      * cpu_operator_cost seems a little excessive.
                               2749                 :                :      */
                               2750                 :         191620 :     total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
                               2751                 :                : 
                               2752                 :                :     /*
                               2753                 :                :      * Now adjust for storing things in the cache, since that's not free
                               2754                 :                :      * either.  Everything must go in the cache.  We don't proportion this
                               2755                 :                :      * over any ratio, just apply it once for the scan.  We charge a
                               2756                 :                :      * cpu_tuple_cost for the creation of the cache entry and also a
                               2757                 :                :      * cpu_operator_cost for each tuple we expect to cache.
                               2758                 :                :      */
                               2759                 :         191620 :     total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
                               2760                 :                : 
                               2761                 :                :     /*
                               2762                 :                :      * Getting the first row must be also be proportioned according to the
                               2763                 :                :      * expected cache hit ratio.
                               2764                 :                :      */
                               2765                 :         191620 :     startup_cost = input_startup_cost * (1.0 - hit_ratio);
                               2766                 :                : 
                               2767                 :                :     /*
                               2768                 :                :      * Additionally we charge a cpu_tuple_cost to account for cache lookups,
                               2769                 :                :      * which we'll do regardless of whether it was a cache hit or not.
                               2770                 :                :      */
                               2771                 :         191620 :     startup_cost += cpu_tuple_cost;
                               2772                 :                : 
                               2773                 :         191620 :     *rescan_startup_cost = startup_cost;
                               2774                 :         191620 :     *rescan_total_cost = total_cost;
                               2775                 :         191620 : }
                               2776                 :                : 
                               2777                 :                : /*
                               2778                 :                :  * cost_agg
                               2779                 :                :  *      Determines and returns the cost of performing an Agg plan node,
                               2780                 :                :  *      including the cost of its input.
                               2781                 :                :  *
                               2782                 :                :  * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
                               2783                 :                :  * we are using a hashed Agg node just to do grouping).
                               2784                 :                :  *
                               2785                 :                :  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
                               2786                 :                :  * are for appropriately-sorted input.
                               2787                 :                :  */
                               2788                 :                : void
 7721 tgl@sss.pgh.pa.us        2789                 :          74665 : cost_agg(Path *path, PlannerInfo *root,
                               2790                 :                :          AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
                               2791                 :                :          int numGroupCols, double numGroups,
                               2792                 :                :          List *quals,
                               2793                 :                :          int disabled_nodes,
                               2794                 :                :          Cost input_startup_cost, Cost input_total_cost,
                               2795                 :                :          double input_tuples, double input_width)
                               2796                 :                : {
                               2797                 :                :     double      output_tuples;
                               2798                 :                :     Cost        startup_cost;
                               2799                 :                :     Cost        total_cost;
  493 peter@eisentraut.org     2800                 :          74665 :     const AggClauseCosts dummy_aggcosts = {0};
                               2801                 :                : 
                               2802                 :                :     /* Use all-zero per-aggregate costs if NULL is passed */
 5572 tgl@sss.pgh.pa.us        2803         [ +  + ]:          74665 :     if (aggcosts == NULL)
                               2804                 :                :     {
                               2805         [ -  + ]:          15374 :         Assert(aggstrategy == AGG_HASHED);
                               2806                 :          15374 :         aggcosts = &dummy_aggcosts;
                               2807                 :                :     }
                               2808                 :                : 
                               2809                 :                :     /*
                               2810                 :                :      * The transCost.per_tuple component of aggcosts should be charged once
                               2811                 :                :      * per input tuple, corresponding to the costs of evaluating the aggregate
                               2812                 :                :      * transfns and their input expressions. The finalCost.per_tuple component
                               2813                 :                :      * is charged once per output tuple, corresponding to the costs of
                               2814                 :                :      * evaluating the finalfns.  Startup costs are of course charged but once.
                               2815                 :                :      *
                               2816                 :                :      * If we are grouping, we charge an additional cpu_operator_cost per
                               2817                 :                :      * grouping column per input tuple for grouping comparisons.
                               2818                 :                :      *
                               2819                 :                :      * We will produce a single output tuple if not grouping, and a tuple per
                               2820                 :                :      * group otherwise.  We charge cpu_tuple_cost for each output tuple.
                               2821                 :                :      *
                               2822                 :                :      * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
                               2823                 :                :      * same total CPU cost, but AGG_SORTED has lower startup cost.  If the
                               2824                 :                :      * input path is already sorted appropriately, AGG_SORTED should be
                               2825                 :                :      * preferred (since it has no risk of memory overflow).  This will happen
                               2826                 :                :      * as long as the computed total costs are indeed exactly equal --- but if
                               2827                 :                :      * there's roundoff error we might do the wrong thing.  So be sure that
                               2828                 :                :      * the computations below form the same intermediate values in the same
                               2829                 :                :      * order.
                               2830                 :                :      */
 8648                          2831         [ +  + ]:          74665 :     if (aggstrategy == AGG_PLAIN)
                               2832                 :                :     {
                               2833                 :          33073 :         startup_cost = input_total_cost;
 5572                          2834                 :          33073 :         startup_cost += aggcosts->transCost.startup;
                               2835                 :          33073 :         startup_cost += aggcosts->transCost.per_tuple * input_tuples;
 2724                          2836                 :          33073 :         startup_cost += aggcosts->finalCost.startup;
                               2837                 :          33073 :         startup_cost += aggcosts->finalCost.per_tuple;
                               2838                 :                :         /* we aren't grouping */
 7638                          2839                 :          33073 :         total_cost = startup_cost + cpu_tuple_cost;
 5294                          2840                 :          33073 :         output_tuples = 1;
                               2841                 :                : 
                               2842                 :                :         /* AGG_PLAIN neither hashes nor sorts, so neither switch disables it */
                               2843                 :                :     }
 3408 rhodiumtoad@postgres     2844   [ +  +  +  + ]:          41592 :     else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
                               2845                 :                :     {
                               2846                 :                :         /* Here we are able to deliver output on-the-fly */
 8648 tgl@sss.pgh.pa.us        2847                 :          15502 :         startup_cost = input_startup_cost;
                               2848                 :          15502 :         total_cost = input_total_cost;
                               2849                 :                :         /* calcs phrased this way to match HASHED case, see note above */
 5572                          2850                 :          15502 :         total_cost += aggcosts->transCost.startup;
                               2851                 :          15502 :         total_cost += aggcosts->transCost.per_tuple * input_tuples;
                               2852                 :          15502 :         total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
 2724                          2853                 :          15502 :         total_cost += aggcosts->finalCost.startup;
                               2854                 :          15502 :         total_cost += aggcosts->finalCost.per_tuple * numGroups;
 7638                          2855                 :          15502 :         total_cost += cpu_tuple_cost * numGroups;
 5294                          2856                 :          15502 :         output_tuples = numGroups;
                               2857                 :                : 
                               2858                 :                :         /*
                               2859                 :                :          * AGG_MIXED hashes at least one grouping set, so it is disabled when
                               2860                 :                :          * enable_hashagg is off.  Any sorted grouping it also performs is
                               2861                 :                :          * costed separately, since create_groupingsets_path() calls
                               2862                 :                :          * cost_agg() once per rollup and the non-hashed rollups come through
                               2863                 :                :          * as AGG_SORTED.
                               2864                 :                :          *
                               2865                 :                :          * AGG_SORTED is disabled when enable_groupagg is off, but only when
                               2866                 :                :          * there are grouping columns.  The empty grouping set arrives with
                               2867                 :                :          * numGroupCols == 0 and is computed like AGG_PLAIN, with no hashing
                               2868                 :                :          * or sorting, so it isn't disabled.
                               2869                 :                :          */
   17 rguo@postgresql.org      2870         [ +  + ]:GNC       15502 :         if (aggstrategy == AGG_MIXED)
                               2871                 :                :         {
                               2872         [ +  + ]:            966 :             if (!enable_hashagg)
                               2873                 :            460 :                 ++disabled_nodes;
                               2874                 :                :         }
                               2875   [ +  +  +  + ]:          14536 :         else if (numGroupCols > 0 && !enable_groupagg)   /* AGG_SORTED */
                               2876                 :             90 :             ++disabled_nodes;
                               2877                 :                :     }
                               2878                 :                :     else
                               2879                 :                :     {
                               2880                 :                :         /* must be AGG_HASHED */
 8648 tgl@sss.pgh.pa.us        2881                 :CBC       26090 :         startup_cost = input_total_cost;
 5572                          2882                 :          26090 :         startup_cost += aggcosts->transCost.startup;
                               2883                 :          26090 :         startup_cost += aggcosts->transCost.per_tuple * input_tuples;
                               2884                 :                :         /* cost of computing hash value */
                               2885                 :          26090 :         startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
 2724                          2886                 :          26090 :         startup_cost += aggcosts->finalCost.startup;
                               2887                 :                : 
 8648                          2888                 :          26090 :         total_cost = startup_cost;
 2724                          2889                 :          26090 :         total_cost += aggcosts->finalCost.per_tuple * numGroups;
                               2890                 :                :         /* cost of retrieving from hash table */
 7638                          2891                 :          26090 :         total_cost += cpu_tuple_cost * numGroups;
 5294                          2892                 :          26090 :         output_tuples = numGroups;
                               2893                 :                : 
                               2894                 :                :         /* AGG_HASHED is disabled when enable_hashagg is off */
   17 rguo@postgresql.org      2895         [ +  + ]:GNC       26090 :         if (!enable_hashagg)
                               2896                 :           1569 :             ++disabled_nodes;
                               2897                 :                :     }
                               2898                 :                : 
                               2899                 :                :     /*
                               2900                 :                :      * Add the disk costs of hash aggregation that spills to disk.
                               2901                 :                :      *
                               2902                 :                :      * Groups that go into the hash table stay in memory until finalized, so
                               2903                 :                :      * spilling and reprocessing tuples doesn't incur additional invocations
                               2904                 :                :      * of transCost or finalCost. Furthermore, the computed hash value is
                               2905                 :                :      * stored with the spilled tuples, so we don't incur extra invocations of
                               2906                 :                :      * the hash function.
                               2907                 :                :      *
                               2908                 :                :      * Hash Agg begins returning tuples after the first batch is complete.
                               2909                 :                :      * Accrue writes (spilled tuples) to startup_cost and to total_cost;
                               2910                 :                :      * accrue reads only to total_cost.
                               2911                 :                :      */
 2321 jdavis@postgresql.or     2912   [ +  +  +  + ]:CBC       74665 :     if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
                               2913                 :                :     {
                               2914                 :                :         double      pages;
 2264 tgl@sss.pgh.pa.us        2915                 :          27056 :         double      pages_written = 0.0;
                               2916                 :          27056 :         double      pages_read = 0.0;
                               2917                 :                :         double      spill_cost;
                               2918                 :                :         double      hashentrysize;
                               2919                 :                :         double      nbatches;
                               2920                 :                :         Size        mem_limit;
                               2921                 :                :         uint64      ngroups_limit;
                               2922                 :                :         int         num_partitions;
                               2923                 :                :         int         depth;
                               2924                 :                : 
                               2925                 :                :         /*
                               2926                 :                :          * Estimate number of batches based on the computed limits. If less
                               2927                 :                :          * than or equal to one, all groups are expected to fit in memory;
                               2928                 :                :          * otherwise we expect to spill.
                               2929                 :                :          */
 2070 heikki.linnakangas@i     2930                 :          27056 :         hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
                               2931                 :                :                                             input_width,
 2264 tgl@sss.pgh.pa.us        2932                 :          27056 :                                             aggcosts->transitionSpace);
 2321 jdavis@postgresql.or     2933                 :          27056 :         hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
                               2934                 :                :                             &ngroups_limit, &num_partitions);
                               2935                 :                : 
 2264 tgl@sss.pgh.pa.us        2936         [ -  + ]:          27056 :         nbatches = Max((numGroups * hashentrysize) / mem_limit,
                               2937                 :                :                        numGroups / ngroups_limit);
                               2938                 :                : 
 2311 jdavis@postgresql.or     2939         [ +  + ]:          27056 :         nbatches = Max(ceil(nbatches), 1.0);
                               2940                 :          27056 :         num_partitions = Max(num_partitions, 2);
                               2941                 :                : 
                               2942                 :                :         /*
                               2943                 :                :          * The number of partitions can change at different levels of
                               2944                 :                :          * recursion; but for the purposes of this calculation assume it stays
                               2945                 :                :          * constant.
                               2946                 :                :          */
 2264 tgl@sss.pgh.pa.us        2947                 :          27056 :         depth = ceil(log(nbatches) / log(num_partitions));
                               2948                 :                : 
                               2949                 :                :         /*
                               2950                 :                :          * Estimate number of pages read and written. For each level of
                               2951                 :                :          * recursion, a tuple must be written and then later read.
                               2952                 :                :          */
 2311 jdavis@postgresql.or     2953                 :          27056 :         pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
                               2954                 :          27056 :         pages_written = pages_read = pages * depth;
                               2955                 :                : 
                               2956                 :                :         /*
                               2957                 :                :          * HashAgg has somewhat worse IO behavior than Sort on typical
                               2958                 :                :          * hardware/OS combinations. Account for this with a generic penalty.
                               2959                 :                :          */
 2148                          2960                 :          27056 :         pages_read *= 2.0;
                               2961                 :          27056 :         pages_written *= 2.0;
                               2962                 :                : 
 2321                          2963                 :          27056 :         startup_cost += pages_written * random_page_cost;
                               2964                 :          27056 :         total_cost += pages_written * random_page_cost;
                               2965                 :          27056 :         total_cost += pages_read * seq_page_cost;
                               2966                 :                : 
                               2967                 :                :         /* account for CPU cost of spilling a tuple and reading it back */
 2148                          2968                 :          27056 :         spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
                               2969                 :          27056 :         startup_cost += spill_cost;
                               2970                 :          27056 :         total_cost += spill_cost;
                               2971                 :                :     }
                               2972                 :                : 
                               2973                 :                :     /*
                               2974                 :                :      * If there are quals (HAVING quals), account for their cost and
                               2975                 :                :      * selectivity.
                               2976                 :                :      */
 3188 tgl@sss.pgh.pa.us        2977         [ +  + ]:          74665 :     if (quals)
                               2978                 :                :     {
                               2979                 :                :         QualCost    qual_cost;
                               2980                 :                : 
                               2981                 :           4018 :         cost_qual_eval(&qual_cost, quals, root);
                               2982                 :           4018 :         startup_cost += qual_cost.startup;
                               2983                 :           4018 :         total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
                               2984                 :                : 
                               2985                 :           4018 :         output_tuples = clamp_row_est(output_tuples *
                               2986                 :           4018 :                                       clauselist_selectivity(root,
                               2987                 :                :                                                              quals,
                               2988                 :                :                                                              0,
                               2989                 :                :                                                              JOIN_INNER,
                               2990                 :                :                                                              NULL));
                               2991                 :                :     }
                               2992                 :                : 
 5294                          2993                 :          74665 :     path->rows = output_tuples;
  704 rhaas@postgresql.org     2994                 :          74665 :     path->disabled_nodes = disabled_nodes;
 8648 tgl@sss.pgh.pa.us        2995                 :          74665 :     path->startup_cost = startup_cost;
                               2996                 :          74665 :     path->total_cost = total_cost;
                               2997                 :          74665 : }
                               2998                 :                : 
                               2999                 :                : /*
                               3000                 :                :  * get_windowclause_startup_tuples
                               3001                 :                :  *      Estimate how many tuples we'll need to fetch from a WindowAgg's
                               3002                 :                :  *      subnode before we can output the first WindowAgg tuple.
                               3003                 :                :  *
                               3004                 :                :  * How many tuples need to be read depends on the WindowClause.  For example,
                               3005                 :                :  * a WindowClause with no PARTITION BY and no ORDER BY requires that all
                               3006                 :                :  * subnode tuples are read and aggregated before the WindowAgg can output
                               3007                 :                :  * anything.  If there's a PARTITION BY, then we only need to look at tuples
                               3008                 :                :  * in the first partition.  Here we attempt to estimate just how many
                               3009                 :                :  * 'input_tuples' the WindowAgg will need to read for the given WindowClause
                               3010                 :                :  * before the first tuple can be output.
                               3011                 :                :  */
                               3012                 :                : static double
 1087 drowley@postgresql.o     3013                 :           2647 : get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc,
                               3014                 :                :                                 double input_tuples)
                               3015                 :                : {
                               3016                 :           2647 :     int         frameOptions = wc->frameOptions;
                               3017                 :                :     double      partition_tuples;
                               3018                 :                :     double      return_tuples;
                               3019                 :                :     double      peer_tuples;
                               3020                 :                : 
                               3021                 :                :     /*
                               3022                 :                :      * First, figure out how many partitions there are likely to be and set
                               3023                 :                :      * partition_tuples according to that estimate.
                               3024                 :                :      */
                               3025         [ +  + ]:           2647 :     if (wc->partitionClause != NIL)
                               3026                 :                :     {
                               3027                 :                :         double      num_partitions;
                               3028                 :            613 :         List       *partexprs = get_sortgrouplist_exprs(wc->partitionClause,
                               3029                 :            613 :                                                         root->parse->targetList);
                               3030                 :                : 
                               3031                 :            613 :         num_partitions = estimate_num_groups(root, partexprs, input_tuples,
                               3032                 :                :                                              NULL, NULL);
                               3033                 :            613 :         list_free(partexprs);
                               3034                 :                : 
                               3035                 :            613 :         partition_tuples = input_tuples / num_partitions;
                               3036                 :                :     }
                               3037                 :                :     else
                               3038                 :                :     {
                               3039                 :                :         /* all tuples belong to the same partition */
                               3040                 :           2034 :         partition_tuples = input_tuples;
                               3041                 :                :     }
                               3042                 :                : 
                               3043                 :                :     /* estimate the number of tuples in each peer group */
                               3044         [ +  + ]:           2647 :     if (wc->orderClause != NIL)
                               3045                 :                :     {
                               3046                 :                :         double      num_groups;
                               3047                 :                :         List       *orderexprs;
                               3048                 :                : 
                               3049                 :           2057 :         orderexprs = get_sortgrouplist_exprs(wc->orderClause,
                               3050                 :           2057 :                                              root->parse->targetList);
                               3051                 :                : 
                               3052                 :                :         /* estimate out how many peer groups there are in the partition */
                               3053                 :           2057 :         num_groups = estimate_num_groups(root, orderexprs,
                               3054                 :                :                                          partition_tuples, NULL,
                               3055                 :                :                                          NULL);
                               3056                 :           2057 :         list_free(orderexprs);
                               3057                 :           2057 :         peer_tuples = partition_tuples / num_groups;
                               3058                 :                :     }
                               3059                 :                :     else
                               3060                 :                :     {
                               3061                 :                :         /* no ORDER BY so only 1 tuple belongs in each peer group */
                               3062                 :            590 :         peer_tuples = 1.0;
                               3063                 :                :     }
                               3064                 :                : 
                               3065         [ +  + ]:           2647 :     if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
                               3066                 :                :     {
                               3067                 :                :         /* include all partition rows */
                               3068                 :            304 :         return_tuples = partition_tuples;
                               3069                 :                :     }
                               3070         [ +  + ]:           2343 :     else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
                               3071                 :                :     {
                               3072         [ +  + ]:           1425 :         if (frameOptions & FRAMEOPTION_ROWS)
                               3073                 :                :         {
                               3074                 :                :             /* just count the current row */
                               3075                 :            632 :             return_tuples = 1.0;
                               3076                 :                :         }
                               3077         [ +  - ]:            793 :         else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
                               3078                 :                :         {
                               3079                 :                :             /*
                               3080                 :                :              * When in RANGE/GROUPS mode, it's more complex.  If there's no
                               3081                 :                :              * ORDER BY, then all rows in the partition are peers, otherwise
                               3082                 :                :              * we'll need to read the first group of peers.
                               3083                 :                :              */
                               3084         [ +  + ]:            793 :             if (wc->orderClause == NIL)
                               3085                 :            343 :                 return_tuples = partition_tuples;
                               3086                 :                :             else
                               3087                 :            450 :                 return_tuples = peer_tuples;
                               3088                 :                :         }
                               3089                 :                :         else
                               3090                 :                :         {
                               3091                 :                :             /*
                               3092                 :                :              * Something new we don't support yet?  This needs attention.
                               3093                 :                :              * We'll just return 1.0 in the meantime.
                               3094                 :                :              */
 1087 drowley@postgresql.o     3095                 :UBC           0 :             Assert(false);
                               3096                 :                :             return_tuples = 1.0;
                               3097                 :                :         }
                               3098                 :                :     }
 1087 drowley@postgresql.o     3099         [ +  + ]:CBC         918 :     else if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
                               3100                 :                :     {
                               3101                 :                :         /*
                               3102                 :                :          * BETWEEN ... AND N PRECEDING will only need to read the WindowAgg's
                               3103                 :                :          * subnode after N ROWS/RANGES/GROUPS.  N can be 0, but not negative,
                               3104                 :                :          * so we'll just assume only the current row needs to be read to fetch
                               3105                 :                :          * the first WindowAgg row.
                               3106                 :                :          */
                               3107                 :            125 :         return_tuples = 1.0;
                               3108                 :                :     }
                               3109         [ +  - ]:            793 :     else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
                               3110                 :                :     {
                               3111                 :            793 :         Const      *endOffset = (Const *) wc->endOffset;
                               3112                 :                :         double      end_offset_value;
                               3113                 :                : 
                               3114                 :                :         /* try and figure out the value specified in the endOffset. */
                               3115         [ +  - ]:            793 :         if (IsA(endOffset, Const))
                               3116                 :                :         {
                               3117         [ -  + ]:            793 :             if (endOffset->constisnull)
                               3118                 :                :             {
                               3119                 :                :                 /*
                               3120                 :                :                  * NULLs are not allowed, but currently, there's no code to
                               3121                 :                :                  * error out if there's a NULL Const.  We'll only discover
                               3122                 :                :                  * this during execution.  For now, just pretend everything is
                               3123                 :                :                  * fine and assume that just the first row/range/group will be
                               3124                 :                :                  * needed.
                               3125                 :                :                  */
 1087 drowley@postgresql.o     3126                 :UBC           0 :                 end_offset_value = 1.0;
                               3127                 :                :             }
                               3128                 :                :             else
                               3129                 :                :             {
 1087 drowley@postgresql.o     3130   [ +  +  +  + ]:CBC         793 :                 switch (endOffset->consttype)
                               3131                 :                :                 {
                               3132                 :             20 :                     case INT2OID:
                               3133                 :             20 :                         end_offset_value =
                               3134                 :             20 :                             (double) DatumGetInt16(endOffset->constvalue);
                               3135                 :             20 :                         break;
                               3136                 :            110 :                     case INT4OID:
                               3137                 :            110 :                         end_offset_value =
                               3138                 :            110 :                             (double) DatumGetInt32(endOffset->constvalue);
                               3139                 :            110 :                         break;
                               3140                 :            378 :                     case INT8OID:
                               3141                 :            378 :                         end_offset_value =
                               3142                 :            378 :                             (double) DatumGetInt64(endOffset->constvalue);
                               3143                 :            378 :                         break;
                               3144                 :            285 :                     default:
                               3145                 :            285 :                         end_offset_value =
                               3146                 :            285 :                             partition_tuples / peer_tuples *
                               3147                 :                :                             DEFAULT_INEQ_SEL;
                               3148                 :            285 :                         break;
                               3149                 :                :                 }
                               3150                 :                :             }
                               3151                 :                :         }
                               3152                 :                :         else
                               3153                 :                :         {
                               3154                 :                :             /*
                               3155                 :                :              * When the end bound is not a Const, we'll just need to guess. We
                               3156                 :                :              * just make use of DEFAULT_INEQ_SEL.
                               3157                 :                :              */
 1087 drowley@postgresql.o     3158                 :UBC           0 :             end_offset_value =
                               3159                 :              0 :                 partition_tuples / peer_tuples * DEFAULT_INEQ_SEL;
                               3160                 :                :         }
                               3161                 :                : 
 1087 drowley@postgresql.o     3162         [ +  + ]:CBC         793 :         if (frameOptions & FRAMEOPTION_ROWS)
                               3163                 :                :         {
                               3164                 :                :             /* include the N FOLLOWING and the current row */
                               3165                 :            238 :             return_tuples = end_offset_value + 1.0;
                               3166                 :                :         }
                               3167         [ +  - ]:            555 :         else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
                               3168                 :                :         {
                               3169                 :                :             /* include N FOLLOWING ranges/group and the initial range/group */
                               3170                 :            555 :             return_tuples = peer_tuples * (end_offset_value + 1.0);
                               3171                 :                :         }
                               3172                 :                :         else
                               3173                 :                :         {
                               3174                 :                :             /*
                               3175                 :                :              * Something new we don't support yet?  This needs attention.
                               3176                 :                :              * We'll just return 1.0 in the meantime.
                               3177                 :                :              */
 1087 drowley@postgresql.o     3178                 :UBC           0 :             Assert(false);
                               3179                 :                :             return_tuples = 1.0;
                               3180                 :                :         }
                               3181                 :                :     }
                               3182                 :                :     else
                               3183                 :                :     {
                               3184                 :                :         /*
                               3185                 :                :          * Something new we don't support yet?  This needs attention.  We'll
                               3186                 :                :          * just return 1.0 in the meantime.
                               3187                 :                :          */
                               3188                 :              0 :         Assert(false);
                               3189                 :                :         return_tuples = 1.0;
                               3190                 :                :     }
                               3191                 :                : 
 1087 drowley@postgresql.o     3192   [ +  +  +  + ]:CBC        2647 :     if (wc->partitionClause != NIL || wc->orderClause != NIL)
                               3193                 :                :     {
                               3194                 :                :         /*
                               3195                 :                :          * Cap the return value to the estimated partition tuples and account
                               3196                 :                :          * for the extra tuple WindowAgg will need to read to confirm the next
                               3197                 :                :          * tuple does not belong to the same partition or peer group.
                               3198                 :                :          */
                               3199         [ +  + ]:           2251 :         return_tuples = Min(return_tuples + 1.0, partition_tuples);
                               3200                 :                :     }
                               3201                 :                :     else
                               3202                 :                :     {
                               3203                 :                :         /*
                               3204                 :                :          * Cap the return value so it's never higher than the expected tuples
                               3205                 :                :          * in the partition.
                               3206                 :                :          */
                               3207         [ +  + ]:            396 :         return_tuples = Min(return_tuples, partition_tuples);
                               3208                 :                :     }
                               3209                 :                : 
                               3210                 :                :     /*
                               3211                 :                :      * We needn't worry about any EXCLUDE options as those only exclude rows
                               3212                 :                :      * from being aggregated, not from being read from the WindowAgg's
                               3213                 :                :      * subnode.
                               3214                 :                :      */
                               3215                 :                : 
                               3216                 :           2647 :     return clamp_row_est(return_tuples);
                               3217                 :                : }
                               3218                 :                : 
                               3219                 :                : /*
                               3220                 :                :  * cost_windowagg
                               3221                 :                :  *      Determines and returns the cost of performing a WindowAgg plan node,
                               3222                 :                :  *      including the cost of its input.
                               3223                 :                :  *
                               3224                 :                :  * Input is assumed already properly sorted.
                               3225                 :                :  */
                               3226                 :                : void
 6419 tgl@sss.pgh.pa.us        3227                 :           2647 : cost_windowagg(Path *path, PlannerInfo *root,
                               3228                 :                :                List *windowFuncs, WindowClause *winclause,
                               3229                 :                :                int input_disabled_nodes,
                               3230                 :                :                Cost input_startup_cost, Cost input_total_cost,
                               3231                 :                :                double input_tuples)
                               3232                 :                : {
                               3233                 :                :     Cost        startup_cost;
                               3234                 :                :     Cost        total_cost;
                               3235                 :                :     double      startup_tuples;
                               3236                 :                :     int         numPartCols;
                               3237                 :                :     int         numOrderCols;
                               3238                 :                :     ListCell   *lc;
                               3239                 :                : 
 1087 drowley@postgresql.o     3240                 :           2647 :     numPartCols = list_length(winclause->partitionClause);
                               3241                 :           2647 :     numOrderCols = list_length(winclause->orderClause);
                               3242                 :                : 
 6419 tgl@sss.pgh.pa.us        3243                 :           2647 :     startup_cost = input_startup_cost;
                               3244                 :           2647 :     total_cost = input_total_cost;
                               3245                 :                : 
                               3246                 :                :     /*
                               3247                 :                :      * Window functions are assumed to cost their stated execution cost, plus
                               3248                 :                :      * the cost of evaluating their input expressions, per tuple.  Since they
                               3249                 :                :      * may in fact evaluate their inputs at multiple rows during each cycle,
                               3250                 :                :      * this could be a drastic underestimate; but without a way to know how
                               3251                 :                :      * many rows the window function will fetch, it's hard to do better.  In
                               3252                 :                :      * any case, it's a good estimate for all the built-in window functions,
                               3253                 :                :      * so we'll just do this for now.
                               3254                 :                :      */
 5572                          3255   [ +  -  +  +  :           6027 :     foreach(lc, windowFuncs)
                                              +  + ]
                               3256                 :                :     {
 3394                          3257                 :           3380 :         WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
                               3258                 :                :         Cost        wfunccost;
                               3259                 :                :         QualCost    argcosts;
                               3260                 :                : 
 2724                          3261                 :           3380 :         argcosts.startup = argcosts.per_tuple = 0;
                               3262                 :           3380 :         add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
                               3263                 :                :                           &argcosts);
                               3264                 :           3380 :         startup_cost += argcosts.startup;
                               3265                 :           3380 :         wfunccost = argcosts.per_tuple;
                               3266                 :                : 
                               3267                 :                :         /* also add the input expressions' cost to per-input-row costs */
 5572                          3268                 :           3380 :         cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
                               3269                 :           3380 :         startup_cost += argcosts.startup;
                               3270                 :           3380 :         wfunccost += argcosts.per_tuple;
                               3271                 :                : 
                               3272                 :                :         /*
                               3273                 :                :          * Add the filter's cost to per-input-row costs.  XXX We should reduce
                               3274                 :                :          * input expression costs according to filter selectivity.
                               3275                 :                :          */
 4758 noah@leadboat.com        3276                 :           3380 :         cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
                               3277                 :           3380 :         startup_cost += argcosts.startup;
                               3278                 :           3380 :         wfunccost += argcosts.per_tuple;
                               3279                 :                : 
 5572 tgl@sss.pgh.pa.us        3280                 :           3380 :         total_cost += wfunccost * input_tuples;
                               3281                 :                :     }
                               3282                 :                : 
                               3283                 :                :     /*
                               3284                 :                :      * We also charge cpu_operator_cost per grouping column per tuple for
                               3285                 :                :      * grouping comparisons, plus cpu_tuple_cost per tuple for general
                               3286                 :                :      * overhead.
                               3287                 :                :      *
                               3288                 :                :      * XXX this neglects costs of spooling the data to disk when it overflows
                               3289                 :                :      * work_mem.  Sooner or later that should get accounted for.
                               3290                 :                :      */
                               3291                 :           2647 :     total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
 6419                          3292                 :           2647 :     total_cost += cpu_tuple_cost * input_tuples;
                               3293                 :                : 
 5294                          3294                 :           2647 :     path->rows = input_tuples;
  704 rhaas@postgresql.org     3295                 :           2647 :     path->disabled_nodes = input_disabled_nodes;
 6419 tgl@sss.pgh.pa.us        3296                 :           2647 :     path->startup_cost = startup_cost;
                               3297                 :           2647 :     path->total_cost = total_cost;
                               3298                 :                : 
                               3299                 :                :     /*
                               3300                 :                :      * Also, take into account how many tuples we need to read from the
                               3301                 :                :      * subnode in order to produce the first tuple from the WindowAgg.  To do
                               3302                 :                :      * this we proportion the run cost (total cost not including startup cost)
                               3303                 :                :      * over the estimated startup tuples.  We already included the startup
                               3304                 :                :      * cost of the subnode, so we only need to do this when the estimated
                               3305                 :                :      * startup tuples is above 1.0.
                               3306                 :                :      */
 1087 drowley@postgresql.o     3307                 :           2647 :     startup_tuples = get_windowclause_startup_tuples(root, winclause,
                               3308                 :                :                                                      input_tuples);
                               3309                 :                : 
                               3310         [ +  + ]:           2647 :     if (startup_tuples > 1.0)
                               3311                 :           2305 :         path->startup_cost += (total_cost - startup_cost) / input_tuples *
                               3312                 :           2305 :             (startup_tuples - 1.0);
 6419 tgl@sss.pgh.pa.us        3313                 :           2647 : }
                               3314                 :                : 
                               3315                 :                : /*
                               3316                 :                :  * cost_group
                               3317                 :                :  *      Determines and returns the cost of performing a Group plan node,
                               3318                 :                :  *      including the cost of its input.
                               3319                 :                :  *
                               3320                 :                :  * Note: caller must ensure that input costs are for appropriately-sorted
                               3321                 :                :  * input.
                               3322                 :                :  */
                               3323                 :                : void
 7721                          3324                 :           1043 : cost_group(Path *path, PlannerInfo *root,
                               3325                 :                :            int numGroupCols, double numGroups,
                               3326                 :                :            List *quals,
                               3327                 :                :            int input_disabled_nodes,
                               3328                 :                :            Cost input_startup_cost, Cost input_total_cost,
                               3329                 :                :            double input_tuples)
                               3330                 :                : {
                               3331                 :                :     double      output_tuples;
                               3332                 :                :     Cost        startup_cost;
                               3333                 :                :     Cost        total_cost;
                               3334                 :                : 
 3188                          3335                 :           1043 :     output_tuples = numGroups;
 8648                          3336                 :           1043 :     startup_cost = input_startup_cost;
                               3337                 :           1043 :     total_cost = input_total_cost;
                               3338                 :                : 
                               3339                 :                :     /*
                               3340                 :                :      * Charge one cpu_operator_cost per comparison per input tuple. We assume
                               3341                 :                :      * all columns get compared at most of the tuples.
                               3342                 :                :      */
                               3343                 :           1043 :     total_cost += cpu_operator_cost * input_tuples * numGroupCols;
                               3344                 :                : 
                               3345                 :                :     /*
                               3346                 :                :      * If there are quals (HAVING quals), account for their cost and
                               3347                 :                :      * selectivity.
                               3348                 :                :      */
 3188                          3349         [ -  + ]:           1043 :     if (quals)
                               3350                 :                :     {
                               3351                 :                :         QualCost    qual_cost;
                               3352                 :                : 
 3188 tgl@sss.pgh.pa.us        3353                 :UBC           0 :         cost_qual_eval(&qual_cost, quals, root);
                               3354                 :              0 :         startup_cost += qual_cost.startup;
                               3355                 :              0 :         total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
                               3356                 :                : 
                               3357                 :              0 :         output_tuples = clamp_row_est(output_tuples *
                               3358                 :              0 :                                       clauselist_selectivity(root,
                               3359                 :                :                                                              quals,
                               3360                 :                :                                                              0,
                               3361                 :                :                                                              JOIN_INNER,
                               3362                 :                :                                                              NULL));
                               3363                 :                :     }
                               3364                 :                : 
 3188 tgl@sss.pgh.pa.us        3365                 :CBC        1043 :     path->rows = output_tuples;
   17 rguo@postgresql.org      3366                 :GNC        1043 :     path->disabled_nodes = input_disabled_nodes + (enable_groupagg ? 0 : 1);
 8648 tgl@sss.pgh.pa.us        3367                 :CBC        1043 :     path->startup_cost = startup_cost;
                               3368                 :           1043 :     path->total_cost = total_cost;
                               3369                 :           1043 : }
                               3370                 :                : 
                               3371                 :                : /*
                               3372                 :                :  * initial_cost_nestloop
                               3373                 :                :  *    Preliminary estimate of the cost of a nestloop join path.
                               3374                 :                :  *
                               3375                 :                :  * This must quickly produce lower-bound estimates of the path's startup and
                               3376                 :                :  * total costs.  If we are unable to eliminate the proposed path from
                               3377                 :                :  * consideration using the lower bounds, final_cost_nestloop will be called
                               3378                 :                :  * to obtain the final estimates.
                               3379                 :                :  *
                               3380                 :                :  * The exact division of labor between this function and final_cost_nestloop
                               3381                 :                :  * is private to them, and represents a tradeoff between speed of the initial
                               3382                 :                :  * estimate and getting a tight lower bound.  We choose to not examine the
                               3383                 :                :  * join quals here, since that's by far the most expensive part of the
                               3384                 :                :  * calculations.  The end result is that CPU-cost considerations must be
                               3385                 :                :  * left for the second phase; and for SEMI/ANTI joins, we must also postpone
                               3386                 :                :  * incorporation of the inner path's run cost.
                               3387                 :                :  *
                               3388                 :                :  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
                               3389                 :                :  *      other data to be used by final_cost_nestloop
                               3390                 :                :  * 'jointype' is the type of join to be performed
                               3391                 :                :  * 'outer_path' is the outer input to the join
                               3392                 :                :  * 'inner_path' is the inner input to the join
                               3393                 :                :  * 'extra' contains miscellaneous information about the join
                               3394                 :                :  */
                               3395                 :                : void
 5294                          3396                 :        2557415 : initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
                               3397                 :                :                       JoinType jointype, uint64 enable_mask,
                               3398                 :                :                       Path *outer_path, Path *inner_path,
                               3399                 :                :                       JoinPathExtraData *extra)
                               3400                 :                : {
                               3401                 :                :     int         disabled_nodes;
 9658                          3402                 :        2557415 :     Cost        startup_cost = 0;
                               3403                 :        2557415 :     Cost        run_cost = 0;
 5294                          3404                 :        2557415 :     double      outer_path_rows = outer_path->rows;
                               3405                 :                :     Cost        inner_rescan_start_cost;
                               3406                 :                :     Cost        inner_rescan_total_cost;
                               3407                 :                :     Cost        inner_run_cost;
                               3408                 :                :     Cost        inner_rescan_run_cost;
                               3409                 :                : 
                               3410                 :                :     /* Count up disabled nodes. */
  179 rhaas@postgresql.org     3411                 :        2557415 :     disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
  704                          3412                 :        2557415 :     disabled_nodes += inner_path->disabled_nodes;
                               3413                 :        2557415 :     disabled_nodes += outer_path->disabled_nodes;
                               3414                 :                : 
                               3415                 :                :     /* estimate costs to rescan the inner relation */
 6161 tgl@sss.pgh.pa.us        3416                 :        2557415 :     cost_rescan(root, inner_path,
                               3417                 :                :                 &inner_rescan_start_cost,
                               3418                 :                :                 &inner_rescan_total_cost);
                               3419                 :                : 
                               3420                 :                :     /* cost of source data */
                               3421                 :                : 
                               3422                 :                :     /*
                               3423                 :                :      * NOTE: clearly, we must pay both outer and inner paths' startup_cost
                               3424                 :                :      * before we can start returning tuples, so the join's startup cost is
                               3425                 :                :      * their sum.  We'll also pay the inner path's rescan startup cost
                               3426                 :                :      * multiple times.
                               3427                 :                :      */
 9658                          3428                 :        2557415 :     startup_cost += outer_path->startup_cost + inner_path->startup_cost;
                               3429                 :        2557415 :     run_cost += outer_path->total_cost - outer_path->startup_cost;
 6161                          3430         [ +  + ]:        2557415 :     if (outer_path_rows > 1)
                               3431                 :        1784266 :         run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
                               3432                 :                : 
 6287                          3433                 :        2557415 :     inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
 6161                          3434                 :        2557415 :     inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
                               3435                 :                : 
 3397                          3436   [ +  +  +  + ]:        2557415 :     if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
                               3437         [ +  + ]:        2439856 :         extra->inner_unique)
                               3438                 :                :     {
                               3439                 :                :         /*
                               3440                 :                :          * With a SEMI or ANTI join, or if the innerrel is known unique, the
                               3441                 :                :          * executor will stop after the first match.
                               3442                 :                :          *
                               3443                 :                :          * Getting decent estimates requires inspection of the join quals,
                               3444                 :                :          * which we choose to postpone to final_cost_nestloop.
                               3445                 :                :          */
                               3446                 :                : 
                               3447                 :                :         /* Save private data for final_cost_nestloop */
 4071                          3448                 :        1084736 :         workspace->inner_run_cost = inner_run_cost;
                               3449                 :        1084736 :         workspace->inner_rescan_run_cost = inner_rescan_run_cost;
                               3450                 :                :     }
                               3451                 :                :     else
                               3452                 :                :     {
                               3453                 :                :         /* Normal case; we'll scan whole input rel for each outer row */
 5294                          3454                 :        1472679 :         run_cost += inner_run_cost;
                               3455         [ +  + ]:        1472679 :         if (outer_path_rows > 1)
                               3456                 :        1114222 :             run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
                               3457                 :                :     }
                               3458                 :                : 
                               3459                 :                :     /* CPU costs left for later */
                               3460                 :                : 
                               3461                 :                :     /* Public result fields */
  704 rhaas@postgresql.org     3462                 :        2557415 :     workspace->disabled_nodes = disabled_nodes;
 5294 tgl@sss.pgh.pa.us        3463                 :        2557415 :     workspace->startup_cost = startup_cost;
                               3464                 :        2557415 :     workspace->total_cost = startup_cost + run_cost;
                               3465                 :                :     /* Save private data for final_cost_nestloop */
                               3466                 :        2557415 :     workspace->run_cost = run_cost;
                               3467                 :        2557415 : }
                               3468                 :                : 
                               3469                 :                : /*
                               3470                 :                :  * final_cost_nestloop
                               3471                 :                :  *    Final estimate of the cost and result size of a nestloop join path.
                               3472                 :                :  *
                               3473                 :                :  * 'path' is already filled in except for the rows and cost fields
                               3474                 :                :  * 'workspace' is the result from initial_cost_nestloop
                               3475                 :                :  * 'extra' contains miscellaneous information about the join
                               3476                 :                :  */
                               3477                 :                : void
                               3478                 :        1172451 : final_cost_nestloop(PlannerInfo *root, NestPath *path,
                               3479                 :                :                     JoinCostWorkspace *workspace,
                               3480                 :                :                     JoinPathExtraData *extra)
                               3481                 :                : {
 1813 peter@eisentraut.org     3482                 :        1172451 :     Path       *outer_path = path->jpath.outerjoinpath;
                               3483                 :        1172451 :     Path       *inner_path = path->jpath.innerjoinpath;
 5294 tgl@sss.pgh.pa.us        3484                 :        1172451 :     double      outer_path_rows = outer_path->rows;
                               3485                 :        1172451 :     double      inner_path_rows = inner_path->rows;
                               3486                 :        1172451 :     Cost        startup_cost = workspace->startup_cost;
                               3487                 :        1172451 :     Cost        run_cost = workspace->run_cost;
                               3488                 :                :     Cost        cpu_per_tuple;
                               3489                 :                :     QualCost    restrict_qual_cost;
                               3490                 :                :     double      ntuples;
                               3491                 :                : 
                               3492                 :                :     /* Set the number of disabled nodes. */
  704 rhaas@postgresql.org     3493                 :        1172451 :     path->jpath.path.disabled_nodes = workspace->disabled_nodes;
                               3494                 :                : 
                               3495                 :                :     /* Protect some assumptions below that rowcounts aren't zero */
 2106 drowley@postgresql.o     3496         [ -  + ]:        1172451 :     if (outer_path_rows <= 0)
 3774 tgl@sss.pgh.pa.us        3497                 :UBC           0 :         outer_path_rows = 1;
 2106 drowley@postgresql.o     3498         [ +  + ]:CBC     1172451 :     if (inner_path_rows <= 0)
 3774 tgl@sss.pgh.pa.us        3499                 :            556 :         inner_path_rows = 1;
                               3500                 :                :     /* Mark the path with the correct row estimate */
 1813 peter@eisentraut.org     3501         [ +  + ]:        1172451 :     if (path->jpath.path.param_info)
                               3502                 :          27603 :         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
                               3503                 :                :     else
                               3504                 :        1144848 :         path->jpath.path.rows = path->jpath.path.parent->rows;
                               3505                 :                : 
                               3506                 :                :     /* For partial paths, scale row estimate. */
                               3507         [ +  + ]:        1172451 :     if (path->jpath.path.parallel_workers > 0)
                               3508                 :                :     {
                               3509                 :          38257 :         double      parallel_divisor = get_parallel_divisor(&path->jpath.path);
                               3510                 :                : 
                               3511                 :          38257 :         path->jpath.path.rows =
                               3512                 :          38257 :             clamp_row_est(path->jpath.path.rows / parallel_divisor);
                               3513                 :                :     }
                               3514                 :                : 
                               3515                 :                :     /* cost of inner-relation source data (we already dealt with outer rel) */
                               3516                 :                : 
                               3517   [ +  +  +  + ]:        1172451 :     if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
 3397 tgl@sss.pgh.pa.us        3518         [ +  + ]:        1087433 :         extra->inner_unique)
 5294                          3519                 :         737453 :     {
                               3520                 :                :         /*
                               3521                 :                :          * With a SEMI or ANTI join, or if the innerrel is known unique, the
                               3522                 :                :          * executor will stop after the first match.
                               3523                 :                :          */
 4071                          3524                 :         737453 :         Cost        inner_run_cost = workspace->inner_run_cost;
                               3525                 :         737453 :         Cost        inner_rescan_run_cost = workspace->inner_rescan_run_cost;
                               3526                 :                :         double      outer_matched_rows;
                               3527                 :                :         double      outer_unmatched_rows;
                               3528                 :                :         Selectivity inner_scan_frac;
                               3529                 :                : 
                               3530                 :                :         /*
                               3531                 :                :          * For an outer-rel row that has at least one match, we can expect the
                               3532                 :                :          * inner scan to stop after a fraction 1/(match_count+1) of the inner
                               3533                 :                :          * rows, if the matches are evenly distributed.  Since they probably
                               3534                 :                :          * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
                               3535                 :                :          * that fraction.  (If we used a larger fuzz factor, we'd have to
                               3536                 :                :          * clamp inner_scan_frac to at most 1.0; but since match_count is at
                               3537                 :                :          * least 1, no such clamp is needed now.)
                               3538                 :                :          */
 3397                          3539                 :         737453 :         outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
 3340                          3540                 :         737453 :         outer_unmatched_rows = outer_path_rows - outer_matched_rows;
 3397                          3541                 :         737453 :         inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
                               3542                 :                : 
                               3543                 :                :         /*
                               3544                 :                :          * Compute number of tuples processed (not number emitted!).  First,
                               3545                 :                :          * account for successfully-matched outer rows.
                               3546                 :                :          */
 6287                          3547                 :         737453 :         ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
                               3548                 :                : 
                               3549                 :                :         /*
                               3550                 :                :          * Now we need to estimate the actual costs of scanning the inner
                               3551                 :                :          * relation, which may be quite a bit less than N times inner_run_cost
                               3552                 :                :          * due to early scan stops.  We consider two cases.  If the inner path
                               3553                 :                :          * is an indexscan using all the joinquals as indexquals, then an
                               3554                 :                :          * unmatched outer row results in an indexscan returning no rows,
                               3555                 :                :          * which is probably quite cheap.  Otherwise, the executor will have
                               3556                 :                :          * to scan the whole inner rel for an unmatched row; not so cheap.
                               3557                 :                :          */
 5211                          3558         [ +  + ]:         737453 :         if (has_indexed_join_quals(path))
                               3559                 :                :         {
                               3560                 :                :             /*
                               3561                 :                :              * Successfully-matched outer rows will only require scanning
                               3562                 :                :              * inner_scan_frac of the inner relation.  In this case, we don't
                               3563                 :                :              * need to charge the full inner_run_cost even when that's more
                               3564                 :                :              * than inner_rescan_run_cost, because we can assume that none of
                               3565                 :                :              * the inner scans ever scan the whole inner relation.  So it's
                               3566                 :                :              * okay to assume that all the inner scan executions can be
                               3567                 :                :              * fractions of the full cost, even if materialization is reducing
                               3568                 :                :              * the rescan cost.  At this writing, it's impossible to get here
                               3569                 :                :              * for a materialized inner scan, so inner_run_cost and
                               3570                 :                :              * inner_rescan_run_cost will be the same anyway; but just in
                               3571                 :                :              * case, use inner_run_cost for the first matched tuple and
                               3572                 :                :              * inner_rescan_run_cost for additional ones.
                               3573                 :                :              */
 4071                          3574                 :         116877 :             run_cost += inner_run_cost * inner_scan_frac;
                               3575         [ +  + ]:         116877 :             if (outer_matched_rows > 1)
                               3576                 :          12521 :                 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
                               3577                 :                : 
                               3578                 :                :             /*
                               3579                 :                :              * Add the cost of inner-scan executions for unmatched outer rows.
                               3580                 :                :              * We estimate this as the same cost as returning the first tuple
                               3581                 :                :              * of a nonempty scan.  We consider that these are all rescans,
                               3582                 :                :              * since we used inner_run_cost once already.
                               3583                 :                :              */
 3340                          3584                 :         116877 :             run_cost += outer_unmatched_rows *
 6161                          3585                 :         116877 :                 inner_rescan_run_cost / inner_path_rows;
                               3586                 :                : 
                               3587                 :                :             /*
                               3588                 :                :              * We won't be evaluating any quals at all for unmatched rows, so
                               3589                 :                :              * don't add them to ntuples.
                               3590                 :                :              */
                               3591                 :                :         }
                               3592                 :                :         else
                               3593                 :                :         {
                               3594                 :                :             /*
                               3595                 :                :              * Here, a complicating factor is that rescans may be cheaper than
                               3596                 :                :              * first scans.  If we never scan all the way to the end of the
                               3597                 :                :              * inner rel, it might be (depending on the plan type) that we'd
                               3598                 :                :              * never pay the whole inner first-scan run cost.  However it is
                               3599                 :                :              * difficult to estimate whether that will happen (and it could
                               3600                 :                :              * not happen if there are any unmatched outer rows!), so be
                               3601                 :                :              * conservative and always charge the whole first-scan cost once.
                               3602                 :                :              * We consider this charge to correspond to the first unmatched
                               3603                 :                :              * outer row, unless there isn't one in our estimate, in which
                               3604                 :                :              * case blame it on the first matched row.
                               3605                 :                :              */
                               3606                 :                : 
                               3607                 :                :             /* First, count all unmatched join tuples as being processed */
 3340                          3608                 :         620576 :             ntuples += outer_unmatched_rows * inner_path_rows;
                               3609                 :                : 
                               3610                 :                :             /* Now add the forced full scan, and decrement appropriate count */
 4071                          3611                 :         620576 :             run_cost += inner_run_cost;
 3340                          3612         [ +  + ]:         620576 :             if (outer_unmatched_rows >= 1)
                               3613                 :         594834 :                 outer_unmatched_rows -= 1;
                               3614                 :                :             else
                               3615                 :          25742 :                 outer_matched_rows -= 1;
                               3616                 :                : 
                               3617                 :                :             /* Add inner run cost for additional outer tuples having matches */
                               3618         [ +  + ]:         620576 :             if (outer_matched_rows > 0)
                               3619                 :         210657 :                 run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
                               3620                 :                : 
                               3621                 :                :             /* Add inner run cost for additional unmatched outer tuples */
                               3622         [ +  + ]:         620576 :             if (outer_unmatched_rows > 0)
                               3623                 :         359121 :                 run_cost += outer_unmatched_rows * inner_rescan_run_cost;
                               3624                 :                :         }
                               3625                 :                :     }
                               3626                 :                :     else
                               3627                 :                :     {
                               3628                 :                :         /* Normal-case source costs were included in preliminary estimate */
                               3629                 :                : 
                               3630                 :                :         /* Compute number of tuples processed (not number emitted!) */
 6287                          3631                 :         434998 :         ntuples = outer_path_rows * inner_path_rows;
                               3632                 :                :     }
                               3633                 :                : 
                               3634                 :                :     /* CPU costs */
 1813 peter@eisentraut.org     3635                 :        1172451 :     cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
 8596 tgl@sss.pgh.pa.us        3636                 :        1172451 :     startup_cost += restrict_qual_cost.startup;
                               3637                 :        1172451 :     cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
 9658                          3638                 :        1172451 :     run_cost += cpu_per_tuple * ntuples;
                               3639                 :                : 
                               3640                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 1813 peter@eisentraut.org     3641                 :        1172451 :     startup_cost += path->jpath.path.pathtarget->cost.startup;
                               3642                 :        1172451 :     run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
                               3643                 :                : 
                               3644                 :        1172451 :     path->jpath.path.startup_cost = startup_cost;
                               3645                 :        1172451 :     path->jpath.path.total_cost = startup_cost + run_cost;
10974 scrappy@hub.org          3646                 :        1172451 : }
                               3647                 :                : 
                               3648                 :                : /*
                               3649                 :                :  * initial_cost_mergejoin
                               3650                 :                :  *    Preliminary estimate of the cost of a mergejoin path.
                               3651                 :                :  *
                               3652                 :                :  * This must quickly produce lower-bound estimates of the path's startup and
                               3653                 :                :  * total costs.  If we are unable to eliminate the proposed path from
                               3654                 :                :  * consideration using the lower bounds, final_cost_mergejoin will be called
                               3655                 :                :  * to obtain the final estimates.
                               3656                 :                :  *
                               3657                 :                :  * The exact division of labor between this function and final_cost_mergejoin
                               3658                 :                :  * is private to them, and represents a tradeoff between speed of the initial
                               3659                 :                :  * estimate and getting a tight lower bound.  We choose to not examine the
                               3660                 :                :  * join quals here, except for obtaining the scan selectivity estimate which
                               3661                 :                :  * is really essential (but fortunately, use of caching keeps the cost of
                               3662                 :                :  * getting that down to something reasonable).
                               3663                 :                :  * We also assume that cost_sort/cost_incremental_sort is cheap enough to use
                               3664                 :                :  * here.
                               3665                 :                :  *
                               3666                 :                :  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
                               3667                 :                :  *      other data to be used by final_cost_mergejoin
                               3668                 :                :  * 'jointype' is the type of join to be performed
                               3669                 :                :  * 'mergeclauses' is the list of joinclauses to be used as merge clauses
                               3670                 :                :  * 'outer_path' is the outer input to the join
                               3671                 :                :  * 'inner_path' is the inner input to the join
                               3672                 :                :  * 'outersortkeys' is the list of sort keys for the outer path
                               3673                 :                :  * 'innersortkeys' is the list of sort keys for the inner path
                               3674                 :                :  * 'outer_presorted_keys' is the number of presorted keys of the outer path
                               3675                 :                :  * 'extra' contains miscellaneous information about the join
                               3676                 :                :  *
                               3677                 :                :  * Note: outersortkeys and innersortkeys should be NIL if no explicit
                               3678                 :                :  * sort is needed because the respective source path is already ordered.
                               3679                 :                :  */
                               3680                 :                : void
 5294 tgl@sss.pgh.pa.us        3681                 :        1090957 : initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
                               3682                 :                :                        JoinType jointype,
                               3683                 :                :                        List *mergeclauses,
                               3684                 :                :                        Path *outer_path, Path *inner_path,
                               3685                 :                :                        List *outersortkeys, List *innersortkeys,
                               3686                 :                :                        int outer_presorted_keys,
                               3687                 :                :                        JoinPathExtraData *extra)
                               3688                 :                : {
                               3689                 :                :     int         disabled_nodes;
 9658                          3690                 :        1090957 :     Cost        startup_cost = 0;
                               3691                 :        1090957 :     Cost        run_cost = 0;
 5294                          3692                 :        1090957 :     double      outer_path_rows = outer_path->rows;
                               3693                 :        1090957 :     double      inner_path_rows = inner_path->rows;
                               3694                 :                :     Cost        inner_run_cost;
                               3695                 :                :     double      outer_rows,
                               3696                 :                :                 inner_rows,
                               3697                 :                :                 outer_skip_rows,
                               3698                 :                :                 inner_skip_rows;
                               3699                 :                :     Selectivity outerstartsel,
                               3700                 :                :                 outerendsel,
                               3701                 :                :                 innerstartsel,
                               3702                 :                :                 innerendsel;
                               3703                 :                :     Path        sort_path;      /* dummy for result of
                               3704                 :                :                                  * cost_sort/cost_incremental_sort */
                               3705                 :                : 
                               3706                 :                :     /* Protect some assumptions below that rowcounts aren't zero */
 2106 drowley@postgresql.o     3707         [ +  + ]:        1090957 :     if (outer_path_rows <= 0)
 6698 tgl@sss.pgh.pa.us        3708                 :             72 :         outer_path_rows = 1;
 2106 drowley@postgresql.o     3709         [ +  + ]:        1090957 :     if (inner_path_rows <= 0)
 6698 tgl@sss.pgh.pa.us        3710                 :             94 :         inner_path_rows = 1;
                               3711                 :                : 
                               3712                 :                :     /*
                               3713                 :                :      * A merge join will stop as soon as it exhausts either input stream
                               3714                 :                :      * (unless it's an outer join, in which case the outer side has to be
                               3715                 :                :      * scanned all the way anyway).  Estimate fraction of the left and right
                               3716                 :                :      * inputs that will actually need to be scanned.  Likewise, we can
                               3717                 :                :      * estimate the number of rows that will be skipped before the first join
                               3718                 :                :      * pair is found, which should be factored into startup cost. We use only
                               3719                 :                :      * the first (most significant) merge clause for this purpose. Since
                               3720                 :                :      * mergejoinscansel() is a fairly expensive computation, we cache the
                               3721                 :                :      * results in the merge clause RestrictInfo.
                               3722                 :                :      */
 5294                          3723   [ +  +  +  + ]:        1090957 :     if (mergeclauses && jointype != JOIN_FULL)
 8913                          3724                 :        1085992 :     {
 7127                          3725                 :        1085992 :         RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
                               3726                 :                :         List       *opathkeys;
                               3727                 :                :         List       *ipathkeys;
                               3728                 :                :         PathKey    *opathkey;
                               3729                 :                :         PathKey    *ipathkey;
                               3730                 :                :         MergeScanSelCache *cache;
                               3731                 :                : 
                               3732                 :                :         /* Get the input pathkeys to determine the sort-order details */
                               3733         [ +  + ]:        1085992 :         opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
                               3734         [ +  + ]:        1085992 :         ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
                               3735         [ -  + ]:        1085992 :         Assert(opathkeys);
                               3736         [ -  + ]:        1085992 :         Assert(ipathkeys);
                               3737                 :        1085992 :         opathkey = (PathKey *) linitial(opathkeys);
                               3738                 :        1085992 :         ipathkey = (PathKey *) linitial(ipathkeys);
                               3739                 :                :         /* debugging check */
                               3740         [ +  - ]:        1085992 :         if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
 5608                          3741         [ +  - ]:        1085992 :             opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
  478 peter@eisentraut.org     3742         [ +  - ]:        1085992 :             opathkey->pk_cmptype != ipathkey->pk_cmptype ||
 7127 tgl@sss.pgh.pa.us        3743         [ -  + ]:        1085992 :             opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
 7127 tgl@sss.pgh.pa.us        3744         [ #  # ]:UBC           0 :             elog(ERROR, "left and right pathkeys do not match in mergejoin");
                               3745                 :                : 
                               3746                 :                :         /* Get the selectivity with caching */
 7125 tgl@sss.pgh.pa.us        3747                 :CBC     1085992 :         cache = cached_scansel(root, firstclause, opathkey);
                               3748                 :                : 
 7127                          3749         [ +  + ]:        1085992 :         if (bms_is_subset(firstclause->left_relids,
                               3750                 :        1085992 :                           outer_path->parent->relids))
                               3751                 :                :         {
                               3752                 :                :             /* left side of clause is outer */
 6805                          3753                 :         564366 :             outerstartsel = cache->leftstartsel;
                               3754                 :         564366 :             outerendsel = cache->leftendsel;
                               3755                 :         564366 :             innerstartsel = cache->rightstartsel;
                               3756                 :         564366 :             innerendsel = cache->rightendsel;
                               3757                 :                :         }
                               3758                 :                :         else
                               3759                 :                :         {
                               3760                 :                :             /* left side of clause is inner */
                               3761                 :         521626 :             outerstartsel = cache->rightstartsel;
                               3762                 :         521626 :             outerendsel = cache->rightendsel;
                               3763                 :         521626 :             innerstartsel = cache->leftstartsel;
                               3764                 :         521626 :             innerendsel = cache->leftendsel;
                               3765                 :                :         }
 5294                          3766   [ +  +  +  + ]:        1085992 :         if (jointype == JOIN_LEFT ||
                               3767                 :                :             jointype == JOIN_ANTI)
                               3768                 :                :         {
 6805                          3769                 :         133129 :             outerstartsel = 0.0;
                               3770                 :         133129 :             outerendsel = 1.0;
                               3771                 :                :         }
 1208                          3772   [ +  +  +  + ]:         952863 :         else if (jointype == JOIN_RIGHT ||
                               3773                 :                :                  jointype == JOIN_RIGHT_ANTI)
                               3774                 :                :         {
 6805                          3775                 :         134771 :             innerstartsel = 0.0;
                               3776                 :         134771 :             innerendsel = 1.0;
                               3777                 :                :         }
                               3778                 :                :     }
                               3779                 :                :     else
                               3780                 :                :     {
                               3781                 :                :         /* cope with clauseless or full mergejoin */
                               3782                 :           4965 :         outerstartsel = innerstartsel = 0.0;
                               3783                 :           4965 :         outerendsel = innerendsel = 1.0;
                               3784                 :                :     }
                               3785                 :                : 
                               3786                 :                :     /*
                               3787                 :                :      * Convert selectivities to row counts.  We force outer_rows and
                               3788                 :                :      * inner_rows to be at least 1, but the skip_rows estimates can be zero.
                               3789                 :                :      */
                               3790                 :        1090957 :     outer_skip_rows = rint(outer_path_rows * outerstartsel);
                               3791                 :        1090957 :     inner_skip_rows = rint(inner_path_rows * innerstartsel);
                               3792                 :        1090957 :     outer_rows = clamp_row_est(outer_path_rows * outerendsel);
                               3793                 :        1090957 :     inner_rows = clamp_row_est(inner_path_rows * innerendsel);
                               3794                 :                : 
                               3795         [ -  + ]:        1090957 :     Assert(outer_skip_rows <= outer_rows);
                               3796         [ -  + ]:        1090957 :     Assert(inner_skip_rows <= inner_rows);
                               3797                 :                : 
                               3798                 :                :     /*
                               3799                 :                :      * Readjust scan selectivities to account for above rounding.  This is
                               3800                 :                :      * normally an insignificant effect, but when there are only a few rows in
                               3801                 :                :      * the inputs, failing to do this makes for a large percentage error.
                               3802                 :                :      */
                               3803                 :        1090957 :     outerstartsel = outer_skip_rows / outer_path_rows;
                               3804                 :        1090957 :     innerstartsel = inner_skip_rows / inner_path_rows;
                               3805                 :        1090957 :     outerendsel = outer_rows / outer_path_rows;
                               3806                 :        1090957 :     innerendsel = inner_rows / inner_path_rows;
                               3807                 :                : 
 5322                          3808         [ -  + ]:        1090957 :     Assert(outerstartsel <= outerendsel);
                               3809         [ -  + ]:        1090957 :     Assert(innerstartsel <= innerendsel);
                               3810                 :                : 
                               3811                 :                :     /*
                               3812                 :                :      * We don't decide whether to materialize the inner path until we get to
                               3813                 :                :      * final_cost_mergejoin(), so we don't know whether to check the pgs_mask
                               3814                 :                :      * against PGS_MERGEJOIN_PLAIN or PGS_MERGEJOIN_MATERIALIZE. Instead, we
                               3815                 :                :      * just account for any child nodes here and assume that this node is not
                               3816                 :                :      * itself disabled; we can sort out the details in final_cost_mergejoin().
                               3817                 :                :      *
                               3818                 :                :      * (We could be more precise here by setting disabled_nodes to 1 at this
                               3819                 :                :      * stage if both PGS_MERGEJOIN_PLAIN and PGS_MERGEJOIN_MATERIALIZE are
                               3820                 :                :      * disabled, but that seems to against the idea of making this function
                               3821                 :                :      * produce a quick, optimistic approximation of the final cost.)
                               3822                 :                :      */
  179 rhaas@postgresql.org     3823                 :        1090957 :     disabled_nodes = 0;
                               3824                 :                : 
                               3825                 :                :     /* cost of source data */
                               3826                 :                : 
 9658 tgl@sss.pgh.pa.us        3827         [ +  + ]:        1090957 :     if (outersortkeys)          /* do we need to sort outer? */
                               3828                 :                :     {
                               3829                 :                :         /*
                               3830                 :                :          * We can assert that the outer path is not already ordered
                               3831                 :                :          * appropriately for the mergejoin; otherwise, outersortkeys would
                               3832                 :                :          * have been set to NIL.
                               3833                 :                :          */
  444 rguo@postgresql.org      3834         [ -  + ]:         562072 :         Assert(!pathkeys_contained_in(outersortkeys, outer_path->pathkeys));
                               3835                 :                : 
                               3836                 :                :         /*
                               3837                 :                :          * We choose to use incremental sort if it is enabled and there are
                               3838                 :                :          * presorted keys; otherwise we use full sort.
                               3839                 :                :          */
                               3840   [ +  +  +  + ]:         562072 :         if (enable_incremental_sort && outer_presorted_keys > 0)
                               3841                 :                :         {
                               3842                 :           1658 :             cost_incremental_sort(&sort_path,
                               3843                 :                :                                   root,
                               3844                 :                :                                   outersortkeys,
                               3845                 :                :                                   outer_presorted_keys,
                               3846                 :                :                                   outer_path->disabled_nodes,
                               3847                 :                :                                   outer_path->startup_cost,
                               3848                 :                :                                   outer_path->total_cost,
                               3849                 :                :                                   outer_path_rows,
                               3850                 :           1658 :                                   outer_path->pathtarget->width,
                               3851                 :                :                                   0.0,
                               3852                 :                :                                   work_mem,
                               3853                 :                :                                   -1.0);
                               3854                 :                :         }
                               3855                 :                :         else
                               3856                 :                :         {
  655                          3857                 :         560414 :             cost_sort(&sort_path,
                               3858                 :                :                       root,
                               3859                 :                :                       outersortkeys,
                               3860                 :                :                       outer_path->disabled_nodes,
                               3861                 :                :                       outer_path->total_cost,
                               3862                 :                :                       outer_path_rows,
                               3863                 :         560414 :                       outer_path->pathtarget->width,
                               3864                 :                :                       0.0,
                               3865                 :                :                       work_mem,
                               3866                 :                :                       -1.0);
                               3867                 :                :         }
                               3868                 :                : 
  704 rhaas@postgresql.org     3869                 :         562072 :         disabled_nodes += sort_path.disabled_nodes;
 9658 tgl@sss.pgh.pa.us        3870                 :         562072 :         startup_cost += sort_path.startup_cost;
 6805                          3871                 :         562072 :         startup_cost += (sort_path.total_cost - sort_path.startup_cost)
                               3872                 :         562072 :             * outerstartsel;
 8913                          3873                 :         562072 :         run_cost += (sort_path.total_cost - sort_path.startup_cost)
 6805                          3874                 :         562072 :             * (outerendsel - outerstartsel);
                               3875                 :                :     }
                               3876                 :                :     else
                               3877                 :                :     {
  704 rhaas@postgresql.org     3878                 :         528885 :         disabled_nodes += outer_path->disabled_nodes;
 9658 tgl@sss.pgh.pa.us        3879                 :         528885 :         startup_cost += outer_path->startup_cost;
 6805                          3880                 :         528885 :         startup_cost += (outer_path->total_cost - outer_path->startup_cost)
                               3881                 :         528885 :             * outerstartsel;
 8913                          3882                 :         528885 :         run_cost += (outer_path->total_cost - outer_path->startup_cost)
 6805                          3883                 :         528885 :             * (outerendsel - outerstartsel);
                               3884                 :                :     }
                               3885                 :                : 
 9658                          3886         [ +  + ]:        1090957 :     if (innersortkeys)          /* do we need to sort inner? */
                               3887                 :                :     {
                               3888                 :                :         /*
                               3889                 :                :          * We can assert that the inner path is not already ordered
                               3890                 :                :          * appropriately for the mergejoin; otherwise, innersortkeys would
                               3891                 :                :          * have been set to NIL.
                               3892                 :                :          */
  444 rguo@postgresql.org      3893         [ -  + ]:         881104 :         Assert(!pathkeys_contained_in(innersortkeys, inner_path->pathkeys));
                               3894                 :                : 
                               3895                 :                :         /*
                               3896                 :                :          * We do not consider incremental sort for inner path, because
                               3897                 :                :          * incremental sort does not support mark/restore.
                               3898                 :                :          */
                               3899                 :                : 
 9658 tgl@sss.pgh.pa.us        3900                 :         881104 :         cost_sort(&sort_path,
                               3901                 :                :                   root,
                               3902                 :                :                   innersortkeys,
                               3903                 :                :                   inner_path->disabled_nodes,
                               3904                 :                :                   inner_path->total_cost,
                               3905                 :                :                   inner_path_rows,
 3811                          3906                 :         881104 :                   inner_path->pathtarget->width,
                               3907                 :                :                   0.0,
                               3908                 :                :                   work_mem,
                               3909                 :                :                   -1.0);
  704 rhaas@postgresql.org     3910                 :         881104 :         disabled_nodes += sort_path.disabled_nodes;
 9658 tgl@sss.pgh.pa.us        3911                 :         881104 :         startup_cost += sort_path.startup_cost;
 6805                          3912                 :         881104 :         startup_cost += (sort_path.total_cost - sort_path.startup_cost)
 6097                          3913                 :         881104 :             * innerstartsel;
                               3914                 :         881104 :         inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
                               3915                 :         881104 :             * (innerendsel - innerstartsel);
                               3916                 :                :     }
                               3917                 :                :     else
                               3918                 :                :     {
  704 rhaas@postgresql.org     3919                 :         209853 :         disabled_nodes += inner_path->disabled_nodes;
 9658 tgl@sss.pgh.pa.us        3920                 :         209853 :         startup_cost += inner_path->startup_cost;
 6805                          3921                 :         209853 :         startup_cost += (inner_path->total_cost - inner_path->startup_cost)
 6097                          3922                 :         209853 :             * innerstartsel;
                               3923                 :         209853 :         inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
                               3924                 :         209853 :             * (innerendsel - innerstartsel);
                               3925                 :                :     }
                               3926                 :                : 
                               3927                 :                :     /*
                               3928                 :                :      * We can't yet determine whether rescanning occurs, or whether
                               3929                 :                :      * materialization of the inner input should be done.  The minimum
                               3930                 :                :      * possible inner input cost, regardless of rescan and materialization
                               3931                 :                :      * considerations, is inner_run_cost.  We include that in
                               3932                 :                :      * workspace->total_cost, but not yet in run_cost.
                               3933                 :                :      */
                               3934                 :                : 
                               3935                 :                :     /* CPU costs left for later */
                               3936                 :                : 
                               3937                 :                :     /* Public result fields */
  704 rhaas@postgresql.org     3938                 :        1090957 :     workspace->disabled_nodes = disabled_nodes;
 5294 tgl@sss.pgh.pa.us        3939                 :        1090957 :     workspace->startup_cost = startup_cost;
                               3940                 :        1090957 :     workspace->total_cost = startup_cost + run_cost + inner_run_cost;
                               3941                 :                :     /* Save private data for final_cost_mergejoin */
                               3942                 :        1090957 :     workspace->run_cost = run_cost;
                               3943                 :        1090957 :     workspace->inner_run_cost = inner_run_cost;
                               3944                 :        1090957 :     workspace->outer_rows = outer_rows;
                               3945                 :        1090957 :     workspace->inner_rows = inner_rows;
                               3946                 :        1090957 :     workspace->outer_skip_rows = outer_skip_rows;
                               3947                 :        1090957 :     workspace->inner_skip_rows = inner_skip_rows;
                               3948                 :        1090957 : }
                               3949                 :                : 
                               3950                 :                : /*
                               3951                 :                :  * final_cost_mergejoin
                               3952                 :                :  *    Final estimate of the cost and result size of a mergejoin path.
                               3953                 :                :  *
                               3954                 :                :  * Unlike other costsize functions, this routine makes two actual decisions:
                               3955                 :                :  * whether the executor will need to do mark/restore, and whether we should
                               3956                 :                :  * materialize the inner path.  It would be logically cleaner to build
                               3957                 :                :  * separate paths testing these alternatives, but that would require repeating
                               3958                 :                :  * most of the cost calculations, which are not all that cheap.  Since the
                               3959                 :                :  * choice will not affect output pathkeys or startup cost, only total cost,
                               3960                 :                :  * there is no possibility of wanting to keep more than one path.  So it seems
                               3961                 :                :  * best to make the decisions here and record them in the path's
                               3962                 :                :  * skip_mark_restore and materialize_inner fields.
                               3963                 :                :  *
                               3964                 :                :  * Mark/restore overhead is usually required, but can be skipped if we know
                               3965                 :                :  * that the executor need find only one match per outer tuple, and that the
                               3966                 :                :  * mergeclauses are sufficient to identify a match.
                               3967                 :                :  *
                               3968                 :                :  * We materialize the inner path if we need mark/restore and either the inner
                               3969                 :                :  * path can't support mark/restore, or it's cheaper to use an interposed
                               3970                 :                :  * Material node to handle mark/restore.
                               3971                 :                :  *
                               3972                 :                :  * 'path' is already filled in except for the rows and cost fields and
                               3973                 :                :  *      skip_mark_restore and materialize_inner
                               3974                 :                :  * 'workspace' is the result from initial_cost_mergejoin
                               3975                 :                :  * 'extra' contains miscellaneous information about the join
                               3976                 :                :  */
                               3977                 :                : void
                               3978                 :         352656 : final_cost_mergejoin(PlannerInfo *root, MergePath *path,
                               3979                 :                :                      JoinCostWorkspace *workspace,
                               3980                 :                :                      JoinPathExtraData *extra)
                               3981                 :                : {
                               3982                 :         352656 :     Path       *outer_path = path->jpath.outerjoinpath;
                               3983                 :         352656 :     Path       *inner_path = path->jpath.innerjoinpath;
                               3984                 :         352656 :     double      inner_path_rows = inner_path->rows;
                               3985                 :         352656 :     List       *mergeclauses = path->path_mergeclauses;
                               3986                 :         352656 :     List       *innersortkeys = path->innersortkeys;
                               3987                 :         352656 :     Cost        startup_cost = workspace->startup_cost;
                               3988                 :         352656 :     Cost        run_cost = workspace->run_cost;
                               3989                 :         352656 :     Cost        inner_run_cost = workspace->inner_run_cost;
                               3990                 :         352656 :     double      outer_rows = workspace->outer_rows;
                               3991                 :         352656 :     double      inner_rows = workspace->inner_rows;
                               3992                 :         352656 :     double      outer_skip_rows = workspace->outer_skip_rows;
                               3993                 :         352656 :     double      inner_skip_rows = workspace->inner_skip_rows;
                               3994                 :                :     Cost        cpu_per_tuple,
                               3995                 :                :                 bare_inner_cost,
                               3996                 :                :                 mat_inner_cost;
                               3997                 :                :     QualCost    merge_qual_cost;
                               3998                 :                :     QualCost    qp_qual_cost;
                               3999                 :                :     double      mergejointuples,
                               4000                 :                :                 rescannedtuples;
                               4001                 :                :     double      rescanratio;
  179 rhaas@postgresql.org     4002                 :         352656 :     uint64      enable_mask = 0;
                               4003                 :                : 
                               4004                 :                :     /* Protect some assumptions below that rowcounts aren't zero */
 2106 drowley@postgresql.o     4005         [ +  + ]:         352656 :     if (inner_path_rows <= 0)
 5294 tgl@sss.pgh.pa.us        4006                 :             64 :         inner_path_rows = 1;
                               4007                 :                : 
                               4008                 :                :     /* Mark the path with the correct row estimate */
 5211                          4009         [ +  + ]:         352656 :     if (path->jpath.path.param_info)
                               4010                 :           1484 :         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
                               4011                 :                :     else
                               4012                 :         351172 :         path->jpath.path.rows = path->jpath.path.parent->rows;
                               4013                 :                : 
                               4014                 :                :     /* For partial paths, scale row estimate. */
 3481 rhaas@postgresql.org     4015         [ +  + ]:         352656 :     if (path->jpath.path.parallel_workers > 0)
                               4016                 :                :     {
 3357 bruce@momjian.us         4017                 :          47295 :         double      parallel_divisor = get_parallel_divisor(&path->jpath.path);
                               4018                 :                : 
 3420 rhaas@postgresql.org     4019                 :          47295 :         path->jpath.path.rows =
                               4020                 :          47295 :             clamp_row_est(path->jpath.path.rows / parallel_divisor);
                               4021                 :                :     }
                               4022                 :                : 
                               4023                 :                :     /*
                               4024                 :                :      * Compute cost of the mergequals and qpquals (other restriction clauses)
                               4025                 :                :      * separately.
                               4026                 :                :      */
 5294 tgl@sss.pgh.pa.us        4027                 :         352656 :     cost_qual_eval(&merge_qual_cost, mergeclauses, root);
                               4028                 :         352656 :     cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
                               4029                 :         352656 :     qp_qual_cost.startup -= merge_qual_cost.startup;
                               4030                 :         352656 :     qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
                               4031                 :                : 
                               4032                 :                :     /*
                               4033                 :                :      * With a SEMI or ANTI join, or if the innerrel is known unique, the
                               4034                 :                :      * executor will stop scanning for matches after the first match.  When
                               4035                 :                :      * all the joinclauses are merge clauses, this means we don't ever need to
                               4036                 :                :      * back up the merge, and so we can skip mark/restore overhead.
                               4037                 :                :      */
 3397                          4038         [ +  + ]:         352656 :     if ((path->jpath.jointype == JOIN_SEMI ||
                               4039         [ +  + ]:         347966 :          path->jpath.jointype == JOIN_ANTI ||
                               4040   [ +  +  +  + ]:         458307 :          extra->inner_unique) &&
                               4041                 :         127152 :         (list_length(path->jpath.joinrestrictinfo) ==
                               4042                 :         127152 :          list_length(path->path_mergeclauses)))
                               4043                 :         108639 :         path->skip_mark_restore = true;
                               4044                 :                :     else
                               4045                 :         244017 :         path->skip_mark_restore = false;
                               4046                 :                : 
                               4047                 :                :     /*
                               4048                 :                :      * Get approx # tuples passing the mergequals.  We use approx_tuple_count
                               4049                 :                :      * here because we need an estimate done with JOIN_INNER semantics.
                               4050                 :                :      */
 5294                          4051                 :         352656 :     mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
                               4052                 :                : 
                               4053                 :                :     /*
                               4054                 :                :      * When there are equal merge keys in the outer relation, the mergejoin
                               4055                 :                :      * must rescan any matching tuples in the inner relation. This means
                               4056                 :                :      * re-fetching inner tuples; we have to estimate how often that happens.
                               4057                 :                :      *
                               4058                 :                :      * For regular inner and outer joins, the number of re-fetches can be
                               4059                 :                :      * estimated approximately as size of merge join output minus size of
                               4060                 :                :      * inner relation. Assume that the distinct key values are 1, 2, ..., and
                               4061                 :                :      * denote the number of values of each key in the outer relation as m1,
                               4062                 :                :      * m2, ...; in the inner relation, n1, n2, ...  Then we have
                               4063                 :                :      *
                               4064                 :                :      * size of join = m1 * n1 + m2 * n2 + ...
                               4065                 :                :      *
                               4066                 :                :      * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
                               4067                 :                :      * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
                               4068                 :                :      * relation
                               4069                 :                :      *
                               4070                 :                :      * This equation works correctly for outer tuples having no inner match
                               4071                 :                :      * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
                               4072                 :                :      * are effectively subtracting those from the number of rescanned tuples,
                               4073                 :                :      * when we should not.  Can we do better without expensive selectivity
                               4074                 :                :      * computations?
                               4075                 :                :      *
                               4076                 :                :      * The whole issue is moot if we know we don't need to mark/restore at
                               4077                 :                :      * all, or if we are working from a unique-ified outer input.
                               4078                 :                :      */
  341 rguo@postgresql.org      4079         [ +  + ]:         352656 :     if (path->skip_mark_restore ||
                               4080   [ +  +  +  +  :         244017 :         RELATION_WAS_MADE_UNIQUE(outer_path->parent, extra->sjinfo,
                                              +  + ]
                               4081                 :                :                                  path->jpath.jointype))
 5294 tgl@sss.pgh.pa.us        4082                 :         111299 :         rescannedtuples = 0;
                               4083                 :                :     else
                               4084                 :                :     {
                               4085                 :         241357 :         rescannedtuples = mergejointuples - inner_path_rows;
                               4086                 :                :         /* Must clamp because of possible underestimate */
                               4087         [ +  + ]:         241357 :         if (rescannedtuples < 0)
                               4088                 :          60898 :             rescannedtuples = 0;
                               4089                 :                :     }
                               4090                 :                : 
                               4091                 :                :     /*
                               4092                 :                :      * We'll inflate various costs this much to account for rescanning.  Note
                               4093                 :                :      * that this is to be multiplied by something involving inner_rows, or
                               4094                 :                :      * another number related to the portion of the inner rel we'll scan.
                               4095                 :                :      */
 2777                          4096                 :         352656 :     rescanratio = 1.0 + (rescannedtuples / inner_rows);
                               4097                 :                : 
                               4098                 :                :     /*
                               4099                 :                :      * Decide whether we want to materialize the inner input to shield it from
                               4100                 :                :      * mark/restore and performing re-fetches.  Our cost model for regular
                               4101                 :                :      * re-fetches is that a re-fetch costs the same as an original fetch,
                               4102                 :                :      * which is probably an overestimate; but on the other hand we ignore the
                               4103                 :                :      * bookkeeping costs of mark/restore.  Not clear if it's worth developing
                               4104                 :                :      * a more refined model.  So we just need to inflate the inner run cost by
                               4105                 :                :      * rescanratio.
                               4106                 :                :      */
 6097                          4107                 :         352656 :     bare_inner_cost = inner_run_cost * rescanratio;
                               4108                 :                : 
                               4109                 :                :     /*
                               4110                 :                :      * When we interpose a Material node the re-fetch cost is assumed to be
                               4111                 :                :      * just cpu_operator_cost per tuple, independently of the underlying
                               4112                 :                :      * plan's cost; and we charge an extra cpu_operator_cost per original
                               4113                 :                :      * fetch as well.  Note that we're assuming the materialize node will
                               4114                 :                :      * never spill to disk, since it only has to remember tuples back to the
                               4115                 :                :      * last mark.  (If there are a huge number of duplicates, our other cost
                               4116                 :                :      * factors will make the path so expensive that it probably won't get
                               4117                 :                :      * chosen anyway.)  So we don't use cost_rescan here.
                               4118                 :                :      *
                               4119                 :                :      * Note: keep this estimate in sync with create_mergejoin_plan's labeling
                               4120                 :                :      * of the generated Material node.
                               4121                 :                :      */
                               4122                 :         352656 :     mat_inner_cost = inner_run_cost +
 2777                          4123                 :         352656 :         cpu_operator_cost * inner_rows * rescanratio;
                               4124                 :                : 
                               4125                 :                :     /*
                               4126                 :                :      * If we don't need mark/restore at all, we don't need materialization.
                               4127                 :                :      */
 3397                          4128         [ +  + ]:         352656 :     if (path->skip_mark_restore)
                               4129                 :         108639 :         path->materialize_inner = false;
                               4130                 :                : 
                               4131                 :                :     /*
                               4132                 :                :      * If merge joins with materialization are enabled, then choose
                               4133                 :                :      * materialization if either (a) it looks cheaper or (b) merge joins
                               4134                 :                :      * without materialization are disabled.
                               4135                 :                :      */
  179 rhaas@postgresql.org     4136   [ +  +  +  + ]:         244017 :     else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
                               4137                 :         239948 :              (mat_inner_cost < bare_inner_cost ||
                               4138         [ +  + ]:         239948 :               (extra->pgs_mask & PGS_MERGEJOIN_PLAIN) == 0))
 6097 tgl@sss.pgh.pa.us        4139                 :           2697 :         path->materialize_inner = true;
                               4140                 :                : 
                               4141                 :                :     /*
                               4142                 :                :      * Regardless of what plan shapes are enabled and what the costs seem to
                               4143                 :                :      * be, we *must* materialize it if the inner path is to be used directly
                               4144                 :                :      * (without sorting) and it doesn't support mark/restore. Planner failure
                               4145                 :                :      * is not an option!
                               4146                 :                :      *
                               4147                 :                :      * Since the inner side must be ordered, and only Sorts and IndexScans can
                               4148                 :                :      * create order to begin with, and they both support mark/restore, you
                               4149                 :                :      * might think there's no problem --- but you'd be wrong.  Nestloop and
                               4150                 :                :      * merge joins can *preserve* the order of their inputs, so they can be
                               4151                 :                :      * selected as the input of a mergejoin, and they don't support
                               4152                 :                :      * mark/restore at present.
                               4153                 :                :      */
                               4154         [ +  + ]:         241320 :     else if (innersortkeys == NIL &&
 4279 rhaas@postgresql.org     4155         [ +  + ]:           5791 :              !ExecSupportsMarkRestore(inner_path))
 6097 tgl@sss.pgh.pa.us        4156                 :           1281 :         path->materialize_inner = true;
                               4157                 :                : 
                               4158                 :                :     /*
                               4159                 :                :      * Also, force materializing if the inner path is to be sorted and the
                               4160                 :                :      * sort is expected to spill to disk.  This is because the final merge
                               4161                 :                :      * pass can be done on-the-fly if it doesn't have to support mark/restore.
                               4162                 :                :      * We don't try to adjust the cost estimates for this consideration,
                               4163                 :                :      * though.
                               4164                 :                :      *
                               4165                 :                :      * Since materialization is a performance optimization in this case,
                               4166                 :                :      * rather than necessary for correctness, we skip it if materialization is
                               4167                 :                :      * switched off.
                               4168                 :                :      */
  179 rhaas@postgresql.org     4169   [ +  +  +  + ]:         240039 :     else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
                               4170                 :         234178 :              innersortkeys != NIL &&
 3811 tgl@sss.pgh.pa.us        4171                 :         234178 :              relation_byte_size(inner_path_rows,
                               4172                 :         234178 :                                 inner_path->pathtarget->width) >
  541                          4173         [ +  + ]:         234178 :              work_mem * (Size) 1024)
 6097                          4174                 :            164 :         path->materialize_inner = true;
                               4175                 :                :     else
                               4176                 :         239875 :         path->materialize_inner = false;
                               4177                 :                : 
                               4178                 :                :     /* Get the number of disabled nodes, not yet including this one. */
  179 rhaas@postgresql.org     4179                 :         352656 :     path->jpath.path.disabled_nodes = workspace->disabled_nodes;
                               4180                 :                : 
                               4181                 :                :     /*
                               4182                 :                :      * Charge the right incremental cost for the chosen case, and update
                               4183                 :                :      * enable_mask as appropriate.
                               4184                 :                :      */
 6097 tgl@sss.pgh.pa.us        4185         [ +  + ]:         352656 :     if (path->materialize_inner)
                               4186                 :                :     {
                               4187                 :           4142 :         run_cost += mat_inner_cost;
  179 rhaas@postgresql.org     4188                 :           4142 :         enable_mask |= PGS_MERGEJOIN_MATERIALIZE;
                               4189                 :                :     }
                               4190                 :                :     else
                               4191                 :                :     {
 6097 tgl@sss.pgh.pa.us        4192                 :         348514 :         run_cost += bare_inner_cost;
  179 rhaas@postgresql.org     4193                 :         348514 :         enable_mask |= PGS_MERGEJOIN_PLAIN;
                               4194                 :                :     }
                               4195                 :                : 
                               4196                 :                :     /* Incremental count of disabled nodes if this node is disabled. */
                               4197         [ +  + ]:         352656 :     if (path->jpath.path.parallel_workers == 0)
                               4198                 :         305361 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               4199         [ +  + ]:         352656 :     if ((extra->pgs_mask & enable_mask) != enable_mask)
                               4200                 :            562 :         ++path->jpath.path.disabled_nodes;
                               4201                 :                : 
                               4202                 :                :     /* CPU costs */
                               4203                 :                : 
                               4204                 :                :     /*
                               4205                 :                :      * The number of tuple comparisons needed is approximately number of outer
                               4206                 :                :      * rows plus number of inner rows plus number of rescanned tuples (can we
                               4207                 :                :      * refine this?).  At each one, we need to evaluate the mergejoin quals.
                               4208                 :                :      */
 8581 tgl@sss.pgh.pa.us        4209                 :         352656 :     startup_cost += merge_qual_cost.startup;
 6805                          4210                 :         352656 :     startup_cost += merge_qual_cost.per_tuple *
                               4211                 :         352656 :         (outer_skip_rows + inner_skip_rows * rescanratio);
 8581                          4212                 :         352656 :     run_cost += merge_qual_cost.per_tuple *
 6805                          4213                 :         352656 :         ((outer_rows - outer_skip_rows) +
                               4214                 :         352656 :          (inner_rows - inner_skip_rows) * rescanratio);
                               4215                 :                : 
                               4216                 :                :     /*
                               4217                 :                :      * For each tuple that gets through the mergejoin proper, we charge
                               4218                 :                :      * cpu_tuple_cost plus the cost of evaluating additional restriction
                               4219                 :                :      * clauses that are to be applied at the join.  (This is pessimistic since
                               4220                 :                :      * not all of the quals may get evaluated at each tuple.)
                               4221                 :                :      *
                               4222                 :                :      * Note: we could adjust for SEMI/ANTI joins skipping some qual
                               4223                 :                :      * evaluations here, but it's probably not worth the trouble.
                               4224                 :                :      */
 8581                          4225                 :         352656 :     startup_cost += qp_qual_cost.startup;
                               4226                 :         352656 :     cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
 6553                          4227                 :         352656 :     run_cost += cpu_per_tuple * mergejointuples;
                               4228                 :                : 
                               4229                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811                          4230                 :         352656 :     startup_cost += path->jpath.path.pathtarget->cost.startup;
                               4231                 :         352656 :     run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
                               4232                 :                : 
 8581                          4233                 :         352656 :     path->jpath.path.startup_cost = startup_cost;
                               4234                 :         352656 :     path->jpath.path.total_cost = startup_cost + run_cost;
10974 scrappy@hub.org          4235                 :         352656 : }
                               4236                 :                : 
                               4237                 :                : /*
                               4238                 :                :  * run mergejoinscansel() with caching
                               4239                 :                :  */
                               4240                 :                : static MergeScanSelCache *
 6828 bruce@momjian.us         4241                 :        1085992 : cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
                               4242                 :                : {
                               4243                 :                :     MergeScanSelCache *cache;
                               4244                 :                :     ListCell   *lc;
                               4245                 :                :     Selectivity leftstartsel,
                               4246                 :                :                 leftendsel,
                               4247                 :                :                 rightstartsel,
                               4248                 :                :                 rightendsel;
                               4249                 :                :     MemoryContext oldcontext;
                               4250                 :                : 
                               4251                 :                :     /* Do we have this result already? */
 7125 tgl@sss.pgh.pa.us        4252   [ +  +  +  +  :        1085996 :     foreach(lc, rinfo->scansel_cache)
                                              +  + ]
                               4253                 :                :     {
                               4254                 :         983649 :         cache = (MergeScanSelCache *) lfirst(lc);
                               4255         [ +  - ]:         983649 :         if (cache->opfamily == pathkey->pk_opfamily &&
 5608                          4256         [ +  - ]:         983649 :             cache->collation == pathkey->pk_eclass->ec_collation &&
  478 peter@eisentraut.org     4257         [ +  + ]:         983649 :             cache->cmptype == pathkey->pk_cmptype &&
 7125 tgl@sss.pgh.pa.us        4258         [ +  - ]:         983645 :             cache->nulls_first == pathkey->pk_nulls_first)
                               4259                 :         983645 :             return cache;
                               4260                 :                :     }
                               4261                 :                : 
                               4262                 :                :     /* Nope, do the computation */
                               4263                 :         102347 :     mergejoinscansel(root,
                               4264                 :         102347 :                      (Node *) rinfo->clause,
                               4265                 :                :                      pathkey->pk_opfamily,
                               4266                 :                :                      pathkey->pk_cmptype,
                               4267                 :         102347 :                      pathkey->pk_nulls_first,
                               4268                 :                :                      &leftstartsel,
                               4269                 :                :                      &leftendsel,
                               4270                 :                :                      &rightstartsel,
                               4271                 :                :                      &rightendsel);
                               4272                 :                : 
                               4273                 :                :     /* Cache the result in suitably long-lived workspace */
                               4274                 :         102347 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
                               4275                 :                : 
  228 michael@paquier.xyz      4276                 :         102347 :     cache = palloc_object(MergeScanSelCache);
 7125 tgl@sss.pgh.pa.us        4277                 :         102347 :     cache->opfamily = pathkey->pk_opfamily;
 5608                          4278                 :         102347 :     cache->collation = pathkey->pk_eclass->ec_collation;
  478 peter@eisentraut.org     4279                 :         102347 :     cache->cmptype = pathkey->pk_cmptype;
 7125 tgl@sss.pgh.pa.us        4280                 :         102347 :     cache->nulls_first = pathkey->pk_nulls_first;
 6805                          4281                 :         102347 :     cache->leftstartsel = leftstartsel;
                               4282                 :         102347 :     cache->leftendsel = leftendsel;
                               4283                 :         102347 :     cache->rightstartsel = rightstartsel;
                               4284                 :         102347 :     cache->rightendsel = rightendsel;
                               4285                 :                : 
 7125                          4286                 :         102347 :     rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
                               4287                 :                : 
                               4288                 :         102347 :     MemoryContextSwitchTo(oldcontext);
                               4289                 :                : 
                               4290                 :         102347 :     return cache;
                               4291                 :                : }
                               4292                 :                : 
                               4293                 :                : /*
                               4294                 :                :  * initial_cost_hashjoin
                               4295                 :                :  *    Preliminary estimate of the cost of a hashjoin path.
                               4296                 :                :  *
                               4297                 :                :  * This must quickly produce lower-bound estimates of the path's startup and
                               4298                 :                :  * total costs.  If we are unable to eliminate the proposed path from
                               4299                 :                :  * consideration using the lower bounds, final_cost_hashjoin will be called
                               4300                 :                :  * to obtain the final estimates.
                               4301                 :                :  *
                               4302                 :                :  * The exact division of labor between this function and final_cost_hashjoin
                               4303                 :                :  * is private to them, and represents a tradeoff between speed of the initial
                               4304                 :                :  * estimate and getting a tight lower bound.  We choose to not examine the
                               4305                 :                :  * join quals here (other than by counting the number of hash clauses),
                               4306                 :                :  * so we can't do much with CPU costs.  We do assume that
                               4307                 :                :  * ExecChooseHashTableSize is cheap enough to use here.
                               4308                 :                :  *
                               4309                 :                :  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
                               4310                 :                :  *      other data to be used by final_cost_hashjoin
                               4311                 :                :  * 'jointype' is the type of join to be performed
                               4312                 :                :  * 'hashclauses' is the list of joinclauses to be used as hash clauses
                               4313                 :                :  * 'outer_path' is the outer input to the join
                               4314                 :                :  * 'inner_path' is the inner input to the join
                               4315                 :                :  * 'extra' contains miscellaneous information about the join
                               4316                 :                :  * 'parallel_hash' indicates that inner_path is partial and that a shared
                               4317                 :                :  *      hash table will be built in parallel
                               4318                 :                :  */
                               4319                 :                : void
 5294                          4320                 :         642440 : initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
                               4321                 :                :                       JoinType jointype,
                               4322                 :                :                       List *hashclauses,
                               4323                 :                :                       Path *outer_path, Path *inner_path,
                               4324                 :                :                       JoinPathExtraData *extra,
                               4325                 :                :                       bool parallel_hash)
                               4326                 :                : {
                               4327                 :                :     int         disabled_nodes;
 9658                          4328                 :         642440 :     Cost        startup_cost = 0;
                               4329                 :         642440 :     Cost        run_cost = 0;
 5294                          4330                 :         642440 :     double      outer_path_rows = outer_path->rows;
                               4331                 :         642440 :     double      inner_path_rows = inner_path->rows;
 3140 andres@anarazel.de       4332                 :         642440 :     double      inner_path_rows_total = inner_path_rows;
 8092 neilc@samurai.com        4333                 :         642440 :     int         num_hashclauses = list_length(hashclauses);
                               4334                 :                :     int         numbuckets;
                               4335                 :                :     int         numbatches;
                               4336                 :                :     int         num_skew_mcvs;
                               4337                 :                :     size_t      space_allowed;  /* unused */
  179 rhaas@postgresql.org     4338                 :         642440 :     uint64      enable_mask = PGS_HASHJOIN;
                               4339                 :                : 
                               4340         [ +  + ]:         642440 :     if (outer_path->parallel_workers == 0)
                               4341                 :         528302 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
                               4342                 :                : 
                               4343                 :                :     /* Count up disabled nodes. */
                               4344                 :         642440 :     disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
  704                          4345                 :         642440 :     disabled_nodes += inner_path->disabled_nodes;
                               4346                 :         642440 :     disabled_nodes += outer_path->disabled_nodes;
                               4347                 :                : 
                               4348                 :                :     /* cost of source data */
 9658 tgl@sss.pgh.pa.us        4349                 :         642440 :     startup_cost += outer_path->startup_cost;
                               4350                 :         642440 :     run_cost += outer_path->total_cost - outer_path->startup_cost;
                               4351                 :         642440 :     startup_cost += inner_path->total_cost;
                               4352                 :                : 
                               4353                 :                :     /*
                               4354                 :                :      * Cost of computing hash function: must do it once per input tuple. We
                               4355                 :                :      * charge one cpu_operator_cost for each column's hash function.  Also,
                               4356                 :                :      * tack on one cpu_tuple_cost per inner row, to model the costs of
                               4357                 :                :      * inserting the row into the hashtable.
                               4358                 :                :      *
                               4359                 :                :      * XXX when a hashclause is more complex than a single operator, we really
                               4360                 :                :      * should charge the extra eval costs of the left or right side, as
                               4361                 :                :      * appropriate, here.  This seems more work than it's worth at the moment.
                               4362                 :                :      */
 7139                          4363                 :         642440 :     startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
                               4364                 :         642440 :         * inner_path_rows;
 8581                          4365                 :         642440 :     run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
                               4366                 :                : 
                               4367                 :                :     /*
                               4368                 :                :      * If this is a parallel hash build, then the value we have for
                               4369                 :                :      * inner_rows_total currently refers only to the rows returned by each
                               4370                 :                :      * participant.  For shared hash table size estimation, we need the total
                               4371                 :                :      * number, so we need to undo the division.
                               4372                 :                :      */
 3140 andres@anarazel.de       4373         [ +  + ]:         642440 :     if (parallel_hash)
                               4374                 :          57942 :         inner_path_rows_total *= get_parallel_divisor(inner_path);
                               4375                 :                : 
                               4376                 :                :     /*
                               4377                 :                :      * Get hash table size that executor would use for inner relation.
                               4378                 :                :      *
                               4379                 :                :      * XXX for the moment, always assume that skew optimization will be
                               4380                 :                :      * performed.  As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
                               4381                 :                :      * trying to determine that for sure.
                               4382                 :                :      *
                               4383                 :                :      * XXX at some point it might be interesting to try to account for skew
                               4384                 :                :      * optimization in the cost estimate, but for now, we don't.
                               4385                 :                :      */
                               4386                 :         642440 :     ExecChooseHashTableSize(inner_path_rows_total,
 3811 tgl@sss.pgh.pa.us        4387                 :         642440 :                             inner_path->pathtarget->width,
                               4388                 :                :                             true,   /* useskew */
                               4389                 :                :                             parallel_hash,  /* try_combined_hash_mem */
                               4390                 :                :                             outer_path->parallel_workers,
                               4391                 :                :                             &space_allowed,
                               4392                 :                :                             &numbuckets,
                               4393                 :                :                             &numbatches,
                               4394                 :                :                             &num_skew_mcvs);
                               4395                 :                : 
                               4396                 :                :     /*
                               4397                 :                :      * If inner relation is too big then we will need to "batch" the join,
                               4398                 :                :      * which implies writing and reading most of the tuples to disk an extra
                               4399                 :                :      * time.  Charge seq_page_cost per page, since the I/O should be nice and
                               4400                 :                :      * sequential.  Writing the inner rel counts as startup cost, all the rest
                               4401                 :                :      * as run cost.
                               4402                 :                :      */
 5294                          4403         [ +  + ]:         642440 :     if (numbatches > 1)
                               4404                 :                :     {
                               4405                 :           3069 :         double      outerpages = page_size(outer_path_rows,
 3811                          4406                 :           3069 :                                            outer_path->pathtarget->width);
 5294                          4407                 :           3069 :         double      innerpages = page_size(inner_path_rows,
 3811                          4408                 :           3069 :                                            inner_path->pathtarget->width);
                               4409                 :                : 
 5294                          4410                 :           3069 :         startup_cost += seq_page_cost * innerpages;
                               4411                 :           3069 :         run_cost += seq_page_cost * (innerpages + 2 * outerpages);
                               4412                 :                :     }
                               4413                 :                : 
                               4414                 :                :     /* CPU costs left for later */
                               4415                 :                : 
                               4416                 :                :     /* Public result fields */
  704 rhaas@postgresql.org     4417                 :         642440 :     workspace->disabled_nodes = disabled_nodes;
 5294 tgl@sss.pgh.pa.us        4418                 :         642440 :     workspace->startup_cost = startup_cost;
                               4419                 :         642440 :     workspace->total_cost = startup_cost + run_cost;
                               4420                 :                :     /* Save private data for final_cost_hashjoin */
                               4421                 :         642440 :     workspace->run_cost = run_cost;
                               4422                 :         642440 :     workspace->numbuckets = numbuckets;
                               4423                 :         642440 :     workspace->numbatches = numbatches;
 3140 andres@anarazel.de       4424                 :         642440 :     workspace->inner_rows_total = inner_path_rows_total;
 5294 tgl@sss.pgh.pa.us        4425                 :         642440 : }
                               4426                 :                : 
                               4427                 :                : /*
                               4428                 :                :  * final_cost_hashjoin
                               4429                 :                :  *    Final estimate of the cost and result size of a hashjoin path.
                               4430                 :                :  *
                               4431                 :                :  * Note: the numbatches estimate is also saved into 'path' for use later
                               4432                 :                :  *
                               4433                 :                :  * 'path' is already filled in except for the rows and cost fields and
                               4434                 :                :  *      num_batches
                               4435                 :                :  * 'workspace' is the result from initial_cost_hashjoin
                               4436                 :                :  * 'extra' contains miscellaneous information about the join
                               4437                 :                :  */
                               4438                 :                : void
                               4439                 :         350121 : final_cost_hashjoin(PlannerInfo *root, HashPath *path,
                               4440                 :                :                     JoinCostWorkspace *workspace,
                               4441                 :                :                     JoinPathExtraData *extra)
                               4442                 :                : {
                               4443                 :         350121 :     Path       *outer_path = path->jpath.outerjoinpath;
                               4444                 :         350121 :     Path       *inner_path = path->jpath.innerjoinpath;
                               4445                 :         350121 :     double      outer_path_rows = outer_path->rows;
                               4446                 :         350121 :     double      inner_path_rows = inner_path->rows;
 3140 andres@anarazel.de       4447                 :         350121 :     double      inner_path_rows_total = workspace->inner_rows_total;
 5294 tgl@sss.pgh.pa.us        4448                 :         350121 :     List       *hashclauses = path->path_hashclauses;
                               4449                 :         350121 :     Cost        startup_cost = workspace->startup_cost;
                               4450                 :         350121 :     Cost        run_cost = workspace->run_cost;
                               4451                 :         350121 :     int         numbuckets = workspace->numbuckets;
                               4452                 :         350121 :     int         numbatches = workspace->numbatches;
                               4453                 :                :     Cost        cpu_per_tuple;
                               4454                 :                :     QualCost    hash_qual_cost;
                               4455                 :                :     QualCost    qp_qual_cost;
                               4456                 :                :     double      hashjointuples;
                               4457                 :                :     double      virtualbuckets;
                               4458                 :                :     Selectivity innerbucketsize;
                               4459                 :                :     Selectivity innermcvfreq;
                               4460                 :                :     ListCell   *hcl;
                               4461                 :                : 
                               4462                 :                :     /* Set the number of disabled nodes. */
  704 rhaas@postgresql.org     4463                 :         350121 :     path->jpath.path.disabled_nodes = workspace->disabled_nodes;
                               4464                 :                : 
                               4465                 :                :     /* Mark the path with the correct row estimate */
 5211 tgl@sss.pgh.pa.us        4466         [ +  + ]:         350121 :     if (path->jpath.path.param_info)
                               4467                 :           3060 :         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
                               4468                 :                :     else
                               4469                 :         347061 :         path->jpath.path.rows = path->jpath.path.parent->rows;
                               4470                 :                : 
                               4471                 :                :     /* For partial paths, scale row estimate. */
 3481 rhaas@postgresql.org     4472         [ +  + ]:         350121 :     if (path->jpath.path.parallel_workers > 0)
                               4473                 :                :     {
 3357 bruce@momjian.us         4474                 :          81977 :         double      parallel_divisor = get_parallel_divisor(&path->jpath.path);
                               4475                 :                : 
 3420 rhaas@postgresql.org     4476                 :          81977 :         path->jpath.path.rows =
                               4477                 :          81977 :             clamp_row_est(path->jpath.path.rows / parallel_divisor);
                               4478                 :                :     }
                               4479                 :                : 
                               4480                 :                :     /* mark the path with estimated # of batches */
 6331 tgl@sss.pgh.pa.us        4481                 :         350121 :     path->num_batches = numbatches;
                               4482                 :                : 
                               4483                 :                :     /* store the total number of tuples (sum of partial row estimates) */
 3140 andres@anarazel.de       4484                 :         350121 :     path->inner_rows_total = inner_path_rows_total;
                               4485                 :                : 
                               4486                 :                :     /* and compute the number of "virtual" buckets in the whole join */
 3322 tgl@sss.pgh.pa.us        4487                 :         350121 :     virtualbuckets = (double) numbuckets * (double) numbatches;
                               4488                 :                : 
                               4489                 :                :     /*
                               4490                 :                :      * Determine bucketsize fraction and MCV frequency for the inner relation.
                               4491                 :                :      * We use the smallest bucketsize or MCV frequency estimated for any
                               4492                 :                :      * individual hashclause; this is undoubtedly conservative.
                               4493                 :                :      *
                               4494                 :                :      * BUT: if inner relation has been unique-ified, we can assume it's good
                               4495                 :                :      * for hashing.  This is important both because it's the right answer, and
                               4496                 :                :      * because we avoid contaminating the cache with a value that's wrong for
                               4497                 :                :      * non-unique-ified paths.
                               4498                 :                :      */
  341 rguo@postgresql.org      4499   [ +  +  +  +  :         350121 :     if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
                                              +  + ]
                               4500                 :                :                                  path->jpath.jointype))
                               4501                 :                :     {
 8580 tgl@sss.pgh.pa.us        4502                 :           3050 :         innerbucketsize = 1.0 / virtualbuckets;
  209                          4503                 :           3050 :         innermcvfreq = 1.0 / inner_path_rows_total;
                               4504                 :                :     }
                               4505                 :                :     else
                               4506                 :                :     {
                               4507                 :                :         List       *otherclauses;
                               4508                 :                : 
 8580                          4509                 :         347071 :         innerbucketsize = 1.0;
 3267                          4510                 :         347071 :         innermcvfreq = 1.0;
                               4511                 :                : 
                               4512                 :                :         /* At first, try to estimate bucket size using extended statistics. */
  503 akorotkov@postgresql     4513                 :         347071 :         otherclauses = estimate_multivariate_bucketsize(root,
                               4514                 :                :                                                         inner_path->parent,
                               4515                 :                :                                                         hashclauses,
                               4516                 :                :                                                         &innerbucketsize);
                               4517                 :                : 
                               4518                 :                :         /* Pass through the remaining clauses */
                               4519   [ +  +  +  +  :         730045 :         foreach(hcl, otherclauses)
                                              +  + ]
                               4520                 :                :         {
 3394 tgl@sss.pgh.pa.us        4521                 :         382974 :             RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
                               4522                 :                :             Selectivity thisbucketsize;
                               4523                 :                :             Selectivity thismcvfreq;
                               4524                 :                : 
                               4525                 :                :             /*
                               4526                 :                :              * First we have to figure out which side of the hashjoin clause
                               4527                 :                :              * is the inner side.
                               4528                 :                :              *
                               4529                 :                :              * Since we tend to visit the same clauses over and over when
                               4530                 :                :              * planning a large query, we cache the bucket stats estimates in
                               4531                 :                :              * the RestrictInfo node to avoid repeated lookups of statistics.
                               4532                 :                :              */
 8569                          4533         [ +  + ]:         382974 :             if (bms_is_subset(restrictinfo->right_relids,
                               4534                 :         382974 :                               inner_path->parent->relids))
                               4535                 :                :             {
                               4536                 :                :                 /* righthand side is inner */
 8580                          4537                 :         199314 :                 thisbucketsize = restrictinfo->right_bucketsize;
                               4538         [ +  + ]:         199314 :                 if (thisbucketsize < 0)
                               4539                 :                :                 {
                               4540                 :                :                     /* not cached yet */
 3267                          4541                 :          85234 :                     estimate_hash_bucket_stats(root,
                               4542                 :          85234 :                                                get_rightop(restrictinfo->clause),
                               4543                 :                :                                                virtualbuckets,
                               4544                 :                :                                                &restrictinfo->right_mcvfreq,
                               4545                 :                :                                                &restrictinfo->right_bucketsize);
                               4546                 :          85234 :                     thisbucketsize = restrictinfo->right_bucketsize;
                               4547                 :                :                 }
                               4548                 :         199314 :                 thismcvfreq = restrictinfo->right_mcvfreq;
                               4549                 :                :             }
                               4550                 :                :             else
                               4551                 :                :             {
 8569                          4552         [ -  + ]:         183660 :                 Assert(bms_is_subset(restrictinfo->left_relids,
                               4553                 :                :                                      inner_path->parent->relids));
                               4554                 :                :                 /* lefthand side is inner */
 8580                          4555                 :         183660 :                 thisbucketsize = restrictinfo->left_bucketsize;
                               4556         [ +  + ]:         183660 :                 if (thisbucketsize < 0)
                               4557                 :                :                 {
                               4558                 :                :                     /* not cached yet */
 3267                          4559                 :          73403 :                     estimate_hash_bucket_stats(root,
                               4560                 :          73403 :                                                get_leftop(restrictinfo->clause),
                               4561                 :                :                                                virtualbuckets,
                               4562                 :                :                                                &restrictinfo->left_mcvfreq,
                               4563                 :                :                                                &restrictinfo->left_bucketsize);
                               4564                 :          73403 :                     thisbucketsize = restrictinfo->left_bucketsize;
                               4565                 :                :                 }
                               4566                 :         183660 :                 thismcvfreq = restrictinfo->left_mcvfreq;
                               4567                 :                :             }
                               4568                 :                : 
 8580                          4569         [ +  + ]:         382974 :             if (innerbucketsize > thisbucketsize)
                               4570                 :         283833 :                 innerbucketsize = thisbucketsize;
                               4571                 :                :             /* Disregard zero for MCV freq, it means we have no data */
  209                          4572   [ +  +  +  + ]:         382974 :             if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
 3267                          4573                 :         273965 :                 innermcvfreq = thismcvfreq;
                               4574                 :                :         }
                               4575                 :                :     }
                               4576                 :                : 
                               4577                 :                :     /*
                               4578                 :                :      * If the bucket holding the inner MCV would exceed hash_mem, we don't
                               4579                 :                :      * want to hash unless there is really no other alternative, so apply
                               4580                 :                :      * disable_cost.  (The executor normally copes with excessive memory usage
                               4581                 :                :      * by splitting batches, but obviously it cannot separate equal values
                               4582                 :                :      * that way, so it will be unable to drive the batch size below hash_mem
                               4583                 :                :      * when this is true.)
                               4584                 :                :      */
                               4585                 :         350121 :     if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
 1827                          4586         [ +  + ]:         700242 :                            inner_path->pathtarget->width) > get_hash_memory_limit())
 3267                          4587                 :             70 :         startup_cost += disable_cost;
                               4588                 :                : 
                               4589                 :                :     /*
                               4590                 :                :      * Compute cost of the hashquals and qpquals (other restriction clauses)
                               4591                 :                :      * separately.
                               4592                 :                :      */
 5294                          4593                 :         350121 :     cost_qual_eval(&hash_qual_cost, hashclauses, root);
                               4594                 :         350121 :     cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
                               4595                 :         350121 :     qp_qual_cost.startup -= hash_qual_cost.startup;
                               4596                 :         350121 :     qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
                               4597                 :                : 
                               4598                 :                :     /* CPU costs */
                               4599                 :                : 
 3397                          4600         [ +  + ]:         350121 :     if (path->jpath.jointype == JOIN_SEMI ||
                               4601         [ +  + ]:         345723 :         path->jpath.jointype == JOIN_ANTI ||
                               4602         [ +  + ]:         337127 :         extra->inner_unique)
 6287                          4603                 :          96977 :     {
                               4604                 :                :         double      outer_matched_rows;
                               4605                 :                :         Selectivity inner_scan_frac;
                               4606                 :                : 
                               4607                 :                :         /*
                               4608                 :                :          * With a SEMI or ANTI join, or if the innerrel is known unique, the
                               4609                 :                :          * executor will stop after the first match.
                               4610                 :                :          *
                               4611                 :                :          * For an outer-rel row that has at least one match, we can expect the
                               4612                 :                :          * bucket scan to stop after a fraction 1/(match_count+1) of the
                               4613                 :                :          * bucket's rows, if the matches are evenly distributed.  Since they
                               4614                 :                :          * probably aren't quite evenly distributed, we apply a fuzz factor of
                               4615                 :                :          * 2.0 to that fraction.  (If we used a larger fuzz factor, we'd have
                               4616                 :                :          * to clamp inner_scan_frac to at most 1.0; but since match_count is
                               4617                 :                :          * at least 1, no such clamp is needed now.)
                               4618                 :                :          */
 3397                          4619                 :          96977 :         outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
                               4620                 :          96977 :         inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
                               4621                 :                : 
 6287                          4622                 :          96977 :         startup_cost += hash_qual_cost.startup;
                               4623                 :         193954 :         run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
                               4624                 :          96977 :             clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
                               4625                 :                : 
                               4626                 :                :         /*
                               4627                 :                :          * For unmatched outer-rel rows, the picture is quite a lot different.
                               4628                 :                :          * In the first place, there is no reason to assume that these rows
                               4629                 :                :          * preferentially hit heavily-populated buckets; instead assume they
                               4630                 :                :          * are uncorrelated with the inner distribution and so they see an
                               4631                 :                :          * average bucket size of inner_path_rows / virtualbuckets.  In the
                               4632                 :                :          * second place, it seems likely that they will have few if any exact
                               4633                 :                :          * hash-code matches and so very few of the tuples in the bucket will
                               4634                 :                :          * actually require eval of the hash quals.  We don't have any good
                               4635                 :                :          * way to estimate how many will, but for the moment assume that the
                               4636                 :                :          * effective cost per bucket entry is one-tenth what it is for
                               4637                 :                :          * matchable tuples.
                               4638                 :                :          */
                               4639                 :         193954 :         run_cost += hash_qual_cost.per_tuple *
                               4640                 :         193954 :             (outer_path_rows - outer_matched_rows) *
                               4641                 :          96977 :             clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
                               4642                 :                : 
                               4643                 :                :         /* Get # of tuples that will pass the basic join */
 2934                          4644         [ +  + ]:          96977 :         if (path->jpath.jointype == JOIN_ANTI)
 6287                          4645                 :           8596 :             hashjointuples = outer_path_rows - outer_matched_rows;
                               4646                 :                :         else
 2934                          4647                 :          88381 :             hashjointuples = outer_matched_rows;
                               4648                 :                :     }
                               4649                 :                :     else
                               4650                 :                :     {
                               4651                 :                :         /*
                               4652                 :                :          * The number of tuple comparisons needed is the number of outer
                               4653                 :                :          * tuples times the typical number of tuples in a hash bucket, which
                               4654                 :                :          * is the inner relation size times its bucketsize fraction.  At each
                               4655                 :                :          * one, we need to evaluate the hashjoin quals.  But actually,
                               4656                 :                :          * charging the full qual eval cost at each tuple is pessimistic,
                               4657                 :                :          * since we don't evaluate the quals unless the hash values match
                               4658                 :                :          * exactly.  For lack of a better idea, halve the cost estimate to
                               4659                 :                :          * allow for that.
                               4660                 :                :          */
 6287                          4661                 :         253144 :         startup_cost += hash_qual_cost.startup;
                               4662                 :         506288 :         run_cost += hash_qual_cost.per_tuple * outer_path_rows *
                               4663                 :         253144 :             clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
                               4664                 :                : 
                               4665                 :                :         /*
                               4666                 :                :          * Get approx # tuples passing the hashquals.  We use
                               4667                 :                :          * approx_tuple_count here because we need an estimate done with
                               4668                 :                :          * JOIN_INNER semantics.
                               4669                 :                :          */
                               4670                 :         253144 :         hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
                               4671                 :                :     }
                               4672                 :                : 
                               4673                 :                :     /*
                               4674                 :                :      * For each tuple that gets through the hashjoin proper, we charge
                               4675                 :                :      * cpu_tuple_cost plus the cost of evaluating additional restriction
                               4676                 :                :      * clauses that are to be applied at the join.  (This is pessimistic since
                               4677                 :                :      * not all of the quals may get evaluated at each tuple.)
                               4678                 :                :      */
 8581                          4679                 :         350121 :     startup_cost += qp_qual_cost.startup;
                               4680                 :         350121 :     cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
 6553                          4681                 :         350121 :     run_cost += cpu_per_tuple * hashjointuples;
                               4682                 :                : 
                               4683                 :                :     /* tlist eval costs are paid per output row, not per tuple scanned */
 3811                          4684                 :         350121 :     startup_cost += path->jpath.path.pathtarget->cost.startup;
                               4685                 :         350121 :     run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
                               4686                 :                : 
 8581                          4687                 :         350121 :     path->jpath.path.startup_cost = startup_cost;
                               4688                 :         350121 :     path->jpath.path.total_cost = startup_cost + run_cost;
 9658                          4689                 :         350121 : }
                               4690                 :                : 
                               4691                 :                : 
                               4692                 :                : /*
                               4693                 :                :  * cost_subplan
                               4694                 :                :  *      Figure the costs for a SubPlan (or initplan).
                               4695                 :                :  *
                               4696                 :                :  * Note: we could dig the subplan's Plan out of the root list, but in practice
                               4697                 :                :  * all callers have it handy already, so we make them pass it.
                               4698                 :                :  */
                               4699                 :                : void
 6547                          4700                 :          32238 : cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
                               4701                 :                : {
                               4702                 :                :     QualCost    sp_cost;
                               4703                 :                : 
                               4704                 :                :     /*
                               4705                 :                :      * Figure any cost for evaluating the testexpr.
                               4706                 :                :      *
                               4707                 :                :      * Usually, SubPlan nodes are built very early, before we have constructed
                               4708                 :                :      * any RelOptInfos for the parent query level, which means the parent root
                               4709                 :                :      * does not yet contain enough information to safely consult statistics.
                               4710                 :                :      * Therefore, we pass root as NULL here.  cost_qual_eval() is already
                               4711                 :                :      * well-equipped to handle a NULL root.
                               4712                 :                :      *
                               4713                 :                :      * One exception is SubPlan nodes built for the initplans of MIN/MAX
                               4714                 :                :      * aggregates from indexes (cf. SS_make_initplan_from_plan).  In this
                               4715                 :                :      * case, having a NULL root is safe because testexpr will be NULL.
                               4716                 :                :      * Besides, an initplan will by definition not consult anything from the
                               4717                 :                :      * parent plan.
                               4718                 :                :      */
                               4719                 :          32238 :     cost_qual_eval(&sp_cost,
                               4720                 :          32238 :                    make_ands_implicit((Expr *) subplan->testexpr),
                               4721                 :                :                    NULL);
                               4722                 :                : 
                               4723         [ +  + ]:          32238 :     if (subplan->useHashTable)
                               4724                 :                :     {
                               4725                 :                :         /*
                               4726                 :                :          * If we are using a hash table for the subquery outputs, then the
                               4727                 :                :          * cost of evaluating the query is a one-time cost.  We charge one
                               4728                 :                :          * cpu_operator_cost per tuple for the work of loading the hashtable,
                               4729                 :                :          * too.
                               4730                 :                :          */
                               4731                 :           1649 :         sp_cost.startup += plan->total_cost +
                               4732                 :           1649 :             cpu_operator_cost * plan->plan_rows;
                               4733                 :                : 
                               4734                 :                :         /*
                               4735                 :                :          * The per-tuple costs include the cost of evaluating the lefthand
                               4736                 :                :          * expressions, plus the cost of probing the hashtable.  We already
                               4737                 :                :          * accounted for the lefthand expressions as part of the testexpr, and
                               4738                 :                :          * will also have counted one cpu_operator_cost for each comparison
                               4739                 :                :          * operator.  That is probably too low for the probing cost, but it's
                               4740                 :                :          * hard to make a better estimate, so live with it for now.
                               4741                 :                :          */
                               4742                 :                :     }
                               4743                 :                :     else
                               4744                 :                :     {
                               4745                 :                :         /*
                               4746                 :                :          * Otherwise we will be rescanning the subplan output on each
                               4747                 :                :          * evaluation.  We need to estimate how much of the output we will
                               4748                 :                :          * actually need to scan.  NOTE: this logic should agree with the
                               4749                 :                :          * tuple_fraction estimates used by make_subplan() in
                               4750                 :                :          * plan/subselect.c.
                               4751                 :                :          */
                               4752                 :          30589 :         Cost        plan_run_cost = plan->total_cost - plan->startup_cost;
                               4753                 :                : 
                               4754         [ +  + ]:          30589 :         if (subplan->subLinkType == EXISTS_SUBLINK)
                               4755                 :                :         {
                               4756                 :                :             /* we only need to fetch 1 tuple; clamp to avoid zero divide */
 3774                          4757                 :           1740 :             sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
                               4758                 :                :         }
 6547                          4759         [ +  + ]:          28849 :         else if (subplan->subLinkType == ALL_SUBLINK ||
                               4760         [ +  + ]:          28834 :                  subplan->subLinkType == ANY_SUBLINK)
                               4761                 :                :         {
                               4762                 :                :             /* assume we need 50% of the tuples */
                               4763                 :            121 :             sp_cost.per_tuple += 0.50 * plan_run_cost;
                               4764                 :                :             /* also charge a cpu_operator_cost per row examined */
                               4765                 :            121 :             sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
                               4766                 :                :         }
                               4767                 :                :         else
                               4768                 :                :         {
                               4769                 :                :             /* assume we need all tuples */
                               4770                 :          28728 :             sp_cost.per_tuple += plan_run_cost;
                               4771                 :                :         }
                               4772                 :                : 
                               4773                 :                :         /*
                               4774                 :                :          * Also account for subplan's startup cost. If the subplan is
                               4775                 :                :          * uncorrelated or undirect correlated, AND its topmost node is one
                               4776                 :                :          * that materializes its output, assume that we'll only need to pay
                               4777                 :                :          * its startup cost once; otherwise assume we pay the startup cost
                               4778                 :                :          * every time.
                               4779                 :                :          */
                               4780   [ +  +  +  + ]:          39902 :         if (subplan->parParam == NIL &&
 6161                          4781                 :           9313 :             ExecMaterializesOutput(nodeTag(plan)))
 6547                          4782                 :            536 :             sp_cost.startup += plan->startup_cost;
                               4783                 :                :         else
                               4784                 :          30053 :             sp_cost.per_tuple += plan->startup_cost;
                               4785                 :                :     }
                               4786                 :                : 
  128 rhaas@postgresql.org     4787                 :          32238 :     subplan->disabled_nodes = plan->disabled_nodes;
 6547 tgl@sss.pgh.pa.us        4788                 :          32238 :     subplan->startup_cost = sp_cost.startup;
                               4789                 :          32238 :     subplan->per_call_cost = sp_cost.per_tuple;
                               4790                 :          32238 : }
                               4791                 :                : 
                               4792                 :                : 
                               4793                 :                : /*
                               4794                 :                :  * cost_rescan
                               4795                 :                :  *      Given a finished Path, estimate the costs of rescanning it after
                               4796                 :                :  *      having done so the first time.  For some Path types a rescan is
                               4797                 :                :  *      cheaper than an original scan (if no parameters change), and this
                               4798                 :                :  *      function embodies knowledge about that.  The default is to return
                               4799                 :                :  *      the same costs stored in the Path.  (Note that the cost estimates
                               4800                 :                :  *      actually stored in Paths are always for first scans.)
                               4801                 :                :  *
                               4802                 :                :  * This function is not currently intended to model effects such as rescans
                               4803                 :                :  * being cheaper due to disk block caching; what we are concerned with is
                               4804                 :                :  * plan types wherein the executor caches results explicitly, or doesn't
                               4805                 :                :  * redo startup calculations, etc.
                               4806                 :                :  */
                               4807                 :                : static void
 6161                          4808                 :        2557415 : cost_rescan(PlannerInfo *root, Path *path,
                               4809                 :                :             Cost *rescan_startup_cost,  /* output parameters */
                               4810                 :                :             Cost *rescan_total_cost)
                               4811                 :                : {
                               4812   [ +  +  +  +  :        2557415 :     switch (path->pathtype)
                                              +  + ]
                               4813                 :                :     {
                               4814                 :          30474 :         case T_FunctionScan:
                               4815                 :                : 
                               4816                 :                :             /*
                               4817                 :                :              * Currently, nodeFunctionscan.c always executes the function to
                               4818                 :                :              * completion before returning any rows, and caches the results in
                               4819                 :                :              * a tuplestore.  So the function eval cost is all startup cost
                               4820                 :                :              * and isn't paid over again on rescans. However, all run costs
                               4821                 :                :              * will be paid over again.
                               4822                 :                :              */
                               4823                 :          30474 :             *rescan_startup_cost = 0;
                               4824                 :          30474 :             *rescan_total_cost = path->total_cost - path->startup_cost;
                               4825                 :          30474 :             break;
                               4826                 :          94360 :         case T_HashJoin:
                               4827                 :                : 
                               4828                 :                :             /*
                               4829                 :                :              * If it's a single-batch join, we don't need to rebuild the hash
                               4830                 :                :              * table during a rescan.
                               4831                 :                :              */
 3651                          4832         [ +  - ]:          94360 :             if (((HashPath *) path)->num_batches == 1)
                               4833                 :                :             {
                               4834                 :                :                 /* Startup cost is exactly the cost of hash table building */
                               4835                 :          94360 :                 *rescan_startup_cost = 0;
                               4836                 :          94360 :                 *rescan_total_cost = path->total_cost - path->startup_cost;
                               4837                 :                :             }
                               4838                 :                :             else
                               4839                 :                :             {
                               4840                 :                :                 /* Otherwise, no special treatment */
 3651 tgl@sss.pgh.pa.us        4841                 :UBC           0 :                 *rescan_startup_cost = path->startup_cost;
                               4842                 :              0 :                 *rescan_total_cost = path->total_cost;
                               4843                 :                :             }
 6161 tgl@sss.pgh.pa.us        4844                 :CBC       94360 :             break;
                               4845                 :           4448 :         case T_CteScan:
                               4846                 :                :         case T_WorkTableScan:
                               4847                 :                :             {
                               4848                 :                :                 /*
                               4849                 :                :                  * These plan types materialize their final result in a
                               4850                 :                :                  * tuplestore or tuplesort object.  So the rescan cost is only
                               4851                 :                :                  * cpu_tuple_cost per tuple, unless the result is large enough
                               4852                 :                :                  * to spill to disk.
                               4853                 :                :                  */
 5294                          4854                 :           4448 :                 Cost        run_cost = cpu_tuple_cost * path->rows;
                               4855                 :           4448 :                 double      nbytes = relation_byte_size(path->rows,
 3322                          4856                 :           4448 :                                                         path->pathtarget->width);
  541                          4857                 :           4448 :                 double      work_mem_bytes = work_mem * (Size) 1024;
                               4858                 :                : 
 6161                          4859         [ +  + ]:           4448 :                 if (nbytes > work_mem_bytes)
                               4860                 :                :                 {
                               4861                 :                :                     /* It will spill, so account for re-read cost */
                               4862                 :            192 :                     double      npages = ceil(nbytes / BLCKSZ);
                               4863                 :                : 
                               4864                 :            192 :                     run_cost += seq_page_cost * npages;
                               4865                 :                :                 }
                               4866                 :           4448 :                 *rescan_startup_cost = 0;
                               4867                 :           4448 :                 *rescan_total_cost = run_cost;
                               4868                 :                :             }
                               4869                 :           4448 :             break;
 6001                          4870                 :         878796 :         case T_Material:
                               4871                 :                :         case T_Sort:
                               4872                 :                :             {
                               4873                 :                :                 /*
                               4874                 :                :                  * These plan types not only materialize their results, but do
                               4875                 :                :                  * not implement qual filtering or projection.  So they are
                               4876                 :                :                  * even cheaper to rescan than the ones above.  We charge only
                               4877                 :                :                  * cpu_operator_cost per tuple.  (Note: keep that in sync with
                               4878                 :                :                  * the run_cost charge in cost_sort, and also see comments in
                               4879                 :                :                  * cost_material before you change it.)
                               4880                 :                :                  */
 5294                          4881                 :         878796 :                 Cost        run_cost = cpu_operator_cost * path->rows;
                               4882                 :         878796 :                 double      nbytes = relation_byte_size(path->rows,
 3322                          4883                 :         878796 :                                                         path->pathtarget->width);
  541                          4884                 :         878796 :                 double      work_mem_bytes = work_mem * (Size) 1024;
                               4885                 :                : 
 6001                          4886         [ +  + ]:         878796 :                 if (nbytes > work_mem_bytes)
                               4887                 :                :                 {
                               4888                 :                :                     /* It will spill, so account for re-read cost */
                               4889                 :           6006 :                     double      npages = ceil(nbytes / BLCKSZ);
                               4890                 :                : 
                               4891                 :           6006 :                     run_cost += seq_page_cost * npages;
                               4892                 :                :                 }
                               4893                 :         878796 :                 *rescan_startup_cost = 0;
                               4894                 :         878796 :                 *rescan_total_cost = run_cost;
                               4895                 :                :             }
                               4896                 :         878796 :             break;
 1838 drowley@postgresql.o     4897                 :         191620 :         case T_Memoize:
                               4898                 :                :             /* All the hard work is done by cost_memoize_rescan */
                               4899                 :         191620 :             cost_memoize_rescan(root, (MemoizePath *) path,
                               4900                 :                :                                 rescan_startup_cost, rescan_total_cost);
 1941                          4901                 :         191620 :             break;
 6161 tgl@sss.pgh.pa.us        4902                 :        1357717 :         default:
                               4903                 :        1357717 :             *rescan_startup_cost = path->startup_cost;
                               4904                 :        1357717 :             *rescan_total_cost = path->total_cost;
                               4905                 :        1357717 :             break;
                               4906                 :                :     }
                               4907                 :        2557415 : }
                               4908                 :                : 
                               4909                 :                : 
                               4910                 :                : /*
                               4911                 :                :  * cost_qual_eval
                               4912                 :                :  *      Estimate the CPU costs of evaluating a WHERE clause.
                               4913                 :                :  *      The input can be either an implicitly-ANDed list of boolean
                               4914                 :                :  *      expressions, or a list of RestrictInfo nodes.  (The latter is
                               4915                 :                :  *      preferred since it allows caching of the results.)
                               4916                 :                :  *      The result includes both a one-time (startup) component,
                               4917                 :                :  *      and a per-evaluation component.
                               4918                 :                :  *
                               4919                 :                :  * Note: in some code paths root can be passed as NULL, resulting in
                               4920                 :                :  * slightly worse estimates.
                               4921                 :                :  */
                               4922                 :                : void
 7094                          4923                 :        3692530 : cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
                               4924                 :                : {
                               4925                 :                :     cost_qual_eval_context context;
                               4926                 :                :     ListCell   *l;
                               4927                 :                : 
                               4928                 :        3692530 :     context.root = root;
                               4929                 :        3692530 :     context.total.startup = 0;
                               4930                 :        3692530 :     context.total.per_tuple = 0;
                               4931                 :                : 
                               4932                 :                :     /* We don't charge any cost for the implicit ANDing at top level ... */
                               4933                 :                : 
 9357                          4934   [ +  +  +  +  :        7127047 :     foreach(l, quals)
                                              +  + ]
                               4935                 :                :     {
 9257 bruce@momjian.us         4936                 :        3434517 :         Node       *qual = (Node *) lfirst(l);
                               4937                 :                : 
 7094 tgl@sss.pgh.pa.us        4938                 :        3434517 :         cost_qual_eval_walker(qual, &context);
                               4939                 :                :     }
                               4940                 :                : 
                               4941                 :        3692530 :     *cost = context.total;
 9658                          4942                 :        3692530 : }
                               4943                 :                : 
                               4944                 :                : /*
                               4945                 :                :  * cost_qual_eval_node
                               4946                 :                :  *      As above, for a single RestrictInfo or expression.
                               4947                 :                :  */
                               4948                 :                : void
 7094                          4949                 :        1440982 : cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
                               4950                 :                : {
                               4951                 :                :     cost_qual_eval_context context;
                               4952                 :                : 
                               4953                 :        1440982 :     context.root = root;
                               4954                 :        1440982 :     context.total.startup = 0;
                               4955                 :        1440982 :     context.total.per_tuple = 0;
                               4956                 :                : 
                               4957                 :        1440982 :     cost_qual_eval_walker(qual, &context);
                               4958                 :                : 
                               4959                 :        1440982 :     *cost = context.total;
 7125                          4960                 :        1440982 : }
                               4961                 :                : 
                               4962                 :                : static bool
 6828 bruce@momjian.us         4963                 :        7622876 : cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
                               4964                 :                : {
 9658 tgl@sss.pgh.pa.us        4965         [ +  + ]:        7622876 :     if (node == NULL)
                               4966                 :          78283 :         return false;
                               4967                 :                : 
                               4968                 :                :     /*
                               4969                 :                :      * RestrictInfo nodes contain an eval_cost field reserved for this
                               4970                 :                :      * routine's use, so that it's not necessary to evaluate the qual clause's
                               4971                 :                :      * cost more than once.  If the clause's cost hasn't been computed yet,
                               4972                 :                :      * the field's startup value will contain -1.
                               4973                 :                :      */
 7125                          4974         [ +  + ]:        7544593 :     if (IsA(node, RestrictInfo))
                               4975                 :                :     {
                               4976                 :        3591544 :         RestrictInfo *rinfo = (RestrictInfo *) node;
                               4977                 :                : 
                               4978         [ +  + ]:        3591544 :         if (rinfo->eval_cost.startup < 0)
                               4979                 :                :         {
                               4980                 :                :             cost_qual_eval_context locContext;
                               4981                 :                : 
 7094                          4982                 :         465455 :             locContext.root = context->root;
                               4983                 :         465455 :             locContext.total.startup = 0;
                               4984                 :         465455 :             locContext.total.per_tuple = 0;
                               4985                 :                : 
                               4986                 :                :             /*
                               4987                 :                :              * For an OR clause, recurse into the marked-up tree so that we
                               4988                 :                :              * set the eval_cost for contained RestrictInfos too.
                               4989                 :                :              */
 7125                          4990         [ +  + ]:         465455 :             if (rinfo->orclause)
 7094                          4991                 :           8129 :                 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
                               4992                 :                :             else
                               4993                 :         457326 :                 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
                               4994                 :                : 
                               4995                 :                :             /*
                               4996                 :                :              * If the RestrictInfo is marked pseudoconstant, it will be tested
                               4997                 :                :              * only once, so treat its cost as all startup cost.
                               4998                 :                :              */
 7125                          4999         [ +  + ]:         465455 :             if (rinfo->pseudoconstant)
                               5000                 :                :             {
                               5001                 :                :                 /* count one execution during startup */
 7094                          5002                 :           8611 :                 locContext.total.startup += locContext.total.per_tuple;
                               5003                 :           8611 :                 locContext.total.per_tuple = 0;
                               5004                 :                :             }
                               5005                 :         465455 :             rinfo->eval_cost = locContext.total;
                               5006                 :                :         }
                               5007                 :        3591544 :         context->total.startup += rinfo->eval_cost.startup;
                               5008                 :        3591544 :         context->total.per_tuple += rinfo->eval_cost.per_tuple;
                               5009                 :                :         /* do NOT recurse into children */
 7125                          5010                 :        3591544 :         return false;
                               5011                 :                :     }
                               5012                 :                : 
                               5013                 :                :     /*
                               5014                 :                :      * For each operator or function node in the given tree, we charge the
                               5015                 :                :      * estimated execution cost given by pg_proc.procost (remember to multiply
                               5016                 :                :      * this by cpu_operator_cost).
                               5017                 :                :      *
                               5018                 :                :      * Vars and Consts are charged zero, and so are boolean operators (AND,
                               5019                 :                :      * OR, NOT). Simplistic, but a lot better than no model at all.
                               5020                 :                :      *
                               5021                 :                :      * Should we try to account for the possibility of short-circuit
                               5022                 :                :      * evaluation of AND/OR?  Probably *not*, because that would make the
                               5023                 :                :      * results depend on the clause ordering, and we are not in any position
                               5024                 :                :      * to expect that the current ordering of the clauses is the one that's
                               5025                 :                :      * going to end up being used.  The above per-RestrictInfo caching would
                               5026                 :                :      * not mix well with trying to re-order clauses anyway.
                               5027                 :                :      *
                               5028                 :                :      * Another issue that is entirely ignored here is that if a set-returning
                               5029                 :                :      * function is below top level in the tree, the functions/operators above
                               5030                 :                :      * it will need to be evaluated multiple times.  In practical use, such
                               5031                 :                :      * cases arise so seldom as to not be worth the added complexity needed;
                               5032                 :                :      * moreover, since our rowcount estimates for functions tend to be pretty
                               5033                 :                :      * phony, the results would also be pretty phony.
                               5034                 :                :      */
                               5035         [ +  + ]:        3953049 :     if (IsA(node, FuncExpr))
                               5036                 :                :     {
 2724                          5037                 :         254108 :         add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
                               5038                 :                :                           &context->total);
                               5039                 :                :     }
 7125                          5040         [ +  + ]:        3698941 :     else if (IsA(node, OpExpr) ||
                               5041         [ +  + ]:        3179181 :              IsA(node, DistinctExpr) ||
                               5042         [ +  + ]:        3178546 :              IsA(node, NullIfExpr))
                               5043                 :                :     {
                               5044                 :                :         /* rely on struct equivalence to treat these all alike */
                               5045                 :         520639 :         set_opfuncid((OpExpr *) node);
 2724                          5046                 :         520639 :         add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
                               5047                 :                :                           &context->total);
                               5048                 :                :     }
 8428                          5049         [ +  + ]:        3178302 :     else if (IsA(node, ScalarArrayOpExpr))
                               5050                 :                :     {
 7547                          5051                 :          34317 :         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
 7235 bruce@momjian.us         5052                 :          34317 :         Node       *arraynode = (Node *) lsecond(saop->args);
                               5053                 :                :         QualCost    sacosts;
                               5054                 :                :         QualCost    hcosts;
  934 tgl@sss.pgh.pa.us        5055                 :          34317 :         double      estarraylen = estimate_array_length(context->root, arraynode);
                               5056                 :                : 
 7125                          5057                 :          34317 :         set_sa_opfuncid(saop);
 2724                          5058                 :          34317 :         sacosts.startup = sacosts.per_tuple = 0;
                               5059                 :          34317 :         add_function_cost(context->root, saop->opfuncid, NULL,
                               5060                 :                :                           &sacosts);
                               5061                 :                : 
 1935 drowley@postgresql.o     5062         [ +  + ]:          34317 :         if (OidIsValid(saop->hashfuncid))
                               5063                 :                :         {
                               5064                 :                :             /* Handle costs for hashed ScalarArrayOpExpr */
                               5065                 :            245 :             hcosts.startup = hcosts.per_tuple = 0;
                               5066                 :                : 
                               5067                 :            245 :             add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
                               5068                 :            245 :             context->total.startup += sacosts.startup + hcosts.startup;
                               5069                 :                : 
                               5070                 :                :             /* Estimate the cost of building the hashtable. */
                               5071                 :            245 :             context->total.startup += estarraylen * hcosts.per_tuple;
                               5072                 :                : 
                               5073                 :                :             /*
                               5074                 :                :              * XXX should we charge a little bit for sacosts.per_tuple when
                               5075                 :                :              * building the table, or is it ok to assume there will be zero
                               5076                 :                :              * hash collision?
                               5077                 :                :              */
                               5078                 :                : 
                               5079                 :                :             /*
                               5080                 :                :              * Charge for hashtable lookups.  Charge a single hash and a
                               5081                 :                :              * single comparison.
                               5082                 :                :              */
                               5083                 :            245 :             context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
                               5084                 :                :         }
                               5085                 :                :         else
                               5086                 :                :         {
                               5087                 :                :             /*
                               5088                 :                :              * Estimate that the operator will be applied to about half of the
                               5089                 :                :              * array elements before the answer is determined.
                               5090                 :                :              */
                               5091                 :          34072 :             context->total.startup += sacosts.startup;
                               5092                 :          68144 :             context->total.per_tuple += sacosts.per_tuple *
  934 tgl@sss.pgh.pa.us        5093                 :          34072 :                 estimate_array_length(context->root, arraynode) * 0.5;
                               5094                 :                :         }
                               5095                 :                :     }
 5572                          5096         [ +  + ]:        3143985 :     else if (IsA(node, Aggref) ||
                               5097         [ +  + ]:        3088452 :              IsA(node, WindowFunc))
                               5098                 :                :     {
                               5099                 :                :         /*
                               5100                 :                :          * Aggref and WindowFunc nodes are (and should be) treated like Vars,
                               5101                 :                :          * ie, zero execution cost in the current model, because they behave
                               5102                 :                :          * essentially like Vars at execution.  We disregard the costs of
                               5103                 :                :          * their input expressions for the same reason.  The actual execution
                               5104                 :                :          * costs of the aggregate/window functions and their arguments have to
                               5105                 :                :          * be factored into plan-node-specific costing of the Agg or WindowAgg
                               5106                 :                :          * plan node.
                               5107                 :                :          */
                               5108                 :          59002 :         return false;           /* don't recurse into children */
                               5109                 :                :     }
 1588                          5110         [ +  + ]:        3084983 :     else if (IsA(node, GroupingFunc))
                               5111                 :                :     {
                               5112                 :                :         /* Treat this as having cost 1 */
                               5113                 :            358 :         context->total.per_tuple += cpu_operator_cost;
                               5114                 :            358 :         return false;           /* don't recurse into children */
                               5115                 :                :     }
 6991                          5116         [ +  + ]:        3084625 :     else if (IsA(node, CoerceViaIO))
                               5117                 :                :     {
                               5118                 :          20102 :         CoerceViaIO *iocoerce = (CoerceViaIO *) node;
                               5119                 :                :         Oid         iofunc;
                               5120                 :                :         Oid         typioparam;
                               5121                 :                :         bool        typisvarlena;
                               5122                 :                : 
                               5123                 :                :         /* check the result type's input function */
                               5124                 :          20102 :         getTypeInputInfo(iocoerce->resulttype,
                               5125                 :                :                          &iofunc, &typioparam);
 2724                          5126                 :          20102 :         add_function_cost(context->root, iofunc, NULL,
                               5127                 :                :                           &context->total);
                               5128                 :                :         /* check the input type's output function */
 6991                          5129                 :          20102 :         getTypeOutputInfo(exprType((Node *) iocoerce->arg),
                               5130                 :                :                           &iofunc, &typisvarlena);
 2724                          5131                 :          20102 :         add_function_cost(context->root, iofunc, NULL,
                               5132                 :                :                           &context->total);
                               5133                 :                :     }
 7061                          5134         [ +  + ]:        3064523 :     else if (IsA(node, ArrayCoerceExpr))
                               5135                 :                :     {
                               5136                 :           3910 :         ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
                               5137                 :                :         QualCost    perelemcost;
                               5138                 :                : 
 3221                          5139                 :           3910 :         cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
                               5140                 :                :                             context->root);
                               5141                 :           3910 :         context->total.startup += perelemcost.startup;
                               5142         [ +  + ]:           3910 :         if (perelemcost.per_tuple > 0)
                               5143                 :             52 :             context->total.per_tuple += perelemcost.per_tuple *
  934                          5144                 :             52 :                 estimate_array_length(context->root, (Node *) acoerce->arg);
                               5145                 :                :     }
 7515                          5146         [ +  + ]:        3060613 :     else if (IsA(node, RowCompareExpr))
                               5147                 :                :     {
                               5148                 :                :         /* Conservatively assume we will check all the columns */
                               5149                 :            235 :         RowCompareExpr *rcexpr = (RowCompareExpr *) node;
                               5150                 :                :         ListCell   *lc;
                               5151                 :                : 
 7125                          5152   [ +  -  +  +  :            750 :         foreach(lc, rcexpr->opnos)
                                              +  + ]
                               5153                 :                :         {
 6828 bruce@momjian.us         5154                 :            515 :             Oid         opid = lfirst_oid(lc);
                               5155                 :                : 
 2724 tgl@sss.pgh.pa.us        5156                 :            515 :             add_function_cost(context->root, get_opcode(opid), NULL,
                               5157                 :                :                               &context->total);
                               5158                 :                :         }
                               5159                 :                :     }
 3299                          5160         [ +  + ]:        3060378 :     else if (IsA(node, MinMaxExpr) ||
 1166 michael@paquier.xyz      5161         [ +  + ]:        3060155 :              IsA(node, SQLValueFunction) ||
 3299 tgl@sss.pgh.pa.us        5162         [ +  + ]:        3056363 :              IsA(node, XmlExpr) ||
                               5163         [ +  + ]:        3055778 :              IsA(node, CoerceToDomain) ||
  857 amitlan@postgresql.o     5164         [ +  + ]:        3049222 :              IsA(node, NextValueExpr) ||
                               5165         [ +  + ]:        3048893 :              IsA(node, JsonExpr))
                               5166                 :                :     {
                               5167                 :                :         /* Treat all these as having cost 1 */
 3299 tgl@sss.pgh.pa.us        5168                 :          14059 :         context->total.per_tuple += cpu_operator_cost;
                               5169                 :                :     }
 8596                          5170         [ -  + ]:        3046319 :     else if (IsA(node, SubLink))
                               5171                 :                :     {
                               5172                 :                :         /* This routine should not be applied to un-planned expressions */
 8402 tgl@sss.pgh.pa.us        5173         [ #  # ]:UBC           0 :         elog(ERROR, "cannot handle unplanned sub-select");
                               5174                 :                :     }
 8625 tgl@sss.pgh.pa.us        5175         [ +  + ]:CBC     3046319 :     else if (IsA(node, SubPlan))
                               5176                 :                :     {
                               5177                 :                :         /*
                               5178                 :                :          * A subplan node in an expression typically indicates that the
                               5179                 :                :          * subplan will be executed on each evaluation, so charge accordingly.
                               5180                 :                :          * (Sub-selects that can be executed as InitPlans have already been
                               5181                 :                :          * removed from the expression.)
                               5182                 :                :          */
 8392 bruce@momjian.us         5183                 :          33166 :         SubPlan    *subplan = (SubPlan *) node;
                               5184                 :                : 
 6547 tgl@sss.pgh.pa.us        5185                 :          33166 :         context->total.startup += subplan->startup_cost;
                               5186                 :          33166 :         context->total.per_tuple += subplan->per_call_cost;
                               5187                 :                : 
                               5188                 :                :         /*
                               5189                 :                :          * We don't want to recurse into the testexpr, because it was already
                               5190                 :                :          * counted in the SubPlan node's costs.  So we're done.
                               5191                 :                :          */
                               5192                 :          33166 :         return false;
                               5193                 :                :     }
                               5194         [ +  + ]:        3013153 :     else if (IsA(node, AlternativeSubPlan))
                               5195                 :                :     {
                               5196                 :                :         /*
                               5197                 :                :          * Arbitrarily use the first alternative plan for costing.  (We should
                               5198                 :                :          * certainly only include one alternative, and we don't yet have
                               5199                 :                :          * enough information to know which one the executor is most likely to
                               5200                 :                :          * use.)
                               5201                 :                :          */
                               5202                 :           1382 :         AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
                               5203                 :                : 
                               5204                 :           1382 :         return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
                               5205                 :                :                                      context);
                               5206                 :                :     }
 3811                          5207         [ +  + ]:        3011771 :     else if (IsA(node, PlaceHolderVar))
                               5208                 :                :     {
                               5209                 :                :         /*
                               5210                 :                :          * A PlaceHolderVar should be given cost zero when considering general
                               5211                 :                :          * expression evaluation costs.  The expense of doing the contained
                               5212                 :                :          * expression is charged as part of the tlist eval costs of the scan
                               5213                 :                :          * or join where the PHV is first computed (see set_rel_width and
                               5214                 :                :          * add_placeholders_to_joinrel).  If we charged it again here, we'd be
                               5215                 :                :          * double-counting the cost for each level of plan that the PHV
                               5216                 :                :          * bubbles up through.  Hence, return without recursing into the
                               5217                 :                :          * phexpr.
                               5218                 :                :          */
                               5219                 :           5019 :         return false;
                               5220                 :                :     }
                               5221                 :                : 
                               5222                 :                :     /* recurse into children */
  605 peter@eisentraut.org     5223                 :        3854122 :     return expression_tree_walker(node, cost_qual_eval_walker, context);
                               5224                 :                : }
                               5225                 :                : 
                               5226                 :                : /*
                               5227                 :                :  * get_restriction_qual_cost
                               5228                 :                :  *    Compute evaluation costs of a baserel's restriction quals, plus any
                               5229                 :                :  *    movable join quals that have been pushed down to the scan.
                               5230                 :                :  *    Results are returned into *qpqual_cost.
                               5231                 :                :  *
                               5232                 :                :  * This is a convenience subroutine that works for seqscans and other cases
                               5233                 :                :  * where all the given quals will be evaluated the hard way.  It's not useful
                               5234                 :                :  * for cost_index(), for example, where the index machinery takes care of
                               5235                 :                :  * some of the quals.  We assume baserestrictcost was previously set by
                               5236                 :                :  * set_baserel_size_estimates().
                               5237                 :                :  */
                               5238                 :                : static void
 5211 tgl@sss.pgh.pa.us        5239                 :         884223 : get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
                               5240                 :                :                           ParamPathInfo *param_info,
                               5241                 :                :                           QualCost *qpqual_cost)
                               5242                 :                : {
                               5243         [ +  + ]:         884223 :     if (param_info)
                               5244                 :                :     {
                               5245                 :                :         /* Include costs of pushed-down clauses */
                               5246                 :         226190 :         cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
                               5247                 :                : 
                               5248                 :         226190 :         qpqual_cost->startup += baserel->baserestrictcost.startup;
                               5249                 :         226190 :         qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
                               5250                 :                :     }
                               5251                 :                :     else
                               5252                 :         658033 :         *qpqual_cost = baserel->baserestrictcost;
                               5253                 :         884223 : }
                               5254                 :                : 
                               5255                 :                : 
                               5256                 :                : /*
                               5257                 :                :  * compute_semi_anti_join_factors
                               5258                 :                :  *    Estimate how much of the inner input a SEMI, ANTI, or inner_unique join
                               5259                 :                :  *    can be expected to scan.
                               5260                 :                :  *
                               5261                 :                :  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
                               5262                 :                :  * inner rows as soon as it finds a match to the current outer row.
                               5263                 :                :  * The same happens if we have detected the inner rel is unique.
                               5264                 :                :  * We should therefore adjust some of the cost components for this effect.
                               5265                 :                :  * This function computes some estimates needed for these adjustments.
                               5266                 :                :  * These estimates will be the same regardless of the particular paths used
                               5267                 :                :  * for the outer and inner relation, so we compute these once and then pass
                               5268                 :                :  * them to all the join cost estimation functions.
                               5269                 :                :  *
                               5270                 :                :  * Input parameters:
                               5271                 :                :  *  joinrel: join relation under consideration
                               5272                 :                :  *  outerrel: outer relation under consideration
                               5273                 :                :  *  innerrel: inner relation under consideration
                               5274                 :                :  *  jointype: if not JOIN_SEMI or JOIN_ANTI, we assume it's inner_unique
                               5275                 :                :  *  sjinfo: SpecialJoinInfo relevant to this join
                               5276                 :                :  *  restrictlist: join quals
                               5277                 :                :  * Output parameters:
                               5278                 :                :  *  *semifactors is filled in (see pathnodes.h for field definitions)
                               5279                 :                :  */
                               5280                 :                : void
 5294                          5281                 :         186896 : compute_semi_anti_join_factors(PlannerInfo *root,
                               5282                 :                :                                RelOptInfo *joinrel,
                               5283                 :                :                                RelOptInfo *outerrel,
                               5284                 :                :                                RelOptInfo *innerrel,
                               5285                 :                :                                JoinType jointype,
                               5286                 :                :                                SpecialJoinInfo *sjinfo,
                               5287                 :                :                                List *restrictlist,
                               5288                 :                :                                SemiAntiJoinFactors *semifactors)
                               5289                 :                : {
                               5290                 :                :     Selectivity jselec;
                               5291                 :                :     Selectivity nselec;
                               5292                 :                :     Selectivity avgmatch;
                               5293                 :                :     SpecialJoinInfo norm_sjinfo;
                               5294                 :                :     List       *joinquals;
                               5295                 :                :     ListCell   *l;
                               5296                 :                : 
                               5297                 :                :     /*
                               5298                 :                :      * In an ANTI join, we must ignore clauses that are "pushed down", since
                               5299                 :                :      * those won't affect the match logic.  In a SEMI join, we do not
                               5300                 :                :      * distinguish joinquals from "pushed down" quals, so just use the whole
                               5301                 :                :      * restrictinfo list.  For other outer join types, we should consider only
                               5302                 :                :      * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
                               5303                 :                :      */
 3397                          5304         [ +  + ]:         186896 :     if (IS_OUTER_JOIN(jointype))
                               5305                 :                :     {
 6287                          5306                 :          61696 :         joinquals = NIL;
 5294                          5307   [ +  +  +  +  :         142646 :         foreach(l, restrictlist)
                                              +  + ]
                               5308                 :                :         {
 3394                          5309                 :          80950 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
                               5310                 :                : 
 3019                          5311   [ +  +  +  - ]:          80950 :             if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
 6287                          5312                 :          73154 :                 joinquals = lappend(joinquals, rinfo);
                               5313                 :                :         }
                               5314                 :                :     }
                               5315                 :                :     else
 5294                          5316                 :         125200 :         joinquals = restrictlist;
                               5317                 :                : 
                               5318                 :                :     /*
                               5319                 :                :      * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
                               5320                 :                :      */
 6287                          5321         [ +  + ]:         186896 :     jselec = clauselist_selectivity(root,
                               5322                 :                :                                     joinquals,
                               5323                 :                :                                     0,
                               5324                 :                :                                     (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
                               5325                 :                :                                     sjinfo);
                               5326                 :                : 
                               5327                 :                :     /*
                               5328                 :                :      * Also get the normal inner-join selectivity of the join clauses.
                               5329                 :                :      */
  853 amitlan@postgresql.o     5330                 :         186896 :     init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
                               5331                 :                : 
 6287 tgl@sss.pgh.pa.us        5332                 :         186896 :     nselec = clauselist_selectivity(root,
                               5333                 :                :                                     joinquals,
                               5334                 :                :                                     0,
                               5335                 :                :                                     JOIN_INNER,
                               5336                 :                :                                     &norm_sjinfo);
                               5337                 :                : 
                               5338                 :                :     /* Avoid leaking a lot of ListCells */
 3397                          5339         [ +  + ]:         186896 :     if (IS_OUTER_JOIN(jointype))
 6287                          5340                 :          61696 :         list_free(joinquals);
                               5341                 :                : 
                               5342                 :                :     /*
                               5343                 :                :      * jselec can be interpreted as the fraction of outer-rel rows that have
                               5344                 :                :      * any matches (this is true for both SEMI and ANTI cases).  And nselec is
                               5345                 :                :      * the fraction of the Cartesian product that matches.  So, the average
                               5346                 :                :      * number of matches for each outer-rel row that has at least one match is
                               5347                 :                :      * nselec * inner_rows / jselec.
                               5348                 :                :      *
                               5349                 :                :      * Note: it is correct to use the inner rel's "rows" count here, even
                               5350                 :                :      * though we might later be considering a parameterized inner path with
                               5351                 :                :      * fewer rows.  This is because we have included all the join clauses in
                               5352                 :                :      * the selectivity estimate.
                               5353                 :                :      */
                               5354         [ +  + ]:         186896 :     if (jselec > 0)              /* protect against zero divide */
                               5355                 :                :     {
 5294                          5356                 :         186730 :         avgmatch = nselec * innerrel->rows / jselec;
                               5357                 :                :         /* Clamp to sane range */
 6287                          5358         [ +  + ]:         186730 :         avgmatch = Max(1.0, avgmatch);
                               5359                 :                :     }
                               5360                 :                :     else
                               5361                 :            166 :         avgmatch = 1.0;
                               5362                 :                : 
 5294                          5363                 :         186896 :     semifactors->outer_match_frac = jselec;
                               5364                 :         186896 :     semifactors->match_count = avgmatch;
                               5365                 :         186896 : }
                               5366                 :                : 
                               5367                 :                : /*
                               5368                 :                :  * has_indexed_join_quals
                               5369                 :                :  *    Check whether all the joinquals of a nestloop join are used as
                               5370                 :                :  *    inner index quals.
                               5371                 :                :  *
                               5372                 :                :  * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
                               5373                 :                :  * indexscan) that uses all the joinquals as indexquals, we can assume that an
                               5374                 :                :  * unmatched outer tuple is cheap to process, whereas otherwise it's probably
                               5375                 :                :  * expensive.
                               5376                 :                :  */
                               5377                 :                : static bool
 1813 peter@eisentraut.org     5378                 :         737453 : has_indexed_join_quals(NestPath *path)
                               5379                 :                : {
                               5380                 :         737453 :     JoinPath   *joinpath = &path->jpath;
 5211 tgl@sss.pgh.pa.us        5381                 :         737453 :     Relids      joinrelids = joinpath->path.parent->relids;
                               5382                 :         737453 :     Path       *innerpath = joinpath->innerjoinpath;
                               5383                 :                :     List       *indexclauses;
                               5384                 :                :     bool        found_one;
                               5385                 :                :     ListCell   *lc;
                               5386                 :                : 
                               5387                 :                :     /* If join still has quals to evaluate, it's not fast */
                               5388         [ +  + ]:         737453 :     if (joinpath->joinrestrictinfo != NIL)
                               5389                 :         546391 :         return false;
                               5390                 :                :     /* Nor if the inner path isn't parameterized at all */
                               5391         [ +  + ]:         191062 :     if (innerpath->param_info == NULL)
                               5392                 :           2485 :         return false;
                               5393                 :                : 
                               5394                 :                :     /* Find the indexclauses list for the inner scan */
                               5395      [ +  +  + ]:         188577 :     switch (innerpath->pathtype)
                               5396                 :                :     {
                               5397                 :         122172 :         case T_IndexScan:
                               5398                 :                :         case T_IndexOnlyScan:
                               5399                 :         122172 :             indexclauses = ((IndexPath *) innerpath)->indexclauses;
                               5400                 :         122172 :             break;
                               5401                 :            334 :         case T_BitmapHeapScan:
                               5402                 :                :             {
                               5403                 :                :                 /* Accept only a simple bitmap scan, not AND/OR cases */
 5159 bruce@momjian.us         5404                 :            334 :                 Path       *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
                               5405                 :                : 
                               5406         [ +  + ]:            334 :                 if (IsA(bmqual, IndexPath))
                               5407                 :            294 :                     indexclauses = ((IndexPath *) bmqual)->indexclauses;
                               5408                 :                :                 else
                               5409                 :             40 :                     return false;
                               5410                 :            294 :                 break;
                               5411                 :                :             }
 5211 tgl@sss.pgh.pa.us        5412                 :          66071 :         default:
                               5413                 :                : 
                               5414                 :                :             /*
                               5415                 :                :              * If it's not a simple indexscan, it probably doesn't run quickly
                               5416                 :                :              * for zero rows out, even if it's a parameterized path using all
                               5417                 :                :              * the joinquals.
                               5418                 :                :              */
 5294                          5419                 :          66071 :             return false;
                               5420                 :                :     }
                               5421                 :                : 
                               5422                 :                :     /*
                               5423                 :                :      * Examine the inner path's param clauses.  Any that are from the outer
                               5424                 :                :      * path must be found in the indexclauses list, either exactly or in an
                               5425                 :                :      * equivalent form generated by equivclass.c.  Also, we must find at least
                               5426                 :                :      * one such clause, else it's a clauseless join which isn't fast.
                               5427                 :                :      */
 5211                          5428                 :         122466 :     found_one = false;
                               5429   [ +  -  +  +  :         245384 :     foreach(lc, innerpath->param_info->ppi_clauses)
                                              +  + ]
                               5430                 :                :     {
                               5431                 :         128067 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
                               5432                 :                : 
                               5433         [ +  + ]:         128067 :         if (join_clause_is_movable_into(rinfo,
                               5434                 :         128067 :                                         innerpath->parent->relids,
                               5435                 :                :                                         joinrelids))
                               5436                 :                :         {
 2724                          5437         [ +  + ]:         127627 :             if (!is_redundant_with_indexclauses(rinfo, indexclauses))
 5211                          5438                 :           5149 :                 return false;
                               5439                 :         122478 :             found_one = true;
                               5440                 :                :         }
                               5441                 :                :     }
                               5442                 :         117317 :     return found_one;
                               5443                 :                : }
                               5444                 :                : 
                               5445                 :                : 
                               5446                 :                : /*
                               5447                 :                :  * approx_tuple_count
                               5448                 :                :  *      Quick-and-dirty estimation of the number of join rows passing
                               5449                 :                :  *      a set of qual conditions.
                               5450                 :                :  *
                               5451                 :                :  * The quals can be either an implicitly-ANDed list of boolean expressions,
                               5452                 :                :  * or a list of RestrictInfo nodes (typically the latter).
                               5453                 :                :  *
                               5454                 :                :  * We intentionally compute the selectivity under JOIN_INNER rules, even
                               5455                 :                :  * if it's some type of outer join.  This is appropriate because we are
                               5456                 :                :  * trying to figure out how many tuples pass the initial merge or hash
                               5457                 :                :  * join step.
                               5458                 :                :  *
                               5459                 :                :  * This is quick-and-dirty because we bypass clauselist_selectivity, and
                               5460                 :                :  * simply multiply the independent clause selectivities together.  Now
                               5461                 :                :  * clauselist_selectivity often can't do any better than that anyhow, but
                               5462                 :                :  * for some situations (such as range constraints) it is smarter.  However,
                               5463                 :                :  * we can't effectively cache the results of clauselist_selectivity, whereas
                               5464                 :                :  * the individual clause selectivities can be and are cached.
                               5465                 :                :  *
                               5466                 :                :  * Since we are only using the results to estimate how many potential
                               5467                 :                :  * output tuples are generated and passed through qpqual checking, it
                               5468                 :                :  * seems OK to live with the approximation.
                               5469                 :                :  */
                               5470                 :                : static double
 6379                          5471                 :         605800 : approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
                               5472                 :                : {
                               5473                 :                :     double      tuples;
 5294                          5474                 :         605800 :     double      outer_tuples = path->outerjoinpath->rows;
                               5475                 :         605800 :     double      inner_tuples = path->innerjoinpath->rows;
                               5476                 :                :     SpecialJoinInfo sjinfo;
 6553                          5477                 :         605800 :     Selectivity selec = 1.0;
                               5478                 :                :     ListCell   *l;
                               5479                 :                : 
                               5480                 :                :     /*
                               5481                 :                :      * Make up a SpecialJoinInfo for JOIN_INNER semantics.
                               5482                 :                :      */
  853 amitlan@postgresql.o     5483                 :         605800 :     init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
                               5484                 :         605800 :                       path->innerjoinpath->parent->relids);
                               5485                 :                : 
                               5486                 :                :     /* Get the approximate selectivity */
 9182 tgl@sss.pgh.pa.us        5487   [ +  +  +  +  :        1302769 :     foreach(l, quals)
                                              +  + ]
                               5488                 :                :     {
                               5489                 :         696969 :         Node       *qual = (Node *) lfirst(l);
                               5490                 :                : 
                               5491                 :                :         /* Note that clause_selectivity will be able to cache its result */
 3398 simon@2ndQuadrant.co     5492                 :         696969 :         selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
                               5493                 :                :     }
                               5494                 :                : 
                               5495                 :                :     /* Apply it to the input relation sizes */
 6379 tgl@sss.pgh.pa.us        5496                 :         605800 :     tuples = selec * outer_tuples * inner_tuples;
                               5497                 :                : 
 6553                          5498                 :         605800 :     return clamp_row_est(tuples);
                               5499                 :                : }
                               5500                 :                : 
                               5501                 :                : 
                               5502                 :                : /*
                               5503                 :                :  * set_baserel_size_estimates
                               5504                 :                :  *      Set the size estimates for the given base relation.
                               5505                 :                :  *
                               5506                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               5507                 :                :  * already, and rel->tuples must be set.
                               5508                 :                :  *
                               5509                 :                :  * We set the following fields of the rel node:
                               5510                 :                :  *  rows: the estimated number of output tuples (after applying
                               5511                 :                :  *        restriction clauses).
                               5512                 :                :  *  width: the estimated average output tuple width in bytes.
                               5513                 :                :  *  baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
                               5514                 :                :  */
                               5515                 :                : void
 7721                          5516                 :         397848 : set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               5517                 :                : {
                               5518                 :                :     double      nrows;
                               5519                 :                : 
                               5520                 :                :     /* Should only be applied to base relations */
 8569                          5521         [ -  + ]:         397848 :     Assert(rel->relid > 0);
                               5522                 :                : 
 8238                          5523                 :         795676 :     nrows = rel->tuples *
 8239                          5524                 :         397848 :         clauselist_selectivity(root,
                               5525                 :                :                                rel->baserestrictinfo,
                               5526                 :                :                                0,
                               5527                 :                :                                JOIN_INNER,
                               5528                 :                :                                NULL);
                               5529                 :                : 
 8238                          5530                 :         397828 :     rel->rows = clamp_row_est(nrows);
                               5531                 :                : 
 7094                          5532                 :         397828 :     cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
                               5533                 :                : 
 9695                          5534                 :         397828 :     set_rel_width(root, rel);
10974 scrappy@hub.org          5535                 :         397828 : }
                               5536                 :                : 
                               5537                 :                : /*
                               5538                 :                :  * get_parameterized_baserel_size
                               5539                 :                :  *      Make a size estimate for a parameterized scan of a base relation.
                               5540                 :                :  *
                               5541                 :                :  * 'param_clauses' lists the additional join clauses to be used.
                               5542                 :                :  *
                               5543                 :                :  * set_baserel_size_estimates must have been applied already.
                               5544                 :                :  */
                               5545                 :                : double
 5211 tgl@sss.pgh.pa.us        5546                 :         135526 : get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
                               5547                 :                :                                List *param_clauses)
                               5548                 :                : {
                               5549                 :                :     List       *allclauses;
                               5550                 :                :     double      nrows;
                               5551                 :                : 
                               5552                 :                :     /*
                               5553                 :                :      * Estimate the number of rows returned by the parameterized scan, knowing
                               5554                 :                :      * that it will apply all the extra join clauses as well as the rel's own
                               5555                 :                :      * restriction clauses.  Note that we force the clauses to be treated as
                               5556                 :                :      * non-join clauses during selectivity estimation.
                               5557                 :                :      */
 2540                          5558                 :         135526 :     allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
 5211                          5559                 :         271052 :     nrows = rel->tuples *
                               5560                 :         135526 :         clauselist_selectivity(root,
                               5561                 :                :                                allclauses,
 3322                          5562                 :         135526 :                                rel->relid,   /* do not use 0! */
                               5563                 :                :                                JOIN_INNER,
                               5564                 :                :                                NULL);
 5211                          5565                 :         135526 :     nrows = clamp_row_est(nrows);
                               5566                 :                :     /* For safety, make sure result is not more than the base estimate */
                               5567         [ -  + ]:         135526 :     if (nrows > rel->rows)
 5211 tgl@sss.pgh.pa.us        5568                 :UBC           0 :         nrows = rel->rows;
 5211 tgl@sss.pgh.pa.us        5569                 :CBC      135526 :     return nrows;
                               5570                 :                : }
                               5571                 :                : 
                               5572                 :                : /*
                               5573                 :                :  * set_joinrel_size_estimates
                               5574                 :                :  *      Set the size estimates for the given join relation.
                               5575                 :                :  *
                               5576                 :                :  * The rel's targetlist must have been constructed already, and a
                               5577                 :                :  * restriction clause list that matches the given component rels must
                               5578                 :                :  * be provided.
                               5579                 :                :  *
                               5580                 :                :  * Since there is more than one way to make a joinrel for more than two
                               5581                 :                :  * base relations, the results we get here could depend on which component
                               5582                 :                :  * rel pair is provided.  In theory we should get the same answers no matter
                               5583                 :                :  * which pair is provided; in practice, since the selectivity estimation
                               5584                 :                :  * routines don't handle all cases equally well, we might not.  But there's
                               5585                 :                :  * not much to be done about it.  (Would it make sense to repeat the
                               5586                 :                :  * calculations for each pair of input rels that's encountered, and somehow
                               5587                 :                :  * average the results?  Probably way more trouble than it's worth, and
                               5588                 :                :  * anyway we must keep the rowcount estimate the same for all paths for the
                               5589                 :                :  * joinrel.)
                               5590                 :                :  *
                               5591                 :                :  * We set only the rows field here.  The reltarget field was already set by
                               5592                 :                :  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
                               5593                 :                :  */
                               5594                 :                : void
 7721                          5595                 :         208836 : set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
                               5596                 :                :                            RelOptInfo *outer_rel,
                               5597                 :                :                            RelOptInfo *inner_rel,
                               5598                 :                :                            SpecialJoinInfo *sjinfo,
                               5599                 :                :                            List *restrictlist)
                               5600                 :                : {
 5294                          5601                 :         208836 :     rel->rows = calc_joinrel_size_estimate(root,
                               5602                 :                :                                            rel,
                               5603                 :                :                                            outer_rel,
                               5604                 :                :                                            inner_rel,
                               5605                 :                :                                            outer_rel->rows,
                               5606                 :                :                                            inner_rel->rows,
                               5607                 :                :                                            sjinfo,
                               5608                 :                :                                            restrictlist);
                               5609                 :         208836 : }
                               5610                 :                : 
                               5611                 :                : /*
                               5612                 :                :  * get_parameterized_joinrel_size
                               5613                 :                :  *      Make a size estimate for a parameterized scan of a join relation.
                               5614                 :                :  *
                               5615                 :                :  * 'rel' is the joinrel under consideration.
                               5616                 :                :  * 'outer_path', 'inner_path' are (probably also parameterized) Paths that
                               5617                 :                :  *      produce the relations being joined.
                               5618                 :                :  * 'sjinfo' is any SpecialJoinInfo relevant to this join.
                               5619                 :                :  * 'restrict_clauses' lists the join clauses that need to be applied at the
                               5620                 :                :  * join node (including any movable clauses that were moved down to this join,
                               5621                 :                :  * and not including any movable clauses that were pushed down into the
                               5622                 :                :  * child paths).
                               5623                 :                :  *
                               5624                 :                :  * set_joinrel_size_estimates must have been applied already.
                               5625                 :                :  */
                               5626                 :                : double
 5211                          5627                 :           9466 : get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
                               5628                 :                :                                Path *outer_path,
                               5629                 :                :                                Path *inner_path,
                               5630                 :                :                                SpecialJoinInfo *sjinfo,
                               5631                 :                :                                List *restrict_clauses)
                               5632                 :                : {
                               5633                 :                :     double      nrows;
                               5634                 :                : 
                               5635                 :                :     /*
                               5636                 :                :      * Estimate the number of rows returned by the parameterized join as the
                               5637                 :                :      * sizes of the input paths times the selectivity of the clauses that have
                               5638                 :                :      * ended up at this join node.
                               5639                 :                :      *
                               5640                 :                :      * As with set_joinrel_size_estimates, the rowcount estimate could depend
                               5641                 :                :      * on the pair of input paths provided, though ideally we'd get the same
                               5642                 :                :      * estimate for any pair with the same parameterization.
                               5643                 :                :      */
                               5644                 :           9466 :     nrows = calc_joinrel_size_estimate(root,
                               5645                 :                :                                        rel,
                               5646                 :                :                                        outer_path->parent,
                               5647                 :                :                                        inner_path->parent,
                               5648                 :                :                                        outer_path->rows,
                               5649                 :                :                                        inner_path->rows,
                               5650                 :                :                                        sjinfo,
                               5651                 :                :                                        restrict_clauses);
                               5652                 :                :     /* For safety, make sure result is not more than the base estimate */
                               5653         [ +  + ]:           9466 :     if (nrows > rel->rows)
                               5654                 :            370 :         nrows = rel->rows;
                               5655                 :           9466 :     return nrows;
                               5656                 :                : }
                               5657                 :                : 
                               5658                 :                : /*
                               5659                 :                :  * calc_joinrel_size_estimate
                               5660                 :                :  *      Workhorse for set_joinrel_size_estimates and
                               5661                 :                :  *      get_parameterized_joinrel_size.
                               5662                 :                :  *
                               5663                 :                :  * outer_rel/inner_rel are the relations being joined, but they should be
                               5664                 :                :  * assumed to have sizes outer_rows/inner_rows; those numbers might be less
                               5665                 :                :  * than what rel->rows says, when we are considering parameterized paths.
                               5666                 :                :  */
                               5667                 :                : static double
 5294                          5668                 :         218302 : calc_joinrel_size_estimate(PlannerInfo *root,
                               5669                 :                :                            RelOptInfo *joinrel,
                               5670                 :                :                            RelOptInfo *outer_rel,
                               5671                 :                :                            RelOptInfo *inner_rel,
                               5672                 :                :                            double outer_rows,
                               5673                 :                :                            double inner_rows,
                               5674                 :                :                            SpecialJoinInfo *sjinfo,
                               5675                 :                :                            List *restrictlist)
                               5676                 :                : {
 6555                          5677                 :         218302 :     JoinType    jointype = sjinfo->jointype;
                               5678                 :                :     Selectivity fkselec;
                               5679                 :                :     Selectivity jselec;
                               5680                 :                :     Selectivity pselec;
                               5681                 :                :     double      nrows;
                               5682                 :                : 
                               5683                 :                :     /*
                               5684                 :                :      * Compute joinclause selectivity.  Note that we are only considering
                               5685                 :                :      * clauses that become restriction clauses at this join level; we are not
                               5686                 :                :      * double-counting them because they were not considered in estimating the
                               5687                 :                :      * sizes of the component rels.
                               5688                 :                :      *
                               5689                 :                :      * First, see whether any of the joinclauses can be matched to known FK
                               5690                 :                :      * constraints.  If so, drop those clauses from the restrictlist, and
                               5691                 :                :      * instead estimate their selectivity using FK semantics.  (We do this
                               5692                 :                :      * without regard to whether said clauses are local or "pushed down".
                               5693                 :                :      * Probably, an FK-matching clause could never be seen as pushed down at
                               5694                 :                :      * an outer join, since it would be strict and hence would be grounds for
                               5695                 :                :      * join strength reduction.)  fkselec gets the net selectivity for
                               5696                 :                :      * FK-matching clauses, or 1.0 if there are none.
                               5697                 :                :      */
 3690                          5698                 :         218302 :     fkselec = get_foreign_key_join_selectivity(root,
                               5699                 :                :                                                outer_rel->relids,
                               5700                 :                :                                                inner_rel->relids,
                               5701                 :                :                                                sjinfo,
                               5702                 :                :                                                &restrictlist);
                               5703                 :                : 
                               5704                 :                :     /*
                               5705                 :                :      * For an outer join, we have to distinguish the selectivity of the join's
                               5706                 :                :      * own clauses (JOIN/ON conditions) from any clauses that were "pushed
                               5707                 :                :      * down".  For inner joins we just count them all as joinclauses.
                               5708                 :                :      */
 7198                          5709         [ +  + ]:         218302 :     if (IS_OUTER_JOIN(jointype))
                               5710                 :                :     {
                               5711                 :          62111 :         List       *joinquals = NIL;
                               5712                 :          62111 :         List       *pushedquals = NIL;
                               5713                 :                :         ListCell   *l;
                               5714                 :                : 
                               5715                 :                :         /* Grovel through the clauses to separate into two lists */
                               5716   [ +  +  +  +  :         145188 :         foreach(l, restrictlist)
                                              +  + ]
                               5717                 :                :         {
 3394                          5718                 :          83077 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
                               5719                 :                : 
 3019                          5720   [ +  +  +  + ]:          83077 :             if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
 7198                          5721                 :           5309 :                 pushedquals = lappend(pushedquals, rinfo);
                               5722                 :                :             else
                               5723                 :          77768 :                 joinquals = lappend(joinquals, rinfo);
                               5724                 :                :         }
                               5725                 :                : 
                               5726                 :                :         /* Get the separate selectivities */
 3701                          5727                 :          62111 :         jselec = clauselist_selectivity(root,
                               5728                 :                :                                         joinquals,
                               5729                 :                :                                         0,
                               5730                 :                :                                         jointype,
                               5731                 :                :                                         sjinfo);
 7198                          5732                 :          62111 :         pselec = clauselist_selectivity(root,
                               5733                 :                :                                         pushedquals,
                               5734                 :                :                                         0,
                               5735                 :                :                                         jointype,
                               5736                 :                :                                         sjinfo);
                               5737                 :                : 
                               5738                 :                :         /* Avoid leaking a lot of ListCells */
                               5739                 :          62111 :         list_free(joinquals);
                               5740                 :          62111 :         list_free(pushedquals);
                               5741                 :                :     }
                               5742                 :                :     else
                               5743                 :                :     {
 3701                          5744                 :         156191 :         jselec = clauselist_selectivity(root,
                               5745                 :                :                                         restrictlist,
                               5746                 :                :                                         0,
                               5747                 :                :                                         jointype,
                               5748                 :                :                                         sjinfo);
 7198                          5749                 :         156191 :         pselec = 0.0;           /* not used, keep compiler quiet */
                               5750                 :                :     }
                               5751                 :                : 
                               5752                 :                :     /*
                               5753                 :                :      * Basically, we multiply size of Cartesian product by selectivity.
                               5754                 :                :      *
                               5755                 :                :      * If we are doing an outer join, take that into account: the joinqual
                               5756                 :                :      * selectivity has to be clamped using the knowledge that the output must
                               5757                 :                :      * be at least as large as the non-nullable input.  However, any
                               5758                 :                :      * pushed-down quals are applied after the outer join, so their
                               5759                 :                :      * selectivity applies fully.
                               5760                 :                :      *
                               5761                 :                :      * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
                               5762                 :                :      * of LHS rows that have matches, and we apply that straightforwardly.
                               5763                 :                :      */
 9291                          5764   [ +  +  +  +  :         218302 :     switch (jointype)
                                              +  - ]
                               5765                 :                :     {
                               5766                 :         149782 :         case JOIN_INNER:
 3690                          5767                 :         149782 :             nrows = outer_rows * inner_rows * fkselec * jselec;
                               5768                 :                :             /* pselec not used */
 9291                          5769                 :         149782 :             break;
                               5770                 :          48491 :         case JOIN_LEFT:
 3690                          5771                 :          48491 :             nrows = outer_rows * inner_rows * fkselec * jselec;
 5294                          5772         [ +  + ]:          48491 :             if (nrows < outer_rows)
                               5773                 :          21832 :                 nrows = outer_rows;
 7198                          5774                 :          48491 :             nrows *= pselec;
 9291                          5775                 :          48491 :             break;
                               5776                 :           1390 :         case JOIN_FULL:
 3690                          5777                 :           1390 :             nrows = outer_rows * inner_rows * fkselec * jselec;
 5294                          5778         [ +  + ]:           1390 :             if (nrows < outer_rows)
                               5779                 :            987 :                 nrows = outer_rows;
                               5780         [ +  + ]:           1390 :             if (nrows < inner_rows)
                               5781                 :            100 :                 nrows = inner_rows;
 7198                          5782                 :           1390 :             nrows *= pselec;
 9291                          5783                 :           1390 :             break;
 6555                          5784                 :           6409 :         case JOIN_SEMI:
 3690                          5785                 :           6409 :             nrows = outer_rows * fkselec * jselec;
                               5786                 :                :             /* pselec not used */
 8588                          5787                 :           6409 :             break;
 6555                          5788                 :          12230 :         case JOIN_ANTI:
 3690                          5789                 :          12230 :             nrows = outer_rows * (1.0 - fkselec * jselec);
 6555                          5790                 :          12230 :             nrows *= pselec;
 8588                          5791                 :          12230 :             break;
 9291 tgl@sss.pgh.pa.us        5792                 :UBC           0 :         default:
                               5793                 :                :             /* other values not expected here */
 8402                          5794         [ #  # ]:              0 :             elog(ERROR, "unrecognized join type: %d", (int) jointype);
                               5795                 :                :             nrows = 0;          /* keep compiler quiet */
                               5796                 :                :             break;
                               5797                 :                :     }
                               5798                 :                : 
 5294 tgl@sss.pgh.pa.us        5799                 :CBC      218302 :     return clamp_row_est(nrows);
                               5800                 :                : }
                               5801                 :                : 
                               5802                 :                : /*
                               5803                 :                :  * get_foreign_key_join_selectivity
                               5804                 :                :  *      Estimate join selectivity for foreign-key-related clauses.
                               5805                 :                :  *
                               5806                 :                :  * Remove any clauses that can be matched to FK constraints from *restrictlist,
                               5807                 :                :  * and return a substitute estimate of their selectivity.  1.0 is returned
                               5808                 :                :  * when there are no such clauses.
                               5809                 :                :  *
                               5810                 :                :  * The reason for treating such clauses specially is that we can get better
                               5811                 :                :  * estimates this way than by relying on clauselist_selectivity(), especially
                               5812                 :                :  * for multi-column FKs where that function's assumption that the clauses are
                               5813                 :                :  * independent falls down badly.  But even with single-column FKs, we may be
                               5814                 :                :  * able to get a better answer when the pg_statistic stats are missing or out
                               5815                 :                :  * of date.
                               5816                 :                :  */
                               5817                 :                : static Selectivity
 3690                          5818                 :         218302 : get_foreign_key_join_selectivity(PlannerInfo *root,
                               5819                 :                :                                  Relids outer_relids,
                               5820                 :                :                                  Relids inner_relids,
                               5821                 :                :                                  SpecialJoinInfo *sjinfo,
                               5822                 :                :                                  List **restrictlist)
                               5823                 :                : {
                               5824                 :         218302 :     Selectivity fkselec = 1.0;
                               5825                 :         218302 :     JoinType    jointype = sjinfo->jointype;
                               5826                 :         218302 :     List       *worklist = *restrictlist;
                               5827                 :                :     ListCell   *lc;
                               5828                 :                : 
                               5829                 :                :     /* Consider each FK constraint that is known to match the query */
                               5830   [ +  +  +  +  :         222247 :     foreach(lc, root->fkey_list)
                                              +  + ]
                               5831                 :                :     {
                               5832                 :           3945 :         ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
                               5833                 :                :         bool        ref_is_outer;
                               5834                 :                :         List       *removedlist;
                               5835                 :                :         ListCell   *cell;
                               5836                 :                : 
                               5837                 :                :         /*
                               5838                 :                :          * This FK is not relevant unless it connects a baserel on one side of
                               5839                 :                :          * this join to a baserel on the other side.
                               5840                 :                :          */
                               5841   [ +  +  +  + ]:           6640 :         if (bms_is_member(fkinfo->con_relid, outer_relids) &&
                               5842                 :           2695 :             bms_is_member(fkinfo->ref_relid, inner_relids))
                               5843                 :           1633 :             ref_is_outer = false;
                               5844   [ +  +  +  + ]:           3312 :         else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
                               5845                 :           1000 :                  bms_is_member(fkinfo->con_relid, inner_relids))
                               5846                 :            295 :             ref_is_outer = true;
                               5847                 :                :         else
                               5848                 :           2017 :             continue;
                               5849                 :                : 
                               5850                 :                :         /*
                               5851                 :                :          * If we're dealing with a semi/anti join, and the FK's referenced
                               5852                 :                :          * relation is on the outside, then knowledge of the FK doesn't help
                               5853                 :                :          * us figure out what we need to know (which is the fraction of outer
                               5854                 :                :          * rows that have matches).  On the other hand, if the referenced rel
                               5855                 :                :          * is on the inside, then all outer rows must have matches in the
                               5856                 :                :          * referenced table (ignoring nulls).  But any restriction or join
                               5857                 :                :          * clauses that filter that table will reduce the fraction of matches.
                               5858                 :                :          * We can account for restriction clauses, but it's too hard to guess
                               5859                 :                :          * how many table rows would get through a join that's inside the RHS.
                               5860                 :                :          * Hence, if either case applies, punt and ignore the FK.
                               5861                 :                :          */
 3324                          5862   [ +  -  +  +  :           1928 :         if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
                                              +  + ]
                               5863         [ -  + ]:            856 :             (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
                               5864                 :             10 :             continue;
                               5865                 :                : 
                               5866                 :                :         /*
                               5867                 :                :          * Modify the restrictlist by removing clauses that match the FK (and
                               5868                 :                :          * putting them into removedlist instead).  It seems unsafe to modify
                               5869                 :                :          * the originally-passed List structure, so we make a shallow copy the
                               5870                 :                :          * first time through.
                               5871                 :                :          */
 3690                          5872         [ +  + ]:           1918 :         if (worklist == *restrictlist)
                               5873                 :           1730 :             worklist = list_copy(worklist);
                               5874                 :                : 
                               5875                 :           1918 :         removedlist = NIL;
 2568                          5876   [ +  +  +  +  :           3946 :         foreach(cell, worklist)
                                              +  + ]
                               5877                 :                :         {
 3690                          5878                 :           2028 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
                               5879                 :           2028 :             bool        remove_it = false;
                               5880                 :                :             int         i;
                               5881                 :                : 
                               5882                 :                :             /* Drop this clause if it matches any column of the FK */
                               5883         [ +  + ]:           2391 :             for (i = 0; i < fkinfo->nkeys; i++)
                               5884                 :                :             {
                               5885         [ +  + ]:           2366 :                 if (rinfo->parent_ec)
                               5886                 :                :                 {
                               5887                 :                :                     /*
                               5888                 :                :                      * EC-derived clauses can only match by EC.  It is okay to
                               5889                 :                :                      * consider any clause derived from the same EC as
                               5890                 :                :                      * matching the FK: even if equivclass.c chose to generate
                               5891                 :                :                      * a clause equating some other pair of Vars, it could
                               5892                 :                :                      * have generated one equating the FK's Vars.  So for
                               5893                 :                :                      * purposes of estimation, we can act as though it did so.
                               5894                 :                :                      *
                               5895                 :                :                      * Note: checking parent_ec is a bit of a cheat because
                               5896                 :                :                      * there are EC-derived clauses that don't have parent_ec
                               5897                 :                :                      * set; but such clauses must compare expressions that
                               5898                 :                :                      * aren't just Vars, so they cannot match the FK anyway.
                               5899                 :                :                      */
                               5900         [ +  + ]:            897 :                     if (fkinfo->eclass[i] == rinfo->parent_ec)
                               5901                 :                :                     {
                               5902                 :            892 :                         remove_it = true;
                               5903                 :            892 :                         break;
                               5904                 :                :                     }
                               5905                 :                :                 }
                               5906                 :                :                 else
                               5907                 :                :                 {
                               5908                 :                :                     /*
                               5909                 :                :                      * Otherwise, see if rinfo was previously matched to FK as
                               5910                 :                :                      * a "loose" clause.
                               5911                 :                :                      */
                               5912         [ +  + ]:           1469 :                     if (list_member_ptr(fkinfo->rinfos[i], rinfo))
                               5913                 :                :                     {
                               5914                 :           1111 :                         remove_it = true;
                               5915                 :           1111 :                         break;
                               5916                 :                :                     }
                               5917                 :                :                 }
                               5918                 :                :             }
                               5919         [ +  + ]:           2028 :             if (remove_it)
                               5920                 :                :             {
 2568                          5921                 :           2003 :                 worklist = foreach_delete_current(worklist, cell);
 3690                          5922                 :           2003 :                 removedlist = lappend(removedlist, rinfo);
                               5923                 :                :             }
                               5924                 :                :         }
                               5925                 :                : 
                               5926                 :                :         /*
                               5927                 :                :          * If we failed to remove all the matching clauses we expected to
                               5928                 :                :          * find, chicken out and ignore this FK; applying its selectivity
                               5929                 :                :          * might result in double-counting.  Put any clauses we did manage to
                               5930                 :                :          * remove back into the worklist.
                               5931                 :                :          *
                               5932                 :                :          * Since the matching clauses are known not outerjoin-delayed, they
                               5933                 :                :          * would normally have appeared in the initial joinclause list.  If we
                               5934                 :                :          * didn't find them, there are two possibilities:
                               5935                 :                :          *
                               5936                 :                :          * 1. If the FK match is based on an EC that is ec_has_const, it won't
                               5937                 :                :          * have generated any join clauses at all.  We discount such ECs while
                               5938                 :                :          * checking to see if we have "all" the clauses.  (Below, we'll adjust
                               5939                 :                :          * the selectivity estimate for this case.)
                               5940                 :                :          *
                               5941                 :                :          * 2. The clauses were matched to some other FK in a previous
                               5942                 :                :          * iteration of this loop, and thus removed from worklist.  (A likely
                               5943                 :                :          * case is that two FKs are matched to the same EC; there will be only
                               5944                 :                :          * one EC-derived clause in the initial list, so the first FK will
                               5945                 :                :          * consume it.)  Applying both FKs' selectivity independently risks
                               5946                 :                :          * underestimating the join size; in particular, this would undo one
                               5947                 :                :          * of the main things that ECs were invented for, namely to avoid
                               5948                 :                :          * double-counting the selectivity of redundant equality conditions.
                               5949                 :                :          * Later we might think of a reasonable way to combine the estimates,
                               5950                 :                :          * but for now, just punt, since this is a fairly uncommon situation.
                               5951                 :                :          */
 2097                          5952         [ +  + ]:           1918 :         if (removedlist == NIL ||
                               5953                 :           1685 :             list_length(removedlist) !=
                               5954         [ -  + ]:           1685 :             (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
                               5955                 :                :         {
 3690                          5956                 :            233 :             worklist = list_concat(worklist, removedlist);
                               5957                 :            233 :             continue;
                               5958                 :                :         }
                               5959                 :                : 
                               5960                 :                :         /*
                               5961                 :                :          * Finally we get to the payoff: estimate selectivity using the
                               5962                 :                :          * knowledge that each referencing row will match exactly one row in
                               5963                 :                :          * the referenced table.
                               5964                 :                :          *
                               5965                 :                :          * XXX that's not true in the presence of nulls in the referencing
                               5966                 :                :          * column(s), so in principle we should derate the estimate for those.
                               5967                 :                :          * However (1) if there are any strict restriction clauses for the
                               5968                 :                :          * referencing column(s) elsewhere in the query, derating here would
                               5969                 :                :          * be double-counting the null fraction, and (2) it's not very clear
                               5970                 :                :          * how to combine null fractions for multiple referencing columns. So
                               5971                 :                :          * we do nothing for now about correcting for nulls.
                               5972                 :                :          *
                               5973                 :                :          * XXX another point here is that if either side of an FK constraint
                               5974                 :                :          * is an inheritance parent, we estimate as though the constraint
                               5975                 :                :          * covers all its children as well.  This is not an unreasonable
                               5976                 :                :          * assumption for a referencing table, ie the user probably applied
                               5977                 :                :          * identical constraints to all child tables (though perhaps we ought
                               5978                 :                :          * to check that).  But it's not possible to have done that for a
                               5979                 :                :          * referenced table.  Fortunately, precisely because that doesn't
                               5980                 :                :          * work, it is uncommon in practice to have an FK referencing a parent
                               5981                 :                :          * table.  So, at least for now, disregard inheritance here.
                               5982                 :                :          */
 3324                          5983   [ +  -  +  + ]:           1685 :         if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
 3690                          5984                 :            668 :         {
                               5985                 :                :             /*
                               5986                 :                :              * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
                               5987                 :                :              * referenced table is exactly the inside of the join.  The join
                               5988                 :                :              * selectivity is defined as the fraction of LHS rows that have
                               5989                 :                :              * matches.  The FK implies that every LHS row has a match *in the
                               5990                 :                :              * referenced table*; but any restriction clauses on it will
                               5991                 :                :              * reduce the number of matches.  Hence we take the join
                               5992                 :                :              * selectivity as equal to the selectivity of the table's
                               5993                 :                :              * restriction clauses, which is rows / tuples; but we must guard
                               5994                 :                :              * against tuples == 0.
                               5995                 :                :              */
 3324                          5996                 :            668 :             RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
                               5997         [ +  + ]:            668 :             double      ref_tuples = Max(ref_rel->tuples, 1.0);
                               5998                 :                : 
                               5999                 :            668 :             fkselec *= ref_rel->rows / ref_tuples;
                               6000                 :                :         }
                               6001                 :                :         else
                               6002                 :                :         {
                               6003                 :                :             /*
                               6004                 :                :              * Otherwise, selectivity is exactly 1/referenced-table-size; but
                               6005                 :                :              * guard against tuples == 0.  Note we should use the raw table
                               6006                 :                :              * tuple count, not any estimate of its filtered or joined size.
                               6007                 :                :              */
 3690                          6008                 :           1017 :             RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
                               6009         [ +  - ]:           1017 :             double      ref_tuples = Max(ref_rel->tuples, 1.0);
                               6010                 :                : 
                               6011                 :           1017 :             fkselec *= 1.0 / ref_tuples;
                               6012                 :                :         }
                               6013                 :                : 
                               6014                 :                :         /*
                               6015                 :                :          * If any of the FK columns participated in ec_has_const ECs, then
                               6016                 :                :          * equivclass.c will have generated "var = const" restrictions for
                               6017                 :                :          * each side of the join, thus reducing the sizes of both input
                               6018                 :                :          * relations.  Taking the fkselec at face value would amount to
                               6019                 :                :          * double-counting the selectivity of the constant restriction for the
                               6020                 :                :          * referencing Var.  Hence, look for the restriction clause(s) that
                               6021                 :                :          * were applied to the referencing Var(s), and divide out their
                               6022                 :                :          * selectivity to correct for this.
                               6023                 :                :          */
 2097                          6024         [ +  + ]:           1685 :         if (fkinfo->nconst_ec > 0)
                               6025                 :                :         {
                               6026         [ +  + ]:             20 :             for (int i = 0; i < fkinfo->nkeys; i++)
                               6027                 :                :             {
                               6028                 :             15 :                 EquivalenceClass *ec = fkinfo->eclass[i];
                               6029                 :                : 
                               6030   [ +  -  +  + ]:             15 :                 if (ec && ec->ec_has_const)
                               6031                 :                :                 {
                               6032                 :              5 :                     EquivalenceMember *em = fkinfo->fk_eclass_member[i];
  478 amitlan@postgresql.o     6033                 :              5 :                     RestrictInfo *rinfo = find_derived_clause_for_ec_member(root,
                               6034                 :                :                                                                             ec,
                               6035                 :                :                                                                             em);
                               6036                 :                : 
 2097 tgl@sss.pgh.pa.us        6037         [ +  - ]:              5 :                     if (rinfo)
                               6038                 :                :                     {
                               6039                 :                :                         Selectivity s0;
                               6040                 :                : 
                               6041                 :              5 :                         s0 = clause_selectivity(root,
                               6042                 :                :                                                 (Node *) rinfo,
                               6043                 :                :                                                 0,
                               6044                 :                :                                                 jointype,
                               6045                 :                :                                                 sjinfo);
                               6046         [ +  - ]:              5 :                         if (s0 > 0)
                               6047                 :              5 :                             fkselec /= s0;
                               6048                 :                :                     }
                               6049                 :                :                 }
                               6050                 :                :             }
                               6051                 :                :         }
                               6052                 :                :     }
                               6053                 :                : 
 3690                          6054                 :         218302 :     *restrictlist = worklist;
 2097                          6055   [ -  +  -  + ]:         218302 :     CLAMP_PROBABILITY(fkselec);
 3690                          6056                 :         218302 :     return fkselec;
                               6057                 :                : }
                               6058                 :                : 
                               6059                 :                : /*
                               6060                 :                :  * set_subquery_size_estimates
                               6061                 :                :  *      Set the size estimates for a base relation that is a subquery.
                               6062                 :                :  *
                               6063                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6064                 :                :  * already, and the Paths for the subquery must have been completed.
                               6065                 :                :  * We look at the subquery's PlannerInfo to extract data.
                               6066                 :                :  *
                               6067                 :                :  * We set the same fields as set_baserel_size_estimates.
                               6068                 :                :  */
                               6069                 :                : void
 5440                          6070                 :          30021 : set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6071                 :                : {
                               6072                 :          30021 :     PlannerInfo *subroot = rel->subroot;
                               6073                 :                :     RelOptInfo *sub_final_rel;
                               6074                 :                :     ListCell   *lc;
                               6075                 :                : 
                               6076                 :                :     /* Should only be applied to base relations that are subqueries */
 5728                          6077         [ -  + ]:          30021 :     Assert(rel->relid > 0);
 3230 andrew@dunslane.net      6078   [ +  -  -  + ]:          30021 :     Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
                               6079                 :                : 
                               6080                 :                :     /*
                               6081                 :                :      * Copy raw number of output rows from subquery.  All of its paths should
                               6082                 :                :      * have the same output rowcount, so just look at cheapest-total.
                               6083                 :                :      */
 3793 tgl@sss.pgh.pa.us        6084                 :          30021 :     sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
                               6085                 :          30021 :     rel->tuples = sub_final_rel->cheapest_total_path->rows;
                               6086                 :                : 
                               6087                 :                :     /*
                               6088                 :                :      * Compute per-output-column width estimates by examining the subquery's
                               6089                 :                :      * targetlist.  For any output that is a plain Var, get the width estimate
                               6090                 :                :      * that was made while planning the subquery.  Otherwise, we leave it to
                               6091                 :                :      * set_rel_width to fill in a datatype-based default estimate.
                               6092                 :                :      */
 5728                          6093   [ +  +  +  +  :         144369 :     foreach(lc, subroot->parse->targetList)
                                              +  + ]
                               6094                 :                :     {
 3394                          6095                 :         114348 :         TargetEntry *te = lfirst_node(TargetEntry, lc);
 5728                          6096                 :         114348 :         Node       *texpr = (Node *) te->expr;
 5451                          6097                 :         114348 :         int32       item_width = 0;
                               6098                 :                : 
                               6099                 :                :         /* junk columns aren't visible to upper query */
 5728                          6100         [ +  + ]:         114348 :         if (te->resjunk)
                               6101                 :           3842 :             continue;
                               6102                 :                : 
                               6103                 :                :         /*
                               6104                 :                :          * The subquery could be an expansion of a view that's had columns
                               6105                 :                :          * added to it since the current query was parsed, so that there are
                               6106                 :                :          * non-junk tlist columns in it that don't correspond to any column
                               6107                 :                :          * visible at our query level.  Ignore such columns.
                               6108                 :                :          */
 4865                          6109   [ +  -  -  + ]:         110506 :         if (te->resno < rel->min_attr || te->resno > rel->max_attr)
 4865 tgl@sss.pgh.pa.us        6110                 :UBC           0 :             continue;
                               6111                 :                : 
                               6112                 :                :         /*
                               6113                 :                :          * XXX This currently doesn't work for subqueries containing set
                               6114                 :                :          * operations, because the Vars in their tlists are bogus references
                               6115                 :                :          * to the first leaf subquery, which wouldn't give the right answer
                               6116                 :                :          * even if we could still get to its PlannerInfo.
                               6117                 :                :          *
                               6118                 :                :          * Also, the subquery could be an appendrel for which all branches are
                               6119                 :                :          * known empty due to constraint exclusion, in which case
                               6120                 :                :          * set_append_rel_pathlist will have left the attr_widths set to zero.
                               6121                 :                :          *
                               6122                 :                :          * In either case, we just leave the width estimate zero until
                               6123                 :                :          * set_rel_width fixes it.
                               6124                 :                :          */
 5728 tgl@sss.pgh.pa.us        6125         [ +  + ]:CBC      110506 :         if (IsA(texpr, Var) &&
                               6126         [ +  + ]:          46901 :             subroot->parse->setOperations == NULL)
                               6127                 :                :         {
 5586 bruce@momjian.us         6128                 :          44595 :             Var        *var = (Var *) texpr;
 5728 tgl@sss.pgh.pa.us        6129                 :          44595 :             RelOptInfo *subrel = find_base_rel(subroot, var->varno);
                               6130                 :                : 
                               6131                 :          44595 :             item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
                               6132                 :                :         }
                               6133                 :         110506 :         rel->attr_widths[te->resno - rel->min_attr] = item_width;
                               6134                 :                :     }
                               6135                 :                : 
                               6136                 :                :     /* Now estimate number of output rows, etc */
                               6137                 :          30021 :     set_baserel_size_estimates(root, rel);
                               6138                 :          30021 : }
                               6139                 :                : 
                               6140                 :                : /*
                               6141                 :                :  * set_function_size_estimates
                               6142                 :                :  *      Set the size estimates for a base relation that is a function call.
                               6143                 :                :  *
                               6144                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6145                 :                :  * already.
                               6146                 :                :  *
                               6147                 :                :  * We set the same fields as set_baserel_size_estimates.
                               6148                 :                :  */
                               6149                 :                : void
 7721                          6150                 :          35061 : set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6151                 :                : {
                               6152                 :                :     RangeTblEntry *rte;
                               6153                 :                :     ListCell   *lc;
                               6154                 :                : 
                               6155                 :                :     /* Should only be applied to base relations that are functions */
 8569                          6156         [ -  + ]:          35061 :     Assert(rel->relid > 0);
 7036                          6157         [ +  - ]:          35061 :     rte = planner_rt_fetch(rel->relid, root);
 7599                          6158         [ -  + ]:          35061 :     Assert(rte->rtekind == RTE_FUNCTION);
                               6159                 :                : 
                               6160                 :                :     /*
                               6161                 :                :      * Estimate number of rows the functions will return. The rowcount of the
                               6162                 :                :      * node is that of the largest function result.
                               6163                 :                :      */
 4630                          6164                 :          35061 :     rel->tuples = 0;
                               6165   [ +  -  +  +  :          70375 :     foreach(lc, rte->functions)
                                              +  + ]
                               6166                 :                :     {
                               6167                 :          35314 :         RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
 2724                          6168                 :          35314 :         double      ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
                               6169                 :                : 
 4630                          6170         [ +  + ]:          35314 :         if (ntup > rel->tuples)
                               6171                 :          35081 :             rel->tuples = ntup;
                               6172                 :                :     }
                               6173                 :                : 
                               6174                 :                :     /* Now estimate number of output rows, etc */
 8238                          6175                 :          35061 :     set_baserel_size_estimates(root, rel);
 8841                          6176                 :          35061 : }
                               6177                 :                : 
                               6178                 :                : /*
                               6179                 :                :  * set_function_size_estimates
                               6180                 :                :  *      Set the size estimates for a base relation that is a function call.
                               6181                 :                :  *
                               6182                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6183                 :                :  * already.
                               6184                 :                :  *
                               6185                 :                :  * We set the same fields as set_tablefunc_size_estimates.
                               6186                 :                :  */
                               6187                 :                : void
 3427 alvherre@alvh.no-ip.     6188                 :            602 : set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6189                 :                : {
                               6190                 :                :     /* Should only be applied to base relations that are functions */
                               6191         [ -  + ]:            602 :     Assert(rel->relid > 0);
 3230 andrew@dunslane.net      6192   [ +  -  -  + ]:            602 :     Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
                               6193                 :                : 
 3427 alvherre@alvh.no-ip.     6194                 :            602 :     rel->tuples = 100;
                               6195                 :                : 
                               6196                 :                :     /* Now estimate number of output rows, etc */
                               6197                 :            602 :     set_baserel_size_estimates(root, rel);
                               6198                 :            602 : }
                               6199                 :                : 
                               6200                 :                : /*
                               6201                 :                :  * set_values_size_estimates
                               6202                 :                :  *      Set the size estimates for a base relation that is a values list.
                               6203                 :                :  *
                               6204                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6205                 :                :  * already.
                               6206                 :                :  *
                               6207                 :                :  * We set the same fields as set_baserel_size_estimates.
                               6208                 :                :  */
                               6209                 :                : void
 7298 mail@joeconway.com       6210                 :           6996 : set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6211                 :                : {
                               6212                 :                :     RangeTblEntry *rte;
                               6213                 :                : 
                               6214                 :                :     /* Should only be applied to base relations that are values lists */
                               6215         [ -  + ]:           6996 :     Assert(rel->relid > 0);
 7036 tgl@sss.pgh.pa.us        6216         [ +  - ]:           6996 :     rte = planner_rt_fetch(rel->relid, root);
 7298 mail@joeconway.com       6217         [ -  + ]:           6996 :     Assert(rte->rtekind == RTE_VALUES);
                               6218                 :                : 
                               6219                 :                :     /*
                               6220                 :                :      * Estimate number of rows the values list will return. We know this
                               6221                 :                :      * precisely based on the list length (well, barring set-returning
                               6222                 :                :      * functions in list items, but that's a refinement not catered for
                               6223                 :                :      * anywhere else either).
                               6224                 :                :      */
                               6225                 :           6996 :     rel->tuples = list_length(rte->values_lists);
                               6226                 :                : 
                               6227                 :                :     /* Now estimate number of output rows, etc */
                               6228                 :           6996 :     set_baserel_size_estimates(root, rel);
                               6229                 :           6996 : }
                               6230                 :                : 
                               6231                 :                : /*
                               6232                 :                :  * set_cte_size_estimates
                               6233                 :                :  *      Set the size estimates for a base relation that is a CTE reference.
                               6234                 :                :  *
                               6235                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6236                 :                :  * already, and we need an estimate of the number of rows returned by the CTE
                               6237                 :                :  * (if a regular CTE) or the non-recursive term (if a self-reference).
                               6238                 :                :  *
                               6239                 :                :  * We set the same fields as set_baserel_size_estimates.
                               6240                 :                :  */
                               6241                 :                : void
 3793 tgl@sss.pgh.pa.us        6242                 :           3518 : set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
                               6243                 :                : {
                               6244                 :                :     RangeTblEntry *rte;
                               6245                 :                : 
                               6246                 :                :     /* Should only be applied to base relations that are CTE references */
 6504                          6247         [ -  + ]:           3518 :     Assert(rel->relid > 0);
                               6248         [ +  - ]:           3518 :     rte = planner_rt_fetch(rel->relid, root);
                               6249         [ -  + ]:           3518 :     Assert(rte->rtekind == RTE_CTE);
                               6250                 :                : 
                               6251         [ +  + ]:           3518 :     if (rte->self_reference)
                               6252                 :                :     {
                               6253                 :                :         /*
                               6254                 :                :          * In a self-reference, we assume the average worktable size is a
                               6255                 :                :          * multiple of the nonrecursive term's size.  The best multiplier will
                               6256                 :                :          * vary depending on query "fan-out", so make its value adjustable.
                               6257                 :                :          */
 1585                          6258                 :            637 :         rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
                               6259                 :                :     }
                               6260                 :                :     else
                               6261                 :                :     {
                               6262                 :                :         /* Otherwise just believe the CTE's rowcount estimate */
 3793                          6263                 :           2881 :         rel->tuples = cte_rows;
                               6264                 :                :     }
                               6265                 :                : 
                               6266                 :                :     /* Now estimate number of output rows, etc */
 6504                          6267                 :           3518 :     set_baserel_size_estimates(root, rel);
                               6268                 :           3518 : }
                               6269                 :                : 
                               6270                 :                : /*
                               6271                 :                :  * set_namedtuplestore_size_estimates
                               6272                 :                :  *      Set the size estimates for a base relation that is a tuplestore reference.
                               6273                 :                :  *
                               6274                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6275                 :                :  * already.
                               6276                 :                :  *
                               6277                 :                :  * We set the same fields as set_baserel_size_estimates.
                               6278                 :                :  */
                               6279                 :                : void
 3404 kgrittn@postgresql.o     6280                 :            437 : set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6281                 :                : {
                               6282                 :                :     RangeTblEntry *rte;
                               6283                 :                : 
                               6284                 :                :     /* Should only be applied to base relations that are tuplestore references */
                               6285         [ -  + ]:            437 :     Assert(rel->relid > 0);
                               6286         [ +  - ]:            437 :     rte = planner_rt_fetch(rel->relid, root);
                               6287         [ -  + ]:            437 :     Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
                               6288                 :                : 
                               6289                 :                :     /*
                               6290                 :                :      * Use the estimate provided by the code which is generating the named
                               6291                 :                :      * tuplestore.  In some cases, the actual number might be available; in
                               6292                 :                :      * others the same plan will be re-used, so a "typical" value might be
                               6293                 :                :      * estimated and used.
                               6294                 :                :      */
                               6295                 :            437 :     rel->tuples = rte->enrtuples;
                               6296         [ -  + ]:            437 :     if (rel->tuples < 0)
 3404 kgrittn@postgresql.o     6297                 :UBC           0 :         rel->tuples = 1000;
                               6298                 :                : 
                               6299                 :                :     /* Now estimate number of output rows, etc */
 3404 kgrittn@postgresql.o     6300                 :CBC         437 :     set_baserel_size_estimates(root, rel);
                               6301                 :            437 : }
                               6302                 :                : 
                               6303                 :                : /*
                               6304                 :                :  * set_result_size_estimates
                               6305                 :                :  *      Set the size estimates for an RTE_RESULT base relation
                               6306                 :                :  *
                               6307                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6308                 :                :  * already.
                               6309                 :                :  *
                               6310                 :                :  * We set the same fields as set_baserel_size_estimates.
                               6311                 :                :  */
                               6312                 :                : void
 2736 tgl@sss.pgh.pa.us        6313                 :           3636 : set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6314                 :                : {
                               6315                 :                :     /* Should only be applied to RTE_RESULT base relations */
                               6316         [ -  + ]:           3636 :     Assert(rel->relid > 0);
                               6317   [ +  -  -  + ]:           3636 :     Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
                               6318                 :                : 
                               6319                 :                :     /* RTE_RESULT always generates a single row, natively */
                               6320                 :           3636 :     rel->tuples = 1;
                               6321                 :                : 
                               6322                 :                :     /* Now estimate number of output rows, etc */
                               6323                 :           3636 :     set_baserel_size_estimates(root, rel);
                               6324                 :           3636 : }
                               6325                 :                : 
                               6326                 :                : /*
                               6327                 :                :  * set_foreign_size_estimates
                               6328                 :                :  *      Set the size estimates for a base relation that is a foreign table.
                               6329                 :                :  *
                               6330                 :                :  * There is not a whole lot that we can do here; the foreign-data wrapper
                               6331                 :                :  * is responsible for producing useful estimates.  We can do a decent job
                               6332                 :                :  * of estimating baserestrictcost, so we set that, and we also set up width
                               6333                 :                :  * using what will be purely datatype-driven estimates from the targetlist.
                               6334                 :                :  * There is no way to do anything sane with the rows value, so we just put
                               6335                 :                :  * a default estimate and hope that the wrapper can improve on it.  The
                               6336                 :                :  * wrapper's GetForeignRelSize function will be called momentarily.
                               6337                 :                :  *
                               6338                 :                :  * The rel's targetlist and restrictinfo list must have been constructed
                               6339                 :                :  * already.
                               6340                 :                :  */
                               6341                 :                : void
 5635                          6342                 :           1275 : set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
                               6343                 :                : {
                               6344                 :                :     /* Should only be applied to base relations */
                               6345         [ -  + ]:           1275 :     Assert(rel->relid > 0);
                               6346                 :                : 
                               6347                 :           1275 :     rel->rows = 1000;            /* entirely bogus default estimate */
                               6348                 :                : 
                               6349                 :           1275 :     cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
                               6350                 :                : 
                               6351                 :           1275 :     set_rel_width(root, rel);
                               6352                 :           1275 : }
                               6353                 :                : 
                               6354                 :                : 
                               6355                 :                : /*
                               6356                 :                :  * set_rel_width
                               6357                 :                :  *      Set the estimated output width of a base relation.
                               6358                 :                :  *
                               6359                 :                :  * The estimated output width is the sum of the per-attribute width estimates
                               6360                 :                :  * for the actually-referenced columns, plus any PHVs or other expressions
                               6361                 :                :  * that have to be calculated at this relation.  This is the amount of data
                               6362                 :                :  * we'd need to pass upwards in case of a sort, hash, etc.
                               6363                 :                :  *
                               6364                 :                :  * This function also sets reltarget->cost, so it's a bit misnamed now.
                               6365                 :                :  *
                               6366                 :                :  * NB: this works best on plain relations because it prefers to look at
                               6367                 :                :  * real Vars.  For subqueries, set_subquery_size_estimates will already have
                               6368                 :                :  * copied up whatever per-column estimates were made within the subquery,
                               6369                 :                :  * and for other types of rels there isn't much we can do anyway.  We fall
                               6370                 :                :  * back on (fairly stupid) datatype-based width estimates if we can't get
                               6371                 :                :  * any better number.
                               6372                 :                :  *
                               6373                 :                :  * The per-attribute width estimates are cached for possible re-use while
                               6374                 :                :  * building join relations or post-scan/join pathtargets.
                               6375                 :                :  */
                               6376                 :                : static void
 7721                          6377                 :         399103 : set_rel_width(PlannerInfo *root, RelOptInfo *rel)
                               6378                 :                : {
 6491                          6379         [ +  - ]:         399103 :     Oid         reloid = planner_rt_fetch(rel->relid, root)->relid;
  950                          6380                 :         399103 :     int64       tuple_width = 0;
 5728                          6381                 :         399103 :     bool        have_wholerow_var = false;
                               6382                 :                :     ListCell   *lc;
                               6383                 :                : 
                               6384                 :                :     /* Vars are assumed to have cost zero, but other exprs do not */
 3786                          6385                 :         399103 :     rel->reltarget->cost.startup = 0;
                               6386                 :         399103 :     rel->reltarget->cost.per_tuple = 0;
                               6387                 :                : 
                               6388   [ +  +  +  +  :        1411381 :     foreach(lc, rel->reltarget->exprs)
                                              +  + ]
                               6389                 :                :     {
 6487                          6390                 :        1012278 :         Node       *node = (Node *) lfirst(lc);
                               6391                 :                : 
                               6392                 :                :         /*
                               6393                 :                :          * Ordinarily, a Var in a rel's targetlist must belong to that rel;
                               6394                 :                :          * but there are corner cases involving LATERAL references where that
                               6395                 :                :          * isn't so.  If the Var has the wrong varno, fall through to the
                               6396                 :                :          * generic case (it doesn't seem worth the trouble to be any smarter).
                               6397                 :                :          */
 5082                          6398         [ +  + ]:        1012278 :         if (IsA(node, Var) &&
                               6399         [ +  + ]:         992449 :             ((Var *) node)->varno == rel->relid)
 8086                          6400                 :         247531 :         {
 6487                          6401                 :         992374 :             Var        *var = (Var *) node;
                               6402                 :                :             int         ndx;
                               6403                 :                :             int32       item_width;
                               6404                 :                : 
                               6405         [ -  + ]:         992374 :             Assert(var->varattno >= rel->min_attr);
                               6406         [ -  + ]:         992374 :             Assert(var->varattno <= rel->max_attr);
                               6407                 :                : 
                               6408                 :         992374 :             ndx = var->varattno - rel->min_attr;
                               6409                 :                : 
                               6410                 :                :             /*
                               6411                 :                :              * If it's a whole-row Var, we'll deal with it below after we have
                               6412                 :                :              * already cached as many attr widths as possible.
                               6413                 :                :              */
 5728                          6414         [ +  + ]:         992374 :             if (var->varattno == 0)
                               6415                 :                :             {
                               6416                 :           2132 :                 have_wholerow_var = true;
                               6417                 :           2132 :                 continue;
                               6418                 :                :             }
                               6419                 :                : 
                               6420                 :                :             /*
                               6421                 :                :              * The width may have been cached already (especially if it's a
                               6422                 :                :              * subquery), so don't duplicate effort.
                               6423                 :                :              */
 6487                          6424         [ +  + ]:         990242 :             if (rel->attr_widths[ndx] > 0)
                               6425                 :                :             {
                               6426                 :         217119 :                 tuple_width += rel->attr_widths[ndx];
 8428                          6427                 :         217119 :                 continue;
                               6428                 :                :             }
                               6429                 :                : 
                               6430                 :                :             /* Try to get column width from statistics */
 5728                          6431   [ +  +  +  + ]:         773123 :             if (reloid != InvalidOid && var->varattno > 0)
                               6432                 :                :             {
 6487                          6433                 :         611958 :                 item_width = get_attavgwidth(reloid, var->varattno);
                               6434         [ +  + ]:         611958 :                 if (item_width > 0)
                               6435                 :                :                 {
                               6436                 :         525592 :                     rel->attr_widths[ndx] = item_width;
                               6437                 :         525592 :                     tuple_width += item_width;
                               6438                 :         525592 :                     continue;
                               6439                 :                :                 }
                               6440                 :                :             }
                               6441                 :                : 
                               6442                 :                :             /*
                               6443                 :                :              * Not a plain relation, or can't find statistics for it. Estimate
                               6444                 :                :              * using just the type info.
                               6445                 :                :              */
                               6446                 :         247531 :             item_width = get_typavgwidth(var->vartype, var->vartypmod);
                               6447         [ -  + ]:         247531 :             Assert(item_width > 0);
                               6448                 :         247531 :             rel->attr_widths[ndx] = item_width;
                               6449                 :         247531 :             tuple_width += item_width;
                               6450                 :                :         }
                               6451         [ +  + ]:          19904 :         else if (IsA(node, PlaceHolderVar))
                               6452                 :                :         {
                               6453                 :                :             /*
                               6454                 :                :              * We will need to evaluate the PHV's contained expression while
                               6455                 :                :              * scanning this rel, so be sure to include it in reltarget->cost.
                               6456                 :                :              */
                               6457                 :           1890 :             PlaceHolderVar *phv = (PlaceHolderVar *) node;
 1439                          6458                 :           1890 :             PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
                               6459                 :                :             QualCost    cost;
                               6460                 :                : 
 6487                          6461                 :           1890 :             tuple_width += phinfo->ph_width;
 3811                          6462                 :           1890 :             cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
 3786                          6463                 :           1890 :             rel->reltarget->cost.startup += cost.startup;
                               6464                 :           1890 :             rel->reltarget->cost.per_tuple += cost.per_tuple;
                               6465                 :                :         }
                               6466                 :                :         else
                               6467                 :                :         {
                               6468                 :                :             /*
                               6469                 :                :              * We could be looking at an expression pulled up from a subquery,
                               6470                 :                :              * or a ROW() representing a whole-row child Var, etc.  Do what we
                               6471                 :                :              * can using the expression type information.
                               6472                 :                :              */
                               6473                 :                :             int32       item_width;
                               6474                 :                :             QualCost    cost;
                               6475                 :                : 
 6224                          6476                 :          18014 :             item_width = get_typavgwidth(exprType(node), exprTypmod(node));
                               6477         [ -  + ]:          18014 :             Assert(item_width > 0);
                               6478                 :          18014 :             tuple_width += item_width;
                               6479                 :                :             /* Not entirely clear if we need to account for cost, but do so */
 3811                          6480                 :          18014 :             cost_qual_eval_node(&cost, node, root);
 3786                          6481                 :          18014 :             rel->reltarget->cost.startup += cost.startup;
                               6482                 :          18014 :             rel->reltarget->cost.per_tuple += cost.per_tuple;
                               6483                 :                :         }
                               6484                 :                :     }
                               6485                 :                : 
                               6486                 :                :     /*
                               6487                 :                :      * If we have a whole-row reference, estimate its width as the sum of
                               6488                 :                :      * per-column widths plus heap tuple header overhead.
                               6489                 :                :      */
 5728                          6490         [ +  + ]:         399103 :     if (have_wholerow_var)
                               6491                 :                :     {
  950                          6492                 :           2132 :         int64       wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
                               6493                 :                : 
 5728                          6494         [ +  + ]:           2132 :         if (reloid != InvalidOid)
                               6495                 :                :         {
                               6496                 :                :             /* Real relation, so estimate true tuple width */
                               6497                 :           1624 :             wholerow_width += get_relation_data_width(reloid,
 3322                          6498                 :           1624 :                                                       rel->attr_widths - rel->min_attr);
                               6499                 :                :         }
                               6500                 :                :         else
                               6501                 :                :         {
                               6502                 :                :             /* Do what we can with info for a phony rel */
                               6503                 :                :             AttrNumber  i;
                               6504                 :                : 
 5728                          6505         [ +  + ]:           1384 :             for (i = 1; i <= rel->max_attr; i++)
                               6506                 :            876 :                 wholerow_width += rel->attr_widths[i - rel->min_attr];
                               6507                 :                :         }
                               6508                 :                : 
  950                          6509                 :           2132 :         rel->attr_widths[0 - rel->min_attr] = clamp_width_est(wholerow_width);
                               6510                 :                : 
                               6511                 :                :         /*
                               6512                 :                :          * Include the whole-row Var as part of the output tuple.  Yes, that
                               6513                 :                :          * really is what happens at runtime.
                               6514                 :                :          */
 5728                          6515                 :           2132 :         tuple_width += wholerow_width;
                               6516                 :                :     }
                               6517                 :                : 
  950                          6518                 :         399103 :     rel->reltarget->width = clamp_width_est(tuple_width);
10974 scrappy@hub.org          6519                 :         399103 : }
                               6520                 :                : 
                               6521                 :                : /*
                               6522                 :                :  * set_pathtarget_cost_width
                               6523                 :                :  *      Set the estimated eval cost and output width of a PathTarget tlist.
                               6524                 :                :  *
                               6525                 :                :  * As a notational convenience, returns the same PathTarget pointer passed in.
                               6526                 :                :  *
                               6527                 :                :  * Most, though not quite all, uses of this function occur after we've run
                               6528                 :                :  * set_rel_width() for base relations; so we can usually obtain cached width
                               6529                 :                :  * estimates for Vars.  If we can't, fall back on datatype-based width
                               6530                 :                :  * estimates.  Present early-planning uses of PathTargets don't need accurate
                               6531                 :                :  * widths badly enough to justify going to the catalogs for better data.
                               6532                 :                :  */
                               6533                 :                : PathTarget *
 3793 tgl@sss.pgh.pa.us        6534                 :         465938 : set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
                               6535                 :                : {
  950                          6536                 :         465938 :     int64       tuple_width = 0;
                               6537                 :                :     ListCell   *lc;
                               6538                 :                : 
                               6539                 :                :     /* Vars are assumed to have cost zero, but other exprs do not */
 3793                          6540                 :         465938 :     target->cost.startup = 0;
                               6541                 :         465938 :     target->cost.per_tuple = 0;
                               6542                 :                : 
                               6543   [ +  +  +  +  :        1607866 :     foreach(lc, target->exprs)
                                              +  + ]
                               6544                 :                :     {
                               6545                 :        1141928 :         Node       *node = (Node *) lfirst(lc);
                               6546                 :                : 
 1224 drowley@postgresql.o     6547                 :        1141928 :         tuple_width += get_expr_width(root, node);
                               6548                 :                : 
                               6549                 :                :         /* For non-Vars, account for evaluation cost */
                               6550         [ +  + ]:        1141928 :         if (!IsA(node, Var))
                               6551                 :                :         {
                               6552                 :                :             QualCost    cost;
                               6553                 :                : 
 3793 tgl@sss.pgh.pa.us        6554                 :         501982 :             cost_qual_eval_node(&cost, node, root);
                               6555                 :         501982 :             target->cost.startup += cost.startup;
                               6556                 :         501982 :             target->cost.per_tuple += cost.per_tuple;
                               6557                 :                :         }
                               6558                 :                :     }
                               6559                 :                : 
  950                          6560                 :         465938 :     target->width = clamp_width_est(tuple_width);
                               6561                 :                : 
 3793                          6562                 :         465938 :     return target;
                               6563                 :                : }
                               6564                 :                : 
                               6565                 :                : /*
                               6566                 :                :  * get_expr_width
                               6567                 :                :  *      Estimate the width of the given expr attempting to use the width
                               6568                 :                :  *      cached in a Var's owning RelOptInfo, else fallback on the type's
                               6569                 :                :  *      average width when unable to or when the given Node is not a Var.
                               6570                 :                :  */
                               6571                 :                : static int32
 1224 drowley@postgresql.o     6572                 :        1356387 : get_expr_width(PlannerInfo *root, const Node *expr)
                               6573                 :                : {
                               6574                 :                :     int32       width;
                               6575                 :                : 
                               6576         [ +  + ]:        1356387 :     if (IsA(expr, Var))
                               6577                 :                :     {
                               6578                 :         846344 :         const Var  *var = (const Var *) expr;
                               6579                 :                : 
                               6580                 :                :         /* We should not see any upper-level Vars here */
                               6581         [ -  + ]:         846344 :         Assert(var->varlevelsup == 0);
                               6582                 :                : 
                               6583                 :                :         /* Try to get data from RelOptInfo cache */
                               6584         [ +  + ]:         846344 :         if (!IS_SPECIAL_VARNO(var->varno) &&
                               6585         [ +  - ]:         841648 :             var->varno < root->simple_rel_array_size)
                               6586                 :                :         {
                               6587                 :         841648 :             RelOptInfo *rel = root->simple_rel_array[var->varno];
                               6588                 :                : 
                               6589         [ +  + ]:         841648 :             if (rel != NULL &&
                               6590         [ +  - ]:         827405 :                 var->varattno >= rel->min_attr &&
                               6591         [ +  - ]:         827405 :                 var->varattno <= rel->max_attr)
                               6592                 :                :             {
                               6593                 :         827405 :                 int         ndx = var->varattno - rel->min_attr;
                               6594                 :                : 
                               6595         [ +  + ]:         827405 :                 if (rel->attr_widths[ndx] > 0)
                               6596                 :         801204 :                     return rel->attr_widths[ndx];
                               6597                 :                :             }
                               6598                 :                :         }
                               6599                 :                : 
                               6600                 :                :         /*
                               6601                 :                :          * No cached data available, so estimate using just the type info.
                               6602                 :                :          */
                               6603                 :          45140 :         width = get_typavgwidth(var->vartype, var->vartypmod);
                               6604         [ -  + ]:          45140 :         Assert(width > 0);
                               6605                 :                : 
                               6606                 :          45140 :         return width;
                               6607                 :                :     }
                               6608                 :                : 
                               6609                 :         510043 :     width = get_typavgwidth(exprType(expr), exprTypmod(expr));
                               6610         [ -  + ]:         510043 :     Assert(width > 0);
                               6611                 :         510043 :     return width;
                               6612                 :                : }
                               6613                 :                : 
                               6614                 :                : /*
                               6615                 :                :  * relation_byte_size
                               6616                 :                :  *    Estimate the storage space in bytes for a given number of tuples
                               6617                 :                :  *    of a given width (size in bytes).
                               6618                 :                :  */
                               6619                 :                : static double
 9695 tgl@sss.pgh.pa.us        6620                 :        3745835 : relation_byte_size(double tuples, int width)
                               6621                 :                : {
 4173                          6622                 :        3745835 :     return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
                               6623                 :                : }
                               6624                 :                : 
                               6625                 :                : /*
                               6626                 :                :  * page_size
                               6627                 :                :  *    Returns an estimate of the number of pages covered by a given
                               6628                 :                :  *    number of tuples of a given width (size in bytes).
                               6629                 :                :  */
                               6630                 :                : static double
 9695                          6631                 :           6138 : page_size(double tuples, int width)
                               6632                 :                : {
                               6633                 :           6138 :     return ceil(relation_byte_size(tuples, width) / BLCKSZ);
                               6634                 :                : }
                               6635                 :                : 
                               6636                 :                : /*
                               6637                 :                :  * Estimate the fraction of the work that each worker will do given the
                               6638                 :                :  * number of workers budgeted for the path.
                               6639                 :                :  */
                               6640                 :                : static double
 3481 rhaas@postgresql.org     6641                 :         374269 : get_parallel_divisor(Path *path)
                               6642                 :                : {
                               6643                 :         374269 :     double      parallel_divisor = path->parallel_workers;
                               6644                 :                : 
                               6645                 :                :     /*
                               6646                 :                :      * Early experience with parallel query suggests that when there is only
                               6647                 :                :      * one worker, the leader often makes a very substantial contribution to
                               6648                 :                :      * executing the parallel portion of the plan, but as more workers are
                               6649                 :                :      * added, it does less and less, because it's busy reading tuples from the
                               6650                 :                :      * workers and doing whatever non-parallel post-processing is needed.  By
                               6651                 :                :      * the time we reach 4 workers, the leader no longer makes a meaningful
                               6652                 :                :      * contribution.  Thus, for now, estimate that the leader spends 30% of
                               6653                 :                :      * its time servicing each worker, and the remainder executing the
                               6654                 :                :      * parallel plan.
                               6655                 :                :      */
 3175                          6656         [ +  + ]:         374269 :     if (parallel_leader_participation)
                               6657                 :                :     {
                               6658                 :                :         double      leader_contribution;
                               6659                 :                : 
                               6660                 :         373264 :         leader_contribution = 1.0 - (0.3 * path->parallel_workers);
                               6661         [ +  + ]:         373264 :         if (leader_contribution > 0)
                               6662                 :         371113 :             parallel_divisor += leader_contribution;
                               6663                 :                :     }
                               6664                 :                : 
 3481                          6665                 :         374269 :     return parallel_divisor;
                               6666                 :                : }
                               6667                 :                : 
                               6668                 :                : /*
                               6669                 :                :  * compute_bitmap_pages
                               6670                 :                :  *    Estimate number of pages fetched from heap in a bitmap heap scan.
                               6671                 :                :  *
                               6672                 :                :  * 'baserel' is the relation to be scanned
                               6673                 :                :  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
                               6674                 :                :  * 'loop_count' is the number of repetitions of the indexscan to factor into
                               6675                 :                :  *      estimates of caching behavior
                               6676                 :                :  *
                               6677                 :                :  * If cost_p isn't NULL, the indexTotalCost estimate is returned in *cost_p.
                               6678                 :                :  * If tuples_p isn't NULL, the tuples_fetched estimate is returned in *tuples_p.
                               6679                 :                :  */
                               6680                 :                : double
  951 tgl@sss.pgh.pa.us        6681                 :         576081 : compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel,
                               6682                 :                :                      Path *bitmapqual, double loop_count,
                               6683                 :                :                      Cost *cost_p, double *tuples_p)
                               6684                 :                : {
                               6685                 :                :     Cost        indexTotalCost;
                               6686                 :                :     Selectivity indexSelectivity;
                               6687                 :                :     double      T;
                               6688                 :                :     double      pages_fetched;
                               6689                 :                :     double      tuples_fetched;
                               6690                 :                :     double      heap_pages;
                               6691                 :                :     double      maxentries;
                               6692                 :                : 
                               6693                 :                :     /*
                               6694                 :                :      * Fetch total cost of obtaining the bitmap, as well as its total
                               6695                 :                :      * selectivity.
                               6696                 :                :      */
 3467 rhaas@postgresql.org     6697                 :         576081 :     cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
                               6698                 :                : 
                               6699                 :                :     /*
                               6700                 :                :      * Estimate number of main-table pages fetched.
                               6701                 :                :      */
                               6702                 :         576081 :     tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
                               6703                 :                : 
                               6704         [ +  + ]:         576081 :     T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
                               6705                 :                : 
                               6706                 :                :     /*
                               6707                 :                :      * For a single scan, the number of heap pages that need to be fetched is
                               6708                 :                :      * the same as the Mackert and Lohman formula for the case T <= b (ie, no
                               6709                 :                :      * re-reads needed).
                               6710                 :                :      */
 3180                          6711                 :         576081 :     pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
                               6712                 :                : 
                               6713                 :                :     /*
                               6714                 :                :      * Calculate the number of pages fetched from the heap.  Then based on
                               6715                 :                :      * current work_mem estimate get the estimated maxentries in the bitmap.
                               6716                 :                :      * (Note that we always do this calculation based on the number of pages
                               6717                 :                :      * that would be fetched in a single iteration, even if loop_count > 1.
                               6718                 :                :      * That's correct, because only that number of entries will be stored in
                               6719                 :                :      * the bitmap at one time.)
                               6720                 :                :      */
                               6721         [ +  + ]:         576081 :     heap_pages = Min(pages_fetched, baserel->pages);
  541 tgl@sss.pgh.pa.us        6722                 :         576081 :     maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
                               6723                 :                : 
 3467 rhaas@postgresql.org     6724         [ +  + ]:         576081 :     if (loop_count > 1)
                               6725                 :                :     {
                               6726                 :                :         /*
                               6727                 :                :          * For repeated bitmap scans, scale up the number of tuples fetched in
                               6728                 :                :          * the Mackert and Lohman formula by the number of scans, so that we
                               6729                 :                :          * estimate the number of pages fetched by all the scans. Then
                               6730                 :                :          * pro-rate for one scan.
                               6731                 :                :          */
                               6732                 :         129283 :         pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
                               6733                 :                :                                             baserel->pages,
                               6734                 :                :                                             get_indexpath_pages(bitmapqual),
                               6735                 :                :                                             root);
                               6736                 :         129283 :         pages_fetched /= loop_count;
                               6737                 :                :     }
                               6738                 :                : 
                               6739         [ +  + ]:         576081 :     if (pages_fetched >= T)
                               6740                 :          54228 :         pages_fetched = T;
                               6741                 :                :     else
                               6742                 :         521853 :         pages_fetched = ceil(pages_fetched);
                               6743                 :                : 
 3180                          6744         [ +  + ]:         576081 :     if (maxentries < heap_pages)
                               6745                 :                :     {
                               6746                 :                :         double      exact_pages;
                               6747                 :                :         double      lossy_pages;
                               6748                 :                : 
                               6749                 :                :         /*
                               6750                 :                :          * Crude approximation of the number of lossy pages.  Because of the
                               6751                 :                :          * way tbm_lossify() is coded, the number of lossy pages increases
                               6752                 :                :          * very sharply as soon as we run short of memory; this formula has
                               6753                 :                :          * that property and seems to perform adequately in testing, but it's
                               6754                 :                :          * possible we could do better somehow.
                               6755                 :                :          */
                               6756         [ -  + ]:             15 :         lossy_pages = Max(0, heap_pages - maxentries / 2);
                               6757                 :             15 :         exact_pages = heap_pages - lossy_pages;
                               6758                 :                : 
                               6759                 :                :         /*
                               6760                 :                :          * If there are lossy pages then recompute the number of tuples
                               6761                 :                :          * processed by the bitmap heap node.  We assume here that the chance
                               6762                 :                :          * of a given tuple coming from an exact page is the same as the
                               6763                 :                :          * chance that a given page is exact.  This might not be true, but
                               6764                 :                :          * it's not clear how we can do any better.
                               6765                 :                :          */
                               6766         [ +  - ]:             15 :         if (lossy_pages > 0)
                               6767                 :                :             tuples_fetched =
                               6768                 :             15 :                 clamp_row_est(indexSelectivity *
                               6769                 :             15 :                               (exact_pages / heap_pages) * baserel->tuples +
                               6770                 :             15 :                               (lossy_pages / heap_pages) * baserel->tuples);
                               6771                 :                :     }
                               6772                 :                : 
  951 tgl@sss.pgh.pa.us        6773         [ +  + ]:         576081 :     if (cost_p)
                               6774                 :         463050 :         *cost_p = indexTotalCost;
                               6775         [ +  + ]:         576081 :     if (tuples_p)
                               6776                 :         463050 :         *tuples_p = tuples_fetched;
                               6777                 :                : 
 3467 rhaas@postgresql.org     6778                 :         576081 :     return pages_fetched;
                               6779                 :                : }
                               6780                 :                : 
                               6781                 :                : /*
                               6782                 :                :  * compute_gather_rows
                               6783                 :                :  *    Estimate number of rows for gather (merge) nodes.
                               6784                 :                :  *
                               6785                 :                :  * In a parallel plan, each worker's row estimate is determined by dividing the
                               6786                 :                :  * total number of rows by parallel_divisor, which accounts for the leader's
                               6787                 :                :  * contribution in addition to the number of workers.  Accordingly, when
                               6788                 :                :  * estimating the number of rows for gather (merge) nodes, we multiply the rows
                               6789                 :                :  * per worker by the same parallel_divisor to undo the division.
                               6790                 :                :  */
                               6791                 :                : double
  733 rguo@postgresql.org      6792                 :          37779 : compute_gather_rows(Path *path)
                               6793                 :                : {
                               6794         [ -  + ]:          37779 :     Assert(path->parallel_workers > 0);
                               6795                 :                : 
                               6796                 :          37779 :     return clamp_row_est(path->rows * get_parallel_divisor(path));
                               6797                 :                : }
        

Generated by: LCOV version 2.0-1