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

Generated by: LCOV version 2.0-1