LCOV - code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 920 970 94.8 %
Date: 2024-04-13 10:11:43 Functions: 19 19 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14