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

Generated by: LCOV version 1.13