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

Generated by: LCOV version 1.14