LCOV - code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 95.8 % 1009 967
Test Date: 2026-07-07 09:15:43 Functions: 100.0 % 20 20
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 84.9 % 588 499

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

Generated by: LCOV version 2.0-1