LCOV - code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 921 967 95.2 %
Date: 2024-07-27 04:11:39 Functions: 18 18 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14