LCOV - code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 942 988 95.3 %
Date: 2025-11-10 05:18:35 Functions: 18 18 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16