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-04-21 04:16:29 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        10295 : 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        10295 :     AcquireSampleRowsFunc acquirefunc = NULL;
     117        10295 :     BlockNumber relpages = 0;
     118        10295 :     bool        stats_imported = false;
     119              : 
     120              :     /* Select logging level */
     121        10295 :     if (params->options & VACOPT_VERBOSE)
     122            6 :         elevel = INFO;
     123              :     else
     124        10289 :         elevel = DEBUG2;
     125              : 
     126              :     /* Set up static variables */
     127        10295 :     vac_strategy = bstrategy;
     128              : 
     129              :     /*
     130              :      * Check for user-requested abort.
     131              :      */
     132        10295 :     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        10295 :     onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
     144        10295 :                                   params->log_analyze_min_duration >= 0,
     145              :                                   ShareUpdateExclusiveLock);
     146              : 
     147              :     /* leave if relation could not be opened or locked */
     148        10295 :     if (!onerel)
     149          124 :         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        10289 :     if (!vacuum_is_permitted_for_relation(RelationGetRelid(onerel),
     159              :                                           onerel->rd_rel,
     160        10289 :                                           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        10265 :     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        10265 :     if (RelationGetRelid(onerel) == StatisticRelationId)
     182              :     {
     183           94 :         relation_close(onerel, ShareUpdateExclusiveLock);
     184           94 :         return;
     185              :     }
     186              : 
     187              :     /*
     188              :      * Check the given list of columns
     189              :      */
     190        10171 :     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        10136 :     pgstat_progress_start_command(PROGRESS_COMMAND_ANALYZE,
     201              :                                   RelationGetRelid(onerel));
     202        10136 :     if (AmAutoVacuumWorkerProcess())
     203          321 :         pgstat_progress_update_param(PROGRESS_ANALYZE_STARTED_BY,
     204              :                                      PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM);
     205              :     else
     206         9815 :         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        10136 :     if (onerel->rd_rel->relkind == RELKIND_RELATION ||
     213          544 :         onerel->rd_rel->relkind == RELKIND_MATVIEW)
     214              :     {
     215              :         /* Regular table, so we'll use the regular row acquisition function */
     216         9594 :         acquirefunc = acquire_sample_rows;
     217              :         /* Also get regular table's size */
     218         9594 :         relpages = RelationGetNumberOfBlocks(onerel);
     219              :     }
     220          542 :     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           44 :         fdwroutine = GetFdwRoutineForRelation(onerel, false);
     229              : 
     230           87 :         if (fdwroutine->ImportForeignStatistics != NULL &&
     231           43 :             fdwroutine->ImportForeignStatistics(onerel, va_cols, elevel))
     232            6 :             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          498 :     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        10136 :     if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
     275         9638 :         && !stats_imported)
     276         9632 :         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        10131 :     if (onerel->rd_rel->relhassubclass)
     283          589 :         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        10131 :     relation_close(onerel, NoLock);
     293              : 
     294        10131 : out:
     295        10131 :     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        10221 : 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        10221 :     TimestampTz starttime = 0;
     330              :     MemoryContext caller_context;
     331              :     Oid         save_userid;
     332              :     int         save_sec_context;
     333              :     int         save_nestlevel;
     334        10221 :     WalUsage    startwalusage = pgWalUsage;
     335        10221 :     BufferUsage startbufferusage = pgBufferUsage;
     336              :     BufferUsage bufferusage;
     337        10221 :     PgStat_Counter startreadtime = 0;
     338        10221 :     PgStat_Counter startwritetime = 0;
     339              : 
     340        10221 :     verbose = (params->options & VACOPT_VERBOSE) != 0;
     341        10543 :     instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
     342          322 :                               params->log_analyze_min_duration >= 0));
     343        10221 :     if (inh)
     344          589 :         ereport(elevel,
     345              :                 (errmsg("analyzing \"%s.%s\" inheritance tree",
     346              :                         get_namespace_name(RelationGetNamespace(onerel)),
     347              :                         RelationGetRelationName(onerel))));
     348              :     else
     349         9632 :         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        10221 :     anl_context = AllocSetContextCreate(CurrentMemoryContext,
     359              :                                         "Analyze",
     360              :                                         ALLOCSET_DEFAULT_SIZES);
     361        10221 :     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        10221 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
     369        10221 :     SetUserIdAndSecContext(onerel->rd_rel->relowner,
     370              :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
     371        10221 :     save_nestlevel = NewGUCNestLevel();
     372        10221 :     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        10221 :     if (instrument)
     379              :     {
     380          322 :         if (track_io_timing)
     381              :         {
     382            0 :             startreadtime = pgStatBlockReadTime;
     383            0 :             startwritetime = pgStatBlockWriteTime;
     384              :         }
     385              : 
     386          322 :         pg_rusage_init(&ru0);
     387              :     }
     388              : 
     389              :     /* Used for instrumentation and stats report */
     390        10221 :     starttime = GetCurrentTimestamp();
     391              : 
     392              :     /*
     393              :      * Determine which columns to analyze.
     394              :      */
     395        10221 :     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        10181 :         attr_cnt = onerel->rd_att->natts;
     417              :         vacattrstats = (VacAttrStats **)
     418        10181 :             palloc(attr_cnt * sizeof(VacAttrStats *));
     419        10181 :         tcnt = 0;
     420        81808 :         for (i = 1; i <= attr_cnt; i++)
     421              :         {
     422        71627 :             vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
     423        71627 :             if (vacattrstats[tcnt] != NULL)
     424        71548 :                 tcnt++;
     425              :         }
     426        10181 :         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        10221 :     if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     439              :     {
     440          498 :         List       *idxs = RelationGetIndexList(onerel);
     441              : 
     442          498 :         Irel = NULL;
     443          498 :         nindexes = 0;
     444          498 :         hasindex = idxs != NIL;
     445          498 :         list_free(idxs);
     446              :     }
     447         9723 :     else if (!inh)
     448              :     {
     449         9632 :         vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
     450         9632 :         hasindex = nindexes > 0;
     451              :     }
     452              :     else
     453              :     {
     454           91 :         Irel = NULL;
     455           91 :         nindexes = 0;
     456           91 :         hasindex = false;
     457              :     }
     458        10221 :     indexdata = NULL;
     459        10221 :     if (nindexes > 0)
     460              :     {
     461         7398 :         indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
     462        21419 :         for (ind = 0; ind < nindexes; ind++)
     463              :         {
     464        14021 :             AnlIndexData *thisdata = &indexdata[ind];
     465              :             IndexInfo  *indexInfo;
     466              : 
     467        14021 :             thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
     468        14021 :             thisdata->tupleFract = 1.0; /* fix later if partial */
     469        14021 :             if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
     470              :             {
     471           77 :                 ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
     472              : 
     473           77 :                 thisdata->vacattrstats = (VacAttrStats **)
     474           77 :                     palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
     475           77 :                 tcnt = 0;
     476          157 :                 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
     477              :                 {
     478           80 :                     int         keycol = indexInfo->ii_IndexAttrNumbers[i];
     479              : 
     480           80 :                     if (keycol == 0)
     481              :                     {
     482              :                         /* Found an index expression */
     483              :                         Node       *indexkey;
     484              : 
     485           77 :                         if (indexpr_item == NULL)   /* shouldn't happen */
     486            0 :                             elog(ERROR, "too few entries in indexprs list");
     487           77 :                         indexkey = (Node *) lfirst(indexpr_item);
     488           77 :                         indexpr_item = lnext(indexInfo->ii_Expressions,
     489              :                                              indexpr_item);
     490          154 :                         thisdata->vacattrstats[tcnt] =
     491           77 :                             examine_attribute(Irel[ind], i + 1, indexkey);
     492           77 :                         if (thisdata->vacattrstats[tcnt] != NULL)
     493           77 :                             tcnt++;
     494              :                     }
     495              :                 }
     496           77 :                 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        10221 :     targrows = 100;
     508        81814 :     for (i = 0; i < attr_cnt; i++)
     509              :     {
     510        71593 :         if (targrows < vacattrstats[i]->minrows)
     511        10172 :             targrows = vacattrstats[i]->minrows;
     512              :     }
     513        24242 :     for (ind = 0; ind < nindexes; ind++)
     514              :     {
     515        14021 :         AnlIndexData *thisdata = &indexdata[ind];
     516              : 
     517        14098 :         for (i = 0; i < thisdata->attr_cnt; i++)
     518              :         {
     519           77 :             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        10221 :     minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
     530              : 
     531        10221 :     if (targrows < minrows)
     532            0 :         targrows = minrows;
     533              : 
     534              :     /*
     535              :      * Acquire the sample rows
     536              :      */
     537        10221 :     rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
     538        10221 :     pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
     539              :                                  inh ? PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH :
     540              :                                  PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS);
     541        10221 :     if (inh)
     542          589 :         numrows = acquire_inherited_sample_rows(onerel, elevel,
     543              :                                                 rows, targrows,
     544              :                                                 &totalrows, &totaldeadrows);
     545              :     else
     546         9632 :         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        10220 :     if (numrows > 0)
     557              :     {
     558              :         MemoryContext col_context,
     559              :                     old_context;
     560              : 
     561         6774 :         pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE,
     562              :                                      PROGRESS_ANALYZE_PHASE_COMPUTE_STATS);
     563              : 
     564         6774 :         col_context = AllocSetContextCreate(anl_context,
     565              :                                             "Analyze Column",
     566              :                                             ALLOCSET_DEFAULT_SIZES);
     567         6774 :         old_context = MemoryContextSwitchTo(col_context);
     568              : 
     569        57455 :         for (i = 0; i < attr_cnt; i++)
     570              :         {
     571        50681 :             VacAttrStats *stats = vacattrstats[i];
     572              :             AttributeOpts *aopt;
     573              : 
     574        50681 :             stats->rows = rows;
     575        50681 :             stats->tupDesc = onerel->rd_att;
     576        50681 :             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        50681 :             aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
     586        50681 :             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        50681 :             MemoryContextReset(col_context);
     596              :         }
     597              : 
     598         6774 :         if (nindexes > 0)
     599         4142 :             compute_index_stats(onerel, totalrows,
     600              :                                 indexdata, nindexes,
     601              :                                 rows, numrows,
     602              :                                 col_context);
     603              : 
     604         6770 :         MemoryContextSwitchTo(old_context);
     605         6770 :         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         6770 :         update_attstats(RelationGetRelid(onerel), inh,
     613              :                         attr_cnt, vacattrstats);
     614              : 
     615        14788 :         for (ind = 0; ind < nindexes; ind++)
     616              :         {
     617         8018 :             AnlIndexData *thisdata = &indexdata[ind];
     618              : 
     619         8018 :             update_attstats(RelationGetRelid(Irel[ind]), false,
     620              :                             thisdata->attr_cnt, thisdata->vacattrstats);
     621              :         }
     622              : 
     623              :         /* Build extended statistics (if there are any). */
     624         6770 :         BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
     625              :                                    attr_cnt, vacattrstats);
     626              :     }
     627              : 
     628        10216 :     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        10216 :     if (!inh)
     643              :     {
     644         9627 :         BlockNumber relallvisible = 0;
     645         9627 :         BlockNumber relallfrozen = 0;
     646              : 
     647         9627 :         if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
     648         9590 :             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         9627 :         CommandCounterIncrement();
     655         9627 :         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        23640 :         for (ind = 0; ind < nindexes; ind++)
     668              :         {
     669        14013 :             AnlIndexData *thisdata = &indexdata[ind];
     670              :             double      totalindexrows;
     671              : 
     672        14013 :             totalindexrows = ceil(thisdata->tupleFract * totalrows);
     673        14013 :             vac_update_relstats(Irel[ind],
     674        14013 :                                 RelationGetNumberOfBlocks(Irel[ind]),
     675              :                                 totalindexrows,
     676              :                                 0, 0,
     677              :                                 false,
     678              :                                 InvalidTransactionId,
     679              :                                 InvalidMultiXactId,
     680              :                                 NULL, NULL,
     681              :                                 in_outer_xact);
     682              :         }
     683              :     }
     684          589 :     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          498 :         CommandCounterIncrement();
     691          498 :         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        10216 :     if (!inh)
     708         9627 :         pgstat_report_analyze(onerel, totalrows, totaldeadrows,
     709              :                               (va_cols == NIL), starttime);
     710          589 :     else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     711          498 :         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        10216 :     if (!(params->options & VACOPT_VACUUM))
     721              :     {
     722        19059 :         for (ind = 0; ind < nindexes; ind++)
     723              :         {
     724              :             IndexBulkDeleteResult *stats;
     725              :             IndexVacuumInfo ivinfo;
     726              : 
     727        10804 :             ivinfo.index = Irel[ind];
     728        10804 :             ivinfo.heaprel = onerel;
     729        10804 :             ivinfo.analyze_only = true;
     730        10804 :             ivinfo.estimated_count = true;
     731        10804 :             ivinfo.message_level = elevel;
     732        10804 :             ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
     733        10804 :             ivinfo.strategy = vac_strategy;
     734              : 
     735        10804 :             stats = index_vacuum_cleanup(&ivinfo, NULL);
     736              : 
     737        10804 :             if (stats)
     738            0 :                 pfree(stats);
     739              :         }
     740              :     }
     741              : 
     742              :     /* Done with indexes */
     743        10216 :     vac_close_indexes(nindexes, Irel, NoLock);
     744              : 
     745              :     /* Log the action if appropriate */
     746        10216 :     if (instrument)
     747              :     {
     748          322 :         TimestampTz endtime = GetCurrentTimestamp();
     749              : 
     750          612 :         if (verbose || params->log_analyze_min_duration == 0 ||
     751          290 :             TimestampDifferenceExceeds(starttime, endtime,
     752          290 :                                        params->log_analyze_min_duration))
     753              :         {
     754              :             long        delay_in_ms;
     755              :             WalUsage    walusage;
     756           32 :             double      read_rate = 0;
     757           32 :             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           32 :             memset(&bufferusage, 0, sizeof(BufferUsage));
     765           32 :             BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
     766           32 :             memset(&walusage, 0, sizeof(WalUsage));
     767           32 :             WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
     768              : 
     769           32 :             total_blks_hit = bufferusage.shared_blks_hit +
     770           32 :                 bufferusage.local_blks_hit;
     771           32 :             total_blks_read = bufferusage.shared_blks_read +
     772           32 :                 bufferusage.local_blks_read;
     773           32 :             total_blks_dirtied = bufferusage.shared_blks_dirtied +
     774           32 :                 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           32 :             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           32 :             if (delay_in_ms > 0)
     799              :             {
     800           32 :                 read_rate = (double) BLCKSZ * total_blks_read /
     801           32 :                     (1024 * 1024) / (delay_in_ms / 1000.0);
     802           32 :                 write_rate = (double) BLCKSZ * total_blks_dirtied /
     803           32 :                     (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           32 :             initStringInfo(&buf);
     812              : 
     813           32 :             if (AmAutoVacuumWorkerProcess())
     814           32 :                 msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
     815              :             else
     816            0 :                 msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
     817              : 
     818           32 :             appendStringInfo(&buf, msgfmt,
     819              :                              get_database_name(MyDatabaseId),
     820           32 :                              get_namespace_name(RelationGetNamespace(onerel)),
     821           32 :                              RelationGetRelationName(onerel));
     822           32 :             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           32 :             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           32 :             appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
     840              :                              read_rate, write_rate);
     841           32 :             appendStringInfo(&buf, _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
     842              :                              total_blks_hit,
     843              :                              total_blks_read,
     844              :                              total_blks_dirtied);
     845           32 :             appendStringInfo(&buf,
     846           32 :                              _("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           32 :             appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
     853              : 
     854           32 :             ereport(verbose ? INFO : LOG,
     855              :                     (errmsg_internal("%s", buf.data)));
     856              : 
     857           32 :             pfree(buf.data);
     858              :         }
     859              :     }
     860              : 
     861              :     /* Roll back any GUC changes executed by index functions */
     862        10216 :     AtEOXact_GUC(false, save_nestlevel);
     863              : 
     864              :     /* Restore userid and security context */
     865        10216 :     SetUserIdAndSecContext(save_userid, save_sec_context);
     866              : 
     867              :     /* Restore current context and release memory */
     868        10216 :     MemoryContextSwitchTo(caller_context);
     869        10216 :     MemoryContextDelete(anl_context);
     870        10216 :     anl_context = NULL;
     871        10216 : }
     872              : 
     873              : /*
     874              :  * Compute statistics about indexes of a relation
     875              :  */
     876              : static void
     877         4142 : 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         4142 :     ind_context = AllocSetContextCreate(anl_context,
     890              :                                         "Analyze Index",
     891              :                                         ALLOCSET_DEFAULT_SIZES);
     892         4142 :     old_context = MemoryContextSwitchTo(ind_context);
     893              : 
     894        12164 :     for (ind = 0; ind < nindexes; ind++)
     895              :     {
     896         8026 :         AnlIndexData *thisdata = &indexdata[ind];
     897         8026 :         IndexInfo  *indexInfo = thisdata->indexInfo;
     898         8026 :         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         8026 :         if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
     912         7930 :             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           96 :         estate = CreateExecutorState();
     920           96 :         econtext = GetPerTupleExprContext(estate);
     921              :         /* Need a slot to hold the current heap tuple, too */
     922           96 :         slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
     923              :                                         &TTSOpsHeapTuple);
     924              : 
     925              :         /* Arrange for econtext's scan tuple to be the tuple under test */
     926           96 :         econtext->ecxt_scantuple = slot;
     927              : 
     928              :         /* Set up execution state for predicate. */
     929           96 :         predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
     930              : 
     931              :         /* Compute and save index expression values */
     932           96 :         exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
     933           96 :         exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
     934           96 :         numindexrows = 0;
     935           96 :         tcnt = 0;
     936       111173 :         for (rowno = 0; rowno < numrows; rowno++)
     937              :         {
     938       111081 :             HeapTuple   heapTuple = rows[rowno];
     939              : 
     940       111081 :             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       111081 :             ResetExprContext(econtext);
     947              : 
     948              :             /* Set up for predicate or expression evaluation */
     949       111081 :             ExecStoreHeapTuple(heapTuple, slot, false);
     950              : 
     951              :             /* If index is partial, check predicate */
     952       111081 :             if (predicate != NULL)
     953              :             {
     954        37036 :                 if (!ExecQual(predicate, econtext))
     955        23552 :                     continue;
     956              :             }
     957        87529 :             numindexrows++;
     958              : 
     959        87529 :             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        74045 :                 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       148082 :                 for (i = 0; i < attr_cnt; i++)
     976              :                 {
     977        74041 :                     VacAttrStats *stats = thisdata->vacattrstats[i];
     978        74041 :                     int         attnum = stats->tupattnum;
     979              : 
     980        74041 :                     if (isnull[attnum - 1])
     981              :                     {
     982            8 :                         exprvals[tcnt] = (Datum) 0;
     983            8 :                         exprnulls[tcnt] = true;
     984              :                     }
     985              :                     else
     986              :                     {
     987       148066 :                         exprvals[tcnt] = datumCopy(values[attnum - 1],
     988        74033 :                                                    stats->attrtype->typbyval,
     989        74033 :                                                    stats->attrtype->typlen);
     990        74033 :                         exprnulls[tcnt] = false;
     991              :                     }
     992        74041 :                     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           92 :         thisdata->tupleFract = (double) numindexrows / (double) numrows;
    1002           92 :         totalindexrows = ceil(thisdata->tupleFract * totalrows);
    1003              : 
    1004              :         /*
    1005              :          * Now we can compute the statistics for the expression columns.
    1006              :          */
    1007           92 :         if (numindexrows > 0)
    1008              :         {
    1009           87 :             MemoryContextSwitchTo(col_context);
    1010          148 :             for (i = 0; i < attr_cnt; i++)
    1011              :             {
    1012           61 :                 VacAttrStats *stats = thisdata->vacattrstats[i];
    1013              : 
    1014           61 :                 stats->exprvals = exprvals + i;
    1015           61 :                 stats->exprnulls = exprnulls + i;
    1016           61 :                 stats->rowstride = attr_cnt;
    1017           61 :                 stats->compute_stats(stats,
    1018              :                                      ind_fetch_func,
    1019              :                                      numindexrows,
    1020              :                                      totalindexrows);
    1021              : 
    1022           61 :                 MemoryContextReset(col_context);
    1023              :             }
    1024              :         }
    1025              : 
    1026              :         /* And clean up */
    1027           92 :         MemoryContextSwitchTo(ind_context);
    1028              : 
    1029           92 :         ExecDropSingleTupleTableSlot(slot);
    1030           92 :         FreeExecutorState(estate);
    1031           92 :         MemoryContextReset(ind_context);
    1032              :     }
    1033              : 
    1034         4138 :     MemoryContextSwitchTo(old_context);
    1035         4138 :     MemoryContextDelete(ind_context);
    1036         4138 : }
    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        71749 : examine_attribute(Relation onerel, int attnum, Node *index_expr)
    1083              : {
    1084        71749 :     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        71749 :     if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
    1095           77 :         return NULL;
    1096              : 
    1097              :     /*
    1098              :      * Create the VacAttrStats struct.
    1099              :      */
    1100        71672 :     stats = palloc0_object(VacAttrStats);
    1101        71672 :     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        71672 :     if (index_expr)
    1113              :     {
    1114           77 :         stats->attrtypid = exprType(index_expr);
    1115           77 :         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           77 :         if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
    1123            9 :             stats->attrcollid = onerel->rd_indcollation[attnum - 1];
    1124              :         else
    1125           68 :             stats->attrcollid = exprCollation(index_expr);
    1126              :     }
    1127              :     else
    1128              :     {
    1129        71595 :         stats->attrtypid = attr->atttypid;
    1130        71595 :         stats->attrtypmod = attr->atttypmod;
    1131        71595 :         stats->attrcollid = attr->attcollation;
    1132              :     }
    1133              : 
    1134        71672 :     typtuple = SearchSysCacheCopy1(TYPEOID,
    1135              :                                    ObjectIdGetDatum(stats->attrtypid));
    1136        71672 :     if (!HeapTupleIsValid(typtuple))
    1137            0 :         elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
    1138        71672 :     stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
    1139        71672 :     stats->anl_context = anl_context;
    1140        71672 :     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       430032 :     for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
    1148              :     {
    1149       358360 :         stats->statypid[i] = stats->attrtypid;
    1150       358360 :         stats->statyplen[i] = stats->attrtype->typlen;
    1151       358360 :         stats->statypbyval[i] = stats->attrtype->typbyval;
    1152       358360 :         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        71672 :     if (OidIsValid(stats->attrtype->typanalyze))
    1160         4963 :         ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
    1161              :                                            PointerGetDatum(stats)));
    1162              :     else
    1163        66709 :         ok = std_typanalyze(stats);
    1164              : 
    1165        71672 :     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        71670 :     return stats;
    1173              : }
    1174              : 
    1175              : bool
    1176        71764 : 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        71764 :     if (attr->attisdropped)
    1186            3 :         return false;
    1187              : 
    1188              :     /* Don't analyze virtual generated columns */
    1189        71761 :     if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    1190           67 :         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        71694 :     atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
    1198        71694 :     if (!HeapTupleIsValid(atttuple))
    1199            0 :         elog(ERROR, "cache lookup failed for attribute %d of relation %u",
    1200              :              attnum, RelationGetRelid(onerel));
    1201        71694 :     dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
    1202        71694 :     attstattarget = isnull ? -1 : DatumGetInt16(dat);
    1203        71694 :     ReleaseSysCache(atttuple);
    1204              : 
    1205              :     /* Don't analyze column if user has specified not to */
    1206        71694 :     if (attstattarget == 0)
    1207            7 :         return false;
    1208              : 
    1209        71687 :     if (p_attstattarget)
    1210        71672 :         *p_attstattarget = attstattarget;
    1211        71687 :     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        91940 : block_sampling_read_stream_next(ReadStream *stream,
    1220              :                                 void *callback_private_data,
    1221              :                                 void *per_buffer_data)
    1222              : {
    1223        91940 :     BlockSamplerData *bs = callback_private_data;
    1224              : 
    1225        91940 :     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        10985 : acquire_sample_rows(Relation onerel, int elevel,
    1263              :                     HeapTuple *rows, int targrows,
    1264              :                     double *totalrows, double *totaldeadrows)
    1265              : {
    1266        10985 :     int         numrows = 0;    /* # rows now in reservoir */
    1267        10985 :     double      samplerows = 0; /* total # rows collected */
    1268        10985 :     double      liverows = 0;   /* # live rows seen */
    1269        10985 :     double      deadrows = 0;   /* # dead rows seen */
    1270        10985 :     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        10985 :     BlockNumber blksdone = 0;
    1279              :     ReadStream *stream;
    1280              : 
    1281              :     Assert(targrows > 0);
    1282              : 
    1283        10985 :     totalblocks = RelationGetNumberOfBlocks(onerel);
    1284              : 
    1285              :     /* Prepare for sampling block numbers */
    1286        10985 :     randseed = pg_prng_uint32(&pg_global_prng_state);
    1287        10985 :     nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
    1288              : 
    1289              :     /* Report sampling block numbers */
    1290        10985 :     pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_TOTAL,
    1291              :                                  nblocks);
    1292              : 
    1293              :     /* Prepare for sampling rows */
    1294        10985 :     reservoir_init_selection_state(&rstate, targrows);
    1295              : 
    1296        10985 :     scan = table_beginscan_analyze(onerel);
    1297        10985 :     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        10985 :     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        91940 :     while (table_scan_analyze_next_block(scan, stream))
    1314              :     {
    1315        80955 :         vacuum_delay_point(true);
    1316              : 
    1317      7219901 :         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      7138946 :             if (numrows < targrows)
    1332      6588967 :                 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       275958 :                     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       275929 :                     int         k = (int) (targrows * sampler_random_fract(&rstate.randstate));
    1350              : 
    1351              :                     Assert(k >= 0 && k < targrows);
    1352       275929 :                     heap_freetuple(rows[k]);
    1353       275929 :                     rows[k] = ExecCopySlotHeapTuple(slot);
    1354              :                 }
    1355              : 
    1356       549979 :                 rowstoskip -= 1;
    1357              :             }
    1358              : 
    1359      7138946 :             samplerows += 1;
    1360              :         }
    1361              : 
    1362        80955 :         pgstat_progress_update_param(PROGRESS_ANALYZE_BLOCKS_DONE,
    1363              :                                      ++blksdone);
    1364              :     }
    1365              : 
    1366        10985 :     read_stream_end(stream);
    1367              : 
    1368        10985 :     ExecDropSingleTupleTableSlot(slot);
    1369        10985 :     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        10985 :     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        10985 :     if (bs.m > 0)
    1391              :     {
    1392         7594 :         *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
    1393         7594 :         *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
    1394              :     }
    1395              :     else
    1396              :     {
    1397         3391 :         *totalrows = 0.0;
    1398         3391 :         *totaldeadrows = 0.0;
    1399              :     }
    1400              : 
    1401              :     /*
    1402              :      * Emit some interesting relation info
    1403              :      */
    1404        10985 :     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        10985 :     return numrows;
    1414              : }
    1415              : 
    1416              : /*
    1417              :  * Comparator for sorting rows[] array
    1418              :  */
    1419              : static int
    1420      5128352 : compare_rows(const void *a, const void *b, void *arg)
    1421              : {
    1422      5128352 :     HeapTuple   ha = *(const HeapTuple *) a;
    1423      5128352 :     HeapTuple   hb = *(const HeapTuple *) b;
    1424      5128352 :     BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
    1425      5128352 :     OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
    1426      5128352 :     BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
    1427      5128352 :     OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
    1428              : 
    1429      5128352 :     if (ba < bb)
    1430      1365669 :         return -1;
    1431      3762683 :     if (ba > bb)
    1432      1351591 :         return 1;
    1433      2411092 :     if (oa < ob)
    1434      1408819 :         return -1;
    1435      1002273 :     if (oa > ob)
    1436      1002273 :         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          589 : 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          589 :     *totalrows = 0;
    1467          589 :     *totaldeadrows = 0;
    1468              : 
    1469              :     /*
    1470              :      * Find all members of inheritance set.  We only need AccessShareLock on
    1471              :      * the children.
    1472              :      */
    1473              :     tableOIDs =
    1474          589 :         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          589 :     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          576 :     rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
    1500              :     acquirefuncs = (AcquireSampleRowsFunc *)
    1501          576 :         palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
    1502          576 :     relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
    1503          576 :     totalblocks = 0;
    1504          576 :     nrels = 0;
    1505          576 :     has_child = false;
    1506         2630 :     foreach(lc, tableOIDs)
    1507              :     {
    1508         2054 :         Oid         childOID = lfirst_oid(lc);
    1509              :         Relation    childrel;
    1510         2054 :         AcquireSampleRowsFunc acquirefunc = NULL;
    1511         2054 :         BlockNumber relpages = 0;
    1512              : 
    1513              :         /* We already got the needed lock */
    1514         2054 :         childrel = table_open(childOID, NoLock);
    1515              : 
    1516              :         /* Ignore if temp table of another backend */
    1517         2054 :         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          546 :             continue;
    1523              :         }
    1524              : 
    1525              :         /* Check table type (MATVIEW can't happen, but might as well allow) */
    1526         2054 :         if (childrel->rd_rel->relkind == RELKIND_RELATION ||
    1527          561 :             childrel->rd_rel->relkind == RELKIND_MATVIEW)
    1528              :         {
    1529              :             /* Regular table, so use the regular row acquisition function */
    1530         1493 :             acquirefunc = acquire_sample_rows;
    1531         1493 :             relpages = RelationGetNumberOfBlocks(childrel);
    1532              :         }
    1533          561 :         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          546 :             if (childrel != onerel)
    1565           52 :                 table_close(childrel, AccessShareLock);
    1566              :             else
    1567          494 :                 table_close(childrel, NoLock);
    1568          546 :             continue;
    1569              :         }
    1570              : 
    1571              :         /* OK, we'll process this child */
    1572         1508 :         has_child = true;
    1573         1508 :         rels[nrels] = childrel;
    1574         1508 :         acquirefuncs[nrels] = acquirefunc;
    1575         1508 :         relblocks[nrels] = (double) relpages;
    1576         1508 :         totalblocks += (double) relpages;
    1577         1508 :         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          576 :     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          576 :     pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_TOTAL,
    1600              :                                  nrels);
    1601          576 :     numrows = 0;
    1602         2084 :     for (i = 0; i < nrels; i++)
    1603              :     {
    1604         1508 :         Relation    childrel = rels[i];
    1605         1508 :         AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
    1606         1508 :         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         1508 :             const int   progress_index[] = {
    1615              :                 PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID,
    1616              :                 PROGRESS_ANALYZE_BLOCKS_DONE,
    1617              :                 PROGRESS_ANALYZE_BLOCKS_TOTAL
    1618              :             };
    1619         1508 :             const int64 progress_vals[] = {
    1620         1508 :                 RelationGetRelid(childrel),
    1621              :                 0,
    1622              :                 0,
    1623              :             };
    1624              : 
    1625         1508 :             pgstat_progress_update_multi_param(3, progress_index, progress_vals);
    1626              :         }
    1627              : 
    1628         1508 :         if (childblocks > 0)
    1629              :         {
    1630              :             int         childtargrows;
    1631              : 
    1632         1406 :             childtargrows = (int) rint(targrows * childblocks / totalblocks);
    1633              :             /* Make sure we don't overrun due to roundoff error */
    1634         1406 :             childtargrows = Min(childtargrows, targrows - numrows);
    1635         1406 :             if (childtargrows > 0)
    1636              :             {
    1637              :                 int         childrows;
    1638              :                 double      trows,
    1639              :                             tdrows;
    1640              : 
    1641              :                 /* Fetch a random sample of the child's rows */
    1642         1406 :                 childrows = (*acquirefunc) (childrel, elevel,
    1643         1406 :                                             rows + numrows, childtargrows,
    1644              :                                             &trows, &tdrows);
    1645              : 
    1646              :                 /* We may need to convert from child's rowtype to parent's */
    1647         1406 :                 if (childrows > 0 &&
    1648         1406 :                     !equalRowTypes(RelationGetDescr(childrel),
    1649              :                                    RelationGetDescr(onerel)))
    1650              :                 {
    1651              :                     TupleConversionMap *map;
    1652              : 
    1653         1340 :                     map = convert_tuples_by_name(RelationGetDescr(childrel),
    1654              :                                                  RelationGetDescr(onerel));
    1655         1340 :                     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         1406 :                 numrows += childrows;
    1673         1406 :                 *totalrows += trows;
    1674         1406 :                 *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         1508 :         table_close(childrel, NoLock);
    1683         1508 :         pgstat_progress_update_param(PROGRESS_ANALYZE_CHILD_TABLES_DONE,
    1684         1508 :                                      i + 1);
    1685              :     }
    1686              : 
    1687          576 :     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        14788 : update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
    1715              : {
    1716              :     Relation    sd;
    1717              :     int         attno;
    1718        14788 :     CatalogIndexState indstate = NULL;
    1719              : 
    1720        14788 :     if (natts <= 0)
    1721         7966 :         return;                 /* nothing to do */
    1722              : 
    1723         6822 :     sd = table_open(StatisticRelationId, RowExclusiveLock);
    1724              : 
    1725        57564 :     for (attno = 0; attno < natts; attno++)
    1726              :     {
    1727        50742 :         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        50742 :         if (!stats->stats_valid)
    1739            6 :             continue;
    1740              : 
    1741              :         /*
    1742              :          * Construct a new pg_statistic tuple
    1743              :          */
    1744      1623552 :         for (i = 0; i < Natts_pg_statistic; ++i)
    1745              :         {
    1746      1572816 :             nulls[i] = false;
    1747      1572816 :             replaces[i] = true;
    1748              :         }
    1749              : 
    1750        50736 :         values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
    1751        50736 :         values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
    1752        50736 :         values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
    1753        50736 :         values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
    1754        50736 :         values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
    1755        50736 :         values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
    1756        50736 :         i = Anum_pg_statistic_stakind1 - 1;
    1757       304416 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1758              :         {
    1759       253680 :             values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
    1760              :         }
    1761        50736 :         i = Anum_pg_statistic_staop1 - 1;
    1762       304416 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1763              :         {
    1764       253680 :             values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
    1765              :         }
    1766        50736 :         i = Anum_pg_statistic_stacoll1 - 1;
    1767       304416 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1768              :         {
    1769       253680 :             values[i++] = ObjectIdGetDatum(stats->stacoll[k]);   /* stacollN */
    1770              :         }
    1771        50736 :         i = Anum_pg_statistic_stanumbers1 - 1;
    1772       304416 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1773              :         {
    1774       253680 :             if (stats->stanumbers[k] != NULL)
    1775              :             {
    1776        78792 :                 int         nnum = stats->numnumbers[k];
    1777        78792 :                 Datum      *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
    1778              :                 ArrayType  *arry;
    1779              : 
    1780       657563 :                 for (n = 0; n < nnum; n++)
    1781       578771 :                     numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
    1782        78792 :                 arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
    1783        78792 :                 values[i++] = PointerGetDatum(arry);    /* stanumbersN */
    1784              :             }
    1785              :             else
    1786              :             {
    1787       174888 :                 nulls[i] = true;
    1788       174888 :                 values[i++] = (Datum) 0;
    1789              :             }
    1790              :         }
    1791        50736 :         i = Anum_pg_statistic_stavalues1 - 1;
    1792       304416 :         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
    1793              :         {
    1794       253680 :             if (stats->stavalues[k] != NULL)
    1795              :             {
    1796              :                 ArrayType  *arry;
    1797              : 
    1798        55605 :                 arry = construct_array(stats->stavalues[k],
    1799              :                                        stats->numvalues[k],
    1800              :                                        stats->statypid[k],
    1801        55605 :                                        stats->statyplen[k],
    1802        55605 :                                        stats->statypbyval[k],
    1803        55605 :                                        stats->statypalign[k]);
    1804        55605 :                 values[i++] = PointerGetDatum(arry);    /* stavaluesN */
    1805              :             }
    1806              :             else
    1807              :             {
    1808       198075 :                 nulls[i] = true;
    1809       198075 :                 values[i++] = (Datum) 0;
    1810              :             }
    1811              :         }
    1812              : 
    1813              :         /* Is there already a pg_statistic tuple for this attribute? */
    1814       101472 :         oldtup = SearchSysCache3(STATRELATTINH,
    1815              :                                  ObjectIdGetDatum(relid),
    1816        50736 :                                  Int16GetDatum(stats->tupattnum),
    1817              :                                  BoolGetDatum(inh));
    1818              : 
    1819              :         /* Open index information when we know we need it */
    1820        50736 :         if (indstate == NULL)
    1821         6818 :             indstate = CatalogOpenIndexes(sd);
    1822              : 
    1823        50736 :         if (HeapTupleIsValid(oldtup))
    1824              :         {
    1825              :             /* Yes, replace it */
    1826        22261 :             stup = heap_modify_tuple(oldtup,
    1827              :                                      RelationGetDescr(sd),
    1828              :                                      values,
    1829              :                                      nulls,
    1830              :                                      replaces);
    1831        22261 :             ReleaseSysCache(oldtup);
    1832        22261 :             CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
    1833              :         }
    1834              :         else
    1835              :         {
    1836              :             /* No, insert new tuple */
    1837        28475 :             stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
    1838        28475 :             CatalogTupleInsertWithInfo(sd, stup, indstate);
    1839              :         }
    1840              : 
    1841        50736 :         heap_freetuple(stup);
    1842              :     }
    1843              : 
    1844         6822 :     if (indstate != NULL)
    1845         6818 :         CatalogCloseIndexes(indstate);
    1846         6822 :     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     50006284 : std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
    1857              : {
    1858     50006284 :     int         attnum = stats->tupattnum;
    1859     50006284 :     HeapTuple   tuple = stats->rows[rownum];
    1860     50006284 :     TupleDesc   tupDesc = stats->tupDesc;
    1861              : 
    1862     50006284 :     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        74041 : 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        74041 :     i = rownum * stats->rowstride;
    1878        74041 :     *isNull = stats->exprnulls[i];
    1879        74041 :     return stats->exprvals[i];
    1880              : }
    1881              : 
    1882              : 
    1883              : /*==========================================================================
    1884              :  *
    1885              :  * Code below this point represents the "standard" type-specific statistics
    1886              :  * analysis algorithms.  This code can be replaced on a per-data-type basis
    1887              :  * by setting a nonzero value in pg_type.typanalyze.
    1888              :  *
    1889              :  *==========================================================================
    1890              :  */
    1891              : 
    1892              : 
    1893              : /*
    1894              :  * To avoid consuming too much memory during analysis and/or too much space
    1895              :  * in the resulting pg_statistic rows, we ignore varlena datums that are wider
    1896              :  * than WIDTH_THRESHOLD (after detoasting!).  This is legitimate for MCV
    1897              :  * and distinct-value calculations since a wide value is unlikely to be
    1898              :  * duplicated at all, much less be a most-common value.  For the same reason,
    1899              :  * ignoring wide values will not affect our estimates of histogram bin
    1900              :  * boundaries very much.
    1901              :  */
    1902              : #define WIDTH_THRESHOLD  1024
    1903              : 
    1904              : #define swapInt(a,b)    do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
    1905              : #define swapDatum(a,b)  do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
    1906              : 
    1907              : /*
    1908              :  * Extra information used by the default analysis routines
    1909              :  */
    1910              : typedef struct
    1911              : {
    1912              :     int         count;          /* # of duplicates */
    1913              :     int         first;          /* values[] index of first occurrence */
    1914              : } ScalarMCVItem;
    1915              : 
    1916              : typedef struct
    1917              : {
    1918              :     SortSupport ssup;
    1919              :     int        *tupnoLink;
    1920              : } CompareScalarsContext;
    1921              : 
    1922              : 
    1923              : static void compute_trivial_stats(VacAttrStatsP stats,
    1924              :                                   AnalyzeAttrFetchFunc fetchfunc,
    1925              :                                   int samplerows,
    1926              :                                   double totalrows);
    1927              : static void compute_distinct_stats(VacAttrStatsP stats,
    1928              :                                    AnalyzeAttrFetchFunc fetchfunc,
    1929              :                                    int samplerows,
    1930              :                                    double totalrows);
    1931              : static void compute_scalar_stats(VacAttrStatsP stats,
    1932              :                                  AnalyzeAttrFetchFunc fetchfunc,
    1933              :                                  int samplerows,
    1934              :                                  double totalrows);
    1935              : static int  compare_scalars(const void *a, const void *b, void *arg);
    1936              : static int  compare_mcvs(const void *a, const void *b, void *arg);
    1937              : static int  analyze_mcv_list(int *mcv_counts,
    1938              :                              int num_mcv,
    1939              :                              double stadistinct,
    1940              :                              double stanullfrac,
    1941              :                              int samplerows,
    1942              :                              double totalrows);
    1943              : 
    1944              : 
    1945              : /*
    1946              :  * std_typanalyze -- the default type-specific typanalyze function
    1947              :  */
    1948              : bool
    1949        72848 : std_typanalyze(VacAttrStats *stats)
    1950              : {
    1951              :     Oid         ltopr;
    1952              :     Oid         eqopr;
    1953              :     StdAnalyzeData *mystats;
    1954              : 
    1955              :     /* If the attstattarget column is negative, use the default value */
    1956        72848 :     if (stats->attstattarget < 0)
    1957        72232 :         stats->attstattarget = default_statistics_target;
    1958              : 
    1959              :     /* Look for default "<" and "=" operators for column's type */
    1960        72848 :     get_sort_group_operators(stats->attrtypid,
    1961              :                              false, false, false,
    1962              :                              &ltopr, &eqopr, NULL,
    1963              :                              NULL);
    1964              : 
    1965              :     /* Save the operator info for compute_stats routines */
    1966        72848 :     mystats = palloc_object(StdAnalyzeData);
    1967        72848 :     mystats->eqopr = eqopr;
    1968        72848 :     mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
    1969        72848 :     mystats->ltopr = ltopr;
    1970        72848 :     stats->extra_data = mystats;
    1971              : 
    1972              :     /*
    1973              :      * Determine which standard statistics algorithm to use
    1974              :      */
    1975        72848 :     if (OidIsValid(eqopr) && OidIsValid(ltopr))
    1976              :     {
    1977              :         /* Seems to be a scalar datatype */
    1978        70771 :         stats->compute_stats = compute_scalar_stats;
    1979              :         /*--------------------
    1980              :          * The following choice of minrows is based on the paper
    1981              :          * "Random sampling for histogram construction: how much is enough?"
    1982              :          * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
    1983              :          * Proceedings of ACM SIGMOD International Conference on Management
    1984              :          * of Data, 1998, Pages 436-447.  Their Corollary 1 to Theorem 5
    1985              :          * says that for table size n, histogram size k, maximum relative
    1986              :          * error in bin size f, and error probability gamma, the minimum
    1987              :          * random sample size is
    1988              :          *      r = 4 * k * ln(2*n/gamma) / f^2
    1989              :          * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
    1990              :          *      r = 305.82 * k
    1991              :          * Note that because of the log function, the dependence on n is
    1992              :          * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
    1993              :          * bin size error with probability 0.99.  So there's no real need to
    1994              :          * scale for n, which is a good thing because we don't necessarily
    1995              :          * know it at this point.
    1996              :          *--------------------
    1997              :          */
    1998        70771 :         stats->minrows = 300 * stats->attstattarget;
    1999              :     }
    2000         2077 :     else if (OidIsValid(eqopr))
    2001              :     {
    2002              :         /* We can still recognize distinct values */
    2003         1784 :         stats->compute_stats = compute_distinct_stats;
    2004              :         /* Might as well use the same minrows as above */
    2005         1784 :         stats->minrows = 300 * stats->attstattarget;
    2006              :     }
    2007              :     else
    2008              :     {
    2009              :         /* Can't do much but the trivial stuff */
    2010          293 :         stats->compute_stats = compute_trivial_stats;
    2011              :         /* Might as well use the same minrows as above */
    2012          293 :         stats->minrows = 300 * stats->attstattarget;
    2013              :     }
    2014              : 
    2015        72848 :     return true;
    2016              : }
    2017              : 
    2018              : 
    2019              : /*
    2020              :  *  compute_trivial_stats() -- compute very basic column statistics
    2021              :  *
    2022              :  *  We use this when we cannot find a hash "=" operator for the datatype.
    2023              :  *
    2024              :  *  We determine the fraction of non-null rows and the average datum width.
    2025              :  */
    2026              : static void
    2027          200 : compute_trivial_stats(VacAttrStatsP stats,
    2028              :                       AnalyzeAttrFetchFunc fetchfunc,
    2029              :                       int samplerows,
    2030              :                       double totalrows)
    2031              : {
    2032              :     int         i;
    2033          200 :     int         null_cnt = 0;
    2034          200 :     int         nonnull_cnt = 0;
    2035          200 :     double      total_width = 0;
    2036          400 :     bool        is_varlena = (!stats->attrtype->typbyval &&
    2037          200 :                               stats->attrtype->typlen == -1);
    2038          400 :     bool        is_varwidth = (!stats->attrtype->typbyval &&
    2039          200 :                                stats->attrtype->typlen < 0);
    2040              : 
    2041       636051 :     for (i = 0; i < samplerows; i++)
    2042              :     {
    2043              :         Datum       value;
    2044              :         bool        isnull;
    2045              : 
    2046       635851 :         vacuum_delay_point(true);
    2047              : 
    2048       635851 :         value = fetchfunc(stats, i, &isnull);
    2049              : 
    2050              :         /* Check for null/nonnull */
    2051       635851 :         if (isnull)
    2052              :         {
    2053       393123 :             null_cnt++;
    2054       393123 :             continue;
    2055              :         }
    2056       242728 :         nonnull_cnt++;
    2057              : 
    2058              :         /*
    2059              :          * If it's a variable-width field, add up widths for average width
    2060              :          * calculation.  Note that if the value is toasted, we use the toasted
    2061              :          * width.  We don't bother with this calculation if it's a fixed-width
    2062              :          * type.
    2063              :          */
    2064       242728 :         if (is_varlena)
    2065              :         {
    2066        45668 :             total_width += VARSIZE_ANY(DatumGetPointer(value));
    2067              :         }
    2068       197060 :         else if (is_varwidth)
    2069              :         {
    2070              :             /* must be cstring */
    2071            0 :             total_width += strlen(DatumGetCString(value)) + 1;
    2072              :         }
    2073              :     }
    2074              : 
    2075              :     /* We can only compute average width if we found some non-null values. */
    2076          200 :     if (nonnull_cnt > 0)
    2077              :     {
    2078           95 :         stats->stats_valid = true;
    2079              :         /* Do the simple null-frac and width stats */
    2080           95 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2081           95 :         if (is_varwidth)
    2082           46 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2083              :         else
    2084           49 :             stats->stawidth = stats->attrtype->typlen;
    2085           95 :         stats->stadistinct = 0.0;    /* "unknown" */
    2086              :     }
    2087          105 :     else if (null_cnt > 0)
    2088              :     {
    2089              :         /* We found only nulls; assume the column is entirely null */
    2090          105 :         stats->stats_valid = true;
    2091          105 :         stats->stanullfrac = 1.0;
    2092          105 :         if (is_varwidth)
    2093          105 :             stats->stawidth = 0; /* "unknown" */
    2094              :         else
    2095            0 :             stats->stawidth = stats->attrtype->typlen;
    2096          105 :         stats->stadistinct = 0.0;    /* "unknown" */
    2097              :     }
    2098          200 : }
    2099              : 
    2100              : 
    2101              : /*
    2102              :  *  compute_distinct_stats() -- compute column statistics including ndistinct
    2103              :  *
    2104              :  *  We use this when we can find only an "=" operator for the datatype.
    2105              :  *
    2106              :  *  We determine the fraction of non-null rows, the average width, the
    2107              :  *  most common values, and the (estimated) number of distinct values.
    2108              :  *
    2109              :  *  The most common values are determined by brute force: we keep a list
    2110              :  *  of previously seen values, ordered by number of times seen, as we scan
    2111              :  *  the samples.  A newly seen value is inserted just after the last
    2112              :  *  multiply-seen value, causing the bottommost (oldest) singly-seen value
    2113              :  *  to drop off the list.  The accuracy of this method, and also its cost,
    2114              :  *  depend mainly on the length of the list we are willing to keep.
    2115              :  */
    2116              : static void
    2117         1302 : compute_distinct_stats(VacAttrStatsP stats,
    2118              :                        AnalyzeAttrFetchFunc fetchfunc,
    2119              :                        int samplerows,
    2120              :                        double totalrows)
    2121              : {
    2122              :     int         i;
    2123         1302 :     int         null_cnt = 0;
    2124         1302 :     int         nonnull_cnt = 0;
    2125         1302 :     int         toowide_cnt = 0;
    2126         1302 :     double      total_width = 0;
    2127         2198 :     bool        is_varlena = (!stats->attrtype->typbyval &&
    2128          896 :                               stats->attrtype->typlen == -1);
    2129         2198 :     bool        is_varwidth = (!stats->attrtype->typbyval &&
    2130          896 :                                stats->attrtype->typlen < 0);
    2131              :     FmgrInfo    f_cmpeq;
    2132              :     typedef struct
    2133              :     {
    2134              :         Datum       value;
    2135              :         int         count;
    2136              :     } TrackItem;
    2137              :     TrackItem  *track;
    2138              :     int         track_cnt,
    2139              :                 track_max;
    2140         1302 :     int         num_mcv = stats->attstattarget;
    2141         1302 :     StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
    2142              : 
    2143              :     /*
    2144              :      * We track up to 2*n values for an n-element MCV list; but at least 10
    2145              :      */
    2146         1302 :     track_max = 2 * num_mcv;
    2147         1302 :     if (track_max < 10)
    2148           39 :         track_max = 10;
    2149         1302 :     track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
    2150         1302 :     track_cnt = 0;
    2151              : 
    2152         1302 :     fmgr_info(mystats->eqfunc, &f_cmpeq);
    2153              : 
    2154       968771 :     for (i = 0; i < samplerows; i++)
    2155              :     {
    2156              :         Datum       value;
    2157              :         bool        isnull;
    2158              :         bool        match;
    2159              :         int         firstcount1,
    2160              :                     j;
    2161              : 
    2162       967469 :         vacuum_delay_point(true);
    2163              : 
    2164       967469 :         value = fetchfunc(stats, i, &isnull);
    2165              : 
    2166              :         /* Check for null/nonnull */
    2167       967469 :         if (isnull)
    2168              :         {
    2169       802736 :             null_cnt++;
    2170       802736 :             continue;
    2171              :         }
    2172       164733 :         nonnull_cnt++;
    2173              : 
    2174              :         /*
    2175              :          * If it's a variable-width field, add up widths for average width
    2176              :          * calculation.  Note that if the value is toasted, we use the toasted
    2177              :          * width.  We don't bother with this calculation if it's a fixed-width
    2178              :          * type.
    2179              :          */
    2180       164733 :         if (is_varlena)
    2181              :         {
    2182        58689 :             total_width += VARSIZE_ANY(DatumGetPointer(value));
    2183              : 
    2184              :             /*
    2185              :              * If the value is toasted, we want to detoast it just once to
    2186              :              * avoid repeated detoastings and resultant excess memory usage
    2187              :              * during the comparisons.  Also, check to see if the value is
    2188              :              * excessively wide, and if so don't detoast at all --- just
    2189              :              * ignore the value.
    2190              :              */
    2191        58689 :             if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
    2192              :             {
    2193            0 :                 toowide_cnt++;
    2194            0 :                 continue;
    2195              :             }
    2196        58689 :             value = PointerGetDatum(PG_DETOAST_DATUM(value));
    2197              :         }
    2198       106044 :         else if (is_varwidth)
    2199              :         {
    2200              :             /* must be cstring */
    2201            0 :             total_width += strlen(DatumGetCString(value)) + 1;
    2202              :         }
    2203              : 
    2204              :         /*
    2205              :          * See if the value matches anything we're already tracking.
    2206              :          */
    2207       164733 :         match = false;
    2208       164733 :         firstcount1 = track_cnt;
    2209       402529 :         for (j = 0; j < track_cnt; j++)
    2210              :         {
    2211       398277 :             if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
    2212              :                                                stats->attrcollid,
    2213       398277 :                                                value, track[j].value)))
    2214              :             {
    2215       160481 :                 match = true;
    2216       160481 :                 break;
    2217              :             }
    2218       237796 :             if (j < firstcount1 && track[j].count == 1)
    2219         2819 :                 firstcount1 = j;
    2220              :         }
    2221              : 
    2222       164733 :         if (match)
    2223              :         {
    2224              :             /* Found a match */
    2225       160481 :             track[j].count++;
    2226              :             /* This value may now need to "bubble up" in the track list */
    2227       167694 :             while (j > 0 && track[j].count > track[j - 1].count)
    2228              :             {
    2229         7213 :                 swapDatum(track[j].value, track[j - 1].value);
    2230         7213 :                 swapInt(track[j].count, track[j - 1].count);
    2231         7213 :                 j--;
    2232              :             }
    2233              :         }
    2234              :         else
    2235              :         {
    2236              :             /* No match.  Insert at head of count-1 list */
    2237         4252 :             if (track_cnt < track_max)
    2238         3869 :                 track_cnt++;
    2239        84303 :             for (j = track_cnt - 1; j > firstcount1; j--)
    2240              :             {
    2241        80051 :                 track[j].value = track[j - 1].value;
    2242        80051 :                 track[j].count = track[j - 1].count;
    2243              :             }
    2244         4252 :             if (firstcount1 < track_cnt)
    2245              :             {
    2246         4252 :                 track[firstcount1].value = value;
    2247         4252 :                 track[firstcount1].count = 1;
    2248              :             }
    2249              :         }
    2250              :     }
    2251              : 
    2252              :     /* We can only compute real stats if we found some non-null values. */
    2253         1302 :     if (nonnull_cnt > 0)
    2254              :     {
    2255              :         int         nmultiple,
    2256              :                     summultiple;
    2257              : 
    2258          952 :         stats->stats_valid = true;
    2259              :         /* Do the simple null-frac and width stats */
    2260          952 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2261          952 :         if (is_varwidth)
    2262          546 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2263              :         else
    2264          406 :             stats->stawidth = stats->attrtype->typlen;
    2265              : 
    2266              :         /* Count the number of values we found multiple times */
    2267          952 :         summultiple = 0;
    2268         3743 :         for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
    2269              :         {
    2270         3277 :             if (track[nmultiple].count == 1)
    2271          486 :                 break;
    2272         2791 :             summultiple += track[nmultiple].count;
    2273              :         }
    2274              : 
    2275          952 :         if (nmultiple == 0)
    2276              :         {
    2277              :             /*
    2278              :              * If we found no repeated non-null values, assume it's a unique
    2279              :              * column; but be sure to discount for any nulls we found.
    2280              :              */
    2281          112 :             stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
    2282              :         }
    2283          840 :         else if (track_cnt < track_max && toowide_cnt == 0 &&
    2284              :                  nmultiple == track_cnt)
    2285              :         {
    2286              :             /*
    2287              :              * Our track list includes every value in the sample, and every
    2288              :              * value appeared more than once.  Assume the column has just
    2289              :              * these values.  (This case is meant to address columns with
    2290              :              * small, fixed sets of possible values, such as boolean or enum
    2291              :              * columns.  If there are any values that appear just once in the
    2292              :              * sample, including too-wide values, we should assume that that's
    2293              :              * not what we're dealing with.)
    2294              :              */
    2295          466 :             stats->stadistinct = track_cnt;
    2296              :         }
    2297              :         else
    2298              :         {
    2299              :             /*----------
    2300              :              * Estimate the number of distinct values using the estimator
    2301              :              * proposed by Haas and Stokes in IBM Research Report RJ 10025:
    2302              :              *      n*d / (n - f1 + f1*n/N)
    2303              :              * where f1 is the number of distinct values that occurred
    2304              :              * exactly once in our sample of n rows (from a total of N),
    2305              :              * and d is the total number of distinct values in the sample.
    2306              :              * This is their Duj1 estimator; the other estimators they
    2307              :              * recommend are considerably more complex, and are numerically
    2308              :              * very unstable when n is much smaller than N.
    2309              :              *
    2310              :              * In this calculation, we consider only non-nulls.  We used to
    2311              :              * include rows with null values in the n and N counts, but that
    2312              :              * leads to inaccurate answers in columns with many nulls, and
    2313              :              * it's intuitively bogus anyway considering the desired result is
    2314              :              * the number of distinct non-null values.
    2315              :              *
    2316              :              * We assume (not very reliably!) that all the multiply-occurring
    2317              :              * values are reflected in the final track[] list, and the other
    2318              :              * nonnull values all appeared but once.  (XXX this usually
    2319              :              * results in a drastic overestimate of ndistinct.  Can we do
    2320              :              * any better?)
    2321              :              *----------
    2322              :              */
    2323          374 :             int         f1 = nonnull_cnt - summultiple;
    2324          374 :             int         d = f1 + nmultiple;
    2325          374 :             double      n = samplerows - null_cnt;
    2326          374 :             double      N = totalrows * (1.0 - stats->stanullfrac);
    2327              :             double      stadistinct;
    2328              : 
    2329              :             /* N == 0 shouldn't happen, but just in case ... */
    2330          374 :             if (N > 0)
    2331          374 :                 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
    2332              :             else
    2333            0 :                 stadistinct = 0;
    2334              : 
    2335              :             /* Clamp to sane range in case of roundoff error */
    2336          374 :             if (stadistinct < d)
    2337            3 :                 stadistinct = d;
    2338          374 :             if (stadistinct > N)
    2339            0 :                 stadistinct = N;
    2340              :             /* And round to integer */
    2341          374 :             stats->stadistinct = floor(stadistinct + 0.5);
    2342              :         }
    2343              : 
    2344              :         /*
    2345              :          * If we estimated the number of distinct values at more than 10% of
    2346              :          * the total row count (a very arbitrary limit), then assume that
    2347              :          * stadistinct should scale with the row count rather than be a fixed
    2348              :          * value.
    2349              :          */
    2350          952 :         if (stats->stadistinct > 0.1 * totalrows)
    2351          213 :             stats->stadistinct = -(stats->stadistinct / totalrows);
    2352              : 
    2353              :         /*
    2354              :          * Decide how many values are worth storing as most-common values. If
    2355              :          * we are able to generate a complete MCV list (all the values in the
    2356              :          * sample will fit, and we think these are all the ones in the table),
    2357              :          * then do so.  Otherwise, store only those values that are
    2358              :          * significantly more common than the values not in the list.
    2359              :          *
    2360              :          * Note: the first of these cases is meant to address columns with
    2361              :          * small, fixed sets of possible values, such as boolean or enum
    2362              :          * columns.  If we can *completely* represent the column population by
    2363              :          * an MCV list that will fit into the stats target, then we should do
    2364              :          * so and thus provide the planner with complete information.  But if
    2365              :          * the MCV list is not complete, it's generally worth being more
    2366              :          * selective, and not just filling it all the way up to the stats
    2367              :          * target.
    2368              :          */
    2369          952 :         if (track_cnt < track_max && toowide_cnt == 0 &&
    2370          947 :             stats->stadistinct > 0 &&
    2371              :             track_cnt <= num_mcv)
    2372              :         {
    2373              :             /* Track list includes all values seen, and all will fit */
    2374          613 :             num_mcv = track_cnt;
    2375              :         }
    2376              :         else
    2377              :         {
    2378              :             int        *mcv_counts;
    2379              : 
    2380              :             /* Incomplete list; decide how many values are worth keeping */
    2381          339 :             if (num_mcv > track_cnt)
    2382          309 :                 num_mcv = track_cnt;
    2383              : 
    2384          339 :             if (num_mcv > 0)
    2385              :             {
    2386          339 :                 mcv_counts = (int *) palloc(num_mcv * sizeof(int));
    2387         1081 :                 for (i = 0; i < num_mcv; i++)
    2388          742 :                     mcv_counts[i] = track[i].count;
    2389              : 
    2390          339 :                 num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
    2391          339 :                                            stats->stadistinct,
    2392          339 :                                            stats->stanullfrac,
    2393              :                                            samplerows, totalrows);
    2394              :             }
    2395              :         }
    2396              : 
    2397              :         /* Generate MCV slot entry */
    2398          952 :         if (num_mcv > 0)
    2399              :         {
    2400              :             MemoryContext old_context;
    2401              :             Datum      *mcv_values;
    2402              :             float4     *mcv_freqs;
    2403              : 
    2404              :             /* Must copy the target values into anl_context */
    2405          949 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2406          949 :             mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
    2407          949 :             mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
    2408         4484 :             for (i = 0; i < num_mcv; i++)
    2409              :             {
    2410         7070 :                 mcv_values[i] = datumCopy(track[i].value,
    2411         3535 :                                           stats->attrtype->typbyval,
    2412         3535 :                                           stats->attrtype->typlen);
    2413         3535 :                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
    2414              :             }
    2415          949 :             MemoryContextSwitchTo(old_context);
    2416              : 
    2417          949 :             stats->stakind[0] = STATISTIC_KIND_MCV;
    2418          949 :             stats->staop[0] = mystats->eqopr;
    2419          949 :             stats->stacoll[0] = stats->attrcollid;
    2420          949 :             stats->stanumbers[0] = mcv_freqs;
    2421          949 :             stats->numnumbers[0] = num_mcv;
    2422          949 :             stats->stavalues[0] = mcv_values;
    2423          949 :             stats->numvalues[0] = num_mcv;
    2424              : 
    2425              :             /*
    2426              :              * Accept the defaults for stats->statypid and others. They have
    2427              :              * been set before we were called (see vacuum.h)
    2428              :              */
    2429              :         }
    2430              :     }
    2431          350 :     else if (null_cnt > 0)
    2432              :     {
    2433              :         /* We found only nulls; assume the column is entirely null */
    2434          350 :         stats->stats_valid = true;
    2435          350 :         stats->stanullfrac = 1.0;
    2436          350 :         if (is_varwidth)
    2437          350 :             stats->stawidth = 0; /* "unknown" */
    2438              :         else
    2439            0 :             stats->stawidth = stats->attrtype->typlen;
    2440          350 :         stats->stadistinct = 0.0;    /* "unknown" */
    2441              :     }
    2442              : 
    2443              :     /* We don't need to bother cleaning up any of our temporary palloc's */
    2444         1302 : }
    2445              : 
    2446              : 
    2447              : /*
    2448              :  *  compute_scalar_stats() -- compute column statistics
    2449              :  *
    2450              :  *  We use this when we can find "=" and "<" operators for the datatype.
    2451              :  *
    2452              :  *  We determine the fraction of non-null rows, the average width, the
    2453              :  *  most common values, the (estimated) number of distinct values, the
    2454              :  *  distribution histogram, and the correlation of physical to logical order.
    2455              :  *
    2456              :  *  The desired stats can be determined fairly easily after sorting the
    2457              :  *  data values into order.
    2458              :  */
    2459              : static void
    2460        49500 : compute_scalar_stats(VacAttrStatsP stats,
    2461              :                      AnalyzeAttrFetchFunc fetchfunc,
    2462              :                      int samplerows,
    2463              :                      double totalrows)
    2464              : {
    2465              :     int         i;
    2466        49500 :     int         null_cnt = 0;
    2467        49500 :     int         nonnull_cnt = 0;
    2468        49500 :     int         toowide_cnt = 0;
    2469        49500 :     double      total_width = 0;
    2470        61569 :     bool        is_varlena = (!stats->attrtype->typbyval &&
    2471        12069 :                               stats->attrtype->typlen == -1);
    2472        61569 :     bool        is_varwidth = (!stats->attrtype->typbyval &&
    2473        12069 :                                stats->attrtype->typlen < 0);
    2474              :     double      corr_xysum;
    2475              :     SortSupportData ssup;
    2476              :     ScalarItem *values;
    2477        49500 :     int         values_cnt = 0;
    2478              :     int        *tupnoLink;
    2479              :     ScalarMCVItem *track;
    2480        49500 :     int         track_cnt = 0;
    2481        49500 :     int         num_mcv = stats->attstattarget;
    2482        49500 :     int         num_bins = stats->attstattarget;
    2483        49500 :     StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
    2484              : 
    2485        49500 :     values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
    2486        49500 :     tupnoLink = (int *) palloc(samplerows * sizeof(int));
    2487        49500 :     track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
    2488              : 
    2489        49500 :     memset(&ssup, 0, sizeof(ssup));
    2490        49500 :     ssup.ssup_cxt = CurrentMemoryContext;
    2491        49500 :     ssup.ssup_collation = stats->attrcollid;
    2492        49500 :     ssup.ssup_nulls_first = false;
    2493              : 
    2494              :     /*
    2495              :      * For now, don't perform abbreviated key conversion, because full values
    2496              :      * are required for MCV slot generation.  Supporting that optimization
    2497              :      * would necessitate teaching compare_scalars() to call a tie-breaker.
    2498              :      */
    2499        49500 :     ssup.abbreviate = false;
    2500              : 
    2501        49500 :     PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
    2502              : 
    2503              :     /* Initial scan to find sortable values */
    2504     45766988 :     for (i = 0; i < samplerows; i++)
    2505              :     {
    2506              :         Datum       value;
    2507              :         bool        isnull;
    2508              : 
    2509     45717488 :         vacuum_delay_point(true);
    2510              : 
    2511     45717488 :         value = fetchfunc(stats, i, &isnull);
    2512              : 
    2513              :         /* Check for null/nonnull */
    2514     45717488 :         if (isnull)
    2515              :         {
    2516      5941964 :             null_cnt++;
    2517      5964337 :             continue;
    2518              :         }
    2519     39775524 :         nonnull_cnt++;
    2520              : 
    2521              :         /*
    2522              :          * If it's a variable-width field, add up widths for average width
    2523              :          * calculation.  Note that if the value is toasted, we use the toasted
    2524              :          * width.  We don't bother with this calculation if it's a fixed-width
    2525              :          * type.
    2526              :          */
    2527     39775524 :         if (is_varlena)
    2528              :         {
    2529      4837530 :             total_width += VARSIZE_ANY(DatumGetPointer(value));
    2530              : 
    2531              :             /*
    2532              :              * If the value is toasted, we want to detoast it just once to
    2533              :              * avoid repeated detoastings and resultant excess memory usage
    2534              :              * during the comparisons.  Also, check to see if the value is
    2535              :              * excessively wide, and if so don't detoast at all --- just
    2536              :              * ignore the value.
    2537              :              */
    2538      4837530 :             if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
    2539              :             {
    2540        22373 :                 toowide_cnt++;
    2541        22373 :                 continue;
    2542              :             }
    2543      4815157 :             value = PointerGetDatum(PG_DETOAST_DATUM(value));
    2544              :         }
    2545     34937994 :         else if (is_varwidth)
    2546              :         {
    2547              :             /* must be cstring */
    2548            0 :             total_width += strlen(DatumGetCString(value)) + 1;
    2549              :         }
    2550              : 
    2551              :         /* Add it to the list to be sorted */
    2552     39753151 :         values[values_cnt].value = value;
    2553     39753151 :         values[values_cnt].tupno = values_cnt;
    2554     39753151 :         tupnoLink[values_cnt] = values_cnt;
    2555     39753151 :         values_cnt++;
    2556              :     }
    2557              : 
    2558              :     /* We can only compute real stats if we found some sortable values. */
    2559        49500 :     if (values_cnt > 0)
    2560              :     {
    2561              :         int         ndistinct,  /* # distinct values in sample */
    2562              :                     nmultiple,  /* # that appear multiple times */
    2563              :                     num_hist,
    2564              :                     dups_cnt;
    2565        46274 :         int         slot_idx = 0;
    2566              :         CompareScalarsContext cxt;
    2567              : 
    2568              :         /* Sort the collected values */
    2569        46274 :         cxt.ssup = &ssup;
    2570        46274 :         cxt.tupnoLink = tupnoLink;
    2571        46274 :         qsort_interruptible(values, values_cnt, sizeof(ScalarItem),
    2572              :                             compare_scalars, &cxt);
    2573              : 
    2574              :         /*
    2575              :          * Now scan the values in order, find the most common ones, and also
    2576              :          * accumulate ordering-correlation statistics.
    2577              :          *
    2578              :          * To determine which are most common, we first have to count the
    2579              :          * number of duplicates of each value.  The duplicates are adjacent in
    2580              :          * the sorted list, so a brute-force approach is to compare successive
    2581              :          * datum values until we find two that are not equal. However, that
    2582              :          * requires N-1 invocations of the datum comparison routine, which are
    2583              :          * completely redundant with work that was done during the sort.  (The
    2584              :          * sort algorithm must at some point have compared each pair of items
    2585              :          * that are adjacent in the sorted order; otherwise it could not know
    2586              :          * that it's ordered the pair correctly.) We exploit this by having
    2587              :          * compare_scalars remember the highest tupno index that each
    2588              :          * ScalarItem has been found equal to.  At the end of the sort, a
    2589              :          * ScalarItem's tupnoLink will still point to itself if and only if it
    2590              :          * is the last item of its group of duplicates (since the group will
    2591              :          * be ordered by tupno).
    2592              :          */
    2593        46274 :         corr_xysum = 0;
    2594        46274 :         ndistinct = 0;
    2595        46274 :         nmultiple = 0;
    2596        46274 :         dups_cnt = 0;
    2597     39799425 :         for (i = 0; i < values_cnt; i++)
    2598              :         {
    2599     39753151 :             int         tupno = values[i].tupno;
    2600              : 
    2601     39753151 :             corr_xysum += ((double) i) * ((double) tupno);
    2602     39753151 :             dups_cnt++;
    2603     39753151 :             if (tupnoLink[tupno] == tupno)
    2604              :             {
    2605              :                 /* Reached end of duplicates of this value */
    2606      8015846 :                 ndistinct++;
    2607      8015846 :                 if (dups_cnt > 1)
    2608              :                 {
    2609       688664 :                     nmultiple++;
    2610       688664 :                     if (track_cnt < num_mcv ||
    2611       283500 :                         dups_cnt > track[track_cnt - 1].count)
    2612              :                     {
    2613              :                         /*
    2614              :                          * Found a new item for the mcv list; find its
    2615              :                          * position, bubbling down old items if needed. Loop
    2616              :                          * invariant is that j points at an empty/ replaceable
    2617              :                          * slot.
    2618              :                          */
    2619              :                         int         j;
    2620              : 
    2621       466961 :                         if (track_cnt < num_mcv)
    2622       405164 :                             track_cnt++;
    2623      6162745 :                         for (j = track_cnt - 1; j > 0; j--)
    2624              :                         {
    2625      6112249 :                             if (dups_cnt <= track[j - 1].count)
    2626       416465 :                                 break;
    2627      5695784 :                             track[j].count = track[j - 1].count;
    2628      5695784 :                             track[j].first = track[j - 1].first;
    2629              :                         }
    2630       466961 :                         track[j].count = dups_cnt;
    2631       466961 :                         track[j].first = i + 1 - dups_cnt;
    2632              :                     }
    2633              :                 }
    2634      8015846 :                 dups_cnt = 0;
    2635              :             }
    2636              :         }
    2637              : 
    2638        46274 :         stats->stats_valid = true;
    2639              :         /* Do the simple null-frac and width stats */
    2640        46274 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2641        46274 :         if (is_varwidth)
    2642         6842 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2643              :         else
    2644        39432 :             stats->stawidth = stats->attrtype->typlen;
    2645              : 
    2646        46274 :         if (nmultiple == 0)
    2647              :         {
    2648              :             /*
    2649              :              * If we found no repeated non-null values, assume it's a unique
    2650              :              * column; but be sure to discount for any nulls we found.
    2651              :              */
    2652        12691 :             stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
    2653              :         }
    2654        33583 :         else if (toowide_cnt == 0 && nmultiple == ndistinct)
    2655              :         {
    2656              :             /*
    2657              :              * Every value in the sample appeared more than once.  Assume the
    2658              :              * column has just these values.  (This case is meant to address
    2659              :              * columns with small, fixed sets of possible values, such as
    2660              :              * boolean or enum columns.  If there are any values that appear
    2661              :              * just once in the sample, including too-wide values, we should
    2662              :              * assume that that's not what we're dealing with.)
    2663              :              */
    2664        20787 :             stats->stadistinct = ndistinct;
    2665              :         }
    2666              :         else
    2667              :         {
    2668              :             /*----------
    2669              :              * Estimate the number of distinct values using the estimator
    2670              :              * proposed by Haas and Stokes in IBM Research Report RJ 10025:
    2671              :              *      n*d / (n - f1 + f1*n/N)
    2672              :              * where f1 is the number of distinct values that occurred
    2673              :              * exactly once in our sample of n rows (from a total of N),
    2674              :              * and d is the total number of distinct values in the sample.
    2675              :              * This is their Duj1 estimator; the other estimators they
    2676              :              * recommend are considerably more complex, and are numerically
    2677              :              * very unstable when n is much smaller than N.
    2678              :              *
    2679              :              * In this calculation, we consider only non-nulls.  We used to
    2680              :              * include rows with null values in the n and N counts, but that
    2681              :              * leads to inaccurate answers in columns with many nulls, and
    2682              :              * it's intuitively bogus anyway considering the desired result is
    2683              :              * the number of distinct non-null values.
    2684              :              *
    2685              :              * Overwidth values are assumed to have been distinct.
    2686              :              *----------
    2687              :              */
    2688        12796 :             int         f1 = ndistinct - nmultiple + toowide_cnt;
    2689        12796 :             int         d = f1 + nmultiple;
    2690        12796 :             double      n = samplerows - null_cnt;
    2691        12796 :             double      N = totalrows * (1.0 - stats->stanullfrac);
    2692              :             double      stadistinct;
    2693              : 
    2694              :             /* N == 0 shouldn't happen, but just in case ... */
    2695        12796 :             if (N > 0)
    2696        12796 :                 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
    2697              :             else
    2698            0 :                 stadistinct = 0;
    2699              : 
    2700              :             /* Clamp to sane range in case of roundoff error */
    2701        12796 :             if (stadistinct < d)
    2702          549 :                 stadistinct = d;
    2703        12796 :             if (stadistinct > N)
    2704            0 :                 stadistinct = N;
    2705              :             /* And round to integer */
    2706        12796 :             stats->stadistinct = floor(stadistinct + 0.5);
    2707              :         }
    2708              : 
    2709              :         /*
    2710              :          * If we estimated the number of distinct values at more than 10% of
    2711              :          * the total row count (a very arbitrary limit), then assume that
    2712              :          * stadistinct should scale with the row count rather than be a fixed
    2713              :          * value.
    2714              :          */
    2715        46274 :         if (stats->stadistinct > 0.1 * totalrows)
    2716         9569 :             stats->stadistinct = -(stats->stadistinct / totalrows);
    2717              : 
    2718              :         /*
    2719              :          * Decide how many values are worth storing as most-common values. If
    2720              :          * we are able to generate a complete MCV list (all the values in the
    2721              :          * sample will fit, and we think these are all the ones in the table),
    2722              :          * then do so.  Otherwise, store only those values that are
    2723              :          * significantly more common than the values not in the list.
    2724              :          *
    2725              :          * Note: the first of these cases is meant to address columns with
    2726              :          * small, fixed sets of possible values, such as boolean or enum
    2727              :          * columns.  If we can *completely* represent the column population by
    2728              :          * an MCV list that will fit into the stats target, then we should do
    2729              :          * so and thus provide the planner with complete information.  But if
    2730              :          * the MCV list is not complete, it's generally worth being more
    2731              :          * selective, and not just filling it all the way up to the stats
    2732              :          * target.
    2733              :          */
    2734        46274 :         if (track_cnt == ndistinct && toowide_cnt == 0 &&
    2735        20406 :             stats->stadistinct > 0 &&
    2736              :             track_cnt <= num_mcv)
    2737              :         {
    2738              :             /* Track list includes all values seen, and all will fit */
    2739        18257 :             num_mcv = track_cnt;
    2740              :         }
    2741              :         else
    2742              :         {
    2743              :             int        *mcv_counts;
    2744              : 
    2745              :             /* Incomplete list; decide how many values are worth keeping */
    2746        28017 :             if (num_mcv > track_cnt)
    2747        25836 :                 num_mcv = track_cnt;
    2748              : 
    2749        28017 :             if (num_mcv > 0)
    2750              :             {
    2751        15326 :                 mcv_counts = (int *) palloc(num_mcv * sizeof(int));
    2752       318764 :                 for (i = 0; i < num_mcv; i++)
    2753       303438 :                     mcv_counts[i] = track[i].count;
    2754              : 
    2755        15326 :                 num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
    2756        15326 :                                            stats->stadistinct,
    2757        15326 :                                            stats->stanullfrac,
    2758              :                                            samplerows, totalrows);
    2759              :             }
    2760              :         }
    2761              : 
    2762              :         /* Generate MCV slot entry */
    2763        46274 :         if (num_mcv > 0)
    2764              :         {
    2765              :             MemoryContext old_context;
    2766              :             Datum      *mcv_values;
    2767              :             float4     *mcv_freqs;
    2768              : 
    2769              :             /* Must copy the target values into anl_context */
    2770        33561 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2771        33561 :             mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
    2772        33561 :             mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
    2773       438612 :             for (i = 0; i < num_mcv; i++)
    2774              :             {
    2775       810102 :                 mcv_values[i] = datumCopy(values[track[i].first].value,
    2776       405051 :                                           stats->attrtype->typbyval,
    2777       405051 :                                           stats->attrtype->typlen);
    2778       405051 :                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
    2779              :             }
    2780        33561 :             MemoryContextSwitchTo(old_context);
    2781              : 
    2782        33561 :             stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
    2783        33561 :             stats->staop[slot_idx] = mystats->eqopr;
    2784        33561 :             stats->stacoll[slot_idx] = stats->attrcollid;
    2785        33561 :             stats->stanumbers[slot_idx] = mcv_freqs;
    2786        33561 :             stats->numnumbers[slot_idx] = num_mcv;
    2787        33561 :             stats->stavalues[slot_idx] = mcv_values;
    2788        33561 :             stats->numvalues[slot_idx] = num_mcv;
    2789              : 
    2790              :             /*
    2791              :              * Accept the defaults for stats->statypid and others. They have
    2792              :              * been set before we were called (see vacuum.h)
    2793              :              */
    2794        33561 :             slot_idx++;
    2795              :         }
    2796              : 
    2797              :         /*
    2798              :          * Generate a histogram slot entry if there are at least two distinct
    2799              :          * values not accounted for in the MCV list.  (This ensures the
    2800              :          * histogram won't collapse to empty or a singleton.)
    2801              :          */
    2802        46274 :         num_hist = ndistinct - num_mcv;
    2803        46274 :         if (num_hist > num_bins)
    2804         7266 :             num_hist = num_bins + 1;
    2805        46274 :         if (num_hist >= 2)
    2806              :         {
    2807              :             MemoryContext old_context;
    2808              :             Datum      *hist_values;
    2809              :             int         nvals;
    2810              :             int         pos,
    2811              :                         posfrac,
    2812              :                         delta,
    2813              :                         deltafrac;
    2814              : 
    2815              :             /* Sort the MCV items into position order to speed next loop */
    2816        20746 :             qsort_interruptible(track, num_mcv, sizeof(ScalarMCVItem),
    2817              :                                 compare_mcvs, NULL);
    2818              : 
    2819              :             /*
    2820              :              * Collapse out the MCV items from the values[] array.
    2821              :              *
    2822              :              * Note we destroy the values[] array here... but we don't need it
    2823              :              * for anything more.  We do, however, still need values_cnt.
    2824              :              * nvals will be the number of remaining entries in values[].
    2825              :              */
    2826        20746 :             if (num_mcv > 0)
    2827              :             {
    2828              :                 int         src,
    2829              :                             dest;
    2830              :                 int         j;
    2831              : 
    2832        10707 :                 src = dest = 0;
    2833        10707 :                 j = 0;          /* index of next interesting MCV item */
    2834       391525 :                 while (src < values_cnt)
    2835              :                 {
    2836              :                     int         ncopy;
    2837              : 
    2838       380818 :                     if (j < num_mcv)
    2839              :                     {
    2840       372859 :                         int         first = track[j].first;
    2841              : 
    2842       372859 :                         if (src >= first)
    2843              :                         {
    2844              :                             /* advance past this MCV item */
    2845       271290 :                             src = first + track[j].count;
    2846       271290 :                             j++;
    2847       271290 :                             continue;
    2848              :                         }
    2849       101569 :                         ncopy = first - src;
    2850              :                     }
    2851              :                     else
    2852         7959 :                         ncopy = values_cnt - src;
    2853       109528 :                     memmove(&values[dest], &values[src],
    2854              :                             ncopy * sizeof(ScalarItem));
    2855       109528 :                     src += ncopy;
    2856       109528 :                     dest += ncopy;
    2857              :                 }
    2858        10707 :                 nvals = dest;
    2859              :             }
    2860              :             else
    2861        10039 :                 nvals = values_cnt;
    2862              :             Assert(nvals >= num_hist);
    2863              : 
    2864              :             /* Must copy the target values into anl_context */
    2865        20746 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2866        20746 :             hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
    2867              : 
    2868              :             /*
    2869              :              * The object of this loop is to copy the first and last values[]
    2870              :              * entries along with evenly-spaced values in between.  So the
    2871              :              * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)].  But
    2872              :              * computing that subscript directly risks integer overflow when
    2873              :              * the stats target is more than a couple thousand.  Instead we
    2874              :              * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
    2875              :              * the integral and fractional parts of the sum separately.
    2876              :              */
    2877        20746 :             delta = (nvals - 1) / (num_hist - 1);
    2878        20746 :             deltafrac = (nvals - 1) % (num_hist - 1);
    2879        20746 :             pos = posfrac = 0;
    2880              : 
    2881      1092515 :             for (i = 0; i < num_hist; i++)
    2882              :             {
    2883      2143538 :                 hist_values[i] = datumCopy(values[pos].value,
    2884      1071769 :                                            stats->attrtype->typbyval,
    2885      1071769 :                                            stats->attrtype->typlen);
    2886      1071769 :                 pos += delta;
    2887      1071769 :                 posfrac += deltafrac;
    2888      1071769 :                 if (posfrac >= (num_hist - 1))
    2889              :                 {
    2890              :                     /* fractional part exceeds 1, carry to integer part */
    2891       353522 :                     pos++;
    2892       353522 :                     posfrac -= (num_hist - 1);
    2893              :                 }
    2894              :             }
    2895              : 
    2896        20746 :             MemoryContextSwitchTo(old_context);
    2897              : 
    2898        20746 :             stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
    2899        20746 :             stats->staop[slot_idx] = mystats->ltopr;
    2900        20746 :             stats->stacoll[slot_idx] = stats->attrcollid;
    2901        20746 :             stats->stavalues[slot_idx] = hist_values;
    2902        20746 :             stats->numvalues[slot_idx] = num_hist;
    2903              : 
    2904              :             /*
    2905              :              * Accept the defaults for stats->statypid and others. They have
    2906              :              * been set before we were called (see vacuum.h)
    2907              :              */
    2908        20746 :             slot_idx++;
    2909              :         }
    2910              : 
    2911              :         /* Generate a correlation entry if there are multiple values */
    2912        46274 :         if (values_cnt > 1)
    2913              :         {
    2914              :             MemoryContext old_context;
    2915              :             float4     *corrs;
    2916              :             double      corr_xsum,
    2917              :                         corr_x2sum;
    2918              : 
    2919              :             /* Must copy the target values into anl_context */
    2920        43600 :             old_context = MemoryContextSwitchTo(stats->anl_context);
    2921        43600 :             corrs = palloc_object(float4);
    2922        43600 :             MemoryContextSwitchTo(old_context);
    2923              : 
    2924              :             /*----------
    2925              :              * Since we know the x and y value sets are both
    2926              :              *      0, 1, ..., values_cnt-1
    2927              :              * we have sum(x) = sum(y) =
    2928              :              *      (values_cnt-1)*values_cnt / 2
    2929              :              * and sum(x^2) = sum(y^2) =
    2930              :              *      (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
    2931              :              *----------
    2932              :              */
    2933        43600 :             corr_xsum = ((double) (values_cnt - 1)) *
    2934        43600 :                 ((double) values_cnt) / 2.0;
    2935        43600 :             corr_x2sum = ((double) (values_cnt - 1)) *
    2936        43600 :                 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
    2937              : 
    2938              :             /* And the correlation coefficient reduces to */
    2939        43600 :             corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
    2940        43600 :                 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
    2941              : 
    2942        43600 :             stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
    2943        43600 :             stats->staop[slot_idx] = mystats->ltopr;
    2944        43600 :             stats->stacoll[slot_idx] = stats->attrcollid;
    2945        43600 :             stats->stanumbers[slot_idx] = corrs;
    2946        43600 :             stats->numnumbers[slot_idx] = 1;
    2947        43600 :             slot_idx++;
    2948              :         }
    2949              :     }
    2950         3226 :     else if (nonnull_cnt > 0)
    2951              :     {
    2952              :         /* We found some non-null values, but they were all too wide */
    2953              :         Assert(nonnull_cnt == toowide_cnt);
    2954          206 :         stats->stats_valid = true;
    2955              :         /* Do the simple null-frac and width stats */
    2956          206 :         stats->stanullfrac = (double) null_cnt / (double) samplerows;
    2957          206 :         if (is_varwidth)
    2958          206 :             stats->stawidth = total_width / (double) nonnull_cnt;
    2959              :         else
    2960            0 :             stats->stawidth = stats->attrtype->typlen;
    2961              :         /* Assume all too-wide values are distinct, so it's a unique column */
    2962          206 :         stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
    2963              :     }
    2964         3020 :     else if (null_cnt > 0)
    2965              :     {
    2966              :         /* We found only nulls; assume the column is entirely null */
    2967         3020 :         stats->stats_valid = true;
    2968         3020 :         stats->stanullfrac = 1.0;
    2969         3020 :         if (is_varwidth)
    2970         2614 :             stats->stawidth = 0; /* "unknown" */
    2971              :         else
    2972          406 :             stats->stawidth = stats->attrtype->typlen;
    2973         3020 :         stats->stadistinct = 0.0;    /* "unknown" */
    2974              :     }
    2975              : 
    2976              :     /* We don't need to bother cleaning up any of our temporary palloc's */
    2977        49500 : }
    2978              : 
    2979              : /*
    2980              :  * Comparator for sorting ScalarItems
    2981              :  *
    2982              :  * Aside from sorting the items, we update the tupnoLink[] array
    2983              :  * whenever two ScalarItems are found to contain equal datums.  The array
    2984              :  * is indexed by tupno; for each ScalarItem, it contains the highest
    2985              :  * tupno that that item's datum has been found to be equal to.  This allows
    2986              :  * us to avoid additional comparisons in compute_scalar_stats().
    2987              :  */
    2988              : static int
    2989    369477202 : compare_scalars(const void *a, const void *b, void *arg)
    2990              : {
    2991    369477202 :     Datum       da = ((const ScalarItem *) a)->value;
    2992    369477202 :     int         ta = ((const ScalarItem *) a)->tupno;
    2993    369477202 :     Datum       db = ((const ScalarItem *) b)->value;
    2994    369477202 :     int         tb = ((const ScalarItem *) b)->tupno;
    2995    369477202 :     CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
    2996              :     int         compare;
    2997              : 
    2998    369477202 :     compare = ApplySortComparator(da, false, db, false, cxt->ssup);
    2999    369477202 :     if (compare != 0)
    3000    135926693 :         return compare;
    3001              : 
    3002              :     /*
    3003              :      * The two datums are equal, so update cxt->tupnoLink[].
    3004              :      */
    3005    233550509 :     if (cxt->tupnoLink[ta] < tb)
    3006     32970854 :         cxt->tupnoLink[ta] = tb;
    3007    233550509 :     if (cxt->tupnoLink[tb] < ta)
    3008      2302436 :         cxt->tupnoLink[tb] = ta;
    3009              : 
    3010              :     /*
    3011              :      * For equal datums, sort by tupno
    3012              :      */
    3013    233550509 :     return ta - tb;
    3014              : }
    3015              : 
    3016              : /*
    3017              :  * Comparator for sorting ScalarMCVItems by position
    3018              :  */
    3019              : static int
    3020      1424386 : compare_mcvs(const void *a, const void *b, void *arg)
    3021              : {
    3022      1424386 :     int         da = ((const ScalarMCVItem *) a)->first;
    3023      1424386 :     int         db = ((const ScalarMCVItem *) b)->first;
    3024              : 
    3025      1424386 :     return da - db;
    3026              : }
    3027              : 
    3028              : /*
    3029              :  * Analyze the list of common values in the sample and decide how many are
    3030              :  * worth storing in the table's MCV list.
    3031              :  *
    3032              :  * mcv_counts is assumed to be a list of the counts of the most common values
    3033              :  * seen in the sample, starting with the most common.  The return value is the
    3034              :  * number that are significantly more common than the values not in the list,
    3035              :  * and which are therefore deemed worth storing in the table's MCV list.
    3036              :  */
    3037              : static int
    3038        15665 : analyze_mcv_list(int *mcv_counts,
    3039              :                  int num_mcv,
    3040              :                  double stadistinct,
    3041              :                  double stanullfrac,
    3042              :                  int samplerows,
    3043              :                  double totalrows)
    3044              : {
    3045              :     double      ndistinct_table;
    3046              :     double      sumcount;
    3047              :     int         i;
    3048              : 
    3049              :     /*
    3050              :      * If the entire table was sampled, keep the whole list.  This also
    3051              :      * protects us against division by zero in the code below.
    3052              :      */
    3053        15665 :     if (samplerows == totalrows || totalrows <= 1.0)
    3054        15248 :         return num_mcv;
    3055              : 
    3056              :     /* Re-extract the estimated number of distinct nonnull values in table */
    3057          417 :     ndistinct_table = stadistinct;
    3058          417 :     if (ndistinct_table < 0)
    3059           74 :         ndistinct_table = -ndistinct_table * totalrows;
    3060              : 
    3061              :     /*
    3062              :      * Exclude the least common values from the MCV list, if they are not
    3063              :      * significantly more common than the estimated selectivity they would
    3064              :      * have if they weren't in the list.  All non-MCV values are assumed to be
    3065              :      * equally common, after taking into account the frequencies of all the
    3066              :      * values in the MCV list and the number of nulls (c.f. eqsel()).
    3067              :      *
    3068              :      * Here sumcount tracks the total count of all but the last (least common)
    3069              :      * value in the MCV list, allowing us to determine the effect of excluding
    3070              :      * that value from the list.
    3071              :      *
    3072              :      * Note that we deliberately do this by removing values from the full
    3073              :      * list, rather than starting with an empty list and adding values,
    3074              :      * because the latter approach can fail to add any values if all the most
    3075              :      * common values have around the same frequency and make up the majority
    3076              :      * of the table, so that the overall average frequency of all values is
    3077              :      * roughly the same as that of the common values.  This would lead to any
    3078              :      * uncommon values being significantly overestimated.
    3079              :      */
    3080          417 :     sumcount = 0.0;
    3081          874 :     for (i = 0; i < num_mcv - 1; i++)
    3082          457 :         sumcount += mcv_counts[i];
    3083              : 
    3084          508 :     while (num_mcv > 0)
    3085              :     {
    3086              :         double      selec,
    3087              :                     otherdistinct,
    3088              :                     N,
    3089              :                     n,
    3090              :                     K,
    3091              :                     variance,
    3092              :                     stddev;
    3093              : 
    3094              :         /*
    3095              :          * Estimated selectivity the least common value would have if it
    3096              :          * wasn't in the MCV list (c.f. eqsel()).
    3097              :          */
    3098          508 :         selec = 1.0 - sumcount / samplerows - stanullfrac;
    3099          508 :         if (selec < 0.0)
    3100            0 :             selec = 0.0;
    3101          508 :         if (selec > 1.0)
    3102            0 :             selec = 1.0;
    3103          508 :         otherdistinct = ndistinct_table - (num_mcv - 1);
    3104          508 :         if (otherdistinct > 1)
    3105          508 :             selec /= otherdistinct;
    3106              : 
    3107              :         /*
    3108              :          * If the value is kept in the MCV list, its population frequency is
    3109              :          * assumed to equal its sample frequency.  We use the lower end of a
    3110              :          * textbook continuity-corrected Wald-type confidence interval to
    3111              :          * determine if that is significantly more common than the non-MCV
    3112              :          * frequency --- specifically we assume the population frequency is
    3113              :          * highly likely to be within around 2 standard errors of the sample
    3114              :          * frequency, which equates to an interval of 2 standard deviations
    3115              :          * either side of the sample count, plus an additional 0.5 for the
    3116              :          * continuity correction.  Since we are sampling without replacement,
    3117              :          * this is a hypergeometric distribution.
    3118              :          *
    3119              :          * XXX: Empirically, this approach seems to work quite well, but it
    3120              :          * may be worth considering more advanced techniques for estimating
    3121              :          * the confidence interval of the hypergeometric distribution.
    3122              :          */
    3123          508 :         N = totalrows;
    3124          508 :         n = samplerows;
    3125          508 :         K = N * mcv_counts[num_mcv - 1] / n;
    3126          508 :         variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
    3127          508 :         stddev = sqrt(variance);
    3128              : 
    3129          508 :         if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
    3130              :         {
    3131              :             /*
    3132              :              * The value is significantly more common than the non-MCV
    3133              :              * selectivity would suggest.  Keep it, and all the other more
    3134              :              * common values in the list.
    3135              :              */
    3136          392 :             break;
    3137              :         }
    3138              :         else
    3139              :         {
    3140              :             /* Discard this value and consider the next least common value */
    3141          116 :             num_mcv--;
    3142          116 :             if (num_mcv == 0)
    3143           25 :                 break;
    3144           91 :             sumcount -= mcv_counts[num_mcv - 1];
    3145              :         }
    3146              :     }
    3147          417 :     return num_mcv;
    3148              : }
        

Generated by: LCOV version 2.0-1