LCOV - code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 95.8 % 1008 966
Test Date: 2026-08-18 16:15:47 Functions: 100.0 % 20 20
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 85.0 % 588 500

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * analyze.c
       4                 :             :  *    the Postgres statistics generator
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/commands/analyze.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include <math.h>
      18                 :             : 
      19                 :             : #include "access/detoast.h"
      20                 :             : #include "access/genam.h"
      21                 :             : #include "access/multixact.h"
      22                 :             : #include "access/relation.h"
      23                 :             : #include "access/table.h"
      24                 :             : #include "access/tableam.h"
      25                 :             : #include "access/transam.h"
      26                 :             : #include "access/tupconvert.h"
      27                 :             : #include "access/visibilitymap.h"
      28                 :             : #include "access/xact.h"
      29                 :             : #include "catalog/index.h"
      30                 :             : #include "catalog/indexing.h"
      31                 :             : #include "catalog/pg_inherits.h"
      32                 :             : #include "commands/progress.h"
      33                 :             : #include "commands/tablecmds.h"
      34                 :             : #include "commands/vacuum.h"
      35                 :             : #include "common/pg_prng.h"
      36                 :             : #include "executor/executor.h"
      37                 :             : #include "executor/instrument.h"
      38                 :             : #include "foreign/fdwapi.h"
      39                 :             : #include "miscadmin.h"
      40                 :             : #include "nodes/nodeFuncs.h"
      41                 :             : #include "parser/parse_oper.h"
      42                 :             : #include "parser/parse_relation.h"
      43                 :             : #include "pgstat.h"
      44                 :             : #include "statistics/extended_stats_internal.h"
      45                 :             : #include "statistics/statistics.h"
      46                 :             : #include "storage/bufmgr.h"
      47                 :             : #include "storage/procarray.h"
      48                 :             : #include "utils/attoptcache.h"
      49                 :             : #include "utils/datum.h"
      50                 :             : #include "utils/guc.h"
      51                 :             : #include "utils/lsyscache.h"
      52                 :             : #include "utils/memutils.h"
      53                 :             : #include "utils/pg_rusage.h"
      54                 :             : #include "utils/sampling.h"
      55                 :             : #include "utils/sortsupport.h"
      56                 :             : #include "utils/syscache.h"
      57                 :             : #include "utils/timestamp.h"
      58                 :             : 
      59                 :             : 
      60                 :             : /* Per-index data for ANALYZE */
      61                 :             : typedef struct AnlIndexData
      62                 :             : {
      63                 :             :     IndexInfo  *indexInfo;      /* BuildIndexInfo result */
      64                 :             :     double      tupleFract;     /* fraction of rows for partial index */
      65                 :             :     VacAttrStats **vacattrstats;    /* index attrs to analyze */
      66                 :             :     int         attr_cnt;
      67                 :             : } AnlIndexData;
      68                 :             : 
      69                 :             : 
      70                 :             : /* Default statistics target (GUC parameter) */
      71                 :             : int         default_statistics_target = 100;
      72                 :             : 
      73                 :             : /* A few variables that don't seem worth passing around as parameters */
      74                 :             : static MemoryContext anl_context = NULL;
      75                 :             : static BufferAccessStrategy vac_strategy;
      76                 :             : 
      77                 :             : 
      78                 :             : static void do_analyze_rel(Relation onerel,
      79                 :             :                            const VacuumParams *params, List *va_cols,
      80                 :             :                            AcquireSampleRowsFunc acquirefunc, BlockNumber relpages,
      81                 :             :                            bool inh, bool in_outer_xact, int elevel);
      82                 :             : static void compute_index_stats(Relation onerel, double totalrows,
      83                 :             :                                 AnlIndexData *indexdata, int nindexes,
      84                 :             :                                 HeapTuple *rows, int numrows,
      85                 :             :                                 MemoryContext col_context);
      86                 :             : static void validate_va_cols_list(Relation onerel, List *va_cols);
      87                 :             : static VacAttrStats *examine_attribute(Relation onerel, int attnum,
      88                 :             :                                        Node *index_expr);
      89                 :             : static int  acquire_sample_rows(Relation onerel, int elevel,
      90                 :             :                                 HeapTuple *rows, int targrows,
      91                 :             :                                 double *totalrows, double *totaldeadrows);
      92                 :             : static int  compare_rows(const void *a, const void *b, void *arg);
      93                 :             : static int  acquire_inherited_sample_rows(Relation onerel, int elevel,
      94                 :             :                                           HeapTuple *rows, int targrows,
      95                 :             :                                           double *totalrows, double *totaldeadrows);
      96                 :             : static void update_attstats(Oid relid, bool inh,
      97                 :             :                             int natts, VacAttrStats **vacattrstats);
      98                 :             : static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
      99                 :             : static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
     100                 :             : 
     101                 :             : 
     102                 :             : /*
     103                 :             :  *  analyze_rel() -- analyze one relation
     104                 :             :  *
     105                 :             :  * relid identifies the relation to analyze.  If relation is supplied, use
     106                 :             :  * the name therein for reporting any failure to open/lock the rel; do not
     107                 :             :  * use it once we've successfully opened the rel, since it might be stale.
     108                 :             :  */
     109                 :             : void
     110                 :       10716 : analyze_rel(Oid relid, RangeVar *relation,
     111                 :             :             const VacuumParams *params, List *va_cols, bool in_outer_xact,
     112                 :             :             BufferAccessStrategy bstrategy)
     113                 :             : {
     114                 :             :     Relation    onerel;
     115                 :             :     int         elevel;
     116                 :       10716 :     AcquireSampleRowsFunc acquirefunc = NULL;
     117                 :       10716 :     BlockNumber relpages = 0;
     118                 :       10716 :     bool        stats_imported = false;
     119                 :             : 
     120                 :             :     /* Select logging level */
     121         [ +  + ]:       10716 :     if (params->options & VACOPT_VERBOSE)
     122                 :           7 :         elevel = INFO;
     123                 :             :     else
     124                 :       10709 :         elevel = DEBUG2;
     125                 :             : 
     126                 :             :     /* Set up static variables */
     127                 :       10716 :     vac_strategy = bstrategy;
     128                 :             : 
     129                 :             :     /*
     130                 :             :      * Check for user-requested abort.
     131                 :             :      */
     132         [ +  + ]:       10716 :     CHECK_FOR_INTERRUPTS();
     133                 :             : 
     134                 :             :     /*
     135                 :             :      * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
     136                 :             :      * ANALYZEs don't run on it concurrently.  (This also locks out a
     137                 :             :      * concurrent VACUUM, which doesn't matter much at the moment but might
     138                 :             :      * matter if we ever try to accumulate stats on dead tuples.) If the rel
     139                 :             :      * has been dropped since we last saw it, we don't need to process it.
     140                 :             :      *
     141                 :             :      * Make sure to generate only logs for ANALYZE in this case.
     142                 :             :      */
     143                 :       10716 :     onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
     144                 :       10716 :                                   params->log_analyze_min_duration >= 0,
     145                 :             :                                   ShareUpdateExclusiveLock);
     146                 :             : 
     147                 :             :     /* leave if relation could not be opened or locked */
     148         [ +  + ]:       10716 :     if (!onerel)
     149                 :         129 :         return;
     150                 :             : 
     151                 :             :     /*
     152                 :             :      * Check if relation needs to be skipped based on privileges.  This check
     153                 :             :      * happens also when building the relation list to analyze for a manual
     154                 :             :      * operation, and needs to be done additionally here as ANALYZE could
     155                 :             :      * happen across multiple transactions where privileges could have changed
     156                 :             :      * in-between.  Make sure to generate only logs for ANALYZE in this case.
     157                 :             :      */
     158         [ +  + ]:       10708 :     if (!vacuum_is_permitted_for_relation(RelationGetRelid(onerel),
     159                 :             :                                           onerel->rd_rel,
     160                 :       10708 :                                           params->options & ~VACOPT_VACUUM,
     161                 :             :                                           false))
     162                 :             :     {
     163                 :          24 :         relation_close(onerel, ShareUpdateExclusiveLock);
     164                 :          24 :         return;
     165                 :             :     }
     166                 :             : 
     167                 :             :     /*
     168                 :             :      * Silently ignore tables that are temp tables of other backends ---
     169                 :             :      * trying to analyze these is rather pointless, since their contents are
     170                 :             :      * probably not up-to-date on disk.  (We don't throw a warning here; it
     171                 :             :      * would just lead to chatter during a database-wide ANALYZE.)
     172                 :             :      */
     173   [ +  +  -  + ]:       10684 :     if (RELATION_IS_OTHER_TEMP(onerel))
     174                 :             :     {
     175                 :           0 :         relation_close(onerel, ShareUpdateExclusiveLock);
     176                 :           0 :         return;
     177                 :             :     }
     178                 :             : 
     179                 :             :     /*
     180                 :             :      * We can ANALYZE any table except pg_statistic. See update_attstats
     181                 :             :      */
     182         [ +  + ]:       10684 :     if (RelationGetRelid(onerel) == StatisticRelationId)
     183                 :             :     {
     184                 :          97 :         relation_close(onerel, ShareUpdateExclusiveLock);
     185                 :          97 :         return;
     186                 :             :     }
     187                 :             : 
     188                 :             :     /*
     189                 :             :      * Check the given list of columns
     190                 :             :      */
     191         [ +  + ]:       10587 :     if (va_cols != NIL)
     192                 :          75 :         validate_va_cols_list(onerel, va_cols);
     193                 :             : 
     194                 :             :     /*
     195                 :             :      * Initialize progress reporting before setup for regular/foreign tables.
     196                 :             :      * (For the former, the time spent on it would be negligible, but for the
     197                 :             :      * latter, if FDWs support statistics import or analysis, they'd do some
     198                 :             :      * work that needs the remote access, so the time might be
     199                 :             :      * non-negligible.)
     200                 :             :      */
     201                 :       10552 :     pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
     202                 :             :                                   RelationGetRelid(onerel));
     203         [ +  + ]:       10552 :     if (AmAutoVacuumWorkerProcess())
     204                 :         467 :         pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
     205                 :             :                                      PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
     206                 :             :     else
     207                 :       10085 :         pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
     208                 :             :                                      PROGRESS_ANALYZE_STARTED_BY_MANUAL);
     209                 :             : 
     210                 :             :     /*
     211                 :             :      * Check that it's of an analyzable relkind, and set up appropriately.
     212                 :             :      */
     213         [ +  + ]:       10552 :     if (onerel->rd_rel->relkind == RELKIND_RELATION ||
     214         [ +  + ]:         552 :         onerel->rd_rel->relkind == RELKIND_MATVIEW)
     215                 :             :     {
     216                 :             :         /* Regular table, so we'll use the regular row acquisition function */
     217                 :       10002 :         acquirefunc = acquire_sample_rows;
     218                 :             :         /* Also get regular table's size */
     219                 :       10002 :         relpages = RelationGetNumberOfBlocks(onerel);
     220                 :             :     }
     221         [ +  + ]:         550 :     else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
     222                 :             :     {
     223                 :             :         /*
     224                 :             :          * For a foreign table, call the FDW's hook functions to see whether
     225                 :             :          * it supports statistics import or analysis.
     226                 :             :          */
     227                 :             :         FdwRoutine *fdwroutine;
     228                 :             : 
     229                 :          45 :         fdwroutine = GetFdwRoutineForRelation(onerel, false);
     230                 :             : 
     231   [ +  +  +  + ]:          89 :         if (fdwroutine->ImportForeignStatistics != NULL &&
     232                 :          44 :             fdwroutine->ImportForeignStatistics(onerel, va_cols, elevel))
     233                 :           7 :             stats_imported = true;
     234                 :             :         else
     235                 :             :         {
     236                 :          38 :             bool        ok = false;
     237                 :             : 
     238         [ +  - ]:          38 :             if (fdwroutine->AnalyzeForeignTable != NULL)
     239                 :          38 :                 ok = fdwroutine->AnalyzeForeignTable(onerel,
     240                 :             :                                                      &acquirefunc,
     241                 :             :                                                      &relpages);
     242                 :             : 
     243         [ -  + ]:          38 :             if (!ok)
     244                 :             :             {
     245         [ #  # ]:           0 :                 ereport(WARNING,
     246                 :             :                         errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
     247                 :             :                                RelationGetRelationName(onerel)));
     248                 :           0 :                 relation_close(onerel, ShareUpdateExclusiveLock);
     249                 :           0 :                 goto out;
     250                 :             :             }
     251                 :             :         }
     252                 :             :     }
     253         [ -  + ]:         505 :     else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     254                 :             :     {
     255                 :             :         /*
     256                 :             :          * For partitioned tables, we want to do the recursive ANALYZE below.
     257                 :             :          */
     258                 :             :     }
     259                 :             :     else
     260                 :             :     {
     261                 :             :         /* No need for a WARNING if we already complained during VACUUM */
     262         [ #  # ]:           0 :         if (!(params->options & VACOPT_VACUUM))
     263         [ #  # ]:           0 :             ereport(WARNING,
     264                 :             :                     (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
     265                 :             :                             RelationGetRelationName(onerel))));
     266                 :           0 :         relation_close(onerel, ShareUpdateExclusiveLock);
     267                 :           0 :         goto out;
     268                 :             :     }
     269                 :             : 
     270                 :             :     /*
     271                 :             :      * Do the normal non-recursive ANALYZE.  We can skip this for partitioned
     272                 :             :      * tables, which don't contain any rows, and foreign tables that
     273                 :             :      * successfully imported statistics.
     274                 :             :      */
     275         [ +  + ]:       10552 :     if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
     276         [ +  + ]:       10047 :         && !stats_imported)
     277                 :       10040 :         do_analyze_rel(onerel, params, va_cols, acquirefunc,
     278                 :             :                        relpages, false, in_outer_xact, elevel);
     279                 :             : 
     280                 :             :     /*
     281                 :             :      * If there are child tables, do recursive ANALYZE.
     282                 :             :      */
     283         [ +  + ]:       10545 :     if (onerel->rd_rel->relhassubclass)
     284                 :         602 :         do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
     285                 :             :                        true, in_outer_xact, elevel);
     286                 :             : 
     287                 :             :     /*
     288                 :             :      * Close source relation now, but keep lock so that no one deletes it
     289                 :             :      * before we commit.  (If someone did, they'd fail to clean up the entries
     290                 :             :      * we made in pg_statistic.  Also, releasing the lock before commit would
     291                 :             :      * expose us to concurrent-update failures in update_attstats.)
     292                 :             :      */
     293                 :       10545 :     relation_close(onerel, NoLock);
     294                 :             : 
     295                 :       10545 : out:
     296                 :       10545 :     pgstat_progress_end_command();
     297                 :             : }
     298                 :             : 
     299                 :             : /*
     300                 :             :  *  do_analyze_rel() -- analyze one relation, recursively or not
     301                 :             :  *
     302                 :             :  * Note that "acquirefunc" is only relevant for the non-inherited case.
     303                 :             :  * For the inherited case, acquire_inherited_sample_rows() determines the
     304                 :             :  * appropriate acquirefunc for each child table.
     305                 :             :  */
     306                 :             : static void
     307                 :       10642 : do_analyze_rel(Relation onerel, const VacuumParams *params,
     308                 :             :                List *va_cols, AcquireSampleRowsFunc acquirefunc,
     309                 :             :                BlockNumber relpages, bool inh, bool in_outer_xact,
     310                 :             :                int elevel)
     311                 :             : {
     312                 :             :     int         attr_cnt,
     313                 :             :                 tcnt,
     314                 :             :                 i,
     315                 :             :                 ind;
     316                 :             :     Relation   *Irel;
     317                 :             :     int         nindexes;
     318                 :             :     bool        verbose,
     319                 :             :                 instrument,
     320                 :             :                 hasindex;
     321                 :             :     VacAttrStats **vacattrstats;
     322                 :             :     AnlIndexData *indexdata;
     323                 :             :     int         targrows,
     324                 :             :                 numrows,
     325                 :             :                 minrows;
     326                 :             :     double      totalrows,
     327                 :             :                 totaldeadrows;
     328                 :             :     HeapTuple  *rows;
     329                 :             :     PGRUsage    ru0;
     330                 :       10642 :     TimestampTz starttime = 0;
     331                 :             :     MemoryContext caller_context;
     332                 :             :     Oid         save_userid;
     333                 :             :     int         save_sec_context;
     334                 :             :     int         save_nestlevel;
     335                 :       10642 :     WalUsage    startwalusage = pgWalUsage;
     336                 :       10642 :     BufferUsage startbufferusage = pgBufferUsage;
     337                 :             :     BufferUsage bufferusage;
     338                 :       10642 :     PgStat_Counter startreadtime = 0;
     339                 :       10642 :     PgStat_Counter startwritetime = 0;
     340                 :             : 
     341                 :       10642 :     verbose = (params->options & VACOPT_VERBOSE) != 0;
     342   [ +  -  +  + ]:       11113 :     instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
     343         [ +  - ]:         471 :                               params->log_analyze_min_duration >= 0));
     344         [ +  + ]:       10642 :     if (inh)
     345         [ -  + ]:         602 :         ereport(elevel,
     346                 :             :                 (errmsg("analyzing \"%s.%s\" inheritance tree",
     347                 :             :                         get_namespace_name(RelationGetNamespace(onerel)),
     348                 :             :                         RelationGetRelationName(onerel))));
     349                 :             :     else
     350         [ +  + ]:       10040 :         ereport(elevel,
     351                 :             :                 (errmsg("analyzing \"%s.%s\"",
     352                 :             :                         get_namespace_name(RelationGetNamespace(onerel)),
     353                 :             :                         RelationGetRelationName(onerel))));
     354                 :             : 
     355                 :             :     /*
     356                 :             :      * Set up a working context so that we can easily free whatever junk gets
     357                 :             :      * created.
     358                 :             :      */
     359                 :       10642 :     anl_context = AllocSetContextCreate(CurrentMemoryContext,
     360                 :             :                                         "Analyze",
     361                 :             :                                         ALLOCSET_DEFAULT_SIZES);
     362                 :       10642 :     caller_context = MemoryContextSwitchTo(anl_context);
     363                 :             : 
     364                 :             :     /*
     365                 :             :      * Switch to the table owner's userid, so that any index functions are run
     366                 :             :      * as that user.  Also lock down security-restricted operations and
     367                 :             :      * arrange to make GUC variable changes local to this command.
     368                 :             :      */
     369                 :       10642 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
     370                 :       10642 :     SetUserIdAndSecContext(onerel->rd_rel->relowner,
     371                 :             :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
     372                 :       10642 :     save_nestlevel = NewGUCNestLevel();
     373                 :       10642 :     RestrictSearchPath();
     374                 :             : 
     375                 :             :     /*
     376                 :             :      * When verbose or autovacuum logging is used, initialize a resource usage
     377                 :             :      * snapshot and optionally track I/O timing.
     378                 :             :      */
     379         [ +  + ]:       10642 :     if (instrument)
     380                 :             :     {
     381         [ -  + ]:         471 :         if (track_io_timing)
     382                 :             :         {
     383                 :           0 :             startreadtime = pgStatBlockReadTime;
     384                 :           0 :             startwritetime = pgStatBlockWriteTime;
     385                 :             :         }
     386                 :             : 
     387                 :         471 :         pg_rusage_init(&ru0);
     388                 :             :     }
     389                 :             : 
     390                 :             :     /* Used for instrumentation and stats report */
     391                 :       10642 :     starttime = GetCurrentTimestamp();
     392                 :             : 
     393                 :             :     /*
     394                 :             :      * Determine which columns to analyze.
     395                 :             :      */
     396         [ +  + ]:       10642 :     if (va_cols != NIL)
     397                 :             :     {
     398                 :             :         ListCell   *le;
     399                 :             : 
     400                 :          40 :         vacattrstats = palloc_array(VacAttrStats *, list_length(va_cols));
     401                 :          40 :         tcnt = 0;
     402   [ +  -  +  +  :          85 :         foreach(le, va_cols)
                   +  + ]
     403                 :             :         {
     404                 :          45 :             char       *col = strVal(lfirst(le));
     405                 :             : 
     406                 :          45 :             i = attnameAttNum(onerel, col, false);
     407                 :             :             Assert(i != InvalidAttrNumber);
     408                 :          45 :             vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
     409         [ +  - ]:          45 :             if (vacattrstats[tcnt] != NULL)
     410                 :          45 :                 tcnt++;
     411                 :             :         }
     412                 :          40 :         attr_cnt = tcnt;
     413                 :             :     }
     414                 :             :     else
     415                 :             :     {
     416                 :       10602 :         attr_cnt = onerel->rd_att->natts;
     417                 :       10602 :         vacattrstats = palloc_array(VacAttrStats *, attr_cnt);
     418                 :       10602 :         tcnt = 0;
     419         [ +  + ]:       85245 :         for (i = 1; i <= attr_cnt; i++)
     420                 :             :         {
     421                 :       74643 :             vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
     422         [ +  + ]:       74643 :             if (vacattrstats[tcnt] != NULL)
     423                 :       74552 :                 tcnt++;
     424                 :             :         }
     425                 :       10602 :         attr_cnt = tcnt;
     426                 :             :     }
     427                 :             : 
     428                 :             :     /*
     429                 :             :      * Open all indexes of the relation, and see if there are any analyzable
     430                 :             :      * columns in the indexes.  We do not analyze index columns if there was
     431                 :             :      * an explicit column list in the ANALYZE command, however.
     432                 :             :      *
     433                 :             :      * If we are doing a recursive scan, we don't want to touch the parent's
     434                 :             :      * indexes at all.  If we're processing a partitioned table, we need to
     435                 :             :      * know if there are any indexes, but we don't want to process them.
     436                 :             :      */
     437         [ +  + ]:       10642 :     if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     438                 :             :     {
     439                 :         505 :         List       *idxs = RelationGetIndexList(onerel);
     440                 :             : 
     441                 :         505 :         Irel = NULL;
     442                 :         505 :         nindexes = 0;
     443                 :         505 :         hasindex = idxs != NIL;
     444                 :         505 :         list_free(idxs);
     445                 :             :     }
     446         [ +  + ]:       10137 :     else if (!inh)
     447                 :             :     {
     448                 :       10040 :         vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
     449                 :       10040 :         hasindex = nindexes > 0;
     450                 :             :     }
     451                 :             :     else
     452                 :             :     {
     453                 :          97 :         Irel = NULL;
     454                 :          97 :         nindexes = 0;
     455                 :          97 :         hasindex = false;
     456                 :             :     }
     457                 :       10642 :     indexdata = NULL;
     458         [ +  + ]:       10642 :     if (nindexes > 0)
     459                 :             :     {
     460                 :        7781 :         indexdata = palloc0_array(AnlIndexData, nindexes);
     461         [ +  + ]:       22488 :         for (ind = 0; ind < nindexes; ind++)
     462                 :             :         {
     463                 :       14707 :             AnlIndexData *thisdata = &indexdata[ind];
     464                 :             :             IndexInfo  *indexInfo;
     465                 :             : 
     466                 :       14707 :             thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
     467                 :       14707 :             thisdata->tupleFract = 1.0; /* fix later if partial */
     468   [ +  +  +  - ]:       14707 :             if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
     469                 :             :             {
     470                 :          92 :                 ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
     471                 :             : 
     472                 :          92 :                 thisdata->vacattrstats = palloc_array(VacAttrStats *,
     473                 :             :                                                       indexInfo->ii_NumIndexAttrs);
     474                 :          92 :                 tcnt = 0;
     475         [ +  + ]:         190 :                 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
     476                 :             :                 {
     477                 :          98 :                     int         keycol = indexInfo->ii_IndexAttrNumbers[i];
     478                 :             : 
     479         [ +  + ]:          98 :                     if (keycol == 0)
     480                 :             :                     {
     481                 :             :                         /* Found an index expression */
     482                 :             :                         Node       *indexkey;
     483                 :             : 
     484         [ -  + ]:          92 :                         if (indexpr_item == NULL)   /* shouldn't happen */
     485         [ #  # ]:           0 :                             elog(ERROR, "too few entries in indexprs list");
     486                 :          92 :                         indexkey = (Node *) lfirst(indexpr_item);
     487                 :          92 :                         indexpr_item = lnext(indexInfo->ii_Expressions,
     488                 :             :                                              indexpr_item);
     489                 :         184 :                         thisdata->vacattrstats[tcnt] =
     490                 :          92 :                             examine_attribute(Irel[ind], i + 1, indexkey);
     491         [ +  - ]:          92 :                         if (thisdata->vacattrstats[tcnt] != NULL)
     492                 :          92 :                             tcnt++;
     493                 :             :                     }
     494                 :             :                 }
     495                 :          92 :                 thisdata->attr_cnt = tcnt;
     496                 :             :             }
     497                 :             :         }
     498                 :             :     }
     499                 :             : 
     500                 :             :     /*
     501                 :             :      * Determine how many rows we need to sample, using the worst case from
     502                 :             :      * all analyzable columns.  We use a lower bound of 100 rows to avoid
     503                 :             :      * possible overflow in Vitter's algorithm.  (Note: that will also be the
     504                 :             :      * target in the corner case where there are no analyzable columns.)
     505                 :             :      */
     506                 :       10642 :     targrows = 100;
     507         [ +  + ]:       85239 :     for (i = 0; i < attr_cnt; i++)
     508                 :             :     {
     509         [ +  + ]:       74597 :         if (targrows < vacattrstats[i]->minrows)
     510                 :       10593 :             targrows = vacattrstats[i]->minrows;
     511                 :             :     }
     512         [ +  + ]:       25349 :     for (ind = 0; ind < nindexes; ind++)
     513                 :             :     {
     514                 :       14707 :         AnlIndexData *thisdata = &indexdata[ind];
     515                 :             : 
     516         [ +  + ]:       14799 :         for (i = 0; i < thisdata->attr_cnt; i++)
     517                 :             :         {
     518         [ +  + ]:          92 :             if (targrows < thisdata->vacattrstats[i]->minrows)
     519                 :           8 :                 targrows = thisdata->vacattrstats[i]->minrows;
     520                 :             :         }
     521                 :             :     }
     522                 :             : 
     523                 :             :     /*
     524                 :             :      * Look at extended statistics objects too, as those may define custom
     525                 :             :      * statistics target. So we may need to sample more rows and then build
     526                 :             :      * the statistics with enough detail.
     527                 :             :      */
     528                 :       10642 :     minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
     529                 :             : 
     530         [ -  + ]:       10642 :     if (targrows < minrows)
     531                 :           0 :         targrows = minrows;
     532                 :             : 
     533                 :             :     /*
     534                 :             :      * Acquire the sample rows
     535                 :             :      */
     536                 :       10642 :     rows = palloc_array(HeapTuple, targrows);
     537         [ +  + ]:       10642 :     pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
     538                 :             :                                  inh ? PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH :
     539                 :             :                                  PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS);
     540         [ +  + ]:       10642 :     if (inh)
     541                 :         602 :         numrows = acquire_inherited_sample_rows(onerel, elevel,
     542                 :             :                                                 rows, targrows,
     543                 :             :                                                 &totalrows, &totaldeadrows);
     544                 :             :     else
     545                 :       10040 :         numrows = (*acquirefunc) (onerel, elevel,
     546                 :             :                                   rows, targrows,
     547                 :             :                                   &totalrows, &totaldeadrows);
     548                 :             : 
     549                 :             :     /*
     550                 :             :      * Compute the statistics.  Temporary results during the calculations for
     551                 :             :      * each column are stored in a child context.  The calc routines are
     552                 :             :      * responsible to make sure that whatever they store into the VacAttrStats
     553                 :             :      * structure is allocated in anl_context.
     554                 :             :      */
     555         [ +  + ]:       10641 :     if (numrows > 0)
     556                 :             :     {
     557                 :             :         MemoryContext col_context,
     558                 :             :                     old_context;
     559                 :             : 
     560                 :        7095 :         pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
     561                 :             :                                      PROGRESS_ANALYZE_PHASE_COMPUTE_STATS);
     562                 :             : 
     563                 :        7095 :         col_context = AllocSetContextCreate(anl_context,
     564                 :             :                                             "Analyze Column",
     565                 :             :                                             ALLOCSET_DEFAULT_SIZES);
     566                 :        7095 :         old_context = MemoryContextSwitchTo(col_context);
     567                 :             : 
     568         [ +  + ]:       59963 :         for (i = 0; i < attr_cnt; i++)
     569                 :             :         {
     570                 :       52870 :             VacAttrStats *stats = vacattrstats[i];
     571                 :             :             AttributeOpts *aopt;
     572                 :             : 
     573                 :       52870 :             stats->rows = rows;
     574                 :       52870 :             stats->tupDesc = onerel->rd_att;
     575                 :       52870 :             stats->compute_stats(stats,
     576                 :             :                                  std_fetch_func,
     577                 :             :                                  numrows,
     578                 :             :                                  totalrows);
     579                 :             : 
     580                 :             :             /*
     581                 :             :              * If the appropriate flavor of the n_distinct option is
     582                 :             :              * specified, override with the corresponding value.
     583                 :             :              */
     584                 :       52868 :             aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
     585         [ +  + ]:       52868 :             if (aopt != NULL)
     586                 :             :             {
     587                 :             :                 float8      n_distinct;
     588                 :             : 
     589         [ -  + ]:           4 :                 n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
     590         [ +  - ]:           4 :                 if (n_distinct != 0.0)
     591                 :           4 :                     stats->stadistinct = n_distinct;
     592                 :             :             }
     593                 :             : 
     594                 :       52868 :             MemoryContextReset(col_context);
     595                 :             :         }
     596                 :             : 
     597         [ +  + ]:        7093 :         if (nindexes > 0)
     598                 :        4435 :             compute_index_stats(onerel, totalrows,
     599                 :             :                                 indexdata, nindexes,
     600                 :             :                                 rows, numrows,
     601                 :             :                                 col_context);
     602                 :             : 
     603                 :        7089 :         MemoryContextSwitchTo(old_context);
     604                 :        7089 :         MemoryContextDelete(col_context);
     605                 :             : 
     606                 :             :         /*
     607                 :             :          * Emit the completed stats rows into pg_statistic, replacing any
     608                 :             :          * previous statistics for the target columns.  (If there are stats in
     609                 :             :          * pg_statistic for columns we didn't process, we leave them alone.)
     610                 :             :          */
     611                 :        7089 :         update_attstats(RelationGetRelid(onerel), inh,
     612                 :             :                         attr_cnt, vacattrstats);
     613                 :             : 
     614         [ +  + ]:       15620 :         for (ind = 0; ind < nindexes; ind++)
     615                 :             :         {
     616                 :        8531 :             AnlIndexData *thisdata = &indexdata[ind];
     617                 :             : 
     618                 :        8531 :             update_attstats(RelationGetRelid(Irel[ind]), false,
     619                 :             :                             thisdata->attr_cnt, thisdata->vacattrstats);
     620                 :             :         }
     621                 :             : 
     622                 :             :         /* Build extended statistics (if there are any). */
     623                 :        7089 :         BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
     624                 :             :                                    attr_cnt, vacattrstats);
     625                 :             :     }
     626                 :             : 
     627                 :       10635 :     pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
     628                 :             :                                  PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE);
     629                 :             : 
     630                 :             :     /*
     631                 :             :      * Update pages/tuples stats in pg_class ... but not if we're doing
     632                 :             :      * inherited stats.
     633                 :             :      *
     634                 :             :      * We assume that VACUUM hasn't set pg_class.reltuples already, even
     635                 :             :      * during a VACUUM ANALYZE.  Although VACUUM often updates pg_class,
     636                 :             :      * exceptions exist.  A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command will
     637                 :             :      * never update pg_class entries for index relations.  It's also possible
     638                 :             :      * that an individual index's pg_class entry won't be updated during
     639                 :             :      * VACUUM if the index AM returns NULL from its amvacuumcleanup() routine.
     640                 :             :      */
     641         [ +  + ]:       10635 :     if (!inh)
     642                 :             :     {
     643                 :       10033 :         BlockNumber relallvisible = 0;
     644                 :       10033 :         BlockNumber relallfrozen = 0;
     645                 :             : 
     646   [ +  +  +  -  :       10033 :         if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
          +  -  +  -  +  
                      + ]
     647                 :        9996 :             visibilitymap_count(onerel, &relallvisible, &relallfrozen);
     648                 :             : 
     649                 :             :         /*
     650                 :             :          * Update pg_class for table relation.  CCI first, in case acquirefunc
     651                 :             :          * updated pg_class.
     652                 :             :          */
     653                 :       10033 :         CommandCounterIncrement();
     654                 :       10033 :         vac_update_relstats(onerel,
     655                 :             :                             relpages,
     656                 :             :                             totalrows,
     657                 :             :                             relallvisible,
     658                 :             :                             relallfrozen,
     659                 :             :                             hasindex,
     660                 :             :                             InvalidTransactionId,
     661                 :             :                             InvalidMultiXactId,
     662                 :             :                             NULL, NULL,
     663                 :             :                             in_outer_xact);
     664                 :             : 
     665                 :             :         /* Same for indexes */
     666         [ +  + ]:       24723 :         for (ind = 0; ind < nindexes; ind++)
     667                 :             :         {
     668                 :       14690 :             AnlIndexData *thisdata = &indexdata[ind];
     669                 :             :             double      totalindexrows;
     670                 :             : 
     671                 :       14690 :             totalindexrows = ceil(thisdata->tupleFract * totalrows);
     672                 :       14690 :             vac_update_relstats(Irel[ind],
     673                 :       14690 :                                 RelationGetNumberOfBlocks(Irel[ind]),
     674                 :             :                                 totalindexrows,
     675                 :             :                                 0, 0,
     676                 :             :                                 false,
     677                 :             :                                 InvalidTransactionId,
     678                 :             :                                 InvalidMultiXactId,
     679                 :             :                                 NULL, NULL,
     680                 :             :                                 in_outer_xact);
     681                 :             :         }
     682                 :             :     }
     683         [ +  + ]:         602 :     else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     684                 :             :     {
     685                 :             :         /*
     686                 :             :          * Partitioned tables don't have storage, so we don't set any fields
     687                 :             :          * in their pg_class entries except for reltuples and relhasindex.
     688                 :             :          */
     689                 :         505 :         CommandCounterIncrement();
     690                 :         505 :         vac_update_relstats(onerel, -1, totalrows,
     691                 :             :                             0, 0, hasindex, InvalidTransactionId,
     692                 :             :                             InvalidMultiXactId,
     693                 :             :                             NULL, NULL,
     694                 :             :                             in_outer_xact);
     695                 :             :     }
     696                 :             : 
     697                 :             :     /*
     698                 :             :      * Now report ANALYZE to the cumulative stats system.  For regular tables,
     699                 :             :      * we do it only if not doing inherited stats.  For partitioned tables, we
     700                 :             :      * only do it for inherited stats. (We're never called for not-inherited
     701                 :             :      * stats on partitioned tables anyway.)
     702                 :             :      *
     703                 :             :      * Reset the mod_since_analyze counter only if we analyzed all columns;
     704                 :             :      * otherwise, there is still work for auto-analyze to do.
     705                 :             :      */
     706         [ +  + ]:       10635 :     if (!inh)
     707                 :       10033 :         pgstat_report_analyze(onerel, totalrows, totaldeadrows,
     708                 :             :                               (va_cols == NIL), starttime);
     709         [ +  + ]:         602 :     else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     710                 :         505 :         pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL), starttime);
     711                 :             : 
     712                 :             :     /*
     713                 :             :      * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
     714                 :             :      *
     715                 :             :      * Note that most index AMs perform a no-op as a matter of policy for
     716                 :             :      * amvacuumcleanup() when called in ANALYZE-only mode.  The only exception
     717                 :             :      * among core index AMs is GIN/ginvacuumcleanup().
     718                 :             :      */
     719         [ +  + ]:       10635 :     if (!(params->options & VACOPT_VACUUM))
     720                 :             :     {
     721         [ +  + ]:       19893 :         for (ind = 0; ind < nindexes; ind++)
     722                 :             :         {
     723                 :             :             IndexBulkDeleteResult *stats;
     724                 :             :             IndexVacuumInfo ivinfo;
     725                 :             : 
     726                 :       11320 :             ivinfo.index = Irel[ind];
     727                 :       11320 :             ivinfo.heaprel = onerel;
     728                 :       11320 :             ivinfo.analyze_only = true;
     729                 :       11320 :             ivinfo.estimated_count = true;
     730                 :       11320 :             ivinfo.message_level = elevel;
     731                 :       11320 :             ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
     732                 :       11320 :             ivinfo.strategy = vac_strategy;
     733                 :             : 
     734                 :       11320 :             stats = index_vacuum_cleanup(&ivinfo, NULL);
     735                 :             : 
     736         [ -  + ]:       11320 :             if (stats)
     737                 :           0 :                 pfree(stats);
     738                 :             :         }
     739                 :             :     }
     740                 :             : 
     741                 :             :     /* Done with indexes */
     742                 :       10635 :     vac_close_indexes(nindexes, Irel, NoLock);
     743                 :             : 
     744                 :             :     /* Log the action if appropriate */
     745         [ +  + ]:       10635 :     if (instrument)
     746                 :             :     {
     747                 :         469 :         TimestampTz endtime = GetCurrentTimestamp();
     748                 :             : 
     749   [ +  -  +  +  :         830 :         if (verbose || params->log_analyze_min_duration == 0 ||
                   -  + ]
     750                 :         361 :             TimestampDifferenceExceeds(starttime, endtime,
     751                 :         361 :                                        params->log_analyze_min_duration))
     752                 :             :         {
     753                 :             :             long        delay_in_ms;
     754                 :             :             WalUsage    walusage;
     755                 :         108 :             double      read_rate = 0;
     756                 :         108 :             double      write_rate = 0;
     757                 :             :             char       *msgfmt;
     758                 :             :             StringInfoData buf;
     759                 :             :             int64       total_blks_hit;
     760                 :             :             int64       total_blks_read;
     761                 :             :             int64       total_blks_dirtied;
     762                 :             : 
     763                 :         108 :             memset(&bufferusage, 0, sizeof(BufferUsage));
     764                 :         108 :             BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
     765                 :         108 :             memset(&walusage, 0, sizeof(WalUsage));
     766                 :         108 :             WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
     767                 :             : 
     768                 :         108 :             total_blks_hit = bufferusage.shared_blks_hit +
     769                 :         108 :                 bufferusage.local_blks_hit;
     770                 :         108 :             total_blks_read = bufferusage.shared_blks_read +
     771                 :         108 :                 bufferusage.local_blks_read;
     772                 :         108 :             total_blks_dirtied = bufferusage.shared_blks_dirtied +
     773                 :         108 :                 bufferusage.local_blks_dirtied;
     774                 :             : 
     775                 :             :             /*
     776                 :             :              * We do not expect an analyze to take > 25 days and it simplifies
     777                 :             :              * things a bit to use TimestampDifferenceMilliseconds.
     778                 :             :              */
     779                 :         108 :             delay_in_ms = TimestampDifferenceMilliseconds(starttime, endtime);
     780                 :             : 
     781                 :             :             /*
     782                 :             :              * Note that we are reporting these read/write rates in the same
     783                 :             :              * manner as VACUUM does, which means that while the 'average read
     784                 :             :              * rate' here actually corresponds to page misses and resulting
     785                 :             :              * reads which are also picked up by track_io_timing, if enabled,
     786                 :             :              * the 'average write rate' is actually talking about the rate of
     787                 :             :              * pages being dirtied, not being written out, so it's typical to
     788                 :             :              * have a non-zero 'avg write rate' while I/O timings only reports
     789                 :             :              * reads.
     790                 :             :              *
     791                 :             :              * It's not clear that an ANALYZE will ever result in
     792                 :             :              * FlushBuffer() being called, but we track and support reporting
     793                 :             :              * on I/O write time in case that changes as it's practically free
     794                 :             :              * to do so anyway.
     795                 :             :              */
     796                 :             : 
     797         [ +  - ]:         108 :             if (delay_in_ms > 0)
     798                 :             :             {
     799                 :         108 :                 read_rate = (double) BLCKSZ * total_blks_read /
     800                 :         108 :                     (1024 * 1024) / (delay_in_ms / 1000.0);
     801                 :         108 :                 write_rate = (double) BLCKSZ * total_blks_dirtied /
     802                 :         108 :                     (1024 * 1024) / (delay_in_ms / 1000.0);
     803                 :             :             }
     804                 :             : 
     805                 :             :             /*
     806                 :             :              * We split this up so we don't emit empty I/O timing values when
     807                 :             :              * track_io_timing isn't enabled.
     808                 :             :              */
     809                 :             : 
     810                 :         108 :             initStringInfo(&buf);
     811                 :             : 
     812         [ +  - ]:         108 :             if (AmAutoVacuumWorkerProcess())
     813                 :         108 :                 msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
     814                 :             :             else
     815                 :           0 :                 msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
     816                 :             : 
     817                 :         108 :             appendStringInfo(&buf, msgfmt,
     818                 :             :                              get_database_name(MyDatabaseId),
     819                 :         108 :                              get_namespace_name(RelationGetNamespace(onerel)),
     820                 :         108 :                              RelationGetRelationName(onerel));
     821         [ -  + ]:         108 :             if (track_cost_delay_timing)
     822                 :             :             {
     823                 :             :                 /*
     824                 :             :                  * We bypass the changecount mechanism because this value is
     825                 :             :                  * only updated by the calling process.
     826                 :             :                  */
     827                 :           0 :                 appendStringInfo(&buf, _("delay time: %.3f ms\n"),
     828                 :           0 :                                  (double) MyBEEntry->st_progress_param[PROGRESS_ANALYZE_DELAY_TIME] / 1000000.0);
     829                 :             :             }
     830         [ -  + ]:         108 :             if (track_io_timing)
     831                 :             :             {
     832                 :           0 :                 double      read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
     833                 :           0 :                 double      write_ms = (double) (pgStatBlockWriteTime - startwritetime) / 1000;
     834                 :             : 
     835                 :           0 :                 appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
     836                 :             :                                  read_ms, write_ms);
     837                 :             :             }
     838                 :         108 :             appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
     839                 :             :                              read_rate, write_rate);
     840                 :         108 :             appendStringInfo(&buf, _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
     841                 :             :                              total_blks_hit,
     842                 :             :                              total_blks_read,
     843                 :             :                              total_blks_dirtied);
     844                 :         108 :             appendStringInfo(&buf,
     845                 :         108 :                              _("WAL usage: %" PRId64 " records, %" PRId64 " full page images, %" PRIu64 " bytes, %" PRIu64 " full page image bytes, %" PRId64 " buffers full\n"),
     846                 :             :                              walusage.wal_records,
     847                 :             :                              walusage.wal_fpi,
     848                 :             :                              walusage.wal_bytes,
     849                 :             :                              walusage.wal_fpi_bytes,
     850                 :             :                              walusage.wal_buffers_full);
     851                 :         108 :             appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
     852                 :             : 
     853   [ -  +  +  - ]:         108 :             ereport(verbose ? INFO : LOG,
     854                 :             :                     (errmsg_internal("%s", buf.data)));
     855                 :             : 
     856                 :         108 :             pfree(buf.data);
     857                 :             :         }
     858                 :             :     }
     859                 :             : 
     860                 :             :     /* Roll back any GUC changes executed by index functions */
     861                 :       10635 :     AtEOXact_GUC(false, save_nestlevel);
     862                 :             : 
     863                 :             :     /* Restore userid and security context */
     864                 :       10635 :     SetUserIdAndSecContext(save_userid, save_sec_context);
     865                 :             : 
     866                 :             :     /* Restore current context and release memory */
     867                 :       10635 :     MemoryContextSwitchTo(caller_context);
     868                 :       10635 :     MemoryContextDelete(anl_context);
     869                 :       10635 :     anl_context = NULL;
     870                 :       10635 : }
     871                 :             : 
     872                 :             : /*
     873                 :             :  * Compute statistics about indexes of a relation
     874                 :             :  */
     875                 :             : static void
     876                 :        4435 : compute_index_stats(Relation onerel, double totalrows,
     877                 :             :                     AnlIndexData *indexdata, int nindexes,
     878                 :             :                     HeapTuple *rows, int numrows,
     879                 :             :                     MemoryContext col_context)
     880                 :             : {
     881                 :             :     MemoryContext ind_context,
     882                 :             :                 old_context;
     883                 :             :     Datum       values[INDEX_MAX_KEYS];
     884                 :             :     bool        isnull[INDEX_MAX_KEYS];
     885                 :             :     int         ind,
     886                 :             :                 i;
     887                 :             : 
     888                 :        4435 :     ind_context = AllocSetContextCreate(anl_context,
     889                 :             :                                         "Analyze Index",
     890                 :             :                                         ALLOCSET_DEFAULT_SIZES);
     891                 :        4435 :     old_context = MemoryContextSwitchTo(ind_context);
     892                 :             : 
     893         [ +  + ]:       12970 :     for (ind = 0; ind < nindexes; ind++)
     894                 :             :     {
     895                 :        8539 :         AnlIndexData *thisdata = &indexdata[ind];
     896                 :        8539 :         IndexInfo  *indexInfo = thisdata->indexInfo;
     897                 :        8539 :         int         attr_cnt = thisdata->attr_cnt;
     898                 :             :         TupleTableSlot *slot;
     899                 :             :         EState     *estate;
     900                 :             :         ExprContext *econtext;
     901                 :             :         ExprState  *predicate;
     902                 :             :         Datum      *exprvals;
     903                 :             :         bool       *exprnulls;
     904                 :             :         int         numindexrows,
     905                 :             :                     tcnt,
     906                 :             :                     rowno;
     907                 :             :         double      totalindexrows;
     908                 :             : 
     909                 :             :         /* Ignore index if no columns to analyze and not partial */
     910   [ +  +  +  + ]:        8539 :         if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
     911                 :        8422 :             continue;
     912                 :             : 
     913                 :             :         /*
     914                 :             :          * Need an EState for evaluation of index expressions and
     915                 :             :          * partial-index predicates.  Create it in the per-index context to be
     916                 :             :          * sure it gets cleaned up at the bottom of the loop.
     917                 :             :          */
     918                 :         117 :         estate = CreateExecutorState();
     919         [ -  + ]:         117 :         econtext = GetPerTupleExprContext(estate);
     920                 :             :         /* Need a slot to hold the current heap tuple, too */
     921                 :         117 :         slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
     922                 :             :                                         &TTSOpsHeapTuple);
     923                 :             : 
     924                 :             :         /* Arrange for econtext's scan tuple to be the tuple under test */
     925                 :         117 :         econtext->ecxt_scantuple = slot;
     926                 :             : 
     927                 :             :         /* Set up execution state for predicate. */
     928                 :         117 :         predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
     929                 :             : 
     930                 :             :         /* Compute and save index expression values */
     931                 :         117 :         exprvals = palloc_array(Datum, numrows * attr_cnt);
     932                 :         117 :         exprnulls = palloc_array(bool, numrows * attr_cnt);
     933                 :         117 :         numindexrows = 0;
     934                 :         117 :         tcnt = 0;
     935         [ +  + ]:      231230 :         for (rowno = 0; rowno < numrows; rowno++)
     936                 :             :         {
     937                 :      231117 :             HeapTuple   heapTuple = rows[rowno];
     938                 :             : 
     939                 :      231117 :             vacuum_delay_point(true);
     940                 :             : 
     941                 :             :             /*
     942                 :             :              * Reset the per-tuple context each time, to reclaim any cruft
     943                 :             :              * left behind by evaluating the predicate or index expressions.
     944                 :             :              */
     945                 :      231117 :             ResetExprContext(econtext);
     946                 :             : 
     947                 :             :             /* Set up for predicate or expression evaluation */
     948                 :      231117 :             ExecStoreHeapTuple(heapTuple, slot, false);
     949                 :             : 
     950                 :             :             /* If index is partial, check predicate */
     951         [ +  + ]:      231117 :             if (predicate != NULL)
     952                 :             :             {
     953         [ +  + ]:       97036 :                 if (!ExecQual(predicate, econtext))
     954                 :       56552 :                     continue;
     955                 :             :             }
     956                 :      174565 :             numindexrows++;
     957                 :             : 
     958         [ +  + ]:      174565 :             if (attr_cnt > 0)
     959                 :             :             {
     960                 :             :                 /*
     961                 :             :                  * Evaluate the index row to compute expression values. We
     962                 :             :                  * could do this by hand, but FormIndexDatum is convenient.
     963                 :             :                  */
     964                 :      134081 :                 FormIndexDatum(indexInfo,
     965                 :             :                                slot,
     966                 :             :                                estate,
     967                 :             :                                values,
     968                 :             :                                isnull);
     969                 :             : 
     970                 :             :                 /*
     971                 :             :                  * Save just the columns we care about.  We copy the values
     972                 :             :                  * into ind_context from the estate's per-tuple context.
     973                 :             :                  */
     974         [ +  + ]:      268154 :                 for (i = 0; i < attr_cnt; i++)
     975                 :             :                 {
     976                 :      134077 :                     VacAttrStats *stats = thisdata->vacattrstats[i];
     977                 :      134077 :                     int         attnum = stats->tupattnum;
     978                 :             : 
     979         [ +  + ]:      134077 :                     if (isnull[attnum - 1])
     980                 :             :                     {
     981                 :           8 :                         exprvals[tcnt] = (Datum) 0;
     982                 :           8 :                         exprnulls[tcnt] = true;
     983                 :             :                     }
     984                 :             :                     else
     985                 :             :                     {
     986                 :      268138 :                         exprvals[tcnt] = datumCopy(values[attnum - 1],
     987                 :      134069 :                                                    stats->attrtype->typbyval,
     988                 :      134069 :                                                    stats->attrtype->typlen);
     989                 :      134069 :                         exprnulls[tcnt] = false;
     990                 :             :                     }
     991                 :      134077 :                     tcnt++;
     992                 :             :                 }
     993                 :             :             }
     994                 :             :         }
     995                 :             : 
     996                 :             :         /*
     997                 :             :          * Having counted the number of rows that pass the predicate in the
     998                 :             :          * sample, we can estimate the total number of rows in the index.
     999                 :             :          */
    1000                 :         113 :         thisdata->tupleFract = (double) numindexrows / (double) numrows;
    1001                 :         113 :         totalindexrows = ceil(thisdata->tupleFract * totalrows);
    1002                 :             : 
    1003                 :             :         /*
    1004                 :             :          * Now we can compute the statistics for the expression columns.
    1005                 :             :          */
    1006         [ +  + ]:         113 :         if (numindexrows > 0)
    1007                 :             :         {
    1008                 :         108 :             MemoryContextSwitchTo(col_context);
    1009         [ +  + ]:         184 :             for (i = 0; i < attr_cnt; i++)
    1010                 :             :             {
    1011                 :          76 :                 VacAttrStats *stats = thisdata->vacattrstats[i];
    1012                 :             : 
    1013                 :          76 :                 stats->exprvals = exprvals + i;
    1014                 :          76 :                 stats->exprnulls = exprnulls + i;
    1015                 :          76 :                 stats->rowstride = attr_cnt;
    1016                 :          76 :                 stats->compute_stats(stats,
    1017                 :             :                                      ind_fetch_func,
    1018                 :             :                                      numindexrows,
    1019                 :             :                                      totalindexrows);
    1020                 :             : 
    1021                 :          76 :                 MemoryContextReset(col_context);
    1022                 :             :             }
    1023                 :             :         }
    1024                 :             : 
    1025                 :             :         /* And clean up */
    1026                 :         113 :         MemoryContextSwitchTo(ind_context);
    1027                 :             : 
    1028                 :         113 :         ExecDropSingleTupleTableSlot(slot);
    1029                 :         113 :         FreeExecutorState(estate);
    1030                 :         113 :         MemoryContextReset(ind_context);
    1031                 :             :     }
    1032                 :             : 
    1033                 :        4431 :     MemoryContextSwitchTo(old_context);
    1034                 :        4431 :     MemoryContextDelete(ind_context);
    1035                 :        4431 : }
    1036                 :             : 
    1037                 :             : /*
    1038                 :             :  * validate_va_cols_list -- validate the columns list given to analyze_rel
    1039                 :             :  *
    1040                 :             :  * Note that system attributes are never analyzed, so we just reject them at
    1041                 :             :  * the lookup stage.  We also reject duplicate column mentions.  (We could
    1042                 :             :  * alternatively ignore duplicates, but analyzing a column twice won't work;
    1043                 :             :  * we'd end up making a conflicting update in pg_statistic.)
    1044                 :             :  */
    1045                 :             : static void
    1046                 :          75 : validate_va_cols_list(Relation onerel, List *va_cols)
    1047                 :             : {
    1048                 :          75 :     Bitmapset  *unique_cols = NULL;
    1049                 :             :     ListCell   *le;
    1050                 :             : 
    1051                 :             :     Assert(va_cols != NIL);
    1052   [ +  -  +  +  :         139 :     foreach(le, va_cols)
                   +  + ]
    1053                 :             :     {
    1054                 :          99 :         char       *col = strVal(lfirst(le));
    1055                 :          99 :         int         i = attnameAttNum(onerel, col, false);
    1056                 :             : 
    1057         [ +  + ]:          99 :         if (i == InvalidAttrNumber)
    1058         [ +  - ]:          26 :             ereport(ERROR,
    1059                 :             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    1060                 :             :                      errmsg("column \"%s\" of relation \"%s\" does not exist",
    1061                 :             :                             col, RelationGetRelationName(onerel))));
    1062         [ +  + ]:          73 :         if (bms_is_member(i, unique_cols))
    1063         [ +  - ]:           9 :             ereport(ERROR,
    1064                 :             :                     (errcode(ERRCODE_DUPLICATE_COLUMN),
    1065                 :             :                      errmsg("column \"%s\" of relation \"%s\" appears more than once",
    1066                 :             :                             col, RelationGetRelationName(onerel))));
    1067                 :          64 :         unique_cols = bms_add_member(unique_cols, i);
    1068                 :             :     }
    1069                 :          40 : }
    1070                 :             : 
    1071                 :             : /*
    1072                 :             :  * examine_attribute -- pre-analysis of a single column
    1073                 :             :  *
    1074                 :             :  * Determine whether the column is analyzable; if so, create and initialize
    1075                 :             :  * a VacAttrStats struct for it.  If not, return NULL.
    1076                 :             :  *
    1077                 :             :  * If index_expr isn't NULL, then we're trying to analyze an expression index,
    1078                 :             :  * and index_expr is the expression tree representing the column's data.
    1079                 :             :  */
    1080                 :             : static VacAttrStats *
    1081                 :       74780 : examine_attribute(Relation onerel, int attnum, Node *index_expr)
    1082                 :             : {
    1083                 :       74780 :     Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
    1084                 :             :     int         attstattarget;
    1085                 :             :     HeapTuple   typtuple;
    1086                 :             :     VacAttrStats *stats;
    1087                 :             :     int         i;
    1088                 :             :     bool        ok;
    1089                 :             : 
    1090                 :             :     /*
    1091                 :             :      * Check if the column is analyzable.
    1092                 :             :      */
    1093         [ +  + ]:       74780 :     if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
    1094                 :          89 :         return NULL;
    1095                 :             : 
    1096                 :             :     /*
    1097                 :             :      * Create the VacAttrStats struct.
    1098                 :             :      */
    1099                 :       74691 :     stats = palloc0_object(VacAttrStats);
    1100                 :       74691 :     stats->attstattarget = attstattarget;
    1101                 :             : 
    1102                 :             :     /*
    1103                 :             :      * When analyzing an expression index, believe the expression tree's type
    1104                 :             :      * not the column datatype --- the latter might be the opckeytype storage
    1105                 :             :      * type of the opclass, which is not interesting for our purposes.  (Note:
    1106                 :             :      * if we did anything with non-expression index columns, we'd need to
    1107                 :             :      * figure out where to get the correct type info from, but for now that's
    1108                 :             :      * not a problem.)  It's not clear whether anyone will care about the
    1109                 :             :      * typmod, but we store that too just in case.
    1110                 :             :      */
    1111         [ +  + ]:       74691 :     if (index_expr)
    1112                 :             :     {
    1113                 :          92 :         stats->attrtypid = exprType(index_expr);
    1114                 :          92 :         stats->attrtypmod = exprTypmod(index_expr);
    1115                 :             : 
    1116                 :             :         /*
    1117                 :             :          * If a collation has been specified for the index column, use that in
    1118                 :             :          * preference to anything else; but if not, fall back to whatever we
    1119                 :             :          * can get from the expression.
    1120                 :             :          */
    1121         [ +  + ]:          92 :         if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
    1122                 :           9 :             stats->attrcollid = onerel->rd_indcollation[attnum - 1];
    1123                 :             :         else
    1124                 :          83 :             stats->attrcollid = exprCollation(index_expr);
    1125                 :             :     }
    1126                 :             :     else
    1127                 :             :     {
    1128                 :       74599 :         stats->attrtypid = attr->atttypid;
    1129                 :       74599 :         stats->attrtypmod = attr->atttypmod;
    1130                 :       74599 :         stats->attrcollid = attr->attcollation;
    1131                 :             :     }
    1132                 :             : 
    1133                 :       74691 :     typtuple = SearchSysCacheCopy1(TYPEOID,
    1134                 :             :                                    ObjectIdGetDatum(stats->attrtypid));
    1135         [ -  + ]:       74691 :     if (!HeapTupleIsValid(typtuple))
    1136         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
    1137                 :       74691 :     stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
    1138                 :       74691 :     stats->anl_context = anl_context;
    1139                 :       74691 :     stats->tupattnum = attnum;
    1140                 :             : 
    1141                 :             :     /*
    1142                 :             :      * The fields describing the stats->stavalues[n] element types default to
    1143                 :             :      * the type of the data being analyzed, but the type-specific typanalyze
    1144                 :             :      * function can change them if it wants to store something else.
    1145                 :             :      */
    1146         [ +  + ]:      448146 :     for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
    1147                 :             :     {
    1148                 :      373455 :         stats->statypid[i] = stats->attrtypid;
    1149                 :      373455 :         stats->statyplen[i] = stats->attrtype->typlen;
    1150                 :      373455 :         stats->statypbyval[i] = stats->attrtype->typbyval;
    1151                 :      373455 :         stats->statypalign[i] = stats->attrtype->typalign;
    1152                 :             :     }
    1153                 :             : 
    1154                 :             :     /*
    1155                 :             :      * Call the type-specific typanalyze function.  If none is specified, use
    1156                 :             :      * std_typanalyze().
    1157                 :             :      */
    1158         [ +  + ]:       74691 :     if (OidIsValid(stats->attrtype->typanalyze))
    1159                 :        5203 :         ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
    1160                 :             :                                            PointerGetDatum(stats)));
    1161                 :             :     else
    1162                 :       69488 :         ok = std_typanalyze(stats);
    1163                 :             : 
    1164   [ +  +  +  -  :       74691 :     if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
                   -  + ]
    1165                 :             :     {
    1166                 :           2 :         heap_freetuple(typtuple);
    1167                 :           2 :         pfree(stats);
    1168                 :           2 :         return NULL;
    1169                 :             :     }
    1170                 :             : 
    1171                 :       74689 :     return stats;
    1172                 :             : }
    1173                 :             : 
    1174                 :             : bool
    1175                 :       74797 : attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr,
    1176                 :             :                         int *p_attstattarget)
    1177                 :             : {
    1178                 :             :     int         attstattarget;
    1179                 :             :     HeapTuple   atttuple;
    1180                 :             :     Datum       dat;
    1181                 :             :     bool        isnull;
    1182                 :             : 
    1183                 :             :     /* Never analyze dropped columns */
    1184         [ +  + ]:       74797 :     if (attr->attisdropped)
    1185                 :           3 :         return false;
    1186                 :             : 
    1187                 :             :     /* Don't analyze virtual generated columns */
    1188         [ +  + ]:       74794 :     if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    1189                 :          79 :         return false;
    1190                 :             : 
    1191                 :             :     /*
    1192                 :             :      * Get attstattarget value.  Set to -1 if null.  (Analyze functions expect
    1193                 :             :      * -1 to mean use default_statistics_target; see for example
    1194                 :             :      * std_typanalyze.)
    1195                 :             :      */
    1196                 :       74715 :     atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
    1197         [ -  + ]:       74715 :     if (!HeapTupleIsValid(atttuple))
    1198         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    1199                 :             :              attnum, RelationGetRelid(onerel));
    1200                 :       74715 :     dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
    1201         [ +  + ]:       74715 :     attstattarget = isnull ? -1 : DatumGetInt16(dat);
    1202                 :       74715 :     ReleaseSysCache(atttuple);
    1203                 :             : 
    1204                 :             :     /* Don't analyze column if user has specified not to */
    1205         [ +  + ]:       74715 :     if (attstattarget == 0)
    1206                 :           7 :         return false;
    1207                 :             : 
    1208         [ +  + ]:       74708 :     if (p_attstattarget)
    1209                 :       74691 :         *p_attstattarget = attstattarget;
    1210                 :       74708 :     return true;
    1211                 :             : }
    1212                 :             : 
    1213                 :             : /*
    1214                 :             :  * Read stream callback returning the next BlockNumber as chosen by the
    1215                 :             :  * BlockSampling algorithm.
    1216                 :             :  */
    1217                 :             : static BlockNumber
    1218                 :      106151 : block_sampling_read_stream_next(ReadStream *stream,
    1219                 :             :                                 void *callback_private_data,
    1220                 :             :                                 void *per_buffer_data)
    1221                 :             : {
    1222                 :      106151 :     BlockSamplerData *bs = callback_private_data;
    1223                 :             : 
    1224         [ +  + ]:      106151 :     return BlockSampler_HasMore(bs) ? BlockSampler_Next(bs) : InvalidBlockNumber;
    1225                 :             : }
    1226                 :             : 
    1227                 :             : /*
    1228                 :             :  * acquire_sample_rows -- acquire a random sample of rows from the table
    1229                 :             :  *
    1230                 :             :  * Selected rows are returned in the caller-allocated array rows[], which
    1231                 :             :  * must have at least targrows entries.
    1232                 :             :  * The actual number of rows selected is returned as the function result.
    1233                 :             :  * We also estimate the total numbers of live and dead rows in the table,
    1234                 :             :  * and return them into *totalrows and *totaldeadrows, respectively.
    1235                 :             :  *
    1236                 :             :  * The returned list of tuples is in order by physical position in the table.
    1237                 :             :  * (We will rely on this later to derive correlation estimates.)
    1238                 :             :  *
    1239                 :             :  * As of May 2004 we use a new two-stage method:  Stage one selects up
    1240                 :             :  * to targrows random blocks (or all blocks, if there aren't so many).
    1241                 :             :  * Stage two scans these blocks and uses the Vitter algorithm to create
    1242                 :             :  * a random sample of targrows rows (or less, if there are less in the
    1243                 :             :  * sample of blocks).  The two stages are executed simultaneously: each
    1244                 :             :  * block is processed as soon as stage one returns its number and while
    1245                 :             :  * the rows are read stage two controls which ones are to be inserted
    1246                 :             :  * into the sample.
    1247                 :             :  *
    1248                 :             :  * Although every row has an equal chance of ending up in the final
    1249                 :             :  * sample, this sampling method is not perfect: not every possible
    1250                 :             :  * sample has an equal chance of being selected.  For large relations
    1251                 :             :  * the number of different blocks represented by the sample tends to be
    1252                 :             :  * too small.  We can live with that for now.  Improvements are welcome.
    1253                 :             :  *
    1254                 :             :  * An important property of this sampling method is that because we do
    1255                 :             :  * look at a statistically unbiased set of blocks, we should get
    1256                 :             :  * unbiased estimates of the average numbers of live and dead rows per
    1257                 :             :  * block.  The previous sampling method put too much credence in the row
    1258                 :             :  * density near the start of the table.
    1259                 :             :  */
    1260                 :             : static int
    1261                 :       11415 : acquire_sample_rows(Relation onerel, int elevel,
    1262                 :             :                     HeapTuple *rows, int targrows,
    1263                 :             :                     double *totalrows, double *totaldeadrows)
    1264                 :             : {
    1265                 :       11415 :     int         numrows = 0;    /* # rows now in reservoir */
    1266                 :       11415 :     double      samplerows = 0; /* total # rows collected */
    1267                 :       11415 :     double      liverows = 0;   /* # live rows seen */
    1268                 :       11415 :     double      deadrows = 0;   /* # dead rows seen */
    1269                 :       11415 :     double      rowstoskip = -1;    /* -1 means not set yet */
    1270                 :             :     uint32      randseed;       /* Seed for block sampler(s) */
    1271                 :             :     BlockNumber totalblocks;
    1272                 :             :     BlockSamplerData bs;
    1273                 :             :     ReservoirStateData rstate;
    1274                 :             :     TupleTableSlot *slot;
    1275                 :             :     TableScanDesc scan;
    1276                 :             :     BlockNumber nblocks;
    1277                 :       11415 :     BlockNumber blksdone = 0;
    1278                 :             :     ReadStream *stream;
    1279                 :             : 
    1280                 :             :     Assert(targrows > 0);
    1281                 :             : 
    1282                 :       11415 :     totalblocks = RelationGetNumberOfBlocks(onerel);
    1283                 :             : 
    1284                 :             :     /* Prepare for sampling block numbers */
    1285                 :       11415 :     randseed = pg_prng_uint32(&pg_global_prng_state);
    1286                 :       11415 :     nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
    1287                 :             : 
    1288                 :             :     /* Report sampling block numbers */
    1289                 :       11415 :     pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_TOTAL,
    1290                 :             :                                  nblocks);
    1291                 :             : 
    1292                 :             :     /* Prepare for sampling rows */
    1293                 :       11415 :     reservoir_init_selection_state(&rstate, targrows);
    1294                 :             : 
    1295                 :       11415 :     scan = table_beginscan_analyze(onerel);
    1296                 :       11415 :     slot = table_slot_create(onerel, NULL);
    1297                 :             : 
    1298                 :             :     /*
    1299                 :             :      * It is safe to use batching, as block_sampling_read_stream_next never
    1300                 :             :      * blocks.
    1301                 :             :      */
    1302                 :       11415 :     stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE |
    1303                 :             :                                         READ_STREAM_USE_BATCHING,
    1304                 :             :                                         vac_strategy,
    1305                 :             :                                         scan->rs_rd,
    1306                 :             :                                         MAIN_FORKNUM,
    1307                 :             :                                         block_sampling_read_stream_next,
    1308                 :             :                                         &bs,
    1309                 :             :                                         0);
    1310                 :             : 
    1311                 :             :     /* Outer loop over blocks to sample */
    1312         [ +  + ]:      106151 :     while (table_scan_analyze_next_block(scan, stream))
    1313                 :             :     {
    1314                 :       94736 :         vacuum_delay_point(true);
    1315                 :             : 
    1316         [ +  + ]:     8174908 :         while (table_scan_analyze_next_tuple(scan, &liverows, &deadrows, slot))
    1317                 :             :         {
    1318                 :             :             /*
    1319                 :             :              * The first targrows sample rows are simply copied into the
    1320                 :             :              * reservoir. Then we start replacing tuples in the sample until
    1321                 :             :              * we reach the end of the relation.  This algorithm is from Jeff
    1322                 :             :              * Vitter's paper (see full citation in utils/misc/sampling.c). It
    1323                 :             :              * works by repeatedly computing the number of tuples to skip
    1324                 :             :              * before selecting a tuple, which replaces a randomly chosen
    1325                 :             :              * element of the reservoir (current set of tuples).  At all times
    1326                 :             :              * the reservoir is a true random sample of the tuples we've
    1327                 :             :              * passed over so far, so when we fall off the end of the relation
    1328                 :             :              * we're done.
    1329                 :             :              */
    1330         [ +  + ]:     8080172 :             if (numrows < targrows)
    1331                 :     7509717 :                 rows[numrows++] = ExecCopySlotHeapTuple(slot);
    1332                 :             :             else
    1333                 :             :             {
    1334                 :             :                 /*
    1335                 :             :                  * t in Vitter's paper is the number of records already
    1336                 :             :                  * processed.  If we need to compute a new S value, we must
    1337                 :             :                  * use the not-yet-incremented value of samplerows as t.
    1338                 :             :                  */
    1339         [ +  + ]:      570455 :                 if (rowstoskip < 0)
    1340                 :      284266 :                     rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
    1341                 :             : 
    1342         [ +  + ]:      570455 :                 if (rowstoskip <= 0)
    1343                 :             :                 {
    1344                 :             :                     /*
    1345                 :             :                      * Found a suitable tuple, so save it, replacing one old
    1346                 :             :                      * tuple at random
    1347                 :             :                      */
    1348                 :      284228 :                     int         k = (int) (targrows * sampler_random_fract(&rstate.randstate));
    1349                 :             : 
    1350                 :             :                     Assert(k >= 0 && k < targrows);
    1351                 :      284228 :                     heap_freetuple(rows[k]);
    1352                 :      284228 :                     rows[k] = ExecCopySlotHeapTuple(slot);
    1353                 :             :                 }
    1354                 :             : 
    1355                 :      570455 :                 rowstoskip -= 1;
    1356                 :             :             }
    1357                 :             : 
    1358                 :     8080172 :             samplerows += 1;
    1359                 :             :         }
    1360                 :             : 
    1361                 :       94736 :         pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_DONE,
    1362                 :             :                                      ++blksdone);
    1363                 :             :     }
    1364                 :             : 
    1365                 :       11415 :     read_stream_end(stream);
    1366                 :             : 
    1367                 :       11415 :     ExecDropSingleTupleTableSlot(slot);
    1368                 :       11415 :     table_endscan(scan);
    1369                 :             : 
    1370                 :             :     /*
    1371                 :             :      * If we didn't find as many tuples as we wanted then we're done. No sort
    1372                 :             :      * is needed, since they're already in order.
    1373                 :             :      *
    1374                 :             :      * Otherwise we need to sort the collected tuples by position
    1375                 :             :      * (itempointer). It's not worth worrying about corner cases where the
    1376                 :             :      * tuples are already sorted.
    1377                 :             :      */
    1378         [ +  + ]:       11415 :     if (numrows == targrows)
    1379                 :         111 :         qsort_interruptible(rows, numrows, sizeof(HeapTuple),
    1380                 :             :                             compare_rows, NULL);
    1381                 :             : 
    1382                 :             :     /*
    1383                 :             :      * Estimate total numbers of live and dead rows in relation, extrapolating
    1384                 :             :      * on the assumption that the average tuple density in pages we didn't
    1385                 :             :      * scan is the same as in the pages we did scan.  Since what we scanned is
    1386                 :             :      * a random sample of the pages in the relation, this should be a good
    1387                 :             :      * assumption.
    1388                 :             :      */
    1389         [ +  + ]:       11415 :     if (bs.m > 0)
    1390                 :             :     {
    1391                 :        7924 :         *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
    1392                 :        7924 :         *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
    1393                 :             :     }
    1394                 :             :     else
    1395                 :             :     {
    1396                 :        3491 :         *totalrows = 0.0;
    1397                 :        3491 :         *totaldeadrows = 0.0;
    1398                 :             :     }
    1399                 :             : 
    1400                 :             :     /*
    1401                 :             :      * Emit some interesting relation info
    1402                 :             :      */
    1403         [ +  + ]:       11415 :     ereport(elevel,
    1404                 :             :             (errmsg("\"%s\": scanned %d of %u pages, "
    1405                 :             :                     "containing %.0f live rows and %.0f dead rows; "
    1406                 :             :                     "%d rows in sample, %.0f estimated total rows",
    1407                 :             :                     RelationGetRelationName(onerel),
    1408                 :             :                     bs.m, totalblocks,
    1409                 :             :                     liverows, deadrows,
    1410                 :             :                     numrows, *totalrows)));
    1411                 :             : 
    1412                 :       11415 :     return numrows;
    1413                 :             : }
    1414                 :             : 
    1415                 :             : /*
    1416                 :             :  * Comparator for sorting rows[] array
    1417                 :             :  */
    1418                 :             : static int
    1419                 :     5248607 : compare_rows(const void *a, const void *b, void *arg)
    1420                 :             : {
    1421                 :     5248607 :     HeapTuple   ha = *(const HeapTuple *) a;
    1422                 :     5248607 :     HeapTuple   hb = *(const HeapTuple *) b;
    1423                 :     5248607 :     BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
    1424                 :     5248607 :     OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
    1425                 :     5248607 :     BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
    1426                 :     5248607 :     OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
    1427                 :             : 
    1428         [ +  + ]:     5248607 :     if (ba < bb)
    1429                 :     1388912 :         return -1;
    1430         [ +  + ]:     3859695 :     if (ba > bb)
    1431                 :     1383096 :         return 1;
    1432         [ +  + ]:     2476599 :     if (oa < ob)
    1433                 :     1438478 :         return -1;
    1434         [ +  - ]:     1038121 :     if (oa > ob)
    1435                 :     1038121 :         return 1;
    1436                 :           0 :     return 0;
    1437                 :             : }
    1438                 :             : 
    1439                 :             : 
    1440                 :             : /*
    1441                 :             :  * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
    1442                 :             :  *
    1443                 :             :  * This has the same API as acquire_sample_rows, except that rows are
    1444                 :             :  * collected from all inheritance children as well as the specified table.
    1445                 :             :  * We fail and return zero if there are no inheritance children, or if all
    1446                 :             :  * children are foreign tables that don't support ANALYZE.
    1447                 :             :  */
    1448                 :             : static int
    1449                 :         602 : acquire_inherited_sample_rows(Relation onerel, int elevel,
    1450                 :             :                               HeapTuple *rows, int targrows,
    1451                 :             :                               double *totalrows, double *totaldeadrows)
    1452                 :             : {
    1453                 :             :     List       *tableOIDs;
    1454                 :             :     Relation   *rels;
    1455                 :             :     AcquireSampleRowsFunc *acquirefuncs;
    1456                 :             :     double     *relblocks;
    1457                 :             :     double      totalblocks;
    1458                 :             :     int         numrows,
    1459                 :             :                 nrels,
    1460                 :             :                 i;
    1461                 :             :     ListCell   *lc;
    1462                 :             :     bool        has_child;
    1463                 :             : 
    1464                 :             :     /* Initialize output parameters to zero now, in case we exit early */
    1465                 :         602 :     *totalrows = 0;
    1466                 :         602 :     *totaldeadrows = 0;
    1467                 :             : 
    1468                 :             :     /*
    1469                 :             :      * Find all members of inheritance set.  We only need AccessShareLock on
    1470                 :             :      * the children.
    1471                 :             :      */
    1472                 :             :     tableOIDs =
    1473                 :         602 :         find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
    1474                 :             : 
    1475                 :             :     /*
    1476                 :             :      * Check that there's at least one descendant, else fail.  This could
    1477                 :             :      * happen despite analyze_rel's relhassubclass check, if table once had a
    1478                 :             :      * child but no longer does.  In that case, we can clear the
    1479                 :             :      * relhassubclass field so as not to make the same mistake again later.
    1480                 :             :      * (This is safe because we hold ShareUpdateExclusiveLock.)
    1481                 :             :      */
    1482         [ +  + ]:         602 :     if (list_length(tableOIDs) < 2)
    1483                 :             :     {
    1484                 :             :         /* CCI because we already updated the pg_class row in this command */
    1485                 :          13 :         CommandCounterIncrement();
    1486                 :          13 :         SetRelationHasSubclass(RelationGetRelid(onerel), false);
    1487         [ -  + ]:          13 :         ereport(elevel,
    1488                 :             :                 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
    1489                 :             :                         get_namespace_name(RelationGetNamespace(onerel)),
    1490                 :             :                         RelationGetRelationName(onerel))));
    1491                 :          13 :         return 0;
    1492                 :             :     }
    1493                 :             : 
    1494                 :             :     /*
    1495                 :             :      * Identify acquirefuncs to use, and count blocks in all the relations.
    1496                 :             :      * The result could overflow BlockNumber, so we use double arithmetic.
    1497                 :             :      */
    1498                 :         589 :     rels = palloc_array(Relation, list_length(tableOIDs));
    1499                 :         589 :     acquirefuncs = palloc_array(AcquireSampleRowsFunc, list_length(tableOIDs));
    1500                 :         589 :     relblocks = palloc_array(double, list_length(tableOIDs));
    1501                 :         589 :     totalblocks = 0;
    1502                 :         589 :     nrels = 0;
    1503                 :         589 :     has_child = false;
    1504   [ +  -  +  +  :        2672 :     foreach(lc, tableOIDs)
                   +  + ]
    1505                 :             :     {
    1506                 :        2083 :         Oid         childOID = lfirst_oid(lc);
    1507                 :             :         Relation    childrel;
    1508                 :        2083 :         AcquireSampleRowsFunc acquirefunc = NULL;
    1509                 :        2083 :         BlockNumber relpages = 0;
    1510                 :             : 
    1511                 :             :         /* We already got the needed lock */
    1512                 :        2083 :         childrel = table_open(childOID, NoLock);
    1513                 :             : 
    1514                 :             :         /* Ignore if temp table of another backend */
    1515   [ +  +  -  + ]:        2083 :         if (RELATION_IS_OTHER_TEMP(childrel))
    1516                 :             :         {
    1517                 :             :             /* ... but release the lock on it */
    1518                 :             :             Assert(childrel != onerel);
    1519                 :           0 :             table_close(childrel, AccessShareLock);
    1520                 :         553 :             continue;
    1521                 :             :         }
    1522                 :             : 
    1523                 :             :         /* Check table type (MATVIEW can't happen, but might as well allow) */
    1524         [ +  + ]:        2083 :         if (childrel->rd_rel->relkind == RELKIND_RELATION ||
    1525         [ -  + ]:         568 :             childrel->rd_rel->relkind == RELKIND_MATVIEW)
    1526                 :             :         {
    1527                 :             :             /* Regular table, so use the regular row acquisition function */
    1528                 :        1515 :             acquirefunc = acquire_sample_rows;
    1529                 :        1515 :             relpages = RelationGetNumberOfBlocks(childrel);
    1530                 :             :         }
    1531         [ +  + ]:         568 :         else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    1532                 :             :         {
    1533                 :             :             /*
    1534                 :             :              * For a foreign table, call the FDW's hook function to see
    1535                 :             :              * whether it supports analysis.
    1536                 :             :              */
    1537                 :             :             FdwRoutine *fdwroutine;
    1538                 :          15 :             bool        ok = false;
    1539                 :             : 
    1540                 :          15 :             fdwroutine = GetFdwRoutineForRelation(childrel, false);
    1541                 :             : 
    1542         [ +  - ]:          15 :             if (fdwroutine->AnalyzeForeignTable != NULL)
    1543                 :          15 :                 ok = fdwroutine->AnalyzeForeignTable(childrel,
    1544                 :             :                                                      &acquirefunc,
    1545                 :             :                                                      &relpages);
    1546                 :             : 
    1547         [ -  + ]:          15 :             if (!ok)
    1548                 :             :             {
    1549                 :             :                 /* ignore, but release the lock on it */
    1550                 :             :                 Assert(childrel != onerel);
    1551                 :           0 :                 table_close(childrel, AccessShareLock);
    1552                 :           0 :                 continue;
    1553                 :             :             }
    1554                 :             :         }
    1555                 :             :         else
    1556                 :             :         {
    1557                 :             :             /*
    1558                 :             :              * ignore, but release the lock on it.  don't try to unlock the
    1559                 :             :              * passed-in relation
    1560                 :             :              */
    1561                 :             :             Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
    1562         [ +  + ]:         553 :             if (childrel != onerel)
    1563                 :          52 :                 table_close(childrel, AccessShareLock);
    1564                 :             :             else
    1565                 :         501 :                 table_close(childrel, NoLock);
    1566                 :         553 :             continue;
    1567                 :             :         }
    1568                 :             : 
    1569                 :             :         /* OK, we'll process this child */
    1570                 :        1530 :         has_child = true;
    1571                 :        1530 :         rels[nrels] = childrel;
    1572                 :        1530 :         acquirefuncs[nrels] = acquirefunc;
    1573                 :        1530 :         relblocks[nrels] = (double) relpages;
    1574                 :        1530 :         totalblocks += (double) relpages;
    1575                 :        1530 :         nrels++;
    1576                 :             :     }
    1577                 :             : 
    1578                 :             :     /*
    1579                 :             :      * If we don't have at least one child table to consider, fail.  If the
    1580                 :             :      * relation is a partitioned table, it's not counted as a child table.
    1581                 :             :      */
    1582         [ -  + ]:         589 :     if (!has_child)
    1583                 :             :     {
    1584         [ #  # ]:           0 :         ereport(elevel,
    1585                 :             :                 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
    1586                 :             :                         get_namespace_name(RelationGetNamespace(onerel)),
    1587                 :             :                         RelationGetRelationName(onerel))));
    1588                 :           0 :         return 0;
    1589                 :             :     }
    1590                 :             : 
    1591                 :             :     /*
    1592                 :             :      * Now sample rows from each relation, proportionally to its fraction of
    1593                 :             :      * the total block count.  (This might be less than desirable if the child
    1594                 :             :      * rels have radically different free-space percentages, but it's not
    1595                 :             :      * clear that it's worth working harder.)
    1596                 :             :      */
    1597                 :         589 :     pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_TOTAL,
    1598                 :             :                                  nrels);
    1599                 :         589 :     numrows = 0;
    1600         [ +  + ]:        2119 :     for (i = 0; i < nrels; i++)
    1601                 :             :     {
    1602                 :        1530 :         Relation    childrel = rels[i];
    1603                 :        1530 :         AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
    1604                 :        1530 :         double      childblocks = relblocks[i];
    1605                 :             : 
    1606                 :             :         /*
    1607                 :             :          * Report progress.  The sampling function will normally report blocks
    1608                 :             :          * done/total, but we need to reset them to 0 here, so that they don't
    1609                 :             :          * show an old value until that.
    1610                 :             :          */
    1611                 :             :         {
    1612                 :        1530 :             const int   progress_index[] = {
    1613                 :             :                 PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID,
    1614                 :             :                 PROGRESS_ANALYZE_BLOCKS_DONE,
    1615                 :             :                 PROGRESS_ANALYZE_BLOCKS_TOTAL
    1616                 :             :             };
    1617                 :        1530 :             const int64 progress_vals[] = {
    1618                 :        1530 :                 RelationGetRelid(childrel),
    1619                 :             :                 0,
    1620                 :             :                 0,
    1621                 :             :             };
    1622                 :             : 
    1623                 :        1530 :             pgstat_progress_update_multi_param(3, progress_index, progress_vals);
    1624                 :             :         }
    1625                 :             : 
    1626         [ +  + ]:        1530 :         if (childblocks > 0)
    1627                 :             :         {
    1628                 :             :             int         childtargrows;
    1629                 :             : 
    1630                 :        1428 :             childtargrows = (int) rint(targrows * childblocks / totalblocks);
    1631                 :             :             /* Make sure we don't overrun due to roundoff error */
    1632                 :        1428 :             childtargrows = Min(childtargrows, targrows - numrows);
    1633         [ +  - ]:        1428 :             if (childtargrows > 0)
    1634                 :             :             {
    1635                 :             :                 int         childrows;
    1636                 :             :                 double      trows,
    1637                 :             :                             tdrows;
    1638                 :             : 
    1639                 :             :                 /* Fetch a random sample of the child's rows */
    1640                 :        1428 :                 childrows = (*acquirefunc) (childrel, elevel,
    1641                 :        1428 :                                             rows + numrows, childtargrows,
    1642                 :             :                                             &trows, &tdrows);
    1643                 :             : 
    1644                 :             :                 /* We may need to convert from child's rowtype to parent's */
    1645         [ +  - ]:        1428 :                 if (childrows > 0 &&
    1646         [ +  + ]:        1428 :                     !equalRowTypes(RelationGetDescr(childrel),
    1647                 :             :                                    RelationGetDescr(onerel)))
    1648                 :             :                 {
    1649                 :             :                     TupleConversionMap *map;
    1650                 :             : 
    1651                 :        1356 :                     map = convert_tuples_by_name(RelationGetDescr(childrel),
    1652                 :             :                                                  RelationGetDescr(onerel));
    1653         [ +  + ]:        1356 :                     if (map != NULL)
    1654                 :             :                     {
    1655                 :             :                         int         j;
    1656                 :             : 
    1657         [ +  + ]:       70915 :                         for (j = 0; j < childrows; j++)
    1658                 :             :                         {
    1659                 :             :                             HeapTuple   newtup;
    1660                 :             : 
    1661                 :       70825 :                             newtup = execute_attr_map_tuple(rows[numrows + j], map);
    1662                 :       70825 :                             heap_freetuple(rows[numrows + j]);
    1663                 :       70825 :                             rows[numrows + j] = newtup;
    1664                 :             :                         }
    1665                 :          90 :                         free_conversion_map(map);
    1666                 :             :                     }
    1667                 :             :                 }
    1668                 :             : 
    1669                 :             :                 /* And add to counts */
    1670                 :        1428 :                 numrows += childrows;
    1671                 :        1428 :                 *totalrows += trows;
    1672                 :        1428 :                 *totaldeadrows += tdrows;
    1673                 :             :             }
    1674                 :             :         }
    1675                 :             : 
    1676                 :             :         /*
    1677                 :             :          * Note: we cannot release the child-table locks, since we may have
    1678                 :             :          * pointers to their TOAST tables in the sampled rows.
    1679                 :             :          */
    1680                 :        1530 :         table_close(childrel, NoLock);
    1681                 :        1530 :         pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_DONE,
    1682                 :        1530 :                                      i + 1);
    1683                 :             :     }
    1684                 :             : 
    1685                 :         589 :     return numrows;
    1686                 :             : }
    1687                 :             : 
    1688                 :             : 
    1689                 :             : /*
    1690                 :             :  *  update_attstats() -- update attribute statistics for one relation
    1691                 :             :  *
    1692                 :             :  *      Statistics are stored in several places: the pg_class row for the
    1693                 :             :  *      relation has stats about the whole relation, and there is a
    1694                 :             :  *      pg_statistic row for each (non-system) attribute that has ever
    1695                 :             :  *      been analyzed.  The pg_class values are updated by VACUUM, not here.
    1696                 :             :  *
    1697                 :             :  *      pg_statistic rows are just added or updated normally.  This means
    1698                 :             :  *      that pg_statistic will probably contain some deleted rows at the
    1699                 :             :  *      completion of a vacuum cycle, unless it happens to get vacuumed last.
    1700                 :             :  *
    1701                 :             :  *      To keep things simple, we punt for pg_statistic, and don't try
    1702                 :             :  *      to compute or store rows for pg_statistic itself in pg_statistic.
    1703                 :             :  *      This could possibly be made to work, but it's not worth the trouble.
    1704                 :             :  *      Note analyze_rel() has seen to it that we won't come here when
    1705                 :             :  *      vacuuming pg_statistic itself.
    1706                 :             :  *
    1707                 :             :  *      Note: there would be a race condition here if two backends could
    1708                 :             :  *      ANALYZE the same table concurrently.  Presently, we lock that out
    1709                 :             :  *      by taking a self-exclusive lock on the relation in analyze_rel().
    1710                 :             :  */
    1711                 :             : static void
    1712                 :       15620 : update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
    1713                 :             : {
    1714                 :             :     Relation    sd;
    1715                 :             :     int         attno;
    1716                 :       15620 :     CatalogIndexState indstate = NULL;
    1717                 :             : 
    1718         [ +  + ]:       15620 :     if (natts <= 0)
    1719                 :        8464 :         return;                 /* nothing to do */
    1720                 :             : 
    1721                 :        7156 :     sd = table_open(StatisticRelationId, RowExclusiveLock);
    1722                 :             : 
    1723         [ +  + ]:       60098 :     for (attno = 0; attno < natts; attno++)
    1724                 :             :     {
    1725                 :       52942 :         VacAttrStats *stats = vacattrstats[attno];
    1726                 :             :         HeapTuple   stup,
    1727                 :             :                     oldtup;
    1728                 :             :         int         i,
    1729                 :             :                     k,
    1730                 :             :                     n;
    1731                 :             :         Datum       values[Natts_pg_statistic];
    1732                 :             :         bool        nulls[Natts_pg_statistic];
    1733                 :             :         bool        replaces[Natts_pg_statistic];
    1734                 :             : 
    1735                 :             :         /* Ignore attr if we weren't able to collect stats */
    1736         [ +  + ]:       52942 :         if (!stats->stats_valid)
    1737                 :           6 :             continue;
    1738                 :             : 
    1739                 :             :         /*
    1740                 :             :          * Construct a new pg_statistic tuple
    1741                 :             :          */
    1742         [ +  + ]:     1693952 :         for (i = 0; i < Natts_pg_statistic; ++i)
    1743                 :             :         {
    1744                 :     1641016 :             nulls[i] = false;
    1745                 :     1641016 :             replaces[i] = true;
    1746                 :             :         }
    1747                 :             : 
    1748                 :       52936 :         values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
    1749                 :       52936 :         values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
    1750                 :       52936 :         values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
    1751                 :       52936 :         values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
    1752                 :       52936 :         values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
    1753                 :       52936 :         values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
    1754                 :       52936 :         i = Anum_pg_statistic_stakind1 - 1;
    1755         [ +  + ]:      317616 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1756                 :             :         {
    1757                 :      264680 :             values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
    1758                 :             :         }
    1759                 :       52936 :         i = Anum_pg_statistic_staop1 - 1;
    1760         [ +  + ]:      317616 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1761                 :             :         {
    1762                 :      264680 :             values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
    1763                 :             :         }
    1764                 :       52936 :         i = Anum_pg_statistic_stacoll1 - 1;
    1765         [ +  + ]:      317616 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1766                 :             :         {
    1767                 :      264680 :             values[i++] = ObjectIdGetDatum(stats->stacoll[k]);   /* stacollN */
    1768                 :             :         }
    1769                 :       52936 :         i = Anum_pg_statistic_stanumbers1 - 1;
    1770         [ +  + ]:      317616 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1771                 :             :         {
    1772         [ +  + ]:      264680 :             if (stats->stanumbers[k] != NULL)
    1773                 :             :             {
    1774                 :       82438 :                 int         nnum = stats->numnumbers[k];
    1775                 :       82438 :                 Datum      *numdatums = palloc_array(Datum, nnum);
    1776                 :             :                 ArrayType  *arry;
    1777                 :             : 
    1778         [ +  + ]:      699659 :                 for (n = 0; n < nnum; n++)
    1779                 :      617221 :                     numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
    1780                 :       82438 :                 arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
    1781                 :       82438 :                 values[i++] = PointerGetDatum(arry);    /* stanumbersN */
    1782                 :             :             }
    1783                 :             :             else
    1784                 :             :             {
    1785                 :      182242 :                 nulls[i] = true;
    1786                 :      182242 :                 values[i++] = (Datum) 0;
    1787                 :             :             }
    1788                 :             :         }
    1789                 :       52936 :         i = Anum_pg_statistic_stavalues1 - 1;
    1790         [ +  + ]:      317616 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1791                 :             :         {
    1792         [ +  + ]:      264680 :             if (stats->stavalues[k] != NULL)
    1793                 :             :             {
    1794                 :             :                 ArrayType  *arry;
    1795                 :             : 
    1796                 :       58275 :                 arry = construct_array(stats->stavalues[k],
    1797                 :             :                                        stats->numvalues[k],
    1798                 :             :                                        stats->statypid[k],
    1799                 :       58275 :                                        stats->statyplen[k],
    1800                 :       58275 :                                        stats->statypbyval[k],
    1801                 :       58275 :                                        stats->statypalign[k]);
    1802                 :       58275 :                 values[i++] = PointerGetDatum(arry);    /* stavaluesN */
    1803                 :             :             }
    1804                 :             :             else
    1805                 :             :             {
    1806                 :      206405 :                 nulls[i] = true;
    1807                 :      206405 :                 values[i++] = (Datum) 0;
    1808                 :             :             }
    1809                 :             :         }
    1810                 :             : 
    1811                 :             :         /* Is there already a pg_statistic tuple for this attribute? */
    1812                 :      105872 :         oldtup = SearchSysCache3(STATRELATTINH,
    1813                 :             :                                  ObjectIdGetDatum(relid),
    1814                 :       52936 :                                  Int16GetDatum(stats->tupattnum),
    1815                 :             :                                  BoolGetDatum(inh));
    1816                 :             : 
    1817                 :             :         /* Open index information when we know we need it */
    1818         [ +  + ]:       52936 :         if (indstate == NULL)
    1819                 :        7152 :             indstate = CatalogOpenIndexes(sd);
    1820                 :             : 
    1821         [ +  + ]:       52936 :         if (HeapTupleIsValid(oldtup))
    1822                 :             :         {
    1823                 :             :             /* Yes, replace it */
    1824                 :       23872 :             stup = heap_modify_tuple(oldtup,
    1825                 :             :                                      RelationGetDescr(sd),
    1826                 :             :                                      values,
    1827                 :             :                                      nulls,
    1828                 :             :                                      replaces);
    1829                 :       23872 :             ReleaseSysCache(oldtup);
    1830                 :       23872 :             CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
    1831                 :             :         }
    1832                 :             :         else
    1833                 :             :         {
    1834                 :             :             /* No, insert new tuple */
    1835                 :       29064 :             stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
    1836                 :       29064 :             CatalogTupleInsertWithInfo(sd, stup, indstate);
    1837                 :             :         }
    1838                 :             : 
    1839                 :       52936 :         heap_freetuple(stup);
    1840                 :             :     }
    1841                 :             : 
    1842         [ +  + ]:        7156 :     if (indstate != NULL)
    1843                 :        7152 :         CatalogCloseIndexes(indstate);
    1844                 :        7156 :     table_close(sd, RowExclusiveLock);
    1845                 :             : }
    1846                 :             : 
    1847                 :             : /*
    1848                 :             :  * Standard fetch function for use by compute_stats subroutines.
    1849                 :             :  *
    1850                 :             :  * This exists to provide some insulation between compute_stats routines
    1851                 :             :  * and the actual storage of the sample data.
    1852                 :             :  */
    1853                 :             : static Datum
    1854                 :    53962057 : std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
    1855                 :             : {
    1856                 :    53962057 :     int         attnum = stats->tupattnum;
    1857                 :    53962057 :     HeapTuple   tuple = stats->rows[rownum];
    1858                 :    53962057 :     TupleDesc   tupDesc = stats->tupDesc;
    1859                 :             : 
    1860                 :    53962057 :     return heap_getattr(tuple, attnum, tupDesc, isNull);
    1861                 :             : }
    1862                 :             : 
    1863                 :             : /*
    1864                 :             :  * Fetch function for analyzing index expressions.
    1865                 :             :  *
    1866                 :             :  * We have not bothered to construct index tuples, instead the data is
    1867                 :             :  * just in Datum arrays.
    1868                 :             :  */
    1869                 :             : static Datum
    1870                 :      134077 : ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
    1871                 :             : {
    1872                 :             :     int         i;
    1873                 :             : 
    1874                 :             :     /* exprvals and exprnulls are already offset for proper column */
    1875                 :      134077 :     i = rownum * stats->rowstride;
    1876                 :      134077 :     *isNull = stats->exprnulls[i];
    1877                 :      134077 :     return stats->exprvals[i];
    1878                 :             : }
    1879                 :             : 
    1880                 :             : 
    1881                 :             : /*
    1882                 :             :  * ==========================================================================
    1883                 :             :  *
    1884                 :             :  * Code below this point represents the "standard" type-specific statistics
    1885                 :             :  * analysis algorithms.  This code can be replaced on a per-data-type basis
    1886                 :             :  * by setting a nonzero value in pg_type.typanalyze.
    1887                 :             :  *
    1888                 :             :  *==========================================================================
    1889                 :             :  */
    1890                 :             : 
    1891                 :             : 
    1892                 :             : /*
    1893                 :             :  * To avoid consuming too much memory during analysis and/or too much space
    1894                 :             :  * in the resulting pg_statistic rows, we ignore varlena datums that are wider
    1895                 :             :  * than WIDTH_THRESHOLD (after detoasting!).  This is legitimate for MCV
    1896                 :             :  * and distinct-value calculations since a wide value is unlikely to be
    1897                 :             :  * duplicated at all, much less be a most-common value.  For the same reason,
    1898                 :             :  * ignoring wide values will not affect our estimates of histogram bin
    1899                 :             :  * boundaries very much.
    1900                 :             :  */
    1901                 :             : #define WIDTH_THRESHOLD  1024
    1902                 :             : 
    1903                 :             : #define swapInt(a,b)    do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
    1904                 :             : #define swapDatum(a,b)  do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
    1905                 :             : 
    1906                 :             : /*
    1907                 :             :  * Extra information used by the default analysis routines
    1908                 :             :  */
    1909                 :             : typedef struct
    1910                 :             : {
    1911                 :             :     int         count;          /* # of duplicates */
    1912                 :             :     int         first;          /* values[] index of first occurrence */
    1913                 :             : } ScalarMCVItem;
    1914                 :             : 
    1915                 :             : typedef struct
    1916                 :             : {
    1917                 :             :     SortSupport ssup;
    1918                 :             :     int        *tupnoLink;
    1919                 :             : } CompareScalarsContext;
    1920                 :             : 
    1921                 :             : 
    1922                 :             : static void compute_trivial_stats(VacAttrStatsP stats,
    1923                 :             :                                   AnalyzeAttrFetchFunc fetchfunc,
    1924                 :             :                                   int samplerows,
    1925                 :             :                                   double totalrows);
    1926                 :             : static void compute_distinct_stats(VacAttrStatsP stats,
    1927                 :             :                                    AnalyzeAttrFetchFunc fetchfunc,
    1928                 :             :                                    int samplerows,
    1929                 :             :                                    double totalrows);
    1930                 :             : static void compute_scalar_stats(VacAttrStatsP stats,
    1931                 :             :                                  AnalyzeAttrFetchFunc fetchfunc,
    1932                 :             :                                  int samplerows,
    1933                 :             :                                  double totalrows);
    1934                 :             : static int  compare_scalars(const void *a, const void *b, void *arg);
    1935                 :             : static int  compare_mcvs(const void *a, const void *b, void *arg);
    1936                 :             : static int  analyze_mcv_list(int *mcv_counts,
    1937                 :             :                              int num_mcv,
    1938                 :             :                              double stadistinct,
    1939                 :             :                              double stanullfrac,
    1940                 :             :                              int samplerows,
    1941                 :             :                              double totalrows);
    1942                 :             : 
    1943                 :             : 
    1944                 :             : /*
    1945                 :             :  * std_typanalyze -- the default type-specific typanalyze function
    1946                 :             :  */
    1947                 :             : bool
    1948                 :       75855 : std_typanalyze(VacAttrStats *stats)
    1949                 :             : {
    1950                 :             :     Oid         ltopr;
    1951                 :             :     Oid         eqopr;
    1952                 :             :     StdAnalyzeData *mystats;
    1953                 :             : 
    1954                 :             :     /* If the attstattarget column is negative, use the default value */
    1955         [ +  + ]:       75855 :     if (stats->attstattarget < 0)
    1956                 :       75239 :         stats->attstattarget = default_statistics_target;
    1957                 :             : 
    1958                 :             :     /* Look for default "<" and "=" operators for column's type */
    1959                 :       75855 :     get_sort_group_operators(stats->attrtypid,
    1960                 :             :                              false, false, false,
    1961                 :             :                              &ltopr, &eqopr, NULL,
    1962                 :             :                              NULL);
    1963                 :             : 
    1964                 :             :     /* Save the operator info for compute_stats routines */
    1965                 :       75855 :     mystats = palloc_object(StdAnalyzeData);
    1966                 :       75855 :     mystats->eqopr = eqopr;
    1967         [ +  + ]:       75855 :     mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
    1968                 :       75855 :     mystats->ltopr = ltopr;
    1969                 :       75855 :     stats->extra_data = mystats;
    1970                 :             : 
    1971                 :             :     /*
    1972                 :             :      * Determine which standard statistics algorithm to use
    1973                 :             :      */
    1974   [ +  +  +  + ]:       75855 :     if (OidIsValid(eqopr) && OidIsValid(ltopr))
    1975                 :             :     {
    1976                 :             :         /* Seems to be a scalar datatype */
    1977                 :       73658 :         stats->compute_stats = compute_scalar_stats;
    1978                 :             :         /*--------------------
    1979                 :             :          * The following choice of minrows is based on the paper
    1980                 :             :          * "Random sampling for histogram construction: how much is enough?"
    1981                 :             :          * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
    1982                 :             :          * Proceedings of ACM SIGMOD International Conference on Management
    1983                 :             :          * of Data, 1998, Pages 436-447.  Their Corollary 1 to Theorem 5
    1984                 :             :          * says that for table size n, histogram size k, maximum relative
    1985                 :             :          * error in bin size f, and error probability gamma, the minimum
    1986                 :             :          * random sample size is
    1987                 :             :          *      r = 4 * k * ln(2*n/gamma) / f^2
    1988                 :             :          * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
    1989                 :             :          *      r = 305.82 * k
    1990                 :             :          * Note that because of the log function, the dependence on n is
    1991                 :             :          * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
    1992                 :             :          * bin size error with probability 0.99.  So there's no real need to
    1993                 :             :          * scale for n, which is a good thing because we don't necessarily
    1994                 :             :          * know it at this point.
    1995                 :             :          *--------------------
    1996                 :             :          */
    1997                 :       73658 :         stats->minrows = 300 * stats->attstattarget;
    1998                 :             :     }
    1999         [ +  + ]:        2197 :     else if (OidIsValid(eqopr))
    2000                 :             :     {
    2001                 :             :         /* We can still recognize distinct values */
    2002                 :        1850 :         stats->compute_stats = compute_distinct_stats;
    2003                 :             :         /* Might as well use the same minrows as above */
    2004                 :        1850 :         stats->minrows = 300 * stats->attstattarget;
    2005                 :             :     }
    2006                 :             :     else
    2007                 :             :     {
    2008                 :             :         /* Can't do much but the trivial stuff */
    2009                 :         347 :         stats->compute_stats = compute_trivial_stats;
    2010                 :             :         /* Might as well use the same minrows as above */
    2011                 :         347 :         stats->minrows = 300 * stats->attstattarget;
    2012                 :             :     }
    2013                 :             : 
    2014                 :       75855 :     return true;
    2015                 :             : }
    2016                 :             : 
    2017                 :             : 
    2018                 :             : /*
    2019                 :             :  *  compute_trivial_stats() -- compute very basic column statistics
    2020                 :             :  *
    2021                 :             :  *  We use this when we cannot find a hash "=" operator for the datatype.
    2022                 :             :  *
    2023                 :             :  *  We determine the fraction of non-null rows and the average datum width.
    2024                 :             :  */
    2025                 :             : static void
    2026                 :         254 : compute_trivial_stats(VacAttrStatsP stats,
    2027                 :             :                       AnalyzeAttrFetchFunc fetchfunc,
    2028                 :             :                       int samplerows,
    2029                 :             :                       double totalrows)
    2030                 :             : {
    2031                 :             :     int         i;
    2032                 :         254 :     int         null_cnt = 0;
    2033                 :         254 :     int         nonnull_cnt = 0;
    2034                 :         254 :     double      total_width = 0;
    2035         [ +  - ]:         508 :     bool        is_varlena = (!stats->attrtype->typbyval &&
    2036         [ +  + ]:         254 :                               stats->attrtype->typlen == -1);
    2037         [ +  - ]:         508 :     bool        is_varwidth = (!stats->attrtype->typbyval &&
    2038         [ +  + ]:         254 :                                stats->attrtype->typlen < 0);
    2039                 :             : 
    2040         [ +  + ]:      888356 :     for (i = 0; i < samplerows; i++)
    2041                 :             :     {
    2042                 :             :         Datum       value;
    2043                 :             :         bool        isnull;
    2044                 :             : 
    2045                 :      888102 :         vacuum_delay_point(true);
    2046                 :             : 
    2047                 :      888102 :         value = fetchfunc(stats, i, &isnull);
    2048                 :             : 
    2049                 :             :         /* Check for null/nonnull */
    2050         [ +  + ]:      888102 :         if (isnull)
    2051                 :             :         {
    2052                 :      418699 :             null_cnt++;
    2053                 :      418699 :             continue;
    2054                 :             :         }
    2055                 :      469403 :         nonnull_cnt++;
    2056                 :             : 
    2057                 :             :         /*
    2058                 :             :          * If it's a variable-width field, add up widths for average width
    2059                 :             :          * calculation.  Note that if the value is toasted, we use the toasted
    2060                 :             :          * width.  We don't bother with this calculation if it's a fixed-width
    2061                 :             :          * type.
    2062                 :             :          */
    2063         [ +  + ]:      469403 :         if (is_varlena)
    2064                 :             :         {
    2065                 :      114031 :             total_width += VARSIZE_ANY(DatumGetPointer(value));
    2066                 :             :         }
    2067         [ -  + ]:      355372 :         else if (is_varwidth)
    2068                 :             :         {
    2069                 :             :             /* must be cstring */
    2070                 :           0 :             total_width += strlen(DatumGetCString(value)) + 1;
    2071                 :             :         }
    2072                 :             :     }
    2073                 :             : 
    2074                 :             :     /* We can only compute average width if we found some non-null values. */
    2075         [ +  + ]:         254 :     if (nonnull_cnt > 0)
    2076                 :             :     {
    2077                 :         144 :         stats->stats_valid = true;
    2078                 :             :         /* Do the simple null-frac and width stats */
    2079                 :         144 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2080         [ +  + ]:         144 :         if (is_varwidth)
    2081                 :          69 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2082                 :             :         else
    2083                 :          75 :             stats->stawidth = stats->attrtype->typlen;
    2084                 :         144 :         stats->stadistinct = 0.0;    /* "unknown" */
    2085                 :             :     }
    2086         [ +  - ]:         110 :     else if (null_cnt > 0)
    2087                 :             :     {
    2088                 :             :         /* We found only nulls; assume the column is entirely null */
    2089                 :         110 :         stats->stats_valid = true;
    2090                 :         110 :         stats->stanullfrac = 1.0;
    2091         [ +  - ]:         110 :         if (is_varwidth)
    2092                 :         110 :             stats->stawidth = 0; /* "unknown" */
    2093                 :             :         else
    2094                 :           0 :             stats->stawidth = stats->attrtype->typlen;
    2095                 :         110 :         stats->stadistinct = 0.0;    /* "unknown" */
    2096                 :             :     }
    2097                 :         254 : }
    2098                 :             : 
    2099                 :             : 
    2100                 :             : /*
    2101                 :             :  *  compute_distinct_stats() -- compute column statistics including ndistinct
    2102                 :             :  *
    2103                 :             :  *  We use this when we can find only an "=" operator for the datatype.
    2104                 :             :  *
    2105                 :             :  *  We determine the fraction of non-null rows, the average width, the
    2106                 :             :  *  most common values, and the (estimated) number of distinct values.
    2107                 :             :  *
    2108                 :             :  *  The most common values are determined by brute force: we keep a list
    2109                 :             :  *  of previously seen values, ordered by number of times seen, as we scan
    2110                 :             :  *  the samples.  A newly seen value is inserted just after the last
    2111                 :             :  *  multiply-seen value, causing the bottommost (oldest) singly-seen value
    2112                 :             :  *  to drop off the list.  The accuracy of this method, and also its cost,
    2113                 :             :  *  depend mainly on the length of the list we are willing to keep.
    2114                 :             :  */
    2115                 :             : static void
    2116                 :        1349 : compute_distinct_stats(VacAttrStatsP stats,
    2117                 :             :                        AnalyzeAttrFetchFunc fetchfunc,
    2118                 :             :                        int samplerows,
    2119                 :             :                        double totalrows)
    2120                 :             : {
    2121                 :             :     int         i;
    2122                 :        1349 :     int         null_cnt = 0;
    2123                 :        1349 :     int         nonnull_cnt = 0;
    2124                 :        1349 :     int         toowide_cnt = 0;
    2125                 :        1349 :     double      total_width = 0;
    2126         [ +  + ]:        2278 :     bool        is_varlena = (!stats->attrtype->typbyval &&
    2127         [ +  - ]:         929 :                               stats->attrtype->typlen == -1);
    2128         [ +  + ]:        2278 :     bool        is_varwidth = (!stats->attrtype->typbyval &&
    2129         [ +  - ]:         929 :                                stats->attrtype->typlen < 0);
    2130                 :             :     FmgrInfo    f_cmpeq;
    2131                 :             :     typedef struct
    2132                 :             :     {
    2133                 :             :         Datum       value;
    2134                 :             :         int         count;
    2135                 :             :     } TrackItem;
    2136                 :             :     TrackItem  *track;
    2137                 :             :     int         track_cnt,
    2138                 :             :                 track_max;
    2139                 :        1349 :     int         num_mcv = stats->attstattarget;
    2140                 :        1349 :     StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
    2141                 :             : 
    2142                 :             :     /*
    2143                 :             :      * We track up to 2*n values for an n-element MCV list; but at least 10
    2144                 :             :      */
    2145                 :        1349 :     track_max = 2 * num_mcv;
    2146         [ +  + ]:        1349 :     if (track_max < 10)
    2147                 :          52 :         track_max = 10;
    2148                 :        1349 :     track = palloc_array(TrackItem, track_max);
    2149                 :        1349 :     track_cnt = 0;
    2150                 :             : 
    2151                 :        1349 :     fmgr_info(mystats->eqfunc, &f_cmpeq);
    2152                 :             : 
    2153         [ +  + ]:     1025953 :     for (i = 0; i < samplerows; i++)
    2154                 :             :     {
    2155                 :             :         Datum       value;
    2156                 :             :         bool        isnull;
    2157                 :             :         bool        match;
    2158                 :             :         int         firstcount1,
    2159                 :             :                     j;
    2160                 :             : 
    2161                 :     1024604 :         vacuum_delay_point(true);
    2162                 :             : 
    2163                 :     1024604 :         value = fetchfunc(stats, i, &isnull);
    2164                 :             : 
    2165                 :             :         /* Check for null/nonnull */
    2166         [ +  + ]:     1024604 :         if (isnull)
    2167                 :             :         {
    2168                 :      850659 :             null_cnt++;
    2169                 :      850659 :             continue;
    2170                 :             :         }
    2171                 :      173945 :         nonnull_cnt++;
    2172                 :             : 
    2173                 :             :         /*
    2174                 :             :          * If it's a variable-width field, add up widths for average width
    2175                 :             :          * calculation.  Note that if the value is toasted, we use the toasted
    2176                 :             :          * width.  We don't bother with this calculation if it's a fixed-width
    2177                 :             :          * type.
    2178                 :             :          */
    2179         [ +  + ]:      173945 :         if (is_varlena)
    2180                 :             :         {
    2181                 :       61451 :             total_width += VARSIZE_ANY(DatumGetPointer(value));
    2182                 :             : 
    2183                 :             :             /*
    2184                 :             :              * If the value is toasted, we want to detoast it just once to
    2185                 :             :              * avoid repeated detoastings and resultant excess memory usage
    2186                 :             :              * during the comparisons.  Also, check to see if the value is
    2187                 :             :              * excessively wide, and if so don't detoast at all --- just
    2188                 :             :              * ignore the value.
    2189                 :             :              */
    2190         [ -  + ]:       61451 :             if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
    2191                 :             :             {
    2192                 :           0 :                 toowide_cnt++;
    2193                 :           0 :                 continue;
    2194                 :             :             }
    2195                 :       61451 :             value = PointerGetDatum(PG_DETOAST_DATUM(value));
    2196                 :             :         }
    2197         [ -  + ]:      112494 :         else if (is_varwidth)
    2198                 :             :         {
    2199                 :             :             /* must be cstring */
    2200                 :           0 :             total_width += strlen(DatumGetCString(value)) + 1;
    2201                 :             :         }
    2202                 :             : 
    2203                 :             :         /*
    2204                 :             :          * See if the value matches anything we're already tracking.
    2205                 :             :          */
    2206                 :      173945 :         match = false;
    2207                 :      173945 :         firstcount1 = track_cnt;
    2208         [ +  + ]:      425741 :         for (j = 0; j < track_cnt; j++)
    2209                 :             :         {
    2210         [ +  + ]:      421153 :             if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
    2211                 :             :                                                stats->attrcollid,
    2212                 :      421153 :                                                value, track[j].value)))
    2213                 :             :             {
    2214                 :      169357 :                 match = true;
    2215                 :      169357 :                 break;
    2216                 :             :             }
    2217   [ +  +  +  + ]:      251796 :             if (j < firstcount1 && track[j].count == 1)
    2218                 :        3345 :                 firstcount1 = j;
    2219                 :             :         }
    2220                 :             : 
    2221         [ +  + ]:      173945 :         if (match)
    2222                 :             :         {
    2223                 :             :             /* Found a match */
    2224                 :      169357 :             track[j].count++;
    2225                 :             :             /* This value may now need to "bubble up" in the track list */
    2226   [ +  +  +  + ]:      176859 :             while (j > 0 && track[j].count > track[j - 1].count)
    2227                 :             :             {
    2228                 :        7502 :                 swapDatum(track[j].value, track[j - 1].value);
    2229                 :        7502 :                 swapInt(track[j].count, track[j - 1].count);
    2230                 :        7502 :                 j--;
    2231                 :             :             }
    2232                 :             :         }
    2233                 :             :         else
    2234                 :             :         {
    2235                 :             :             /* No match.  Insert at head of count-1 list */
    2236         [ +  + ]:        4588 :             if (track_cnt < track_max)
    2237                 :        4319 :                 track_cnt++;
    2238         [ +  + ]:      103600 :             for (j = track_cnt - 1; j > firstcount1; j--)
    2239                 :             :             {
    2240                 :       99012 :                 track[j].value = track[j - 1].value;
    2241                 :       99012 :                 track[j].count = track[j - 1].count;
    2242                 :             :             }
    2243         [ +  - ]:        4588 :             if (firstcount1 < track_cnt)
    2244                 :             :             {
    2245                 :        4588 :                 track[firstcount1].value = value;
    2246                 :        4588 :                 track[firstcount1].count = 1;
    2247                 :             :             }
    2248                 :             :         }
    2249                 :             :     }
    2250                 :             : 
    2251                 :             :     /* We can only compute real stats if we found some non-null values. */
    2252         [ +  + ]:        1349 :     if (nonnull_cnt > 0)
    2253                 :             :     {
    2254                 :             :         int         nmultiple,
    2255                 :             :                     summultiple;
    2256                 :             : 
    2257                 :         991 :         stats->stats_valid = true;
    2258                 :             :         /* Do the simple null-frac and width stats */
    2259                 :         991 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2260         [ +  + ]:         991 :         if (is_varwidth)
    2261                 :         571 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2262                 :             :         else
    2263                 :         420 :             stats->stawidth = stats->attrtype->typlen;
    2264                 :             : 
    2265                 :             :         /* Count the number of values we found multiple times */
    2266                 :         991 :         summultiple = 0;
    2267         [ +  + ]:        4014 :         for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
    2268                 :             :         {
    2269         [ +  + ]:        3525 :             if (track[nmultiple].count == 1)
    2270                 :         502 :                 break;
    2271                 :        3023 :             summultiple += track[nmultiple].count;
    2272                 :             :         }
    2273                 :             : 
    2274         [ +  + ]:         991 :         if (nmultiple == 0)
    2275                 :             :         {
    2276                 :             :             /*
    2277                 :             :              * If we found no repeated non-null values, assume it's a unique
    2278                 :             :              * column; but be sure to discount for any nulls we found.
    2279                 :             :              */
    2280                 :         115 :             stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
    2281                 :             :         }
    2282   [ +  +  +  -  :         876 :         else if (track_cnt < track_max && toowide_cnt == 0 &&
                   +  + ]
    2283                 :             :                  nmultiple == track_cnt)
    2284                 :             :         {
    2285                 :             :             /*
    2286                 :             :              * Our track list includes every value in the sample, and every
    2287                 :             :              * value appeared more than once.  Assume the column has just
    2288                 :             :              * these values.  (This case is meant to address columns with
    2289                 :             :              * small, fixed sets of possible values, such as boolean or enum
    2290                 :             :              * columns.  If there are any values that appear just once in the
    2291                 :             :              * sample, including too-wide values, we should assume that that's
    2292                 :             :              * not what we're dealing with.)
    2293                 :             :              */
    2294                 :         489 :             stats->stadistinct = track_cnt;
    2295                 :             :         }
    2296                 :             :         else
    2297                 :             :         {
    2298                 :             :             /*----------
    2299                 :             :              * Estimate the number of distinct values using the estimator
    2300                 :             :              * proposed by Haas and Stokes in IBM Research Report RJ 10025:
    2301                 :             :              *      n*d / (n - f1 + f1*n/N)
    2302                 :             :              * where f1 is the number of distinct values that occurred
    2303                 :             :              * exactly once in our sample of n rows (from a total of N),
    2304                 :             :              * and d is the total number of distinct values in the sample.
    2305                 :             :              * This is their Duj1 estimator; the other estimators they
    2306                 :             :              * recommend are considerably more complex, and are numerically
    2307                 :             :              * very unstable when n is much smaller than N.
    2308                 :             :              *
    2309                 :             :              * In this calculation, we consider only non-nulls.  We used to
    2310                 :             :              * include rows with null values in the n and N counts, but that
    2311                 :             :              * leads to inaccurate answers in columns with many nulls, and
    2312                 :             :              * it's intuitively bogus anyway considering the desired result is
    2313                 :             :              * the number of distinct non-null values.
    2314                 :             :              *
    2315                 :             :              * We assume (not very reliably!) that all the multiply-occurring
    2316                 :             :              * values are reflected in the final track[] list, and the other
    2317                 :             :              * nonnull values all appeared but once.  (XXX this usually
    2318                 :             :              * results in a drastic overestimate of ndistinct.  Can we do
    2319                 :             :              * any better?)
    2320                 :             :              *----------
    2321                 :             :              */
    2322                 :         387 :             int         f1 = nonnull_cnt - summultiple;
    2323                 :         387 :             int         d = f1 + nmultiple;
    2324                 :         387 :             double      n = samplerows - null_cnt;
    2325                 :         387 :             double      N = totalrows * (1.0 - stats->stanullfrac);
    2326                 :             :             double      stadistinct;
    2327                 :             : 
    2328                 :             :             /* N == 0 shouldn't happen, but just in case ... */
    2329         [ +  - ]:         387 :             if (N > 0)
    2330                 :         387 :                 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
    2331                 :             :             else
    2332                 :           0 :                 stadistinct = 0;
    2333                 :             : 
    2334                 :             :             /* Clamp to sane range in case of roundoff error */
    2335         [ +  + ]:         387 :             if (stadistinct < d)
    2336                 :         104 :                 stadistinct = d;
    2337         [ -  + ]:         387 :             if (stadistinct > N)
    2338                 :           0 :                 stadistinct = N;
    2339                 :             :             /* And round to integer */
    2340                 :         387 :             stats->stadistinct = floor(stadistinct + 0.5);
    2341                 :             :         }
    2342                 :             : 
    2343                 :             :         /*
    2344                 :             :          * If we estimated the number of distinct values at more than 10% of
    2345                 :             :          * the total row count (a very arbitrary limit), then assume that
    2346                 :             :          * stadistinct should scale with the row count rather than be a fixed
    2347                 :             :          * value.
    2348                 :             :          */
    2349         [ +  + ]:         991 :         if (stats->stadistinct > 0.1 * totalrows)
    2350                 :         224 :             stats->stadistinct = -(stats->stadistinct / totalrows);
    2351                 :             : 
    2352                 :             :         /*
    2353                 :             :          * Decide how many values are worth storing as most-common values. If
    2354                 :             :          * we are able to generate a complete MCV list (all the values in the
    2355                 :             :          * sample will fit, and we think these are all the ones in the table),
    2356                 :             :          * then do so.  Otherwise, store only those values that are
    2357                 :             :          * significantly more common than the values not in the list.
    2358                 :             :          *
    2359                 :             :          * Note: the first of these cases is meant to address columns with
    2360                 :             :          * small, fixed sets of possible values, such as boolean or enum
    2361                 :             :          * columns.  If we can *completely* represent the column population by
    2362                 :             :          * an MCV list that will fit into the stats target, then we should do
    2363                 :             :          * so and thus provide the planner with complete information.  But if
    2364                 :             :          * the MCV list is not complete, it's generally worth being more
    2365                 :             :          * selective, and not just filling it all the way up to the stats
    2366                 :             :          * target.
    2367                 :             :          */
    2368   [ +  +  +  - ]:         991 :         if (track_cnt < track_max && toowide_cnt == 0 &&
    2369   [ +  +  +  + ]:         984 :             stats->stadistinct > 0 &&
    2370                 :             :             track_cnt <= num_mcv)
    2371                 :             :         {
    2372                 :             :             /* Track list includes all values seen, and all will fit */
    2373                 :         632 :             num_mcv = track_cnt;
    2374                 :             :         }
    2375                 :             :         else
    2376                 :             :         {
    2377                 :             :             int        *mcv_counts;
    2378                 :             : 
    2379                 :             :             /* Incomplete list; decide how many values are worth keeping */
    2380         [ +  + ]:         359 :             if (num_mcv > track_cnt)
    2381                 :         317 :                 num_mcv = track_cnt;
    2382                 :             : 
    2383         [ +  - ]:         359 :             if (num_mcv > 0)
    2384                 :             :             {
    2385                 :         359 :                 mcv_counts = palloc_array(int, num_mcv);
    2386         [ +  + ]:        1334 :                 for (i = 0; i < num_mcv; i++)
    2387                 :         975 :                     mcv_counts[i] = track[i].count;
    2388                 :             : 
    2389                 :         359 :                 num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
    2390                 :         359 :                                            stats->stadistinct,
    2391                 :         359 :                                            stats->stanullfrac,
    2392                 :             :                                            samplerows, totalrows);
    2393                 :             :             }
    2394                 :             :         }
    2395                 :             : 
    2396                 :             :         /* Generate MCV slot entry */
    2397         [ +  + ]:         991 :         if (num_mcv > 0)
    2398                 :             :         {
    2399                 :             :             MemoryContext old_context;
    2400                 :             :             Datum      *mcv_values;
    2401                 :             :             float4     *mcv_freqs;
    2402                 :             : 
    2403                 :             :             /* Must copy the target values into anl_context */
    2404                 :         987 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2405                 :         987 :             mcv_values = palloc_array(Datum, num_mcv);
    2406                 :         987 :             mcv_freqs = palloc_array(float4, num_mcv);
    2407         [ +  + ]:        4784 :             for (i = 0; i < num_mcv; i++)
    2408                 :             :             {
    2409                 :        7594 :                 mcv_values[i] = datumCopy(track[i].value,
    2410                 :        3797 :                                           stats->attrtype->typbyval,
    2411                 :        3797 :                                           stats->attrtype->typlen);
    2412                 :        3797 :                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
    2413                 :             :             }
    2414                 :         987 :             MemoryContextSwitchTo(old_context);
    2415                 :             : 
    2416                 :         987 :             stats->stakind[0] = STATISTIC_KIND_MCV;
    2417                 :         987 :             stats->staop[0] = mystats->eqopr;
    2418                 :         987 :             stats->stacoll[0] = stats->attrcollid;
    2419                 :         987 :             stats->stanumbers[0] = mcv_freqs;
    2420                 :         987 :             stats->numnumbers[0] = num_mcv;
    2421                 :         987 :             stats->stavalues[0] = mcv_values;
    2422                 :         987 :             stats->numvalues[0] = num_mcv;
    2423                 :             : 
    2424                 :             :             /*
    2425                 :             :              * Accept the defaults for stats->statypid and others. They have
    2426                 :             :              * been set before we were called (see vacuum.h)
    2427                 :             :              */
    2428                 :             :         }
    2429                 :             :     }
    2430         [ +  - ]:         358 :     else if (null_cnt > 0)
    2431                 :             :     {
    2432                 :             :         /* We found only nulls; assume the column is entirely null */
    2433                 :         358 :         stats->stats_valid = true;
    2434                 :         358 :         stats->stanullfrac = 1.0;
    2435         [ +  - ]:         358 :         if (is_varwidth)
    2436                 :         358 :             stats->stawidth = 0; /* "unknown" */
    2437                 :             :         else
    2438                 :           0 :             stats->stawidth = stats->attrtype->typlen;
    2439                 :         358 :         stats->stadistinct = 0.0;    /* "unknown" */
    2440                 :             :     }
    2441                 :             : 
    2442                 :             :     /* We don't need to bother cleaning up any of our temporary palloc's */
    2443                 :        1349 : }
    2444                 :             : 
    2445                 :             : 
    2446                 :             : /*
    2447                 :             :  *  compute_scalar_stats() -- compute column statistics
    2448                 :             :  *
    2449                 :             :  *  We use this when we can find "=" and "<" operators for the datatype.
    2450                 :             :  *
    2451                 :             :  *  We determine the fraction of non-null rows, the average width, the
    2452                 :             :  *  most common values, the (estimated) number of distinct values, the
    2453                 :             :  *  distribution histogram, and the correlation of physical to logical order.
    2454                 :             :  *
    2455                 :             :  *  The desired stats can be determined fairly easily after sorting the
    2456                 :             :  *  data values into order.
    2457                 :             :  */
    2458                 :             : static void
    2459                 :       51591 : compute_scalar_stats(VacAttrStatsP stats,
    2460                 :             :                      AnalyzeAttrFetchFunc fetchfunc,
    2461                 :             :                      int samplerows,
    2462                 :             :                      double totalrows)
    2463                 :             : {
    2464                 :             :     int         i;
    2465                 :       51591 :     int         null_cnt = 0;
    2466                 :       51591 :     int         nonnull_cnt = 0;
    2467                 :       51591 :     int         toowide_cnt = 0;
    2468                 :       51591 :     double      total_width = 0;
    2469         [ +  + ]:       64181 :     bool        is_varlena = (!stats->attrtype->typbyval &&
    2470         [ +  + ]:       12590 :                               stats->attrtype->typlen == -1);
    2471         [ +  + ]:       64181 :     bool        is_varwidth = (!stats->attrtype->typbyval &&
    2472         [ +  + ]:       12590 :                                stats->attrtype->typlen < 0);
    2473                 :             :     double      corr_xysum;
    2474                 :             :     SortSupportData ssup;
    2475                 :             :     ScalarItem *values;
    2476                 :       51591 :     int         values_cnt = 0;
    2477                 :             :     int        *tupnoLink;
    2478                 :             :     ScalarMCVItem *track;
    2479                 :       51591 :     int         track_cnt = 0;
    2480                 :       51591 :     int         num_mcv = stats->attstattarget;
    2481                 :       51591 :     int         num_bins = stats->attstattarget;
    2482                 :       51591 :     StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
    2483                 :             : 
    2484                 :       51591 :     values = palloc_array(ScalarItem, samplerows);
    2485                 :       51591 :     tupnoLink = palloc_array(int, samplerows);
    2486                 :       51591 :     track = palloc_array(ScalarMCVItem, num_mcv);
    2487                 :             : 
    2488                 :       51591 :     memset(&ssup, 0, sizeof(ssup));
    2489                 :       51591 :     ssup.ssup_cxt = CurrentMemoryContext;
    2490                 :       51591 :     ssup.ssup_collation = stats->attrcollid;
    2491                 :       51591 :     ssup.ssup_nulls_first = false;
    2492                 :             : 
    2493                 :             :     /*
    2494                 :             :      * For now, don't perform abbreviated key conversion, because full values
    2495                 :             :      * are required for MCV slot generation.  Supporting that optimization
    2496                 :             :      * would necessitate teaching compare_scalars() to call a tie-breaker.
    2497                 :             :      */
    2498                 :       51591 :     ssup.abbreviate = false;
    2499                 :             : 
    2500                 :       51591 :     PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
    2501                 :             : 
    2502                 :             :     /* Initial scan to find sortable values */
    2503         [ +  + ]:    49277644 :     for (i = 0; i < samplerows; i++)
    2504                 :             :     {
    2505                 :             :         Datum       value;
    2506                 :             :         bool        isnull;
    2507                 :             : 
    2508                 :    49226054 :         vacuum_delay_point(true);
    2509                 :             : 
    2510                 :    49226053 :         value = fetchfunc(stats, i, &isnull);
    2511                 :             : 
    2512                 :             :         /* Check for null/nonnull */
    2513         [ +  + ]:    49226053 :         if (isnull)
    2514                 :             :         {
    2515                 :     6196173 :             null_cnt++;
    2516                 :     6219710 :             continue;
    2517                 :             :         }
    2518                 :    43029880 :         nonnull_cnt++;
    2519                 :             : 
    2520                 :             :         /*
    2521                 :             :          * If it's a variable-width field, add up widths for average width
    2522                 :             :          * calculation.  Note that if the value is toasted, we use the toasted
    2523                 :             :          * width.  We don't bother with this calculation if it's a fixed-width
    2524                 :             :          * type.
    2525                 :             :          */
    2526         [ +  + ]:    43029880 :         if (is_varlena)
    2527                 :             :         {
    2528                 :     5067954 :             total_width += VARSIZE_ANY(DatumGetPointer(value));
    2529                 :             : 
    2530                 :             :             /*
    2531                 :             :              * If the value is toasted, we want to detoast it just once to
    2532                 :             :              * avoid repeated detoastings and resultant excess memory usage
    2533                 :             :              * during the comparisons.  Also, check to see if the value is
    2534                 :             :              * excessively wide, and if so don't detoast at all --- just
    2535                 :             :              * ignore the value.
    2536                 :             :              */
    2537         [ +  + ]:     5067954 :             if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
    2538                 :             :             {
    2539                 :       23537 :                 toowide_cnt++;
    2540                 :       23537 :                 continue;
    2541                 :             :             }
    2542                 :     5044417 :             value = PointerGetDatum(PG_DETOAST_DATUM(value));
    2543                 :             :         }
    2544         [ -  + ]:    37961926 :         else if (is_varwidth)
    2545                 :             :         {
    2546                 :             :             /* must be cstring */
    2547                 :           0 :             total_width += strlen(DatumGetCString(value)) + 1;
    2548                 :             :         }
    2549                 :             : 
    2550                 :             :         /* Add it to the list to be sorted */
    2551                 :    43006343 :         values[values_cnt].value = value;
    2552                 :    43006343 :         values[values_cnt].tupno = values_cnt;
    2553                 :    43006343 :         tupnoLink[values_cnt] = values_cnt;
    2554                 :    43006343 :         values_cnt++;
    2555                 :             :     }
    2556                 :             : 
    2557                 :             :     /* We can only compute real stats if we found some sortable values. */
    2558         [ +  + ]:       51590 :     if (values_cnt > 0)
    2559                 :             :     {
    2560                 :             :         int         ndistinct,  /* # distinct values in sample */
    2561                 :             :                     nmultiple,  /* # that appear multiple times */
    2562                 :             :                     num_hist,
    2563                 :             :                     dups_cnt;
    2564                 :       48301 :         int         slot_idx = 0;
    2565                 :             :         CompareScalarsContext cxt;
    2566                 :             : 
    2567                 :             :         /* Sort the collected values */
    2568                 :       48301 :         cxt.ssup = &ssup;
    2569                 :       48301 :         cxt.tupnoLink = tupnoLink;
    2570                 :       48301 :         qsort_interruptible(values, values_cnt, sizeof(ScalarItem),
    2571                 :             :                             compare_scalars, &cxt);
    2572                 :             : 
    2573                 :             :         /*
    2574                 :             :          * Now scan the values in order, find the most common ones, and also
    2575                 :             :          * accumulate ordering-correlation statistics.
    2576                 :             :          *
    2577                 :             :          * To determine which are most common, we first have to count the
    2578                 :             :          * number of duplicates of each value.  The duplicates are adjacent in
    2579                 :             :          * the sorted list, so a brute-force approach is to compare successive
    2580                 :             :          * datum values until we find two that are not equal. However, that
    2581                 :             :          * requires N-1 invocations of the datum comparison routine, which are
    2582                 :             :          * completely redundant with work that was done during the sort.  (The
    2583                 :             :          * sort algorithm must at some point have compared each pair of items
    2584                 :             :          * that are adjacent in the sorted order; otherwise it could not know
    2585                 :             :          * that it's ordered the pair correctly.) We exploit this by having
    2586                 :             :          * compare_scalars remember the highest tupno index that each
    2587                 :             :          * ScalarItem has been found equal to.  At the end of the sort, a
    2588                 :             :          * ScalarItem's tupnoLink will still point to itself if and only if it
    2589                 :             :          * is the last item of its group of duplicates (since the group will
    2590                 :             :          * be ordered by tupno).
    2591                 :             :          */
    2592                 :       48300 :         corr_xysum = 0;
    2593                 :       48300 :         ndistinct = 0;
    2594                 :       48300 :         nmultiple = 0;
    2595                 :       48300 :         dups_cnt = 0;
    2596         [ +  + ]:    43044643 :         for (i = 0; i < values_cnt; i++)
    2597                 :             :         {
    2598                 :    42996343 :             int         tupno = values[i].tupno;
    2599                 :             : 
    2600                 :    42996343 :             corr_xysum += ((double) i) * ((double) tupno);
    2601                 :    42996343 :             dups_cnt++;
    2602         [ +  + ]:    42996343 :             if (tupnoLink[tupno] == tupno)
    2603                 :             :             {
    2604                 :             :                 /* Reached end of duplicates of this value */
    2605                 :     9371565 :                 ndistinct++;
    2606         [ +  + ]:     9371565 :                 if (dups_cnt > 1)
    2607                 :             :                 {
    2608                 :      771585 :                     nmultiple++;
    2609         [ +  + ]:      771585 :                     if (track_cnt < num_mcv ||
    2610         [ +  + ]:      345556 :                         dups_cnt > track[track_cnt - 1].count)
    2611                 :             :                     {
    2612                 :             :                         /*
    2613                 :             :                          * Found a new item for the mcv list; find its
    2614                 :             :                          * position, bubbling down old items if needed. Loop
    2615                 :             :                          * invariant is that j points at an empty/ replaceable
    2616                 :             :                          * slot.
    2617                 :             :                          */
    2618                 :             :                         int         j;
    2619                 :             : 
    2620         [ +  + ]:      491902 :                         if (track_cnt < num_mcv)
    2621                 :      426029 :                             track_cnt++;
    2622         [ +  + ]:     6435783 :                         for (j = track_cnt - 1; j > 0; j--)
    2623                 :             :                         {
    2624         [ +  + ]:     6382808 :                             if (dups_cnt <= track[j - 1].count)
    2625                 :      438927 :                                 break;
    2626                 :     5943881 :                             track[j].count = track[j - 1].count;
    2627                 :     5943881 :                             track[j].first = track[j - 1].first;
    2628                 :             :                         }
    2629                 :      491902 :                         track[j].count = dups_cnt;
    2630                 :      491902 :                         track[j].first = i + 1 - dups_cnt;
    2631                 :             :                     }
    2632                 :             :                 }
    2633                 :     9371565 :                 dups_cnt = 0;
    2634                 :             :             }
    2635                 :             :         }
    2636                 :             : 
    2637                 :       48300 :         stats->stats_valid = true;
    2638                 :             :         /* Do the simple null-frac and width stats */
    2639                 :       48300 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2640         [ +  + ]:       48300 :         if (is_varwidth)
    2641                 :        7158 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2642                 :             :         else
    2643                 :       41142 :             stats->stawidth = stats->attrtype->typlen;
    2644                 :             : 
    2645         [ +  + ]:       48300 :         if (nmultiple == 0)
    2646                 :             :         {
    2647                 :             :             /*
    2648                 :             :              * If we found no repeated non-null values, assume it's a unique
    2649                 :             :              * column; but be sure to discount for any nulls we found.
    2650                 :             :              */
    2651                 :       13191 :             stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
    2652                 :             :         }
    2653   [ +  +  +  + ]:       35109 :         else if (toowide_cnt == 0 && nmultiple == ndistinct)
    2654                 :             :         {
    2655                 :             :             /*
    2656                 :             :              * Every value in the sample appeared more than once.  Assume the
    2657                 :             :              * column has just these values.  (This case is meant to address
    2658                 :             :              * columns with small, fixed sets of possible values, such as
    2659                 :             :              * boolean or enum columns.  If there are any values that appear
    2660                 :             :              * just once in the sample, including too-wide values, we should
    2661                 :             :              * assume that that's not what we're dealing with.)
    2662                 :             :              */
    2663                 :       21518 :             stats->stadistinct = ndistinct;
    2664                 :             :         }
    2665                 :             :         else
    2666                 :             :         {
    2667                 :             :             /*----------
    2668                 :             :              * Estimate the number of distinct values using the estimator
    2669                 :             :              * proposed by Haas and Stokes in IBM Research Report RJ 10025:
    2670                 :             :              *      n*d / (n - f1 + f1*n/N)
    2671                 :             :              * where f1 is the number of distinct values that occurred
    2672                 :             :              * exactly once in our sample of n rows (from a total of N),
    2673                 :             :              * and d is the total number of distinct values in the sample.
    2674                 :             :              * This is their Duj1 estimator; the other estimators they
    2675                 :             :              * recommend are considerably more complex, and are numerically
    2676                 :             :              * very unstable when n is much smaller than N.
    2677                 :             :              *
    2678                 :             :              * In this calculation, we consider only non-nulls.  We used to
    2679                 :             :              * include rows with null values in the n and N counts, but that
    2680                 :             :              * leads to inaccurate answers in columns with many nulls, and
    2681                 :             :              * it's intuitively bogus anyway considering the desired result is
    2682                 :             :              * the number of distinct non-null values.
    2683                 :             :              *
    2684                 :             :              * Overwidth values are assumed to have been distinct.
    2685                 :             :              *----------
    2686                 :             :              */
    2687                 :       13591 :             int         f1 = ndistinct - nmultiple + toowide_cnt;
    2688                 :       13591 :             int         d = f1 + nmultiple;
    2689                 :       13591 :             double      n = samplerows - null_cnt;
    2690                 :       13591 :             double      N = totalrows * (1.0 - stats->stanullfrac);
    2691                 :             :             double      stadistinct;
    2692                 :             : 
    2693                 :             :             /* N == 0 shouldn't happen, but just in case ... */
    2694         [ +  - ]:       13591 :             if (N > 0)
    2695                 :       13591 :                 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
    2696                 :             :             else
    2697                 :           0 :                 stadistinct = 0;
    2698                 :             : 
    2699                 :             :             /* Clamp to sane range in case of roundoff error */
    2700         [ +  + ]:       13591 :             if (stadistinct < d)
    2701                 :         729 :                 stadistinct = d;
    2702         [ -  + ]:       13591 :             if (stadistinct > N)
    2703                 :           0 :                 stadistinct = N;
    2704                 :             :             /* And round to integer */
    2705                 :       13591 :             stats->stadistinct = floor(stadistinct + 0.5);
    2706                 :             :         }
    2707                 :             : 
    2708                 :             :         /*
    2709                 :             :          * If we estimated the number of distinct values at more than 10% of
    2710                 :             :          * the total row count (a very arbitrary limit), then assume that
    2711                 :             :          * stadistinct should scale with the row count rather than be a fixed
    2712                 :             :          * value.
    2713                 :             :          */
    2714         [ +  + ]:       48300 :         if (stats->stadistinct > 0.1 * totalrows)
    2715                 :       10224 :             stats->stadistinct = -(stats->stadistinct / totalrows);
    2716                 :             : 
    2717                 :             :         /*
    2718                 :             :          * Decide how many values are worth storing as most-common values. If
    2719                 :             :          * we are able to generate a complete MCV list (all the values in the
    2720                 :             :          * sample will fit, and we think these are all the ones in the table),
    2721                 :             :          * then do so.  Otherwise, store only those values that are
    2722                 :             :          * significantly more common than the values not in the list.
    2723                 :             :          *
    2724                 :             :          * Note: the first of these cases is meant to address columns with
    2725                 :             :          * small, fixed sets of possible values, such as boolean or enum
    2726                 :             :          * columns.  If we can *completely* represent the column population by
    2727                 :             :          * an MCV list that will fit into the stats target, then we should do
    2728                 :             :          * so and thus provide the planner with complete information.  But if
    2729                 :             :          * the MCV list is not complete, it's generally worth being more
    2730                 :             :          * selective, and not just filling it all the way up to the stats
    2731                 :             :          * target.
    2732                 :             :          */
    2733   [ +  +  +  + ]:       48300 :         if (track_cnt == ndistinct && toowide_cnt == 0 &&
    2734   [ +  +  +  - ]:       21030 :             stats->stadistinct > 0 &&
    2735                 :             :             track_cnt <= num_mcv)
    2736                 :             :         {
    2737                 :             :             /* Track list includes all values seen, and all will fit */
    2738                 :       18733 :             num_mcv = track_cnt;
    2739                 :             :         }
    2740                 :             :         else
    2741                 :             :         {
    2742                 :             :             int        *mcv_counts;
    2743                 :             : 
    2744                 :             :             /* Incomplete list; decide how many values are worth keeping */
    2745         [ +  + ]:       29567 :             if (num_mcv > track_cnt)
    2746                 :       26989 :                 num_mcv = track_cnt;
    2747                 :             : 
    2748         [ +  + ]:       29567 :             if (num_mcv > 0)
    2749                 :             :             {
    2750                 :       16376 :                 mcv_counts = palloc_array(int, num_mcv);
    2751         [ +  + ]:      336558 :                 for (i = 0; i < num_mcv; i++)
    2752                 :      320182 :                     mcv_counts[i] = track[i].count;
    2753                 :             : 
    2754                 :       16376 :                 num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
    2755                 :       16376 :                                            stats->stadistinct,
    2756                 :       16376 :                                            stats->stanullfrac,
    2757                 :             :                                            samplerows, totalrows);
    2758                 :             :             }
    2759                 :             :         }
    2760                 :             : 
    2761                 :             :         /* Generate MCV slot entry */
    2762         [ +  + ]:       48300 :         if (num_mcv > 0)
    2763                 :             :         {
    2764                 :             :             MemoryContext old_context;
    2765                 :             :             Datum      *mcv_values;
    2766                 :             :             float4     *mcv_freqs;
    2767                 :             : 
    2768                 :             :             /* Must copy the target values into anl_context */
    2769                 :       35071 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2770                 :       35071 :             mcv_values = palloc_array(Datum, num_mcv);
    2771                 :       35071 :             mcv_freqs = palloc_array(float4, num_mcv);
    2772         [ +  + ]:      460927 :             for (i = 0; i < num_mcv; i++)
    2773                 :             :             {
    2774                 :      851712 :                 mcv_values[i] = datumCopy(values[track[i].first].value,
    2775                 :      425856 :                                           stats->attrtype->typbyval,
    2776                 :      425856 :                                           stats->attrtype->typlen);
    2777                 :      425856 :                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
    2778                 :             :             }
    2779                 :       35071 :             MemoryContextSwitchTo(old_context);
    2780                 :             : 
    2781                 :       35071 :             stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
    2782                 :       35071 :             stats->staop[slot_idx] = mystats->eqopr;
    2783                 :       35071 :             stats->stacoll[slot_idx] = stats->attrcollid;
    2784                 :       35071 :             stats->stanumbers[slot_idx] = mcv_freqs;
    2785                 :       35071 :             stats->numnumbers[slot_idx] = num_mcv;
    2786                 :       35071 :             stats->stavalues[slot_idx] = mcv_values;
    2787                 :       35071 :             stats->numvalues[slot_idx] = num_mcv;
    2788                 :             : 
    2789                 :             :             /*
    2790                 :             :              * Accept the defaults for stats->statypid and others. They have
    2791                 :             :              * been set before we were called (see vacuum.h)
    2792                 :             :              */
    2793                 :       35071 :             slot_idx++;
    2794                 :             :         }
    2795                 :             : 
    2796                 :             :         /*
    2797                 :             :          * Generate a histogram slot entry if there are at least two distinct
    2798                 :             :          * values not accounted for in the MCV list.  (This ensures the
    2799                 :             :          * histogram won't collapse to empty or a singleton.)
    2800                 :             :          */
    2801                 :       48300 :         num_hist = ndistinct - num_mcv;
    2802         [ +  + ]:       48300 :         if (num_hist > num_bins)
    2803                 :        7871 :             num_hist = num_bins + 1;
    2804         [ +  + ]:       48300 :         if (num_hist >= 2)
    2805                 :             :         {
    2806                 :             :             MemoryContext old_context;
    2807                 :             :             Datum      *hist_values;
    2808                 :             :             int         nvals;
    2809                 :             :             int         pos,
    2810                 :             :                         posfrac,
    2811                 :             :                         delta,
    2812                 :             :                         deltafrac;
    2813                 :             : 
    2814                 :             :             /* Sort the MCV items into position order to speed next loop */
    2815                 :       21764 :             qsort_interruptible(track, num_mcv, sizeof(ScalarMCVItem),
    2816                 :             :                                 compare_mcvs, NULL);
    2817                 :             : 
    2818                 :             :             /*
    2819                 :             :              * Collapse out the MCV items from the values[] array.
    2820                 :             :              *
    2821                 :             :              * Note we destroy the values[] array here... but we don't need it
    2822                 :             :              * for anything more.  We do, however, still need values_cnt.
    2823                 :             :              * nvals will be the number of remaining entries in values[].
    2824                 :             :              */
    2825         [ +  + ]:       21764 :             if (num_mcv > 0)
    2826                 :             :             {
    2827                 :             :                 int         src,
    2828                 :             :                             dest;
    2829                 :             :                 int         j;
    2830                 :             : 
    2831                 :       11322 :                 src = dest = 0;
    2832                 :       11322 :                 j = 0;          /* index of next interesting MCV item */
    2833         [ +  + ]:      412785 :                 while (src < values_cnt)
    2834                 :             :                 {
    2835                 :             :                     int         ncopy;
    2836                 :             : 
    2837         [ +  + ]:      401463 :                     if (j < num_mcv)
    2838                 :             :                     {
    2839                 :      392982 :                         int         first = track[j].first;
    2840                 :             : 
    2841         [ +  + ]:      392982 :                         if (src >= first)
    2842                 :             :                         {
    2843                 :             :                             /* advance past this MCV item */
    2844                 :      286180 :                             src = first + track[j].count;
    2845                 :      286180 :                             j++;
    2846                 :      286180 :                             continue;
    2847                 :             :                         }
    2848                 :      106802 :                         ncopy = first - src;
    2849                 :             :                     }
    2850                 :             :                     else
    2851                 :        8481 :                         ncopy = values_cnt - src;
    2852                 :      115283 :                     memmove(&values[dest], &values[src],
    2853                 :             :                             ncopy * sizeof(ScalarItem));
    2854                 :      115283 :                     src += ncopy;
    2855                 :      115283 :                     dest += ncopy;
    2856                 :             :                 }
    2857                 :       11322 :                 nvals = dest;
    2858                 :             :             }
    2859                 :             :             else
    2860                 :       10442 :                 nvals = values_cnt;
    2861                 :             :             Assert(nvals >= num_hist);
    2862                 :             : 
    2863                 :             :             /* Must copy the target values into anl_context */
    2864                 :       21764 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2865                 :       21764 :             hist_values = palloc_array(Datum, num_hist);
    2866                 :             : 
    2867                 :             :             /*
    2868                 :             :              * The object of this loop is to copy the first and last values[]
    2869                 :             :              * entries along with evenly-spaced values in between.  So the
    2870                 :             :              * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)].  But
    2871                 :             :              * computing that subscript directly risks integer overflow when
    2872                 :             :              * the stats target is more than a couple thousand.  Instead we
    2873                 :             :              * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
    2874                 :             :              * the integral and fractional parts of the sum separately.
    2875                 :             :              */
    2876                 :       21764 :             delta = (nvals - 1) / (num_hist - 1);
    2877                 :       21764 :             deltafrac = (nvals - 1) % (num_hist - 1);
    2878                 :       21764 :             pos = posfrac = 0;
    2879                 :             : 
    2880         [ +  + ]:     1134194 :             for (i = 0; i < num_hist; i++)
    2881                 :             :             {
    2882                 :     2224860 :                 hist_values[i] = datumCopy(values[pos].value,
    2883                 :     1112430 :                                            stats->attrtype->typbyval,
    2884                 :     1112430 :                                            stats->attrtype->typlen);
    2885                 :     1112430 :                 pos += delta;
    2886                 :     1112430 :                 posfrac += deltafrac;
    2887         [ +  + ]:     1112430 :                 if (posfrac >= (num_hist - 1))
    2888                 :             :                 {
    2889                 :             :                     /* fractional part exceeds 1, carry to integer part */
    2890                 :      374970 :                     pos++;
    2891                 :      374970 :                     posfrac -= (num_hist - 1);
    2892                 :             :                 }
    2893                 :             :             }
    2894                 :             : 
    2895                 :       21764 :             MemoryContextSwitchTo(old_context);
    2896                 :             : 
    2897                 :       21764 :             stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
    2898                 :       21764 :             stats->staop[slot_idx] = mystats->ltopr;
    2899                 :       21764 :             stats->stacoll[slot_idx] = stats->attrcollid;
    2900                 :       21764 :             stats->stavalues[slot_idx] = hist_values;
    2901                 :       21764 :             stats->numvalues[slot_idx] = num_hist;
    2902                 :             : 
    2903                 :             :             /*
    2904                 :             :              * Accept the defaults for stats->statypid and others. They have
    2905                 :             :              * been set before we were called (see vacuum.h)
    2906                 :             :              */
    2907                 :       21764 :             slot_idx++;
    2908                 :             :         }
    2909                 :             : 
    2910                 :             :         /* Generate a correlation entry if there are multiple values */
    2911         [ +  + ]:       48300 :         if (values_cnt > 1)
    2912                 :             :         {
    2913                 :             :             MemoryContext old_context;
    2914                 :             :             float4     *corrs;
    2915                 :             :             double      corr_xsum,
    2916                 :             :                         corr_x2sum;
    2917                 :             : 
    2918                 :             :             /* Must copy the target values into anl_context */
    2919                 :       45513 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2920                 :       45513 :             corrs = palloc_object(float4);
    2921                 :       45513 :             MemoryContextSwitchTo(old_context);
    2922                 :             : 
    2923                 :             :             /*----------
    2924                 :             :              * Since we know the x and y value sets are both
    2925                 :             :              *      0, 1, ..., values_cnt-1
    2926                 :             :              * we have sum(x) = sum(y) =
    2927                 :             :              *      (values_cnt-1)*values_cnt / 2
    2928                 :             :              * and sum(x^2) = sum(y^2) =
    2929                 :             :              *      (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
    2930                 :             :              *----------
    2931                 :             :              */
    2932                 :       45513 :             corr_xsum = ((double) (values_cnt - 1)) *
    2933                 :       45513 :                 ((double) values_cnt) / 2.0;
    2934                 :       45513 :             corr_x2sum = ((double) (values_cnt - 1)) *
    2935                 :       45513 :                 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
    2936                 :             : 
    2937                 :             :             /* And the correlation coefficient reduces to */
    2938                 :       45513 :             corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
    2939                 :       45513 :                 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
    2940                 :             : 
    2941                 :       45513 :             stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
    2942                 :       45513 :             stats->staop[slot_idx] = mystats->ltopr;
    2943                 :       45513 :             stats->stacoll[slot_idx] = stats->attrcollid;
    2944                 :       45513 :             stats->stanumbers[slot_idx] = corrs;
    2945                 :       45513 :             stats->numnumbers[slot_idx] = 1;
    2946                 :       45513 :             slot_idx++;
    2947                 :             :         }
    2948                 :             :     }
    2949         [ +  + ]:        3289 :     else if (nonnull_cnt > 0)
    2950                 :             :     {
    2951                 :             :         /* We found some non-null values, but they were all too wide */
    2952                 :             :         Assert(nonnull_cnt == toowide_cnt);
    2953                 :         212 :         stats->stats_valid = true;
    2954                 :             :         /* Do the simple null-frac and width stats */
    2955                 :         212 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2956         [ +  - ]:         212 :         if (is_varwidth)
    2957                 :         212 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2958                 :             :         else
    2959                 :           0 :             stats->stawidth = stats->attrtype->typlen;
    2960                 :             :         /* Assume all too-wide values are distinct, so it's a unique column */
    2961                 :         212 :         stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
    2962                 :             :     }
    2963         [ +  - ]:        3077 :     else if (null_cnt > 0)
    2964                 :             :     {
    2965                 :             :         /* We found only nulls; assume the column is entirely null */
    2966                 :        3077 :         stats->stats_valid = true;
    2967                 :        3077 :         stats->stanullfrac = 1.0;
    2968         [ +  + ]:        3077 :         if (is_varwidth)
    2969                 :        2654 :             stats->stawidth = 0; /* "unknown" */
    2970                 :             :         else
    2971                 :         423 :             stats->stawidth = stats->attrtype->typlen;
    2972                 :        3077 :         stats->stadistinct = 0.0;    /* "unknown" */
    2973                 :             :     }
    2974                 :             : 
    2975                 :             :     /* We don't need to bother cleaning up any of our temporary palloc's */
    2976                 :       51589 : }
    2977                 :             : 
    2978                 :             : /*
    2979                 :             :  * Comparator for sorting ScalarItems
    2980                 :             :  *
    2981                 :             :  * Aside from sorting the items, we update the tupnoLink[] array
    2982                 :             :  * whenever two ScalarItems are found to contain equal datums.  The array
    2983                 :             :  * is indexed by tupno; for each ScalarItem, it contains the highest
    2984                 :             :  * tupno that that item's datum has been found to be equal to.  This allows
    2985                 :             :  * us to avoid additional comparisons in compute_scalar_stats().
    2986                 :             :  */
    2987                 :             : static int
    2988                 :   405693465 : compare_scalars(const void *a, const void *b, void *arg)
    2989                 :             : {
    2990                 :   405693465 :     Datum       da = ((const ScalarItem *) a)->value;
    2991                 :   405693465 :     int         ta = ((const ScalarItem *) a)->tupno;
    2992                 :   405693465 :     Datum       db = ((const ScalarItem *) b)->value;
    2993                 :   405693465 :     int         tb = ((const ScalarItem *) b)->tupno;
    2994                 :   405693465 :     CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
    2995                 :             :     int         compare;
    2996                 :             : 
    2997                 :   405693465 :     compare = ApplySortComparator(da, false, db, false, cxt->ssup);
    2998         [ +  + ]:   405693465 :     if (compare != 0)
    2999                 :   156373701 :         return compare;
    3000                 :             : 
    3001                 :             :     /*
    3002                 :             :      * The two datums are equal, so update cxt->tupnoLink[].
    3003                 :             :      */
    3004         [ +  + ]:   249319764 :     if (cxt->tupnoLink[ta] < tb)
    3005                 :    34836031 :         cxt->tupnoLink[ta] = tb;
    3006         [ +  + ]:   249319764 :     if (cxt->tupnoLink[tb] < ta)
    3007                 :     2491008 :         cxt->tupnoLink[tb] = ta;
    3008                 :             : 
    3009                 :             :     /*
    3010                 :             :      * For equal datums, sort by tupno
    3011                 :             :      */
    3012                 :   249319764 :     return ta - tb;
    3013                 :             : }
    3014                 :             : 
    3015                 :             : /*
    3016                 :             :  * Comparator for sorting ScalarMCVItems by position
    3017                 :             :  */
    3018                 :             : static int
    3019                 :     1479054 : compare_mcvs(const void *a, const void *b, void *arg)
    3020                 :             : {
    3021                 :     1479054 :     int         da = ((const ScalarMCVItem *) a)->first;
    3022                 :     1479054 :     int         db = ((const ScalarMCVItem *) b)->first;
    3023                 :             : 
    3024                 :     1479054 :     return da - db;
    3025                 :             : }
    3026                 :             : 
    3027                 :             : /*
    3028                 :             :  * Analyze the list of common values in the sample and decide how many are
    3029                 :             :  * worth storing in the table's MCV list.
    3030                 :             :  *
    3031                 :             :  * mcv_counts is assumed to be a list of the counts of the most common values
    3032                 :             :  * seen in the sample, starting with the most common.  The return value is the
    3033                 :             :  * number that are significantly more common than the values not in the list,
    3034                 :             :  * and which are therefore deemed worth storing in the table's MCV list.
    3035                 :             :  */
    3036                 :             : static int
    3037                 :       16735 : analyze_mcv_list(int *mcv_counts,
    3038                 :             :                  int num_mcv,
    3039                 :             :                  double stadistinct,
    3040                 :             :                  double stanullfrac,
    3041                 :             :                  int samplerows,
    3042                 :             :                  double totalrows)
    3043                 :             : {
    3044                 :             :     double      ndistinct_table;
    3045                 :             :     double      sumcount;
    3046                 :             :     int         i;
    3047                 :             : 
    3048                 :             :     /*
    3049                 :             :      * If the entire table was sampled, keep the whole list.  This also
    3050                 :             :      * protects us against division by zero in the code below.
    3051                 :             :      */
    3052   [ +  +  -  + ]:       16735 :     if (samplerows == totalrows || totalrows <= 1.0)
    3053                 :       16172 :         return num_mcv;
    3054                 :             : 
    3055                 :             :     /* Re-extract the estimated number of distinct nonnull values in table */
    3056                 :         563 :     ndistinct_table = stadistinct;
    3057         [ +  + ]:         563 :     if (ndistinct_table < 0)
    3058                 :         102 :         ndistinct_table = -ndistinct_table * totalrows;
    3059                 :             : 
    3060                 :             :     /*
    3061                 :             :      * Exclude the least common values from the MCV list, if they are not
    3062                 :             :      * significantly more common than the estimated selectivity they would
    3063                 :             :      * have if they weren't in the list.  All non-MCV values are assumed to be
    3064                 :             :      * equally common, after taking into account the frequencies of all the
    3065                 :             :      * values in the MCV list and the number of nulls (c.f. eqsel()).
    3066                 :             :      *
    3067                 :             :      * Here sumcount tracks the total count of all but the last (least common)
    3068                 :             :      * value in the MCV list, allowing us to determine the effect of excluding
    3069                 :             :      * that value from the list.
    3070                 :             :      *
    3071                 :             :      * Note that we deliberately do this by removing values from the full
    3072                 :             :      * list, rather than starting with an empty list and adding values,
    3073                 :             :      * because the latter approach can fail to add any values if all the most
    3074                 :             :      * common values have around the same frequency and make up the majority
    3075                 :             :      * of the table, so that the overall average frequency of all values is
    3076                 :             :      * roughly the same as that of the common values.  This would lead to any
    3077                 :             :      * uncommon values being significantly overestimated.
    3078                 :             :      */
    3079                 :         563 :     sumcount = 0.0;
    3080         [ +  + ]:        1176 :     for (i = 0; i < num_mcv - 1; i++)
    3081                 :         613 :         sumcount += mcv_counts[i];
    3082                 :             : 
    3083         [ +  - ]:         698 :     while (num_mcv > 0)
    3084                 :             :     {
    3085                 :             :         double      selec,
    3086                 :             :                     otherdistinct,
    3087                 :             :                     N,
    3088                 :             :                     n,
    3089                 :             :                     K,
    3090                 :             :                     variance,
    3091                 :             :                     stddev;
    3092                 :             : 
    3093                 :             :         /*
    3094                 :             :          * Estimated selectivity the least common value would have if it
    3095                 :             :          * wasn't in the MCV list (c.f. eqsel()).
    3096                 :             :          */
    3097                 :         698 :         selec = 1.0 - sumcount / samplerows - stanullfrac;
    3098         [ -  + ]:         698 :         if (selec < 0.0)
    3099                 :           0 :             selec = 0.0;
    3100         [ -  + ]:         698 :         if (selec > 1.0)
    3101                 :           0 :             selec = 1.0;
    3102                 :         698 :         otherdistinct = ndistinct_table - (num_mcv - 1);
    3103         [ +  - ]:         698 :         if (otherdistinct > 1)
    3104                 :         698 :             selec /= otherdistinct;
    3105                 :             : 
    3106                 :             :         /*
    3107                 :             :          * If the value is kept in the MCV list, its population frequency is
    3108                 :             :          * assumed to equal its sample frequency.  We use the lower end of a
    3109                 :             :          * textbook continuity-corrected Wald-type confidence interval to
    3110                 :             :          * determine if that is significantly more common than the non-MCV
    3111                 :             :          * frequency --- specifically we assume the population frequency is
    3112                 :             :          * highly likely to be within around 2 standard errors of the sample
    3113                 :             :          * frequency, which equates to an interval of 2 standard deviations
    3114                 :             :          * either side of the sample count, plus an additional 0.5 for the
    3115                 :             :          * continuity correction.  Since we are sampling without replacement,
    3116                 :             :          * this is a hypergeometric distribution.
    3117                 :             :          *
    3118                 :             :          * XXX: Empirically, this approach seems to work quite well, but it
    3119                 :             :          * may be worth considering more advanced techniques for estimating
    3120                 :             :          * the confidence interval of the hypergeometric distribution.
    3121                 :             :          */
    3122                 :         698 :         N = totalrows;
    3123                 :         698 :         n = samplerows;
    3124                 :         698 :         K = N * mcv_counts[num_mcv - 1] / n;
    3125                 :         698 :         variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
    3126                 :         698 :         stddev = sqrt(variance);
    3127                 :             : 
    3128         [ +  + ]:         698 :         if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
    3129                 :             :         {
    3130                 :             :             /*
    3131                 :             :              * The value is significantly more common than the non-MCV
    3132                 :             :              * selectivity would suggest.  Keep it, and all the other more
    3133                 :             :              * common values in the list.
    3134                 :             :              */
    3135                 :         521 :             break;
    3136                 :             :         }
    3137                 :             :         else
    3138                 :             :         {
    3139                 :             :             /* Discard this value and consider the next least common value */
    3140                 :         177 :             num_mcv--;
    3141         [ +  + ]:         177 :             if (num_mcv == 0)
    3142                 :          42 :                 break;
    3143                 :         135 :             sumcount -= mcv_counts[num_mcv - 1];
    3144                 :             :         }
    3145                 :             :     }
    3146                 :         563 :     return num_mcv;
    3147                 :             : }
        

Generated by: LCOV version 2.0-1